/**
 * Grammar Types for Semantic Multilingual Parsing
 *
 * These types define the semantic role system used across all 13 supported languages.
 * Originally from @lokascript/i18n, now consolidated here for package independence.
 *
 * Key Linguistic Concepts:
 * - Word Order: SVO, SOV, VSO (and variations)
 * - Adposition Type: Preposition (English) vs Postposition (Japanese/Korean)
 * - Morphology: Isolating (Chinese) vs Agglutinative (Turkish) vs Fusional (Arabic)
 * - Text Direction: LTR vs RTL
 */
/**
 * Semantic roles in hyperscript commands.
 * These are universal across all 13 supported languages - only the surface form changes.
 *
 * ## Core Thematic Roles (from linguistic theory)
 * | Role        | Usage | Purpose                     | Example                   |
 * |-------------|-------|-----------------------------|---------------------------|
 * | action      | 100%  | Command verb                | toggle, put, fetch        |
 * | patient     | 90%   | What is acted upon          | .active, #count           |
 * | destination | 40%   | Where something goes        | into #output, to .class   |
 * | source      | 13%   | Where something comes from  | from #input, from URL     |
 * | event       | 106%  | Trigger events              | click, keydown, submit    |
 * | condition   | 8%    | Boolean expressions         | if x > 5, when visible    |
 * | agent       | 0%    | Who performs action         | Reserved for future use   |
 * | goal        | 1%    | Target value/state          | to 'red' (in transition)  |
 *
 * ## Quantitative Roles (answer "how much/long")
 * | Role     | Usage | Purpose        | Example              |
 * |----------|-------|----------------|----------------------|
 * | quantity | 7%    | Numeric amount | by 5, 3 times        |
 * | duration | 1%    | Time span      | for 5 seconds, 500ms |
 *
 * ## Adverbial/Modifier Roles (answer "how/by what means")
 * | Role         | Usage | Purpose                   | Example           |
 * |--------------|-------|---------------------------|-------------------|
 * | style        | 2%    | Animation/behavior        | with fade         |
 * | manner       | 2%    | Insertion position        | before, after     |
 * | method       | 1%    | HTTP method/technique     | via POST, as GET  |
 * | responseType | 1%    | Response format           | as json, as html  |
 *
 * ## Control Flow Roles
 * | Role     | Usage | Purpose      | Example               |
 * |----------|-------|--------------|-----------------------|
 * | loopType | 6%    | Loop variant | forever, until, times |
 *
 * ## Design Notes
 * - Low-usage roles (agent, goal, method, responseType) are intentionally kept for:
 *   - Linguistic completeness across all 13 languages
 *   - Future extensibility (AI agents, server-side execution)
 *   - Command-specific semantics (fetch, transition)
 * - Each role has distinct grammatical markers per language (see profiles/index.ts)
 * - Usage percentages based on pattern database analysis
 */
type SemanticRole = 'action' | 'agent' | 'patient' | 'source' | 'destination' | 'goal' | 'event' | 'condition' | 'quantity' | 'duration' | 'responseType' | 'method' | 'style' | 'manner' | 'loopType' | 'continues';

/**
 * Semantic-First Multilingual Hyperscript Types
 *
 * This module defines the canonical semantic representation that all languages
 * parse to and render from. The semantic layer is language-neutral - it captures
 * the MEANING of hyperscript commands independent of surface syntax.
 */

/**
 * Canonical action names (English-based internally, but not visible to users)
 * These map to hyperscript commands and are used in the semantic AST.
 */
type ActionType = 'toggle' | 'add' | 'remove' | 'put' | 'append' | 'prepend' | 'take' | 'make' | 'clone' | 'swap' | 'morph' | 'set' | 'get' | 'increment' | 'decrement' | 'log' | 'show' | 'hide' | 'transition' | 'on' | 'trigger' | 'send' | 'focus' | 'blur' | 'go' | 'wait' | 'fetch' | 'settle' | 'measure' | 'install' | 'if' | 'unless' | 'else' | 'repeat' | 'for' | 'while' | 'continue' | 'halt' | 'throw' | 'call' | 'return' | 'js' | 'async' | 'tell' | 'default' | 'init' | 'behavior' | 'compound';
/**
 * A semantic value represents a typed piece of data in a semantic node.
 * Values are language-neutral - they capture what something IS, not how it's written.
 */
type SemanticValue = LiteralValue | SelectorValue | ReferenceValue | PropertyPathValue | ExpressionValue;
interface LiteralValue {
    readonly type: 'literal';
    readonly value: string | number | boolean;
    readonly dataType?: 'string' | 'number' | 'boolean' | 'duration';
}
interface SelectorValue {
    readonly type: 'selector';
    readonly value: string;
    readonly selectorKind: 'id' | 'class' | 'attribute' | 'element' | 'complex';
}
interface ReferenceValue {
    readonly type: 'reference';
    readonly value: 'me' | 'you' | 'it' | 'result' | 'event' | 'target' | 'body';
}
interface PropertyPathValue {
    readonly type: 'property-path';
    readonly object: SemanticValue;
    readonly property: string;
}
interface ExpressionValue {
    readonly type: 'expression';
    /** Raw expression string for complex expressions that need further parsing */
    readonly raw: string;
}
/**
 * Base interface for all semantic nodes.
 * Semantic nodes capture the MEANING of hyperscript constructs.
 */
interface SemanticNode {
    readonly kind: 'command' | 'event-handler' | 'conditional' | 'compound' | 'loop';
    readonly action: ActionType;
    readonly roles: ReadonlyMap<SemanticRole, SemanticValue>;
    readonly metadata?: SemanticMetadata;
}
/**
 * Metadata about the source of a semantic node.
 * Useful for debugging, error messages, and round-trip conversion.
 */
