@lokascript/framework 4.5.0 → 4.7.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 (123) hide show
  1. package/CHANGELOG.md +220 -8
  2. package/dist/api/create-dsl.d.ts +59 -1
  3. package/dist/api/create-dsl.d.ts.map +1 -1
  4. package/dist/api/domain-registry.d.ts.map +1 -1
  5. package/dist/api/index.d.ts +1 -0
  6. package/dist/api/index.d.ts.map +1 -1
  7. package/dist/api/index.js +1938 -724
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/reading.d.ts +8 -0
  10. package/dist/api/reading.d.ts.map +1 -0
  11. package/dist/api/translation-loss.d.ts +84 -0
  12. package/dist/api/translation-loss.d.ts.map +1 -0
  13. package/dist/core/index.d.ts +1 -0
  14. package/dist/core/index.d.ts.map +1 -1
  15. package/dist/core/index.js +1047 -684
  16. package/dist/core/index.js.map +1 -1
  17. package/dist/core/matching/confidence-model.d.ts +54 -0
  18. package/dist/core/matching/confidence-model.d.ts.map +1 -0
  19. package/dist/core/matching/index.d.ts +12 -0
  20. package/dist/core/matching/index.d.ts.map +1 -0
  21. package/dist/core/matching/match-skeleton.d.ts +114 -0
  22. package/dist/core/matching/match-skeleton.d.ts.map +1 -0
  23. package/dist/core/matching/stock-confidence.d.ts +15 -0
  24. package/dist/core/matching/stock-confidence.d.ts.map +1 -0
  25. package/dist/core/matching/stock-reader.d.ts +56 -0
  26. package/dist/core/matching/stock-reader.d.ts.map +1 -0
  27. package/dist/core/matching/stock-reading.d.ts +44 -0
  28. package/dist/core/matching/stock-reading.d.ts.map +1 -0
  29. package/dist/core/matching/value-reader.d.ts +62 -0
  30. package/dist/core/matching/value-reader.d.ts.map +1 -0
  31. package/dist/core/pattern-matching/index.js +561 -660
  32. package/dist/core/pattern-matching/index.js.map +1 -1
  33. package/dist/core/pattern-matching/pattern-matcher.d.ts +0 -117
  34. package/dist/core/pattern-matching/pattern-matcher.d.ts.map +1 -1
  35. package/dist/core/types.d.ts +48 -0
  36. package/dist/core/types.d.ts.map +1 -1
  37. package/dist/core/types.js.map +1 -1
  38. package/dist/generation/index.d.ts +2 -0
  39. package/dist/generation/index.d.ts.map +1 -1
  40. package/dist/generation/index.js +583 -1
  41. package/dist/generation/index.js.map +1 -1
  42. package/dist/generation/pattern-render.d.ts +72 -0
  43. package/dist/generation/pattern-render.d.ts.map +1 -0
  44. package/dist/generation/schema-patterns.d.ts +152 -0
  45. package/dist/generation/schema-patterns.d.ts.map +1 -0
  46. package/dist/index.cjs +2132 -890
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.js +2110 -887
  49. package/dist/index.js.map +1 -1
  50. package/dist/ir/index.js.map +1 -1
  51. package/dist/parsing/index.js +561 -660
  52. package/dist/parsing/index.js.map +1 -1
  53. package/dist/testing/gate/index.d.ts +8 -0
  54. package/dist/testing/gate/index.d.ts.map +1 -0
  55. package/dist/testing/gate/index.js +632 -0
  56. package/dist/testing/gate/index.js.map +1 -0
  57. package/dist/testing/gate/lint/format.d.ts +7 -0
  58. package/dist/testing/gate/lint/format.d.ts.map +1 -0
  59. package/dist/testing/gate/lint/index.d.ts +30 -0
  60. package/dist/testing/gate/lint/index.d.ts.map +1 -0
  61. package/dist/testing/gate/lint/rules/extractor-coverage.d.ts +18 -0
  62. package/dist/testing/gate/lint/rules/extractor-coverage.d.ts.map +1 -0
  63. package/dist/testing/gate/lint/rules/index.d.ts +14 -0
  64. package/dist/testing/gate/lint/rules/index.d.ts.map +1 -0
  65. package/dist/testing/gate/lint/rules/keyword-classification.d.ts +19 -0
  66. package/dist/testing/gate/lint/rules/keyword-classification.d.ts.map +1 -0
  67. package/dist/testing/gate/lint/rules/keyword-coverage.d.ts +13 -0
  68. package/dist/testing/gate/lint/rules/keyword-coverage.d.ts.map +1 -0
  69. package/dist/testing/gate/lint/rules/marker-tokenization.d.ts +20 -0
  70. package/dist/testing/gate/lint/rules/marker-tokenization.d.ts.map +1 -0
  71. package/dist/testing/gate/lint/rules/position-ordering.d.ts +25 -0
  72. package/dist/testing/gate/lint/rules/position-ordering.d.ts.map +1 -0
  73. package/dist/testing/gate/lint/rules/renderer-coherence.d.ts +24 -0
  74. package/dist/testing/gate/lint/rules/renderer-coherence.d.ts.map +1 -0
  75. package/dist/testing/gate/lint/rules/schema-rules.d.ts +10 -0
  76. package/dist/testing/gate/lint/rules/schema-rules.d.ts.map +1 -0
  77. package/dist/testing/gate/lint/types.d.ts +74 -0
  78. package/dist/testing/gate/lint/types.d.ts.map +1 -0
  79. package/dist/testing/gate/round-trip.d.ts +163 -0
  80. package/dist/testing/gate/round-trip.d.ts.map +1 -0
  81. package/package.json +7 -3
  82. package/src/__test__/fixtures/sql-dsl.ts +11 -2
  83. package/src/__test__/sql-integration.test.ts +2 -2
  84. package/src/api/create-dsl-engine.test.ts +86 -0
  85. package/src/api/create-dsl.test.ts +120 -0
  86. package/src/api/create-dsl.ts +314 -39
  87. package/src/api/domain-registry.test.ts +70 -5
  88. package/src/api/domain-registry.ts +82 -1
  89. package/src/api/index.ts +1 -0
  90. package/src/api/reading.ts +29 -0
  91. package/src/api/translation-loss.test.ts +89 -0
  92. package/src/api/translation-loss.ts +128 -0
  93. package/src/core/index.ts +1 -0
  94. package/src/core/matching/confidence-model.ts +58 -0
  95. package/src/core/matching/index.ts +12 -0
  96. package/src/core/matching/match-skeleton.test.ts +179 -0
  97. package/src/core/matching/match-skeleton.ts +621 -0
  98. package/src/core/matching/stock-confidence.ts +238 -0
  99. package/src/core/matching/stock-reader.test.ts +181 -0
  100. package/src/core/matching/stock-reader.ts +186 -0
  101. package/src/core/matching/stock-reading.ts +681 -0
  102. package/src/core/matching/value-reader.ts +85 -0
  103. package/src/core/pattern-matching/pattern-matcher.ts +11 -876
  104. package/src/core/types.ts +48 -0
  105. package/src/generation/index.ts +2 -0
  106. package/src/generation/pattern-render.ts +378 -0
  107. package/src/generation/schema-patterns.test.ts +99 -0
  108. package/src/generation/schema-patterns.ts +962 -0
  109. package/src/testing/gate/index.ts +8 -0
  110. package/src/testing/gate/lint/format.ts +23 -0
  111. package/src/testing/gate/lint/index.ts +73 -0
  112. package/src/testing/gate/lint/lint.test.ts +131 -0
  113. package/src/testing/gate/lint/rules/extractor-coverage.ts +63 -0
  114. package/src/testing/gate/lint/rules/index.ts +37 -0
  115. package/src/testing/gate/lint/rules/keyword-classification.ts +52 -0
  116. package/src/testing/gate/lint/rules/keyword-coverage.ts +38 -0
  117. package/src/testing/gate/lint/rules/marker-tokenization.ts +129 -0
  118. package/src/testing/gate/lint/rules/position-ordering.ts +87 -0
  119. package/src/testing/gate/lint/rules/renderer-coherence.ts +100 -0
  120. package/src/testing/gate/lint/rules/schema-rules.ts +35 -0
  121. package/src/testing/gate/lint/types.ts +83 -0
  122. package/src/testing/gate/round-trip.test.ts +118 -0
  123. package/src/testing/gate/round-trip.ts +438 -0
