@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
@@ -0,0 +1,681 @@
1
+ /**
2
+ * Reading a domain value at a role slot: the value reading framework's old
3
+ * matcher (`core/pattern-matching/`) did, moved here so the stock reader on the
4
+ * matcher's skeleton (`stock-reader.ts`, domains rethink Phase 4.7) and the old
5
+ * matcher run the same code until Phase 6 deletes the old one.
6
+ *
7
+ * In order: an English noise word before a selector (`the`), then the
8
+ * multi-token forms (a possessive, `my value`; a method call,
9
+ * `#dialog.showModal()`; a possessive selector, `#el's *opacity`; a property
10
+ * access, `user.name`; a selector and its property, `#out.innerText`), then one
11
+ * token by its kind (a selector, a quoted string, a number, a boolean, a
12
+ * duration, a URL, an identifier). Each is checked against the slot's
13
+ * expected types.
14
+ */
15
+
16
+ import type {
17
+ PatternToken,
18
+ ReferenceValue,
19
+ SemanticRole,
20
+ SemanticValue,
21
+ TokenStream,
22
+ LanguageToken,
23
+ } from '../types';
24
+ import { createSelector, createLiteral, createReference, createPropertyPath } from '../types';
25
+ import { isTypeCompatible } from '../pattern-matching/utils/type-validation';
26
+ import { getPossessiveReference } from '../pattern-matching/utils/possessive-keywords';
27
+
28
+ /** What value reading needs of a language profile: its code, and its possessive words. */
29
+ export interface ReadingProfile {
30
+ readonly code: string;
31
+ readonly possessive?: {
32
+ readonly keywords?: Record<string, string>;
33
+ };
34
+ }
35
+
36
+ function isValidReference(_value: string): boolean {
37
+ // In generic framework, no built-in references
38
+ // Identifiers should be expressions
39
+ return false;
40
+ }
41
+
42
+ /**
43
+ * Safely convert a value to lowercase string.
44
+ * Provides protection against non-string values at runtime.
45
+ */
46
+ /** `value` lower-cased, whatever it is (the old matcher's keyword compare uses it too). */
47
+ export function safeToLowerCase(value: unknown): string {
48
+ if (typeof value === 'string') {
49
+ return value.toLowerCase();
50
+ }
51
+ if (value === null || value === undefined) {
52
+ return '';
53
+ }
54
+ return String(value).toLowerCase();
55
+ }
56
+
57
+ /**
58
+ * Match a role pattern token (captures a semantic value).
59
+ * Handles multi-token expressions like:
60
+ * - 'my value' (possessive keyword + property)
61
+ * - '#dialog.showModal()' (method call)
62
+ * - "#element's *opacity" (possessive selector + property)
63
+ */
64
+ /**
65
+ * Read a value for `patternToken`'s role at the stream's position into
66
+ * `captured`, and advance past it. False when the slot does not match; an
67
+ * optional slot whose value does not fit returns true and captures nothing.
68
+ */
69
+ export function readRoleValue(
70
+ tokens: TokenStream,
71
+ patternToken: PatternToken & { type: 'role' },
72
+ captured: Map<SemanticRole, SemanticValue>,
73
+ profile?: ReadingProfile
74
+ ): boolean {
75
+ // Skip noise words like "the" before selectors (English idiom support)
76
+ skipNoiseWords(tokens);
77
+
78
+ const token = tokens.peek();
79
+ if (!token) {
80
+ return patternToken.optional || false;
81
+ }
82
+
83
+ // Check for possessive expression (e.g., 'my value', 'its innerHTML')
84
+ const possessiveValue = tryMatchPossessiveExpression(tokens, profile);
85
+ if (possessiveValue) {
86
+ // Validate expected types if specified
87
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
88
+ if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {
89
+ return patternToken.optional || false;
90
+ }
91
+ }
92
+ captured.set(patternToken.role, possessiveValue);
93
+ return true;
94
+ }
95
+
96
+ // Check for method call expression (e.g., '#dialog.showModal()')
97
+ const methodCallValue = tryMatchMethodCallExpression(tokens);
98
+ if (methodCallValue) {
99
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
100
+ if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {
101
+ return patternToken.optional || false;
102
+ }
103
+ }
104
+ captured.set(patternToken.role, methodCallValue);
105
+ return true;
106
+ }
107
+
108
+ // Check for possessive selector expression (e.g., "#element's *opacity")
109
+ const possessiveSelectorValue = tryMatchPossessiveSelectorExpression(tokens);
110
+ if (possessiveSelectorValue) {
111
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
112
+ // property-path is compatible with selector, reference, and expression
113
+ if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {
114
+ return patternToken.optional || false;
115
+ }
116
+ }
117
+ captured.set(patternToken.role, possessiveSelectorValue);
118
+ return true;
119
+ }
120
+
121
+ // Check for property access expression (e.g., 'userData.name', 'it.data')
122
+ const propertyAccessValue = tryMatchPropertyAccessExpression(tokens);
123
+ if (propertyAccessValue) {
124
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
125
+ if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {
126
+ return patternToken.optional || false;
127
+ }
128
+ }
129
+ captured.set(patternToken.role, propertyAccessValue);
130
+ return true;
131
+ }
132
+
133
+ // Check for selector + property expression (e.g., '#output.innerText')
134
+ // This handles cases where the tokenizer produces two selector tokens
135
+ const selectorPropertyValue = tryMatchSelectorPropertyExpression(tokens);
136
+ if (selectorPropertyValue) {
137
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
138
+ if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {
139
+ return patternToken.optional || false;
140
+ }
141
+ }
142
+ captured.set(patternToken.role, selectorPropertyValue);
143
+ return true;
144
+ }
145
+
146
+ // Try to extract a semantic value from the token
147
+ const value = tokenToSemanticValue(token);
148
+ if (!value) {
149
+ return patternToken.optional || false;
150
+ }
151
+
152
+ // Validate expected types if specified
153
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
154
+ if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {
155
+ return patternToken.optional || false;
156
+ }
157
+ }
158
+
159
+ captured.set(patternToken.role, value);
160
+ tokens.advance();
161
+ return true;
162
+ }
163
+
164
+ /**
165
+ * Try to match a possessive expression like 'my value' or 'its innerHTML'.
166
+ * Returns the PropertyPathValue if matched, or null if not.
167
+ */
168
+ function tryMatchPossessiveExpression(
169
+ tokens: TokenStream,
170
+ profile: ReadingProfile | undefined
171
+ ): SemanticValue | null {
172
+ const token = tokens.peek();
173
+ if (!token) return null;
174
+
175
+ // Use profile-based possessive keyword lookup
176
+ if (!profile) return null;
177
+
178
+ const tokenValue = token.normalized || token.value;
179
+ const tokenLower = safeToLowerCase(tokenValue);
180
+ const baseRef = getPossessiveReference(profile, tokenLower);
181
+
182
+ if (!baseRef) return null;
183
+
184
+ // We have a possessive keyword, look ahead for property name
185
+ const mark = tokens.mark();
186
+ tokens.advance();
187
+
188
+ const propertyToken = tokens.peek();
189
+ if (!propertyToken) {
190
+ // Just the possessive keyword, no property - revert
191
+ tokens.reset(mark);
192
+ return null;
193
+ }
194
+
195
+ // Property should be an identifier, keyword (not structural), or selector (for style/dot/attr)
196
+ // Examples: "my value", "my innerHTML", "my *background", "my *opacity", "my @data-count"
197
+ // Also handles dot-property access: "my.textContent" tokenized as "my" + ".textContent"
198
+ if (
199
+ propertyToken.kind === 'identifier' ||
200
+ (propertyToken.kind === 'keyword' && !isStructuralKeyword(propertyToken.value)) ||
201
+ (propertyToken.kind === 'selector' && propertyToken.value.startsWith('*')) ||
202
+ (propertyToken.kind === 'selector' && propertyToken.value.startsWith('@')) ||
203
+ (propertyToken.kind === 'selector' &&
204
+ propertyToken.value.startsWith('.') &&
205
+ /^\.[a-zA-Z_]\w*/.test(propertyToken.value))
206
+ ) {
207
+ tokens.advance();
208
+
209
+ // For dot-property selectors (.textContent), strip the leading dot
210
+ let propertyName = propertyToken.value;
211
+ if (
212
+ propertyToken.kind === 'selector' &&
213
+ propertyName.startsWith('.') &&
214
+ /^\.[a-zA-Z_]\w*/.test(propertyName)
215
+ ) {
216
+ propertyName = propertyName.substring(1);
217
+ }
218
+
219
+ // Consume chained dot-property access (.parentElement.style.display)
220
+ let chainedProps = propertyName;
221
+ while (
222
+ tokens.peek()?.kind === 'selector' &&
223
+ tokens.peek()!.value.startsWith('.') &&
224
+ /^\.[a-zA-Z_]\w*/.test(tokens.peek()!.value)
225
+ ) {
226
+ chainedProps += tokens.peek()!.value; // keep the dots for chaining
227
+ tokens.advance();
228
+ }
229
+
230
+ // Check for method call — next token is '(' in the value (e.g., .getAttribute("data-id"))
231
+ const nextPeek = tokens.peek();
232
+ if (nextPeek?.kind === 'literal' && nextPeek.value.startsWith('(')) {
233
+ // Consume method args
234
+ chainedProps += nextPeek.value;
235
+ tokens.advance();
236
+ }
237
+
238
+ // Create property-path: my value -> { object: me, property: 'value' }
239
+ // baseRef from getPossessiveReference is always a valid reference ('me', 'you', 'it', etc.)
240
+ return createPropertyPath(createReference(baseRef as ReferenceValue['value']), chainedProps);
241
+ }
242
+
243
+ // Not a valid property, revert
244
+ tokens.reset(mark);
245
+ return null;
246
+ }
247
+
248
+ /**
249
+ * Check if a keyword is a structural keyword (preposition, control flow, etc.)
250
+ * that shouldn't be consumed as a property name.
251
+ */
252
+ function isStructuralKeyword(value: string): boolean {
253
+ const structural = new Set([
254
+ // Prepositions
255
+ 'into',
256
+ 'in',
257
+ 'to',
258
+ 'from',
259
+ 'at',
260
+ 'by',
261
+ 'with',
262
+ 'without',
263
+ 'before',
264
+ 'after',
265
+ 'of',
266
+ 'as',
267
+ 'on',
268
+ // Control flow
269
+ 'then',
270
+ 'end',
271
+ 'else',
272
+ 'if',
273
+ 'repeat',
274
+ 'while',
275
+ 'for',
276
+ // Commands (shouldn't be property names)
277
+ 'toggle',
278
+ 'add',
279
+ 'remove',
280
+ 'put',
281
+ 'set',
282
+ 'show',
283
+ 'hide',
284
+ 'increment',
285
+ 'decrement',
286
+ 'send',
287
+ 'trigger',
288
+ 'call',
289
+ ]);
290
+ return structural.has(value.toLowerCase());
291
+ }
292
+
293
+ /**
294
+ * Try to match a method call expression like '#dialog.showModal()'.
295
+ * Pattern: selector + '.' + identifier + '(' + [args] + ')'
296
+ * Returns an expression value if matched, or null if not.
297
+ */
298
+ function tryMatchMethodCallExpression(tokens: TokenStream): SemanticValue | null {
299
+ const token = tokens.peek();
300
+ if (!token || token.kind !== 'selector') return null;
301
+
302
+ // Look ahead for: . identifier (
303
+ const mark = tokens.mark();
304
+ tokens.advance(); // consume selector
305
+
306
+ const dotToken = tokens.peek();
307
+ if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {
308
+ tokens.reset(mark);
309
+ return null;
310
+ }
311
+ tokens.advance(); // consume .
312
+
313
+ const methodToken = tokens.peek();
314
+ if (!methodToken || methodToken.kind !== 'identifier') {
315
+ tokens.reset(mark);
316
+ return null;
317
+ }
318
+ tokens.advance(); // consume method name
319
+
320
+ const openParen = tokens.peek();
321
+ if (!openParen || openParen.kind !== 'punctuation' || openParen.value !== '(') {
322
+ tokens.reset(mark);
323
+ return null;
324
+ }
325
+ tokens.advance(); // consume (
326
+
327
+ // Consume arguments until we find ) (with depth limit for security)
328
+ const args: string[] = [];
329
+ while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {
330
+ const argToken = tokens.peek();
331
+ if (!argToken) break;
332
+ if (argToken.kind === 'punctuation' && argToken.value === ')') {
333
+ tokens.advance(); // consume )
334
+ break;
335
+ }
336
+ // Skip commas
337
+ if (argToken.kind === 'punctuation' && argToken.value === ',') {
338
+ tokens.advance();
339
+ continue;
340
+ }
341
+ // Collect arg value
342
+ args.push(argToken.value);
343
+ tokens.advance();
344
+ }
345
+
346
+ // Create expression value: #dialog.showModal()
347
+ const methodCall = `${token.value}.${methodToken.value}(${args.join(', ')})`;
348
+ return {
349
+ type: 'expression',
350
+ raw: methodCall,
351
+ } as SemanticValue;
352
+ }
353
+
354
+ /**
355
+ * Try to match a property access expression like 'userData.name' or 'it.data'.
356
+ * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]
357
+ * Returns an expression value if matched, or null if not.
358
+ */
359
+ function tryMatchPropertyAccessExpression(tokens: TokenStream): SemanticValue | null {
360
+ const token = tokens.peek();
361
+ if (!token) return null;
362
+
363
+ // Must start with an identifier or keyword reference
364
+ if (token.kind !== 'identifier' && token.kind !== 'keyword') return null;
365
+
366
+ // Look ahead for: . identifier
367
+ const mark = tokens.mark();
368
+ tokens.advance(); // consume first token
369
+
370
+ const dotToken = tokens.peek();
371
+ if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {
372
+ tokens.reset(mark);
373
+ return null;
374
+ }
375
+ tokens.advance(); // consume .
376
+
377
+ const propertyToken = tokens.peek();
378
+ if (!propertyToken || propertyToken.kind !== 'identifier') {
379
+ tokens.reset(mark);
380
+ return null;
381
+ }
382
+ tokens.advance(); // consume property name
383
+
384
+ // Build the property chain
385
+ let chain = `${token.value}.${propertyToken.value}`;
386
+ let depth = 1; // Already have one property access
387
+
388
+ // Continue for nested property access (e.g., userData.address.city)
389
+ // With depth limit for security
390
+ while (!tokens.isAtEnd() && depth < MAX_PROPERTY_DEPTH) {
391
+ const nextDot = tokens.peek();
392
+ if (!nextDot || nextDot.kind !== 'operator' || nextDot.value !== '.') {
393
+ break;
394
+ }
395
+ tokens.advance(); // consume .
396
+
397
+ const nextProp = tokens.peek();
398
+ if (!nextProp || nextProp.kind !== 'identifier') {
399
+ // Dot without property - put the dot back and stop
400
+ // Can't easily put a single token back, so we'll include it
401
+ break;
402
+ }
403
+ tokens.advance(); // consume property
404
+ chain += `.${nextProp.value}`;
405
+ depth++;
406
+ }
407
+
408
+ // Check for method call: chain + '(' + args + ')'
409
+ // e.g., me.insertBefore(draggedItem, dropTarget)
410
+ const openParen = tokens.peek();
411
+ if (openParen && openParen.kind === 'punctuation' && openParen.value === '(') {
412
+ tokens.advance(); // consume (
413
+
414
+ // Collect arguments (comma-separated values)
415
+ const args: string[] = [];
416
+ let argDepth = 0; // Track nested parentheses
417
+ while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {
418
+ const argToken = tokens.peek();
419
+ if (!argToken) break;
420
+
421
+ // Handle close paren - respecting nesting
422
+ if (argToken.kind === 'punctuation' && argToken.value === ')') {
423
+ if (argDepth === 0) {
424
+ tokens.advance(); // consume )
425
+ break;
426
+ }
427
+ argDepth--;
428
+ }
429
+ // Track nested open parens
430
+ if (argToken.kind === 'punctuation' && argToken.value === '(') {
431
+ argDepth++;
432
+ }
433
+ // Skip commas between arguments
434
+ if (argToken.kind === 'punctuation' && argToken.value === ',') {
435
+ tokens.advance();
436
+ continue;
437
+ }
438
+ // Collect arg value
439
+ args.push(argToken.value);
440
+ tokens.advance();
441
+ }
442
+
443
+ // Create expression value with method call: me.insertBefore(a, b)
444
+ const methodCall = `${chain}(${args.join(', ')})`;
445
+ return {
446
+ type: 'expression',
447
+ raw: methodCall,
448
+ } as SemanticValue;
449
+ }
450
+
451
+ // Create expression value: userData.name
452
+ return {
453
+ type: 'expression',
454
+ raw: chain,
455
+ } as SemanticValue;
456
+ }
457
+
458
+ /**
459
+ * Try to match a possessive selector expression like "#element's *opacity".
460
+ * Pattern: selector + "'s" + (selector | identifier)
461
+ * Returns a property-path value if matched, or null if not.
462
+ */
463
+ function tryMatchPossessiveSelectorExpression(tokens: TokenStream): SemanticValue | null {
464
+ const token = tokens.peek();
465
+ if (!token || token.kind !== 'selector') return null;
466
+
467
+ // Look ahead for: 's (possessive marker)
468
+ const mark = tokens.mark();
469
+ tokens.advance(); // consume selector
470
+
471
+ const possessiveToken = tokens.peek();
472
+ if (
473
+ !possessiveToken ||
474
+ possessiveToken.kind !== 'punctuation' ||
475
+ possessiveToken.value !== "'s"
476
+ ) {
477
+ tokens.reset(mark);
478
+ return null;
479
+ }
480
+ tokens.advance(); // consume 's
481
+
482
+ const propertyToken = tokens.peek();
483
+ if (!propertyToken) {
484
+ tokens.reset(mark);
485
+ return null;
486
+ }
487
+
488
+ // Property can be a selector (*opacity) or identifier
489
+ if (propertyToken.kind !== 'selector' && propertyToken.kind !== 'identifier') {
490
+ tokens.reset(mark);
491
+ return null;
492
+ }
493
+ tokens.advance(); // consume property
494
+
495
+ // Create property-path: #element's *opacity
496
+ return createPropertyPath(createSelector(token.value), propertyToken.value);
497
+ }
498
+
499
+ /**
500
+ * Try to match a selector + property expression like "#output.innerText".
501
+ * This handles cases where the tokenizer produces two selector tokens:
502
+ * - #output (id selector)
503
+ * - .innerText (looks like class selector, but is actually property)
504
+ *
505
+ * Pattern: id-selector + class-selector-that-is-actually-property
506
+ * Returns a property-path value if matched, or null if not.
507
+ */
508
+ function tryMatchSelectorPropertyExpression(tokens: TokenStream): SemanticValue | null {
509
+ const token = tokens.peek();
510
+ if (!token || token.kind !== 'selector') return null;
511
+
512
+ // Must be an ID selector (starts with #)
513
+ if (typeof token.value !== 'string' || !token.value.startsWith('#')) return null;
514
+
515
+ // Look ahead for: selector that looks like a property (.something)
516
+ const mark = tokens.mark();
517
+ tokens.advance(); // consume first selector
518
+
519
+ const propertyToken = tokens.peek();
520
+ if (!propertyToken || propertyToken.kind !== 'selector') {
521
+ tokens.reset(mark);
522
+ return null;
523
+ }
524
+
525
+ // Second token must look like a class selector (starts with .)
526
+ // but we interpret it as a property access
527
+ if (!propertyToken.value.startsWith('.')) {
528
+ tokens.reset(mark);
529
+ return null;
530
+ }
531
+
532
+ // Verify the next token is not a selector (to avoid consuming too many)
533
+ // This helps distinguish "#output.innerText" from "#box .child"
534
+ const peek2 = tokens.peek(1);
535
+ if (peek2 && peek2.kind === 'selector') {
536
+ // Could be a compound selector chain - only take first two
537
+ }
538
+
539
+ tokens.advance(); // consume property selector
540
+
541
+ // Create property-path: #output.innerText
542
+ // Extract property name without the leading dot
543
+ const propertyName = propertyToken.value.slice(1);
544
+
545
+ return createPropertyPath(createSelector(token.value), propertyName);
546
+ }
547
+
548
+ /** Maximum depth for nested property access (e.g., a.b.c.d...) */
549
+ const MAX_PROPERTY_DEPTH = 10;
550
+
551
+ /** Maximum number of arguments in method calls */
552
+ const MAX_METHOD_ARGS = 20;
553
+
554
+ /**
555
+ * Convert a language token to a semantic value.
556
+ */
557
+ function tokenToSemanticValue(token: LanguageToken): SemanticValue | null {
558
+ switch (token.kind) {
559
+ case 'selector':
560
+ return createSelector(token.value);
561
+
562
+ case 'literal':
563
+ return parseLiteralValue(token.value);
564
+
565
+ case 'keyword': {
566
+ // Keywords might be references or values
567
+ const tokenValue = token.normalized || token.value;
568
+ const lower = safeToLowerCase(tokenValue);
569
+ if (isValidReference(lower)) {
570
+ return createReference(lower);
571
+ }
572
+ return createLiteral(token.normalized || token.value);
573
+ }
574
+
575
+ case 'identifier': {
576
+ // Check if it's a variable reference (:varname)
577
+ // Note: :varname doesn't match the ReferenceValue union but is used as a
578
+ // reference token downstream — this cast preserves existing behavior
579
+ if (typeof token.value === 'string' && token.value.startsWith(':')) {
580
+ return createReference(token.value as ReferenceValue['value']);
581
+ }
582
+ // Check if it's a built-in reference
583
+ const identLower = safeToLowerCase(token.value);
584
+ if (isValidReference(identLower)) {
585
+ return createReference(identLower);
586
+ }
587
+ // Regular identifiers are variable references - use 'expression' type
588
+ // which gets converted to 'identifier' AST nodes by semantic-integration.ts
589
+ return { type: 'expression', raw: token.value } as const;
590
+ }
591
+
592
+ case 'url':
593
+ // URLs are treated as string literals (paths/URLs for navigation/fetch)
594
+ return createLiteral(token.value, 'string');
595
+
596
+ default:
597
+ return null;
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Parse a literal value (string, number, boolean).
603
+ */
604
+ function parseLiteralValue(value: string): SemanticValue {
605
+ // String literal
606
+ if (
607
+ value.startsWith('"') ||
608
+ value.startsWith("'") ||
609
+ value.startsWith('`') ||
610
+ value.startsWith('「')
611
+ ) {
612
+ const inner = value.slice(1, -1);
613
+ return createLiteral(inner, 'string');
614
+ }
615
+
616
+ // Boolean
617
+ if (value === 'true') return createLiteral(true, 'boolean');
618
+ if (value === 'false') return createLiteral(false, 'boolean');
619
+
620
+ // Duration (number with suffix)
621
+ const durationMatch = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
622
+ if (durationMatch) {
623
+ const num = parseFloat(durationMatch[1]);
624
+ const unit = durationMatch[2];
625
+ if (unit) {
626
+ return createLiteral(value, 'duration');
627
+ }
628
+ return createLiteral(num, 'number');
629
+ }
630
+
631
+ // Plain number
632
+ const num = parseFloat(value);
633
+ if (!isNaN(num)) {
634
+ return createLiteral(num, 'number');
635
+ }
636
+
637
+ // Default to string
638
+ return createLiteral(value, 'string');
639
+ }
640
+
641
+ /**
642
+ * Noise words that can be skipped in English for more natural syntax.
643
+ * - "the" before selectors: "toggle the .active" → "toggle .active"
644
+ * - "class" after class selectors: "add the .visible class" → "add .visible"
645
+ */
646
+ const ENGLISH_NOISE_WORDS = new Set(['the', 'a', 'an']);
647
+
648
+ /**
649
+ * Skip noise words like "the" before selectors.
650
+ * This enables more natural English syntax like "toggle the .active".
651
+ */
652
+ function skipNoiseWords(tokens: TokenStream): void {
653
+ const token = tokens.peek();
654
+ if (!token) return;
655
+
656
+ const tokenLower = safeToLowerCase(token.value);
657
+
658
+ // Check if current token is a noise word (like "the")
659
+ if (ENGLISH_NOISE_WORDS.has(tokenLower)) {
660
+ // Look ahead to see if the next token is a selector
661
+ const mark = tokens.mark();
662
+ tokens.advance();
663
+ const nextToken = tokens.peek();
664
+
665
+ if (nextToken && nextToken.kind === 'selector') {
666
+ // Keep the position after "the" - effectively skipping it
667
+ return;
668
+ }
669
+
670
+ // Not followed by a selector, revert
671
+ tokens.reset(mark);
672
+ }
673
+
674
+ // Also handle "class" after class selectors: ".visible class" → ".visible"
675
+ // This is handled when the selector has already been consumed,
676
+ // so we check if current token is "class" and skip it
677
+ if (tokenLower === 'class') {
678
+ // Skip "class" as it's just noise after a class selector
679
+ tokens.advance();
680
+ }
681
+ }