interface SemanticMetadata {
    readonly sourceLanguage?: string;
    readonly sourceText?: string;
    readonly sourcePosition?: SourcePosition;
    readonly patternId?: string;
    /**
     * Confidence score for the parse (0-1).
     * Higher values indicate more certain matches.
     * - 1.0: Exact match with all roles captured
     * - 0.8-0.99: High confidence with minor uncertainty (stem matching, optional roles)
     * - 0.6-0.8: Medium confidence (morphological normalization, defaults applied)
     * - <0.6: Low confidence (may need fallback to traditional parser)
     */
    readonly confidence?: number;
}
interface SourcePosition {
    readonly start: number;
    readonly end: number;
    readonly line?: number;
    readonly column?: number;
}
/**
 * A command semantic node - represents a single hyperscript command.
 */
interface CommandSemanticNode extends SemanticNode {
    readonly kind: 'command';
}
/**
 * An event handler semantic node - represents "on [event] [commands]".
 */
interface EventHandlerSemanticNode extends SemanticNode {
    readonly kind: 'event-handler';
    readonly action: 'on';
    readonly body: SemanticNode[];
    readonly eventModifiers?: EventModifiers;
    /**
     * Event parameter names for destructuring.
     * E.g., for "on click(clientX, clientY)", this would be ['clientX', 'clientY']
     */
    readonly parameterNames?: readonly string[];
}
interface EventModifiers {
    readonly once?: boolean;
    readonly debounce?: number;
    readonly throttle?: number;
    readonly queue?: 'first' | 'last' | 'all' | 'none';
    readonly from?: SemanticValue;
}
/**
 * A conditional semantic node - represents "if [condition] then [body] else [body]".
 */
interface ConditionalSemanticNode extends SemanticNode {
    readonly kind: 'conditional';
    readonly action: 'if';
    readonly thenBranch: SemanticNode[];
    readonly elseBranch?: SemanticNode[];
}
/**
 * A compound semantic node - represents multiple chained statements.
 */
interface CompoundSemanticNode extends SemanticNode {
    readonly kind: 'compound';
    readonly statements: SemanticNode[];
    readonly chainType: 'then' | 'and' | 'async';
}
/**
 * Loop variant discriminant for different loop types.
 */
type LoopVariant = 'forever' | 'times' | 'for' | 'while' | 'until';
/**
 * A loop semantic node - represents repeat/for/while loops.
 */
interface LoopSemanticNode extends SemanticNode {
    readonly kind: 'loop';
    readonly action: 'repeat' | 'for' | 'while';
    /** The type of loop (forever, times, for, while, until) */
    readonly loopVariant: LoopVariant;
    /** Commands to execute in each iteration */
    readonly body: SemanticNode[];
    /** Loop variable name for 'for' loops (e.g., 'item' in 'for item in list') */
    readonly loopVariable?: string;
    /** Index variable name if specified (e.g., 'i' in 'for item with index i') */
    readonly indexVariable?: string;
}
/**
 * A pattern defines how a semantic structure appears in a specific language.
 * Patterns enable bidirectional conversion: parse (natural → semantic) and
 * render (semantic → natural).
 */
interface LanguagePattern {
    /** Unique identifier for this pattern */
    readonly id: string;
    /** ISO 639-1 language code */
    readonly language: string;
    /** Which command this pattern matches */
    readonly command: ActionType;
    /** Priority for disambiguation (higher = checked first) */
    readonly priority: number;
    /** The pattern template with role placeholders */
    readonly template: PatternTemplate;
    /** Rules for extracting semantic roles from matched tokens */
    readonly extraction: ExtractionRules;
    /** Optional constraints on when this pattern applies */
    readonly constraints?: PatternConstraints;
}
/**
 * A pattern template defines the expected token sequence.
 *
 * Template syntax:
 * - Literal tokens: "toggle", "を", "على"
 * - Role placeholders: {patient}, {target}, {destination}
 * - Optional groups: [on {target}]
 * - Alternatives in extraction (not in template string)
 *
 * Example templates:
 * - English: "toggle {patient} [on {target}]"
 * - Japanese: "{target} の {patient} を 切り替え"
 * - Arabic: "بدّل {patient} [على {target}]"
 */
interface PatternTemplate {
    /** Human-readable template string */
    readonly format: string;
    /** Parsed token sequence for matching */
    readonly tokens: PatternToken[];
}
type PatternToken = LiteralPatternToken | RolePatternToken | GroupPatternToken;
interface LiteralPatternToken {
    readonly type: 'literal';
    readonly value: string;
    /** Alternative spellings/forms that also match */
    readonly alternatives?: string[];
}
interface RolePatternToken {
    readonly type: 'role';
    readonly role: SemanticRole;
    readonly optional?: boolean;
    /** Expected value types (for validation) */
    readonly expectedTypes?: Array<SemanticValue['type']>;
}
interface GroupPatternToken {
    readonly type: 'group';
    readonly tokens: PatternToken[];
    readonly optional?: boolean;
}
/**
 * Rules for extracting semantic values from matched tokens.
 */
interface ExtractionRules {
    readonly [role: string]: ExtractionRule;
}
interface ExtractionRule {
    /** Position-based extraction (0-indexed from pattern start) */
    readonly position?: number;
    /** Marker-based extraction (find value after this marker) */
    readonly marker?: string;
    /** Alternative markers that also work */
    readonly markerAlternatives?: string[];
    /** Transform the extracted value */
    readonly transform?: (raw: string) => SemanticValue;
    /** Default value if not found (for optional roles) */
    readonly default?: SemanticValue;
    /** Static value extraction (for event handler wrapped commands) */
    readonly value?: string;
    /** Extract value from a pattern role by name */
    readonly fromRole?: string;
}
/**
 * Additional constraints on pattern applicability.
 */