@@ -9,13 +9,11 @@ import type {
9
9
  LanguagePattern,
10
10
  PatternToken,
11
11
  PatternMatchResult,
12
- ReferenceValue,
13
12
  SemanticRole,
14
13
  SemanticValue,
15
14
  TokenStream,
16
15
  LanguageToken,
17
16
  } from '../types';
18
- import { createSelector, createLiteral, createReference, createPropertyPath } from '../types';
19
17
  import { createLogger } from '../logger';
20
18
 
21
19
  /**
@@ -26,13 +24,9 @@ import { createLogger } from '../logger';
26
24
  *
27
25
  * For generic DSLs, identifiers are treated as expressions by default.
28
26
  */
29
- function isValidReference(_value: string): boolean {
30
- // In generic framework, no built-in references
31
- // Identifiers should be expressions
32
- return false;
33
- }
34
- import { isTypeCompatible } from './utils/type-validation';
35
- import { getPossessiveReference } from './utils/possessive-keywords';
27
+ // A role's value is read by the code the stock reader runs too (core/matching/stock-reading.ts).
28
+ import { readRoleValue, safeToLowerCase } from '../matching/stock-reading';
29
+ import { stockConfidenceModel } from '../matching/stock-confidence';
36
30
 
37
31
  /**
38
32
  * Minimal profile interface needed by PatternMatcher.
@@ -59,20 +53,6 @@ export class PatternMatcher {
59
53
  /** Current language profile for the pattern being matched */
60
54
  private currentProfile: PatternMatcherProfile | undefined;
61
55
 
