@lokascript/framework 4.8.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/dist/api/create-dsl.d.ts +9 -10
  3. package/dist/api/create-dsl.d.ts.map +1 -1
  4. package/dist/api/index.js +835 -1670
  5. package/dist/api/index.js.map +1 -1
  6. package/dist/core/index.d.ts +0 -1
  7. package/dist/core/index.d.ts.map +1 -1
  8. package/dist/core/index.js +549 -1132
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/core/matching/index.d.ts +2 -0
  11. package/dist/core/matching/index.d.ts.map +1 -1
  12. package/dist/core/matching/possessive-keywords.d.ts.map +1 -0
  13. package/dist/core/matching/stock-confidence.d.ts +3 -4
  14. package/dist/core/matching/stock-confidence.d.ts.map +1 -1
  15. package/dist/core/matching/stock-reading.d.ts +4 -4
  16. package/dist/core/{pattern-matching/utils → matching}/type-validation.d.ts +1 -1
  17. package/dist/core/matching/type-validation.d.ts.map +1 -0
  18. package/dist/generation/index.d.ts +1 -1
  19. package/dist/generation/index.d.ts.map +1 -1
  20. package/dist/generation/index.js +20 -169
  21. package/dist/generation/index.js.map +1 -1
  22. package/dist/generation/profile.d.ts +30 -0
  23. package/dist/generation/profile.d.ts.map +1 -0
  24. package/dist/generation/renderer.d.ts +1 -1
  25. package/dist/generation/renderer.d.ts.map +1 -1
  26. package/dist/generation/schema-patterns.d.ts +3 -3
  27. package/dist/index.cjs +929 -1674
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.js +929 -1668
  30. package/dist/index.js.map +1 -1
  31. package/dist/multilingual/builders.d.ts +3 -3
  32. package/dist/multilingual/builders.d.ts.map +1 -1
  33. package/dist/multilingual/index.js.map +1 -1
  34. package/dist/parsing/index.d.ts +0 -1
  35. package/dist/parsing/index.d.ts.map +1 -1
  36. package/dist/parsing/index.js +0 -1145
  37. package/dist/parsing/index.js.map +1 -1
  38. package/dist/testing/gate/lint/types.d.ts +1 -1
  39. package/dist/testing/gate/lint/types.d.ts.map +1 -1
  40. package/package.json +2 -7
  41. package/src/__test__/test-utils.ts +1 -1
  42. package/src/api/create-dsl-engine.test.ts +60 -35
  43. package/src/api/create-dsl.ts +24 -35
  44. package/src/core/index.ts +0 -1
  45. package/src/core/matching/index.ts +2 -0
  46. package/src/core/matching/stock-confidence.ts +3 -4
  47. package/src/core/matching/stock-reading.ts +6 -6
  48. package/src/core/{pattern-matching/utils → matching}/type-validation.test.ts +2 -2
  49. package/src/core/{pattern-matching/utils → matching}/type-validation.ts +1 -1
  50. package/src/generation/domain-renderer.test.ts +1 -1
  51. package/src/generation/index.ts +1 -1
  52. package/src/generation/profile.ts +41 -0
  53. package/src/generation/renderer.test.ts +1 -1
  54. package/src/generation/renderer.ts +1 -1
  55. package/src/generation/schema-patterns.ts +3 -3
  56. package/src/multilingual/bridge.test.ts +31 -23
  57. package/src/multilingual/builders.ts +3 -3
  58. package/src/parsing/index.ts +0 -1
  59. package/src/testing/gate/lint/types.ts +1 -1
  60. package/dist/core/pattern-matching/index.d.ts +0 -6
  61. package/dist/core/pattern-matching/index.d.ts.map +0 -1
  62. package/dist/core/pattern-matching/index.js +0 -1211
  63. package/dist/core/pattern-matching/index.js.map +0 -1
  64. package/dist/core/pattern-matching/pattern-matcher.d.ts +0 -122
  65. package/dist/core/pattern-matching/pattern-matcher.d.ts.map +0 -1
  66. package/dist/core/pattern-matching/utils/index.d.ts +0 -6
  67. package/dist/core/pattern-matching/utils/index.d.ts.map +0 -1
  68. package/dist/core/pattern-matching/utils/possessive-keywords.d.ts.map +0 -1
  69. package/dist/core/pattern-matching/utils/type-validation.d.ts.map +0 -1
  70. package/dist/generation/pattern-generator.d.ts +0 -55
  71. package/dist/generation/pattern-generator.d.ts.map +0 -1
  72. package/src/core/pattern-matching/index.ts +0 -6
  73. package/src/core/pattern-matching/pattern-matcher.test.ts +0 -1031
  74. package/src/core/pattern-matching/pattern-matcher.ts +0 -765
  75. package/src/core/pattern-matching/utils/index.ts +0 -6
  76. package/src/generation/pattern-generator.test.ts +0 -532
  77. package/src/generation/pattern-generator.ts +0 -327
  78. /package/dist/core/{pattern-matching/utils → matching}/possessive-keywords.d.ts +0 -0
  79. /package/src/core/{pattern-matching/utils → matching}/possessive-keywords.ts +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/logger.ts","../../src/core/types.ts","../../src/core/pattern-matching/utils/type-validation.ts","../../src/core/pattern-matching/utils/possessive-keywords.ts","../../src/core/matching/stock-reading.ts","../../src/core/matching/stock-confidence.ts","../../src/core/pattern-matching/pattern-matcher.ts","../../src/parsing/multi-statement.ts"],"sourcesContent":["/**\n * Debug Logging System\n *\n * Provides environment-aware debug logging for the framework.\n * Enable via DEBUG environment variable or programmatically.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n isEnabled(): boolean;\n}\n\nclass DebugLogger {\n private enabled: boolean;\n private namespace: string;\n\n constructor(namespace: string) {\n this.namespace = namespace;\n this.enabled = this.checkEnabled();\n }\n\n private checkEnabled(): boolean {\n // Check if running in Node.js\n if (typeof process !== 'undefined' && process.env) {\n const DEBUG = process.env.DEBUG || '';\n // Enable if DEBUG=* or DEBUG=framework:* or DEBUG=framework:namespace\n return (\n DEBUG === '*' ||\n DEBUG.includes('framework:*') ||\n DEBUG.includes(`framework:${this.namespace}`)\n );\n }\n return false;\n }\n\n private log(level: LogLevel, message: string, ...args: any[]): void {\n if (!this.enabled) return;\n\n const prefix = `[framework:${this.namespace}]`;\n const timestamp = new Date().toISOString();\n\n switch (level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(`${timestamp} ${prefix} DEBUG:`, message, ...args);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(`${timestamp} ${prefix} INFO:`, message, ...args);\n break;\n case 'warn':\n // eslint-disable-next-line no-console\n console.warn(`${timestamp} ${prefix} WARN:`, message, ...args);\n break;\n case 'error':\n // eslint-disable-next-line no-console\n console.error(`${timestamp} ${prefix} ERROR:`, message, ...args);\n break;\n }\n }\n\n debug(message: string, ...args: any[]): void {\n this.log('debug', message, ...args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log('info', message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log('warn', message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.log('error', message, ...args);\n }\n\n /**\n * Check if logging is enabled for this namespace.\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n\n /**\n * Programmatically enable logging for this namespace.\n */\n enable(): void {\n this.enabled = true;\n }\n\n /**\n * Programmatically disable logging for this namespace.\n */\n disable(): void {\n this.enabled = false;\n }\n}\n\n/**\n * Create a logger for a specific namespace.\n *\n * @param namespace - Logger namespace (e.g., 'pattern-matcher', 'tokenizer')\n * @returns Logger instance\n *\n * @example\n * const logger = createLogger('pattern-matcher');\n * logger.debug('Matching pattern:', pattern.id);\n * logger.warn('Low confidence match:', confidence);\n */\nexport function createLogger(namespace: string): Logger {\n return new DebugLogger(namespace);\n}\n\n/**\n * No-op logger that does nothing.\n * Useful for disabling logging in production builds.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n isEnabled: () => false,\n};\n","/**\n * Core Types — re-exported from @lokascript/intent + framework-specific extensions\n *\n * The universal semantic types (SemanticNode, SemanticValue, etc.) now live in\n * @lokascript/intent and are re-exported here for backward compatibility.\n *\n * Framework-specific types (tokenization, pattern matching) are defined below.\n */\n\n// =============================================================================\n// Re-export everything from @lokascript/intent\n// =============================================================================\n\nexport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n ExpectedType,\n LiteralValue,\n SelectorValue,\n ReferenceValue,\n PropertyPathValue,\n ExpressionValue,\n FlagValue,\n Annotation,\n ProtocolDiagnostic,\n AsyncVariant,\n MatchArm,\n SemanticNode,\n SemanticMetadata,\n SourcePosition,\n CommandSemanticNode,\n EventHandlerSemanticNode,\n EventModifiers,\n ConditionalSemanticNode,\n CompoundSemanticNode,\n LoopVariant,\n LoopSemanticNode,\n LSEEnvelope,\n} from '@lokascript/intent';\n\nexport {\n createLiteral,\n createSelector,\n createReference,\n createPropertyPath,\n createExpression,\n createFlag,\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createCompoundNode,\n createLoopNode,\n createTryNode,\n createAsyncNode,\n createMatchNode,\n extractValue,\n extractRoleValue,\n getRoleValue,\n} from '@lokascript/intent';\n\n// =============================================================================\n// Framework-specific types (multilingual DSL infrastructure)\n// =============================================================================\n\nimport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n SelectorValue,\n ExpectedType,\n SourcePosition,\n} from '@lokascript/intent';\n\n/**\n * Token kind - categorizes what type of token this is.\n */\nexport type TokenKind =\n | 'keyword' // Command or modifier keyword\n | 'selector' // CSS selector or identifier (#id, .class, table-name)\n | 'literal' // String or number literal\n | 'particle' // Grammatical particle (を, に, من)\n | 'conjunction' // Grammatical conjunction\n | 'event-modifier' // Event modifier (.once, .debounce(300))\n | 'identifier' // Generic identifier\n | 'operator' // Operators (., +, -, etc.)\n | 'punctuation' // Punctuation (parentheses, etc.)\n | 'url'; // URL or path\n\n/**\n * A language token - the result of tokenization.\n */\nexport interface LanguageToken {\n readonly value: string;\n readonly kind: TokenKind;\n readonly position: SourcePosition;\n readonly normalized?: string;\n readonly stem?: string;\n readonly stemConfidence?: number;\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Token stream - provides sequential access to tokens with backtracking.\n */\nexport interface TokenStream {\n readonly tokens: readonly LanguageToken[];\n readonly language: string;\n peek(offset?: number): LanguageToken | null;\n advance(): LanguageToken;\n isAtEnd(): boolean;\n mark(): StreamMark;\n reset(mark: StreamMark): void;\n position(): number;\n}\n\nexport interface StreamMark {\n readonly position: number;\n}\n\n/**\n * Language tokenizer interface - converts text to tokens.\n */\nexport interface LanguageTokenizer {\n readonly language: string;\n readonly direction: 'ltr' | 'rtl';\n tokenize(input: string): TokenStream;\n classifyToken(token: string): TokenKind;\n}\n\n// =============================================================================\n// Pattern Matching Types\n// =============================================================================\n\nexport interface LanguagePattern {\n readonly id: string;\n readonly language: string;\n readonly command: ActionType;\n readonly priority: number;\n readonly template: PatternTemplate;\n readonly extraction: ExtractionRules;\n readonly constraints?: PatternConstraints;\n /**\n * The pattern reads a form the renderer does not write by choosing it\n * (hyperscript's wait `esperar evento {event}`: the renderer writes the event\n * word itself, before a name no table knows). The renderer skips it.\n */\n readonly parseOnly?: boolean;\n}\n\nexport interface PatternTemplate {\n readonly format: string;\n readonly tokens: PatternToken[];\n}\n\nexport type PatternToken = LiteralPatternToken | RolePatternToken | GroupPatternToken;\n\nexport interface LiteralPatternToken {\n readonly type: 'literal';\n readonly value: string;\n readonly alternatives?: string[];\n /**\n * Parse-only marker: the matcher still consumes this literal, but the\n * renderer skips it. Set when a role declares `renderOverride: { <lang>: '' }`\n * (hyperscript's fetch `from`: required to PARSE `fetch from /api`, absent from\n * the render, since `fetch from \"/api\"` is not canonical _hyperscript).\n */\n readonly renderSuppress?: boolean;\n}\n\nexport interface RolePatternToken {\n readonly type: 'role';\n readonly role: SemanticRole;\n readonly optional?: boolean;\n readonly expectedTypes?: Array<ExpectedType>;\n readonly greedy?: boolean;\n /**\n * The words the slot reads, from the schema's `RoleSpec.words` for the pattern's language (its\n * `'*'` list and the language's own): the stock reader reads the slot only from one of them.\n */\n readonly words?: readonly string[];\n /**\n * Mirrors the schema's `RoleSpec.valueShape`: the slot's surface form is\n * unambiguous on its own. Carried onto the pattern token because the value\n * reader needs it too, not just the confidence model (hyperscript's\n * `'keyword'` slots hold a fixed keyword phrase and are exempt from the\n * trailing-slot verb guard).\n */\n readonly valueShape?: 'time' | 'reference' | 'keyword' | 'object' | 'clause' | 'list';\n}\n\nexport interface GroupPatternToken {\n readonly type: 'group';\n readonly tokens: PatternToken[];\n readonly optional?: boolean;\n /**\n * The group is optional for PARSING but belongs in canonical output: the\n * marker-only groups a profile's optional case markers produce (Turkish case\n * suffixes may be dropped colloquially, so the parse accepts both forms).\n * The matcher's skeleton also requires such a group's marker after a role it\n * captures (`MatchSkeleton`).\n */\n readonly renderRequired?: boolean;\n}\n\nexport interface ExtractionRules {\n readonly [role: string]: ExtractionRule;\n}\n\nexport interface ExtractionRule {\n readonly position?: number;\n readonly marker?: string;\n readonly markerAlternatives?: string[];\n readonly transform?: (raw: string) => SemanticValue;\n readonly default?: SemanticValue;\n readonly value?: string;\n /**\n * The static `value` is an expression, as the English parse types the word\n * (hyperscript's `go back` destination), not a literal.\n */\n readonly valueIsExpression?: true;\n readonly fromRole?: string;\n}\n\nexport interface PatternConstraints {\n readonly requiredRoles?: SemanticRole[];\n readonly forbiddenRoles?: SemanticRole[];\n readonly validPatientTypes?: Array<SelectorValue['selectorKind']>;\n readonly conflictsWith?: string[];\n}\n\nexport interface PatternMatchResult {\n readonly pattern: LanguagePattern;\n readonly captured: ReadonlyMap<SemanticRole, SemanticValue>;\n readonly consumedTokens: number;\n readonly confidence: number;\n /**\n * Stream index at which each captured role's value STARTED, for callers that\n * need to re-read a slot's own span rather than the tail after it. Populated\n * on the same success path as `captured` (`MatchSkeleton`), so a role left\n * behind by a rolled-back group survives in both maps or in neither.\n */\n readonly roleStarts?: ReadonlyMap<SemanticRole, number>;\n /**\n * A source phrase hyperscript's reader found in an event HEAD (`from #btn`\n * right after the event) rather than in a pattern slot: kept out of\n * `captured`, so a fused pattern's own source group can neither overwrite it\n * nor be overwritten (`ValueReader.resultFields`).\n */\n readonly eventSource?: SemanticValue;\n}\n\nexport interface PatternMatchError {\n readonly message: string;\n readonly position: SourcePosition;\n readonly expectedPatterns?: string[];\n readonly partialMatch?: Partial<PatternMatchResult>;\n}\n","/**\n * Type Validation Utility\n *\n * Shared utilities for validating semantic value types against expected types.\n * Used by pattern-matcher to validate captured role values.\n */\n\nimport type { SemanticValue } from '../../types';\n\n/**\n * Semantic value type strings.\n */\nexport type SemanticValueType = SemanticValue['type'];\n\n/**\n * Check if a value type matches any of the expected types.\n *\n * The 'expression' type is treated as a wildcard that matches any value.\n * The 'property-path' type is compatible with selector, reference, and expression.\n *\n * @param actualType The actual type of the value\n * @param expectedTypes Array of expected types\n * @returns True if the type is compatible\n */\nexport function isTypeCompatible(\n actualType: SemanticValueType | string,\n expectedTypes: (SemanticValueType | string)[]\n): boolean {\n // Empty expected types means any type is valid\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n // Direct match\n if (expectedTypes.includes(actualType)) {\n return true;\n }\n\n // 'expression' is always compatible (wildcard)\n if (expectedTypes.includes('expression')) {\n return true;\n }\n\n // 'property-path' is compatible with selector, reference, and expression\n if (actualType === 'property-path') {\n return expectedTypes.some(t => ['selector', 'reference', 'expression'].includes(t));\n }\n\n return false;\n}\n\n/**\n * Validate a semantic value against expected types.\n *\n * @param value The semantic value to validate\n * @param expectedTypes Array of expected types (empty means any type is valid)\n * @returns True if the value type is valid\n */\nexport function validateValueType(\n value: SemanticValue,\n expectedTypes?: (SemanticValueType | string)[]\n): boolean {\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n return isTypeCompatible(value.type, expectedTypes);\n}\n\n/**\n * Check if a value is a CSS selector.\n */\nexport function isCSSSelector(value: string): boolean {\n return value.startsWith('.') || value.startsWith('#') || value.startsWith('<');\n}\n\n/**\n * Check if a value is a class name (starts with .).\n */\nexport function isClassName(value: string): boolean {\n return value.startsWith('.');\n}\n\n/**\n * Check if a value is an ID selector (starts with #).\n */\nexport function isIdSelector(value: string): boolean {\n return value.startsWith('#');\n}\n\n/**\n * Check if a value is a CSS property reference (starts with *).\n */\nexport function isCSSPropertyRef(value: string): boolean {\n return value.startsWith('*');\n}\n\n/**\n * Check if a value is a numeric value.\n */\nexport function isNumericValue(value: string): boolean {\n // Handle duration values (e.g., \"100ms\", \"2s\")\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n return true;\n }\n\n // Plain number\n const num = parseFloat(value);\n return !isNaN(num) && isFinite(num);\n}\n\n/**\n * Check if a value is a property name (identifier-like).\n */\nexport function isPropertyName(value: string): boolean {\n // Property names are identifiers (start with letter or _, contain alphanumeric)\n return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);\n}\n\n/**\n * Check if a value is a variable reference (starts with :).\n */\nexport function isVariableRef(value: string): boolean {\n return value.startsWith(':');\n}\n\n/**\n * Check if a value is a built-in reference (me, you, it, etc.).\n */\nexport function isBuiltInReference(value: string): boolean {\n const builtIns = new Set(['me', 'you', 'it', 'result', 'event', 'target', 'body']);\n return builtIns.has(value.toLowerCase());\n}\n","/**\n * Possessive Keywords Utility\n *\n * Provides functions to look up possessive keywords from language profiles.\n * Used by pattern-matcher to recognize possessive expressions like \"my value\".\n */\n\n/**\n * Minimal profile interface for possessive keyword lookup.\n */\nexport interface PossessiveProfile {\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n/**\n * Get the reference for a possessive keyword from a profile.\n *\n * @param profile Language profile\n * @param keyword Possessive keyword (e.g., 'my', 'your', 'its')\n * @returns The reference (e.g., 'me', 'you', 'it') or undefined if not found\n */\nexport function getPossessiveReference(\n profile: PossessiveProfile | undefined,\n keyword: string\n): string | undefined {\n return profile?.possessive?.keywords?.[keyword];\n}\n\n/**\n * Check if a keyword is a possessive keyword in the given profile.\n *\n * @param profile Language profile\n * @param keyword Keyword to check\n * @returns True if the keyword is a possessive keyword\n */\nexport function isPossessiveKeyword(\n profile: PossessiveProfile | undefined,\n keyword: string\n): boolean {\n return profile?.possessive?.keywords?.[keyword] !== undefined;\n}\n\n/**\n * Get all possessive keywords from a profile.\n *\n * @param profile Language profile\n * @returns Record of possessive keywords to references, or empty object\n */\nexport function getAllPossessiveKeywords(\n profile: PossessiveProfile | undefined\n): Record<string, string> {\n return profile?.possessive?.keywords ?? {};\n}\n","/**\n * Reading a domain value at a role slot: the value reading framework's old\n * matcher (`core/pattern-matching/`) did, moved here so the stock reader on the\n * matcher's skeleton (`stock-reader.ts`, domains rethink Phase 4.7) and the old\n * matcher run the same code until Phase 6 deletes the old one.\n *\n * In order: an English noise word before a selector (`the`), then the\n * multi-token forms (a possessive, `my value`; a method call,\n * `#dialog.showModal()`; a possessive selector, `#el's *opacity`; a property\n * access, `user.name`; a selector and its property, `#out.innerText`), then one\n * token by its kind (a selector, a quoted string, a number, a boolean, a\n * duration, a URL, an identifier). Each is checked against the slot's\n * expected types.\n */\n\nimport type {\n PatternToken,\n ReferenceValue,\n SemanticRole,\n SemanticValue,\n TokenStream,\n LanguageToken,\n} from '../types';\nimport { createSelector, createLiteral, createReference, createPropertyPath } from '../types';\nimport { isTypeCompatible } from '../pattern-matching/utils/type-validation';\nimport { getPossessiveReference } from '../pattern-matching/utils/possessive-keywords';\n\n/** What value reading needs of a language profile: its code, and its possessive words. */\nexport interface ReadingProfile {\n readonly code: string;\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\nfunction isValidReference(_value: string): boolean {\n // In generic framework, no built-in references\n // Identifiers should be expressions\n return false;\n}\n\n/**\n * Safely convert a value to lowercase string.\n * Provides protection against non-string values at runtime.\n */\n/** `value` lower-cased, whatever it is (the old matcher's keyword compare uses it too). */\nexport function safeToLowerCase(value: unknown): string {\n if (typeof value === 'string') {\n return value.toLowerCase();\n }\n if (value === null || value === undefined) {\n return '';\n }\n return String(value).toLowerCase();\n}\n\n/**\n * Match a role pattern token (captures a semantic value).\n * Handles multi-token expressions like:\n * - 'my value' (possessive keyword + property)\n * - '#dialog.showModal()' (method call)\n * - \"#element's *opacity\" (possessive selector + property)\n */\n/**\n * Read a value for `patternToken`'s role at the stream's position into\n * `captured`, and advance past it. False when the slot does not match; an\n * optional slot whose value does not fit returns true and captures nothing.\n */\nexport function readRoleValue(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'role' },\n captured: Map<SemanticRole, SemanticValue>,\n profile?: ReadingProfile\n): boolean {\n // Skip noise words like \"the\" before selectors (English idiom support)\n skipNoiseWords(tokens);\n\n const token = tokens.peek();\n if (!token) {\n return patternToken.optional || false;\n }\n\n // Check for possessive expression (e.g., 'my value', 'its innerHTML')\n const possessiveValue = tryMatchPossessiveExpression(tokens, profile);\n if (possessiveValue) {\n // Validate expected types if specified\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveValue);\n return true;\n }\n\n // Check for method call expression (e.g., '#dialog.showModal()')\n const methodCallValue = tryMatchMethodCallExpression(tokens);\n if (methodCallValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, methodCallValue);\n return true;\n }\n\n // Check for possessive selector expression (e.g., \"#element's *opacity\")\n const possessiveSelectorValue = tryMatchPossessiveSelectorExpression(tokens);\n if (possessiveSelectorValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n // property-path is compatible with selector, reference, and expression\n if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveSelectorValue);\n return true;\n }\n\n // Check for property access expression (e.g., 'userData.name', 'it.data')\n const propertyAccessValue = tryMatchPropertyAccessExpression(tokens);\n if (propertyAccessValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, propertyAccessValue);\n return true;\n }\n\n // Check for selector + property expression (e.g., '#output.innerText')\n // This handles cases where the tokenizer produces two selector tokens\n const selectorPropertyValue = tryMatchSelectorPropertyExpression(tokens);\n if (selectorPropertyValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, selectorPropertyValue);\n return true;\n }\n\n // Try to extract a semantic value from the token\n const value = tokenToSemanticValue(token);\n if (!value) {\n return patternToken.optional || false;\n }\n\n // Validate expected types if specified\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n\n captured.set(patternToken.role, value);\n tokens.advance();\n return true;\n}\n\n/**\n * Try to match a possessive expression like 'my value' or 'its innerHTML'.\n * Returns the PropertyPathValue if matched, or null if not.\n */\nfunction tryMatchPossessiveExpression(\n tokens: TokenStream,\n profile: ReadingProfile | undefined\n): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Use profile-based possessive keyword lookup\n if (!profile) return null;\n\n const tokenValue = token.normalized || token.value;\n const tokenLower = safeToLowerCase(tokenValue);\n const baseRef = getPossessiveReference(profile, tokenLower);\n\n if (!baseRef) return null;\n\n // We have a possessive keyword, look ahead for property name\n const mark = tokens.mark();\n tokens.advance();\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n // Just the possessive keyword, no property - revert\n tokens.reset(mark);\n return null;\n }\n\n // Property should be an identifier, keyword (not structural), or selector (for style/dot/attr)\n // Examples: \"my value\", \"my innerHTML\", \"my *background\", \"my *opacity\", \"my @data-count\"\n // Also handles dot-property access: \"my.textContent\" tokenized as \"my\" + \".textContent\"\n if (\n propertyToken.kind === 'identifier' ||\n (propertyToken.kind === 'keyword' && !isStructuralKeyword(propertyToken.value)) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('*')) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('@')) ||\n (propertyToken.kind === 'selector' &&\n propertyToken.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyToken.value))\n ) {\n tokens.advance();\n\n // For dot-property selectors (.textContent), strip the leading dot\n let propertyName = propertyToken.value;\n if (\n propertyToken.kind === 'selector' &&\n propertyName.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyName)\n ) {\n propertyName = propertyName.substring(1);\n }\n\n // Consume chained dot-property access (.parentElement.style.display)\n let chainedProps = propertyName;\n while (\n tokens.peek()?.kind === 'selector' &&\n tokens.peek()!.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(tokens.peek()!.value)\n ) {\n chainedProps += tokens.peek()!.value; // keep the dots for chaining\n tokens.advance();\n }\n\n // Check for method call — next token is '(' in the value (e.g., .getAttribute(\"data-id\"))\n const nextPeek = tokens.peek();\n if (nextPeek?.kind === 'literal' && nextPeek.value.startsWith('(')) {\n // Consume method args\n chainedProps += nextPeek.value;\n tokens.advance();\n }\n\n // Create property-path: my value -> { object: me, property: 'value' }\n // baseRef from getPossessiveReference is always a valid reference ('me', 'you', 'it', etc.)\n return createPropertyPath(createReference(baseRef as ReferenceValue['value']), chainedProps);\n }\n\n // Not a valid property, revert\n tokens.reset(mark);\n return null;\n}\n\n/**\n * Check if a keyword is a structural keyword (preposition, control flow, etc.)\n * that shouldn't be consumed as a property name.\n */\nfunction isStructuralKeyword(value: string): boolean {\n const structural = new Set([\n // Prepositions\n 'into',\n 'in',\n 'to',\n 'from',\n 'at',\n 'by',\n 'with',\n 'without',\n 'before',\n 'after',\n 'of',\n 'as',\n 'on',\n // Control flow\n 'then',\n 'end',\n 'else',\n 'if',\n 'repeat',\n 'while',\n 'for',\n // Commands (shouldn't be property names)\n 'toggle',\n 'add',\n 'remove',\n 'put',\n 'set',\n 'show',\n 'hide',\n 'increment',\n 'decrement',\n 'send',\n 'trigger',\n 'call',\n ]);\n return structural.has(value.toLowerCase());\n}\n\n/**\n * Try to match a method call expression like '#dialog.showModal()'.\n * Pattern: selector + '.' + identifier + '(' + [args] + ')'\n * Returns an expression value if matched, or null if not.\n */\nfunction tryMatchMethodCallExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: . identifier (\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const methodToken = tokens.peek();\n if (!methodToken || methodToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume method name\n\n const openParen = tokens.peek();\n if (!openParen || openParen.kind !== 'punctuation' || openParen.value !== '(') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume (\n\n // Consume arguments until we find ) (with depth limit for security)\n const args: string[] = [];\n while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n tokens.advance(); // consume )\n break;\n }\n // Skip commas\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value: #dialog.showModal()\n const methodCall = `${token.value}.${methodToken.value}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n}\n\n/**\n * Try to match a property access expression like 'userData.name' or 'it.data'.\n * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]\n * Returns an expression value if matched, or null if not.\n */\nfunction tryMatchPropertyAccessExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Must start with an identifier or keyword reference\n if (token.kind !== 'identifier' && token.kind !== 'keyword') return null;\n\n // Look ahead for: . identifier\n const mark = tokens.mark();\n tokens.advance(); // consume first token\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property name\n\n // Build the property chain\n let chain = `${token.value}.${propertyToken.value}`;\n let depth = 1; // Already have one property access\n\n // Continue for nested property access (e.g., userData.address.city)\n // With depth limit for security\n while (!tokens.isAtEnd() && depth < MAX_PROPERTY_DEPTH) {\n const nextDot = tokens.peek();\n if (!nextDot || nextDot.kind !== 'operator' || nextDot.value !== '.') {\n break;\n }\n tokens.advance(); // consume .\n\n const nextProp = tokens.peek();\n if (!nextProp || nextProp.kind !== 'identifier') {\n // Dot without property - put the dot back and stop\n // Can't easily put a single token back, so we'll include it\n break;\n }\n tokens.advance(); // consume property\n chain += `.${nextProp.value}`;\n depth++;\n }\n\n // Check for method call: chain + '(' + args + ')'\n // e.g., me.insertBefore(draggedItem, dropTarget)\n const openParen = tokens.peek();\n if (openParen && openParen.kind === 'punctuation' && openParen.value === '(') {\n tokens.advance(); // consume (\n\n // Collect arguments (comma-separated values)\n const args: string[] = [];\n let argDepth = 0; // Track nested parentheses\n while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n\n // Handle close paren - respecting nesting\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n if (argDepth === 0) {\n tokens.advance(); // consume )\n break;\n }\n argDepth--;\n }\n // Track nested open parens\n if (argToken.kind === 'punctuation' && argToken.value === '(') {\n argDepth++;\n }\n // Skip commas between arguments\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value with method call: me.insertBefore(a, b)\n const methodCall = `${chain}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n // Create expression value: userData.name\n return {\n type: 'expression',\n raw: chain,\n } as SemanticValue;\n}\n\n/**\n * Try to match a possessive selector expression like \"#element's *opacity\".\n * Pattern: selector + \"'s\" + (selector | identifier)\n * Returns a property-path value if matched, or null if not.\n */\nfunction tryMatchPossessiveSelectorExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: 's (possessive marker)\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const possessiveToken = tokens.peek();\n if (\n !possessiveToken ||\n possessiveToken.kind !== 'punctuation' ||\n possessiveToken.value !== \"'s\"\n ) {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume 's\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n tokens.reset(mark);\n return null;\n }\n\n // Property can be a selector (*opacity) or identifier\n if (propertyToken.kind !== 'selector' && propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property\n\n // Create property-path: #element's *opacity\n return createPropertyPath(createSelector(token.value), propertyToken.value);\n}\n\n/**\n * Try to match a selector + property expression like \"#output.innerText\".\n * This handles cases where the tokenizer produces two selector tokens:\n * - #output (id selector)\n * - .innerText (looks like class selector, but is actually property)\n *\n * Pattern: id-selector + class-selector-that-is-actually-property\n * Returns a property-path value if matched, or null if not.\n */\nfunction tryMatchSelectorPropertyExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Must be an ID selector (starts with #)\n if (typeof token.value !== 'string' || !token.value.startsWith('#')) return null;\n\n // Look ahead for: selector that looks like a property (.something)\n const mark = tokens.mark();\n tokens.advance(); // consume first selector\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'selector') {\n tokens.reset(mark);\n return null;\n }\n\n // Second token must look like a class selector (starts with .)\n // but we interpret it as a property access\n if (!propertyToken.value.startsWith('.')) {\n tokens.reset(mark);\n return null;\n }\n\n // Verify the next token is not a selector (to avoid consuming too many)\n // This helps distinguish \"#output.innerText\" from \"#box .child\"\n const peek2 = tokens.peek(1);\n if (peek2 && peek2.kind === 'selector') {\n // Could be a compound selector chain - only take first two\n }\n\n tokens.advance(); // consume property selector\n\n // Create property-path: #output.innerText\n // Extract property name without the leading dot\n const propertyName = propertyToken.value.slice(1);\n\n return createPropertyPath(createSelector(token.value), propertyName);\n}\n\n/** Maximum depth for nested property access (e.g., a.b.c.d...) */\nconst MAX_PROPERTY_DEPTH = 10;\n\n/** Maximum number of arguments in method calls */\nconst MAX_METHOD_ARGS = 20;\n\n/**\n * Convert a language token to a semantic value.\n */\nfunction tokenToSemanticValue(token: LanguageToken): SemanticValue | null {\n switch (token.kind) {\n case 'selector':\n return createSelector(token.value);\n\n case 'literal':\n return parseLiteralValue(token.value);\n\n case 'keyword': {\n // Keywords might be references or values\n const tokenValue = token.normalized || token.value;\n const lower = safeToLowerCase(tokenValue);\n if (isValidReference(lower)) {\n return createReference(lower);\n }\n return createLiteral(token.normalized || token.value);\n }\n\n case 'identifier': {\n // Check if it's a variable reference (:varname)\n // Note: :varname doesn't match the ReferenceValue union but is used as a\n // reference token downstream — this cast preserves existing behavior\n if (typeof token.value === 'string' && token.value.startsWith(':')) {\n return createReference(token.value as ReferenceValue['value']);\n }\n // Check if it's a built-in reference\n const identLower = safeToLowerCase(token.value);\n if (isValidReference(identLower)) {\n return createReference(identLower);\n }\n // Regular identifiers are variable references - use 'expression' type\n // which gets converted to 'identifier' AST nodes by semantic-integration.ts\n return { type: 'expression', raw: token.value } as const;\n }\n\n case 'url':\n // URLs are treated as string literals (paths/URLs for navigation/fetch)\n return createLiteral(token.value, 'string');\n\n default:\n return null;\n }\n}\n\n/**\n * Parse a literal value (string, number, boolean).\n */\nfunction parseLiteralValue(value: string): SemanticValue {\n // String literal\n if (\n value.startsWith('\"') ||\n value.startsWith(\"'\") ||\n value.startsWith('`') ||\n value.startsWith('「')\n ) {\n const inner = value.slice(1, -1);\n return createLiteral(inner, 'string');\n }\n\n // Boolean\n if (value === 'true') return createLiteral(true, 'boolean');\n if (value === 'false') return createLiteral(false, 'boolean');\n\n // Duration (number with suffix)\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n const num = parseFloat(durationMatch[1]);\n const unit = durationMatch[2];\n if (unit) {\n return createLiteral(value, 'duration');\n }\n return createLiteral(num, 'number');\n }\n\n // Plain number\n const num = parseFloat(value);\n if (!isNaN(num)) {\n return createLiteral(num, 'number');\n }\n\n // Default to string\n return createLiteral(value, 'string');\n}\n\n/**\n * Noise words that can be skipped in English for more natural syntax.\n * - \"the\" before selectors: \"toggle the .active\" → \"toggle .active\"\n * - \"class\" after class selectors: \"add the .visible class\" → \"add .visible\"\n */\nconst ENGLISH_NOISE_WORDS = new Set(['the', 'a', 'an']);\n\n/**\n * Skip noise words like \"the\" before selectors.\n * This enables more natural English syntax like \"toggle the .active\".\n */\nfunction skipNoiseWords(tokens: TokenStream): void {\n const token = tokens.peek();\n if (!token) return;\n\n const tokenLower = safeToLowerCase(token.value);\n\n // Check if current token is a noise word (like \"the\")\n if (ENGLISH_NOISE_WORDS.has(tokenLower)) {\n // Look ahead to see if the next token is a selector\n const mark = tokens.mark();\n tokens.advance();\n const nextToken = tokens.peek();\n\n if (nextToken && nextToken.kind === 'selector') {\n // Keep the position after \"the\" - effectively skipping it\n return;\n }\n\n // Not followed by a selector, revert\n tokens.reset(mark);\n }\n\n // Also handle \"class\" after class selectors: \".visible class\" → \".visible\"\n // This is handled when the selector has already been consumed,\n // so we check if current token is \"class\" and skip it\n if (tokenLower === 'class') {\n // Skip \"class\" as it's just noise after a class selector\n tokens.advance();\n }\n}\n","/**\n * The stock confidence model: how framework's old matcher scored a domain\n * pattern's match (`core/pattern-matching/`), moved here as a `ConfidenceModel`\n * for the matcher's skeleton (domains rethink Phase 4.7); the old matcher calls\n * it too until Phase 6.\n *\n * Role coverage (a required slot 1, an optional one 0.8, an absent optional one\n * with a default 60% of that), a stem-match penalty (up to 15%, floor 0.5), and\n * two Arabic adjustments: a VSO verb-first boost and the preposition each role\n * takes most naturally.\n */\n\nimport type { LanguagePattern, SemanticRole, SemanticValue } from '../types';\nimport type { ConfidenceBreakdown, ConfidenceContext, ConfidenceModel } from './confidence-model';\n\n/**\n * Calculate confidence score for a match (0-1).\n *\n * Confidence is reduced for:\n * - Stem matches (morphological normalization has inherent uncertainty)\n * - Missing optional roles (but less penalty if role has a default value)\n *\n * Confidence is increased for:\n * - VSO languages (Arabic) when pattern starts with a verb\n */\nfunction scoreParts(ctx: ConfidenceContext): ConfidenceBreakdown {\n const { pattern, captured } = ctx;\n let score = 0;\n let maxScore = 0;\n\n // Helper to check if a role has a default value in extraction rules\n const hasDefault = (role: SemanticRole): boolean => {\n return pattern.extraction?.[role]?.default !== undefined;\n };\n\n // Score based on captured roles\n for (const token of pattern.template.tokens) {\n if (token.type === 'role') {\n maxScore += 1;\n if (captured.has(token.role)) {\n score += 1;\n }\n } else if (token.type === 'group') {\n // Group tokens are optional - weight depends on whether they have defaults\n for (const subToken of token.tokens) {\n if (subToken.type === 'role') {\n const roleHasDefault = hasDefault(subToken.role);\n const weight = 0.8; // Optional roles: 80% weight\n maxScore += weight;\n\n if (captured.has(subToken.role)) {\n // Role was explicitly provided by user\n score += weight;\n } else if (roleHasDefault) {\n // Role has a default - give 60% partial credit since command is semantically complete\n // This prevents penalizing common patterns like \"toggle .active\" (default: me)\n score += weight * 0.6;\n }\n // If no default and not captured, score += 0 (true penalty for missing info)\n }\n }\n }\n }\n\n const roleCoverage = maxScore > 0 ? score / maxScore : 1;\n let baseConfidence = roleCoverage;\n let stemPenalty = 0;\n\n // Apply penalty for stem matches\n // Each stem match reduces confidence slightly (e.g., 5% per stem match)\n // This ensures exact matches are preferred over morphological matches\n if (ctx.stemMatchCount > 0 && ctx.totalKeywordMatches > 0) {\n stemPenalty = (ctx.stemMatchCount / ctx.totalKeywordMatches) * 0.15;\n baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);\n }\n\n // Apply VSO confidence boost for Arabic verb-first patterns\n const vsoBoost = calculateVSOConfidenceBoost(pattern);\n baseConfidence = Math.min(1.0, baseConfidence + vsoBoost);\n\n // Apply preposition disambiguation adjustment for Arabic\n const prepositionAdjustment = arabicPrepositionDisambiguation(pattern, captured);\n baseConfidence = Math.max(0.0, Math.min(1.0, baseConfidence + prepositionAdjustment));\n\n return {\n roleCoverage,\n stemPenalty,\n languageBoost: vsoBoost,\n languageAdjustment: prepositionAdjustment,\n final: baseConfidence,\n };\n}\n\n/**\n * Calculate confidence boost for VSO (Verb-Subject-Object) language patterns.\n * Arabic naturally uses VSO word order, so patterns that start with a verb\n * should receive a confidence boost.\n *\n * Returns +0.15 confidence boost if:\n * - Language is Arabic ('ar')\n * - Pattern's first token is a verb keyword\n *\n * @param pattern The language pattern being matched\n * @returns Confidence boost (0 or 0.15)\n */\nfunction calculateVSOConfidenceBoost(pattern: LanguagePattern): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n // Check if first token in pattern is a literal (keyword)\n const firstToken = pattern.template.tokens[0];\n if (!firstToken || firstToken.type !== 'literal') {\n return 0;\n }\n\n // List of Arabic verb keywords (command verbs)\n const ARABIC_VERBS = new Set([\n 'بدل',\n 'غير',\n 'أضف',\n 'أزل',\n 'ضع',\n 'اجعل',\n 'عين',\n 'زد',\n 'انقص',\n 'سجل',\n 'أظهر',\n 'أخف',\n 'شغل',\n 'أرسل',\n 'ركز',\n 'شوش',\n 'توقف',\n 'انسخ',\n 'احذف',\n 'اصنع',\n 'انتظر',\n 'انتقال',\n 'أو',\n ]);\n\n // Check if first token value is a verb\n if (ARABIC_VERBS.has(firstToken.value)) {\n return 0.15;\n }\n\n // Check alternatives\n if (firstToken.alternatives) {\n for (const alt of firstToken.alternatives) {\n if (ARABIC_VERBS.has(alt)) {\n return 0.15;\n }\n }\n }\n\n return 0;\n}\n\n/**\n * Arabic preposition disambiguation for confidence adjustment.\n *\n * Different Arabic prepositions are more or less natural for different semantic roles:\n * - على (on/upon) is preferred for patient/target roles (element selectors)\n * - إلى (to) is preferred for destination roles\n * - من (from) is preferred for source roles\n * - في (in) is preferred for location roles\n *\n * This method analyzes the prepositions used with captured semantic roles and\n * adjusts confidence based on idiomaticity:\n * - +0.10 for highly idiomatic preposition choices\n * - -0.10 for less natural preposition choices\n *\n * @param pattern The language pattern being matched\n * @param captured The captured semantic values\n * @returns Confidence adjustment (-0.10 to +0.10)\n */\nfunction arabicPrepositionDisambiguation(\n pattern: LanguagePattern,\n captured: ReadonlyMap<SemanticRole, SemanticValue>\n): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n let adjustment = 0;\n\n // Preferred prepositions for each semantic role\n // Only including roles that commonly use prepositions in Arabic\n const PREFERRED_PREPOSITIONS: Partial<Record<SemanticRole, string[]>> = {\n patient: ['على'], // element selectors prefer على (on/upon)\n destination: ['إلى', 'الى'], // destination prefers إلى (to)\n source: ['من'], // source prefers من (from)\n agent: ['من'], // agent/by prefers من (from/by)\n manner: ['ب'], // manner prefers ب (with/by)\n style: ['ب'], // style prefers ب (with)\n goal: ['إلى', 'الى'], // target state prefers إلى (to)\n method: ['ب'], // method prefers ب (with/by)\n };\n\n // Check each captured role for preposition metadata\n for (const [role, value] of captured.entries()) {\n // Skip if no preferred prepositions defined for this role\n const preferred = PREFERRED_PREPOSITIONS[role];\n if (!preferred || preferred.length === 0) {\n continue;\n }\n\n // Check if the value has preposition metadata (from Arabic tokenizer)\n // This metadata is attached when a preposition particle token is consumed\n const metadata =\n 'metadata' in value ? (value as { metadata: Record<string, unknown> }).metadata : undefined;\n if (metadata && typeof metadata.prepositionValue === 'string') {\n const usedPreposition = metadata.prepositionValue;\n\n // Check if the used preposition is in the preferred list\n if (preferred.includes(usedPreposition)) {\n // Idiomatic choice - boost confidence\n adjustment += 0.1;\n } else {\n // Less natural choice - reduce confidence\n adjustment -= 0.1;\n }\n }\n }\n\n // Cap total adjustment at ±0.10 (even if multiple roles analyzed)\n return Math.max(-0.1, Math.min(0.1, adjustment));\n}\n\n/** The stock confidence model (stateless: one instance serves every matcher). */\nexport const stockConfidenceModel: ConfidenceModel = {\n calculate: ctx => scoreParts(ctx).final,\n calculateWithBreakdown: ctx => scoreParts(ctx),\n};\n","/**\n * Pattern Matcher\n *\n * Matches tokenized input against language patterns to extract semantic roles.\n * This is the core algorithm for multilingual parsing.\n */\n\nimport type {\n LanguagePattern,\n PatternToken,\n PatternMatchResult,\n SemanticRole,\n SemanticValue,\n TokenStream,\n LanguageToken,\n} from '../types';\nimport { createLogger } from '../logger';\n\n/**\n * Helper to check if a value is a built-in reference.\n * In the generic framework, we don't assume any built-in references.\n * DSLs that need references (like hyperscript's 'me', 'it', 'you') should\n * handle them in their tokenizer or provide a custom reference validator.\n *\n * For generic DSLs, identifiers are treated as expressions by default.\n */\n// A role's value is read by the code the stock reader runs too (core/matching/stock-reading.ts).\nimport { readRoleValue, safeToLowerCase } from '../matching/stock-reading';\nimport { stockConfidenceModel } from '../matching/stock-confidence';\n\n/**\n * Minimal profile interface needed by PatternMatcher.\n * DSLs can provide this to enable possessive handling and language-specific features.\n */\nexport interface PatternMatcherProfile {\n readonly code: string;\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n// =============================================================================\n// Pattern Matcher\n// =============================================================================\n\nexport class PatternMatcher {\n /** Maximum tokens to scan ahead when looking for a group's leading marker */\n private static readonly MAX_MARKER_SCAN = 3;\n\n /** Debug logger */\n private logger = createLogger('pattern-matcher');\n\n /** Current language profile for the pattern being matched */\n private currentProfile: PatternMatcherProfile | undefined;\n\n /**\n * Try to match a single pattern against the token stream.\n * Returns the match result or null if no match.\n *\n * @param tokens - Token stream to match against\n * @param pattern - Pattern to match\n * @param profile - Optional language profile for possessive handling\n */\n matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern,\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const mark = tokens.mark();\n const captured = new Map<SemanticRole, SemanticValue>();\n\n // Debug logging\n this.logger.debug('========================================');\n this.logger.debug('matchPattern ENTRY');\n this.logger.debug('Pattern ID:', pattern.id);\n this.logger.debug('Pattern command:', pattern.command);\n this.logger.debug('Pattern language:', pattern.language);\n this.logger.debug('Pattern template:', JSON.stringify(pattern.template, null, 2));\n\n if (this.logger.isEnabled()) {\n const firstTokens = [];\n for (let i = 0; i < 10; i++) {\n const t = tokens.peek(i);\n if (t)\n firstTokens.push({\n type: (t as any).type,\n value: (t as any).value,\n kind: (t as any).kind,\n });\n else break;\n }\n this.logger.debug('Input tokens (first 10):', firstTokens);\n this.logger.debug('Profile code:', profile?.code);\n }\n\n // Use provided profile for possessive keyword lookup\n this.currentProfile = profile;\n\n // Reset match counters for this pattern\n this.stemMatchCount = 0;\n this.totalKeywordMatches = 0;\n\n this.logger.debug('--- Calling matchTokenSequence ---');\n this.logger.debug('Pattern tokens to match:', JSON.stringify(pattern.template.tokens, null, 2));\n const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);\n this.logger.debug('matchTokenSequence returned:', success);\n this.logger.debug(\n 'Captured roles:',\n Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])\n );\n\n if (!success) {\n this.logger.debug('>>> MATCH FAILED - resetting token position');\n tokens.reset(mark);\n return null;\n }\n\n // Calculate confidence BEFORE applying defaults\n // This ensures defaulted roles don't artificially inflate confidence\n const confidence = stockConfidenceModel.calculate({\n pattern,\n captured,\n stemMatchCount: this.stemMatchCount,\n totalKeywordMatches: this.totalKeywordMatches,\n });\n\n // Apply extraction rules to fill in any missing roles with defaults\n this.applyExtractionRules(pattern, captured);\n\n return {\n pattern,\n captured,\n consumedTokens: tokens.position() - mark.position,\n confidence,\n };\n }\n\n /**\n * Try to match multiple patterns, return the best match.\n *\n * @param tokens - Token stream to match against\n * @param patterns - Candidate patterns to try\n * @param profile - Optional language profile for possessive handling\n */\n matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[],\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const matches: PatternMatchResult[] = [];\n\n for (const pattern of patterns) {\n const mark = tokens.mark();\n const result = this.matchPattern(tokens, pattern, profile);\n\n if (result) {\n matches.push(result);\n }\n\n tokens.reset(mark);\n }\n\n if (matches.length === 0) {\n return null;\n }\n\n // Sort by confidence and priority\n matches.sort((a, b) => {\n // First by priority\n const priorityDiff = b.pattern.priority - a.pattern.priority;\n if (priorityDiff !== 0) return priorityDiff;\n\n // Then by confidence\n const confidenceDiff = b.confidence - a.confidence;\n if (Math.abs(confidenceDiff) > 0.001) return confidenceDiff;\n\n // Then by tokens consumed (prefer more complete matches)\n return b.consumedTokens - a.consumedTokens;\n });\n\n // Re-consume tokens for the best match\n const best = matches[0];\n this.matchPattern(tokens, best.pattern);\n\n return best;\n }\n\n /**\n * Match a sequence of pattern tokens against the token stream.\n *\n * Supports bounded single-step backtracking: if an optional role consumes\n * a token and the immediately following pattern token fails, the matcher\n * resets to before the optional role and retries the failed token.\n */\n private matchTokenSequence(\n tokens: TokenStream,\n patternTokens: PatternToken[],\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n // Skip leading conjunctions for Arabic (proclitics: و, ف, ول, وب, etc.)\n // BUT NOT if the pattern explicitly expects a conjunction (proclitic patterns)\n const firstPatternToken = patternTokens[0];\n const patternExpectsConjunction =\n firstPatternToken?.type === 'literal' &&\n (firstPatternToken.value === 'and' ||\n firstPatternToken.value === 'then' ||\n firstPatternToken.alternatives?.includes('and') ||\n firstPatternToken.alternatives?.includes('then'));\n\n if (this.currentProfile?.code === 'ar' && !patternExpectsConjunction) {\n while (tokens.peek()?.kind === 'conjunction') {\n tokens.advance();\n }\n }\n\n // Backtracking state: track the most recent optional role that consumed a token\n let prevOptionalMark: ReturnType<TokenStream['mark']> | null = null;\n let prevOptionalRole: SemanticRole | null = null;\n\n for (let i = 0; i < patternTokens.length; i++) {\n const patternToken = patternTokens[i];\n this.logger.debug(' >> Matching pattern token:', JSON.stringify(patternToken, null, 2));\n const currTok = tokens.peek();\n this.logger.debug(\n ' >> Current input token:',\n currTok\n ? JSON.stringify({\n type: (currTok as any).type,\n value: (currTok as any).value,\n kind: (currTok as any).kind,\n })\n : 'EOF'\n );\n\n // Greedy role capture: consume all remaining tokens until the next\n // recognized marker keyword or end of input\n if (patternToken.type === 'role' && patternToken.greedy) {\n const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n // Merge parent-level stop markers so greedy roles inside groups\n // know when to stop for tokens outside the group (e.g., SOV verb keywords)\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) stopMarkers.add(m);\n }\n const values: string[] = [];\n while (!tokens.isAtEnd()) {\n const nextToken = tokens.peek();\n if (!nextToken) break;\n if (this.isStopMarker(nextToken, stopMarkers)) break;\n values.push(nextToken.value);\n tokens.advance();\n }\n if (values.length > 0) {\n captured.set(patternToken.role, { type: 'expression', raw: values.join(' ') });\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n } else if (patternToken.optional) {\n continue;\n } else {\n return false;\n }\n }\n\n // Group tokens: compute sibling stop markers and forward to inner matching\n if (patternToken.type === 'group') {\n const siblingStopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) siblingStopMarkers.add(m);\n }\n const groupMatched = this.matchGroupToken(\n tokens,\n patternToken as PatternToken & { type: 'group' },\n captured,\n siblingStopMarkers\n );\n if (groupMatched) {\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n }\n if (this.isOptional(patternToken)) {\n continue;\n }\n return false;\n }\n\n // Save stream position before attempting optional roles\n const isOptionalRole = patternToken.type === 'role' && patternToken.optional === true;\n const markBefore = isOptionalRole ? tokens.mark() : null;\n\n // SOV marker-stealing guard: before matching a required role, check if\n // the current input token would match the immediately-following pattern\n // literal (the role's own postpositional marker). If so, skip consuming\n // this token as a role value — it should be matched as the literal instead.\n const isRoleToken = patternToken.type === 'role';\n if (isRoleToken && !isOptionalRole) {\n const nextPT = i + 1 < patternTokens.length ? patternTokens[i + 1] : null;\n if (nextPT?.type === 'literal') {\n const currentToken = tokens.peek();\n if (currentToken && this.getMatchType(currentToken, nextPT.value) !== 'none') {\n // Current token is the marker literal, not a role value — treat role as failed\n this.logger.debug(\n ' >> MARKER-STEAL GUARD: current token matches next literal, skipping role'\n );\n // Fall through to failure handling below\n // (which will trigger backtracking of previous optional role)\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n }\n }\n\n const matched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Match result:', matched);\n\n if (matched) {\n if (isOptionalRole) {\n // Track this consumption so we can undo it if the next token fails\n prevOptionalMark = markBefore;\n prevOptionalRole = patternToken.role;\n } else {\n // Non-optional succeeded — clear backtrack state\n prevOptionalMark = null;\n prevOptionalRole = null;\n }\n continue;\n }\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Match a single pattern token against the current position in the stream.\n */\n private matchPatternToken(\n tokens: TokenStream,\n patternToken: PatternToken,\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n switch (patternToken.type) {\n case 'literal':\n return this.matchLiteralToken(tokens, patternToken);\n\n case 'role':\n return readRoleValue(tokens, patternToken, captured, this.currentProfile);\n\n case 'group':\n return this.matchGroupToken(tokens, patternToken, captured);\n\n default:\n return false;\n }\n }\n\n /**\n * Match a literal pattern token (keyword or particle).\n */\n private matchLiteralToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'literal' }\n ): boolean {\n const token = tokens.peek();\n this.logger.debug(' >>> matchLiteralToken: expecting', patternToken.value);\n this.logger.debug(\n ' >>> matchLiteralToken: got token',\n token\n ? JSON.stringify({\n type: (token as any).type,\n value: (token as any).value,\n kind: (token as any).kind,\n })\n : 'null'\n );\n if (!token) {\n this.logger.debug(' >>> matchLiteralToken: FAIL - no token');\n return false;\n }\n\n // Check main value\n const matchType = this.getMatchType(token, patternToken.value);\n this.logger.debug(\n ' >>> matchType for',\n token.value,\n 'vs',\n patternToken.value,\n ':',\n matchType\n );\n if (matchType !== 'none') {\n this.totalKeywordMatches++;\n if (matchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n\n // Check alternatives\n if (patternToken.alternatives) {\n for (const alt of patternToken.alternatives) {\n const altMatchType = this.getMatchType(token, alt);\n if (altMatchType !== 'none') {\n this.totalKeywordMatches++;\n if (altMatchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Match a group pattern token (optional sequence).\n * When the group's leading marker isn't at the current position, scans ahead\n * up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens\n * (e.g., a value like 'hello') to sit between groups without blocking later\n * marker matches.\n */\n private matchGroupToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'group' },\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n const mark = tokens.mark();\n const capturedBefore = new Set(captured.keys());\n\n const success = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (success) return true;\n\n // Reset from failed attempt\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n\n if (!patternToken.optional) return false;\n\n // Marker scan: look ahead for the group's leading marker past intervening tokens.\n // This handles cases like \"types 'hello' into #search\" where 'hello' blocks the\n // 'into' marker from being found at the current position.\n const leadingMarker = this.getGroupLeadingMarker(patternToken);\n if (leadingMarker) {\n for (let offset = 1; offset <= PatternMatcher.MAX_MARKER_SCAN; offset++) {\n const ahead = tokens.peek(offset);\n if (!ahead) break;\n const aheadValue = (ahead.normalized || ahead.value).toLowerCase();\n if (aheadValue === leadingMarker) {\n this.logger.debug(\n ' >> MARKER SCAN: found',\n leadingMarker,\n 'at offset',\n offset,\n '- skipping intervening tokens'\n );\n // Advance past intervening tokens to reach the marker\n for (let s = 0; s < offset; s++) tokens.advance();\n\n // Retry group match from marker position\n const retrySuccess = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (retrySuccess) return true;\n\n // Retry failed — full reset\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n break;\n }\n }\n }\n\n return true; // Optional group, just skip\n }\n\n /**\n * Get the leading marker literal from an optional group.\n * Returns the lowercase marker value, or null if the group\n * doesn't start with a literal token (e.g., SOV groups where\n * the role comes before the marker).\n */\n private getGroupLeadingMarker(group: PatternToken & { type: 'group' }): string | null {\n const first = group.tokens[0];\n if (first?.type === 'literal') return first.value.toLowerCase();\n return null;\n }\n\n /**\n * Get the type of match for a token against a value.\n * Used for confidence calculation.\n */\n private getMatchType(\n token: LanguageToken,\n value: string\n ): 'exact' | 'normalized' | 'stem' | 'case-insensitive' | 'none' {\n // Exact match (highest confidence)\n if (token.value === value) return 'exact';\n\n // Explicit keyword map normalized match (high confidence)\n if (token.normalized === value) return 'normalized';\n\n // Morphologically normalized stem match (medium-high confidence)\n // Only accept if stem confidence is reasonable\n if (token.stem === value && token.stemConfidence !== undefined && token.stemConfidence >= 0.7) {\n return 'stem';\n }\n\n // Case-insensitive match for keywords (medium confidence)\n if (token.kind === 'keyword' && safeToLowerCase(token.value) === value.toLowerCase()) {\n return 'case-insensitive';\n }\n\n return 'none';\n }\n\n /**\n * Collect literal values from upcoming pattern tokens that act as stop markers\n * for greedy role capture. Returns the set of lowercase values.\n */\n private collectStopMarkers(patternTokens: PatternToken[], startIndex: number): Set<string> {\n const markers = new Set<string>();\n for (let j = startIndex; j < patternTokens.length; j++) {\n const pt = patternTokens[j];\n if (pt.type === 'literal') {\n markers.add(pt.value.toLowerCase());\n if (pt.alternatives) {\n for (const alt of pt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n if (pt.type === 'group') {\n for (const gt of pt.tokens) {\n if (gt.type === 'literal') {\n markers.add(gt.value.toLowerCase());\n if (gt.alternatives) {\n for (const alt of gt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n }\n // For optional groups, continue scanning past them so the greedy\n // capture also sees subsequent required literals (e.g., the SOV verb\n // keyword after an optional WHERE group).\n if (!pt.optional) break;\n }\n }\n return markers;\n }\n\n /**\n * Check if a token matches any stop marker for greedy capture.\n */\n private isStopMarker(token: LanguageToken, stopMarkers: Set<string>): boolean {\n if (stopMarkers.size === 0) return false;\n // Check both raw value and normalized form against stop markers.\n // Pattern literals use native keywords (e.g., '選択') while tokenizers may\n // set normalized to the English equivalent (e.g., 'select'). Both must match.\n if (stopMarkers.has(token.value.toLowerCase())) return true;\n if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;\n return false;\n }\n\n /**\n * Track stem matches for confidence calculation.\n * This is set during matching and read during confidence calculation.\n */\n private stemMatchCount: number = 0;\n private totalKeywordMatches: number = 0;\n\n // ==========================================================================\n // Depth Limits for Expression Parsing (security hardening)\n // ==========================================================================\n\n /**\n * Apply extraction rules to fill in static values and defaults for missing roles.\n */\n private applyExtractionRules(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): void {\n for (const [role, rule] of Object.entries(pattern.extraction)) {\n if (!captured.has(role as SemanticRole)) {\n if (rule.value !== undefined) {\n // Static value extraction (e.g., action: { value: \"toggle\" })\n captured.set(role as SemanticRole, { type: 'literal', value: rule.value });\n } else if (rule.default) {\n captured.set(role as SemanticRole, rule.default);\n }\n }\n }\n }\n\n /**\n * Check if a pattern token is optional.\n */\n private isOptional(patternToken: PatternToken): boolean {\n return patternToken.type !== 'literal' && patternToken.optional === true;\n }\n\n // ===========================================================================\n // English Idiom Support - Noise Word Handling\n // ===========================================================================\n\n /**\n * Extract event modifiers from the token stream.\n * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n * that can appear after event names.\n *\n * Returns EventModifiers object or undefined if no modifiers found.\n */\n extractEventModifiers(tokens: TokenStream): import('../types').EventModifiers | undefined {\n const modifiers: {\n once?: boolean;\n debounce?: number;\n throttle?: number;\n queue?: 'first' | 'last' | 'all' | 'none';\n from?: SemanticValue;\n } = {};\n\n let foundModifier = false;\n\n // Consume all consecutive event modifier tokens\n while (!tokens.isAtEnd()) {\n const token = tokens.peek();\n if (!token || token.kind !== 'event-modifier') {\n break;\n }\n\n const metadata = token.metadata as\n { modifierName: string; value?: number | string } | undefined;\n if (!metadata) {\n break;\n }\n\n foundModifier = true;\n\n switch (metadata.modifierName) {\n case 'once':\n modifiers.once = true;\n break;\n case 'debounce':\n if (typeof metadata.value === 'number') {\n modifiers.debounce = metadata.value;\n }\n break;\n case 'throttle':\n if (typeof metadata.value === 'number') {\n modifiers.throttle = metadata.value;\n }\n break;\n case 'queue':\n if (\n metadata.value === 'first' ||\n metadata.value === 'last' ||\n metadata.value === 'all' ||\n metadata.value === 'none'\n ) {\n modifiers.queue = metadata.value;\n }\n break;\n }\n\n tokens.advance();\n }\n\n return foundModifier ? modifiers : undefined;\n }\n}\n\n// =============================================================================\n// Convenience Functions\n// =============================================================================\n\n/**\n * Singleton pattern matcher instance.\n */\nexport const patternMatcher = new PatternMatcher();\n\n/**\n * Match tokens against a pattern.\n */\nexport function matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern\n): PatternMatchResult | null {\n return patternMatcher.matchPattern(tokens, pattern);\n}\n\n/**\n * Match tokens against multiple patterns, return best match.\n */\nexport function matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[]\n): PatternMatchResult | null {\n return patternMatcher.matchBest(tokens, patterns);\n}\n","/**\n * Multi-statement parser for domain DSLs.\n *\n * Provides generic mechanics for parsing multi-line/multi-statement DSL input:\n * - Statement splitting (line-based or delimiter-based)\n * - Keyword classification (SVO start / SOV end detection)\n * - Block accumulation (grouping lines into blocks)\n * - Error collection with line numbers\n *\n * Domains provide the semantics (what keywords mean, preprocessing, hierarchy).\n * The framework provides the mechanics.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL } from '../api/create-dsl';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * Word order affects keyword detection position.\n */\nexport type WordOrderHint = 'SVO' | 'SOV' | 'VSO';\n\n/**\n * How to split input into individual statements.\n */\nexport interface SplitConfig {\n /**\n * Split mode:\n * - 'line': split on newlines (for indentation-based DSLs)\n * - 'delimiter': split on language-specific delimiters\n */\n readonly mode: 'line' | 'delimiter';\n\n /**\n * Language-specific delimiter patterns (used when mode='delimiter').\n * Key is language code, value is regex pattern.\n * Example: { en: /,\\s*|\\n\\s*‍/, ja: /、|。|\\n\\s*‍/ }\n */\n readonly delimiters?: Readonly<Record<string, RegExp>>;\n\n /**\n * Default delimiter when language not in delimiters map.\n */\n readonly defaultDelimiter?: RegExp;\n\n /**\n * Whether to trim each statement after splitting.\n * Default: true\n */\n readonly trim?: boolean;\n\n /**\n * Comment prefixes to strip. Lines starting with these are skipped.\n * Default: ['--', '//']\n */\n readonly commentPrefixes?: readonly string[];\n}\n\n/**\n * A keyword category with its translations.\n * Maps language code to array of keyword variants.\n */\nexport type KeywordMap = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Configuration for keyword classification.\n */\nexport interface KeywordConfig {\n /**\n * Named keyword categories with their per-language translations.\n * Example: { test: { en: ['test'], ja: ['テスト'], es: ['prueba'] } }\n */\n readonly categories: Readonly<Record<string, KeywordMap>>;\n\n /**\n * Word order hint per language (affects where keywords are detected).\n * Default for unlisted languages: 'SVO'\n */\n readonly wordOrders?: Readonly<Record<string, WordOrderHint>>;\n}\n\n/**\n * Configuration for continuation resolution (e.g., BDD's \"and\" keyword).\n */\nexport interface ContinuationConfig {\n /**\n * The keyword(s) that signal continuation, per language.\n * Example: { en: ['and'], es: ['y'], ja: ['かつ'], ar: ['و'] }\n */\n readonly keywords: KeywordMap;\n\n /**\n * How to resolve continuation: re-prefix with previous step's keyword.\n * The function receives (content after 'and', previous step's category, language)\n * and returns the re-prefixed string for re-parsing.\n *\n * Default: `(content, prevCategory, language, categoryKeywords) =>\n * categoryKeywords[prevCategory]?.[language]?.[0] + ' ' + content`\n */\n readonly resolve?: (\n content: string,\n prevCategory: string,\n language: string,\n categoryKeywords: Record<string, KeywordMap>\n ) => string;\n}\n\n/**\n * A parsed statement with its line context.\n */\nexport interface ParsedStatement {\n /** The parsed semantic node */\n readonly node: SemanticNode;\n /** Original source line/text */\n readonly source: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Detected keyword category (e.g., 'test', 'given', 'when') */\n readonly category?: string;\n /** Indentation level (number of leading spaces, 0-based) */\n readonly indent: number;\n}\n\n/**\n * A parse error with location information.\n */\nexport interface StatementError {\n /** Error message */\n readonly message: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Original source line/text */\n readonly source: string;\n /** Error code for programmatic handling */\n readonly code?: 'parse-error' | 'unexpected-line' | 'continuation-error';\n}\n\n/**\n * Result of multi-statement parsing.\n */\nexport interface MultiStatementResult {\n /** Successfully parsed statements */\n readonly statements: readonly ParsedStatement[];\n /** Errors encountered during parsing */\n readonly errors: readonly StatementError[];\n}\n\n/**\n * Preprocessor function called before each statement is parsed.\n * Returns the modified string to parse, or null to skip the line.\n */\nexport type StatementPreprocessor = (\n line: string,\n category: string | undefined,\n language: string,\n context: PreprocessorContext\n) => string | null;\n\n/**\n * Context available to preprocessors.\n */\nexport interface PreprocessorContext {\n /** The previous parsed statement, if any */\n readonly previous?: ParsedStatement;\n /** Line number (1-based) */\n readonly lineNumber: number;\n /** Indentation level */\n readonly indent: number;\n}\n\n/**\n * Full configuration for multi-statement parser.\n */\nexport interface MultiStatementConfig {\n /** How to split input into statements */\n readonly split: SplitConfig;\n /** Keyword classification (optional — if omitted, no category detection) */\n readonly keywords?: KeywordConfig;\n /** Continuation resolution (optional — e.g., BDD 'and') */\n readonly continuation?: ContinuationConfig;\n /** Statement preprocessor (optional — for article stripping, expect-prepending, etc.) */\n readonly preprocessor?: StatementPreprocessor;\n}\n\n// =============================================================================\n// Multi-Statement Parser\n// =============================================================================\n\n/**\n * A reusable multi-statement parser.\n * Created via `createMultiStatementParser()`.\n */\nexport interface MultiStatementParser {\n /**\n * Parse multi-statement input into an array of parsed statements.\n */\n parse(input: string, language: string): MultiStatementResult;\n}\n\n/**\n * Create a multi-statement parser that wraps a `MultilingualDSL` instance.\n *\n * The parser handles splitting, keyword detection, continuation resolution,\n * preprocessing, and error collection. It delegates single-statement parsing\n * to the provided DSL's `parse()` method.\n *\n * @example\n * ```typescript\n * const parser = createMultiStatementParser(myDSL, {\n * split: { mode: 'line', commentPrefixes: ['--', '//'] },\n * keywords: {\n * categories: {\n * given: { en: ['given'], ja: ['前提'], es: ['dado'] },\n * when: { en: ['when'], ja: ['もし'], es: ['cuando'] },\n * then: { en: ['then'], ja: ['ならば'], es: ['entonces'] },\n * },\n * wordOrders: { ja: 'SOV', ar: 'VSO' },\n * },\n * continuation: {\n * keywords: { en: ['and'], es: ['y'], ja: ['かつ'] },\n * },\n * });\n *\n * const result = parser.parse(`\n * given #login is visible\n * when click on #submit\n * then #dashboard appears\n * `, 'en');\n * ```\n */\nexport function createMultiStatementParser(\n dsl: MultilingualDSL,\n config: MultiStatementConfig\n): MultiStatementParser {\n return new MultiStatementParserImpl(dsl, config);\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\nclass MultiStatementParserImpl implements MultiStatementParser {\n constructor(\n private readonly dsl: MultilingualDSL,\n private readonly config: MultiStatementConfig\n ) {}\n\n parse(input: string, language: string): MultiStatementResult {\n const rawStatements = this.splitStatements(input, language);\n const statements: ParsedStatement[] = [];\n const errors: StatementError[] = [];\n let previous: ParsedStatement | undefined;\n\n for (const raw of rawStatements) {\n // Detect keyword category\n const category = this.classifyLine(raw.text, language);\n\n // Handle continuation (e.g., 'and')\n let textToParse = raw.text;\n if (this.config.continuation) {\n const resolved = this.resolveContinuation(raw.text, language, previous?.category);\n if (resolved !== null) {\n textToParse = resolved;\n }\n }\n\n // Run preprocessor\n if (this.config.preprocessor) {\n const processed = this.config.preprocessor(textToParse, category, language, {\n ...(previous != null && { previous }),\n lineNumber: raw.line,\n indent: raw.indent,\n });\n if (processed === null) continue; // skip line\n textToParse = processed;\n }\n\n // Parse with DSL\n try {\n const node = this.dsl.parse(textToParse, language);\n const stmt: ParsedStatement = {\n node,\n source: raw.text,\n line: raw.line,\n ...(category != null && { category }),\n indent: raw.indent,\n };\n statements.push(stmt);\n previous = stmt;\n } catch (err) {\n errors.push({\n message: err instanceof Error ? err.message : String(err),\n line: raw.line,\n source: raw.text,\n code: 'parse-error',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Split input into raw statement lines with metadata.\n */\n private splitStatements(\n input: string,\n language: string\n ): Array<{ text: string; line: number; indent: number }> {\n const { mode, trim = true, commentPrefixes = ['--', '//'] } = this.config.split;\n\n if (mode === 'delimiter') {\n return this.splitByDelimiter(input, language, trim, commentPrefixes);\n }\n\n // Line-based splitting\n const lines = input.split('\\n');\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i];\n const indent = raw.length - raw.trimStart().length;\n const text = trim ? raw.trim() : raw;\n\n // Skip empty lines\n if (!text) continue;\n\n // Skip comments\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent });\n }\n\n return result;\n }\n\n /**\n * Split by language-specific delimiters.\n */\n private splitByDelimiter(\n input: string,\n language: string,\n trim: boolean,\n commentPrefixes: readonly string[]\n ): Array<{ text: string; line: number; indent: number }> {\n const delimiter =\n this.config.split.delimiters?.[language] ??\n this.config.split.defaultDelimiter ??\n /,\\s*|\\n\\s*/;\n\n const parts = input.split(delimiter);\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < parts.length; i++) {\n const raw = parts[i];\n const text = trim ? raw.trim() : raw;\n\n if (!text) continue;\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent: 0 });\n }\n\n return result;\n }\n\n /**\n * Classify a line by its keyword category.\n * Returns the category name or undefined if no match.\n */\n private classifyLine(line: string, language: string): string | undefined {\n if (!this.config.keywords) return undefined;\n\n const lower = line.toLowerCase();\n const wordOrder = this.config.keywords.wordOrders?.[language] ?? 'SVO';\n\n for (const [category, keywordMap] of Object.entries(this.config.keywords.categories)) {\n const keywords = keywordMap[language] ?? keywordMap['en'] ?? [];\n for (const kw of keywords) {\n const kwLower = kw.toLowerCase();\n if (wordOrder === 'SOV') {\n // SOV: check end of line first, then start\n if (lower.endsWith(kwLower) || lower.startsWith(kwLower)) {\n return category;\n }\n } else {\n // SVO/VSO: check start of line\n if (lower.startsWith(kwLower)) {\n return category;\n }\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Resolve continuation keywords (e.g., 'and' → re-prefix with previous step type).\n * Returns the resolved string, or null if not a continuation.\n */\n private resolveContinuation(\n text: string,\n language: string,\n prevCategory: string | undefined\n ): string | null {\n if (!this.config.continuation || !prevCategory) return null;\n\n const contKeywords =\n this.config.continuation.keywords[language] ?? this.config.continuation.keywords['en'] ?? [];\n\n const lower = text.toLowerCase();\n for (const kw of contKeywords) {\n const kwLower = kw.toLowerCase();\n if (lower.startsWith(kwLower)) {\n const content = text.slice(kw.length).trim();\n if (!content) return null;\n\n if (this.config.continuation.resolve) {\n return this.config.continuation.resolve(\n content,\n prevCategory,\n language,\n this.config.keywords?.categories ?? {}\n );\n }\n\n // Default: prepend previous category's keyword\n const prevKeywords =\n this.config.keywords?.categories[prevCategory]?.[language] ??\n this.config.keywords?.categories[prevCategory]?.['en'];\n if (prevKeywords?.[0]) {\n return prevKeywords[0] + ' ' + content;\n }\n\n return null;\n }\n }\n\n return null;\n }\n}\n\n// =============================================================================\n// Block Accumulator (for grouped/nested structures)\n// =============================================================================\n\n/**\n * A block of accumulated statements, grouped by a block-opening keyword.\n */\nexport interface StatementBlock<TMeta = unknown> {\n /** Block type (e.g., 'test', 'feature', 'scenario') */\n readonly type: string;\n /** Block name, if any (e.g., test name from quotes) */\n readonly name?: string;\n /** Statements within this block */\n readonly statements: readonly ParsedStatement[];\n /** Child blocks (for nested structures) */\n readonly children: readonly StatementBlock<TMeta>[];\n /** Starting line number */\n readonly line: number;\n /** Indentation level of the block opener */\n readonly indent: number;\n /** Domain-specific metadata */\n readonly meta?: TMeta;\n}\n\n/**\n * Configuration for block accumulation.\n */\nexport interface BlockConfig {\n /**\n * Block-opening keyword categories.\n * Statements classified in these categories start new blocks.\n */\n readonly blockTypes: readonly string[];\n\n /**\n * How to determine block nesting:\n * - 'indent': indentation-based (deeper indent = child block)\n * - 'flat': all blocks at same level (no nesting)\n */\n readonly nesting: 'indent' | 'flat';\n\n /**\n * Extract block name from statement text.\n * Default: extracts quoted string after keyword (e.g., test \"Login\" → \"Login\")\n */\n readonly extractName?: (text: string, category: string) => string | undefined;\n}\n\n/**\n * Result of block accumulation.\n */\nexport interface BlockResult<TMeta = unknown> {\n /** Top-level blocks */\n readonly blocks: readonly StatementBlock<TMeta>[];\n /** Statements not inside any block */\n readonly orphans: readonly ParsedStatement[];\n}\n\n/**\n * Accumulate parsed statements into blocks based on keyword categories.\n *\n * This groups statements into hierarchical blocks based on block-opening keywords\n * and indentation levels. Useful for test/feature/scenario structures.\n *\n * @example\n * ```typescript\n * const result = accumulateBlocks(statements, {\n * blockTypes: ['test', 'feature', 'setup'],\n * nesting: 'indent',\n * extractName: (text, category) => {\n * const match = text.match(/\"([^\"]+)\"/);\n * return match?.[1];\n * },\n * });\n * ```\n */\nexport function accumulateBlocks<TMeta = unknown>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n if (config.nesting === 'flat') {\n return accumulateFlat(statements, config);\n }\n return accumulateIndented(statements, config);\n}\n\nfunction accumulateFlat<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const blocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n let current: {\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n line: number;\n indent: number;\n } | null = null;\n\n const flush = () => {\n if (current) {\n blocks.push({\n type: current.type,\n ...(current.name != null && { name: current.name }),\n statements: current.stmts,\n children: [],\n line: current.line,\n indent: current.indent,\n });\n current = null;\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n flush();\n const name = config.extractName?.(stmt.source, stmt.category);\n current = {\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n line: stmt.line,\n indent: stmt.indent,\n };\n } else if (current) {\n current.stmts.push(stmt);\n } else {\n orphans.push(stmt);\n }\n }\n\n flush();\n return { blocks, orphans };\n}\n\nfunction accumulateIndented<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const rootBlocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n\n // Stack of open blocks with their indent level\n const stack: Array<{\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n children: StatementBlock<TMeta>[];\n line: number;\n indent: number;\n }> = [];\n\n const flushTo = (targetIndent: number) => {\n while (stack.length > 0) {\n const top = stack[stack.length - 1];\n if (top.indent >= targetIndent) {\n stack.pop();\n const block: StatementBlock<TMeta> = {\n type: top.type,\n ...(top.name != null && { name: top.name }),\n statements: top.stmts,\n children: top.children,\n line: top.line,\n indent: top.indent,\n };\n if (stack.length > 0) {\n stack[stack.length - 1].children.push(block);\n } else {\n rootBlocks.push(block);\n }\n } else {\n break;\n }\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n // Flush blocks at same or deeper indent\n flushTo(stmt.indent);\n const name = config.extractName?.(stmt.source, stmt.category);\n stack.push({\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n children: [],\n line: stmt.line,\n indent: stmt.indent,\n });\n } else if (stack.length > 0) {\n stack[stack.length - 1].stmts.push(stmt);\n } else {\n orphans.push(stmt);\n }\n }\n\n // Flush remaining\n flushTo(-1);\n\n return { blocks: rootBlocks, orphans };\n}\n"],"mappings":";AAiBA,IAAM,cAAN,MAAkB;AAAA,EAIhB,YAAY,WAAmB;AAC7B,SAAK,YAAY;AACjB,SAAK,UAAU,KAAK,aAAa;AAAA,EACnC;AAAA,EAEQ,eAAwB;AAE9B,QAAI,OAAO,YAAY,eAAe,QAAQ,KAAK;AACjD,YAAM,QAAQ,QAAQ,IAAI,SAAS;AAEnC,aACE,UAAU,OACV,MAAM,SAAS,aAAa,KAC5B,MAAM,SAAS,aAAa,KAAK,SAAS,EAAE;AAAA,IAEhD;AACA,WAAO;AAAA,EACT;AAAA,EAEQ,IAAI,OAAiB,YAAoB,MAAmB;AAClE,QAAI,CAAC,KAAK,QAAS;AAEnB,UAAM,SAAS,cAAc,KAAK,SAAS;AAC3C,UAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAEzC,YAAQ,OAAO;AAAA,MACb,KAAK;AAEH,gBAAQ,MAAM,GAAG,SAAS,IAAI,MAAM,WAAW,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AM,QAA+B;AAAA,UACnC,MAAM,IAAI;AAAA,UACV,GAAI,IAAI,QAAQ,QAAQ,EAAE,MAAM,IAAI,KAAK;AAAA,UACzC,YAAY,IAAI;AAAA,UAChB,UAAU,IAAI;AAAA,UACd,MAAM,IAAI;AAAA,UACV,QAAQ,IAAI;AAAA,QACd;AACA,YAAI,MAAM,SAAS,GAAG;AACpB,gBAAM,MAAM,SAAS,CAAC,EAAE,SAAS,KAAK,KAAK;AAAA,QAC7C,OAAO;AACL,qBAAW,KAAK,KAAK;AAAA,QACvB;AAAA,MACF,OAAO;AACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,aAAW,QAAQ,YAAY;AAC7B,QAAI,KAAK,YAAY,OAAO,WAAW,SAAS,KAAK,QAAQ,GAAG;AAE9D,cAAQ,KAAK,MAAM;AACnB,YAAM,OAAO,OAAO,cAAc,KAAK,QAAQ,KAAK,QAAQ;AAC5D,YAAM,KAAK;AAAA,QACT,MAAM,KAAK;AAAA,QACX,GAAI,QAAQ,QAAQ,EAAE,KAAK;AAAA,QAC3B,OAAO,CAAC,IAAI;AAAA,QACZ,UAAU,CAAC;AAAA,QACX,MAAM,KAAK;AAAA,QACX,QAAQ,KAAK;AAAA,MACf,CAAC;AAAA,IACH,WAAW,MAAM,SAAS,GAAG;AAC3B,YAAM,MAAM,SAAS,CAAC,EAAE,MAAM,KAAK,IAAI;AAAA,IACzC,OAAO;AACL,cAAQ,KAAK,IAAI;AAAA,IACnB;AAAA,EACF;AAGA,UAAQ,EAAE;AAEV,SAAO,EAAE,QAAQ,YAAY,QAAQ;AACvC;","names":["num"]}