interface PatternConstraints {
    /** Required roles that must be present */
    readonly requiredRoles?: SemanticRole[];
    /** Roles that must NOT be present */
    readonly forbiddenRoles?: SemanticRole[];
    /** Valid selector types for the patient role */
    readonly validPatientTypes?: Array<SelectorValue['selectorKind']>;
    /** Pattern IDs this conflicts with */
    readonly conflictsWith?: string[];
}
/**
 * A token from language-specific tokenization.
 */
interface LanguageToken {
    readonly value: string;
    readonly kind: TokenKind;
    readonly position: SourcePosition;
    /** Normalized form from explicit keyword map (e.g., 切り替え → toggle) */
    readonly normalized?: string;
    /** Morphologically normalized stem (e.g., 切り替えた → 切り替え) */
    readonly stem?: string;
    /** Confidence in the morphological stem (0.0-1.0) */
    readonly stemConfidence?: number;
    /** Additional metadata for specific token types (e.g., event modifier data) */
    readonly metadata?: Record<string, unknown>;
}
type TokenKind = 'keyword' | 'selector' | 'literal' | 'particle' | 'conjunction' | 'event-modifier' | 'identifier' | 'operator' | 'punctuation' | 'url';
/**
 * A stream of tokens with navigation capabilities.
 */
interface TokenStream {
    readonly tokens: readonly LanguageToken[];
    readonly language: string;
    /** Look at token at current position + offset without consuming */
    peek(offset?: number): LanguageToken | null;
    /** Consume and return current token, advance position */
    advance(): LanguageToken;
    /** Check if we've consumed all tokens */
    isAtEnd(): boolean;
    /** Save current position for backtracking */
    mark(): StreamMark;
    /** Restore to a saved position */
    reset(mark: StreamMark): void;
    /** Get current position */
    position(): number;
}
interface StreamMark {
    readonly position: number;
}
/**
 * Result of successfully matching a pattern.
 */
interface PatternMatchResult {
    readonly pattern: LanguagePattern;
    readonly captured: ReadonlyMap<SemanticRole, SemanticValue>;
    readonly consumedTokens: number;
    readonly confidence: number;
}
/**
 * Language-specific tokenizer interface.
 * Each language implements its own tokenizer to handle:
 * - Word boundaries (spaces for English, particles for Japanese)
 * - Character sets (ASCII, CJK, Arabic, etc.)
 * - Special markers (particles, prefixes, suffixes)
 */
interface LanguageTokenizer {
    readonly language: string;
    readonly direction: 'ltr' | 'rtl';
    /** Convert input string to token stream */
    tokenize(input: string): TokenStream;
    /** Classify a single token */
    classifyToken(token: string): TokenKind;
}
/**
 * Create a selector semantic value from a CSS selector string.
 */
declare function createSelector(value: string): SelectorValue;
/**
 * Create a literal semantic value.
 */
declare function createLiteral(value: string | number | boolean, dataType?: LiteralValue['dataType']): LiteralValue;
/**
 * Create a reference semantic value.
 */
declare function createReference(value: ReferenceValue['value']): ReferenceValue;
/**
 * Create a property path semantic value.
 */
declare function createPropertyPath(object: SemanticValue, property: string): PropertyPathValue;
/**
 * Create a semantic node with the given action and roles.
 */
declare function createCommandNode(action: ActionType, roles: Record<string, SemanticValue>, metadata?: SemanticMetadata): CommandSemanticNode;
/**
 * Create an event handler semantic node.
 */
declare function createEventHandler(event: SemanticValue, body: SemanticNode[], modifiers?: EventModifiers, metadata?: SemanticMetadata, parameterNames?: string[]): EventHandlerSemanticNode;

/**
 * Semantic Result Cache
 *
 * LRU cache for semantic analysis results to optimize repeated parsing.
 *
 * Design:
 * - Cache key: `${language}:${input}` for simple, fast lookups
 * - LRU eviction when max size reached
 * - Optional TTL (time-to-live) for cache entries
 * - Statistics for monitoring cache effectiveness
 * - Thread-safe for browser environments (single-threaded)
 */

/**
 * Cache configuration options.
 */
interface SemanticCacheConfig {
    /** Maximum number of entries to cache. Default: 1000 */
    maxSize?: number;
    /** Time-to-live in milliseconds. 0 = no expiration. Default: 0 */
    ttlMs?: number;
    /** Enable/disable caching. Default: true */
    enabled?: boolean;
}
/**
 * Cache statistics.
 */
interface CacheStats {
    /** Total cache hits */
    hits: number;
    /** Total cache misses */
    misses: number;
    /** Current cache size */
    size: number;
    /** Maximum cache size */
    maxSize: number;
    /** Hit rate (0-1) */
    hitRate: number;
    /** Total evictions due to size limit */
    evictions: number;
    /** Total expirations due to TTL */
    expirations: number;
    /** Whether caching is enabled */
    enabled: boolean;
}
/**
 * LRU Cache for semantic analysis results.
 *
 * Uses Map's insertion order for LRU eviction - when we access an entry,
 * we delete and re-insert it to move it to the end (most recently used).
 */