62
- /**
63
- * Safely convert a value to lowercase string.
64
- * Provides protection against non-string values at runtime.
65
- */
66
- private safeToLowerCase(value: unknown): string {
67
- if (typeof value === 'string') {
68
- return value.toLowerCase();
69
- }
70
- if (value === null || value === undefined) {
71
- return '';
72
- }
73
- return String(value).toLowerCase();
74
- }
75
-
76
56
  /**
77
57
  * Try to match a single pattern against the token stream.
78
58
  * Returns the match result or null if no match.
@@ -137,7 +117,12 @@ export class PatternMatcher {
137
117
 
138
118
  // Calculate confidence BEFORE applying defaults
139
119
  // This ensures defaulted roles don't artificially inflate confidence
140
- const confidence = this.calculateConfidence(pattern, captured);
120
+ const confidence = stockConfidenceModel.calculate({
121
+ pattern,
122
+ captured,
123
+ stemMatchCount: this.stemMatchCount,
124
+ totalKeywordMatches: this.totalKeywordMatches,
125
+ });
141
126
 
142
127
  // Apply extraction rules to fill in any missing roles with defaults
143
128
  this.applyExtractionRules(pattern, captured);
@@ -407,7 +392,7 @@ export class PatternMatcher {
407
392
  return this.matchLiteralToken(tokens, patternToken);
408
393
 
409
394
  case 'role':
410
- return this.matchRoleToken(tokens, patternToken, captured);
395
+ return readRoleValue(tokens, patternToken, captured, this.currentProfile);
411
396
 
412
397
  case 'group':
413
398
  return this.matchGroupToken(tokens, patternToken, captured);
@@ -478,511 +463,6 @@ export class PatternMatcher {
478
463
  return false;
479
464
  }
480
465
 
481
- /**
482
- * Match a role pattern token (captures a semantic value).
483
- * Handles multi-token expressions like:
484
- * - 'my value' (possessive keyword + property)
485
- * - '#dialog.showModal()' (method call)
486
- * - "#element's *opacity" (possessive selector + property)
487
- */
488
- private matchRoleToken(
489
- tokens: TokenStream,
490
- patternToken: PatternToken & { type: 'role' },
491
- captured: Map<SemanticRole, SemanticValue>
492
- ): boolean {
493
- this.logger.debug(' >>> matchRoleToken ENTRY: capturing role', patternToken.role);
494
- this.logger.debug(' >>> matchRoleToken: expected types', patternToken.expectedTypes);
495
- this.logger.debug(' >>> matchRoleToken: optional?', patternToken.optional);
496
- // Skip noise words like "the" before selectors (English idiom support)
497
- this.skipNoiseWords(tokens);
498
-
499
- const token = tokens.peek();
500
- this.logger.debug(
501
- ' >>> After skipNoiseWords, current token:',
502
- token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'
503
- );
504
- if (!token) {
505
- return patternToken.optional || false;
506
- }
507
-
508
- // Check for possessive expression (e.g., 'my value', 'its innerHTML')
509
- const possessiveValue = this.tryMatchPossessiveExpression(tokens);
510
- if (possessiveValue) {
511
- // Validate expected types if specified
512
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
513
- if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {
514
- return patternToken.optional || false;
515
- }
516
- }
517
- captured.set(patternToken.role, possessiveValue);
518
- return true;
519
- }
520
-
521
- // Check for method call expression (e.g., '#dialog.showModal()')
522
- const methodCallValue = this.tryMatchMethodCallExpression(tokens);
523
- if (methodCallValue) {
524
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
525
- if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {
526
- return patternToken.optional || false;
527
- }
528
- }
529
- captured.set(patternToken.role, methodCallValue);
530
- return true;
531
- }
532
-
533
- // Check for possessive selector expression (e.g., "#element's *opacity")
534
- const possessiveSelectorValue = this.tryMatchPossessiveSelectorExpression(tokens);
535
- if (possessiveSelectorValue) {
536
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
537
- // property-path is compatible with selector, reference, and expression
538
- if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {
539
- return patternToken.optional || false;
540
- }
541
- }
542
- captured.set(patternToken.role, possessiveSelectorValue);
543
- return true;
544
- }
545
-
546
- // Check for property access expression (e.g., 'userData.name', 'it.data')
547
- const propertyAccessValue = this.tryMatchPropertyAccessExpression(tokens);
548
- if (propertyAccessValue) {
549
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
550
- if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {
551
- return patternToken.optional || false;
552
- }
553
- }
554
- captured.set(patternToken.role, propertyAccessValue);
555
- return true;
556
- }
557
-
558
- // Check for selector + property expression (e.g., '#output.innerText')
559
- // This handles cases where the tokenizer produces two selector tokens
560
- const selectorPropertyValue = this.tryMatchSelectorPropertyExpression(tokens);
561
- if (selectorPropertyValue) {
562
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
563
- if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {
564
- return patternToken.optional || false;
565
- }
566
- }
567
- captured.set(patternToken.role, selectorPropertyValue);
568
- return true;
569
- }
570
-
571
- // Try to extract a semantic value from the token
572
- this.logger.debug(
573
- ' >>> Trying tokenToSemanticValue for token:',
574
- token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'
575
- );
576
- const value = this.tokenToSemanticValue(token);
577
- this.logger.debug(
578
- ' >>> tokenToSemanticValue returned:',
579
- value ? JSON.stringify(value) : 'null'
580
- );
581
- if (!value) {
582
- return patternToken.optional || false;
583
- }
584
-
585
- // Validate expected types if specified
586
- this.logger.debug(
587
- ' >>> Validating type:',
588
- value.type,
589
- 'against expected:',
590
- patternToken.expectedTypes
591
- );
592
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
593
- if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {
594
- this.logger.debug(' >>> TYPE MISMATCH - returning', patternToken.optional || false);
595
- return patternToken.optional || false;
596
- }
597
- }
598
- this.logger.debug(' >>> Type validation PASSED');
599
-
600
- captured.set(patternToken.role, value);
601
- tokens.advance();
602
- return true;
603
- }
604
-
605
- /**
606
- * Try to match a possessive expression like 'my value' or 'its innerHTML'.
607
- * Returns the PropertyPathValue if matched, or null if not.
608
- */
609
- private tryMatchPossessiveExpression(tokens: TokenStream): SemanticValue | null {
610
- const token = tokens.peek();
611
- if (!token) return null;
612
-
613
- // Use profile-based possessive keyword lookup
614
- if (!this.currentProfile) return null;
615
-
616
- const tokenValue = token.normalized || token.value;
617
- const tokenLower = this.safeToLowerCase(tokenValue);
618
- const baseRef = getPossessiveReference(this.currentProfile, tokenLower);
619
-
620
- if (!baseRef) return null;
621
-
622
- // We have a possessive keyword, look ahead for property name
623
- const mark = tokens.mark();
624
- tokens.advance();
625
-
626
- const propertyToken = tokens.peek();
627
- if (!propertyToken) {
628
- // Just the possessive keyword, no property - revert
629
- tokens.reset(mark);
630
- return null;
631
- }
632
-
633
- // Property should be an identifier, keyword (not structural), or selector (for style/dot/attr)
634
- // Examples: "my value", "my innerHTML", "my *background", "my *opacity", "my @data-count"
635
- // Also handles dot-property access: "my.textContent" tokenized as "my" + ".textContent"
636
- if (
637
- propertyToken.kind === 'identifier' ||
638
- (propertyToken.kind === 'keyword' && !this.isStructuralKeyword(propertyToken.value)) ||
639
- (propertyToken.kind === 'selector' && propertyToken.value.startsWith('*')) ||
640
- (propertyToken.kind === 'selector' && propertyToken.value.startsWith('@')) ||
641
- (propertyToken.kind === 'selector' &&
642
- propertyToken.value.startsWith('.') &&
643
- /^\.[a-zA-Z_]\w*/.test(propertyToken.value))
644
- ) {
645
- tokens.advance();
646
-
647
- // For dot-property selectors (.textContent), strip the leading dot
648
- let propertyName = propertyToken.value;
649
- if (
650
- propertyToken.kind === 'selector' &&
651
- propertyName.startsWith('.') &&
652
- /^\.[a-zA-Z_]\w*/.test(propertyName)
653
- ) {
654
- propertyName = propertyName.substring(1);
655
- }
656
-
657
- // Consume chained dot-property access (.parentElement.style.display)
658
- let chainedProps = propertyName;
659
- while (
660
- tokens.peek()?.kind === 'selector' &&
661
- tokens.peek()!.value.startsWith('.') &&
662
- /^\.[a-zA-Z_]\w*/.test(tokens.peek()!.value)
663
- ) {
664
- chainedProps += tokens.peek()!.value; // keep the dots for chaining
665
- tokens.advance();
666
- }
667
-
668
- // Check for method call — next token is '(' in the value (e.g., .getAttribute("data-id"))
669
- const nextPeek = tokens.peek();
670
- if (nextPeek?.kind === 'literal' && nextPeek.value.startsWith('(')) {
671
- // Consume method args
672
- chainedProps += nextPeek.value;
673
- tokens.advance();
674
- }
675
-
676
- // Create property-path: my value -> { object: me, property: 'value' }
677
- // baseRef from getPossessiveReference is always a valid reference ('me', 'you', 'it', etc.)
678
- return createPropertyPath(createReference(baseRef as ReferenceValue['value']), chainedProps);
679
- }
680
-
681
- // Not a valid property, revert
682
- tokens.reset(mark);
683
- return null;
684
- }
685
-
686
- /**
687
- * Check if a keyword is a structural keyword (preposition, control flow, etc.)
688
- * that shouldn't be consumed as a property name.
689
- */
690
- private isStructuralKeyword(value: string): boolean {
691
- const structural = new Set([
692
- // Prepositions
693
- 'into',
694
- 'in',
695
- 'to',
696
- 'from',
697
- 'at',
698
- 'by',
699
- 'with',
700
- 'without',
701
- 'before',
702
- 'after',
703
- 'of',
704
- 'as',
705
- 'on',
706
- // Control flow
707
- 'then',
708
- 'end',
709
- 'else',
710
- 'if',
711
- 'repeat',
712
- 'while',
713
- 'for',
714
- // Commands (shouldn't be property names)
715
- 'toggle',
716
- 'add',
717
- 'remove',
718
- 'put',
719
- 'set',
720
- 'show',
721
- 'hide',
722
- 'increment',
723
- 'decrement',
724
- 'send',
725
- 'trigger',
726
- 'call',
727
- ]);
728
- return structural.has(value.toLowerCase());
729
- }
730
-
731
- /**
732
- * Try to match a method call expression like '#dialog.showModal()'.
733
- * Pattern: selector + '.' + identifier + '(' + [args] + ')'
734
- * Returns an expression value if matched, or null if not.
735
- */
736
- private tryMatchMethodCallExpression(tokens: TokenStream): SemanticValue | null {
737
- const token = tokens.peek();
738
- if (!token || token.kind !== 'selector') return null;
739
-
740
- // Look ahead for: . identifier (
741
- const mark = tokens.mark();
742
- tokens.advance(); // consume selector
743
-
744
- const dotToken = tokens.peek();
745
- if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {
746
- tokens.reset(mark);
747
- return null;
748
- }
749
- tokens.advance(); // consume .
750
-
751
- const methodToken = tokens.peek();
752
- if (!methodToken || methodToken.kind !== 'identifier') {
753
- tokens.reset(mark);
754
- return null;
755
- }
756
- tokens.advance(); // consume method name
757
-
758
- const openParen = tokens.peek();
759
- if (!openParen || openParen.kind !== 'punctuation' || openParen.value !== '(') {
760
- tokens.reset(mark);
761
- return null;
762
- }
763
- tokens.advance(); // consume (
764
-
765
- // Consume arguments until we find ) (with depth limit for security)
766
- const args: string[] = [];
767
- while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {
768
- const argToken = tokens.peek();
769
- if (!argToken) break;
770
- if (argToken.kind === 'punctuation' && argToken.value === ')') {
771
- tokens.advance(); // consume )
772
- break;
773
- }
774
- // Skip commas
775
- if (argToken.kind === 'punctuation' && argToken.value === ',') {
776
- tokens.advance();
777
- continue;
778
- }
779
- // Collect arg value
780
- args.push(argToken.value);
781
- tokens.advance();
782
- }
783
-
784
- // Create expression value: #dialog.showModal()
785
- const methodCall = `${token.value}.${methodToken.value}(${args.join(', ')})`;
786
- return {
787
- type: 'expression',
788
- raw: methodCall,
789
- } as SemanticValue;
790
- }
791
-
792
- /**
793
- * Try to match a property access expression like 'userData.name' or 'it.data'.
794
- * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]
795
- * Returns an expression value if matched, or null if not.
796
- */
797
- private tryMatchPropertyAccessExpression(tokens: TokenStream): SemanticValue | null {
798
- const token = tokens.peek();
799
- if (!token) return null;
800
-
801
- // Must start with an identifier or keyword reference
802
- if (token.kind !== 'identifier' && token.kind !== 'keyword') return null;
803
-
804
- // Look ahead for: . identifier
805
- const mark = tokens.mark();
806
- tokens.advance(); // consume first token
807
-
808
- const dotToken = tokens.peek();
809
- if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {
810
- tokens.reset(mark);
811
- return null;
812
- }
813
- tokens.advance(); // consume .
814
-
815
- const propertyToken = tokens.peek();
816
- if (!propertyToken || propertyToken.kind !== 'identifier') {
817
- tokens.reset(mark);
818
- return null;
819
- }
820
- tokens.advance(); // consume property name
821
-
822
- // Build the property chain
823
- let chain = `${token.value}.${propertyToken.value}`;
824
- let depth = 1; // Already have one property access
825
-
826
- // Continue for nested property access (e.g., userData.address.city)
827
- // With depth limit for security
828
- while (!tokens.isAtEnd() && depth < PatternMatcher.MAX_PROPERTY_DEPTH) {
829
- const nextDot = tokens.peek();
830
- if (!nextDot || nextDot.kind !== 'operator' || nextDot.value !== '.') {
831
- break;
832
- }
833
- tokens.advance(); // consume .
834
-
835
- const nextProp = tokens.peek();
836
- if (!nextProp || nextProp.kind !== 'identifier') {
837
- // Dot without property - put the dot back and stop
838
- // Can't easily put a single token back, so we'll include it
839
- break;
840
- }
841
- tokens.advance(); // consume property
842
- chain += `.${nextProp.value}`;
843
- depth++;
844
- }
845
-
846
- // Check for method call: chain + '(' + args + ')'
847
- // e.g., me.insertBefore(draggedItem, dropTarget)
848
- const openParen = tokens.peek();
849
- if (openParen && openParen.kind === 'punctuation' && openParen.value === '(') {
850
- tokens.advance(); // consume (
851
-
852
- // Collect arguments (comma-separated values)
853
- const args: string[] = [];
854
- let argDepth = 0; // Track nested parentheses
855
- while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {
856
- const argToken = tokens.peek();
857
- if (!argToken) break;
858
-
859
- // Handle close paren - respecting nesting
860
- if (argToken.kind === 'punctuation' && argToken.value === ')') {
861
- if (argDepth === 0) {
862
- tokens.advance(); // consume )
863
- break;
864
- }
865
- argDepth--;
866
- }
867
- // Track nested open parens
868
- if (argToken.kind === 'punctuation' && argToken.value === '(') {
869
- argDepth++;
870
- }
871
- // Skip commas between arguments
872
- if (argToken.kind === 'punctuation' && argToken.value === ',') {
873
- tokens.advance();
874
- continue;
875
- }
876
- // Collect arg value
877
- args.push(argToken.value);
878
- tokens.advance();
879
- }
880
-
881
- // Create expression value with method call: me.insertBefore(a, b)
882
- const methodCall = `${chain}(${args.join(', ')})`;
883
- return {
884
- type: 'expression',
885
- raw: methodCall,
886
- } as SemanticValue;
887
- }
888
-
889
- // Create expression value: userData.name
890
- return {
891
- type: 'expression',
892
- raw: chain,
893
- } as SemanticValue;
894
- }
895
-
896
- /**
897
- * Try to match a possessive selector expression like "#element's *opacity".
898
- * Pattern: selector + "'s" + (selector | identifier)
899
- * Returns a property-path value if matched, or null if not.
900
- */
901
- private tryMatchPossessiveSelectorExpression(tokens: TokenStream): SemanticValue | null {
902
- const token = tokens.peek();
903
- if (!token || token.kind !== 'selector') return null;
904
-
905
- // Look ahead for: 's (possessive marker)
906
- const mark = tokens.mark();
907
- tokens.advance(); // consume selector
908
-
909
- const possessiveToken = tokens.peek();
910
- if (
911
- !possessiveToken ||
912
- possessiveToken.kind !== 'punctuation' ||
913
- possessiveToken.value !== "'s"
914
- ) {
915
- tokens.reset(mark);
916
- return null;
917
- }
918
- tokens.advance(); // consume 's
919
-
920
- const propertyToken = tokens.peek();
921
- if (!propertyToken) {
922
- tokens.reset(mark);
923
- return null;
924
- }
925
-
926
- // Property can be a selector (*opacity) or identifier
927
- if (propertyToken.kind !== 'selector' && propertyToken.kind !== 'identifier') {
928
- tokens.reset(mark);
929
- return null;
930
- }
931
- tokens.advance(); // consume property
932
-
933
- // Create property-path: #element's *opacity
934
- return createPropertyPath(createSelector(token.value), propertyToken.value);
935
- }
936
-
937
- /**
938
- * Try to match a selector + property expression like "#output.innerText".
939
- * This handles cases where the tokenizer produces two selector tokens:
940
- * - #output (id selector)
941
- * - .innerText (looks like class selector, but is actually property)
942
- *
943
- * Pattern: id-selector + class-selector-that-is-actually-property
944
- * Returns a property-path value if matched, or null if not.
945
- */
946
- private tryMatchSelectorPropertyExpression(tokens: TokenStream): SemanticValue | null {
947
- const token = tokens.peek();
948
- if (!token || token.kind !== 'selector') return null;
949
-
950
- // Must be an ID selector (starts with #)
951
- if (typeof token.value !== 'string' || !token.value.startsWith('#')) return null;
952
-
953
- // Look ahead for: selector that looks like a property (.something)
954
- const mark = tokens.mark();
955
- tokens.advance(); // consume first selector
956
-
957
- const propertyToken = tokens.peek();
958
- if (!propertyToken || propertyToken.kind !== 'selector') {
959
- tokens.reset(mark);
960
- return null;
961
- }
962
-
963
- // Second token must look like a class selector (starts with .)
964
- // but we interpret it as a property access
965
- if (!propertyToken.value.startsWith('.')) {
966
- tokens.reset(mark);
967
- return null;
968
- }
969
-
970
- // Verify the next token is not a selector (to avoid consuming too many)
971
- // This helps distinguish "#output.innerText" from "#box .child"
972
- const peek2 = tokens.peek(1);
973
- if (peek2 && peek2.kind === 'selector') {
974
- // Could be a compound selector chain - only take first two
975
- }
976
-
977
- tokens.advance(); // consume property selector
978
-
979
- // Create property-path: #output.innerText
980
- // Extract property name without the leading dot
981
- const propertyName = propertyToken.value.slice(1);
982
-
983
- return createPropertyPath(createSelector(token.value), propertyName);
984
- }
985
-
986
466
  /**
987
467
  * Match a group pattern token (optional sequence).
988
468
  * When the group's leading marker isn't at the current position, scans ahead
@@ -1090,7 +570,7 @@ export class PatternMatcher {
1090
570
  }
1091
571
 
1092
572
  // Case-insensitive match for keywords (medium confidence)
1093
- if (token.kind === 'keyword' && this.safeToLowerCase(token.value) === value.toLowerCase()) {
573
+ if (token.kind === 'keyword' && safeToLowerCase(token.value) === value.toLowerCase()) {
1094
574
  return 'case-insensitive';
1095
575
  }
1096
576
 
@@ -1159,97 +639,6 @@ export class PatternMatcher {
1159
639
  // Depth Limits for Expression Parsing (security hardening)
1160
640
  // ==========================================================================
1161
641
 
1162
- /** Maximum depth for nested property access (e.g., a.b.c.d...) */
1163
- private static readonly MAX_PROPERTY_DEPTH = 10;
1164
-
1165
- /** Maximum number of arguments in method calls */
1166
- private static readonly MAX_METHOD_ARGS = 20;
1167
-
1168
- /**
1169
- * Convert a language token to a semantic value.
1170
- */
1171
- private tokenToSemanticValue(token: LanguageToken): SemanticValue | null {
1172
- switch (token.kind) {
1173
- case 'selector':
1174
- return createSelector(token.value);
1175
-
1176
- case 'literal':
1177
- return this.parseLiteralValue(token.value);
1178
-
1179
- case 'keyword':
1180
- // Keywords might be references or values
1181
- const tokenValue = token.normalized || token.value;
1182
- const lower = this.safeToLowerCase(tokenValue);
1183
- if (isValidReference(lower)) {
1184
- return createReference(lower);
1185
- }
1186
- return createLiteral(token.normalized || token.value);
1187
-
1188
- case 'identifier':
1189
- // Check if it's a variable reference (:varname)
1190
- // Note: :varname doesn't match the ReferenceValue union but is used as a
1191
- // reference token downstream — this cast preserves existing behavior
1192
- if (typeof token.value === 'string' && token.value.startsWith(':')) {
1193
- return createReference(token.value as ReferenceValue['value']);
1194
- }
1195
- // Check if it's a built-in reference
1196
- const identLower = this.safeToLowerCase(token.value);
1197
- if (isValidReference(identLower)) {
1198
- return createReference(identLower);
1199
- }
1200
- // Regular identifiers are variable references - use 'expression' type
1201
- // which gets converted to 'identifier' AST nodes by semantic-integration.ts
1202
- return { type: 'expression', raw: token.value } as const;
1203
-
1204
- case 'url':
1205
- // URLs are treated as string literals (paths/URLs for navigation/fetch)
1206
- return createLiteral(token.value, 'string');
1207
-
1208
- default:
1209
- return null;
1210
- }
1211
- }
1212
-
1213
- /**
1214
- * Parse a literal value (string, number, boolean).
1215
- */
1216
- private parseLiteralValue(value: string): SemanticValue {
1217
- // String literal
1218
- if (
1219
- value.startsWith('"') ||
1220
- value.startsWith("'") ||
1221
- value.startsWith('`') ||
1222
- value.startsWith('「')
1223
- ) {
1224
- const inner = value.slice(1, -1);
1225
- return createLiteral(inner, 'string');
1226
- }
1227
-
1228
- // Boolean
1229
- if (value === 'true') return createLiteral(true, 'boolean');
1230
- if (value === 'false') return createLiteral(false, 'boolean');
1231
-
1232
- // Duration (number with suffix)
1233
- const durationMatch = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
1234
- if (durationMatch) {
1235
- const num = parseFloat(durationMatch[1]);
1236
- const unit = durationMatch[2];
1237
- if (unit) {
1238
- return createLiteral(value, 'duration');
1239
- }
1240
- return createLiteral(num, 'number');
1241
- }
1242
-
1243
- // Plain number
1244
- const num = parseFloat(value);
1245
- if (!isNaN(num)) {
1246
- return createLiteral(num, 'number');
1247
- }
1248
-
1249
- // Default to string
1250
- return createLiteral(value, 'string');
1251
- }
1252
-
1253
642
  /**
1254
643
  * Apply extraction rules to fill in static values and defaults for missing roles.
1255
644
  */
