@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.
- package/CHANGELOG.md +220 -8
- package/dist/api/create-dsl.d.ts +59 -1
- package/dist/api/create-dsl.d.ts.map +1 -1
- package/dist/api/domain-registry.d.ts.map +1 -1
- package/dist/api/index.d.ts +1 -0
- package/dist/api/index.d.ts.map +1 -1
- package/dist/api/index.js +1938 -724
- package/dist/api/index.js.map +1 -1
- package/dist/api/reading.d.ts +8 -0
- package/dist/api/reading.d.ts.map +1 -0
- package/dist/api/translation-loss.d.ts +84 -0
- package/dist/api/translation-loss.d.ts.map +1 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1047 -684
- package/dist/core/index.js.map +1 -1
- package/dist/core/matching/confidence-model.d.ts +54 -0
- package/dist/core/matching/confidence-model.d.ts.map +1 -0
- package/dist/core/matching/index.d.ts +12 -0
- package/dist/core/matching/index.d.ts.map +1 -0
- package/dist/core/matching/match-skeleton.d.ts +114 -0
- package/dist/core/matching/match-skeleton.d.ts.map +1 -0
- package/dist/core/matching/stock-confidence.d.ts +15 -0
- package/dist/core/matching/stock-confidence.d.ts.map +1 -0
- package/dist/core/matching/stock-reader.d.ts +56 -0
- package/dist/core/matching/stock-reader.d.ts.map +1 -0
- package/dist/core/matching/stock-reading.d.ts +44 -0
- package/dist/core/matching/stock-reading.d.ts.map +1 -0
- package/dist/core/matching/value-reader.d.ts +62 -0
- package/dist/core/matching/value-reader.d.ts.map +1 -0
- package/dist/core/pattern-matching/index.js +561 -660
- package/dist/core/pattern-matching/index.js.map +1 -1
- package/dist/core/pattern-matching/pattern-matcher.d.ts +0 -117
- package/dist/core/pattern-matching/pattern-matcher.d.ts.map +1 -1
- package/dist/core/types.d.ts +48 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js.map +1 -1
- package/dist/generation/index.d.ts +2 -0
- package/dist/generation/index.d.ts.map +1 -1
- package/dist/generation/index.js +583 -1
- package/dist/generation/index.js.map +1 -1
- package/dist/generation/pattern-render.d.ts +72 -0
- package/dist/generation/pattern-render.d.ts.map +1 -0
- package/dist/generation/schema-patterns.d.ts +152 -0
- package/dist/generation/schema-patterns.d.ts.map +1 -0
- package/dist/index.cjs +2132 -890
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2110 -887
- package/dist/index.js.map +1 -1
- package/dist/ir/index.js.map +1 -1
- package/dist/parsing/index.js +561 -660
- package/dist/parsing/index.js.map +1 -1
- package/dist/testing/gate/index.d.ts +8 -0
- package/dist/testing/gate/index.d.ts.map +1 -0
- package/dist/testing/gate/index.js +632 -0
- package/dist/testing/gate/index.js.map +1 -0
- package/dist/testing/gate/lint/format.d.ts +7 -0
- package/dist/testing/gate/lint/format.d.ts.map +1 -0
- package/dist/testing/gate/lint/index.d.ts +30 -0
- package/dist/testing/gate/lint/index.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/extractor-coverage.d.ts +18 -0
- package/dist/testing/gate/lint/rules/extractor-coverage.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/index.d.ts +14 -0
- package/dist/testing/gate/lint/rules/index.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/keyword-classification.d.ts +19 -0
- package/dist/testing/gate/lint/rules/keyword-classification.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/keyword-coverage.d.ts +13 -0
- package/dist/testing/gate/lint/rules/keyword-coverage.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/marker-tokenization.d.ts +20 -0
- package/dist/testing/gate/lint/rules/marker-tokenization.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/position-ordering.d.ts +25 -0
- package/dist/testing/gate/lint/rules/position-ordering.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/renderer-coherence.d.ts +24 -0
- package/dist/testing/gate/lint/rules/renderer-coherence.d.ts.map +1 -0
- package/dist/testing/gate/lint/rules/schema-rules.d.ts +10 -0
- package/dist/testing/gate/lint/rules/schema-rules.d.ts.map +1 -0
- package/dist/testing/gate/lint/types.d.ts +74 -0
- package/dist/testing/gate/lint/types.d.ts.map +1 -0
- package/dist/testing/gate/round-trip.d.ts +163 -0
- package/dist/testing/gate/round-trip.d.ts.map +1 -0
- package/package.json +7 -3
- package/src/__test__/fixtures/sql-dsl.ts +11 -2
- package/src/__test__/sql-integration.test.ts +2 -2
- package/src/api/create-dsl-engine.test.ts +86 -0
- package/src/api/create-dsl.test.ts +120 -0
- package/src/api/create-dsl.ts +314 -39
- package/src/api/domain-registry.test.ts +70 -5
- package/src/api/domain-registry.ts +82 -1
- package/src/api/index.ts +1 -0
- package/src/api/reading.ts +29 -0
- package/src/api/translation-loss.test.ts +89 -0
- package/src/api/translation-loss.ts +128 -0
- package/src/core/index.ts +1 -0
- package/src/core/matching/confidence-model.ts +58 -0
- package/src/core/matching/index.ts +12 -0
- package/src/core/matching/match-skeleton.test.ts +179 -0
- package/src/core/matching/match-skeleton.ts +621 -0
- package/src/core/matching/stock-confidence.ts +238 -0
- package/src/core/matching/stock-reader.test.ts +181 -0
- package/src/core/matching/stock-reader.ts +186 -0
- package/src/core/matching/stock-reading.ts +681 -0
- package/src/core/matching/value-reader.ts +85 -0
- package/src/core/pattern-matching/pattern-matcher.ts +11 -876
- package/src/core/types.ts +48 -0
- package/src/generation/index.ts +2 -0
- package/src/generation/pattern-render.ts +378 -0
- package/src/generation/schema-patterns.test.ts +99 -0
- package/src/generation/schema-patterns.ts +962 -0
- package/src/testing/gate/index.ts +8 -0
- package/src/testing/gate/lint/format.ts +23 -0
- package/src/testing/gate/lint/index.ts +73 -0
- package/src/testing/gate/lint/lint.test.ts +131 -0
- package/src/testing/gate/lint/rules/extractor-coverage.ts +63 -0
- package/src/testing/gate/lint/rules/index.ts +37 -0
- package/src/testing/gate/lint/rules/keyword-classification.ts +52 -0
- package/src/testing/gate/lint/rules/keyword-coverage.ts +38 -0
- package/src/testing/gate/lint/rules/marker-tokenization.ts +129 -0
- package/src/testing/gate/lint/rules/position-ordering.ts +87 -0
- package/src/testing/gate/lint/rules/renderer-coherence.ts +100 -0
- package/src/testing/gate/lint/rules/schema-rules.ts +35 -0
- package/src/testing/gate/lint/types.ts +83 -0
- package/src/testing/gate/round-trip.test.ts +118 -0
- package/src/testing/gate/round-trip.ts +438 -0
package/dist/index.js
CHANGED
|
@@ -150,10 +150,535 @@ function getAllPossessiveKeywords(profile) {
|
|
|
150
150
|
return profile?.possessive?.keywords ?? {};
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
-
// src/core/
|
|
153
|
+
// src/core/matching/stock-reading.ts
|
|
154
154
|
function isValidReference(_value) {
|
|
155
155
|
return false;
|
|
156
156
|
}
|
|
157
|
+
function safeToLowerCase(value) {
|
|
158
|
+
if (typeof value === "string") {
|
|
159
|
+
return value.toLowerCase();
|
|
160
|
+
}
|
|
161
|
+
if (value === null || value === void 0) {
|
|
162
|
+
return "";
|
|
163
|
+
}
|
|
164
|
+
return String(value).toLowerCase();
|
|
165
|
+
}
|
|
166
|
+
function readRoleValue(tokens, patternToken, captured, profile) {
|
|
167
|
+
skipNoiseWords(tokens);
|
|
168
|
+
const token = tokens.peek();
|
|
169
|
+
if (!token) {
|
|
170
|
+
return patternToken.optional || false;
|
|
171
|
+
}
|
|
172
|
+
const possessiveValue = tryMatchPossessiveExpression(tokens, profile);
|
|
173
|
+
if (possessiveValue) {
|
|
174
|
+
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
175
|
+
if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {
|
|
176
|
+
return patternToken.optional || false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
captured.set(patternToken.role, possessiveValue);
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
const methodCallValue = tryMatchMethodCallExpression(tokens);
|
|
183
|
+
if (methodCallValue) {
|
|
184
|
+
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
185
|
+
if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {
|
|
186
|
+
return patternToken.optional || false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
captured.set(patternToken.role, methodCallValue);
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
const possessiveSelectorValue = tryMatchPossessiveSelectorExpression(tokens);
|
|
193
|
+
if (possessiveSelectorValue) {
|
|
194
|
+
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
195
|
+
if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {
|
|
196
|
+
return patternToken.optional || false;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
captured.set(patternToken.role, possessiveSelectorValue);
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
const propertyAccessValue = tryMatchPropertyAccessExpression(tokens);
|
|
203
|
+
if (propertyAccessValue) {
|
|
204
|
+
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
205
|
+
if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {
|
|
206
|
+
return patternToken.optional || false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
captured.set(patternToken.role, propertyAccessValue);
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
const selectorPropertyValue = tryMatchSelectorPropertyExpression(tokens);
|
|
213
|
+
if (selectorPropertyValue) {
|
|
214
|
+
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
215
|
+
if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {
|
|
216
|
+
return patternToken.optional || false;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
captured.set(patternToken.role, selectorPropertyValue);
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
const value = tokenToSemanticValue(token);
|
|
223
|
+
if (!value) {
|
|
224
|
+
return patternToken.optional || false;
|
|
225
|
+
}
|
|
226
|
+
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
227
|
+
if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {
|
|
228
|
+
return patternToken.optional || false;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
captured.set(patternToken.role, value);
|
|
232
|
+
tokens.advance();
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
function tryMatchPossessiveExpression(tokens, profile) {
|
|
236
|
+
const token = tokens.peek();
|
|
237
|
+
if (!token) return null;
|
|
238
|
+
if (!profile) return null;
|
|
239
|
+
const tokenValue = token.normalized || token.value;
|
|
240
|
+
const tokenLower = safeToLowerCase(tokenValue);
|
|
241
|
+
const baseRef = getPossessiveReference(profile, tokenLower);
|
|
242
|
+
if (!baseRef) return null;
|
|
243
|
+
const mark = tokens.mark();
|
|
244
|
+
tokens.advance();
|
|
245
|
+
const propertyToken = tokens.peek();
|
|
246
|
+
if (!propertyToken) {
|
|
247
|
+
tokens.reset(mark);
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
if (propertyToken.kind === "identifier" || propertyToken.kind === "keyword" && !isStructuralKeyword(propertyToken.value) || propertyToken.kind === "selector" && propertyToken.value.startsWith("*") || propertyToken.kind === "selector" && propertyToken.value.startsWith("@") || propertyToken.kind === "selector" && propertyToken.value.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(propertyToken.value)) {
|
|
251
|
+
tokens.advance();
|
|
252
|
+
let propertyName = propertyToken.value;
|
|
253
|
+
if (propertyToken.kind === "selector" && propertyName.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(propertyName)) {
|
|
254
|
+
propertyName = propertyName.substring(1);
|
|
255
|
+
}
|
|
256
|
+
let chainedProps = propertyName;
|
|
257
|
+
while (tokens.peek()?.kind === "selector" && tokens.peek().value.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(tokens.peek().value)) {
|
|
258
|
+
chainedProps += tokens.peek().value;
|
|
259
|
+
tokens.advance();
|
|
260
|
+
}
|
|
261
|
+
const nextPeek = tokens.peek();
|
|
262
|
+
if (nextPeek?.kind === "literal" && nextPeek.value.startsWith("(")) {
|
|
263
|
+
chainedProps += nextPeek.value;
|
|
264
|
+
tokens.advance();
|
|
265
|
+
}
|
|
266
|
+
return createPropertyPath(createReference(baseRef), chainedProps);
|
|
267
|
+
}
|
|
268
|
+
tokens.reset(mark);
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
function isStructuralKeyword(value) {
|
|
272
|
+
const structural = /* @__PURE__ */ new Set([
|
|
273
|
+
// Prepositions
|
|
274
|
+
"into",
|
|
275
|
+
"in",
|
|
276
|
+
"to",
|
|
277
|
+
"from",
|
|
278
|
+
"at",
|
|
279
|
+
"by",
|
|
280
|
+
"with",
|
|
281
|
+
"without",
|
|
282
|
+
"before",
|
|
283
|
+
"after",
|
|
284
|
+
"of",
|
|
285
|
+
"as",
|
|
286
|
+
"on",
|
|
287
|
+
// Control flow
|
|
288
|
+
"then",
|
|
289
|
+
"end",
|
|
290
|
+
"else",
|
|
291
|
+
"if",
|
|
292
|
+
"repeat",
|
|
293
|
+
"while",
|
|
294
|
+
"for",
|
|
295
|
+
// Commands (shouldn't be property names)
|
|
296
|
+
"toggle",
|
|
297
|
+
"add",
|
|
298
|
+
"remove",
|
|
299
|
+
"put",
|
|
300
|
+
"set",
|
|
301
|
+
"show",
|
|
302
|
+
"hide",
|
|
303
|
+
"increment",
|
|
304
|
+
"decrement",
|
|
305
|
+
"send",
|
|
306
|
+
"trigger",
|
|
307
|
+
"call"
|
|
308
|
+
]);
|
|
309
|
+
return structural.has(value.toLowerCase());
|
|
310
|
+
}
|
|
311
|
+
function tryMatchMethodCallExpression(tokens) {
|
|
312
|
+
const token = tokens.peek();
|
|
313
|
+
if (!token || token.kind !== "selector") return null;
|
|
314
|
+
const mark = tokens.mark();
|
|
315
|
+
tokens.advance();
|
|
316
|
+
const dotToken = tokens.peek();
|
|
317
|
+
if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
|
|
318
|
+
tokens.reset(mark);
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
tokens.advance();
|
|
322
|
+
const methodToken = tokens.peek();
|
|
323
|
+
if (!methodToken || methodToken.kind !== "identifier") {
|
|
324
|
+
tokens.reset(mark);
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
tokens.advance();
|
|
328
|
+
const openParen = tokens.peek();
|
|
329
|
+
if (!openParen || openParen.kind !== "punctuation" || openParen.value !== "(") {
|
|
330
|
+
tokens.reset(mark);
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
tokens.advance();
|
|
334
|
+
const args = [];
|
|
335
|
+
while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {
|
|
336
|
+
const argToken = tokens.peek();
|
|
337
|
+
if (!argToken) break;
|
|
338
|
+
if (argToken.kind === "punctuation" && argToken.value === ")") {
|
|
339
|
+
tokens.advance();
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
if (argToken.kind === "punctuation" && argToken.value === ",") {
|
|
343
|
+
tokens.advance();
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
args.push(argToken.value);
|
|
347
|
+
tokens.advance();
|
|
348
|
+
}
|
|
349
|
+
const methodCall = `${token.value}.${methodToken.value}(${args.join(", ")})`;
|
|
350
|
+
return {
|
|
351
|
+
type: "expression",
|
|
352
|
+
raw: methodCall
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
function tryMatchPropertyAccessExpression(tokens) {
|
|
356
|
+
const token = tokens.peek();
|
|
357
|
+
if (!token) return null;
|
|
358
|
+
if (token.kind !== "identifier" && token.kind !== "keyword") return null;
|
|
359
|
+
const mark = tokens.mark();
|
|
360
|
+
tokens.advance();
|
|
361
|
+
const dotToken = tokens.peek();
|
|
362
|
+
if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
|
|
363
|
+
tokens.reset(mark);
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
tokens.advance();
|
|
367
|
+
const propertyToken = tokens.peek();
|
|
368
|
+
if (!propertyToken || propertyToken.kind !== "identifier") {
|
|
369
|
+
tokens.reset(mark);
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
tokens.advance();
|
|
373
|
+
let chain = `${token.value}.${propertyToken.value}`;
|
|
374
|
+
let depth = 1;
|
|
375
|
+
while (!tokens.isAtEnd() && depth < MAX_PROPERTY_DEPTH) {
|
|
376
|
+
const nextDot = tokens.peek();
|
|
377
|
+
if (!nextDot || nextDot.kind !== "operator" || nextDot.value !== ".") {
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
tokens.advance();
|
|
381
|
+
const nextProp = tokens.peek();
|
|
382
|
+
if (!nextProp || nextProp.kind !== "identifier") {
|
|
383
|
+
break;
|
|
384
|
+
}
|
|
385
|
+
tokens.advance();
|
|
386
|
+
chain += `.${nextProp.value}`;
|
|
387
|
+
depth++;
|
|
388
|
+
}
|
|
389
|
+
const openParen = tokens.peek();
|
|
390
|
+
if (openParen && openParen.kind === "punctuation" && openParen.value === "(") {
|
|
391
|
+
tokens.advance();
|
|
392
|
+
const args = [];
|
|
393
|
+
let argDepth = 0;
|
|
394
|
+
while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {
|
|
395
|
+
const argToken = tokens.peek();
|
|
396
|
+
if (!argToken) break;
|
|
397
|
+
if (argToken.kind === "punctuation" && argToken.value === ")") {
|
|
398
|
+
if (argDepth === 0) {
|
|
399
|
+
tokens.advance();
|
|
400
|
+
break;
|
|
401
|
+
}
|
|
402
|
+
argDepth--;
|
|
403
|
+
}
|
|
404
|
+
if (argToken.kind === "punctuation" && argToken.value === "(") {
|
|
405
|
+
argDepth++;
|
|
406
|
+
}
|
|
407
|
+
if (argToken.kind === "punctuation" && argToken.value === ",") {
|
|
408
|
+
tokens.advance();
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
args.push(argToken.value);
|
|
412
|
+
tokens.advance();
|
|
413
|
+
}
|
|
414
|
+
const methodCall = `${chain}(${args.join(", ")})`;
|
|
415
|
+
return {
|
|
416
|
+
type: "expression",
|
|
417
|
+
raw: methodCall
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
return {
|
|
421
|
+
type: "expression",
|
|
422
|
+
raw: chain
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
function tryMatchPossessiveSelectorExpression(tokens) {
|
|
426
|
+
const token = tokens.peek();
|
|
427
|
+
if (!token || token.kind !== "selector") return null;
|
|
428
|
+
const mark = tokens.mark();
|
|
429
|
+
tokens.advance();
|
|
430
|
+
const possessiveToken = tokens.peek();
|
|
431
|
+
if (!possessiveToken || possessiveToken.kind !== "punctuation" || possessiveToken.value !== "'s") {
|
|
432
|
+
tokens.reset(mark);
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
tokens.advance();
|
|
436
|
+
const propertyToken = tokens.peek();
|
|
437
|
+
if (!propertyToken) {
|
|
438
|
+
tokens.reset(mark);
|
|
439
|
+
return null;
|
|
440
|
+
}
|
|
441
|
+
if (propertyToken.kind !== "selector" && propertyToken.kind !== "identifier") {
|
|
442
|
+
tokens.reset(mark);
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
tokens.advance();
|
|
446
|
+
return createPropertyPath(createSelector(token.value), propertyToken.value);
|
|
447
|
+
}
|
|
448
|
+
function tryMatchSelectorPropertyExpression(tokens) {
|
|
449
|
+
const token = tokens.peek();
|
|
450
|
+
if (!token || token.kind !== "selector") return null;
|
|
451
|
+
if (typeof token.value !== "string" || !token.value.startsWith("#")) return null;
|
|
452
|
+
const mark = tokens.mark();
|
|
453
|
+
tokens.advance();
|
|
454
|
+
const propertyToken = tokens.peek();
|
|
455
|
+
if (!propertyToken || propertyToken.kind !== "selector") {
|
|
456
|
+
tokens.reset(mark);
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
if (!propertyToken.value.startsWith(".")) {
|
|
460
|
+
tokens.reset(mark);
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
const peek2 = tokens.peek(1);
|
|
464
|
+
if (peek2 && peek2.kind === "selector") {
|
|
465
|
+
}
|
|
466
|
+
tokens.advance();
|
|
467
|
+
const propertyName = propertyToken.value.slice(1);
|
|
468
|
+
return createPropertyPath(createSelector(token.value), propertyName);
|
|
469
|
+
}
|
|
470
|
+
var MAX_PROPERTY_DEPTH = 10;
|
|
471
|
+
var MAX_METHOD_ARGS = 20;
|
|
472
|
+
function tokenToSemanticValue(token) {
|
|
473
|
+
switch (token.kind) {
|
|
474
|
+
case "selector":
|
|
475
|
+
return createSelector(token.value);
|
|
476
|
+
case "literal":
|
|
477
|
+
return parseLiteralValue(token.value);
|
|
478
|
+
case "keyword": {
|
|
479
|
+
const tokenValue = token.normalized || token.value;
|
|
480
|
+
const lower = safeToLowerCase(tokenValue);
|
|
481
|
+
if (isValidReference(lower)) {
|
|
482
|
+
return createReference(lower);
|
|
483
|
+
}
|
|
484
|
+
return createLiteral(token.normalized || token.value);
|
|
485
|
+
}
|
|
486
|
+
case "identifier": {
|
|
487
|
+
if (typeof token.value === "string" && token.value.startsWith(":")) {
|
|
488
|
+
return createReference(token.value);
|
|
489
|
+
}
|
|
490
|
+
const identLower = safeToLowerCase(token.value);
|
|
491
|
+
if (isValidReference(identLower)) {
|
|
492
|
+
return createReference(identLower);
|
|
493
|
+
}
|
|
494
|
+
return { type: "expression", raw: token.value };
|
|
495
|
+
}
|
|
496
|
+
case "url":
|
|
497
|
+
return createLiteral(token.value, "string");
|
|
498
|
+
default:
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
function parseLiteralValue(value) {
|
|
503
|
+
if (value.startsWith('"') || value.startsWith("'") || value.startsWith("`") || value.startsWith("\u300C")) {
|
|
504
|
+
const inner = value.slice(1, -1);
|
|
505
|
+
return createLiteral(inner, "string");
|
|
506
|
+
}
|
|
507
|
+
if (value === "true") return createLiteral(true, "boolean");
|
|
508
|
+
if (value === "false") return createLiteral(false, "boolean");
|
|
509
|
+
const durationMatch = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
|
|
510
|
+
if (durationMatch) {
|
|
511
|
+
const num2 = parseFloat(durationMatch[1]);
|
|
512
|
+
const unit = durationMatch[2];
|
|
513
|
+
if (unit) {
|
|
514
|
+
return createLiteral(value, "duration");
|
|
515
|
+
}
|
|
516
|
+
return createLiteral(num2, "number");
|
|
517
|
+
}
|
|
518
|
+
const num = parseFloat(value);
|
|
519
|
+
if (!isNaN(num)) {
|
|
520
|
+
return createLiteral(num, "number");
|
|
521
|
+
}
|
|
522
|
+
return createLiteral(value, "string");
|
|
523
|
+
}
|
|
524
|
+
var ENGLISH_NOISE_WORDS = /* @__PURE__ */ new Set(["the", "a", "an"]);
|
|
525
|
+
function skipNoiseWords(tokens) {
|
|
526
|
+
const token = tokens.peek();
|
|
527
|
+
if (!token) return;
|
|
528
|
+
const tokenLower = safeToLowerCase(token.value);
|
|
529
|
+
if (ENGLISH_NOISE_WORDS.has(tokenLower)) {
|
|
530
|
+
const mark = tokens.mark();
|
|
531
|
+
tokens.advance();
|
|
532
|
+
const nextToken = tokens.peek();
|
|
533
|
+
if (nextToken && nextToken.kind === "selector") {
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
tokens.reset(mark);
|
|
537
|
+
}
|
|
538
|
+
if (tokenLower === "class") {
|
|
539
|
+
tokens.advance();
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// src/core/matching/stock-confidence.ts
|
|
544
|
+
function scoreParts(ctx) {
|
|
545
|
+
const { pattern, captured } = ctx;
|
|
546
|
+
let score = 0;
|
|
547
|
+
let maxScore = 0;
|
|
548
|
+
const hasDefault = (role) => {
|
|
549
|
+
return pattern.extraction?.[role]?.default !== void 0;
|
|
550
|
+
};
|
|
551
|
+
for (const token of pattern.template.tokens) {
|
|
552
|
+
if (token.type === "role") {
|
|
553
|
+
maxScore += 1;
|
|
554
|
+
if (captured.has(token.role)) {
|
|
555
|
+
score += 1;
|
|
556
|
+
}
|
|
557
|
+
} else if (token.type === "group") {
|
|
558
|
+
for (const subToken of token.tokens) {
|
|
559
|
+
if (subToken.type === "role") {
|
|
560
|
+
const roleHasDefault = hasDefault(subToken.role);
|
|
561
|
+
const weight = 0.8;
|
|
562
|
+
maxScore += weight;
|
|
563
|
+
if (captured.has(subToken.role)) {
|
|
564
|
+
score += weight;
|
|
565
|
+
} else if (roleHasDefault) {
|
|
566
|
+
score += weight * 0.6;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const roleCoverage = maxScore > 0 ? score / maxScore : 1;
|
|
573
|
+
let baseConfidence = roleCoverage;
|
|
574
|
+
let stemPenalty = 0;
|
|
575
|
+
if (ctx.stemMatchCount > 0 && ctx.totalKeywordMatches > 0) {
|
|
576
|
+
stemPenalty = ctx.stemMatchCount / ctx.totalKeywordMatches * 0.15;
|
|
577
|
+
baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);
|
|
578
|
+
}
|
|
579
|
+
const vsoBoost = calculateVSOConfidenceBoost(pattern);
|
|
580
|
+
baseConfidence = Math.min(1, baseConfidence + vsoBoost);
|
|
581
|
+
const prepositionAdjustment = arabicPrepositionDisambiguation(pattern, captured);
|
|
582
|
+
baseConfidence = Math.max(0, Math.min(1, baseConfidence + prepositionAdjustment));
|
|
583
|
+
return {
|
|
584
|
+
roleCoverage,
|
|
585
|
+
stemPenalty,
|
|
586
|
+
languageBoost: vsoBoost,
|
|
587
|
+
languageAdjustment: prepositionAdjustment,
|
|
588
|
+
final: baseConfidence
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
function calculateVSOConfidenceBoost(pattern) {
|
|
592
|
+
if (pattern.language !== "ar") {
|
|
593
|
+
return 0;
|
|
594
|
+
}
|
|
595
|
+
const firstToken = pattern.template.tokens[0];
|
|
596
|
+
if (!firstToken || firstToken.type !== "literal") {
|
|
597
|
+
return 0;
|
|
598
|
+
}
|
|
599
|
+
const ARABIC_VERBS = /* @__PURE__ */ new Set([
|
|
600
|
+
"\u0628\u062F\u0644",
|
|
601
|
+
"\u063A\u064A\u0631",
|
|
602
|
+
"\u0623\u0636\u0641",
|
|
603
|
+
"\u0623\u0632\u0644",
|
|
604
|
+
"\u0636\u0639",
|
|
605
|
+
"\u0627\u062C\u0639\u0644",
|
|
606
|
+
"\u0639\u064A\u0646",
|
|
607
|
+
"\u0632\u062F",
|
|
608
|
+
"\u0627\u0646\u0642\u0635",
|
|
609
|
+
"\u0633\u062C\u0644",
|
|
610
|
+
"\u0623\u0638\u0647\u0631",
|
|
611
|
+
"\u0623\u062E\u0641",
|
|
612
|
+
"\u0634\u063A\u0644",
|
|
613
|
+
"\u0623\u0631\u0633\u0644",
|
|
614
|
+
"\u0631\u0643\u0632",
|
|
615
|
+
"\u0634\u0648\u0634",
|
|
616
|
+
"\u062A\u0648\u0642\u0641",
|
|
617
|
+
"\u0627\u0646\u0633\u062E",
|
|
618
|
+
"\u0627\u062D\u0630\u0641",
|
|
619
|
+
"\u0627\u0635\u0646\u0639",
|
|
620
|
+
"\u0627\u0646\u062A\u0638\u0631",
|
|
621
|
+
"\u0627\u0646\u062A\u0642\u0627\u0644",
|
|
622
|
+
"\u0623\u0648"
|
|
623
|
+
]);
|
|
624
|
+
if (ARABIC_VERBS.has(firstToken.value)) {
|
|
625
|
+
return 0.15;
|
|
626
|
+
}
|
|
627
|
+
if (firstToken.alternatives) {
|
|
628
|
+
for (const alt of firstToken.alternatives) {
|
|
629
|
+
if (ARABIC_VERBS.has(alt)) {
|
|
630
|
+
return 0.15;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return 0;
|
|
635
|
+
}
|
|
636
|
+
function arabicPrepositionDisambiguation(pattern, captured) {
|
|
637
|
+
if (pattern.language !== "ar") {
|
|
638
|
+
return 0;
|
|
639
|
+
}
|
|
640
|
+
let adjustment = 0;
|
|
641
|
+
const PREFERRED_PREPOSITIONS = {
|
|
642
|
+
patient: ["\u0639\u0644\u0649"],
|
|
643
|
+
// element selectors prefer على (on/upon)
|
|
644
|
+
destination: ["\u0625\u0644\u0649", "\u0627\u0644\u0649"],
|
|
645
|
+
// destination prefers إلى (to)
|
|
646
|
+
source: ["\u0645\u0646"],
|
|
647
|
+
// source prefers من (from)
|
|
648
|
+
agent: ["\u0645\u0646"],
|
|
649
|
+
// agent/by prefers من (from/by)
|
|
650
|
+
manner: ["\u0628"],
|
|
651
|
+
// manner prefers ب (with/by)
|
|
652
|
+
style: ["\u0628"],
|
|
653
|
+
// style prefers ب (with)
|
|
654
|
+
goal: ["\u0625\u0644\u0649", "\u0627\u0644\u0649"],
|
|
655
|
+
// target state prefers إلى (to)
|
|
656
|
+
method: ["\u0628"]
|
|
657
|
+
// method prefers ب (with/by)
|
|
658
|
+
};
|
|
659
|
+
for (const [role, value] of captured.entries()) {
|
|
660
|
+
const preferred = PREFERRED_PREPOSITIONS[role];
|
|
661
|
+
if (!preferred || preferred.length === 0) {
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
const metadata = "metadata" in value ? value.metadata : void 0;
|
|
665
|
+
if (metadata && typeof metadata.prepositionValue === "string") {
|
|
666
|
+
const usedPreposition = metadata.prepositionValue;
|
|
667
|
+
if (preferred.includes(usedPreposition)) {
|
|
668
|
+
adjustment += 0.1;
|
|
669
|
+
} else {
|
|
670
|
+
adjustment -= 0.1;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return Math.max(-0.1, Math.min(0.1, adjustment));
|
|
675
|
+
}
|
|
676
|
+
var stockConfidenceModel = {
|
|
677
|
+
calculate: (ctx) => scoreParts(ctx).final,
|
|
678
|
+
calculateWithBreakdown: (ctx) => scoreParts(ctx)
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
// src/core/pattern-matching/pattern-matcher.ts
|
|
157
682
|
var _PatternMatcher = class _PatternMatcher {
|
|
158
683
|
constructor() {
|
|
159
684
|
/** Debug logger */
|
|
@@ -165,19 +690,6 @@ var _PatternMatcher = class _PatternMatcher {
|
|
|
165
690
|
this.stemMatchCount = 0;
|
|
166
691
|
this.totalKeywordMatches = 0;
|
|
167
692
|
}
|
|
168
|
-
/**
|
|
169
|
-
* Safely convert a value to lowercase string.
|
|
170
|
-
* Provides protection against non-string values at runtime.
|
|
171
|
-
*/
|
|
172
|
-
safeToLowerCase(value) {
|
|
173
|
-
if (typeof value === "string") {
|
|
174
|
-
return value.toLowerCase();
|
|
175
|
-
}
|
|
176
|
-
if (value === null || value === void 0) {
|
|
177
|
-
return "";
|
|
178
|
-
}
|
|
179
|
-
return String(value).toLowerCase();
|
|
180
|
-
}
|
|
181
693
|
/**
|
|
182
694
|
* Try to match a single pattern against the token stream.
|
|
183
695
|
* Returns the match result or null if no match.
|
|
@@ -226,7 +738,12 @@ var _PatternMatcher = class _PatternMatcher {
|
|
|
226
738
|
tokens.reset(mark);
|
|
227
739
|
return null;
|
|
228
740
|
}
|
|
229
|
-
const confidence =
|
|
741
|
+
const confidence = stockConfidenceModel.calculate({
|
|
742
|
+
pattern,
|
|
743
|
+
captured,
|
|
744
|
+
stemMatchCount: this.stemMatchCount,
|
|
745
|
+
totalKeywordMatches: this.totalKeywordMatches
|
|
746
|
+
});
|
|
230
747
|
this.applyExtractionRules(pattern, captured);
|
|
231
748
|
return {
|
|
232
749
|
pattern,
|
|
@@ -411,7 +928,7 @@ var _PatternMatcher = class _PatternMatcher {
|
|
|
411
928
|
case "literal":
|
|
412
929
|
return this.matchLiteralToken(tokens, patternToken);
|
|
413
930
|
case "role":
|
|
414
|
-
return
|
|
931
|
+
return readRoleValue(tokens, patternToken, captured, this.currentProfile);
|
|
415
932
|
case "group":
|
|
416
933
|
return this.matchGroupToken(tokens, patternToken, captured);
|
|
417
934
|
default:
|
|
@@ -469,420 +986,54 @@ var _PatternMatcher = class _PatternMatcher {
|
|
|
469
986
|
return false;
|
|
470
987
|
}
|
|
471
988
|
/**
|
|
472
|
-
* Match a
|
|
473
|
-
*
|
|
474
|
-
*
|
|
475
|
-
*
|
|
476
|
-
*
|
|
989
|
+
* Match a group pattern token (optional sequence).
|
|
990
|
+
* When the group's leading marker isn't at the current position, scans ahead
|
|
991
|
+
* up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens
|
|
992
|
+
* (e.g., a value like 'hello') to sit between groups without blocking later
|
|
993
|
+
* marker matches.
|
|
477
994
|
*/
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
token ? JSON.stringify({ value: token.value, kind: token.kind }) : "null"
|
|
995
|
+
matchGroupToken(tokens, patternToken, captured, parentStopMarkers) {
|
|
996
|
+
const mark = tokens.mark();
|
|
997
|
+
const capturedBefore = new Set(captured.keys());
|
|
998
|
+
const success = this.matchTokenSequence(
|
|
999
|
+
tokens,
|
|
1000
|
+
patternToken.tokens,
|
|
1001
|
+
captured,
|
|
1002
|
+
parentStopMarkers
|
|
487
1003
|
);
|
|
488
|
-
if (
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
if (possessiveValue) {
|
|
493
|
-
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
494
|
-
if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {
|
|
495
|
-
return patternToken.optional || false;
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
captured.set(patternToken.role, possessiveValue);
|
|
499
|
-
return true;
|
|
500
|
-
}
|
|
501
|
-
const methodCallValue = this.tryMatchMethodCallExpression(tokens);
|
|
502
|
-
if (methodCallValue) {
|
|
503
|
-
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
504
|
-
if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {
|
|
505
|
-
return patternToken.optional || false;
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
captured.set(patternToken.role, methodCallValue);
|
|
509
|
-
return true;
|
|
510
|
-
}
|
|
511
|
-
const possessiveSelectorValue = this.tryMatchPossessiveSelectorExpression(tokens);
|
|
512
|
-
if (possessiveSelectorValue) {
|
|
513
|
-
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
514
|
-
if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {
|
|
515
|
-
return patternToken.optional || false;
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
captured.set(patternToken.role, possessiveSelectorValue);
|
|
519
|
-
return true;
|
|
520
|
-
}
|
|
521
|
-
const propertyAccessValue = this.tryMatchPropertyAccessExpression(tokens);
|
|
522
|
-
if (propertyAccessValue) {
|
|
523
|
-
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
524
|
-
if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {
|
|
525
|
-
return patternToken.optional || false;
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
captured.set(patternToken.role, propertyAccessValue);
|
|
529
|
-
return true;
|
|
1004
|
+
if (success) return true;
|
|
1005
|
+
tokens.reset(mark);
|
|
1006
|
+
for (const role of captured.keys()) {
|
|
1007
|
+
if (!capturedBefore.has(role)) captured.delete(role);
|
|
530
1008
|
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
|
|
560
|
-
if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {
|
|
561
|
-
this.logger.debug(" >>> TYPE MISMATCH - returning", patternToken.optional || false);
|
|
562
|
-
return patternToken.optional || false;
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
this.logger.debug(" >>> Type validation PASSED");
|
|
566
|
-
captured.set(patternToken.role, value);
|
|
567
|
-
tokens.advance();
|
|
568
|
-
return true;
|
|
569
|
-
}
|
|
570
|
-
/**
|
|
571
|
-
* Try to match a possessive expression like 'my value' or 'its innerHTML'.
|
|
572
|
-
* Returns the PropertyPathValue if matched, or null if not.
|
|
573
|
-
*/
|
|
574
|
-
tryMatchPossessiveExpression(tokens) {
|
|
575
|
-
const token = tokens.peek();
|
|
576
|
-
if (!token) return null;
|
|
577
|
-
if (!this.currentProfile) return null;
|
|
578
|
-
const tokenValue = token.normalized || token.value;
|
|
579
|
-
const tokenLower = this.safeToLowerCase(tokenValue);
|
|
580
|
-
const baseRef = getPossessiveReference(this.currentProfile, tokenLower);
|
|
581
|
-
if (!baseRef) return null;
|
|
582
|
-
const mark = tokens.mark();
|
|
583
|
-
tokens.advance();
|
|
584
|
-
const propertyToken = tokens.peek();
|
|
585
|
-
if (!propertyToken) {
|
|
586
|
-
tokens.reset(mark);
|
|
587
|
-
return null;
|
|
588
|
-
}
|
|
589
|
-
if (propertyToken.kind === "identifier" || propertyToken.kind === "keyword" && !this.isStructuralKeyword(propertyToken.value) || propertyToken.kind === "selector" && propertyToken.value.startsWith("*") || propertyToken.kind === "selector" && propertyToken.value.startsWith("@") || propertyToken.kind === "selector" && propertyToken.value.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(propertyToken.value)) {
|
|
590
|
-
tokens.advance();
|
|
591
|
-
let propertyName = propertyToken.value;
|
|
592
|
-
if (propertyToken.kind === "selector" && propertyName.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(propertyName)) {
|
|
593
|
-
propertyName = propertyName.substring(1);
|
|
594
|
-
}
|
|
595
|
-
let chainedProps = propertyName;
|
|
596
|
-
while (tokens.peek()?.kind === "selector" && tokens.peek().value.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(tokens.peek().value)) {
|
|
597
|
-
chainedProps += tokens.peek().value;
|
|
598
|
-
tokens.advance();
|
|
599
|
-
}
|
|
600
|
-
const nextPeek = tokens.peek();
|
|
601
|
-
if (nextPeek?.kind === "literal" && nextPeek.value.startsWith("(")) {
|
|
602
|
-
chainedProps += nextPeek.value;
|
|
603
|
-
tokens.advance();
|
|
604
|
-
}
|
|
605
|
-
return createPropertyPath(createReference(baseRef), chainedProps);
|
|
606
|
-
}
|
|
607
|
-
tokens.reset(mark);
|
|
608
|
-
return null;
|
|
609
|
-
}
|
|
610
|
-
/**
|
|
611
|
-
* Check if a keyword is a structural keyword (preposition, control flow, etc.)
|
|
612
|
-
* that shouldn't be consumed as a property name.
|
|
613
|
-
*/
|
|
614
|
-
isStructuralKeyword(value) {
|
|
615
|
-
const structural = /* @__PURE__ */ new Set([
|
|
616
|
-
// Prepositions
|
|
617
|
-
"into",
|
|
618
|
-
"in",
|
|
619
|
-
"to",
|
|
620
|
-
"from",
|
|
621
|
-
"at",
|
|
622
|
-
"by",
|
|
623
|
-
"with",
|
|
624
|
-
"without",
|
|
625
|
-
"before",
|
|
626
|
-
"after",
|
|
627
|
-
"of",
|
|
628
|
-
"as",
|
|
629
|
-
"on",
|
|
630
|
-
// Control flow
|
|
631
|
-
"then",
|
|
632
|
-
"end",
|
|
633
|
-
"else",
|
|
634
|
-
"if",
|
|
635
|
-
"repeat",
|
|
636
|
-
"while",
|
|
637
|
-
"for",
|
|
638
|
-
// Commands (shouldn't be property names)
|
|
639
|
-
"toggle",
|
|
640
|
-
"add",
|
|
641
|
-
"remove",
|
|
642
|
-
"put",
|
|
643
|
-
"set",
|
|
644
|
-
"show",
|
|
645
|
-
"hide",
|
|
646
|
-
"increment",
|
|
647
|
-
"decrement",
|
|
648
|
-
"send",
|
|
649
|
-
"trigger",
|
|
650
|
-
"call"
|
|
651
|
-
]);
|
|
652
|
-
return structural.has(value.toLowerCase());
|
|
653
|
-
}
|
|
654
|
-
/**
|
|
655
|
-
* Try to match a method call expression like '#dialog.showModal()'.
|
|
656
|
-
* Pattern: selector + '.' + identifier + '(' + [args] + ')'
|
|
657
|
-
* Returns an expression value if matched, or null if not.
|
|
658
|
-
*/
|
|
659
|
-
tryMatchMethodCallExpression(tokens) {
|
|
660
|
-
const token = tokens.peek();
|
|
661
|
-
if (!token || token.kind !== "selector") return null;
|
|
662
|
-
const mark = tokens.mark();
|
|
663
|
-
tokens.advance();
|
|
664
|
-
const dotToken = tokens.peek();
|
|
665
|
-
if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
|
|
666
|
-
tokens.reset(mark);
|
|
667
|
-
return null;
|
|
668
|
-
}
|
|
669
|
-
tokens.advance();
|
|
670
|
-
const methodToken = tokens.peek();
|
|
671
|
-
if (!methodToken || methodToken.kind !== "identifier") {
|
|
672
|
-
tokens.reset(mark);
|
|
673
|
-
return null;
|
|
674
|
-
}
|
|
675
|
-
tokens.advance();
|
|
676
|
-
const openParen = tokens.peek();
|
|
677
|
-
if (!openParen || openParen.kind !== "punctuation" || openParen.value !== "(") {
|
|
678
|
-
tokens.reset(mark);
|
|
679
|
-
return null;
|
|
680
|
-
}
|
|
681
|
-
tokens.advance();
|
|
682
|
-
const args = [];
|
|
683
|
-
while (!tokens.isAtEnd() && args.length < _PatternMatcher.MAX_METHOD_ARGS) {
|
|
684
|
-
const argToken = tokens.peek();
|
|
685
|
-
if (!argToken) break;
|
|
686
|
-
if (argToken.kind === "punctuation" && argToken.value === ")") {
|
|
687
|
-
tokens.advance();
|
|
688
|
-
break;
|
|
689
|
-
}
|
|
690
|
-
if (argToken.kind === "punctuation" && argToken.value === ",") {
|
|
691
|
-
tokens.advance();
|
|
692
|
-
continue;
|
|
693
|
-
}
|
|
694
|
-
args.push(argToken.value);
|
|
695
|
-
tokens.advance();
|
|
696
|
-
}
|
|
697
|
-
const methodCall = `${token.value}.${methodToken.value}(${args.join(", ")})`;
|
|
698
|
-
return {
|
|
699
|
-
type: "expression",
|
|
700
|
-
raw: methodCall
|
|
701
|
-
};
|
|
702
|
-
}
|
|
703
|
-
/**
|
|
704
|
-
* Try to match a property access expression like 'userData.name' or 'it.data'.
|
|
705
|
-
* Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]
|
|
706
|
-
* Returns an expression value if matched, or null if not.
|
|
707
|
-
*/
|
|
708
|
-
tryMatchPropertyAccessExpression(tokens) {
|
|
709
|
-
const token = tokens.peek();
|
|
710
|
-
if (!token) return null;
|
|
711
|
-
if (token.kind !== "identifier" && token.kind !== "keyword") return null;
|
|
712
|
-
const mark = tokens.mark();
|
|
713
|
-
tokens.advance();
|
|
714
|
-
const dotToken = tokens.peek();
|
|
715
|
-
if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
|
|
716
|
-
tokens.reset(mark);
|
|
717
|
-
return null;
|
|
718
|
-
}
|
|
719
|
-
tokens.advance();
|
|
720
|
-
const propertyToken = tokens.peek();
|
|
721
|
-
if (!propertyToken || propertyToken.kind !== "identifier") {
|
|
722
|
-
tokens.reset(mark);
|
|
723
|
-
return null;
|
|
724
|
-
}
|
|
725
|
-
tokens.advance();
|
|
726
|
-
let chain = `${token.value}.${propertyToken.value}`;
|
|
727
|
-
let depth = 1;
|
|
728
|
-
while (!tokens.isAtEnd() && depth < _PatternMatcher.MAX_PROPERTY_DEPTH) {
|
|
729
|
-
const nextDot = tokens.peek();
|
|
730
|
-
if (!nextDot || nextDot.kind !== "operator" || nextDot.value !== ".") {
|
|
731
|
-
break;
|
|
732
|
-
}
|
|
733
|
-
tokens.advance();
|
|
734
|
-
const nextProp = tokens.peek();
|
|
735
|
-
if (!nextProp || nextProp.kind !== "identifier") {
|
|
736
|
-
break;
|
|
737
|
-
}
|
|
738
|
-
tokens.advance();
|
|
739
|
-
chain += `.${nextProp.value}`;
|
|
740
|
-
depth++;
|
|
741
|
-
}
|
|
742
|
-
const openParen = tokens.peek();
|
|
743
|
-
if (openParen && openParen.kind === "punctuation" && openParen.value === "(") {
|
|
744
|
-
tokens.advance();
|
|
745
|
-
const args = [];
|
|
746
|
-
let argDepth = 0;
|
|
747
|
-
while (!tokens.isAtEnd() && args.length < _PatternMatcher.MAX_METHOD_ARGS) {
|
|
748
|
-
const argToken = tokens.peek();
|
|
749
|
-
if (!argToken) break;
|
|
750
|
-
if (argToken.kind === "punctuation" && argToken.value === ")") {
|
|
751
|
-
if (argDepth === 0) {
|
|
752
|
-
tokens.advance();
|
|
753
|
-
break;
|
|
754
|
-
}
|
|
755
|
-
argDepth--;
|
|
756
|
-
}
|
|
757
|
-
if (argToken.kind === "punctuation" && argToken.value === "(") {
|
|
758
|
-
argDepth++;
|
|
759
|
-
}
|
|
760
|
-
if (argToken.kind === "punctuation" && argToken.value === ",") {
|
|
761
|
-
tokens.advance();
|
|
762
|
-
continue;
|
|
763
|
-
}
|
|
764
|
-
args.push(argToken.value);
|
|
765
|
-
tokens.advance();
|
|
766
|
-
}
|
|
767
|
-
const methodCall = `${chain}(${args.join(", ")})`;
|
|
768
|
-
return {
|
|
769
|
-
type: "expression",
|
|
770
|
-
raw: methodCall
|
|
771
|
-
};
|
|
772
|
-
}
|
|
773
|
-
return {
|
|
774
|
-
type: "expression",
|
|
775
|
-
raw: chain
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
|
-
/**
|
|
779
|
-
* Try to match a possessive selector expression like "#element's *opacity".
|
|
780
|
-
* Pattern: selector + "'s" + (selector | identifier)
|
|
781
|
-
* Returns a property-path value if matched, or null if not.
|
|
782
|
-
*/
|
|
783
|
-
tryMatchPossessiveSelectorExpression(tokens) {
|
|
784
|
-
const token = tokens.peek();
|
|
785
|
-
if (!token || token.kind !== "selector") return null;
|
|
786
|
-
const mark = tokens.mark();
|
|
787
|
-
tokens.advance();
|
|
788
|
-
const possessiveToken = tokens.peek();
|
|
789
|
-
if (!possessiveToken || possessiveToken.kind !== "punctuation" || possessiveToken.value !== "'s") {
|
|
790
|
-
tokens.reset(mark);
|
|
791
|
-
return null;
|
|
792
|
-
}
|
|
793
|
-
tokens.advance();
|
|
794
|
-
const propertyToken = tokens.peek();
|
|
795
|
-
if (!propertyToken) {
|
|
796
|
-
tokens.reset(mark);
|
|
797
|
-
return null;
|
|
798
|
-
}
|
|
799
|
-
if (propertyToken.kind !== "selector" && propertyToken.kind !== "identifier") {
|
|
800
|
-
tokens.reset(mark);
|
|
801
|
-
return null;
|
|
802
|
-
}
|
|
803
|
-
tokens.advance();
|
|
804
|
-
return createPropertyPath(createSelector(token.value), propertyToken.value);
|
|
805
|
-
}
|
|
806
|
-
/**
|
|
807
|
-
* Try to match a selector + property expression like "#output.innerText".
|
|
808
|
-
* This handles cases where the tokenizer produces two selector tokens:
|
|
809
|
-
* - #output (id selector)
|
|
810
|
-
* - .innerText (looks like class selector, but is actually property)
|
|
811
|
-
*
|
|
812
|
-
* Pattern: id-selector + class-selector-that-is-actually-property
|
|
813
|
-
* Returns a property-path value if matched, or null if not.
|
|
814
|
-
*/
|
|
815
|
-
tryMatchSelectorPropertyExpression(tokens) {
|
|
816
|
-
const token = tokens.peek();
|
|
817
|
-
if (!token || token.kind !== "selector") return null;
|
|
818
|
-
if (typeof token.value !== "string" || !token.value.startsWith("#")) return null;
|
|
819
|
-
const mark = tokens.mark();
|
|
820
|
-
tokens.advance();
|
|
821
|
-
const propertyToken = tokens.peek();
|
|
822
|
-
if (!propertyToken || propertyToken.kind !== "selector") {
|
|
823
|
-
tokens.reset(mark);
|
|
824
|
-
return null;
|
|
825
|
-
}
|
|
826
|
-
if (!propertyToken.value.startsWith(".")) {
|
|
827
|
-
tokens.reset(mark);
|
|
828
|
-
return null;
|
|
829
|
-
}
|
|
830
|
-
const peek2 = tokens.peek(1);
|
|
831
|
-
if (peek2 && peek2.kind === "selector") {
|
|
832
|
-
}
|
|
833
|
-
tokens.advance();
|
|
834
|
-
const propertyName = propertyToken.value.slice(1);
|
|
835
|
-
return createPropertyPath(createSelector(token.value), propertyName);
|
|
836
|
-
}
|
|
837
|
-
/**
|
|
838
|
-
* Match a group pattern token (optional sequence).
|
|
839
|
-
* When the group's leading marker isn't at the current position, scans ahead
|
|
840
|
-
* up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens
|
|
841
|
-
* (e.g., a value like 'hello') to sit between groups without blocking later
|
|
842
|
-
* marker matches.
|
|
843
|
-
*/
|
|
844
|
-
matchGroupToken(tokens, patternToken, captured, parentStopMarkers) {
|
|
845
|
-
const mark = tokens.mark();
|
|
846
|
-
const capturedBefore = new Set(captured.keys());
|
|
847
|
-
const success = this.matchTokenSequence(
|
|
848
|
-
tokens,
|
|
849
|
-
patternToken.tokens,
|
|
850
|
-
captured,
|
|
851
|
-
parentStopMarkers
|
|
852
|
-
);
|
|
853
|
-
if (success) return true;
|
|
854
|
-
tokens.reset(mark);
|
|
855
|
-
for (const role of captured.keys()) {
|
|
856
|
-
if (!capturedBefore.has(role)) captured.delete(role);
|
|
857
|
-
}
|
|
858
|
-
if (!patternToken.optional) return false;
|
|
859
|
-
const leadingMarker = this.getGroupLeadingMarker(patternToken);
|
|
860
|
-
if (leadingMarker) {
|
|
861
|
-
for (let offset = 1; offset <= _PatternMatcher.MAX_MARKER_SCAN; offset++) {
|
|
862
|
-
const ahead = tokens.peek(offset);
|
|
863
|
-
if (!ahead) break;
|
|
864
|
-
const aheadValue = (ahead.normalized || ahead.value).toLowerCase();
|
|
865
|
-
if (aheadValue === leadingMarker) {
|
|
866
|
-
this.logger.debug(
|
|
867
|
-
" >> MARKER SCAN: found",
|
|
868
|
-
leadingMarker,
|
|
869
|
-
"at offset",
|
|
870
|
-
offset,
|
|
871
|
-
"- skipping intervening tokens"
|
|
872
|
-
);
|
|
873
|
-
for (let s = 0; s < offset; s++) tokens.advance();
|
|
874
|
-
const retrySuccess = this.matchTokenSequence(
|
|
875
|
-
tokens,
|
|
876
|
-
patternToken.tokens,
|
|
877
|
-
captured,
|
|
878
|
-
parentStopMarkers
|
|
879
|
-
);
|
|
880
|
-
if (retrySuccess) return true;
|
|
881
|
-
tokens.reset(mark);
|
|
882
|
-
for (const role of captured.keys()) {
|
|
883
|
-
if (!capturedBefore.has(role)) captured.delete(role);
|
|
884
|
-
}
|
|
885
|
-
break;
|
|
1009
|
+
if (!patternToken.optional) return false;
|
|
1010
|
+
const leadingMarker = this.getGroupLeadingMarker(patternToken);
|
|
1011
|
+
if (leadingMarker) {
|
|
1012
|
+
for (let offset = 1; offset <= _PatternMatcher.MAX_MARKER_SCAN; offset++) {
|
|
1013
|
+
const ahead = tokens.peek(offset);
|
|
1014
|
+
if (!ahead) break;
|
|
1015
|
+
const aheadValue = (ahead.normalized || ahead.value).toLowerCase();
|
|
1016
|
+
if (aheadValue === leadingMarker) {
|
|
1017
|
+
this.logger.debug(
|
|
1018
|
+
" >> MARKER SCAN: found",
|
|
1019
|
+
leadingMarker,
|
|
1020
|
+
"at offset",
|
|
1021
|
+
offset,
|
|
1022
|
+
"- skipping intervening tokens"
|
|
1023
|
+
);
|
|
1024
|
+
for (let s = 0; s < offset; s++) tokens.advance();
|
|
1025
|
+
const retrySuccess = this.matchTokenSequence(
|
|
1026
|
+
tokens,
|
|
1027
|
+
patternToken.tokens,
|
|
1028
|
+
captured,
|
|
1029
|
+
parentStopMarkers
|
|
1030
|
+
);
|
|
1031
|
+
if (retrySuccess) return true;
|
|
1032
|
+
tokens.reset(mark);
|
|
1033
|
+
for (const role of captured.keys()) {
|
|
1034
|
+
if (!capturedBefore.has(role)) captured.delete(role);
|
|
1035
|
+
}
|
|
1036
|
+
break;
|
|
886
1037
|
}
|
|
887
1038
|
}
|
|
888
1039
|
}
|
|
@@ -909,7 +1060,7 @@ var _PatternMatcher = class _PatternMatcher {
|
|
|
909
1060
|
if (token.stem === value && token.stemConfidence !== void 0 && token.stemConfidence >= 0.7) {
|
|
910
1061
|
return "stem";
|
|
911
1062
|
}
|
|
912
|
-
if (token.kind === "keyword" &&
|
|
1063
|
+
if (token.kind === "keyword" && safeToLowerCase(token.value) === value.toLowerCase()) {
|
|
913
1064
|
return "case-insensitive";
|
|
914
1065
|
}
|
|
915
1066
|
return "none";
|
|
@@ -957,62 +1108,9 @@ var _PatternMatcher = class _PatternMatcher {
|
|
|
957
1108
|
if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;
|
|
958
1109
|
return false;
|
|
959
1110
|
}
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
tokenToSemanticValue(token) {
|
|
964
|
-
switch (token.kind) {
|
|
965
|
-
case "selector":
|
|
966
|
-
return createSelector(token.value);
|
|
967
|
-
case "literal":
|
|
968
|
-
return this.parseLiteralValue(token.value);
|
|
969
|
-
case "keyword":
|
|
970
|
-
const tokenValue = token.normalized || token.value;
|
|
971
|
-
const lower = this.safeToLowerCase(tokenValue);
|
|
972
|
-
if (isValidReference(lower)) {
|
|
973
|
-
return createReference(lower);
|
|
974
|
-
}
|
|
975
|
-
return createLiteral(token.normalized || token.value);
|
|
976
|
-
case "identifier":
|
|
977
|
-
if (typeof token.value === "string" && token.value.startsWith(":")) {
|
|
978
|
-
return createReference(token.value);
|
|
979
|
-
}
|
|
980
|
-
const identLower = this.safeToLowerCase(token.value);
|
|
981
|
-
if (isValidReference(identLower)) {
|
|
982
|
-
return createReference(identLower);
|
|
983
|
-
}
|
|
984
|
-
return { type: "expression", raw: token.value };
|
|
985
|
-
case "url":
|
|
986
|
-
return createLiteral(token.value, "string");
|
|
987
|
-
default:
|
|
988
|
-
return null;
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
/**
|
|
992
|
-
* Parse a literal value (string, number, boolean).
|
|
993
|
-
*/
|
|
994
|
-
parseLiteralValue(value) {
|
|
995
|
-
if (value.startsWith('"') || value.startsWith("'") || value.startsWith("`") || value.startsWith("\u300C")) {
|
|
996
|
-
const inner = value.slice(1, -1);
|
|
997
|
-
return createLiteral(inner, "string");
|
|
998
|
-
}
|
|
999
|
-
if (value === "true") return createLiteral(true, "boolean");
|
|
1000
|
-
if (value === "false") return createLiteral(false, "boolean");
|
|
1001
|
-
const durationMatch = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
|
|
1002
|
-
if (durationMatch) {
|
|
1003
|
-
const num2 = parseFloat(durationMatch[1]);
|
|
1004
|
-
const unit = durationMatch[2];
|
|
1005
|
-
if (unit) {
|
|
1006
|
-
return createLiteral(value, "duration");
|
|
1007
|
-
}
|
|
1008
|
-
return createLiteral(num2, "number");
|
|
1009
|
-
}
|
|
1010
|
-
const num = parseFloat(value);
|
|
1011
|
-
if (!isNaN(num)) {
|
|
1012
|
-
return createLiteral(num, "number");
|
|
1013
|
-
}
|
|
1014
|
-
return createLiteral(value, "string");
|
|
1015
|
-
}
|
|
1111
|
+
// ==========================================================================
|
|
1112
|
+
// Depth Limits for Expression Parsing (security hardening)
|
|
1113
|
+
// ==========================================================================
|
|
1016
1114
|
/**
|
|
1017
1115
|
* Apply extraction rules to fill in static values and defaults for missing roles.
|
|
1018
1116
|
*/
|
|
@@ -1033,260 +1131,634 @@ var _PatternMatcher = class _PatternMatcher {
|
|
|
1033
1131
|
isOptional(patternToken) {
|
|
1034
1132
|
return patternToken.type !== "literal" && patternToken.optional === true;
|
|
1035
1133
|
}
|
|
1134
|
+
// ===========================================================================
|
|
1135
|
+
// English Idiom Support - Noise Word Handling
|
|
1136
|
+
// ===========================================================================
|
|
1036
1137
|
/**
|
|
1037
|
-
*
|
|
1038
|
-
*
|
|
1039
|
-
*
|
|
1040
|
-
* - Stem matches (morphological normalization has inherent uncertainty)
|
|
1041
|
-
* - Missing optional roles (but less penalty if role has a default value)
|
|
1138
|
+
* Extract event modifiers from the token stream.
|
|
1139
|
+
* Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)
|
|
1140
|
+
* that can appear after event names.
|
|
1042
1141
|
*
|
|
1043
|
-
*
|
|
1044
|
-
* - VSO languages (Arabic) when pattern starts with a verb
|
|
1142
|
+
* Returns EventModifiers object or undefined if no modifiers found.
|
|
1045
1143
|
*/
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
let
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
} else if (roleHasDefault) {
|
|
1067
|
-
score += weight * 0.6;
|
|
1068
|
-
}
|
|
1144
|
+
extractEventModifiers(tokens) {
|
|
1145
|
+
const modifiers = {};
|
|
1146
|
+
let foundModifier = false;
|
|
1147
|
+
while (!tokens.isAtEnd()) {
|
|
1148
|
+
const token = tokens.peek();
|
|
1149
|
+
if (!token || token.kind !== "event-modifier") {
|
|
1150
|
+
break;
|
|
1151
|
+
}
|
|
1152
|
+
const metadata = token.metadata;
|
|
1153
|
+
if (!metadata) {
|
|
1154
|
+
break;
|
|
1155
|
+
}
|
|
1156
|
+
foundModifier = true;
|
|
1157
|
+
switch (metadata.modifierName) {
|
|
1158
|
+
case "once":
|
|
1159
|
+
modifiers.once = true;
|
|
1160
|
+
break;
|
|
1161
|
+
case "debounce":
|
|
1162
|
+
if (typeof metadata.value === "number") {
|
|
1163
|
+
modifiers.debounce = metadata.value;
|
|
1069
1164
|
}
|
|
1070
|
-
|
|
1165
|
+
break;
|
|
1166
|
+
case "throttle":
|
|
1167
|
+
if (typeof metadata.value === "number") {
|
|
1168
|
+
modifiers.throttle = metadata.value;
|
|
1169
|
+
}
|
|
1170
|
+
break;
|
|
1171
|
+
case "queue":
|
|
1172
|
+
if (metadata.value === "first" || metadata.value === "last" || metadata.value === "all" || metadata.value === "none") {
|
|
1173
|
+
modifiers.queue = metadata.value;
|
|
1174
|
+
}
|
|
1175
|
+
break;
|
|
1071
1176
|
}
|
|
1177
|
+
tokens.advance();
|
|
1072
1178
|
}
|
|
1073
|
-
|
|
1074
|
-
if (this.stemMatchCount > 0 && this.totalKeywordMatches > 0) {
|
|
1075
|
-
const stemPenalty = this.stemMatchCount / this.totalKeywordMatches * 0.15;
|
|
1076
|
-
baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);
|
|
1077
|
-
}
|
|
1078
|
-
const vsoBoost = this.calculateVSOConfidenceBoost(pattern);
|
|
1079
|
-
baseConfidence = Math.min(1, baseConfidence + vsoBoost);
|
|
1080
|
-
const prepositionAdjustment = this.arabicPrepositionDisambiguation(pattern, captured);
|
|
1081
|
-
baseConfidence = Math.max(0, Math.min(1, baseConfidence + prepositionAdjustment));
|
|
1082
|
-
return baseConfidence;
|
|
1179
|
+
return foundModifier ? modifiers : void 0;
|
|
1083
1180
|
}
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
const
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
"\u0623\u0636\u0641",
|
|
1108
|
-
"\u0623\u0632\u0644",
|
|
1109
|
-
"\u0636\u0639",
|
|
1110
|
-
"\u0627\u062C\u0639\u0644",
|
|
1111
|
-
"\u0639\u064A\u0646",
|
|
1112
|
-
"\u0632\u062F",
|
|
1113
|
-
"\u0627\u0646\u0642\u0635",
|
|
1114
|
-
"\u0633\u062C\u0644",
|
|
1115
|
-
"\u0623\u0638\u0647\u0631",
|
|
1116
|
-
"\u0623\u062E\u0641",
|
|
1117
|
-
"\u0634\u063A\u0644",
|
|
1118
|
-
"\u0623\u0631\u0633\u0644",
|
|
1119
|
-
"\u0631\u0643\u0632",
|
|
1120
|
-
"\u0634\u0648\u0634",
|
|
1121
|
-
"\u062A\u0648\u0642\u0641",
|
|
1122
|
-
"\u0627\u0646\u0633\u062E",
|
|
1123
|
-
"\u0627\u062D\u0630\u0641",
|
|
1124
|
-
"\u0627\u0635\u0646\u0639",
|
|
1125
|
-
"\u0627\u0646\u062A\u0638\u0631",
|
|
1126
|
-
"\u0627\u0646\u062A\u0642\u0627\u0644",
|
|
1127
|
-
"\u0623\u0648"
|
|
1128
|
-
]);
|
|
1129
|
-
if (ARABIC_VERBS.has(firstToken.value)) {
|
|
1130
|
-
return 0.15;
|
|
1131
|
-
}
|
|
1132
|
-
if (firstToken.alternatives) {
|
|
1133
|
-
for (const alt of firstToken.alternatives) {
|
|
1134
|
-
if (ARABIC_VERBS.has(alt)) {
|
|
1135
|
-
return 0.15;
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1181
|
+
};
|
|
1182
|
+
/** Maximum tokens to scan ahead when looking for a group's leading marker */
|
|
1183
|
+
_PatternMatcher.MAX_MARKER_SCAN = 3;
|
|
1184
|
+
var PatternMatcher = _PatternMatcher;
|
|
1185
|
+
var patternMatcher = new PatternMatcher();
|
|
1186
|
+
function matchPattern(tokens, pattern) {
|
|
1187
|
+
return patternMatcher.matchPattern(tokens, pattern);
|
|
1188
|
+
}
|
|
1189
|
+
function matchBest(tokens, patterns) {
|
|
1190
|
+
return patternMatcher.matchBest(tokens, patterns);
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
// src/core/tokenization/token-utils.ts
|
|
1194
|
+
var TokenStreamImpl = class {
|
|
1195
|
+
constructor(tokens, language) {
|
|
1196
|
+
this.pos = 0;
|
|
1197
|
+
this.tokens = tokens;
|
|
1198
|
+
this.language = language;
|
|
1199
|
+
}
|
|
1200
|
+
peek(offset = 0) {
|
|
1201
|
+
const index = this.pos + offset;
|
|
1202
|
+
if (index < 0 || index >= this.tokens.length) {
|
|
1203
|
+
return null;
|
|
1138
1204
|
}
|
|
1139
|
-
return
|
|
1205
|
+
return this.tokens[index];
|
|
1206
|
+
}
|
|
1207
|
+
advance() {
|
|
1208
|
+
if (this.isAtEnd()) {
|
|
1209
|
+
throw new Error("Unexpected end of token stream");
|
|
1210
|
+
}
|
|
1211
|
+
return this.tokens[this.pos++];
|
|
1212
|
+
}
|
|
1213
|
+
isAtEnd() {
|
|
1214
|
+
return this.pos >= this.tokens.length;
|
|
1215
|
+
}
|
|
1216
|
+
mark() {
|
|
1217
|
+
return { position: this.pos };
|
|
1218
|
+
}
|
|
1219
|
+
reset(mark) {
|
|
1220
|
+
this.pos = mark.position;
|
|
1221
|
+
}
|
|
1222
|
+
position() {
|
|
1223
|
+
return this.pos;
|
|
1140
1224
|
}
|
|
1141
1225
|
/**
|
|
1142
|
-
*
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
*
|
|
1149
|
-
*
|
|
1150
|
-
* This method analyzes the prepositions used with captured semantic roles and
|
|
1151
|
-
* adjusts confidence based on idiomaticity:
|
|
1152
|
-
* - +0.10 for highly idiomatic preposition choices
|
|
1153
|
-
* - -0.10 for less natural preposition choices
|
|
1154
|
-
*
|
|
1155
|
-
* @param pattern The language pattern being matched
|
|
1156
|
-
* @param captured The captured semantic values
|
|
1157
|
-
* @returns Confidence adjustment (-0.10 to +0.10)
|
|
1226
|
+
* Get remaining tokens as an array.
|
|
1227
|
+
*/
|
|
1228
|
+
remaining() {
|
|
1229
|
+
return this.tokens.slice(this.pos);
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Consume tokens while predicate is true.
|
|
1158
1233
|
*/
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1234
|
+
takeWhile(predicate) {
|
|
1235
|
+
const result = [];
|
|
1236
|
+
while (!this.isAtEnd() && predicate(this.peek())) {
|
|
1237
|
+
result.push(this.advance());
|
|
1238
|
+
}
|
|
1239
|
+
return result;
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Skip tokens while predicate is true.
|
|
1243
|
+
*/
|
|
1244
|
+
skipWhile(predicate) {
|
|
1245
|
+
while (!this.isAtEnd() && predicate(this.peek())) {
|
|
1246
|
+
this.advance();
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
};
|
|
1250
|
+
function createPosition(start, end) {
|
|
1251
|
+
return { start, end };
|
|
1252
|
+
}
|
|
1253
|
+
function createToken(valueOrParams, kind, position, normalizedOrOptions) {
|
|
1254
|
+
if (typeof valueOrParams === "object") {
|
|
1255
|
+
const { value: value2, kind: kind2, position: position2, normalized: normalized2, stem, stemConfidence, metadata } = valueOrParams;
|
|
1256
|
+
return {
|
|
1257
|
+
value: value2,
|
|
1258
|
+
kind: kind2,
|
|
1259
|
+
position: position2,
|
|
1260
|
+
...normalized2 !== void 0 && { normalized: normalized2 },
|
|
1261
|
+
...stem !== void 0 && { stem },
|
|
1262
|
+
...stemConfidence !== void 0 && { stemConfidence },
|
|
1263
|
+
...metadata !== void 0 && { metadata }
|
|
1181
1264
|
};
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1265
|
+
}
|
|
1266
|
+
const value = valueOrParams;
|
|
1267
|
+
if (!kind || !position) {
|
|
1268
|
+
throw new Error("createToken requires kind and position parameters");
|
|
1269
|
+
}
|
|
1270
|
+
if (typeof normalizedOrOptions === "string") {
|
|
1271
|
+
return { value, kind, position, normalized: normalizedOrOptions };
|
|
1272
|
+
}
|
|
1273
|
+
if (normalizedOrOptions) {
|
|
1274
|
+
const { normalized: normalized2, stem, stemConfidence, metadata } = normalizedOrOptions;
|
|
1275
|
+
return {
|
|
1276
|
+
value,
|
|
1277
|
+
kind,
|
|
1278
|
+
position,
|
|
1279
|
+
...normalized2 !== void 0 && { normalized: normalized2 },
|
|
1280
|
+
...stem !== void 0 && { stem },
|
|
1281
|
+
...stemConfidence !== void 0 && { stemConfidence },
|
|
1282
|
+
...metadata !== void 0 && { metadata }
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
return { value, kind, position };
|
|
1286
|
+
}
|
|
1287
|
+
function isWhitespace(char) {
|
|
1288
|
+
return /\s/.test(char);
|
|
1289
|
+
}
|
|
1290
|
+
function isSelectorStart(char) {
|
|
1291
|
+
return char === "#" || char === "." || char === "[" || char === "@" || char === "*" || char === "<";
|
|
1292
|
+
}
|
|
1293
|
+
function isQuote(char) {
|
|
1294
|
+
return char === '"' || char === "'" || char === "`" || char === "\u300C" || char === "\u300D";
|
|
1295
|
+
}
|
|
1296
|
+
function isDigit(char) {
|
|
1297
|
+
return /\d/.test(char);
|
|
1298
|
+
}
|
|
1299
|
+
function stripOptionalDiacritics(word) {
|
|
1300
|
+
return word.replace(/[\u064b-\u0652\u0670]/g, "");
|
|
1301
|
+
}
|
|
1302
|
+
function isAsciiLetter(char) {
|
|
1303
|
+
return /[a-zA-Z]/.test(char);
|
|
1304
|
+
}
|
|
1305
|
+
function isAsciiIdentifierChar(char) {
|
|
1306
|
+
return /[a-zA-Z0-9_-]/.test(char);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// src/core/matching/match-skeleton.ts
|
|
1310
|
+
function groupHasRole(group) {
|
|
1311
|
+
return group.tokens.some((t) => t.type === "role" || t.type === "group" && groupHasRole(t));
|
|
1312
|
+
}
|
|
1313
|
+
var MatchSkeleton = class {
|
|
1314
|
+
/**
|
|
1315
|
+
* @param makeReader - builds the grammar's reader, handed this matcher's view
|
|
1316
|
+
* of the match in progress (one reader per matcher).
|
|
1317
|
+
*/
|
|
1318
|
+
constructor(makeReader, confidenceModel) {
|
|
1319
|
+
/**
|
|
1320
|
+
* The pattern tokens still to match after the one being matched, through
|
|
1321
|
+
* every enclosing group: a value stops at any marker the pattern still owes.
|
|
1322
|
+
*/
|
|
1323
|
+
this.patternRest = [];
|
|
1324
|
+
/**
|
|
1325
|
+
* Whether the role slot being matched directly follows a literal the pattern
|
|
1326
|
+
* matched: its marker (`[por {quantity}]`), or the command's verb.
|
|
1327
|
+
*/
|
|
1328
|
+
this.slotAfterLiteral = false;
|
|
1329
|
+
/**
|
|
1330
|
+
* Selective memoization cache (Phase 6.1).
|
|
1331
|
+
* Caches pattern match results keyed by `tokenPosition:patternId`.
|
|
1332
|
+
* Cleared before each top-level matchBest() call.
|
|
1333
|
+
*/
|
|
1334
|
+
this.matchCache = /* @__PURE__ */ new Map();
|
|
1335
|
+
/**
|
|
1336
|
+
* Stream index where each role's capture began, for the current
|
|
1337
|
+
* `matchPattern` call. Rebuilt per call, written on the same success path as
|
|
1338
|
+
* `captured` — see `PatternMatchResult.roleStarts`.
|
|
1339
|
+
*/
|
|
1340
|
+
this.roleStarts = /* @__PURE__ */ new Map();
|
|
1341
|
+
/**
|
|
1342
|
+
* Track stem matches for confidence calculation.
|
|
1343
|
+
* This is set during matching and read during confidence calculation.
|
|
1344
|
+
*/
|
|
1345
|
+
this.stemMatchCount = 0;
|
|
1346
|
+
this.totalKeywordMatches = 0;
|
|
1347
|
+
this.confidenceModel = confidenceModel;
|
|
1348
|
+
this.reader = makeReader({
|
|
1349
|
+
patternRest: () => this.patternRest,
|
|
1350
|
+
slotAfterLiteral: () => this.slotAfterLiteral,
|
|
1351
|
+
wouldMatch: (pt, token) => this.patternTokenWouldMatch(pt, token)
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* Try to match a single pattern against the token stream.
|
|
1356
|
+
* Returns the match result or null if no match.
|
|
1357
|
+
*/
|
|
1358
|
+
matchPattern(tokens, pattern) {
|
|
1359
|
+
const mark = tokens.mark();
|
|
1360
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1361
|
+
this.reader.beginPattern(pattern);
|
|
1362
|
+
this.stemMatchCount = 0;
|
|
1363
|
+
this.totalKeywordMatches = 0;
|
|
1364
|
+
this.roleStarts = /* @__PURE__ */ new Map();
|
|
1365
|
+
this.patternRest = [];
|
|
1366
|
+
const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);
|
|
1367
|
+
if (!success) {
|
|
1368
|
+
tokens.reset(mark);
|
|
1369
|
+
return null;
|
|
1370
|
+
}
|
|
1371
|
+
const confidence = this.confidenceModel.calculate({
|
|
1372
|
+
pattern,
|
|
1373
|
+
captured,
|
|
1374
|
+
stemMatchCount: this.stemMatchCount,
|
|
1375
|
+
totalKeywordMatches: this.totalKeywordMatches
|
|
1376
|
+
});
|
|
1377
|
+
this.applyExtractionRules(pattern, captured);
|
|
1378
|
+
return {
|
|
1379
|
+
pattern,
|
|
1380
|
+
captured,
|
|
1381
|
+
consumedTokens: tokens.position() - mark.position,
|
|
1382
|
+
confidence,
|
|
1383
|
+
roleStarts: this.roleStarts,
|
|
1384
|
+
...this.reader.resultFields?.()
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Try to match multiple patterns, return the best match.
|
|
1389
|
+
*/
|
|
1390
|
+
matchBest(tokens, patterns) {
|
|
1391
|
+
this.matchCache.clear();
|
|
1392
|
+
const matches = [];
|
|
1393
|
+
const startPos = tokens.position();
|
|
1394
|
+
for (const pattern of patterns) {
|
|
1395
|
+
const mark = tokens.mark();
|
|
1396
|
+
const cacheKey = `${startPos}:${pattern.id}`;
|
|
1397
|
+
let result;
|
|
1398
|
+
if (this.matchCache.has(cacheKey)) {
|
|
1399
|
+
result = this.matchCache.get(cacheKey);
|
|
1400
|
+
} else {
|
|
1401
|
+
result = this.matchPattern(tokens, pattern);
|
|
1402
|
+
this.matchCache.set(cacheKey, result);
|
|
1186
1403
|
}
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1404
|
+
if (result) {
|
|
1405
|
+
matches.push(result);
|
|
1406
|
+
}
|
|
1407
|
+
tokens.reset(mark);
|
|
1408
|
+
}
|
|
1409
|
+
if (matches.length === 0) {
|
|
1410
|
+
return null;
|
|
1411
|
+
}
|
|
1412
|
+
matches.sort((a, b) => {
|
|
1413
|
+
const priorityDiff = b.pattern.priority - a.pattern.priority;
|
|
1414
|
+
if (priorityDiff !== 0) return priorityDiff;
|
|
1415
|
+
return b.confidence - a.confidence;
|
|
1416
|
+
});
|
|
1417
|
+
const best = matches[0];
|
|
1418
|
+
this.matchPattern(tokens, best.pattern);
|
|
1419
|
+
return best;
|
|
1420
|
+
}
|
|
1421
|
+
/**
|
|
1422
|
+
* Match a sequence of pattern tokens against the token stream.
|
|
1423
|
+
*/
|
|
1424
|
+
matchTokenSequence(tokens, patternTokens, captured, nextAfterSequence) {
|
|
1425
|
+
this.reader.skipLeading?.(tokens, patternTokens);
|
|
1426
|
+
for (let i = 0; i < patternTokens.length; i++) {
|
|
1427
|
+
const patternToken = patternTokens[i];
|
|
1428
|
+
this.reader.beforePatternToken?.(tokens, patternTokens, i, captured);
|
|
1429
|
+
if (this.reader.maySkipSlot(
|
|
1430
|
+
patternToken,
|
|
1431
|
+
tokens.peek(),
|
|
1432
|
+
patternTokens[i + 1] ?? nextAfterSequence
|
|
1433
|
+
)) {
|
|
1434
|
+
const skipMark = tokens.mark();
|
|
1435
|
+
const speculative = new Map(captured);
|
|
1436
|
+
if (this.matchTokenSequence(
|
|
1437
|
+
tokens,
|
|
1438
|
+
patternTokens.slice(i + 1),
|
|
1439
|
+
speculative,
|
|
1440
|
+
nextAfterSequence
|
|
1441
|
+
) && this.reader.atClauseEnd(tokens)) {
|
|
1442
|
+
captured.clear();
|
|
1443
|
+
for (const [role, value] of speculative) captured.set(role, value);
|
|
1444
|
+
return true;
|
|
1445
|
+
}
|
|
1446
|
+
tokens.reset(skipMark);
|
|
1447
|
+
}
|
|
1448
|
+
const outerRest = this.patternRest;
|
|
1449
|
+
this.patternRest = [...patternTokens.slice(i + 1), ...outerRest];
|
|
1450
|
+
this.slotAfterLiteral = patternToken.type === "role" && patternTokens[i - 1]?.type === "literal";
|
|
1451
|
+
const matched = this.matchPatternToken(
|
|
1452
|
+
tokens,
|
|
1453
|
+
patternToken,
|
|
1454
|
+
captured,
|
|
1455
|
+
patternTokens[i + 1] ?? nextAfterSequence
|
|
1456
|
+
);
|
|
1457
|
+
this.patternRest = outerRest;
|
|
1458
|
+
if (!matched) {
|
|
1459
|
+
if (this.isOptional(patternToken)) {
|
|
1460
|
+
continue;
|
|
1194
1461
|
}
|
|
1462
|
+
return false;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
return true;
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Match a single pattern token against the current position in the stream.
|
|
1469
|
+
*/
|
|
1470
|
+
matchPatternToken(tokens, patternToken, captured, nextPatternToken) {
|
|
1471
|
+
switch (patternToken.type) {
|
|
1472
|
+
case "literal":
|
|
1473
|
+
return this.matchLiteralToken(tokens, patternToken);
|
|
1474
|
+
case "role": {
|
|
1475
|
+
const roleStart = tokens.position();
|
|
1476
|
+
const matchedRole = this.reader.readRole(tokens, patternToken, captured, nextPatternToken);
|
|
1477
|
+
if (matchedRole && captured.has(patternToken.role)) {
|
|
1478
|
+
this.roleStarts.set(patternToken.role, roleStart);
|
|
1479
|
+
}
|
|
1480
|
+
return matchedRole;
|
|
1481
|
+
}
|
|
1482
|
+
case "group":
|
|
1483
|
+
return this.matchGroupToken(tokens, patternToken, captured, nextPatternToken);
|
|
1484
|
+
default:
|
|
1485
|
+
return false;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* Match a literal pattern token (keyword or particle).
|
|
1490
|
+
*/
|
|
1491
|
+
matchLiteralToken(tokens, patternToken) {
|
|
1492
|
+
const token = tokens.peek();
|
|
1493
|
+
if (!token) return false;
|
|
1494
|
+
const matchType = this.getMatchType(token, patternToken.value);
|
|
1495
|
+
if (matchType !== "none") {
|
|
1496
|
+
this.totalKeywordMatches++;
|
|
1497
|
+
if (matchType === "stem") {
|
|
1498
|
+
this.stemMatchCount++;
|
|
1499
|
+
}
|
|
1500
|
+
tokens.advance();
|
|
1501
|
+
return true;
|
|
1502
|
+
}
|
|
1503
|
+
if (patternToken.alternatives) {
|
|
1504
|
+
for (const alt of patternToken.alternatives) {
|
|
1505
|
+
const altMatchType = this.getMatchType(token, alt);
|
|
1506
|
+
if (altMatchType !== "none") {
|
|
1507
|
+
this.totalKeywordMatches++;
|
|
1508
|
+
if (altMatchType === "stem") {
|
|
1509
|
+
this.stemMatchCount++;
|
|
1510
|
+
}
|
|
1511
|
+
tokens.advance();
|
|
1512
|
+
return true;
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
for (const value of [patternToken.value, ...patternToken.alternatives ?? []]) {
|
|
1517
|
+
for (const sep of ["-", "_"]) {
|
|
1518
|
+
if (value.includes(sep) && this.tryMatchShatteredCompound(tokens, value, sep)) {
|
|
1519
|
+
this.totalKeywordMatches++;
|
|
1520
|
+
return true;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return false;
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Match a compound keyword (`titik-henti`, `по_умолчанию`) against a
|
|
1528
|
+
* shattered token run (`titik` `-` `henti` / `по` `_` `умолчанию`): word
|
|
1529
|
+
* segments must be identifier/keyword/particle tokens equal to the expected
|
|
1530
|
+
* segments (case-insensitive; particle because prepositions like ru `по` /
|
|
1531
|
+
* uk `за` lead some underscore compounds), separators lone `sep` tokens.
|
|
1532
|
+
* Consumes the run on success, resets the stream on failure.
|
|
1533
|
+
*/
|
|
1534
|
+
tryMatchShatteredCompound(tokens, expected, sep) {
|
|
1535
|
+
const segments = expected.split(sep);
|
|
1536
|
+
if (segments.length < 2 || segments.some((s) => s.length === 0)) return false;
|
|
1537
|
+
const mark = tokens.mark();
|
|
1538
|
+
for (let i = 0; i < segments.length; i++) {
|
|
1539
|
+
if (i > 0) {
|
|
1540
|
+
const sepToken = tokens.peek();
|
|
1541
|
+
if (!sepToken || sepToken.value !== sep) {
|
|
1542
|
+
tokens.reset(mark);
|
|
1543
|
+
return false;
|
|
1544
|
+
}
|
|
1545
|
+
tokens.advance();
|
|
1546
|
+
}
|
|
1547
|
+
const word = tokens.peek();
|
|
1548
|
+
if (!word || word.kind !== "identifier" && word.kind !== "keyword" && word.kind !== "particle" || word.value.toLowerCase() !== segments[i].toLowerCase()) {
|
|
1549
|
+
tokens.reset(mark);
|
|
1550
|
+
return false;
|
|
1551
|
+
}
|
|
1552
|
+
tokens.advance();
|
|
1553
|
+
}
|
|
1554
|
+
return true;
|
|
1555
|
+
}
|
|
1556
|
+
/**
|
|
1557
|
+
* Match a group pattern token (optional sequence).
|
|
1558
|
+
*/
|
|
1559
|
+
matchGroupToken(tokens, patternToken, captured, nextPatternToken) {
|
|
1560
|
+
const mark = tokens.mark();
|
|
1561
|
+
const capturedBefore = new Map(captured);
|
|
1562
|
+
let success = this.matchTokenSequence(tokens, patternToken.tokens, captured, nextPatternToken);
|
|
1563
|
+
if (success && tokens.position() > mark.position && groupHasRole(patternToken) && [...captured].every(([role, value]) => capturedBefore.get(role) === value) && captured.size === capturedBefore.size) {
|
|
1564
|
+
success = false;
|
|
1565
|
+
}
|
|
1566
|
+
if (success) {
|
|
1567
|
+
const markerLiterals = [];
|
|
1568
|
+
for (const inner of patternToken.tokens) {
|
|
1569
|
+
if (inner.type === "group" && inner.renderRequired) {
|
|
1570
|
+
for (const t of inner.tokens) {
|
|
1571
|
+
if (t.type === "literal") markerLiterals.push(t.value, ...t.alternatives ?? []);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
if (markerLiterals.length > 0) {
|
|
1576
|
+
const addedRole = [...captured.keys()].some((role) => !capturedBefore.has(role));
|
|
1577
|
+
if (addedRole) {
|
|
1578
|
+
const last = tokens.tokens[tokens.position() - 1];
|
|
1579
|
+
const markerSeen = last !== void 0 && tokens.position() > mark.position && markerLiterals.some((lit) => this.getMatchType(last, lit) !== "none");
|
|
1580
|
+
if (!markerSeen) success = false;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
if (!success) {
|
|
1585
|
+
tokens.reset(mark);
|
|
1586
|
+
for (const role of captured.keys()) {
|
|
1587
|
+
if (!capturedBefore.has(role)) {
|
|
1588
|
+
captured.delete(role);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
for (const [role, value] of capturedBefore) {
|
|
1592
|
+
if (captured.get(role) !== value) {
|
|
1593
|
+
captured.set(role, value);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
return patternToken.optional || false;
|
|
1597
|
+
}
|
|
1598
|
+
return true;
|
|
1599
|
+
}
|
|
1600
|
+
/**
|
|
1601
|
+
* Whether a pattern token (literal, or a group starting with a literal) would
|
|
1602
|
+
* match the given stream token. Used to keep the event-head source-clause
|
|
1603
|
+
* consumption from stealing a marker the pattern explicitly expects.
|
|
1604
|
+
*/
|
|
1605
|
+
patternTokenWouldMatch(pt, token) {
|
|
1606
|
+
if (!pt) return false;
|
|
1607
|
+
if (pt.type === "literal") {
|
|
1608
|
+
if (this.getMatchType(token, pt.value) !== "none") return true;
|
|
1609
|
+
return !!pt.alternatives?.some((a) => this.getMatchType(token, a) !== "none");
|
|
1610
|
+
}
|
|
1611
|
+
if (pt.type === "group") {
|
|
1612
|
+
return this.patternTokenWouldMatch(pt.tokens?.[0], token);
|
|
1613
|
+
}
|
|
1614
|
+
return false;
|
|
1615
|
+
}
|
|
1616
|
+
/**
|
|
1617
|
+
* Get the type of match for a token against a value.
|
|
1618
|
+
* Used for confidence calculation.
|
|
1619
|
+
*/
|
|
1620
|
+
getMatchType(token, value) {
|
|
1621
|
+
if (token.value === value) return "exact";
|
|
1622
|
+
if (token.normalized === value) return "normalized";
|
|
1623
|
+
if (token.stem === value && token.stemConfidence !== void 0 && token.stemConfidence >= 0.7) {
|
|
1624
|
+
return "stem";
|
|
1625
|
+
}
|
|
1626
|
+
if (token.kind === "keyword" && token.value.toLowerCase() === value.toLowerCase()) {
|
|
1627
|
+
return "case-insensitive";
|
|
1628
|
+
}
|
|
1629
|
+
if (token.kind === "keyword") {
|
|
1630
|
+
const strippedToken = stripOptionalDiacritics(token.value).toLowerCase();
|
|
1631
|
+
if (strippedToken && strippedToken === stripOptionalDiacritics(value).toLowerCase()) {
|
|
1632
|
+
return "case-insensitive";
|
|
1195
1633
|
}
|
|
1196
1634
|
}
|
|
1197
|
-
return
|
|
1635
|
+
return "none";
|
|
1198
1636
|
}
|
|
1199
1637
|
/**
|
|
1200
|
-
*
|
|
1201
|
-
*
|
|
1638
|
+
* Apply extraction rules to fill in static values and defaults for missing
|
|
1639
|
+
* roles, and re-shape captured roles that declare a `transform` (the
|
|
1640
|
+
* ExtractionRule field was documented but unwired — go-qu-url-dest is the
|
|
1641
|
+
* first consumer: it re-types the marker-bound capture to the expression
|
|
1642
|
+
* shape the en reference produces).
|
|
1202
1643
|
*/
|
|
1203
|
-
|
|
1204
|
-
const
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
if (
|
|
1212
|
-
|
|
1644
|
+
applyExtractionRules(pattern, captured) {
|
|
1645
|
+
for (const [role, rule] of Object.entries(pattern.extraction)) {
|
|
1646
|
+
const existing = captured.get(role);
|
|
1647
|
+
if (existing) {
|
|
1648
|
+
if (rule.transform) {
|
|
1649
|
+
const raw = existing.type === "literal" ? String(existing.value) : String(existing.raw ?? "");
|
|
1650
|
+
captured.set(role, rule.transform(raw));
|
|
1651
|
+
}
|
|
1652
|
+
} else if (rule.value !== void 0) {
|
|
1653
|
+
captured.set(
|
|
1654
|
+
role,
|
|
1655
|
+
rule.valueIsExpression ? { type: "expression", raw: rule.value } : { type: "literal", value: rule.value }
|
|
1656
|
+
);
|
|
1657
|
+
} else if (rule.default) {
|
|
1658
|
+
const implicitDefault = {
|
|
1659
|
+
...rule.default,
|
|
1660
|
+
implicit: true
|
|
1661
|
+
};
|
|
1662
|
+
captured.set(role, implicitDefault);
|
|
1213
1663
|
}
|
|
1214
|
-
tokens.reset(mark);
|
|
1215
|
-
}
|
|
1216
|
-
if (tokenLower === "class") {
|
|
1217
|
-
tokens.advance();
|
|
1218
1664
|
}
|
|
1219
1665
|
}
|
|
1220
1666
|
/**
|
|
1221
|
-
*
|
|
1222
|
-
* Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)
|
|
1223
|
-
* that can appear after event names.
|
|
1224
|
-
*
|
|
1225
|
-
* Returns EventModifiers object or undefined if no modifiers found.
|
|
1667
|
+
* Check if a pattern token is optional.
|
|
1226
1668
|
*/
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1669
|
+
isOptional(patternToken) {
|
|
1670
|
+
return patternToken.type !== "literal" && patternToken.optional === true;
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
|
|
1674
|
+
// src/core/matching/stock-reader.ts
|
|
1675
|
+
function greedyStopMarkers(rest) {
|
|
1676
|
+
const markers = /* @__PURE__ */ new Set();
|
|
1677
|
+
const add = (pt) => {
|
|
1678
|
+
markers.add(pt.value.toLowerCase());
|
|
1679
|
+
for (const alt of pt.alternatives ?? []) markers.add(alt.toLowerCase());
|
|
1680
|
+
};
|
|
1681
|
+
for (const pt of rest) {
|
|
1682
|
+
if (pt.type === "literal") {
|
|
1683
|
+
add(pt);
|
|
1684
|
+
break;
|
|
1685
|
+
}
|
|
1686
|
+
if (pt.type === "group") {
|
|
1687
|
+
const lead = pt.tokens.find((t) => t.type === "literal");
|
|
1688
|
+
if (lead?.type === "literal") add(lead);
|
|
1689
|
+
if (!pt.optional) break;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
return markers;
|
|
1693
|
+
}
|
|
1694
|
+
function isStopMarker(token, stopMarkers) {
|
|
1695
|
+
if (stopMarkers.size === 0) return false;
|
|
1696
|
+
if (stopMarkers.has(token.value.toLowerCase())) return true;
|
|
1697
|
+
return !!token.normalized && stopMarkers.has(token.normalized.toLowerCase());
|
|
1698
|
+
}
|
|
1699
|
+
function readGreedy(tokens, stopMarkers) {
|
|
1700
|
+
const values = [];
|
|
1701
|
+
while (!tokens.isAtEnd()) {
|
|
1702
|
+
const next = tokens.peek();
|
|
1703
|
+
if (!next || isStopMarker(next, stopMarkers)) break;
|
|
1704
|
+
values.push(next.value);
|
|
1705
|
+
tokens.advance();
|
|
1706
|
+
}
|
|
1707
|
+
return values.length > 0 ? { type: "expression", raw: values.join(" ") } : null;
|
|
1708
|
+
}
|
|
1709
|
+
var StockValueReader = class {
|
|
1710
|
+
constructor(view, profiles = {}) {
|
|
1711
|
+
this.view = view;
|
|
1712
|
+
this.profiles = profiles;
|
|
1713
|
+
}
|
|
1714
|
+
beginPattern(pattern) {
|
|
1715
|
+
this.profile = this.profiles[pattern.language] ?? { code: pattern.language };
|
|
1716
|
+
this.lastOptional = void 0;
|
|
1717
|
+
}
|
|
1718
|
+
readRole(tokens, slot, captured, next) {
|
|
1719
|
+
const start = tokens.mark();
|
|
1720
|
+
if (this.readOnce(tokens, slot, captured, next, true)) {
|
|
1721
|
+
if (!slot.optional) {
|
|
1722
|
+
this.lastOptional = void 0;
|
|
1723
|
+
} else if (captured.has(slot.role) && tokens.position() > start.position && !this.view.slotAfterLiteral() && next?.type !== "literal") {
|
|
1724
|
+
this.lastOptional = { role: slot.role, start, end: tokens.position() };
|
|
1238
1725
|
}
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1726
|
+
return true;
|
|
1727
|
+
}
|
|
1728
|
+
const before = this.lastOptional;
|
|
1729
|
+
if (slot.optional || !before || before.end !== tokens.position()) return false;
|
|
1730
|
+
this.lastOptional = void 0;
|
|
1731
|
+
tokens.reset(before.start);
|
|
1732
|
+
captured.delete(before.role);
|
|
1733
|
+
return this.readOnce(tokens, slot, captured, next, false);
|
|
1734
|
+
}
|
|
1735
|
+
/** One read of `slot`; `guard` refuses a required slot the marker the pattern wants next. */
|
|
1736
|
+
readOnce(tokens, slot, captured, next, guard) {
|
|
1737
|
+
if (guard && !slot.optional && next?.type === "literal") {
|
|
1738
|
+
const token = tokens.peek();
|
|
1739
|
+
if (token && this.view.wouldMatch(next, token)) return false;
|
|
1740
|
+
}
|
|
1741
|
+
if (slot.greedy) {
|
|
1742
|
+
const value = readGreedy(tokens, greedyStopMarkers(this.view.patternRest()));
|
|
1743
|
+
if (value) {
|
|
1744
|
+
captured.set(slot.role, value);
|
|
1745
|
+
return true;
|
|
1259
1746
|
}
|
|
1260
|
-
|
|
1747
|
+
return slot.optional ?? false;
|
|
1261
1748
|
}
|
|
1262
|
-
return
|
|
1749
|
+
return readRoleValue(tokens, slot, captured, this.profile);
|
|
1750
|
+
}
|
|
1751
|
+
maySkipSlot(patternToken, token, next) {
|
|
1752
|
+
const slot = patternToken.type === "group" && patternToken.optional ? patternToken.tokens.every((t) => t.type === "role") ? patternToken.tokens[0] : void 0 : patternToken;
|
|
1753
|
+
if (!slot || slot.type !== "role" || !slot.optional) return false;
|
|
1754
|
+
return !!token && this.view.wouldMatch(next, token);
|
|
1755
|
+
}
|
|
1756
|
+
atClauseEnd(tokens) {
|
|
1757
|
+
return tokens.isAtEnd();
|
|
1263
1758
|
}
|
|
1264
1759
|
};
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
// ==========================================================================
|
|
1268
|
-
// Depth Limits for Expression Parsing (security hardening)
|
|
1269
|
-
// ==========================================================================
|
|
1270
|
-
/** Maximum depth for nested property access (e.g., a.b.c.d...) */
|
|
1271
|
-
_PatternMatcher.MAX_PROPERTY_DEPTH = 10;
|
|
1272
|
-
/** Maximum number of arguments in method calls */
|
|
1273
|
-
_PatternMatcher.MAX_METHOD_ARGS = 20;
|
|
1274
|
-
// ===========================================================================
|
|
1275
|
-
// English Idiom Support - Noise Word Handling
|
|
1276
|
-
// ===========================================================================
|
|
1277
|
-
/**
|
|
1278
|
-
* Noise words that can be skipped in English for more natural syntax.
|
|
1279
|
-
* - "the" before selectors: "toggle the .active" → "toggle .active"
|
|
1280
|
-
* - "class" after class selectors: "add the .visible class" → "add .visible"
|
|
1281
|
-
*/
|
|
1282
|
-
_PatternMatcher.ENGLISH_NOISE_WORDS = /* @__PURE__ */ new Set(["the", "a", "an"]);
|
|
1283
|
-
var PatternMatcher = _PatternMatcher;
|
|
1284
|
-
var patternMatcher = new PatternMatcher();
|
|
1285
|
-
function matchPattern(tokens, pattern) {
|
|
1286
|
-
return patternMatcher.matchPattern(tokens, pattern);
|
|
1287
|
-
}
|
|
1288
|
-
function matchBest(tokens, patterns) {
|
|
1289
|
-
return patternMatcher.matchBest(tokens, patterns);
|
|
1760
|
+
function createStockReader(profiles = {}) {
|
|
1761
|
+
return (view) => new StockValueReader(view, profiles);
|
|
1290
1762
|
}
|
|
1291
1763
|
|
|
1292
1764
|
// src/generation/pattern-generator.ts
|
|
@@ -1525,39 +1997,614 @@ function buildRenderTables(schemas, profiles) {
|
|
|
1525
1997
|
markerPositions[role][profile.code] = markerDef.position;
|
|
1526
1998
|
}
|
|
1527
1999
|
}
|
|
1528
|
-
const schemaMap = /* @__PURE__ */ new Map();
|
|
1529
|
-
for (const s of schemas) schemaMap.set(s.action, s);
|
|
1530
|
-
return { keywords, markers, markerPositions, sovLanguages, schemaMap };
|
|
2000
|
+
const schemaMap = /* @__PURE__ */ new Map();
|
|
2001
|
+
for (const s of schemas) schemaMap.set(s.action, s);
|
|
2002
|
+
return { keywords, markers, markerPositions, sovLanguages, schemaMap };
|
|
2003
|
+
}
|
|
2004
|
+
function renderFromSchema(node, language, tables) {
|
|
2005
|
+
const schema = tables.schemaMap.get(node.action);
|
|
2006
|
+
if (!schema) return null;
|
|
2007
|
+
const keyword = lookupKeyword(tables.keywords, node.action, language);
|
|
2008
|
+
const isSOV = tables.sovLanguages.has(language);
|
|
2009
|
+
const ordered = sortRolesByWordOrder([...schema.roles], isSOV ? "SOV" : "SVO");
|
|
2010
|
+
const preVerb = [];
|
|
2011
|
+
const postVerb = [];
|
|
2012
|
+
for (const role of ordered) {
|
|
2013
|
+
let value = extractRoleValue(node, role.role);
|
|
2014
|
+
if (!value && role.default !== void 0) {
|
|
2015
|
+
value = String(extractValue(role.default));
|
|
2016
|
+
}
|
|
2017
|
+
if (!value) continue;
|
|
2018
|
+
if (role.quoteMultiword && /\s/.test(value) && !/^(["']).*\1$/.test(value)) {
|
|
2019
|
+
value = `"${value}"`;
|
|
2020
|
+
}
|
|
2021
|
+
const markerText = role.renderOverride?.[language] ?? role.markerOverride?.[language] ?? role.renderOverride?.["*"] ?? tables.markers[role.role]?.[language];
|
|
2022
|
+
const markerPosition = role.markerPositionOverride?.[language] ?? role.markerPosition ?? tables.markerPositions[role.role]?.[language] ?? (isSOV ? "after" : "before");
|
|
2023
|
+
const bucket = isSOV && role.sovSlot === "postVerb" ? postVerb : preVerb;
|
|
2024
|
+
if (markerText && markerPosition === "before") {
|
|
2025
|
+
bucket.push(markerText, value);
|
|
2026
|
+
} else if (markerText) {
|
|
2027
|
+
bucket.push(value, markerText);
|
|
2028
|
+
} else {
|
|
2029
|
+
bucket.push(value);
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
return isSOV ? buildPhrase(...preVerb, keyword, ...postVerb) : buildPhrase(keyword, ...preVerb, ...postVerb);
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
// src/generation/schema-patterns.ts
|
|
2036
|
+
function createSchemaPatternGenerator(grammar) {
|
|
2037
|
+
return {
|
|
2038
|
+
generatePattern: (schema, profile, config) => generatePattern2(grammar, schema, profile, config),
|
|
2039
|
+
generateSimplePattern: (schema, profile, config) => generateSimplePattern(grammar, schema, profile, config),
|
|
2040
|
+
generateVerbFirstPattern: (schema, profile, config) => generateVerbFirstPattern(schema, profile, config),
|
|
2041
|
+
generatePatternVariants: (schema, profile, config) => generatePatternVariants2(grammar, schema, profile, config),
|
|
2042
|
+
buildRoleToken
|
|
2043
|
+
};
|
|
2044
|
+
}
|
|
2045
|
+
function withoutVariantOnlyRoles(schema) {
|
|
2046
|
+
return schema.roles.some((r) => r.variantOnly) ? { ...schema, roles: schema.roles.filter((r) => !r.variantOnly) } : schema;
|
|
2047
|
+
}
|
|
2048
|
+
function sortRolesByPosition(roles, wordOrder, order) {
|
|
2049
|
+
const sortKey = wordOrder === "SOV" ? "sovPosition" : "svoPosition";
|
|
2050
|
+
return [...roles].sort(
|
|
2051
|
+
(a, b) => order === "ascending" ? (a[sortKey] ?? 99) - (b[sortKey] ?? 99) : (b[sortKey] ?? 0) - (a[sortKey] ?? 0)
|
|
2052
|
+
);
|
|
2053
|
+
}
|
|
2054
|
+
function resolveMarkerForRole(roleSpec, profile) {
|
|
2055
|
+
const overrideMarker = roleSpec.markerOverride?.[profile.code];
|
|
2056
|
+
const defaultMarker = profile.roleMarkers[roleSpec.role];
|
|
2057
|
+
if (overrideMarker !== void 0) {
|
|
2058
|
+
const alternatives = legacyMarkerAlternatives(roleSpec, profile.code, overrideMarker);
|
|
2059
|
+
return {
|
|
2060
|
+
primary: overrideMarker,
|
|
2061
|
+
...alternatives && { alternatives },
|
|
2062
|
+
position: defaultMarker?.position ?? "before",
|
|
2063
|
+
isOverride: true
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
if (defaultMarker && defaultMarker.primary) {
|
|
2067
|
+
const result = {
|
|
2068
|
+
primary: defaultMarker.primary,
|
|
2069
|
+
position: defaultMarker.position,
|
|
2070
|
+
isOverride: false
|
|
2071
|
+
};
|
|
2072
|
+
if (defaultMarker.alternatives) {
|
|
2073
|
+
result.alternatives = defaultMarker.alternatives;
|
|
2074
|
+
}
|
|
2075
|
+
return result;
|
|
2076
|
+
}
|
|
2077
|
+
return null;
|
|
2078
|
+
}
|
|
2079
|
+
function legacyMarkerAlternatives(roleSpec, languageCode, overrideMarker) {
|
|
2080
|
+
const legacy = roleSpec.markerLegacy?.[languageCode];
|
|
2081
|
+
if (!legacy?.length) return void 0;
|
|
2082
|
+
const alternatives = [...new Set(legacy)].filter((a) => a && a !== overrideMarker);
|
|
2083
|
+
return alternatives.length ? alternatives : void 0;
|
|
2084
|
+
}
|
|
2085
|
+
function schemaMarkerAlternatives(roleSpec, languageCode, marker) {
|
|
2086
|
+
const legacy = roleSpec.markerLegacy?.[languageCode] ?? [];
|
|
2087
|
+
const variants = roleSpec.methodCarrier ? [] : roleSpec.markerVariants?.[languageCode] ?? [];
|
|
2088
|
+
const alternatives = [.../* @__PURE__ */ new Set([...legacy, ...variants])].filter((a) => a && a !== marker);
|
|
2089
|
+
return alternatives.length ? alternatives : void 0;
|
|
2090
|
+
}
|
|
2091
|
+
var defaultConfig2 = {
|
|
2092
|
+
basePriority: 100,
|
|
2093
|
+
generateSimpleVariants: true,
|
|
2094
|
+
generateAlternatives: true
|
|
2095
|
+
};
|
|
2096
|
+
function generatePattern2(grammar, schema, profile, config = defaultConfig2) {
|
|
2097
|
+
const id = `${schema.action}-${profile.code}-generated`;
|
|
2098
|
+
const priority = config.basePriority ?? 100;
|
|
2099
|
+
const keyword = profile.keywords[schema.action];
|
|
2100
|
+
if (!keyword) {
|
|
2101
|
+
throw new Error(`No keyword translation for '${schema.action}' in ${profile.code}`);
|
|
2102
|
+
}
|
|
2103
|
+
const tokens = buildTokens2(grammar, schema, profile, keyword);
|
|
2104
|
+
const extraction = buildExtractionRulesWithDefaults(schema, profile);
|
|
2105
|
+
const format = buildFormatString2(grammar, schema, profile, keyword);
|
|
2106
|
+
return {
|
|
2107
|
+
id,
|
|
2108
|
+
language: profile.code,
|
|
2109
|
+
command: schema.action,
|
|
2110
|
+
priority,
|
|
2111
|
+
template: {
|
|
2112
|
+
format,
|
|
2113
|
+
tokens
|
|
2114
|
+
},
|
|
2115
|
+
extraction
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
function generateSimplePattern(grammar, schema, profile, config = defaultConfig2) {
|
|
2119
|
+
const optionalRoles = schema.roles.filter((r) => !r.required);
|
|
2120
|
+
if (optionalRoles.length === 0) {
|
|
2121
|
+
return null;
|
|
2122
|
+
}
|
|
2123
|
+
const requiredRoles = schema.roles.filter((r) => r.required);
|
|
2124
|
+
const simpleSchema = {
|
|
2125
|
+
...schema,
|
|
2126
|
+
roles: requiredRoles
|
|
2127
|
+
};
|
|
2128
|
+
const pattern = generatePattern2(grammar, simpleSchema, profile, config);
|
|
2129
|
+
return {
|
|
2130
|
+
...pattern,
|
|
2131
|
+
id: `${schema.action}-${profile.code}-generated-simple`,
|
|
2132
|
+
priority: (config.basePriority ?? 100) - 5,
|
|
2133
|
+
// Lower priority than full pattern (was -10)
|
|
2134
|
+
extraction: buildExtractionRulesWithDefaults(schema, profile)
|
|
2135
|
+
};
|
|
2136
|
+
}
|
|
2137
|
+
function generateVerbFirstPattern(schema, profile, config = defaultConfig2) {
|
|
2138
|
+
if (profile.wordOrder !== "SOV") return null;
|
|
2139
|
+
const requiredRoles = schema.roles.filter((r) => r.required);
|
|
2140
|
+
if (requiredRoles.length !== 1) return null;
|
|
2141
|
+
const keyword = profile.keywords[schema.action];
|
|
2142
|
+
if (!keyword) return null;
|
|
2143
|
+
const verbToken = keyword.alternatives ? { type: "literal", value: keyword.primary, alternatives: keyword.alternatives } : { type: "literal", value: keyword.primary };
|
|
2144
|
+
const roleTokens = requiredRoles.flatMap((r) => {
|
|
2145
|
+
const prefix = r.valuePrefixLiteral?.[profile.code];
|
|
2146
|
+
const roleToken = {
|
|
2147
|
+
type: "role",
|
|
2148
|
+
role: r.role,
|
|
2149
|
+
optional: false,
|
|
2150
|
+
expectedTypes: r.expectedTypes
|
|
2151
|
+
};
|
|
2152
|
+
return prefix ? [{ type: "literal", value: prefix }, roleToken] : [roleToken];
|
|
2153
|
+
});
|
|
2154
|
+
return {
|
|
2155
|
+
id: `${schema.action}-${profile.code}-generated-verb-first`,
|
|
2156
|
+
language: profile.code,
|
|
2157
|
+
command: schema.action,
|
|
2158
|
+
// Strictly below the canonical (basePriority) and simple (basePriority - 5)
|
|
2159
|
+
// patterns so native order is always preferred.
|
|
2160
|
+
priority: (config.basePriority ?? 100) - 20,
|
|
2161
|
+
template: {
|
|
2162
|
+
format: `${keyword.primary} <${requiredRoles[0].role}>`,
|
|
2163
|
+
tokens: [verbToken, ...roleTokens]
|
|
2164
|
+
},
|
|
2165
|
+
extraction: buildExtractionRulesWithDefaults(schema, profile)
|
|
2166
|
+
};
|
|
2167
|
+
}
|
|
2168
|
+
function generatePatternVariants2(grammar, schema, profile, config = defaultConfig2) {
|
|
2169
|
+
const patterns = [];
|
|
2170
|
+
const full = schema;
|
|
2171
|
+
schema = withoutVariantOnlyRoles(schema);
|
|
2172
|
+
patterns.push(generatePattern2(grammar, schema, profile, config));
|
|
2173
|
+
if (config.generateSimpleVariants) {
|
|
2174
|
+
const simple = generateSimplePattern(grammar, schema, profile, config);
|
|
2175
|
+
if (simple) {
|
|
2176
|
+
patterns.push(simple);
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
for (const omitted of schema.omitRoleVariants ?? []) {
|
|
2180
|
+
const variantSchema = {
|
|
2181
|
+
...schema,
|
|
2182
|
+
roles: schema.roles.filter((r) => r.role !== omitted)
|
|
2183
|
+
};
|
|
2184
|
+
const variant = generatePattern2(grammar, variantSchema, profile, config);
|
|
2185
|
+
patterns.push({
|
|
2186
|
+
...variant,
|
|
2187
|
+
id: `${schema.action}-${profile.code}-generated-no-${omitted}`,
|
|
2188
|
+
priority: (config.basePriority ?? 100) - 8
|
|
2189
|
+
});
|
|
2190
|
+
}
|
|
2191
|
+
for (const widen of schema.widenTypeVariants ?? []) {
|
|
2192
|
+
if (widen.excludeLanguages?.includes(profile.code)) continue;
|
|
2193
|
+
const cloneSchema = {
|
|
2194
|
+
...schema,
|
|
2195
|
+
roles: schema.roles.map(
|
|
2196
|
+
(r) => r.role === widen.role ? { ...r, expectedTypes: [...widen.types] } : r
|
|
2197
|
+
)
|
|
2198
|
+
};
|
|
2199
|
+
const main = generatePattern2(grammar, cloneSchema, profile, config);
|
|
2200
|
+
patterns.push({
|
|
2201
|
+
...main,
|
|
2202
|
+
id: `${schema.action}-${profile.code}-generated-${widen.idSuffix}`,
|
|
2203
|
+
priority: (config.basePriority ?? 100) - (widen.priorityDelta ?? 15)
|
|
2204
|
+
});
|
|
2205
|
+
}
|
|
2206
|
+
for (const v of full.requiredRoleVariants ?? []) {
|
|
2207
|
+
const variantSchema = {
|
|
2208
|
+
...full,
|
|
2209
|
+
roles: full.roles.filter((r) => !v.omit?.includes(r.role)).map((r) => {
|
|
2210
|
+
const required = r.role === v.role ? { ...r, required: true } : r;
|
|
2211
|
+
return r.role === v.widen?.role ? { ...required, expectedTypes: [...v.widen.types] } : required;
|
|
2212
|
+
})
|
|
2213
|
+
};
|
|
2214
|
+
const variant = generatePattern2(grammar, variantSchema, profile, config);
|
|
2215
|
+
patterns.push({
|
|
2216
|
+
...variant,
|
|
2217
|
+
id: `${schema.action}-${profile.code}-generated-${v.idSuffix}`,
|
|
2218
|
+
priority: (config.basePriority ?? 100) + (v.priorityDelta ?? 5)
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
2221
|
+
if (config.generateVerbFirstVariants !== false) {
|
|
2222
|
+
const verbFirst = generateVerbFirstPattern(schema, profile, config);
|
|
2223
|
+
if (verbFirst) {
|
|
2224
|
+
patterns.push(verbFirst);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
for (const v of schema.rolePrefixLiteralVariants ?? []) {
|
|
2228
|
+
const literal = v.literal[profile.code];
|
|
2229
|
+
if (!literal) continue;
|
|
2230
|
+
const { rolePrefixLiteralVariants: _omitted, ...baseSchema } = schema;
|
|
2231
|
+
const cloneSchema = {
|
|
2232
|
+
...baseSchema,
|
|
2233
|
+
roles: schema.roles.map(
|
|
2234
|
+
(r) => r.role === v.role ? { ...r, valuePrefixLiteral: { [profile.code]: literal } } : r
|
|
2235
|
+
)
|
|
2236
|
+
};
|
|
2237
|
+
const delta = v.priorityDelta ?? 5;
|
|
2238
|
+
const carrier = v.methodCarrier ? { [v.methodCarrier]: { value: literal } } : {};
|
|
2239
|
+
const main = generatePattern2(grammar, cloneSchema, profile, config);
|
|
2240
|
+
patterns.push({
|
|
2241
|
+
...main,
|
|
2242
|
+
id: `${schema.action}-${profile.code}-generated-${v.idSuffix}`,
|
|
2243
|
+
priority: (config.basePriority ?? 100) + delta,
|
|
2244
|
+
extraction: { ...main.extraction, ...carrier }
|
|
2245
|
+
});
|
|
2246
|
+
if (config.generateVerbFirstVariants !== false) {
|
|
2247
|
+
const verbFirstUrl = generateVerbFirstPattern(cloneSchema, profile, config);
|
|
2248
|
+
if (verbFirstUrl) {
|
|
2249
|
+
patterns.push({
|
|
2250
|
+
...verbFirstUrl,
|
|
2251
|
+
id: `${schema.action}-${profile.code}-generated-verb-first-${v.idSuffix}`,
|
|
2252
|
+
priority: (config.basePriority ?? 100) - 20 + delta,
|
|
2253
|
+
extraction: { ...verbFirstUrl.extraction, ...carrier }
|
|
2254
|
+
});
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
return patterns;
|
|
2259
|
+
}
|
|
2260
|
+
function buildTokens2(grammar, schema, profile, keyword) {
|
|
2261
|
+
const tokens = [];
|
|
2262
|
+
const verbToken = keyword.alternatives ? { type: "literal", value: keyword.primary, alternatives: keyword.alternatives } : { type: "literal", value: keyword.primary };
|
|
2263
|
+
const postVerbRoles = profile.wordOrder === "SOV" ? schema.roles.filter((r) => r.sovSlot === "postVerb") : [];
|
|
2264
|
+
const roleTokens = buildRoleTokens(
|
|
2265
|
+
grammar,
|
|
2266
|
+
postVerbRoles.length ? { ...schema, roles: schema.roles.filter((r) => r.sovSlot !== "postVerb") } : schema,
|
|
2267
|
+
profile
|
|
2268
|
+
);
|
|
2269
|
+
const postVerbTokens = postVerbRoles.length ? buildRoleTokens(grammar, { ...schema, roles: postVerbRoles }, profile) : [];
|
|
2270
|
+
switch (profile.wordOrder) {
|
|
2271
|
+
case "SVO":
|
|
2272
|
+
tokens.push(verbToken);
|
|
2273
|
+
tokens.push(...roleTokens);
|
|
2274
|
+
break;
|
|
2275
|
+
case "SOV":
|
|
2276
|
+
tokens.push(...roleTokens);
|
|
2277
|
+
tokens.push(verbToken);
|
|
2278
|
+
tokens.push(...postVerbTokens);
|
|
2279
|
+
break;
|
|
2280
|
+
case "VSO":
|
|
2281
|
+
tokens.push(verbToken);
|
|
2282
|
+
tokens.push(...roleTokens);
|
|
2283
|
+
break;
|
|
2284
|
+
default:
|
|
2285
|
+
tokens.push(verbToken);
|
|
2286
|
+
tokens.push(...roleTokens);
|
|
2287
|
+
}
|
|
2288
|
+
return collapseAdjacentLiterals(tokens);
|
|
2289
|
+
}
|
|
2290
|
+
function collapseAdjacentLiterals(tokens) {
|
|
2291
|
+
const out = [];
|
|
2292
|
+
for (const tok of tokens) {
|
|
2293
|
+
const prev = out[out.length - 1];
|
|
2294
|
+
if (prev && prev.type === "literal" && tok.type === "literal" && prev.value === tok.value) {
|
|
2295
|
+
const alts = [...prev.alternatives ?? [], ...tok.alternatives ?? []];
|
|
2296
|
+
if (alts.length) out[out.length - 1] = { ...prev, alternatives: [...new Set(alts)] };
|
|
2297
|
+
continue;
|
|
2298
|
+
}
|
|
2299
|
+
out.push(tok);
|
|
2300
|
+
}
|
|
2301
|
+
return out;
|
|
2302
|
+
}
|
|
2303
|
+
function buildRoleTokens(grammar, schema, profile) {
|
|
2304
|
+
const tokens = [];
|
|
2305
|
+
const sortedRoles = sortRolesByPosition(schema.roles, profile.wordOrder, grammar.positionOrder);
|
|
2306
|
+
for (const roleSpec of sortedRoles) {
|
|
2307
|
+
const roleToken = buildRoleToken(roleSpec, profile);
|
|
2308
|
+
if (!roleSpec.required) {
|
|
2309
|
+
tokens.push({
|
|
2310
|
+
type: "group",
|
|
2311
|
+
optional: true,
|
|
2312
|
+
tokens: roleToken
|
|
2313
|
+
});
|
|
2314
|
+
} else {
|
|
2315
|
+
tokens.push(...roleToken);
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
return tokens;
|
|
2319
|
+
}
|
|
2320
|
+
function buildRoleToken(roleSpec, profile) {
|
|
2321
|
+
const tokens = [];
|
|
2322
|
+
const overrideMarker = roleSpec.markerOverride?.[profile.code];
|
|
2323
|
+
const defaultMarker = profile.roleMarkers[roleSpec.role];
|
|
2324
|
+
const suppressMarker = roleSpec.renderOverride?.[profile.code] === "";
|
|
2325
|
+
const roleValueToken = {
|
|
2326
|
+
type: "role",
|
|
2327
|
+
role: roleSpec.role,
|
|
2328
|
+
optional: !roleSpec.required,
|
|
2329
|
+
expectedTypes: roleSpec.expectedTypes,
|
|
2330
|
+
// The matcher reads this too — a `'keyword'`-shaped slot holds a fixed
|
|
2331
|
+
// keyword phrase (`using view transition`) and must not be skipped by the
|
|
2332
|
+
// trailing-slot verb guard.
|
|
2333
|
+
...roleSpec.valueShape !== void 0 ? { valueShape: roleSpec.valueShape } : {},
|
|
2334
|
+
// A greedy role reads up to the next marker the pattern owes (a domain's
|
|
2335
|
+
// SQL condition); its value reader does the reading.
|
|
2336
|
+
...roleSpec.greedy ? { greedy: true } : {}
|
|
2337
|
+
};
|
|
2338
|
+
const prefixLiteral = roleSpec.valuePrefixLiteral?.[profile.code];
|
|
2339
|
+
const pushPrefixed = () => {
|
|
2340
|
+
if (prefixLiteral) tokens.push({ type: "literal", value: prefixLiteral });
|
|
2341
|
+
tokens.push(roleValueToken);
|
|
2342
|
+
};
|
|
2343
|
+
if (overrideMarker !== void 0) {
|
|
2344
|
+
const markerWords = overrideMarker ? overrideMarker.split(/\s+/).filter(Boolean) : [];
|
|
2345
|
+
const isPassthroughOverride = overrideMarker !== void 0 && overrideMarker === roleSpec.markerOverride?.en;
|
|
2346
|
+
const position = roleSpec.markerPositionOverride?.[profile.code] ?? roleSpec.markerPosition ?? defaultMarker?.position ?? (profile.wordOrder === "SOV" && !isPassthroughOverride ? "after" : "before");
|
|
2347
|
+
const optionalMarker = roleSpec.markerOptional?.[profile.code] === true;
|
|
2348
|
+
const pushWord = (word) => {
|
|
2349
|
+
const alternatives = markerWords.length === 1 ? schemaMarkerAlternatives(roleSpec, profile.code, word) ?? [] : [];
|
|
2350
|
+
const literal = {
|
|
2351
|
+
type: "literal",
|
|
2352
|
+
value: word,
|
|
2353
|
+
...alternatives.length ? { alternatives } : {},
|
|
2354
|
+
...suppressMarker ? { renderSuppress: true } : {}
|
|
2355
|
+
};
|
|
2356
|
+
tokens.push(optionalMarker ? { type: "group", optional: true, tokens: [literal] } : literal);
|
|
2357
|
+
};
|
|
2358
|
+
if (position === "before") {
|
|
2359
|
+
for (const word of markerWords) pushWord(word);
|
|
2360
|
+
pushPrefixed();
|
|
2361
|
+
} else {
|
|
2362
|
+
pushPrefixed();
|
|
2363
|
+
for (const word of markerWords) pushWord(word);
|
|
2364
|
+
}
|
|
2365
|
+
} else if (defaultMarker) {
|
|
2366
|
+
const asMarker = () => {
|
|
2367
|
+
const alternatives = [
|
|
2368
|
+
.../* @__PURE__ */ new Set([
|
|
2369
|
+
...defaultMarker.alternatives ?? [],
|
|
2370
|
+
...schemaMarkerAlternatives(roleSpec, profile.code, defaultMarker.primary) ?? []
|
|
2371
|
+
])
|
|
2372
|
+
].filter((a) => a !== defaultMarker.primary);
|
|
2373
|
+
return {
|
|
2374
|
+
type: "literal",
|
|
2375
|
+
value: defaultMarker.primary,
|
|
2376
|
+
...alternatives.length ? { alternatives } : {},
|
|
2377
|
+
...suppressMarker ? { renderSuppress: true } : {}
|
|
2378
|
+
};
|
|
2379
|
+
};
|
|
2380
|
+
const pushMarker = (marker) => {
|
|
2381
|
+
if (!profile.markersOptional && !roleSpec.markerOptional?.[profile.code]) {
|
|
2382
|
+
tokens.push(marker);
|
|
2383
|
+
return;
|
|
2384
|
+
}
|
|
2385
|
+
tokens.push({
|
|
2386
|
+
type: "group",
|
|
2387
|
+
optional: true,
|
|
2388
|
+
...profile.markersOptional && !roleSpec.markerOptional?.[profile.code] ? { renderRequired: true } : {},
|
|
2389
|
+
tokens: [marker]
|
|
2390
|
+
});
|
|
2391
|
+
};
|
|
2392
|
+
if ((roleSpec.markerPosition ?? defaultMarker.position) === "before") {
|
|
2393
|
+
if (defaultMarker.primary) {
|
|
2394
|
+
pushMarker(asMarker());
|
|
2395
|
+
}
|
|
2396
|
+
pushPrefixed();
|
|
2397
|
+
} else {
|
|
2398
|
+
pushPrefixed();
|
|
2399
|
+
pushMarker(asMarker());
|
|
2400
|
+
}
|
|
2401
|
+
} else {
|
|
2402
|
+
pushPrefixed();
|
|
2403
|
+
}
|
|
2404
|
+
return tokens;
|
|
2405
|
+
}
|
|
2406
|
+
function buildExtractionRules2(schema, profile) {
|
|
2407
|
+
const rules = {};
|
|
2408
|
+
for (const roleSpec of schema.roles) {
|
|
2409
|
+
const overrideMarker = roleSpec.markerOverride?.[profile.code];
|
|
2410
|
+
const defaultMarker = profile.roleMarkers[roleSpec.role];
|
|
2411
|
+
if (roleSpec.valuePrefixLiteral?.[profile.code]) {
|
|
2412
|
+
rules[roleSpec.role] = { marker: roleSpec.valuePrefixLiteral[profile.code] };
|
|
2413
|
+
} else if (overrideMarker !== void 0) {
|
|
2414
|
+
if (!overrideMarker) {
|
|
2415
|
+
rules[roleSpec.role] = {};
|
|
2416
|
+
} else {
|
|
2417
|
+
const isSingleWord = !/\s/.test(overrideMarker.trim());
|
|
2418
|
+
const markerAlternatives = isSingleWord ? schemaMarkerAlternatives(roleSpec, profile.code, overrideMarker) ?? [] : [];
|
|
2419
|
+
rules[roleSpec.role] = markerAlternatives.length ? { marker: overrideMarker, markerAlternatives } : { marker: overrideMarker };
|
|
2420
|
+
}
|
|
2421
|
+
} else if (defaultMarker && defaultMarker.primary) {
|
|
2422
|
+
const markerAlternatives = [
|
|
2423
|
+
.../* @__PURE__ */ new Set([
|
|
2424
|
+
...defaultMarker.alternatives ?? [],
|
|
2425
|
+
...schemaMarkerAlternatives(roleSpec, profile.code, defaultMarker.primary) ?? []
|
|
2426
|
+
])
|
|
2427
|
+
].filter((a) => a !== defaultMarker.primary);
|
|
2428
|
+
rules[roleSpec.role] = markerAlternatives.length ? { marker: defaultMarker.primary, markerAlternatives } : { marker: defaultMarker.primary };
|
|
2429
|
+
} else {
|
|
2430
|
+
rules[roleSpec.role] = {};
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
return rules;
|
|
2434
|
+
}
|
|
2435
|
+
function buildExtractionRulesWithDefaults(schema, profile) {
|
|
2436
|
+
const baseRules = buildExtractionRules2(schema, profile);
|
|
2437
|
+
const rules = {};
|
|
2438
|
+
for (const roleSpec of schema.roles) {
|
|
2439
|
+
const baseRule = baseRules[roleSpec.role] || {};
|
|
2440
|
+
if (!roleSpec.required && roleSpec.default) {
|
|
2441
|
+
rules[roleSpec.role] = { ...baseRule, default: roleSpec.default };
|
|
2442
|
+
} else {
|
|
2443
|
+
rules[roleSpec.role] = baseRule;
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
return rules;
|
|
2447
|
+
}
|
|
2448
|
+
function buildFormatString2(grammar, schema, profile, keyword) {
|
|
2449
|
+
const parts = [];
|
|
2450
|
+
const sortedRoles = sortRolesByPosition(schema.roles, profile.wordOrder, grammar.positionOrder);
|
|
2451
|
+
const roleParts = sortedRoles.map((roleSpec) => {
|
|
2452
|
+
const resolved = resolveMarkerForRole(roleSpec, profile);
|
|
2453
|
+
let part = "";
|
|
2454
|
+
if (resolved && resolved.primary) {
|
|
2455
|
+
if (resolved.position === "before") {
|
|
2456
|
+
part = `${resolved.primary} {${roleSpec.role}}`;
|
|
2457
|
+
} else {
|
|
2458
|
+
part = `{${roleSpec.role}} ${resolved.primary}`;
|
|
2459
|
+
}
|
|
2460
|
+
} else {
|
|
2461
|
+
part = `{${roleSpec.role}}`;
|
|
2462
|
+
}
|
|
2463
|
+
return roleSpec.required ? part : `[${part}]`;
|
|
2464
|
+
});
|
|
2465
|
+
switch (profile.wordOrder) {
|
|
2466
|
+
case "SVO":
|
|
2467
|
+
case "VSO":
|
|
2468
|
+
parts.push(keyword.primary, ...roleParts);
|
|
2469
|
+
break;
|
|
2470
|
+
case "SOV":
|
|
2471
|
+
parts.push(...roleParts, keyword.primary);
|
|
2472
|
+
break;
|
|
2473
|
+
default:
|
|
2474
|
+
parts.push(keyword.primary, ...roleParts);
|
|
2475
|
+
}
|
|
2476
|
+
return parts.join(" ");
|
|
1531
2477
|
}
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
2478
|
+
|
|
2479
|
+
// src/generation/pattern-render.ts
|
|
2480
|
+
var NESTED_ROLE_BONUS = 5;
|
|
2481
|
+
var UNCOVERED_ROLE_PENALTY = 30;
|
|
2482
|
+
function pinnedLiteral(rule) {
|
|
2483
|
+
if (rule?.default?.type === "literal") return String(rule.default.value).trim().toLowerCase();
|
|
2484
|
+
if (rule?.value !== void 0) return String(rule.value).trim().toLowerCase();
|
|
2485
|
+
return void 0;
|
|
2486
|
+
}
|
|
2487
|
+
function selectRenderPattern(node, patterns, hooks) {
|
|
2488
|
+
let candidates = patterns.filter((pattern) => !pattern.parseOnly);
|
|
2489
|
+
if (candidates.length === 0) candidates = patterns;
|
|
2490
|
+
if (hooks.candidates) candidates = hooks.candidates(node, candidates);
|
|
2491
|
+
const pinnedValues = /* @__PURE__ */ new Map();
|
|
2492
|
+
for (const pattern of candidates) {
|
|
2493
|
+
for (const [role, rule] of Object.entries(pattern.extraction ?? {})) {
|
|
2494
|
+
const key = pinnedLiteral(rule);
|
|
2495
|
+
if (key === void 0) continue;
|
|
2496
|
+
const set = pinnedValues.get(role) ?? /* @__PURE__ */ new Set();
|
|
2497
|
+
set.add(key);
|
|
2498
|
+
pinnedValues.set(role, set);
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
const scored = candidates.map((pattern) => {
|
|
2502
|
+
let score = pattern.priority;
|
|
2503
|
+
const hasRealRole = (role) => hooks.hasRealRole(node, role);
|
|
2504
|
+
const scoreTokens = (tokens, inGroup) => {
|
|
2505
|
+
for (const token of tokens) {
|
|
2506
|
+
if (token.type === "group") {
|
|
2507
|
+
scoreTokens(token.tokens, true);
|
|
2508
|
+
} else if (token.type === "role") {
|
|
2509
|
+
if (hasRealRole(token.role)) {
|
|
2510
|
+
score += inGroup ? NESTED_ROLE_BONUS : 10;
|
|
2511
|
+
} else if (!inGroup && !token.optional) {
|
|
2512
|
+
score -= 50;
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2516
|
+
};
|
|
2517
|
+
scoreTokens(pattern.template.tokens, false);
|
|
2518
|
+
const slots = /* @__PURE__ */ new Set();
|
|
2519
|
+
const collectSlots = (tokens) => {
|
|
2520
|
+
for (const token of tokens) {
|
|
2521
|
+
if (token.type === "group") collectSlots(token.tokens);
|
|
2522
|
+
else if (token.type === "role") slots.add(token.role);
|
|
2523
|
+
}
|
|
2524
|
+
};
|
|
2525
|
+
collectSlots(pattern.template.tokens);
|
|
2526
|
+
for (const role of node.roles.keys()) {
|
|
2527
|
+
if (hasRealRole(role) && !slots.has(role)) score -= UNCOVERED_ROLE_PENALTY;
|
|
2528
|
+
}
|
|
2529
|
+
for (const [role, rule] of Object.entries(pattern.extraction ?? {})) {
|
|
2530
|
+
const pinnedKey = pinnedLiteral(rule);
|
|
2531
|
+
if (pinnedKey === void 0) continue;
|
|
2532
|
+
const actual = node.roles.get(role);
|
|
2533
|
+
const actualKey = actual?.type === (rule.valueIsExpression ? "expression" : "literal") ? String(
|
|
2534
|
+
actual.type === "expression" ? actual.raw : actual.value
|
|
2535
|
+
).trim().toLowerCase() : void 0;
|
|
2536
|
+
if (actualKey === pinnedKey) {
|
|
2537
|
+
score += 60;
|
|
2538
|
+
} else if (actualKey === void 0 || pinnedValues.get(role)?.has(actualKey)) {
|
|
2539
|
+
score -= 200;
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
score += hooks.adjustScore?.(pattern, node) ?? 0;
|
|
2543
|
+
return { pattern, score };
|
|
2544
|
+
});
|
|
2545
|
+
scored.sort((a, b) => b.score - a.score);
|
|
2546
|
+
return scored.length > 0 ? scored[0].pattern : null;
|
|
2547
|
+
}
|
|
2548
|
+
function renderPattern(node, pattern, hooks) {
|
|
2549
|
+
const parts = [];
|
|
2550
|
+
const language = pattern.language;
|
|
2551
|
+
const tokens = pattern.template.tokens;
|
|
2552
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
2553
|
+
hooks.beforeToken?.(tokens, i, parts, node, language);
|
|
2554
|
+
const span = hooks.span?.(tokens, i, node, language, true);
|
|
2555
|
+
if (span !== void 0) {
|
|
2556
|
+
parts.push(span.text);
|
|
2557
|
+
i += span.tokens - 1;
|
|
2558
|
+
continue;
|
|
1544
2559
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
2560
|
+
const token = tokens[i];
|
|
2561
|
+
const rendered = renderPatternToken(token, node, language, hooks);
|
|
2562
|
+
if (rendered !== null) {
|
|
2563
|
+
pushPart(hooks, parts, rendered, token, tokens[i - 1], node, language);
|
|
2564
|
+
hooks.afterToken?.(token, parts.length - 1, node);
|
|
1548
2565
|
}
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
2566
|
+
}
|
|
2567
|
+
return parts;
|
|
2568
|
+
}
|
|
2569
|
+
function pushPart(hooks, parts, text, token, previous, node, language) {
|
|
2570
|
+
if (hooks.pushPart) hooks.pushPart(parts, text, token, previous, node, language);
|
|
2571
|
+
else parts.push(text);
|
|
2572
|
+
}
|
|
2573
|
+
function renderPatternToken(token, node, language, hooks) {
|
|
2574
|
+
switch (token.type) {
|
|
2575
|
+
case "literal":
|
|
2576
|
+
return token.renderSuppress ? null : token.value;
|
|
2577
|
+
case "role":
|
|
2578
|
+
return hooks.writeRole(token, node, language);
|
|
2579
|
+
case "group": {
|
|
2580
|
+
const hasRequired = token.tokens.filter((t) => t.type === "role" && !t.optional).every((t) => node.roles.has(t.role));
|
|
2581
|
+
if (!hasRequired && token.optional) {
|
|
2582
|
+
return null;
|
|
2583
|
+
}
|
|
2584
|
+
if (hooks.writeGroup && !hooks.writeGroup(token, node, language)) return null;
|
|
2585
|
+
const groupParts = [];
|
|
2586
|
+
let hasRoleValue = false;
|
|
2587
|
+
for (let i = 0; i < token.tokens.length; i++) {
|
|
2588
|
+
const span = hooks.span?.(token.tokens, i, node, language, false);
|
|
2589
|
+
if (span !== void 0) {
|
|
2590
|
+
groupParts.push(span.text);
|
|
2591
|
+
hasRoleValue = true;
|
|
2592
|
+
i += span.tokens - 1;
|
|
2593
|
+
continue;
|
|
2594
|
+
}
|
|
2595
|
+
const subToken = token.tokens[i];
|
|
2596
|
+
const rendered = renderPatternToken(subToken, node, language, hooks);
|
|
2597
|
+
if (rendered !== null) {
|
|
2598
|
+
pushPart(hooks, groupParts, rendered, subToken, token.tokens[i - 1], node, language);
|
|
2599
|
+
if (subToken.type === "role") hasRoleValue = true;
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
if (token.optional && !hasRoleValue && !token.renderRequired) return null;
|
|
2603
|
+
return groupParts.length > 0 ? groupParts.join(" ") : null;
|
|
1558
2604
|
}
|
|
2605
|
+
default:
|
|
2606
|
+
return null;
|
|
1559
2607
|
}
|
|
1560
|
-
return isSOV ? buildPhrase(...preVerb, keyword, ...postVerb) : buildPhrase(keyword, ...preVerb, ...postVerb);
|
|
1561
2608
|
}
|
|
1562
2609
|
|
|
1563
2610
|
// src/grammar/types.ts
|
|
@@ -2818,7 +3865,53 @@ function semanticValueToAST(value) {
|
|
|
2818
3865
|
}
|
|
2819
3866
|
}
|
|
2820
3867
|
|
|
3868
|
+
// src/api/reading.ts
|
|
3869
|
+
function roleValues(node) {
|
|
3870
|
+
const out = /* @__PURE__ */ new Map();
|
|
3871
|
+
for (const [role, value] of node.roles) {
|
|
3872
|
+
const v = value;
|
|
3873
|
+
out.set(role, String(v?.value ?? v?.raw ?? value));
|
|
3874
|
+
}
|
|
3875
|
+
return out;
|
|
3876
|
+
}
|
|
3877
|
+
function readingDifference(source, back) {
|
|
3878
|
+
if (back.action !== source.action) return `reads as ${back.action}`;
|
|
3879
|
+
const want = roleValues(source);
|
|
3880
|
+
const got = roleValues(back);
|
|
3881
|
+
const parts = [];
|
|
3882
|
+
for (const [role, value] of want) {
|
|
3883
|
+
if (!got.has(role)) parts.push(`${role} lost`);
|
|
3884
|
+
else if (got.get(role) !== value) parts.push(`${role}: ${value} \u2192 ${got.get(role)}`);
|
|
3885
|
+
}
|
|
3886
|
+
for (const role of got.keys()) if (!want.has(role)) parts.push(`${role} added`);
|
|
3887
|
+
return parts.join(", ");
|
|
3888
|
+
}
|
|
3889
|
+
|
|
2821
3890
|
// src/api/create-dsl.ts
|
|
3891
|
+
var UnreadInputError = class extends Error {
|
|
3892
|
+
constructor(input, language, reading, unread) {
|
|
3893
|
+
super(`"${input}" (${language}) reads as ${reading.action} only by leaving "${unread}" unread`);
|
|
3894
|
+
this.input = input;
|
|
3895
|
+
this.language = language;
|
|
3896
|
+
this.reading = reading;
|
|
3897
|
+
this.unread = unread;
|
|
3898
|
+
this.code = "unread-input";
|
|
3899
|
+
this.name = "UnreadInputError";
|
|
3900
|
+
}
|
|
3901
|
+
};
|
|
3902
|
+
var TranslationReadBackError = class extends Error {
|
|
3903
|
+
constructor(partial, from, to, source, reading, why) {
|
|
3904
|
+
super(`translation ${from} \u2192 ${to} does not read back as the source (${why}): "${partial}"`);
|
|
3905
|
+
this.partial = partial;
|
|
3906
|
+
this.from = from;
|
|
3907
|
+
this.to = to;
|
|
3908
|
+
this.source = source;
|
|
3909
|
+
this.reading = reading;
|
|
3910
|
+
this.why = why;
|
|
3911
|
+
this.code = "translation-does-not-read-back";
|
|
3912
|
+
this.name = "TranslationReadBackError";
|
|
3913
|
+
}
|
|
3914
|
+
};
|
|
2822
3915
|
var DSLRegistry = class {
|
|
2823
3916
|
/**
|
|
2824
3917
|
* @param partiallyTranslatedActions Actions permitted to lack a keyword in
|
|
@@ -2826,7 +3919,8 @@ var DSLRegistry = class {
|
|
|
2826
3919
|
* subset of the DSL's languages. A built-in command missing a keyword stays
|
|
2827
3920
|
* an error, since that is a domain-authoring mistake.
|
|
2828
3921
|
*/
|
|
2829
|
-
constructor(config, partiallyTranslatedActions
|
|
3922
|
+
constructor(config, partiallyTranslatedActions, generate) {
|
|
3923
|
+
this.generate = generate;
|
|
2830
3924
|
this.patterns = /* @__PURE__ */ new Map();
|
|
2831
3925
|
this.tokenizers = /* @__PURE__ */ new Map();
|
|
2832
3926
|
this.schemas = config.schemas;
|
|
@@ -2842,7 +3936,7 @@ var DSLRegistry = class {
|
|
|
2842
3936
|
if (this.partiallyTranslatedActions.has(schema.action) && !lang.patternProfile.keywords[schema.action]) {
|
|
2843
3937
|
continue;
|
|
2844
3938
|
}
|
|
2845
|
-
const pattern =
|
|
3939
|
+
const pattern = this.generate(schema, lang.patternProfile);
|
|
2846
3940
|
patterns.push(pattern);
|
|
2847
3941
|
}
|
|
2848
3942
|
this.patterns.set(lang.code, patterns);
|
|
@@ -2858,9 +3952,9 @@ var DSLRegistry = class {
|
|
|
2858
3952
|
}
|
|
2859
3953
|
};
|
|
2860
3954
|
var MultilingualDSLImpl = class {
|
|
2861
|
-
constructor(config, registry, transformer, profileProvider) {
|
|
3955
|
+
constructor(config, registry, transformer, profileProvider, engine) {
|
|
2862
3956
|
this.registry = registry;
|
|
2863
|
-
this.
|
|
3957
|
+
this.match = engine.match;
|
|
2864
3958
|
this.transformer = transformer;
|
|
2865
3959
|
this.profileProvider = profileProvider;
|
|
2866
3960
|
if (config.codeGenerator) {
|
|
@@ -2873,10 +3967,7 @@ var MultilingualDSLImpl = class {
|
|
|
2873
3967
|
for (const extension of config.extensions ?? []) {
|
|
2874
3968
|
if (extension.render) this.extensionRenderers.set(extension.schema.action, extension.render);
|
|
2875
3969
|
}
|
|
2876
|
-
this.schemaFallbackRenderer =
|
|
2877
|
-
schemas: config.schemas,
|
|
2878
|
-
profiles: config.languages.map((l) => l.patternProfile)
|
|
2879
|
-
});
|
|
3970
|
+
this.schemaFallbackRenderer = engine.fallbackRenderer(config, registry);
|
|
2880
3971
|
const schemaMap = new Map(config.schemas.map((s) => [s.action, s]));
|
|
2881
3972
|
this.schemaLookup = {
|
|
2882
3973
|
getSchema: (action) => schemaMap.get(action)
|
|
@@ -2900,28 +3991,50 @@ var MultilingualDSLImpl = class {
|
|
|
2900
3991
|
}
|
|
2901
3992
|
const tokens = tokenizer.tokenize(input);
|
|
2902
3993
|
const patterns = this.registry.getPatterns(language);
|
|
2903
|
-
const
|
|
2904
|
-
|
|
2905
|
-
|
|
3994
|
+
const total = tokens.tokens.length;
|
|
3995
|
+
let best = null;
|
|
3996
|
+
let longestPartial = null;
|
|
2906
3997
|
for (const pattern of patterns) {
|
|
2907
|
-
const
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
sourceText: input,
|
|
2916
|
-
patternId: pattern.id,
|
|
2917
|
-
confidence: match.confidence
|
|
2918
|
-
}
|
|
2919
|
-
};
|
|
2920
|
-
return { node, confidence: match.confidence };
|
|
3998
|
+
const mark = tokens.mark();
|
|
3999
|
+
const match = this.match(tokens, pattern, language);
|
|
4000
|
+
tokens.reset(mark);
|
|
4001
|
+
if (!match) continue;
|
|
4002
|
+
if (match.consumedTokens < total) {
|
|
4003
|
+
if (!longestPartial || match.consumedTokens > longestPartial.consumedTokens)
|
|
4004
|
+
longestPartial = match;
|
|
4005
|
+
continue;
|
|
2921
4006
|
}
|
|
4007
|
+
if (!best || match.pattern.priority > best.pattern.priority || match.pattern.priority === best.pattern.priority && match.confidence > best.confidence + 1e-3)
|
|
4008
|
+
best = match;
|
|
4009
|
+
}
|
|
4010
|
+
if (best) {
|
|
4011
|
+
const node = this.nodeOf(best, input, language);
|
|
4012
|
+
return { node, confidence: best.confidence };
|
|
4013
|
+
}
|
|
4014
|
+
if (longestPartial) {
|
|
4015
|
+
const unread = tokens.tokens.slice(longestPartial.consumedTokens).map((t) => t.value).join(" ");
|
|
4016
|
+
throw new UnreadInputError(
|
|
4017
|
+
input,
|
|
4018
|
+
language,
|
|
4019
|
+
this.nodeOf(longestPartial, input, language),
|
|
4020
|
+
unread
|
|
4021
|
+
);
|
|
2922
4022
|
}
|
|
2923
4023
|
throw new Error(`No pattern matched for input: ${input}`);
|
|
2924
4024
|
}
|
|
4025
|
+
nodeOf(match, input, language) {
|
|
4026
|
+
return {
|
|
4027
|
+
kind: "command",
|
|
4028
|
+
action: match.pattern.command,
|
|
4029
|
+
roles: match.captured,
|
|
4030
|
+
metadata: {
|
|
4031
|
+
sourceLanguage: language,
|
|
4032
|
+
sourceText: input,
|
|
4033
|
+
patternId: match.pattern.id,
|
|
4034
|
+
confidence: match.confidence
|
|
4035
|
+
}
|
|
4036
|
+
};
|
|
4037
|
+
}
|
|
2925
4038
|
validate(input, language) {
|
|
2926
4039
|
try {
|
|
2927
4040
|
const result = this.parseWithConfidence(input, language);
|
|
@@ -2932,11 +4045,12 @@ var MultilingualDSLImpl = class {
|
|
|
2932
4045
|
} catch (error) {
|
|
2933
4046
|
return {
|
|
2934
4047
|
valid: false,
|
|
2935
|
-
errors: [error instanceof Error ? error.message : String(error)]
|
|
4048
|
+
errors: [error instanceof Error ? error.message : String(error)],
|
|
4049
|
+
...error instanceof UnreadInputError ? { errorCode: error.code } : {}
|
|
2936
4050
|
};
|
|
2937
4051
|
}
|
|
2938
4052
|
}
|
|
2939
|
-
translate(input, fromLanguage, toLanguage) {
|
|
4053
|
+
translate(input, fromLanguage, toLanguage, options) {
|
|
2940
4054
|
if (isExplicitSyntax(input)) return input;
|
|
2941
4055
|
let node;
|
|
2942
4056
|
try {
|
|
@@ -2948,14 +4062,46 @@ var MultilingualDSLImpl = class {
|
|
|
2948
4062
|
throw parseError;
|
|
2949
4063
|
}
|
|
2950
4064
|
const rendered = this.registry.getSupportedLanguages().includes(toLanguage) ? this.render(node, toLanguage) : null;
|
|
2951
|
-
if (rendered != null) return rendered;
|
|
4065
|
+
if (rendered != null) return this.readsBack(rendered, node, fromLanguage, toLanguage, options);
|
|
2952
4066
|
if (this.hasGrammarProfile(fromLanguage) && this.hasGrammarProfile(toLanguage)) {
|
|
2953
|
-
return this.
|
|
4067
|
+
return this.readsBack(
|
|
4068
|
+
this.transformer.transform(input, fromLanguage, toLanguage),
|
|
4069
|
+
node,
|
|
4070
|
+
fromLanguage,
|
|
4071
|
+
toLanguage,
|
|
4072
|
+
options
|
|
4073
|
+
);
|
|
2954
4074
|
}
|
|
2955
4075
|
throw new Error(
|
|
2956
4076
|
`translate() could not render action "${node.action}" in language "${toLanguage}": no custom renderer, domain renderer, or schema pattern covers it, and no grammar profile is configured for the transformer fallback. Either add "${toLanguage}" to the DSL's languages/renderer, or set 'grammarProfile' on its LanguageConfig in createMultilingualDSL() (parse/validate/compile do not need it).`
|
|
2957
4077
|
);
|
|
2958
4078
|
}
|
|
4079
|
+
/**
|
|
4080
|
+
* `rendered`, read in `to`, must be `source`: the same action and role values, or, when the DSL
|
|
4081
|
+
* compiles, the same code (a parser may keep a translated word its generator normalizes: bdd ja
|
|
4082
|
+
* `表示` is `visible`). The rule is the domain gate's (lokascript-domains). A translation used to be
|
|
4083
|
+
* returned whatever it read as: ja/ko bdd `select` dropped its value, and nothing said so.
|
|
4084
|
+
*/
|
|
4085
|
+
readsBack(rendered, source, from, to, options) {
|
|
4086
|
+
if (options?.lossy === "allow") return rendered;
|
|
4087
|
+
let back;
|
|
4088
|
+
try {
|
|
4089
|
+
back = this.parseWithConfidence(rendered, to).node;
|
|
4090
|
+
} catch (error) {
|
|
4091
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
4092
|
+
throw new TranslationReadBackError(rendered, from, to, source, null, why);
|
|
4093
|
+
}
|
|
4094
|
+
const difference = readingDifference(source, back);
|
|
4095
|
+
if (!difference) return rendered;
|
|
4096
|
+
if (this.codeGenerator) {
|
|
4097
|
+
try {
|
|
4098
|
+
if (this.codeGenerator.generate(back) === this.codeGenerator.generate(source))
|
|
4099
|
+
return rendered;
|
|
4100
|
+
} catch {
|
|
4101
|
+
}
|
|
4102
|
+
}
|
|
4103
|
+
throw new TranslationReadBackError(rendered, from, to, source, back, difference);
|
|
4104
|
+
}
|
|
2959
4105
|
hasGrammarProfile(language) {
|
|
2960
4106
|
return this.profileProvider.getProfile(language) != null;
|
|
2961
4107
|
}
|
|
@@ -2981,7 +4127,8 @@ var MultilingualDSLImpl = class {
|
|
|
2981
4127
|
} catch (error) {
|
|
2982
4128
|
return {
|
|
2983
4129
|
ok: false,
|
|
2984
|
-
errors: [error instanceof Error ? error.message : String(error)]
|
|
4130
|
+
errors: [error instanceof Error ? error.message : String(error)],
|
|
4131
|
+
...error instanceof UnreadInputError ? { errorCode: error.code } : {}
|
|
2985
4132
|
};
|
|
2986
4133
|
}
|
|
2987
4134
|
}
|
|
@@ -3093,8 +4240,76 @@ function createMultilingualDSL(config) {
|
|
|
3093
4240
|
dictionary,
|
|
3094
4241
|
profileProvider
|
|
3095
4242
|
});
|
|
3096
|
-
const
|
|
3097
|
-
|
|
4243
|
+
const engine = engineFor(config);
|
|
4244
|
+
const registry = new DSLRegistry(effectiveConfig, extensionActions, engine.generate);
|
|
4245
|
+
return new MultilingualDSLImpl(effectiveConfig, registry, transformer, profileProvider, engine);
|
|
4246
|
+
}
|
|
4247
|
+
function engineFor(config) {
|
|
4248
|
+
const name = config.engine ?? "classic";
|
|
4249
|
+
if (name === "classic") return classicEngine();
|
|
4250
|
+
if (name === "core") return coreEngine();
|
|
4251
|
+
throw new Error(`Unknown DSL engine "${String(name)}" (expected "classic" or "core")`);
|
|
4252
|
+
}
|
|
4253
|
+
function classicEngine() {
|
|
4254
|
+
const matcher = new PatternMatcher();
|
|
4255
|
+
return {
|
|
4256
|
+
generate: (schema, profile) => generatePattern(schema, profile),
|
|
4257
|
+
match: (tokens, pattern, language) => matcher.matchPattern(tokens, pattern, { code: language }),
|
|
4258
|
+
fallbackRenderer: (config) => createDomainRenderer({
|
|
4259
|
+
schemas: config.schemas,
|
|
4260
|
+
profiles: config.languages.map((l) => l.patternProfile)
|
|
4261
|
+
})
|
|
4262
|
+
};
|
|
4263
|
+
}
|
|
4264
|
+
function schemaProfileOf(profile) {
|
|
4265
|
+
const side = profile.wordOrder === "SOV" ? "after" : "before";
|
|
4266
|
+
const roleMarkers = {};
|
|
4267
|
+
for (const [role, marker] of Object.entries(profile.roleMarkers ?? {})) {
|
|
4268
|
+
roleMarkers[role] = {
|
|
4269
|
+
primary: marker.primary,
|
|
4270
|
+
...marker.alternatives ? { alternatives: marker.alternatives } : {},
|
|
4271
|
+
position: marker.position ?? side
|
|
4272
|
+
};
|
|
4273
|
+
}
|
|
4274
|
+
return {
|
|
4275
|
+
code: profile.code,
|
|
4276
|
+
wordOrder: profile.wordOrder,
|
|
4277
|
+
keywords: profile.keywords,
|
|
4278
|
+
roleMarkers
|
|
4279
|
+
};
|
|
4280
|
+
}
|
|
4281
|
+
function coreEngine() {
|
|
4282
|
+
const generator = createSchemaPatternGenerator({ positionOrder: "descending" });
|
|
4283
|
+
const matcher = new MatchSkeleton(createStockReader(), stockConfidenceModel);
|
|
4284
|
+
return {
|
|
4285
|
+
generate: (schema, profile) => generator.generatePattern(schema, schemaProfileOf(profile)),
|
|
4286
|
+
match: (tokens, pattern) => matcher.matchPattern(tokens, pattern),
|
|
4287
|
+
fallbackRenderer: (config, registry) => {
|
|
4288
|
+
const schemas = new Map(config.schemas.map((s) => [s.action, s]));
|
|
4289
|
+
const hooks = {
|
|
4290
|
+
hasRealRole: (node, role) => {
|
|
4291
|
+
const value = node.roles.get(role);
|
|
4292
|
+
return value !== void 0 && value.implicit !== true;
|
|
4293
|
+
},
|
|
4294
|
+
writeRole: (token, node) => {
|
|
4295
|
+
if (!node.roles.has(token.role)) return null;
|
|
4296
|
+
let value = extractRoleValue(node, token.role);
|
|
4297
|
+
const spec = schemas.get(node.action)?.roles.find((r) => r.role === token.role);
|
|
4298
|
+
if (spec?.quoteMultiword && /\s/.test(value) && !/^(["']).*\1$/.test(value)) {
|
|
4299
|
+
value = `"${value}"`;
|
|
4300
|
+
}
|
|
4301
|
+
return value || null;
|
|
4302
|
+
}
|
|
4303
|
+
};
|
|
4304
|
+
return (node, language) => {
|
|
4305
|
+
const patterns = registry.getPatterns(language).filter((p) => p.command === node.action);
|
|
4306
|
+
const pattern = selectRenderPattern(node, patterns, hooks);
|
|
4307
|
+
if (!pattern) return null;
|
|
4308
|
+
const text = renderPattern(node, pattern, hooks).join(" ");
|
|
4309
|
+
return text || null;
|
|
4310
|
+
};
|
|
4311
|
+
}
|
|
4312
|
+
};
|
|
3098
4313
|
}
|
|
3099
4314
|
|
|
3100
4315
|
// src/prompts/prompt-generator.ts
|
|
@@ -3908,6 +5123,8 @@ var DomainRegistry = class {
|
|
|
3908
5123
|
return jsonResponse({ error: `Unknown operation: ${parsed.operation}` }, true);
|
|
3909
5124
|
}
|
|
3910
5125
|
} catch (error) {
|
|
5126
|
+
if (error instanceof UnreadInputError) return unreadInputResponse(error);
|
|
5127
|
+
if (error instanceof TranslationReadBackError) return readBackResponse(error);
|
|
3911
5128
|
const message = error instanceof Error ? error.message : String(error);
|
|
3912
5129
|
return jsonResponse({ error: `${descriptor.name} tool error: ${message}` }, true);
|
|
3913
5130
|
}
|
|
@@ -4033,6 +5250,7 @@ var DomainRegistry = class {
|
|
|
4033
5250
|
ok: result.ok,
|
|
4034
5251
|
code: result.code,
|
|
4035
5252
|
errors: result.errors,
|
|
5253
|
+
...result.errorCode === "unread-input" ? { diagnostics: [UNREAD_INPUT(result.errors)] } : {},
|
|
4036
5254
|
language,
|
|
4037
5255
|
input
|
|
4038
5256
|
});
|
|
@@ -4045,6 +5263,7 @@ var DomainRegistry = class {
|
|
|
4045
5263
|
return jsonResponse({
|
|
4046
5264
|
valid: result.valid,
|
|
4047
5265
|
errors: result.errors,
|
|
5266
|
+
...result.errorCode === "unread-input" ? { diagnostics: [UNREAD_INPUT(result.errors)] } : {},
|
|
4048
5267
|
language,
|
|
4049
5268
|
[descriptor.inputLabel]: input
|
|
4050
5269
|
});
|
|
@@ -4075,7 +5294,24 @@ var DomainRegistry = class {
|
|
|
4075
5294
|
for (const [key, value] of node.roles) {
|
|
4076
5295
|
roles[key] = value;
|
|
4077
5296
|
}
|
|
5297
|
+
if (rendered != null) {
|
|
5298
|
+
let back = null;
|
|
5299
|
+
let why = "";
|
|
5300
|
+
try {
|
|
5301
|
+
back = dsl.parse(rendered, to);
|
|
5302
|
+
why = readingDifference(node, back);
|
|
5303
|
+
if (why && compiled.ok) {
|
|
5304
|
+
const again = dsl.compile(rendered, to);
|
|
5305
|
+
if (again.ok && again.code === compiled.code) why = "";
|
|
5306
|
+
}
|
|
5307
|
+
} catch (error) {
|
|
5308
|
+
why = error instanceof Error ? error.message : String(error);
|
|
5309
|
+
}
|
|
5310
|
+
if (why)
|
|
5311
|
+
return readBackResponse(new TranslationReadBackError(rendered, from, to, node, back, why));
|
|
5312
|
+
}
|
|
4078
5313
|
return jsonResponse({
|
|
5314
|
+
ok: true,
|
|
4079
5315
|
input: { [descriptor.inputLabel]: input, language: from },
|
|
4080
5316
|
...rendered != null && { rendered: { text: rendered, language: to } },
|
|
4081
5317
|
semantic: { action: node.action, roles },
|
|
@@ -4155,7 +5391,7 @@ function generateToolDefinitions(desc) {
|
|
|
4155
5391
|
case "translate":
|
|
4156
5392
|
tools.push({
|
|
4157
5393
|
name: `translate_${desc.name}`,
|
|
4158
|
-
description: `Translate ${desc.description} input between natural languages (requires 'from' and 'to' codes). Supports: ${langList}.`,
|
|
5394
|
+
description: `Translate ${desc.description} input between natural languages (requires 'from' and 'to' codes). Supports: ${langList}. A rendering that does not read back as the source is REFUSED: ok is false, the diagnostic is TRANSLATION_DOES_NOT_READ_BACK, and its text is under \`partial\`, never \`rendered\`: do not present it as the translation. Input left unread is refused as UNREAD_INPUT.`,
|
|
4159
5395
|
inputSchema: {
|
|
4160
5396
|
type: "object",
|
|
4161
5397
|
properties: {
|
|
@@ -4189,6 +5425,46 @@ function getString(args, name, defaultValue = "") {
|
|
|
4189
5425
|
const value = args[name];
|
|
4190
5426
|
return typeof value === "string" ? value : defaultValue;
|
|
4191
5427
|
}
|
|
5428
|
+
function readingOf(node) {
|
|
5429
|
+
const roles = {};
|
|
5430
|
+
for (const [key, value] of node.roles) roles[key] = value;
|
|
5431
|
+
return { action: node.action, roles };
|
|
5432
|
+
}
|
|
5433
|
+
var UNREAD_INPUT = (errors) => ({
|
|
5434
|
+
severity: "error",
|
|
5435
|
+
code: "UNREAD_INPUT",
|
|
5436
|
+
message: errors?.[0] ?? "part of the input was not read",
|
|
5437
|
+
suggestion: "Part of the input belongs to no role of the command it reads as: remove it, or quote a value of several words."
|
|
5438
|
+
});
|
|
5439
|
+
function unreadInputResponse(error) {
|
|
5440
|
+
return jsonResponse(
|
|
5441
|
+
{
|
|
5442
|
+
ok: false,
|
|
5443
|
+
unread: error.unread,
|
|
5444
|
+
reading: readingOf(error.reading),
|
|
5445
|
+
diagnostics: [UNREAD_INPUT([error.message])]
|
|
5446
|
+
},
|
|
5447
|
+
true
|
|
5448
|
+
);
|
|
5449
|
+
}
|
|
5450
|
+
function readBackResponse(error) {
|
|
5451
|
+
return jsonResponse(
|
|
5452
|
+
{
|
|
5453
|
+
ok: false,
|
|
5454
|
+
partial: error.partial,
|
|
5455
|
+
...error.reading ? { reading: readingOf(error.reading) } : {},
|
|
5456
|
+
diagnostics: [
|
|
5457
|
+
{
|
|
5458
|
+
severity: "error",
|
|
5459
|
+
code: "TRANSLATION_DOES_NOT_READ_BACK",
|
|
5460
|
+
message: error.message,
|
|
5461
|
+
suggestion: "The rendering would not mean the source in the target language: do not present `partial` as the translation."
|
|
5462
|
+
}
|
|
5463
|
+
]
|
|
5464
|
+
},
|
|
5465
|
+
true
|
|
5466
|
+
);
|
|
5467
|
+
}
|
|
4192
5468
|
function jsonResponse(data, isError) {
|
|
4193
5469
|
return {
|
|
4194
5470
|
content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
|
|
@@ -4339,6 +5615,50 @@ var CrossDomainDispatcher = class {
|
|
|
4339
5615
|
}
|
|
4340
5616
|
};
|
|
4341
5617
|
|
|
5618
|
+
// src/api/translation-loss.ts
|
|
5619
|
+
var LossyTranslationError = class extends Error {
|
|
5620
|
+
constructor(partial, loss, from, to) {
|
|
5621
|
+
super(
|
|
5622
|
+
`translation ${from} \u2192 ${to} would lose part of the script (${loss.kind}): ` + loss.lost.join(", ")
|
|
5623
|
+
);
|
|
5624
|
+
this.partial = partial;
|
|
5625
|
+
this.loss = loss;
|
|
5626
|
+
this.from = from;
|
|
5627
|
+
this.to = to;
|
|
5628
|
+
this.name = "LossyTranslationError";
|
|
5629
|
+
}
|
|
5630
|
+
};
|
|
5631
|
+
function unconsumedSpans(node) {
|
|
5632
|
+
const out = [];
|
|
5633
|
+
for (const d of node.diagnostics ?? []) {
|
|
5634
|
+
if (d.code !== "unconsumed-input") continue;
|
|
5635
|
+
out.push(/"(.*)"\s*$/s.exec(d.message)?.[1] ?? d.message);
|
|
5636
|
+
}
|
|
5637
|
+
return out;
|
|
5638
|
+
}
|
|
5639
|
+
function findTranslationLoss(input, node, output, readBack, rules) {
|
|
5640
|
+
const unread = unconsumedSpans(node);
|
|
5641
|
+
if (unread.length) return { kind: "truncation", lost: unread };
|
|
5642
|
+
const unwritable = rules.unwritable?.(node) ?? [];
|
|
5643
|
+
if (unwritable.length) return { kind: "core-only", lost: unwritable };
|
|
5644
|
+
let back;
|
|
5645
|
+
try {
|
|
5646
|
+
back = readBack(output);
|
|
5647
|
+
} catch (e) {
|
|
5648
|
+
return { kind: "read-back", lost: [`the output does not read: ${e.message}`] };
|
|
5649
|
+
}
|
|
5650
|
+
const misread = unconsumedSpans(back);
|
|
5651
|
+
if (misread.length) return { kind: "read-back", lost: misread };
|
|
5652
|
+
const written = rules.written ? rules.written(node) : node;
|
|
5653
|
+
for (const difference of rules.differences) {
|
|
5654
|
+
const lost = difference(written, back);
|
|
5655
|
+
if (lost.length) return { kind: "read-back", lost };
|
|
5656
|
+
}
|
|
5657
|
+
const values = rules.missingValues?.(input, output) ?? [];
|
|
5658
|
+
if (values.length) return { kind: "invariant", lost: values };
|
|
5659
|
+
return void 0;
|
|
5660
|
+
}
|
|
5661
|
+
|
|
4342
5662
|
// src/aot/domain-scanner.ts
|
|
4343
5663
|
function buildAttributePatterns(attributes) {
|
|
4344
5664
|
const patterns = [];
|
|
@@ -4630,122 +5950,6 @@ import { defineCommand, defineRole, getRoleSpec } from "@lokascript/intent";
|
|
|
4630
5950
|
// src/generation/diagnostics.ts
|
|
4631
5951
|
import { createDiagnosticCollector, fromError, filterBySeverity } from "@lokascript/intent";
|
|
4632
5952
|
|
|
4633
|
-
// src/core/tokenization/token-utils.ts
|
|
4634
|
-
var TokenStreamImpl = class {
|
|
4635
|
-
constructor(tokens, language) {
|
|
4636
|
-
this.pos = 0;
|
|
4637
|
-
this.tokens = tokens;
|
|
4638
|
-
this.language = language;
|
|
4639
|
-
}
|
|
4640
|
-
peek(offset = 0) {
|
|
4641
|
-
const index = this.pos + offset;
|
|
4642
|
-
if (index < 0 || index >= this.tokens.length) {
|
|
4643
|
-
return null;
|
|
4644
|
-
}
|
|
4645
|
-
return this.tokens[index];
|
|
4646
|
-
}
|
|
4647
|
-
advance() {
|
|
4648
|
-
if (this.isAtEnd()) {
|
|
4649
|
-
throw new Error("Unexpected end of token stream");
|
|
4650
|
-
}
|
|
4651
|
-
return this.tokens[this.pos++];
|
|
4652
|
-
}
|
|
4653
|
-
isAtEnd() {
|
|
4654
|
-
return this.pos >= this.tokens.length;
|
|
4655
|
-
}
|
|
4656
|
-
mark() {
|
|
4657
|
-
return { position: this.pos };
|
|
4658
|
-
}
|
|
4659
|
-
reset(mark) {
|
|
4660
|
-
this.pos = mark.position;
|
|
4661
|
-
}
|
|
4662
|
-
position() {
|
|
4663
|
-
return this.pos;
|
|
4664
|
-
}
|
|
4665
|
-
/**
|
|
4666
|
-
* Get remaining tokens as an array.
|
|
4667
|
-
*/
|
|
4668
|
-
remaining() {
|
|
4669
|
-
return this.tokens.slice(this.pos);
|
|
4670
|
-
}
|
|
4671
|
-
/**
|
|
4672
|
-
* Consume tokens while predicate is true.
|
|
4673
|
-
*/
|
|
4674
|
-
takeWhile(predicate) {
|
|
4675
|
-
const result = [];
|
|
4676
|
-
while (!this.isAtEnd() && predicate(this.peek())) {
|
|
4677
|
-
result.push(this.advance());
|
|
4678
|
-
}
|
|
4679
|
-
return result;
|
|
4680
|
-
}
|
|
4681
|
-
/**
|
|
4682
|
-
* Skip tokens while predicate is true.
|
|
4683
|
-
*/
|
|
4684
|
-
skipWhile(predicate) {
|
|
4685
|
-
while (!this.isAtEnd() && predicate(this.peek())) {
|
|
4686
|
-
this.advance();
|
|
4687
|
-
}
|
|
4688
|
-
}
|
|
4689
|
-
};
|
|
4690
|
-
function createPosition(start, end) {
|
|
4691
|
-
return { start, end };
|
|
4692
|
-
}
|
|
4693
|
-
function createToken(valueOrParams, kind, position, normalizedOrOptions) {
|
|
4694
|
-
if (typeof valueOrParams === "object") {
|
|
4695
|
-
const { value: value2, kind: kind2, position: position2, normalized: normalized2, stem, stemConfidence, metadata } = valueOrParams;
|
|
4696
|
-
return {
|
|
4697
|
-
value: value2,
|
|
4698
|
-
kind: kind2,
|
|
4699
|
-
position: position2,
|
|
4700
|
-
...normalized2 !== void 0 && { normalized: normalized2 },
|
|
4701
|
-
...stem !== void 0 && { stem },
|
|
4702
|
-
...stemConfidence !== void 0 && { stemConfidence },
|
|
4703
|
-
...metadata !== void 0 && { metadata }
|
|
4704
|
-
};
|
|
4705
|
-
}
|
|
4706
|
-
const value = valueOrParams;
|
|
4707
|
-
if (!kind || !position) {
|
|
4708
|
-
throw new Error("createToken requires kind and position parameters");
|
|
4709
|
-
}
|
|
4710
|
-
if (typeof normalizedOrOptions === "string") {
|
|
4711
|
-
return { value, kind, position, normalized: normalizedOrOptions };
|
|
4712
|
-
}
|
|
4713
|
-
if (normalizedOrOptions) {
|
|
4714
|
-
const { normalized: normalized2, stem, stemConfidence, metadata } = normalizedOrOptions;
|
|
4715
|
-
return {
|
|
4716
|
-
value,
|
|
4717
|
-
kind,
|
|
4718
|
-
position,
|
|
4719
|
-
...normalized2 !== void 0 && { normalized: normalized2 },
|
|
4720
|
-
...stem !== void 0 && { stem },
|
|
4721
|
-
...stemConfidence !== void 0 && { stemConfidence },
|
|
4722
|
-
...metadata !== void 0 && { metadata }
|
|
4723
|
-
};
|
|
4724
|
-
}
|
|
4725
|
-
return { value, kind, position };
|
|
4726
|
-
}
|
|
4727
|
-
function isWhitespace(char) {
|
|
4728
|
-
return /\s/.test(char);
|
|
4729
|
-
}
|
|
4730
|
-
function isSelectorStart(char) {
|
|
4731
|
-
return char === "#" || char === "." || char === "[" || char === "@" || char === "*" || char === "<";
|
|
4732
|
-
}
|
|
4733
|
-
function isQuote(char) {
|
|
4734
|
-
return char === '"' || char === "'" || char === "`" || char === "\u300C" || char === "\u300D";
|
|
4735
|
-
}
|
|
4736
|
-
function isDigit(char) {
|
|
4737
|
-
return /\d/.test(char);
|
|
4738
|
-
}
|
|
4739
|
-
function stripOptionalDiacritics(word) {
|
|
4740
|
-
return word.replace(/[\u064b-\u0652\u0670]/g, "");
|
|
4741
|
-
}
|
|
4742
|
-
function isAsciiLetter(char) {
|
|
4743
|
-
return /[a-zA-Z]/.test(char);
|
|
4744
|
-
}
|
|
4745
|
-
function isAsciiIdentifierChar(char) {
|
|
4746
|
-
return /[a-zA-Z0-9_-]/.test(char);
|
|
4747
|
-
}
|
|
4748
|
-
|
|
4749
5953
|
// src/core/tokenization/extractors.ts
|
|
4750
5954
|
function extractCssSelector(input, startPos) {
|
|
4751
5955
|
if (startPos >= input.length) return null;
|
|
@@ -6590,6 +7794,8 @@ export {
|
|
|
6590
7794
|
InMemoryDictionary,
|
|
6591
7795
|
InMemoryProfileProvider,
|
|
6592
7796
|
LatinExtendedIdentifierExtractor,
|
|
7797
|
+
LossyTranslationError,
|
|
7798
|
+
MatchSkeleton,
|
|
6593
7799
|
NullDictionary,
|
|
6594
7800
|
NullProfileProvider,
|
|
6595
7801
|
NumberExtractor,
|
|
@@ -6597,9 +7803,12 @@ export {
|
|
|
6597
7803
|
PatternMatcher,
|
|
6598
7804
|
PatternTracker,
|
|
6599
7805
|
PunctuationExtractor,
|
|
7806
|
+
StockValueReader,
|
|
6600
7807
|
StringLiteralExtractor,
|
|
6601
7808
|
TokenStreamImpl,
|
|
7809
|
+
TranslationReadBackError,
|
|
6602
7810
|
UnicodeIdentifierExtractor,
|
|
7811
|
+
UnreadInputError,
|
|
6603
7812
|
WhitespaceExtractor,
|
|
6604
7813
|
accumulateBlocks,
|
|
6605
7814
|
buildDisambiguation,
|
|
@@ -6629,9 +7838,11 @@ export {
|
|
|
6629
7838
|
createPosition,
|
|
6630
7839
|
createPropertyPath,
|
|
6631
7840
|
createReference,
|
|
7841
|
+
createSchemaPatternGenerator,
|
|
6632
7842
|
createSchemaRenderer,
|
|
6633
7843
|
createSelector,
|
|
6634
7844
|
createSimpleTokenizer,
|
|
7845
|
+
createStockReader,
|
|
6635
7846
|
createToken,
|
|
6636
7847
|
createTokenizerContext,
|
|
6637
7848
|
createTryNode,
|
|
@@ -6647,6 +7858,7 @@ export {
|
|
|
6647
7858
|
extractUrl,
|
|
6648
7859
|
extractValue,
|
|
6649
7860
|
filterBySeverity,
|
|
7861
|
+
findTranslationLoss,
|
|
6650
7862
|
fromEnvelopeJSON,
|
|
6651
7863
|
fromError,
|
|
6652
7864
|
fromInterchangeNode,
|
|
@@ -6661,6 +7873,7 @@ export {
|
|
|
6661
7873
|
getPossessiveReference,
|
|
6662
7874
|
getRoleSpec,
|
|
6663
7875
|
getRoleValue,
|
|
7876
|
+
greedyStopMarkers,
|
|
6664
7877
|
insertMarkers,
|
|
6665
7878
|
isAsciiIdentifierChar,
|
|
6666
7879
|
isAsciiLetter,
|
|
@@ -6688,6 +7901,7 @@ export {
|
|
|
6688
7901
|
isWhitespace,
|
|
6689
7902
|
joinTokens,
|
|
6690
7903
|
jsonToSemanticNode,
|
|
7904
|
+
legacyMarkerAlternatives,
|
|
6691
7905
|
lookupKeyword,
|
|
6692
7906
|
lookupMarker,
|
|
6693
7907
|
matchBest,
|
|
@@ -6700,24 +7914,33 @@ export {
|
|
|
6700
7914
|
parseExplicit,
|
|
6701
7915
|
parseJSONL,
|
|
6702
7916
|
patternMatcher,
|
|
7917
|
+
readGreedy,
|
|
7918
|
+
readRoleValue,
|
|
6703
7919
|
registryToAOTBackends,
|
|
6704
7920
|
renderDocument,
|
|
6705
7921
|
renderExplicit,
|
|
6706
7922
|
renderExpr,
|
|
7923
|
+
renderPattern,
|
|
6707
7924
|
reorderRoles,
|
|
7925
|
+
resolveMarkerForRole,
|
|
7926
|
+
schemaMarkerAlternatives,
|
|
7927
|
+
selectRenderPattern,
|
|
6708
7928
|
semanticNodeToJSON,
|
|
6709
7929
|
semanticNodeToRuntimeAST,
|
|
6710
7930
|
semanticValueToAST,
|
|
6711
7931
|
sortRolesByWordOrder,
|
|
7932
|
+
stockConfidenceModel,
|
|
6712
7933
|
stripOptionalDiacritics,
|
|
6713
7934
|
synthesizeFromSchemas,
|
|
6714
7935
|
toEnvelopeJSON,
|
|
6715
7936
|
toJSONL,
|
|
6716
7937
|
toJSONLRow,
|
|
6717
7938
|
toProtocolJSON,
|
|
7939
|
+
unconsumedSpans,
|
|
6718
7940
|
validateProtocolJSON,
|
|
6719
7941
|
validateSemanticJSON,
|
|
6720
7942
|
validateValueType,
|
|
6721
|
-
withDefaultExtractors
|
|
7943
|
+
withDefaultExtractors,
|
|
7944
|
+
withoutVariantOnlyRoles
|
|
6722
7945
|
};
|
|
6723
7946
|
//# sourceMappingURL=index.js.map
|