declare class SemanticCache {
    private cache;
    private config;
    private stats;
    constructor(config?: SemanticCacheConfig);
    /**
     * Generate cache key from input and language.
     */
    private makeKey;
    /**
     * Check if an entry has expired.
     */
    private isExpired;
    /**
     * Evict the least recently used entry.
     */
    private evictLRU;
    /**
     * Get a cached result.
     *
     * @param input - The input string
     * @param language - The language code
     * @returns The cached result, or undefined if not found/expired
     */
    get(input: string, language: string): SemanticAnalysisResult | undefined;
    /**
     * Store a result in the cache.
     *
     * @param input - The input string
     * @param language - The language code
     * @param result - The analysis result to cache
     */
    set(input: string, language: string, result: SemanticAnalysisResult): void;
    /**
     * Check if a result is cached (without updating LRU).
     */
    has(input: string, language: string): boolean;
    /**
     * Remove a specific entry from the cache.
     */
    delete(input: string, language: string): boolean;
    /**
     * Clear all cached entries.
     */
    clear(): void;
    /**
     * Reset statistics.
     */
    resetStats(): void;
    /**
     * Get cache statistics.
     */
    getStats(): CacheStats;
    /**
     * Update cache configuration.
     */
    configure(config: Partial<SemanticCacheConfig>): void;
    /**
     * Enable caching.
     */
    enable(): void;
    /**
     * Disable caching.
     */
    disable(): void;
    /**
     * Get current configuration.
     */
    getConfig(): Readonly<Required<SemanticCacheConfig>>;
}
/**
 * Default global cache instance.
 */
declare const semanticCache: SemanticCache;
/**
 * Create a cache with custom configuration.
 */
declare function createSemanticCache(config?: SemanticCacheConfig): SemanticCache;
/**
 * Decorator/wrapper for adding caching to an analyze function.
 *
 * @param analyzeFn - The analyze function to wrap
 * @param cache - The cache instance to use
 * @returns Wrapped function with caching
 */
declare function withCache<T extends (input: string, language: string) => SemanticAnalysisResult>(analyzeFn: T, cache?: SemanticCache): T;

/**
 * Core Parser Bridge
 *
 * Provides the SemanticAnalyzer interface that integrates semantic parsing
 * into the core hyperscript parser. This bridge enables confidence-driven
 * fallback between semantic and traditional parsing.
 */

/**
 * Result of semantic analysis.
 */
interface SemanticAnalysisResult {
    /** Confidence score (0-1) for this analysis */
    readonly confidence: number;
    /** The parsed command info (if successful) */
    readonly command?: {
        readonly name: ActionType;
        readonly roles: ReadonlyMap<SemanticRole, SemanticValue>;
    };
    /** The full semantic node (if successful) */
    readonly node?: SemanticNode;
    /** Any errors encountered */
    readonly errors?: string[];
    /** Number of tokens consumed */
    readonly tokensConsumed?: number;
}
/**
 * Interface for semantic analysis that can be integrated into the core parser.
 * This allows the core parser to optionally use semantic parsing with
 * confidence-based fallback to traditional parsing.
 */
interface SemanticAnalyzer {
    /**
     * Analyze input in the specified language.
     *
     * @param input The input string to analyze
     * @param language ISO 639-1 language code
     * @returns Analysis result with confidence score
     */
    analyze(input: string, language: string): SemanticAnalysisResult;
    /**
     * Check if semantic parsing is available for a language.
     */
    supportsLanguage(language: string): boolean;
    /**
     * Get the list of supported languages.
     */
    supportedLanguages(): string[];
    /**
     * Get cache statistics.
     */
    getCacheStats(): CacheStats;
    /**
     * Clear the result cache.
     */
    clearCache(): void;
    /**
     * Configure the cache.
     */
    configureCache(config: Partial<SemanticCacheConfig>): void;
}
/**
 * Options for creating a SemanticAnalyzer.
 */
interface SemanticAnalyzerOptions {
    /** Cache configuration. Pass false to disable caching. */
    cache?: SemanticCacheConfig | false;
}
/**
 * Implementation of SemanticAnalyzer that wraps the semantic parser.
 * Includes LRU caching for performance optimization on repeated inputs.
 */
declare class SemanticAnalyzerImpl implements SemanticAnalyzer {
    private readonly patternMatcher;
    private readonly languages;
    private readonly cache;
    constructor(options?: SemanticAnalyzerOptions);
    analyze(input: string, language: string): SemanticAnalysisResult;
    /**
     * Perform analysis without cache lookup.
     */
    private analyzeUncached;
    supportsLanguage(language: string): boolean;
    supportedLanguages(): string[];
    getCacheStats(): CacheStats;
    clearCache(): void;
    configureCache(config: Partial<SemanticCacheConfig>): void;
    private buildSemanticNode;
}
/**
 * Create a SemanticAnalyzer instance.
 *
 * @param options - Configuration options including cache settings
 * @returns A new SemanticAnalyzer
 *
 * @example
 * // Default: uses shared global cache
 * const analyzer = createSemanticAnalyzer();
 *
 * @example
 * // Custom cache size
 * const analyzer = createSemanticAnalyzer({ cache: { maxSize: 500 } });
 *
 * @example
 * // Disable caching
 * const analyzer = createSemanticAnalyzer({ cache: false });
 */
declare function createSemanticAnalyzer(options?: SemanticAnalyzerOptions): SemanticAnalyzer;

/**
 * Default confidence threshold for preferring semantic parsing.
 * If confidence is above this, use semantic result; otherwise fallback.
 */
declare const DEFAULT_CONFIDENCE_THRESHOLD = 0.5;
/**
 * High confidence threshold for very certain matches.
 */
declare const HIGH_CONFIDENCE_THRESHOLD = 0.8;
/**
 * Determine if semantic analysis should be used based on confidence.
 */