@@ -1276,264 +665,10 @@ export class PatternMatcher {
1276
665
  return patternToken.type !== 'literal' && patternToken.optional === true;
1277
666
  }
1278
667
 
1279
- /**
1280
- * Calculate confidence score for a match (0-1).
1281
- *
1282
- * Confidence is reduced for:
1283
- * - Stem matches (morphological normalization has inherent uncertainty)
1284
- * - Missing optional roles (but less penalty if role has a default value)
1285
- *
1286
- * Confidence is increased for:
1287
- * - VSO languages (Arabic) when pattern starts with a verb
1288
- */
1289
- private calculateConfidence(
1290
- pattern: LanguagePattern,
1291
- captured: Map<SemanticRole, SemanticValue>
1292
- ): number {
1293
- let score = 0;
1294
- let maxScore = 0;
1295
-
1296
- // Helper to check if a role has a default value in extraction rules
1297
- const hasDefault = (role: SemanticRole): boolean => {
1298
- return pattern.extraction?.[role]?.default !== undefined;
1299
- };
1300
-
1301
- // Score based on captured roles
1302
- for (const token of pattern.template.tokens) {
1303
- if (token.type === 'role') {
1304
- maxScore += 1;
1305
- if (captured.has(token.role)) {
1306
- score += 1;
1307
- }
1308
- } else if (token.type === 'group') {
1309
- // Group tokens are optional - weight depends on whether they have defaults
1310
- for (const subToken of token.tokens) {
1311
- if (subToken.type === 'role') {
1312
- const roleHasDefault = hasDefault(subToken.role);
1313
- const weight = 0.8; // Optional roles: 80% weight
1314
- maxScore += weight;
1315
-
1316
- if (captured.has(subToken.role)) {
1317
- // Role was explicitly provided by user
1318
- score += weight;
1319
- } else if (roleHasDefault) {
1320
- // Role has a default - give 60% partial credit since command is semantically complete
1321
- // This prevents penalizing common patterns like "toggle .active" (default: me)
1322
- score += weight * 0.6;
1323
- }
1324
- // If no default and not captured, score += 0 (true penalty for missing info)
1325
- }
1326
- }
1327
- }
1328
- }
1329
-
1330
- let baseConfidence = maxScore > 0 ? score / maxScore : 1;
1331
-
1332
- // Apply penalty for stem matches
1333
- // Each stem match reduces confidence slightly (e.g., 5% per stem match)
1334
- // This ensures exact matches are preferred over morphological matches
1335
- if (this.stemMatchCount > 0 && this.totalKeywordMatches > 0) {
1336
- const stemPenalty = (this.stemMatchCount / this.totalKeywordMatches) * 0.15;
1337
- baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);
1338
- }
1339
-
1340
- // Apply VSO confidence boost for Arabic verb-first patterns
1341
- const vsoBoost = this.calculateVSOConfidenceBoost(pattern);
1342
- baseConfidence = Math.min(1.0, baseConfidence + vsoBoost);
1343
-
1344
- // Apply preposition disambiguation adjustment for Arabic
1345
- const prepositionAdjustment = this.arabicPrepositionDisambiguation(pattern, captured);
1346
- baseConfidence = Math.max(0.0, Math.min(1.0, baseConfidence + prepositionAdjustment));
1347
-
1348
- return baseConfidence;
1349
- }
1350
-
1351
- /**
1352
- * Calculate confidence boost for VSO (Verb-Subject-Object) language patterns.
1353
- * Arabic naturally uses VSO word order, so patterns that start with a verb
1354
- * should receive a confidence boost.
1355
- *
1356
- * Returns +0.15 confidence boost if:
1357
- * - Language is Arabic ('ar')
1358
- * - Pattern's first token is a verb keyword
1359
- *
1360
- * @param pattern The language pattern being matched
1361
- * @returns Confidence boost (0 or 0.15)
1362
- */
1363
- private calculateVSOConfidenceBoost(pattern: LanguagePattern): number {
1364
- // Only apply to Arabic
1365
- if (pattern.language !== 'ar') {
1366
- return 0;
1367
- }
1368
-
1369
- // Check if first token in pattern is a literal (keyword)
1370
- const firstToken = pattern.template.tokens[0];
1371
- if (!firstToken || firstToken.type !== 'literal') {
1372
- return 0;
1373
- }
1374
-
1375
- // List of Arabic verb keywords (command verbs)
1376
- const ARABIC_VERBS = new Set([
1377
- 'بدل',
1378
- 'غير',
1379
- 'أضف',
1380
- 'أزل',
1381
- 'ضع',
1382
- 'اجعل',
1383
- 'عين',
1384
- 'زد',
1385
- 'انقص',
1386
- 'سجل',
1387
- 'أظهر',
1388
- 'أخف',
1389
- 'شغل',
1390
- 'أرسل',
1391
- 'ركز',
1392
- 'شوش',
1393
- 'توقف',
1394
- 'انسخ',
1395
- 'احذف',
1396
- 'اصنع',
1397
- 'انتظر',
1398
- 'انتقال',
1399
- 'أو',
1400
- ]);
1401
-
1402
- // Check if first token value is a verb
1403
- if (ARABIC_VERBS.has(firstToken.value)) {
1404
- return 0.15;
1405
- }
1406
-
1407
- // Check alternatives
1408
- if (firstToken.alternatives) {
1409
- for (const alt of firstToken.alternatives) {
1410
- if (ARABIC_VERBS.has(alt)) {
1411
- return 0.15;
1412
- }
1413
- }
1414
- }
1415
-
1416
- return 0;
1417
- }
1418
-
1419
- /**
1420
- * Arabic preposition disambiguation for confidence adjustment.
1421
- *
1422
- * Different Arabic prepositions are more or less natural for different semantic roles:
1423
- * - على (on/upon) is preferred for patient/target roles (element selectors)
1424
- * - إلى (to) is preferred for destination roles
1425
- * - من (from) is preferred for source roles
1426
- * - في (in) is preferred for location roles
1427
- *
1428
- * This method analyzes the prepositions used with captured semantic roles and
1429
- * adjusts confidence based on idiomaticity:
1430
- * - +0.10 for highly idiomatic preposition choices
1431
- * - -0.10 for less natural preposition choices
1432
- *
1433
- * @param pattern The language pattern being matched
1434
- * @param captured The captured semantic values
1435
- * @returns Confidence adjustment (-0.10 to +0.10)
1436
- */
1437
- private arabicPrepositionDisambiguation(
1438
- pattern: LanguagePattern,
1439
- captured: Map<SemanticRole, SemanticValue>
1440
- ): number {
1441
- // Only apply to Arabic
1442
- if (pattern.language !== 'ar') {
1443
- return 0;
1444
- }
1445
-
1446
- let adjustment = 0;
1447
-
1448
- // Preferred prepositions for each semantic role
1449
- // Only including roles that commonly use prepositions in Arabic
1450
- const PREFERRED_PREPOSITIONS: Partial<Record<SemanticRole, string[]>> = {
1451
- patient: ['على'], // element selectors prefer على (on/upon)
1452
- destination: ['إلى', 'الى'], // destination prefers إلى (to)
1453
- source: ['من'], // source prefers من (from)
1454
- agent: ['من'], // agent/by prefers من (from/by)
1455
- manner: ['ب'], // manner prefers ب (with/by)
1456
- style: ['ب'], // style prefers ب (with)
1457
- goal: ['إلى', 'الى'], // target state prefers إلى (to)
1458
- method: ['ب'], // method prefers ب (with/by)
1459
- };
1460
-
1461
- // Check each captured role for preposition metadata
1462
- for (const [role, value] of captured.entries()) {
1463
- // Skip if no preferred prepositions defined for this role
1464
- const preferred = PREFERRED_PREPOSITIONS[role];
1465
- if (!preferred || preferred.length === 0) {
1466
- continue;
1467
- }
1468
-
1469
- // Check if the value has preposition metadata (from Arabic tokenizer)
1470
- // This metadata is attached when a preposition particle token is consumed
1471
- const metadata =
1472
- 'metadata' in value ? (value as { metadata: Record<string, unknown> }).metadata : undefined;
1473
- if (metadata && typeof metadata.prepositionValue === 'string') {
1474
- const usedPreposition = metadata.prepositionValue;
1475
-
1476
- // Check if the used preposition is in the preferred list
1477
- if (preferred.includes(usedPreposition)) {
1478
- // Idiomatic choice - boost confidence
1479
- adjustment += 0.1;
1480
- } else {
1481
- // Less natural choice - reduce confidence
1482
- adjustment -= 0.1;
1483
- }
1484
- }
1485
- }
1486
-
1487
- // Cap total adjustment at ±0.10 (even if multiple roles analyzed)
1488
- return Math.max(-0.1, Math.min(0.1, adjustment));
1489
- }
1490
-
1491
668
  // ===========================================================================