1
+ {"version":3,"sources":["../../src/parsing/multi-statement.ts"],"sourcesContent":["/**\n * Multi-statement parser for domain DSLs.\n *\n * Provides generic mechanics for parsing multi-line/multi-statement DSL input:\n * - Statement splitting (line-based or delimiter-based)\n * - Keyword classification (SVO start / SOV end detection)\n * - Block accumulation (grouping lines into blocks)\n * - Error collection with line numbers\n *\n * Domains provide the semantics (what keywords mean, preprocessing, hierarchy).\n * The framework provides the mechanics.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL } from '../api/create-dsl';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * Word order affects keyword detection position.\n */\nexport type WordOrderHint = 'SVO' | 'SOV' | 'VSO';\n\n/**\n * How to split input into individual statements.\n */\nexport interface SplitConfig {\n /**\n * Split mode:\n * - 'line': split on newlines (for indentation-based DSLs)\n * - 'delimiter': split on language-specific delimiters\n */\n readonly mode: 'line' | 'delimiter';\n\n /**\n * Language-specific delimiter patterns (used when mode='delimiter').\n * Key is language code, value is regex pattern.\n * Example: { en: /,\\s*|\\n\\s*‍/, ja: /、|。|\\n\\s*‍/ }\n */\n readonly delimiters?: Readonly<Record<string, RegExp>>;\n\n /**\n * Default delimiter when language not in delimiters map.\n */\n readonly defaultDelimiter?: RegExp;\n\n /**\n * Whether to trim each statement after splitting.\n * Default: true\n */\n readonly trim?: boolean;\n\n /**\n * Comment prefixes to strip. Lines starting with these are skipped.\n * Default: ['--', '//']\n */\n readonly commentPrefixes?: readonly string[];\n}\n\n/**\n * A keyword category with its translations.\n * Maps language code to array of keyword variants.\n */\nexport type KeywordMap = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Configuration for keyword classification.\n */\nexport interface KeywordConfig {\n /**\n * Named keyword categories with their per-language translations.\n * Example: { test: { en: ['test'], ja: ['テスト'], es: ['prueba'] } }\n */\n readonly categories: Readonly<Record<string, KeywordMap>>;\n\n /**\n * Word order hint per language (affects where keywords are detected).\n * Default for unlisted languages: 'SVO'\n */\n readonly wordOrders?: Readonly<Record<string, WordOrderHint>>;\n}\n\n/**\n * Configuration for continuation resolution (e.g., BDD's \"and\" keyword).\n */\nexport interface ContinuationConfig {\n /**\n * The keyword(s) that signal continuation, per language.\n * Example: { en: ['and'], es: ['y'], ja: ['かつ'], ar: ['و'] }\n */\n readonly keywords: KeywordMap;\n\n /**\n * How to resolve continuation: re-prefix with previous step's keyword.\n * The function receives (content after 'and', previous step's category, language)\n * and returns the re-prefixed string for re-parsing.\n *\n * Default: `(content, prevCategory, language, categoryKeywords) =>\n * categoryKeywords[prevCategory]?.[language]?.[0] + ' ' + content`\n */\n readonly resolve?: (\n content: string,\n prevCategory: string,\n language: string,\n categoryKeywords: Record<string, KeywordMap>\n ) => string;\n}\n\n/**\n * A parsed statement with its line context.\n */\nexport interface ParsedStatement {\n /** The parsed semantic node */\n readonly node: SemanticNode;\n /** Original source line/text */\n readonly source: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Detected keyword category (e.g., 'test', 'given', 'when') */\n readonly category?: string;\n /** Indentation level (number of leading spaces, 0-based) */\n readonly indent: number;\n}\n\n/**\n * A parse error with location information.\n */\nexport interface StatementError {\n /** Error message */\n readonly message: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Original source line/text */\n readonly source: string;\n /** Error code for programmatic handling */\n readonly code?: 'parse-error' | 'unexpected-line' | 'continuation-error';\n}\n\n/**\n * Result of multi-statement parsing.\n */\nexport interface MultiStatementResult {\n /** Successfully parsed statements */\n readonly statements: readonly ParsedStatement[];\n /** Errors encountered during parsing */\n readonly errors: readonly StatementError[];\n}\n\n/**\n * Preprocessor function called before each statement is parsed.\n * Returns the modified string to parse, or null to skip the line.\n */\nexport type StatementPreprocessor = (\n line: string,\n category: string | undefined,\n language: string,\n context: PreprocessorContext\n) => string | null;\n\n/**\n * Context available to preprocessors.\n */\nexport interface PreprocessorContext {\n /** The previous parsed statement, if any */\n readonly previous?: ParsedStatement;\n /** Line number (1-based) */\n readonly lineNumber: number;\n /** Indentation level */\n readonly indent: number;\n}\n\n/**\n * Full configuration for multi-statement parser.\n */\nexport interface MultiStatementConfig {\n /** How to split input into statements */\n readonly split: SplitConfig;\n /** Keyword classification (optional — if omitted, no category detection) */\n readonly keywords?: KeywordConfig;\n /** Continuation resolution (optional — e.g., BDD 'and') */\n readonly continuation?: ContinuationConfig;\n /** Statement preprocessor (optional — for article stripping, expect-prepending, etc.) */\n readonly preprocessor?: StatementPreprocessor;\n}\n\n// =============================================================================\n// Multi-Statement Parser\n// =============================================================================\n\n/**\n * A reusable multi-statement parser.\n * Created via `createMultiStatementParser()`.\n */\nexport interface MultiStatementParser {\n /**\n * Parse multi-statement input into an array of parsed statements.\n */\n parse(input: string, language: string): MultiStatementResult;\n}\n\n/**\n * Create a multi-statement parser that wraps a `MultilingualDSL` instance.\n *\n * The parser handles splitting, keyword detection, continuation resolution,\n * preprocessing, and error collection. It delegates single-statement parsing\n * to the provided DSL's `parse()` method.\n *\n * @example\n * ```typescript\n * const parser = createMultiStatementParser(myDSL, {\n * split: { mode: 'line', commentPrefixes: ['--', '//'] },\n * keywords: {\n * categories: {\n * given: { en: ['given'], ja: ['前提'], es: ['dado'] },\n * when: { en: ['when'], ja: ['もし'], es: ['cuando'] },\n * then: { en: ['then'], ja: ['ならば'], es: ['entonces'] },\n * },\n * wordOrders: { ja: 'SOV', ar: 'VSO' },\n * },\n * continuation: {\n * keywords: { en: ['and'], es: ['y'], ja: ['かつ'] },\n * },\n * });\n *\n * const result = parser.parse(`\n * given #login is visible\n * when click on #submit\n * then #dashboard appears\n * `, 'en');\n * ```\n */\nexport function createMultiStatementParser(\n dsl: MultilingualDSL,\n config: MultiStatementConfig\n): MultiStatementParser {\n return new MultiStatementParserImpl(dsl, config);\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\nclass MultiStatementParserImpl implements MultiStatementParser {\n constructor(\n private readonly dsl: MultilingualDSL,\n private readonly config: MultiStatementConfig\n ) {}\n\n parse(input: string, language: string): MultiStatementResult {\n const rawStatements = this.splitStatements(input, language);\n const statements: ParsedStatement[] = [];\n const errors: StatementError[] = [];\n let previous: ParsedStatement | undefined;\n\n for (const raw of rawStatements) {\n // Detect keyword category\n const category = this.classifyLine(raw.text, language);\n\n // Handle continuation (e.g., 'and')\n let textToParse = raw.text;\n if (this.config.continuation) {\n const resolved = this.resolveContinuation(raw.text, language, previous?.category);\n if (resolved !== null) {\n textToParse = resolved;\n }\n }\n\n // Run preprocessor\n if (this.config.preprocessor) {\n const processed = this.config.preprocessor(textToParse, category, language, {\n ...(previous != null && { previous }),\n lineNumber: raw.line,\n indent: raw.indent,\n });\n if (processed === null) continue; // skip line\n textToParse = processed;\n }\n\n // Parse with DSL\n try {\n const node = this.dsl.parse(textToParse, language);\n const stmt: ParsedStatement = {\n node,\n source: raw.text,\n line: raw.line,\n ...(category != null && { category }),\n indent: raw.indent,\n };\n statements.push(stmt);\n previous = stmt;\n } catch (err) {\n errors.push({\n message: err instanceof Error ? err.message : String(err),\n line: raw.line,\n source: raw.text,\n code: 'parse-error',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Split input into raw statement lines with metadata.\n */\n private splitStatements(\n input: string,\n language: string\n ): Array<{ text: string; line: number; indent: number }> {\n const { mode, trim = true, commentPrefixes = ['--', '//'] } = this.config.split;\n\n if (mode === 'delimiter') {\n return this.splitByDelimiter(input, language, trim, commentPrefixes);\n }\n\n // Line-based splitting\n const lines = input.split('\\n');\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i];\n const indent = raw.length - raw.trimStart().length;\n const text = trim ? raw.trim() : raw;\n\n // Skip empty lines\n if (!text) continue;\n\n // Skip comments\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent });\n }\n\n return result;\n }\n\n /**\n * Split by language-specific delimiters.\n */\n private splitByDelimiter(\n input: string,\n language: string,\n trim: boolean,\n commentPrefixes: readonly string[]\n ): Array<{ text: string; line: number; indent: number }> {\n const delimiter =\n this.config.split.delimiters?.[language] ??\n this.config.split.defaultDelimiter ??\n /,\\s*|\\n\\s*/;\n\n const parts = input.split(delimiter);\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < parts.length; i++) {\n const raw = parts[i];\n const text = trim ? raw.trim() : raw;\n\n if (!text) continue;\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent: 0 });\n }\n\n return result;\n }\n\n /**\n * Classify a line by its keyword category.\n * Returns the category name or undefined if no match.\n */\n private classifyLine(line: string, language: string): string | undefined {\n if (!this.config.keywords) return undefined;\n\n const lower = line.toLowerCase();\n const wordOrder = this.config.keywords.wordOrders?.[language] ?? 'SVO';\n\n for (const [category, keywordMap] of Object.entries(this.config.keywords.categories)) {\n const keywords = keywordMap[language] ?? keywordMap['en'] ?? [];\n for (const kw of keywords) {\n const kwLower = kw.toLowerCase();\n if (wordOrder === 'SOV') {\n // SOV: check end of line first, then start\n if (lower.endsWith(kwLower) || lower.startsWith(kwLower)) {\n return category;\n }\n } else {\n // SVO/VSO: check start of line\n if (lower.startsWith(kwLower)) {\n return category;\n }\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Resolve continuation keywords (e.g., 'and' → re-prefix with previous step type).\n * Returns the resolved string, or null if not a continuation.\n */\n private resolveContinuation(\n text: string,\n language: string,\n prevCategory: string | undefined\n ): string | null {\n if (!this.config.continuation || !prevCategory) return null;\n\n const contKeywords =\n this.config.continuation.keywords[language] ?? this.config.continuation.keywords['en'] ?? [];\n\n const lower = text.toLowerCase();\n for (const kw of contKeywords) {\n const kwLower = kw.toLowerCase();\n if (lower.startsWith(kwLower)) {\n const content = text.slice(kw.length).trim();\n if (!content) return null;\n\n if (this.config.continuation.resolve) {\n return this.config.continuation.resolve(\n content,\n prevCategory,\n language,\n this.config.keywords?.categories ?? {}\n );\n }\n\n // Default: prepend previous category's keyword\n const prevKeywords =\n this.config.keywords?.categories[prevCategory]?.[language] ??\n this.config.keywords?.categories[prevCategory]?.['en'];\n if (prevKeywords?.[0]) {\n return prevKeywords[0] + ' ' + content;\n }\n\n return null;\n }\n }\n\n return null;\n }\n}\n\n// =============================================================================\n// Block Accumulator (for grouped/nested structures)\n// =============================================================================\n\n/**\n * A block of accumulated statements, grouped by a block-opening keyword.\n */\nexport interface StatementBlock<TMeta = unknown> {\n /** Block type (e.g., 'test', 'feature', 'scenario') */\n readonly type: string;\n /** Block name, if any (e.g., test name from quotes) */\n readonly name?: string;\n /** Statements within this block */\n readonly statements: readonly ParsedStatement[];\n /** Child blocks (for nested structures) */\n readonly children: readonly StatementBlock<TMeta>[];\n /** Starting line number */\n readonly line: number;\n /** Indentation level of the block opener */\n readonly indent: number;\n /** Domain-specific metadata */\n readonly meta?: TMeta;\n}\n\n/**\n * Configuration for block accumulation.\n */\nexport interface BlockConfig {\n /**\n * Block-opening keyword categories.\n * Statements classified in these categories start new blocks.\n */\n readonly blockTypes: readonly string[];\n\n /**\n * How to determine block nesting:\n * - 'indent': indentation-based (deeper indent = child block)\n * - 'flat': all blocks at same level (no nesting)\n */\n readonly nesting: 'indent' | 'flat';\n\n /**\n * Extract block name from statement text.\n * Default: extracts quoted string after keyword (e.g., test \"Login\" → \"Login\")\n */\n readonly extractName?: (text: string, category: string) => string | undefined;\n}\n\n/**\n * Result of block accumulation.\n */\nexport interface BlockResult<TMeta = unknown> {\n /** Top-level blocks */\n readonly blocks: readonly StatementBlock<TMeta>[];\n /** Statements not inside any block */\n readonly orphans: readonly ParsedStatement[];\n}\n\n/**\n * Accumulate parsed statements into blocks based on keyword categories.\n *\n * This groups statements into hierarchical blocks based on block-opening keywords\n * and indentation levels. Useful for test/feature/scenario structures.\n *\n * @example\n * ```typescript\n * const result = accumulateBlocks(statements, {\n * blockTypes: ['test', 'feature', 'setup'],\n * nesting: 'indent',\n * extractName: (text, category) => {\n * const match = text.match(/\"([^\"]+)\"/);\n * return match?.[1];\n * },\n * });\n * ```\n */\nexport function accumulateBlocks<TMeta = unknown>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n if (config.nesting === 'flat') {\n return accumulateFlat(statements, config);\n }\n return accumulateIndented(statements, config);\n}\n\nfunction accumulateFlat<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const blocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n let current: {\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n line: number;\n indent: number;\n } | null = null;\n\n const flush = () => {\n if (current) {\n blocks.push({\n type: current.type,\n ...(current.name != null && { name: current.name }),\n statements: current.stmts,\n children: [],\n line: current.line,\n indent: current.indent,\n });\n current = null;\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n flush();\n const name = config.extractName?.(stmt.source, stmt.category);\n current = {\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n line: stmt.line,\n indent: stmt.indent,\n };\n } else if (current) {\n current.stmts.push(stmt);\n } else {\n orphans.push(stmt);\n }\n }\n\n flush();\n return { blocks, orphans };\n}\n\nfunction accumulateIndented<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const rootBlocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n\n // Stack of open blocks with their indent level\n const stack: Array<{\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n children: StatementBlock<TMeta>[];\n line: number;\n indent: number;\n }> = [];\n\n const flushTo = (targetIndent: number) => {\n while (stack.length > 0) {\n const top = stack[stack.length - 1];\n if (top.indent >= targetIndent) {\n stack.pop();\n const block: StatementBlock<TMeta> = {\n type: top.type,\n ...(top.name != null && { name: top.name }),\n statements: top.stmts,\n children: top.children,\n line: top.line,\n indent: top.indent,\n };\n if (stack.length > 0) {\n stack[stack.length - 1].children.push(block);\n } else {\n rootBlocks.push(block);\n }\n } else {\n break;\n }\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n // Flush blocks at same or deeper indent\n flushTo(stmt.indent);\n const name = config.extractName?.(stmt.source, stmt.category);\n stack.push({\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n children: [],\n line: stmt.line,\n indent: stmt.indent,\n });\n } else if (stack.length > 0) {\n stack[stack.length - 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,MAAM,SAAS,CAAC,EAAE,MAAM,KAAK,IAAI;AAAA,IACzC,OAAO;AACL,cAAQ,KAAK,IAAI;AAAA,IACnB;AAAA,EACF;AAGA,UAAQ,EAAE;AAEV,SAAO,EAAE,QAAQ,YAAY,QAAQ;AACvC;","names":[]}
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import type { CommandSchema } from '../../../schema';
5
5
  import type { LanguageTokenizer } from '../../../core/types';
6
- import type { PatternGenLanguageProfile } from '../../../generation/pattern-generator';
6
+ import type { PatternGenLanguageProfile } from '../../../generation/profile';
7
7
  export type Severity = 'error' | 'warning' | 'note';
8
8
  export interface LintFinding {
9
9
  readonly rule: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/testing/gate/lint/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC;AAEvF,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;AAEpD,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,0FAA0F;IAC1F,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC;CAC9D;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,SAAS,WAAW,EAAE,CAAC;IAC1C,6CAA6C;IAC7C,QAAQ,CAAC,UAAU,EAAE,MAAM,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AW,EAAE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lokascript/framework",
3
- "version": "4.8.0",
3
+ "version": "5.0.0",
4
4
  "description": "Generic framework for building multilingual DSLs with semantic parsing and grammar transformation",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -24,10 +24,6 @@
24
24
  "types": "./dist/core/tokenization/index.d.ts",
25
25
  "import": "./dist/core/tokenization/index.js"
26
26
  },
27
- "./core/pattern-matching": {
28
- "types": "./dist/core/pattern-matching/index.d.ts",
29
- "import": "./dist/core/pattern-matching/index.js"
30
- },
31
27
  "./multilingual": {
32
28
  "types": "./dist/multilingual/index.d.ts",
33
29
  "import": "./dist/multilingual/index.js"
@@ -77,7 +73,6 @@
77
73
  "test:coverage": "vitest run --coverage",
78
74
  "test:unit": "vitest run src/core/**/*.test.ts src/generation/**/*.test.ts",
79
75
  "test:integration": "vitest run src/__test__/**/*.test.ts src/api/**/*.test.ts",
80
- "test:pattern-matcher": "vitest run src/core/pattern-matching",
81
76
  "test:tokenizer": "vitest run src/core/tokenization",
82
77
  "typecheck": "tsc --noEmit",
83
78
  "create-domain": "npx tsx scripts/create-domain.ts"
@@ -100,7 +95,7 @@
100
95
  "author": "LokaScript Contributors",
101
96
  "license": "MIT",
102
97
  "dependencies": {
103
- "@lokascript/intent": "^4.8.0"
98
+ "@lokascript/intent": "^5.0.0"
104
99
  },
105
100
  "devDependencies": {
106
101
  "@lokascript/domains": "^4.0.0",
@@ -15,7 +15,7 @@ import type {
15
15
  PatternMatchResult,
16
16
  } from '../core/types';
17
17
  import type { CommandSchema, RoleSpec } from '../schema';
18
- import type { PatternGenLanguageProfile } from '../generation/pattern-generator';
18
+ import type { PatternGenLanguageProfile } from '../generation/profile';
19
19
  import type { LanguageConfig, MultilingualDSL } from '../api';
20
20
  import { TokenStreamImpl, createToken, createPosition } from '../core/tokenization';
21
21
  import { createMultilingualDSL } from '../api';
@@ -1,9 +1,8 @@
1
1
  /**
2
- * `engine: 'core'` (domains rethink Phase 4.7): the same config and DSL as the
3
- * classic engine, read by the core. framework's SQL fixture reads, compiles and
4
- * translates as it does on the classic engine, refuses what it does not read,
5
- * and renders through its own patterns where no renderer is configured. A role
6
- * with a word list reads only its words.
2
+ * The core engine (domains rethink Phase 4.7), the only engine since 5.0. framework's SQL fixture
3
+ * reads, compiles and translates as the classic engine did (its readings and translations below
4
+ * were taken from the classic engine on 4.8), refuses what it does not read, and renders through
5
+ * its own patterns where no renderer is configured. A role with a word list reads only its words.
7
6
  */
8
7
  import { describe, expect, it, vi } from 'vitest';
9
8
  import { createMultilingualDSL, UnreadInputError, type DSLConfig } from './create-dsl';
@@ -11,22 +10,15 @@ import { defineCommand, defineRole } from '../schema';
11
10
  import { BaseTokenizer, getDefaultExtractors } from '../index';
12
11
  import { sqlDSLConfig, testQueries, expectedSQL } from '../__test__/fixtures/sql-dsl';
13
12
  import type { SemanticNode } from '../core/types';
14
- import { generatePattern } from '../generation/pattern-generator';
15
13
  import { createSchemaPatternGenerator } from '../generation/schema-patterns';
16
14
 
17
- // Pass-through spies. On the SQL fixture the two engines read, compile and render alike, so
18
- // these are what show which engine a DSL was built on.
19
- vi.mock('../generation/pattern-generator', async importOriginal => {
20
- const actual = await importOriginal<typeof import('../generation/pattern-generator')>();
21
- return { ...actual, generatePattern: vi.fn(actual.generatePattern) };
22
- });
15
+ // A pass-through spy: what shows a DSL was built on the core.
23
16
  vi.mock('../generation/schema-patterns', async importOriginal => {
24
17
  const actual = await importOriginal<typeof import('../generation/schema-patterns')>();
25
18
  return { ...actual, createSchemaPatternGenerator: vi.fn(actual.createSchemaPatternGenerator) };
26
19
  });
27
20
 
28
- const core = createMultilingualDSL({ ...sqlDSLConfig(), engine: 'core' });
29
- const classic = createMultilingualDSL(sqlDSLConfig());
21
+ const core = createMultilingualDSL(sqlDSLConfig());
30
22
 
31
23
  const reading = (node: SemanticNode) =>
32
24
  [
@@ -37,23 +29,54 @@ const reading = (node: SemanticNode) =>
37
29
  ),
38
30
  ].join(' ');
39
31
 
40
- describe("createMultilingualDSL with engine: 'core'", () => {
32
+ describe('createMultilingualDSL on the core engine', () => {
33
+ // [language, input, SQL, reading, translation] — the reading and translation the classic engine gave.
41
34
  const queries = [
42
- ['en', testQueries.english.simple, expectedSQL.simple],
43
- ['en', testQueries.english.withWhere, expectedSQL.withWhere],
44
- ['es', testQueries.spanish.simple, 'SELECT nombre FROM usuarios'],
45
- ['es', testQueries.spanish.withWhere, 'SELECT nombre FROM usuarios WHERE edad > 18'],
35
+ [
36
+ 'en',
37
+ testQueries.english.simple,
38
+ expectedSQL.simple,
39
+ 'select columns=name source=users',
40
+ 'seleccionar name de users',
41
+ ],
42
+ [
43
+ 'en',
44
+ testQueries.english.withWhere,
45
+ expectedSQL.withWhere,
46
+ 'select columns=name source=users condition=age > 18',
47
+ 'seleccionar name de users donde age > 18',
48
+ ],
49
+ [
50
+ 'es',
51
+ testQueries.spanish.simple,
52
+ 'SELECT nombre FROM usuarios',
53
+ 'select columns=nombre source=usuarios',
54
+ 'select nombre from usuarios',
55
+ ],
56
+ [
57
+ 'es',
58
+ testQueries.spanish.withWhere,
59
+ 'SELECT nombre FROM usuarios WHERE edad > 18',
60
+ 'select columns=nombre source=usuarios condition=edad > 18',
61
+ 'select nombre from usuarios where edad > 18',
62
+ ],
46
63
  ] as const;
47
64
 
48
- it.each(queries)('reads and compiles %s `%s` as the classic engine does', (lang, input, sql) => {
49
- expect(reading(core.parse(input, lang))).toBe(reading(classic.parse(input, lang)));
50
- expect(core.compile(input, lang).code).toBe(sql);
51
- });
65
+ it.each(queries)(
66
+ 'reads and compiles %s `%s` as the classic engine did',
67
+ (lang, input, sql, read) => {
68
+ expect(reading(core.parse(input, lang))).toBe(read);
69
+ expect(core.compile(input, lang).code).toBe(sql);
70
+ }
71
+ );
52
72
 
53
- it.each(queries)('translates %s `%s` as the classic engine does', (lang, input) => {
54
- const to = lang === 'en' ? 'es' : 'en';
55
- expect(core.translate(input, lang, to)).toBe(classic.translate(input, lang, to));
56
- });
73
+ it.each(queries)(
74
+ 'translates %s `%s` as the classic engine did',
75
+ (lang, input, _sql, _read, translated) => {
76
+ const to = lang === 'en' ? 'es' : 'en';
77
+ expect(core.translate(input, lang, to)).toBe(translated);
78
+ }
79
+ );
57
80
 
58
81
  it('refuses input it does not read', () => {
59
82
  expect(() => core.parse('select name from users banana', 'en')).toThrow(UnreadInputError);
@@ -71,18 +94,20 @@ describe("createMultilingualDSL with engine: 'core'", () => {
71
94
  });
72
95
 
73
96
  it.each([
74
- ['core', { engine: 'core' }],
75
- ['classic', { engine: 'classic' }],
76
- ['classic', {}],
77
- ] as const)('builds on the %s engine with %o', (expected, option) => {
78
- vi.mocked(generatePattern).mockClear();
97
+ ['no engine option', {}],
98
+ ["engine: 'core'", { engine: 'core' }],
99
+ ] as const)('builds on the core with %s', (_label, option) => {
79
100
  vi.mocked(createSchemaPatternGenerator).mockClear();
80
101
  createMultilingualDSL({ ...sqlDSLConfig(), ...option }).parse(testQueries.english.simple, 'en');
81
- expect(vi.mocked(createSchemaPatternGenerator).mock.calls.length > 0).toBe(expected === 'core');
82
- expect(vi.mocked(generatePattern).mock.calls.length > 0).toBe(expected === 'classic');
102
+ expect(vi.mocked(createSchemaPatternGenerator).mock.calls.length).toBeGreaterThan(0);
103
+ });
104
+
105
+ it("refuses engine: 'classic', removed in 5.0, and says what replaced it", () => {
106
+ const classic = { ...sqlDSLConfig(), engine: 'classic' } as unknown as DSLConfig;
107
+ expect(() => createMultilingualDSL(classic)).toThrow(/removed in @lokascript\/framework 5\.0/);
83
108
  });
84
109
 
85
- it('throws on an engine it does not know, rather than reading with the classic one', () => {
110
+ it('throws on an engine it does not know, rather than reading with the default', () => {
86
111
  const misspelled = { ...sqlDSLConfig(), engine: 'cor' } as unknown as DSLConfig;
87
112
  expect(() => createMultilingualDSL(misspelled)).toThrow('Unknown DSL engine "cor"');
88
113
  });