declare function shouldUseSemanticResult(result: SemanticAnalysisResult, threshold?: number): boolean;
/**
 * Convert semantic roles to the format expected by core parser commands.
 * This maps semantic roles to the positional/modifier structure used by
 * the core command implementations.
 *
 * Role to preposition mapping:
 * - patient → first positional arg
 * - event → first positional arg
 * - destination → 'into' (put) or 'on' (others)
 * - source → 'from'
 * - quantity → 'by'
 * - duration → 'over' or 'for'
 * - method → 'as'
 * - style → 'with'
 * - condition → 'if'
 */
declare function rolesToCommandArgs(roles: ReadonlyMap<SemanticRole, SemanticValue>, command: ActionType): {
    args: SemanticValue[];
    modifiers: Record<string, SemanticValue>;
};

/**
 * Expression Parser Types
 *
 * Defines AST node types for expressions that can be shared between
 * the semantic package (AST building) and core package (runtime).
 *
 * These types are intentionally minimal and focused on expressions only.
 */
/**
 * Base interface for all expression AST nodes
 */
interface ExpressionNode {
    readonly type: string;
    readonly start?: number | undefined;
    readonly end?: number | undefined;
    readonly line?: number | undefined;
    readonly column?: number | undefined;
}
interface LiteralNode extends ExpressionNode {
    readonly type: 'literal';
    readonly value: string | number | boolean | null | undefined;
    readonly raw?: string | undefined;
    readonly dataType?: 'string' | 'number' | 'boolean' | 'null' | 'undefined' | 'duration' | undefined;
}
type SelectorKind = 'id' | 'class' | 'attribute' | 'element' | 'query' | 'complex';
interface SelectorNode extends ExpressionNode {
    readonly type: 'selector' | 'cssSelector' | 'idRef' | 'classRef';
    readonly value?: string;
    readonly selector?: string;
    readonly selectorType?: SelectorKind;
}
type ContextType = 'me' | 'you' | 'it' | 'its' | 'my' | 'your' | 'result' | 'event' | 'target' | 'body' | 'detail';
interface ContextReferenceNode extends ExpressionNode {
    readonly type: 'contextReference' | 'symbol';
    readonly contextType?: ContextType;
    readonly name?: string;
}
interface PropertyAccessNode extends ExpressionNode {
    readonly type: 'propertyAccess';
    readonly object: ExpressionNode;
    readonly property: string;
}

/**
 * Semantic Value to AST Node Converters
 *
 * Converts SemanticValue types to AST expression nodes.
 * Used by the AST builder to construct expression trees from semantic parsing results.
 */

/**
 * Convert a SemanticValue to an AST ExpressionNode.
 *
 * @param value - The semantic value to convert
 * @param warnings - Optional array to collect warnings about potentially incorrect type choices
 * @returns The corresponding AST expression node
 */
declare function convertValue(value: SemanticValue, warnings?: string[]): ExpressionNode;
/**
 * Convert a LiteralValue to a LiteralNode.
 */
declare function convertLiteral(value: LiteralValue): LiteralNode;
/**
 * Convert a SelectorValue to a SelectorNode.
 *
 * @param value - The selector value to convert
 * @param warnings - Optional array to collect warnings
 */
declare function convertSelector(value: SelectorValue, warnings?: string[]): SelectorNode;
/**
 * Convert a ReferenceValue to a ContextReferenceNode.
 */
declare function convertReference(value: ReferenceValue): ContextReferenceNode;
/**
 * Convert a PropertyPathValue to a PropertyAccessNode.
 * Recursively converts the object part.
 *
 * @param value - The property path value to convert
 * @param warnings - Optional array to collect warnings
 */
declare function convertPropertyPath(value: PropertyPathValue, warnings?: string[]): PropertyAccessNode;
/**
 * Convert an ExpressionValue (raw string) by parsing it with the expression parser.
 * This is the fallback for complex expressions that couldn't be fully parsed
 * at the semantic level.
 */
declare function convertExpression(value: ExpressionValue): ExpressionNode;

/**
 * Command-specific AST Mappers
 *
 * Each command can have a custom mapper that knows how to convert
 * its semantic roles to the appropriate AST structure.
 */

/**
 * Result from command mapping, including the AST and any warnings.
 */
interface CommandMapperResult {
    ast: CommandNode;
    warnings: string[];
}
/**
 * Interface for command-specific AST mappers.
 */
interface CommandMapper {
    /**
     * The action type this mapper handles.
     */
    readonly action: ActionType;
    /**
     * Convert a CommandSemanticNode to a CommandNode.
     *
     * @param node - The semantic command node
     * @param builder - The AST builder (for recursive building if needed)
     * @returns The AST command node with any warnings, or just the AST node for backward compatibility
     */
    toAST(node: CommandSemanticNode, builder: ASTBuilder): CommandMapperResult | CommandNode;
}
/**
 * Get the command mapper for an action type.
 *
 * @param action - The action type
 * @returns The mapper, or undefined if no specific mapper exists
 */
declare function getCommandMapper(action: ActionType): CommandMapper | undefined;
/**
 * Register a custom command mapper.
 *
 * @param mapper - The command mapper to register
 */
declare function registerCommandMapper(mapper: CommandMapper): void;
/**
 * Get all registered command mappers.
 */
declare function getRegisteredMappers(): Map<ActionType, CommandMapper>;

/**
 * Semantic to AST Builder
 *
 * Converts SemanticNodes directly to AST nodes, bypassing the English text
 * generation and re-parsing step.
 *
 * Flow:
 *   Japanese → Semantic Parser → SemanticNode → AST Builder → AST
 *
 * Instead of:
 *   Japanese → Semantic Parser → SemanticNode → English Text → Parser → AST
 */