1492
669
  // English Idiom Support - Noise Word Handling
1493
670
  // ===========================================================================
1494
671
 
1495
- /**
1496
- * Noise words that can be skipped in English for more natural syntax.
1497
- * - "the" before selectors: "toggle the .active" → "toggle .active"
1498
- * - "class" after class selectors: "add the .visible class" → "add .visible"
1499
- */
1500
- private static readonly ENGLISH_NOISE_WORDS = new Set(['the', 'a', 'an']);
1501
-
1502
- /**
1503
- * Skip noise words like "the" before selectors.
1504
- * This enables more natural English syntax like "toggle the .active".
1505
- */
1506
- private skipNoiseWords(tokens: TokenStream): void {
1507
- const token = tokens.peek();
1508
- if (!token) return;
1509
-
1510
- const tokenLower = this.safeToLowerCase(token.value);
1511
-
1512
- // Check if current token is a noise word (like "the")
1513
- if (PatternMatcher.ENGLISH_NOISE_WORDS.has(tokenLower)) {
1514
- // Look ahead to see if the next token is a selector
1515
- const mark = tokens.mark();
1516
- tokens.advance();
1517
- const nextToken = tokens.peek();
1518
-
1519
- if (nextToken && nextToken.kind === 'selector') {
1520
- // Keep the position after "the" - effectively skipping it
1521
- return;
1522
- }
1523
-
1524
- // Not followed by a selector, revert
1525
- tokens.reset(mark);
1526
- }
1527
-
1528
- // Also handle "class" after class selectors: ".visible class" → ".visible"
1529
- // This is handled when the selector has already been consumed,
1530
- // so we check if current token is "class" and skip it
1531
- if (tokenLower === 'class') {
1532
- // Skip "class" as it's just noise after a class selector
1533
- tokens.advance();
1534
- }
1535
- }
1536
-
1537
672
  /**
1538
673
  * Extract event modifiers from the token stream.
1539
674
  * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)