/**
 * Base AST node interface
 */
interface ASTNode {
    readonly type: string;
    readonly start?: number;
    readonly end?: number;
    readonly line?: number;
    readonly column?: number;
    [key: string]: unknown;
}
/**
 * Command AST node
 */
interface CommandNode extends ASTNode {
    readonly type: 'command';
    readonly name: string;
    readonly args: ExpressionNode[];
    readonly modifiers?: Record<string, ExpressionNode>;
    readonly isBlocking?: boolean;
    readonly implicitTarget?: ExpressionNode;
}
/**
 * Event handler AST node (compatible with @lokascript/core)
 */
interface EventHandlerNode extends ASTNode {
    readonly type: 'eventHandler';
    /** Primary event name */
    readonly event: string;
    /** All event names when using "on event1 or event2" syntax */
    readonly events?: string[];
    /** CSS selector for event delegation ("from" keyword) */
    readonly selector?: string;
    /** Target for "from" clause (as string or expression) */
    readonly target?: string;
    /** Optional event condition ("[condition]" syntax) */
    readonly condition?: ASTNode;
    /** Attribute name for mutation events ("of @attribute" syntax) */
    readonly attributeName?: string;
    /** Target element to watch for changes ("in <target>" syntax) */
    readonly watchTarget?: ExpressionNode;
    /** Event parameter names to destructure (e.g., ['clientX', 'clientY']) */
    readonly args?: string[];
    /** Event parameters (alias for args) */
    readonly params?: string[];
    /** Handler commands */
    readonly commands: ASTNode[];
}
/**
 * Conditional AST node (if/else)
 *
 * Note: For runtime compatibility, buildConditional() now produces a CommandNode
 * with condition and branches as args, matching what IfCommand expects.
 * This interface is retained for reference but not used as output.
 */
interface ConditionalNode extends ASTNode {
    readonly type: 'if';
    readonly condition: ExpressionNode;
    readonly thenBranch: ASTNode[];
    readonly elseBranch?: ASTNode[];
}
/**
 * Command sequence node (runtime-compatible format for chained commands)
 */
interface CommandSequenceNode extends ASTNode {
    readonly type: 'CommandSequence';
    /** Commands in the sequence */
    readonly commands: ASTNode[];
}
/**
 * Block node (for grouping commands)
 */
interface BlockNode extends ASTNode {
    readonly type: 'block';
    readonly commands: ASTNode[];
}
interface ASTBuilderOptions {
    /**
     * Fallback function to parse complex expressions that can't be handled
     * directly by the AST builder. Uses the expression-parser by default.
     */
    parseExpression?: (input: string) => ExpressionNode | null;
}
/**
 * Builds AST nodes directly from SemanticNodes.
 */
declare class ASTBuilder {
    /**
     * Warnings collected during AST building (e.g., type inference issues).
     */
    warnings: string[];
    constructor(_options?: ASTBuilderOptions);
    /**
     * Build an AST from a SemanticNode.
     *
     * @param node - The semantic node to convert
     * @returns The corresponding AST node
     */
    build(node: SemanticNode): ASTNode;
    /**
     * Build a CommandNode from a CommandSemanticNode.
     */
    private buildCommand;
    /**
     * Generic command builder when no specific mapper is available.
     * Maps roles to args in a predictable order.
     */
    private buildGenericCommand;
    /**
     * Map semantic roles to hyperscript modifier keywords.
     */
    private roleToModifierKey;
    /**
     * Build an EventHandlerNode from an EventHandlerSemanticNode.
     */
    private buildEventHandler;
    /**
     * Build a CommandNode from a ConditionalSemanticNode.
     *
     * Produces a command node with:
     * - args[0]: condition expression
     * - args[1]: then block (wrapped in { type: 'block', commands: [...] })
     * - args[2]: else block (optional, same format)
     *
     * This format matches what IfCommand.parseInput() expects.
     */
    private buildConditional;
    /**
     * Build AST nodes from a CompoundSemanticNode.
     *
     * Converts to CommandSequence for runtime compatibility.
     * The runtime recognizes 'CommandSequence' type and executes commands in order.
     */
    private buildCompound;
    /**
     * Build a CommandNode from a LoopSemanticNode.
     *
     * Produces a 'repeat' command with:
     * - args[0]: loop type identifier (forever, times, for, while, until)
     * - args[1]: count/condition/variable depending on loop type
     * - args[2]: collection (for 'for' loops)
     * - args[last]: body block
     *
     * This format matches what the repeat command parser produces.
     */
    private buildLoop;
    /**
     * Build a BlockNode from an array of semantic nodes.
     * Useful for grouping commands in if/else branches.
     */
    buildBlock(nodes: SemanticNode[]): BlockNode;
}
/**
 * Result from building an AST, including any warnings.
 */
interface BuildASTResult {
    ast: ASTNode;
    warnings: string[];
}
/**
 * Build an AST from a SemanticNode using default options.
 *
 * @param node - The semantic node to convert
 * @returns The corresponding AST node and any warnings
 */
declare function buildAST(node: SemanticNode): BuildASTResult;

/**
 * Language Profile Types
 *
 * Type definitions for language profiles, separated for tree-shaking.
 */

/**
 * Word order in a language (for declarative statements).
 */
type WordOrder = 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OSV' | 'OVS';
/**
 * How grammatical relationships are marked.
 */
type MarkingStrategy = 'preposition' | 'postposition' | 'particle' | 'case-suffix';
/**
 * A grammatical marker (preposition, particle, etc.) for a semantic role.
 */
interface RoleMarker {
    /** Primary marker for this role */
    readonly primary: string;
    /** Alternative markers that also work */
    readonly alternatives?: string[];
    /** Position relative to the role value */
    readonly position: 'before' | 'after';
}
/**
 * Verb form configuration for a language.
 */
interface VerbConfig {
    /** Position of verb in the sentence */
    readonly position: 'start' | 'end' | 'second';
    /** Common verb suffixes/conjugations to recognize */
    readonly suffixes?: string[];
    /** Whether the language commonly drops subjects */
    readonly subjectDrop?: boolean;
}
/**
 * Configuration for possessive expression construction.
 * Defines how "X's property" is expressed in a language.
 */
interface PossessiveConfig {
    /** Possessive marker (e.g., "'s" in English, "の" in Japanese) */
    readonly marker: string;
    /** Position of marker: 'after-object' (X's Y), 'between' (X の Y), 'before-property' */
    readonly markerPosition: 'after-object' | 'between' | 'before-property';
    /** Special possessive forms (e.g., 'me' → 'my' in English) */
    readonly specialForms?: Record<string, string>;
    /** Whether to use possessive adjectives instead of marker (e.g., Spanish mi/tu/su) */
    readonly usePossessiveAdjectives?: boolean;
    /**
     * Possessive keywords mapped to their corresponding reference.
     * Used by pattern-matcher to recognize possessive expressions.
     * Example: { my: 'me', your: 'you', its: 'it' }
     */
    readonly keywords?: Record<string, string>;
}
/**
 * Complete language profile for pattern generation.
 */
interface LanguageProfile {
    /** ISO 639-1 or BCP 47 language code (e.g., 'es' or 'es-MX') */
    readonly code: string;
    /** Human-readable language name */
    readonly name: string;
    /** Native name */
    readonly nativeName: string;
    /** Text direction */
    readonly direction: 'ltr' | 'rtl';
    /** Primary word order */
    readonly wordOrder: WordOrder;
    /** How this language marks grammatical roles */
    readonly markingStrategy: MarkingStrategy;
    /** Markers for each semantic role */
    readonly roleMarkers: Partial<Record<SemanticRole, RoleMarker>>;
    /** Verb configuration */
    readonly verb: VerbConfig;
    /** Command keyword translations */
    readonly keywords: Record<string, KeywordTranslation>;
    /** Whether the language uses spaces between words */
    readonly usesSpaces: boolean;
    /** Special tokenization notes */
    readonly tokenization?: TokenizationConfig;
    /** Reference translations (me, it, you, etc.) */
    readonly references?: Record<string, string>;
    /** Possessive expression configuration */
    readonly possessive?: PossessiveConfig;
    /** Event handler pattern configuration (for simple SVO languages) */
    readonly eventHandler?: EventHandlerConfig;
    /**
     * Default verb form for command keywords. Defaults to 'infinitive'.
     *
     * Based on software UI localization research:
     * - 'infinitive': Spanish, French, German, Portuguese, Russian (industry standard)
     * - 'imperative': Polish
     * - 'base': English, Japanese, Korean (no distinction or same form)
     *
     * Individual keywords can override this via KeywordTranslation.form
     */
    readonly defaultVerbForm?: VerbForm;
    /**
     * Base language code to extend (for regional variants).
     * When set, this profile inherits from the base and overrides specific fields.
     * Example: 'es-MX' profile with extends: 'es' inherits from Spanish base.
     */
    readonly extends?: string;
}
/**
 * Configuration for event handler pattern generation.
 * Supports both SVO and SOV/VSO languages.
 */
interface EventHandlerConfig {
    /** Primary event keyword (e.g., 'on', 'bei', 'sur') for SVO */
    readonly keyword?: KeywordTranslation;
    /** Source filter marker (e.g., 'from', 'von', 'de') */
    readonly sourceMarker?: RoleMarker;
    /** Conditional keyword (e.g., 'when', 'wenn', 'quand') */
    readonly conditionalKeyword?: KeywordTranslation;
    /** Event marker for SOV/VSO languages (e.g., で (Japanese), 할 때 (Korean), da (Turkish), عند (Arabic)) */
    readonly eventMarker?: RoleMarker;
    /** Temporal/conditional markers that can optionally appear with events */
    readonly temporalMarkers?: string[];
    /**
     * Negation marker for expressing negated events (e.g., Arabic عدم = "not/lack of").
     * Used in patterns like: عند عدم التركيز = "when not focusing" = "on blur"
     */
    readonly negationMarker?: RoleMarker;
}
/**
 * Verb form used for command keywords.
 *
 * Based on software localization research:
 * - 'infinitive': Standard for most languages (Spanish, French, German, Russian)
 *   Example: "Guardar", "Enregistrer", "Speichern"
 * - 'imperative': Used by some languages (Polish)
 *   Example: "Zapisz", "Otwórz"
 * - 'base': For languages where forms are identical (English, Japanese, Korean)
 *   or where the distinction doesn't apply
 */
type VerbForm = 'infinitive' | 'imperative' | 'base';
/**
 * Translation of a command keyword.
 */
interface KeywordTranslation {
    /** Primary translation (used for output/rendering) */
    readonly primary: string;
    /** Alternative forms for parsing (conjugations, synonyms, informal variants) */
    readonly alternatives?: string[];
    /** Normalized English form for internal matching */
    readonly normalized?: string;
    /**
     * The grammatical form of 'primary'. Defaults to 'infinitive'.
     * This documents the form used and enables future form-switching features.
     * - 'infinitive': Dictionary form (alternar, basculer) - industry standard
     * - 'imperative': Command form (alterna, bascule) - for Polish, etc.
     * - 'base': Same form for both (toggle, トグル) - English, Japanese, Korean
     */
    readonly form?: VerbForm;
}
/**
 * Special tokenization configuration.
 */
interface TokenizationConfig {
    /** Particles to recognize (for particle languages) */
    readonly particles?: string[];
    /** Prefixes to recognize (for prefixing languages) */
    readonly prefixes?: string[];
    /** Word boundary detection strategy */
    readonly boundaryStrategy?: 'space' | 'particle' | 'character';
}

/**
 * Language Registry
 *
 * Central registration point for language support in the semantic parser.
 * Languages self-register when their modules are imported, enabling
 * tree-shaking for minimal bundles.
 *
 * @example
 * ```typescript
 * // Import only the languages you need
 * import '@lokascript/semantic/languages/en';
 * import '@lokascript/semantic/languages/es';
 *
 * // Now parse works for registered languages
 * import { parse } from '@lokascript/semantic';
 * parse('toggle .active', 'en');     // Works
 * parse('alternar .activo', 'es');   // Works
 * parse('切り替え .active', 'ja');    // Error: Language not registered
 * ```
 */

/**
 * Merge a variant profile with its base profile.
 * The variant's fields override the base, with deep merging for nested objects.
 *
 * @example
 * ```typescript
 * const esMX = mergeProfiles(spanishProfile, {
 *   code: 'es-MX',
 *   name: 'Spanish (Mexico)',
 *   keywords: {
 *     toggle: { primary: 'alternar', alternatives: ['dale', 'cambiar'] },
 *   },
 * });
 * ```
 */
declare function mergeProfiles(base: LanguageProfile, variant: Partial<LanguageProfile>): LanguageProfile;
/**
 * Register a language with its tokenizer and profile.
 * Called automatically by language modules when imported.
 * If the profile has an `extends` field, it will inherit from the base profile.
 */
declare function registerLanguage(code: string, tokenizer: LanguageTokenizer, profile: LanguageProfile): void;
/**
 * Set the pattern generator function.
 * Called by patterns module to inject the generator without circular deps.
 */
declare function setPatternGenerator(generator: (profile: LanguageProfile) => LanguagePattern[]): void;
/**
 * Register patterns directly for a language.
 * This enables tree-shaking by allowing each language module to register
 * only its own patterns.
 */
declare function registerPatterns(code: string, patterns: LanguagePattern[]): void;
/**
 * Get a tokenizer for the specified language.
 * Supports fallback: if 'es-MX' is not registered, falls back to 'es'.
 * @throws Error if neither the variant nor base language is registered
 */
declare function getTokenizer(code: string): LanguageTokenizer;
/**
 * Get a profile for the specified language.
 * Supports fallback: if 'es-MX' is not registered, falls back to 'es'.
 * @throws Error if neither the variant nor base language is registered
 */
declare function getProfile(code: string): LanguageProfile;
/**
 * Try to get a profile, returning undefined if not registered.
 * Supports fallback: if 'es-MX' is not registered, falls back to 'es'.
 */
declare function tryGetProfile(code: string): LanguageProfile | undefined;
/**
 * Get all registered language codes.
 */
declare function getRegisteredLanguages(): string[];
/**
 * Check if a language is registered (exact match or base language fallback).
 */
declare function isLanguageRegistered(code: string): boolean;
/**
 * Check if a language is supported (exact match or base language fallback).
 * For backwards compatibility with tokenizers API.
 */
declare function isLanguageSupported(code: string): boolean;
/**
 * Get patterns for a specific language.
 * First checks for directly registered patterns (for tree-shaking),
 * then falls back to pattern generator.
 * Supports fallback: if 'es-MX' is not registered, falls back to 'es'.
 * @throws Error if language is not registered
 */
declare function getPatternsForLanguage(code: string): LanguagePattern[];
/**
 * Get patterns for a specific language and command.
 */
declare function getPatternsForLanguageAndCommand(language: string, command: string): LanguagePattern[];

export { ASTBuilder, type ASTBuilderOptions, type ASTNode, type ActionType, type BlockNode, type BuildASTResult, type CacheStats, type CommandMapper, type CommandMapperResult, type CommandNode, type CommandSemanticNode, type CommandSequenceNode, type CompoundSemanticNode, type ConditionalNode, type ConditionalSemanticNode, DEFAULT_CONFIDENCE_THRESHOLD, type EventHandlerNode, type EventHandlerSemanticNode, HIGH_CONFIDENCE_THRESHOLD, type KeywordTranslation, type LanguagePattern, type LanguageProfile, type LanguageToken, type LanguageTokenizer, type LoopSemanticNode, type MarkingStrategy, type PatternMatchResult, type PossessiveConfig, type RoleMarker, type SemanticAnalysisResult, type SemanticAnalyzer, SemanticAnalyzerImpl, type SemanticAnalyzerOptions, SemanticCache, type SemanticCacheConfig, type SemanticMetadata, type SemanticNode, type SemanticRole, type SemanticValue, type TokenKind, type TokenStream, type TokenizationConfig, type VerbConfig, type WordOrder, buildAST, convertExpression, convertLiteral, convertPropertyPath, convertReference, convertSelector, convertValue, createCommandNode, createEventHandler, createLiteral, createPropertyPath, createReference, createSelector, createSemanticAnalyzer, createSemanticCache, getCommandMapper, getPatternsForLanguage, getPatternsForLanguageAndCommand, getProfile, getRegisteredLanguages, getRegisteredMappers, getTokenizer, isLanguageRegistered, isLanguageSupported, mergeProfiles, registerCommandMapper, registerLanguage, registerPatterns, rolesToCommandArgs, semanticCache, setPatternGenerator, shouldUseSemanticResult, tryGetProfile, withCache };
