@lokascript/i18n 2.11.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/browser.cjs +5 -1690
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.cts +2 -2
  5. package/dist/browser.d.ts +2 -2
  6. package/dist/browser.js +6 -1685
  7. package/dist/browser.js.map +1 -1
  8. package/dist/dictionaries/index.cjs +5 -1
  9. package/dist/dictionaries/index.cjs.map +1 -1
  10. package/dist/dictionaries/index.js +5 -1
  11. package/dist/dictionaries/index.js.map +1 -1
  12. package/dist/{transformer-CsOeqayN.d.cts → index-BykxjYST.d.cts} +1 -232
  13. package/dist/{transformer-DWCTG1DQ.d.ts → index-DuIef8O7.d.ts} +1 -232
  14. package/dist/index.cjs +16 -1878
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +35 -35
  17. package/dist/index.d.ts +35 -35
  18. package/dist/index.js +17 -1873
  19. package/dist/index.js.map +1 -1
  20. package/dist/lokascript-i18n.min.js +1 -1
  21. package/dist/lokascript-i18n.min.js.map +1 -1
  22. package/dist/lokascript-i18n.mjs +49 -2680
  23. package/dist/lokascript-i18n.mjs.map +1 -1
  24. package/dist/plugins/vite.cjs +5 -1
  25. package/dist/plugins/vite.cjs.map +1 -1
  26. package/dist/plugins/vite.js +5 -1
  27. package/dist/plugins/vite.js.map +1 -1
  28. package/dist/plugins/webpack.cjs +5 -1
  29. package/dist/plugins/webpack.cjs.map +1 -1
  30. package/dist/plugins/webpack.js +5 -1
  31. package/dist/plugins/webpack.js.map +1 -1
  32. package/package.json +4 -4
  33. package/src/browser.ts +0 -7
  34. package/src/compatibility/browser-tests/grammar-demo.spec.ts +22 -8
  35. package/src/constants.ts +1 -0
  36. package/src/dictionaries/bn.ts +5 -1
  37. package/src/grammar/index.ts +15 -9
  38. package/src/grammar/profiles.test.ts +440 -0
  39. package/src/index.ts +0 -7
  40. package/src/lexicon-parity.test.ts +77 -0
  41. package/src/grammar/grammar.test.ts +0 -2751
  42. package/src/grammar/transformer.ts +0 -2737
package/dist/browser.cjs CHANGED
@@ -1,39 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  // src/constants.ts
4
- var ENGLISH_MODIFIER_ROLES = {
5
- to: "destination",
6
- into: "destination",
7
- from: "source",
8
- with: "style",
9
- by: "quantity",
10
- as: "method",
11
- on: "event",
12
- over: "duration",
13
- for: "duration"
14
- };
15
- var COMMAND_PRIMARY_ROLES = {
16
- set: "destination",
17
- on: "event",
18
- trigger: "event",
19
- send: "event",
20
- wait: "duration",
21
- fetch: "source",
22
- get: "source",
23
- if: "condition",
24
- unless: "condition",
25
- while: "condition",
26
- repeat: "loopType",
27
- go: "destination",
28
- scroll: "destination",
29
- tell: "destination",
30
- default: "destination",
31
- swap: "destination",
32
- // morph deliberately absent: its schema primaryRole is `patient` (the
33
- // element being morphed — aligned with the transformer's patient marking
34
- // in the session-9 role-layout swap), and patient is the default.
35
- bind: "destination"
36
- };
37
4
  var ENGLISH_MODIFIERS = /* @__PURE__ */ new Set([
38
5
  "to",
39
6
  "from",
@@ -266,69 +233,6 @@ var ENGLISH_EXPRESSION_KEYWORDS = /* @__PURE__ */ new Set([
266
233
  "starts with",
267
234
  "ends with"
268
235
  ]);
269
- var CONDITIONAL_KEYWORDS = /* @__PURE__ */ new Set([
270
- // English
271
- "if",
272
- "unless",
273
- "when",
274
- "where",
275
- // Japanese
276
- "\u3082\u3057",
277
- "\u6642\u306B",
278
- "\u3068\u304D\u306B",
279
- "\u3069\u3053\u3067",
280
- // Chinese
281
- "\u5982\u679C",
282
- "\u5F53",
283
- // Arabic
284
- "\u0625\u0630\u0627",
285
- "\u0639\u0646\u062F\u0645\u0627",
286
- "\u062D\u064A\u062B",
287
- // Spanish
288
- "si",
289
- "cuando",
290
- "donde",
291
- // German
292
- "wenn",
293
- "wann",
294
- "wo",
295
- // French
296
- "quand",
297
- "lorsque",
298
- "o\xF9",
299
- // Portuguese
300
- "quando",
301
- "onde",
302
- // Turkish
303
- "e\u011Fer",
304
- "zaman",
305
- "nerede",
306
- // Indonesian
307
- "ketika",
308
- "saat",
309
- "dimana",
310
- // Korean
311
- "\uB54C",
312
- "\uC5B4\uB514\uC11C",
313
- // Quechua
314
- "maypi",
315
- // Swahili
316
- "wakati",
317
- "wapi"
318
- ]);
319
- var THEN_KEYWORDS = /* @__PURE__ */ new Set([
320
- "then",
321
- "\u305D\u308C\u304B\u3089",
322
- "\u90A3\u4E48",
323
- "\u062B\u0645",
324
- "entonces",
325
- "alors",
326
- "dann",
327
- "sonra",
328
- "lalu",
329
- "chayqa",
330
- "kisha"
331
- ]);
332
236
 
333
237
  // src/parser/create-provider.ts
334
238
  function createKeywordProvider(dictionary, locale, options = {}) {
@@ -4827,7 +4731,11 @@ var bengaliDictionary = {
4827
4731
  random: "\u098F\u09B2\u09CB\u09AE\u09C7\u09B2\u09CB",
4828
4732
  length: "\u09A6\u09C8\u09B0\u09CD\u0998\u09CD\u09AF",
4829
4733
  index: "\u09B8\u09C2\u099A\u0995",
4830
- empty: "\u0996\u09BE\u09B2\u09BF-\u0995\u09B0\u09C1\u09A8",
4734
+ // The EXPRESSION `empty` is the state predicate (`if my value is empty`),
4735
+ // not the command: `খালি-করুন` is the imperative "empty it!" and belongs to
4736
+ // the `empty` COMMAND, which keeps it. Kept in step with the semantic
4737
+ // lexicon by `lexicon-parity.test.ts`.
4738
+ empty: "\u0996\u09BE\u09B2\u09BF",
4831
4739
  "starts with": "\u09A6\u09BF\u09AF\u09BC\u09C7_\u09B6\u09C1\u09B0\u09C1",
4832
4740
  "ends with": "\u09A6\u09BF\u09AF\u09BC\u09C7_\u09B6\u09C7\u09B7",
4833
4741
  "ignoring case": "\u0995\u09C7\u09B8_\u0989\u09AA\u09C7\u0995\u09CD\u09B7\u09BE",
@@ -7838,1596 +7746,8 @@ function getSupportedDirectPairs() {
7838
7746
  });
7839
7747
  }
7840
7748
 
7841
- // src/dictionaries/index.ts
7842
- var en2 = en;
7843
- var es2 = es;
7844
- var ja2 = ja;
7845
- var ko2 = ko;
7846
- var zh2 = zh;
7847
- var fr2 = fr;
7848
- var de2 = de;
7849
- var ar2 = ar;
7850
- var tr2 = tr;
7851
- var id2 = id;
7852
- var pt2 = pt;
7853
- var qu2 = qu;
7854
- var sw2 = sw;
7855
- var it2 = it;
7856
- var vi2 = vi;
7857
- var pl2 = pl;
7858
- var ru = russianDictionary;
7859
- var uk = ukrainianDictionary;
7860
- var hi = hindiDictionary;
7861
- var bn2 = bengaliDictionary;
7862
- var th2 = thaiDictionary;
7863
- var ms2 = malayDictionary;
7864
- var tl2 = tagalogDictionary;
7865
- var he2 = he;
7866
- var dictionaries = {
7867
- en: en2,
7868
- es: es2,
7869
- ko: ko2,
7870
- zh: zh2,
7871
- fr: fr2,
7872
- de: de2,
7873
- ja: ja2,
7874
- ar: ar2,
7875
- tr: tr2,
7876
- id: id2,
7877
- qu: qu2,
7878
- sw: sw2,
7879
- pt: pt2,
7880
- it: it2,
7881
- vi: vi2,
7882
- pl: pl2,
7883
- ru,
7884
- uk,
7885
- hi,
7886
- bn: bn2,
7887
- th: th2,
7888
- ms: ms2,
7889
- tl: tl2,
7890
- he: he2
7891
- };
7892
-
7893
- // src/types.ts
7894
- var DICTIONARY_CATEGORIES = [
7895
- "commands",
7896
- "modifiers",
7897
- "events",
7898
- "logical",
7899
- "temporal",
7900
- "values",
7901
- "attributes",
7902
- "expressions"
7903
- ];
7904
- function findInDictionary(dict, localizedWord) {
7905
- const normalized = localizedWord.toLowerCase();
7906
- for (const category of DICTIONARY_CATEGORIES) {
7907
- const entries = dict[category];
7908
- for (const [english, localized] of Object.entries(entries)) {
7909
- if (localized.toLowerCase() === normalized) {
7910
- return { category, englishKey: english };
7911
- }
7912
- }
7913
- }
7914
- return void 0;
7915
- }
7916
- function translateFromEnglish(dict, englishWord) {
7917
- const normalized = englishWord.toLowerCase();
7918
- for (const category of DICTIONARY_CATEGORIES) {
7919
- const entries = dict[category];
7920
- const translated = entries[normalized];
7921
- if (translated) {
7922
- return translated;
7923
- }
7924
- }
7925
- return void 0;
7926
- }
7927
-
7928
- // src/grammar/transformer.ts
7929
- function getCommandKeywordsForLocale(locale) {
7930
- const keywords = new Set(ENGLISH_COMMANDS);
7931
- const dict = dictionaries[locale];
7932
- if (dict?.commands) {
7933
- Object.values(dict.commands).forEach((cmd) => {
7934
- if (typeof cmd === "string") {
7935
- keywords.add(cmd.toLowerCase());
7936
- }
7937
- });
7938
- }
7939
- return keywords;
7940
- }
7941
- var EN_COPULAS = ["is", "are", "was", "were", "am", "be"];
7942
- function getCopulasForLocale(locale) {
7943
- const copulas = new Set(EN_COPULAS);
7944
- if (locale !== "en") {
7945
- for (const form of EN_COPULAS) {
7946
- copulas.add(translateWord(form, "en", locale).toLowerCase());
7947
- }
7948
- }
7949
- return copulas;
7950
- }
7951
- function isPredicateAdjectivePosition(tokens, i, copulas) {
7952
- const prev = tokens[i - 1]?.toLowerCase();
7953
- return !!prev && copulas.has(prev);
7954
- }
7955
- function getForLoopWordsForLocale(locale) {
7956
- const forWords = /* @__PURE__ */ new Set(["for"]);
7957
- const inWords = /* @__PURE__ */ new Set(["in"]);
7958
- if (locale !== "en") {
7959
- forWords.add(translateWord("for", "en", locale).toLowerCase());
7960
- inWords.add(translateWord("in", "en", locale).toLowerCase());
7961
- }
7962
- return { forWords, inWords };
7963
- }
7964
- function isLoopHeadFor(tokens, i, inWords, commandKeywords) {
7965
- for (let j = i + 1; j < tokens.length; j++) {
7966
- const lt = tokens[j].toLowerCase();
7967
- if (inWords.has(lt)) return true;
7968
- if (commandKeywords.has(lt)) return false;
7969
- }
7970
- return false;
7971
- }
7972
- function repairHebrewFrontedAccusative(text) {
7973
- const ACC = "\u05D0\u05EA";
7974
- const verbs = getCommandKeywordsForLocale("he");
7975
- const tokens = text.split(/\s+/);
7976
- let changed = false;
7977
- for (let i = 0; i + 1 < tokens.length; i++) {
7978
- if (tokens[i] === ACC && verbs.has(tokens[i + 1].toLowerCase())) {
7979
- [tokens[i], tokens[i + 1]] = [tokens[i + 1], tokens[i]];
7980
- changed = true;
7981
- i++;
7982
- }
7983
- }
7984
- return changed ? tokens.join(" ") : text;
7985
- }
7986
- function extractBlockStructure(input, sourceLocale) {
7987
- const tokens = input.split(/\s+/);
7988
- const head = tokens[0]?.toLowerCase();
7989
- if (!head || !BLOCK_HEAD_KEYWORDS.has(head)) return null;
7990
- let depth = 1;
7991
- let endIdx = -1;
7992
- for (let i = 1; i < tokens.length; i++) {
7993
- const t = tokens[i].toLowerCase();
7994
- if (BLOCK_HEAD_KEYWORDS.has(t)) depth++;
7995
- else if (t === "end") {
7996
- depth--;
7997
- if (depth === 0) {
7998
- endIdx = i;
7999
- break;
8000
- }
8001
- }
8002
- }
8003
- if (endIdx !== -1 && endIdx !== tokens.length - 1) return null;
8004
- const inner = endIdx !== -1 ? tokens.slice(1, endIdx) : tokens.slice(1);
8005
- const base = { headKeyword: tokens[0], body: "" };
8006
- if (endIdx !== -1) base.tailKeyword = tokens[endIdx];
8007
- if (head === "live") {
8008
- return { ...base, body: inner.join(" ") };
8009
- }
8010
- if (head === "when") {
8011
- const idx = inner.findIndex((t) => t.toLowerCase() === "changes");
8012
- if (idx >= 0) {
8013
- return {
8014
- ...base,
8015
- prefixExpr: inner.slice(0, idx).join(" "),
8016
- connector: inner[idx],
8017
- body: inner.slice(idx + 1).join(" ")
8018
- };
8019
- }
8020
- return null;
8021
- }
8022
- const commands = getCommandKeywordsForLocale(sourceLocale);
8023
- const copulas = getCopulasForLocale(sourceLocale);
8024
- let bodyStart = -1;
8025
- for (let i = 0; i < inner.length; i++) {
8026
- if (commands.has(inner[i].toLowerCase()) && !isPredicateAdjectivePosition(inner, i, copulas)) {
8027
- bodyStart = i;
8028
- break;
8029
- }
8030
- }
8031
- if (bodyStart <= 0) return null;
8032
- return {
8033
- ...base,
8034
- prefixExpr: inner.slice(0, bodyStart).join(" "),
8035
- body: inner.slice(bodyStart).join(" ")
8036
- };
8037
- }
8038
- function splitCompoundStatement(input, sourceLocale) {
8039
- const lines = input.split(/\n/).map((line) => line.trim()).filter((line) => line.length > 0);
8040
- const parts = [];
8041
- for (const line of lines) {
8042
- const lineParts = splitOnThen(line, sourceLocale);
8043
- for (const part of lineParts) {
8044
- const commandParts = splitOnCommandBoundaries(part, sourceLocale);
8045
- parts.push(...commandParts);
8046
- }
8047
- }
8048
- return parts;
8049
- }
8050
- function splitCompoundStatementWithMetadata(input, sourceLocale) {
8051
- const rawLines = input.split("\n");
8052
- const lineMetadata = [];
8053
- const parts = [];
8054
- const partToLineIndex = [];
8055
- for (let lineIndex = 0; lineIndex < rawLines.length; lineIndex++) {
8056
- const rawLine = rawLines[lineIndex];
8057
- const indentMatch = rawLine.match(/^(\s*)/);
8058
- const originalIndent = indentMatch ? indentMatch[1] : "";
8059
- const trimmed = rawLine.trim();
8060
- lineMetadata.push({
8061
- content: trimmed,
8062
- originalIndent,
8063
- isBlank: trimmed.length === 0
8064
- });
8065
- if (trimmed.length > 0) {
8066
- const lineParts = splitOnThen(trimmed, sourceLocale);
8067
- for (const part of lineParts) {
8068
- const commandParts = splitOnCommandBoundaries(part, sourceLocale);
8069
- for (const cmdPart of commandParts) {
8070
- parts.push(cmdPart);
8071
- partToLineIndex.push(lineIndex);
8072
- }
8073
- }
8074
- }
8075
- }
8076
- return { parts, lineMetadata, partToLineIndex };
8077
- }
8078
- function normalizeIndentation(lineMetadata) {
8079
- const indentedLines = lineMetadata.filter((m) => !m.isBlank && m.originalIndent.length > 0);
8080
- if (indentedLines.length === 0) {
8081
- return lineMetadata.map(() => "");
8082
- }
8083
- const indentLengths = indentedLines.map((m) => {
8084
- const normalized = m.originalIndent.replace(/\t/g, " ");
8085
- return normalized.length;
8086
- });
8087
- const minIndent = Math.min(...indentLengths);
8088
- const baseUnit = minIndent > 0 ? minIndent : 4;
8089
- return lineMetadata.map((meta) => {
8090
- if (meta.isBlank) {
8091
- return "";
8092
- }
8093
- if (meta.originalIndent.length === 0) {
8094
- return "";
8095
- }
8096
- const normalized = meta.originalIndent.replace(/\t/g, " ");
8097
- const level = Math.round(normalized.length / baseUnit);
8098
- return " ".repeat(level);
8099
- });
8100
- }
8101
- function reconstructWithLineStructure(transformedParts, lineMetadata, partToLineIndex, targetThen) {
8102
- const nonBlankCount = lineMetadata.filter((m) => !m.isBlank).length;
8103
- if (nonBlankCount <= 1 && transformedParts.length <= 1) {
8104
- const normalizedIndents2 = normalizeIndentation(lineMetadata);
8105
- const result2 = [];
8106
- for (let i = 0; i < lineMetadata.length; i++) {
8107
- if (lineMetadata[i].isBlank) {
8108
- result2.push("");
8109
- } else if (transformedParts.length > 0) {
8110
- result2.push(normalizedIndents2[i] + transformedParts[0]);
8111
- }
8112
- }
8113
- return result2.join("\n");
8114
- }
8115
- const normalizedIndents = normalizeIndentation(lineMetadata);
8116
- const partsPerLine = /* @__PURE__ */ new Map();
8117
- for (let i = 0; i < transformedParts.length; i++) {
8118
- const lineIdx = partToLineIndex[i];
8119
- if (!partsPerLine.has(lineIdx)) {
8120
- partsPerLine.set(lineIdx, []);
8121
- }
8122
- partsPerLine.get(lineIdx).push(transformedParts[i]);
8123
- }
8124
- const result = [];
8125
- for (let i = 0; i < lineMetadata.length; i++) {
8126
- const meta = lineMetadata[i];
8127
- const indent = normalizedIndents[i];
8128
- if (meta.isBlank) {
8129
- result.push("");
8130
- } else {
8131
- const lineParts = partsPerLine.get(i) || [];
8132
- if (lineParts.length > 0) {
8133
- const lineContent = lineParts.join(` ${targetThen} `);
8134
- result.push(indent + lineContent);
8135
- }
8136
- }
8137
- }
8138
- return result.join("\n");
8139
- }
8140
- var BOUNDARY_MODIFIERS = /* @__PURE__ */ new Set([
8141
- "to",
8142
- "into",
8143
- "from",
8144
- "with",
8145
- "by",
8146
- "as",
8147
- "at",
8148
- "in",
8149
- "on",
8150
- "of",
8151
- "over"
8152
- ]);
8153
- var boundaryModifiersCache = /* @__PURE__ */ new Map();
8154
- function getBoundaryModifiersForLocale(locale) {
8155
- const cached = boundaryModifiersCache.get(locale);
8156
- if (cached) return cached;
8157
- const modifiers = new Set(BOUNDARY_MODIFIERS);
8158
- const profile = getProfile(locale);
8159
- profile?.markers.forEach((marker) => {
8160
- const form = marker.form.replace(/^-|-$/g, "").toLowerCase();
8161
- if (form) modifiers.add(form);
8162
- marker.alternatives?.forEach((alt) => {
8163
- const altForm = alt.replace(/^-|-$/g, "").toLowerCase();
8164
- if (altForm) modifiers.add(altForm);
8165
- });
8166
- });
8167
- boundaryModifiersCache.set(locale, modifiers);
8168
- return modifiers;
8169
- }
8170
- var ON_TARGET_COMMANDS = /* @__PURE__ */ new Set(["toggle", "add", "remove", "trigger", "send"]);
8171
- function commandVerbOf(tokens, commandKeywords) {
8172
- for (const token of tokens) {
8173
- const lt = token.toLowerCase();
8174
- if (commandKeywords.has(lt) && !BOUNDARY_MODIFIERS.has(lt) && !EVENT_KEYWORDS.has(lt)) {
8175
- return lt;
8176
- }
8177
- }
8178
- return null;
8179
- }
8180
- var BLOCK_HEAD_KEYWORDS = /* @__PURE__ */ new Set(["live", "when", "unless"]);
8181
- var BLOCK_BODY_KEYWORDS = /* @__PURE__ */ new Set(["if", "repeat", "unless", "while", "for"]);
8182
- var UNLESS_GUARD_OBJECT_MARKING_LOCALES = /* @__PURE__ */ new Set(["he", "zh"]);
8183
- function splitOnCommandBoundaries(input, sourceLocale) {
8184
- const commandKeywords = getCommandKeywordsForLocale(sourceLocale);
8185
- const boundaryModifiers = getBoundaryModifiersForLocale(sourceLocale);
8186
- const { forWords, inWords } = getForLoopWordsForLocale(sourceLocale);
8187
- const tokens = input.split(/\s+/);
8188
- if (tokens.length === 0) return [input];
8189
- const parts = [];
8190
- let currentPart = [];
8191
- const firstTokenLower = tokens[0]?.toLowerCase();
8192
- const isEventHandler = EVENT_KEYWORDS.has(firstTokenLower);
8193
- let seenFirstCommand = !isEventHandler;
8194
- let blockDepth = 0;
8195
- for (let i = 0; i < tokens.length; i++) {
8196
- const token = tokens[i];
8197
- const lowerToken = token.toLowerCase();
8198
- if (BLOCK_HEAD_KEYWORDS.has(lowerToken)) {
8199
- blockDepth++;
8200
- } else if (lowerToken === "end" && blockDepth > 0) {
8201
- blockDepth--;
8202
- }
8203
- if (commandKeywords.has(lowerToken) && currentPart.length > 0) {
8204
- const prevToken = currentPart[currentPart.length - 1];
8205
- const prevLower = prevToken.toLowerCase();
8206
- if (!seenFirstCommand) {
8207
- seenFirstCommand = true;
8208
- currentPart.push(token);
8209
- continue;
8210
- }
8211
- if (blockDepth > 0) {
8212
- currentPart.push(token);
8213
- continue;
8214
- }
8215
- if (forWords.has(lowerToken) && !isLoopHeadFor(tokens, i, inWords, commandKeywords)) {
8216
- currentPart.push(token);
8217
- continue;
8218
- }
8219
- if (BOUNDARY_MODIFIERS.has(lowerToken)) {
8220
- const verb = commandVerbOf(currentPart, commandKeywords);
8221
- if (verb && ON_TARGET_COMMANDS.has(verb)) {
8222
- currentPart.push(token);
8223
- continue;
8224
- }
8225
- if (lowerToken === "on" && verb === "set") {
8226
- const nextTok = tokens[i + 1];
8227
- const nextLower = nextTok?.toLowerCase();
8228
- const scopeLike = !!nextTok && (/^[#.<@[]/.test(nextTok) || nextLower === "me" || nextLower === "it" || nextLower === "you");
8229
- if (scopeLike) {
8230
- currentPart.push(token);
8231
- continue;
8232
- }
8233
- }
8234
- }
8235
- if (!boundaryModifiers.has(prevLower) && !commandKeywords.has(prevLower)) {
8236
- parts.push(currentPart.join(" "));
8237
- currentPart = [token];
8238
- continue;
8239
- }
8240
- }
8241
- currentPart.push(token);
8242
- }
8243
- if (currentPart.length > 0) {
8244
- parts.push(currentPart.join(" "));
8245
- }
8246
- return parts.filter((p) => p.length > 0);
8247
- }
8248
- function splitOnThen(input, sourceLocale) {
8249
- const thenKeywords = Array.from(THEN_KEYWORDS);
8250
- const sourceDict = sourceLocale === "en" ? null : dictionaries[sourceLocale];
8251
- if (sourceDict?.modifiers?.then) {
8252
- thenKeywords.push(sourceDict.modifiers.then);
8253
- }
8254
- if (sourceDict?.logical?.then) {
8255
- thenKeywords.push((sourceDict?.logical).then);
8256
- }
8257
- const escapedKeywords = thenKeywords.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
8258
- const pattern = new RegExp(`\\s+(${escapedKeywords.join("|")})\\s+`, "gi");
8259
- const parts = input.split(pattern).filter((part) => {
8260
- const lowerPart = part.toLowerCase().trim();
8261
- return lowerPart && !thenKeywords.some((k) => k.toLowerCase() === lowerPart);
8262
- });
8263
- return parts.map((p) => p.trim()).filter((p) => p.length > 0);
8264
- }
8265
- function getTargetThenKeyword(targetLocale) {
8266
- if (targetLocale === "en") return "then";
8267
- const targetDict = dictionaries[targetLocale];
8268
- if (!targetDict) return "then";
8269
- return targetDict.modifiers?.then || targetDict.logical?.then || "then";
8270
- }
8271
- function deriveEventKeywordsFromProfiles() {
8272
- const keywords = /* @__PURE__ */ new Set();
8273
- keywords.add("on");
8274
- for (const profile of Object.values(profiles)) {
8275
- for (const marker of profile.markers) {
8276
- if (marker.role === "event") {
8277
- const form = marker.form.replace(/^-|-$/g, "").toLowerCase();
8278
- if (form) keywords.add(form);
8279
- marker.alternatives?.forEach((alt) => {
8280
- const altForm = alt.replace(/^-|-$/g, "").toLowerCase();
8281
- if (altForm) keywords.add(altForm);
8282
- });
8283
- }
8284
- }
8285
- }
8286
- return keywords;
8287
- }
8288
- var EVENT_KEYWORDS = deriveEventKeywordsFromProfiles();
8289
- var EVENT_CONJUNCTIONS = /* @__PURE__ */ new Set(["or"]);
8290
- var BODY_MODIFIER_KEYWORDS = /* @__PURE__ */ new Set([
8291
- "async",
8292
- "once",
8293
- "debounced",
8294
- "debounce",
8295
- "throttled",
8296
- "throttle"
8297
- ]);
8298
- function generateModifierMap(profile) {
8299
- const map = {};
8300
- profile.markers.forEach((marker) => {
8301
- const form = marker.form.replace(/^-|-$/g, "").toLowerCase();
8302
- if (form) {
8303
- map[form] = marker.role;
8304
- }
8305
- marker.alternatives?.forEach((alt) => {
8306
- const altForm = alt.replace(/^-|-$/g, "").toLowerCase();
8307
- if (altForm) {
8308
- map[altForm] = marker.role;
8309
- }
8310
- });
8311
- });
8312
- for (const [key, role] of Object.entries(ENGLISH_MODIFIER_ROLES)) {
8313
- if (!(key in map)) {
8314
- map[key] = role;
8315
- }
8316
- }
8317
- return map;
8318
- }
8319
- function buildArgumentModifierMap(profile, actionVerb) {
8320
- const map = generateModifierMap(profile);
8321
- const verb = actionVerb?.toLowerCase();
8322
- if (profile.wordOrder !== "SVO" || !verb || !ON_TARGET_COMMANDS.has(verb)) {
8323
- return map;
8324
- }
8325
- const remapped = {};
8326
- for (const [form, role] of Object.entries(map)) {
8327
- remapped[form] = role === "event" ? "destination" : role;
8328
- }
8329
- return remapped;
8330
- }
8331
- function parseStatement(input, sourceLocale = "en") {
8332
- const profile = getProfile(sourceLocale);
8333
- if (!profile) return null;
8334
- const tokens = tokenize(input, profile);
8335
- const statementType = identifyStatementType(tokens, profile);
8336
- switch (statementType) {
8337
- case "event-handler":
8338
- return parseEventHandler(tokens, profile);
8339
- case "command":
8340
- return parseCommand(tokens, profile);
8341
- case "conditional":
8342
- return parseConditional(tokens);
8343
- default:
8344
- return null;
8345
- }
8346
- }
8347
- var ATTACHED_SUFFIXES = {
8348
- // Chinese: 时 (time/when) often attaches to events like 点击时 (when clicking)
8349
- zh: ["\u65F6", "\u7684", "\u5730", "\u5F97"],
8350
- // Japanese: Some particles may attach in casual writing
8351
- ja: [],
8352
- // Korean: Particles sometimes written without spaces
8353
- ko: []
8354
- };
8355
- var ATTACHED_PREFIXES = {
8356
- // Chinese: 当 (when) sometimes written attached
8357
- zh: ["\u5F53"],
8358
- // Arabic: Prepositions that attach
8359
- ar: ["\u0628\u0640", "\u0643\u0640", "\u0648"]
8360
- };
8361
- function splitAttachedAffixes(tokens, locale) {
8362
- const suffixes = ATTACHED_SUFFIXES[locale] || [];
8363
- const prefixes = ATTACHED_PREFIXES[locale] || [];
8364
- if (suffixes.length === 0 && prefixes.length === 0) {
8365
- return tokens;
8366
- }
8367
- const result = [];
8368
- for (const token of tokens) {
8369
- if (/^[#.<@]/.test(token) || /^\d+/.test(token)) {
8370
- result.push(token);
8371
- continue;
8372
- }
8373
- let processed = token;
8374
- let prefix = "";
8375
- let suffix = "";
8376
- for (const p of prefixes) {
8377
- if (processed.startsWith(p) && processed.length > p.length) {
8378
- prefix = p;
8379
- processed = processed.slice(p.length);
8380
- break;
8381
- }
8382
- }
8383
- for (const s of suffixes) {
8384
- if (processed.endsWith(s) && processed.length > s.length) {
8385
- suffix = s;
8386
- processed = processed.slice(0, -s.length);
8387
- break;
8388
- }
8389
- }
8390
- if (prefix) result.push(prefix);
8391
- if (processed) result.push(processed);
8392
- if (suffix) result.push(suffix);
8393
- }
8394
- return result;
8395
- }
8396
- function tokenize(input, profile) {
8397
- const tokens = [];
8398
- let current = "";
8399
- let inSelector = false;
8400
- let selectorDepth = 0;
8401
- let bracketDepth = 0;
8402
- let parenDepth = 0;
8403
- for (let i = 0; i < input.length; i++) {
8404
- const char = input[i];
8405
- if (char === "<") {
8406
- inSelector = true;
8407
- selectorDepth++;
8408
- } else if (char === ">" && inSelector) {
8409
- selectorDepth--;
8410
- if (selectorDepth === 0) inSelector = false;
8411
- }
8412
- if (char === "[") {
8413
- bracketDepth++;
8414
- } else if (char === "]" && bracketDepth > 0) {
8415
- bracketDepth--;
8416
- }
8417
- if (char === "(") {
8418
- parenDepth++;
8419
- } else if (char === ")" && parenDepth > 0) {
8420
- parenDepth--;
8421
- }
8422
- if (/\s/.test(char) && !inSelector && bracketDepth === 0 && parenDepth === 0) {
8423
- if (current) {
8424
- tokens.push(current);
8425
- current = "";
8426
- }
8427
- } else {
8428
- current += char;
8429
- }
8430
- }
8431
- if (current) {
8432
- tokens.push(current);
8433
- }
8434
- return splitAttachedAffixes(tokens, profile.code);
8435
- }
8436
- function identifyStatementType(tokens, profile) {
8437
- if (tokens.length === 0) return "unknown";
8438
- const firstToken = tokens[0].toLowerCase();
8439
- const eventMarker = profile.markers.find((m) => m.role === "event" && m.position === "preposition");
8440
- if (eventMarker && firstToken === eventMarker.form.toLowerCase()) {
8441
- return "event-handler";
8442
- }
8443
- if (EVENT_KEYWORDS.has(firstToken)) {
8444
- return "event-handler";
8445
- }
8446
- if (CONDITIONAL_KEYWORDS.has(firstToken)) {
8447
- return "conditional";
8448
- }
8449
- return "command";
8450
- }
8451
- function parseEventHandler(tokens, profile) {
8452
- const roles = /* @__PURE__ */ new Map();
8453
- let startIndex = EVENT_KEYWORDS.has(tokens[0]?.toLowerCase()) ? 1 : 0;
8454
- if (tokens[startIndex]) {
8455
- const eventTokens = [tokens[startIndex]];
8456
- startIndex++;
8457
- while (tokens[startIndex] && EVENT_CONJUNCTIONS.has(tokens[startIndex].toLowerCase()) && tokens[startIndex + 1]) {
8458
- eventTokens.push(tokens[startIndex], tokens[startIndex + 1]);
8459
- startIndex += 2;
8460
- }
8461
- roles.set("event", {
8462
- role: "event",
8463
- value: eventTokens.join(" ")
8464
- });
8465
- }
8466
- if (tokens[startIndex] && tokens[startIndex].toLowerCase() === "from" && tokens[startIndex + 1]) {
8467
- startIndex++;
8468
- const sourceValue = [];
8469
- while (tokens[startIndex]) {
8470
- if (ENGLISH_COMMANDS.has(tokens[startIndex].toLowerCase())) break;
8471
- sourceValue.push(tokens[startIndex]);
8472
- startIndex++;
8473
- }
8474
- if (sourceValue.length > 0) {
8475
- const value = sourceValue.join(" ");
8476
- roles.set("source", {
8477
- role: "source",
8478
- value,
8479
- isSelector: /^[#.<@]/.test(value)
8480
- });
8481
- }
8482
- }
8483
- if (tokens[startIndex]) {
8484
- roles.set("action", {
8485
- role: "action",
8486
- value: tokens[startIndex]
8487
- });
8488
- startIndex++;
8489
- }
8490
- if (tokens[startIndex]) {
8491
- const modifierMap = buildArgumentModifierMap(profile, roles.get("action")?.value);
8492
- let currentRole = "patient";
8493
- let currentValue = [];
8494
- for (let i = startIndex; i < tokens.length; i++) {
8495
- const token = tokens[i];
8496
- const mappedRole = modifierMap[token.toLowerCase()];
8497
- if (mappedRole) {
8498
- if (currentValue.length > 0) {
8499
- const value = currentValue.join(" ");
8500
- roles.set(currentRole, {
8501
- role: currentRole,
8502
- value,
8503
- isSelector: /^[#.<@]/.test(value)
8504
- });
8505
- }
8506
- currentRole = mappedRole;
8507
- currentValue = [];
8508
- } else {
8509
- currentValue.push(token);
8510
- }
8511
- }
8512
- if (currentValue.length > 0) {
8513
- const value = currentValue.join(" ");
8514
- roles.set(currentRole, {
8515
- role: currentRole,
8516
- value,
8517
- isSelector: /^[#.<@]/.test(value)
8518
- });
8519
- }
8520
- }
8521
- return {
8522
- type: "event-handler",
8523
- roles,
8524
- original: tokens.join(" ")
8525
- };
8526
- }
8527
- function parseCommand(tokens, profile) {
8528
- const roles = /* @__PURE__ */ new Map();
8529
- if (tokens.length === 0) {
8530
- return { type: "command", roles, original: "" };
8531
- }
8532
- roles.set("action", {
8533
- role: "action",
8534
- value: tokens[0]
8535
- });
8536
- const modifierMap = buildArgumentModifierMap(profile, tokens[0]);
8537
- let currentRole = "patient";
8538
- let currentValue = [];
8539
- for (let i = 1; i < tokens.length; i++) {
8540
- const token = tokens[i];
8541
- const mappedRole = modifierMap[token.toLowerCase()];
8542
- if (mappedRole) {
8543
- if (currentValue.length > 0) {
8544
- const value = currentValue.join(" ");
8545
- roles.set(currentRole, {
8546
- role: currentRole,
8547
- value,
8548
- isSelector: /^[#.<@]/.test(value)
8549
- });
8550
- }
8551
- currentRole = mappedRole;
8552
- currentValue = [];
8553
- } else {
8554
- currentValue.push(token);
8555
- }
8556
- }
8557
- if (currentValue.length > 0) {
8558
- const value = currentValue.join(" ");
8559
- roles.set(currentRole, {
8560
- role: currentRole,
8561
- value,
8562
- isSelector: /^[#.<@]/.test(value)
8563
- });
8564
- }
8565
- return {
8566
- type: "command",
8567
- roles,
8568
- original: tokens.join(" ")
8569
- };
8570
- }
8571
- var LITERAL_PRIMARY_ROLES = /* @__PURE__ */ new Set([
8572
- "duration",
8573
- "quantity"
8574
- ]);
8575
- function applyPrimaryRole(parsed, targetProfile) {
8576
- if (parsed.type !== "command") return;
8577
- const action = parsed.roles.get("action")?.value;
8578
- if (!action) return;
8579
- const primaryRole = COMMAND_PRIMARY_ROLES[action.toLowerCase()];
8580
- if (!primaryRole || !LITERAL_PRIMARY_ROLES.has(primaryRole)) return;
8581
- const patientEl = parsed.roles.get("patient");
8582
- if (!patientEl || parsed.roles.has(primaryRole)) return;
8583
- if (targetProfile.markers.some((m) => m.role === primaryRole)) return;
8584
- parsed.roles.delete("patient");
8585
- parsed.roles.set(primaryRole, { ...patientEl, role: primaryRole });
8586
- }
8587
- function parseConditional(tokens, _profile) {
8588
- const roles = /* @__PURE__ */ new Map();
8589
- roles.set("action", {
8590
- role: "action",
8591
- value: tokens[0]
8592
- });
8593
- const thenIndex = tokens.findIndex((t) => THEN_KEYWORDS.has(t.toLowerCase()));
8594
- if (thenIndex > 1) {
8595
- const conditionValue = tokens.slice(1, thenIndex).join(" ");
8596
- roles.set("condition", {
8597
- role: "condition",
8598
- value: conditionValue
8599
- });
8600
- } else if (thenIndex === -1 && tokens.length > 1) {
8601
- roles.set("condition", {
8602
- role: "condition",
8603
- value: tokens.slice(1).join(" ")
8604
- });
8605
- }
8606
- return {
8607
- type: "conditional",
8608
- roles,
8609
- original: tokens.join(" ")
8610
- };
8611
- }
8612
- function translateWord(word, sourceLocale, targetLocale) {
8613
- if (/^[#.<@]/.test(word)) {
8614
- return word;
8615
- }
8616
- if (/^\d+/.test(word)) {
8617
- return word;
8618
- }
8619
- if (/\s/.test(word) && word.startsWith("(")) {
8620
- return word.split(/\s+/).map((w) => translateWord(w, sourceLocale, targetLocale)).join(" ");
8621
- }
8622
- if (word.length > 1 && (word.startsWith("(") || word.endsWith(")"))) {
8623
- const m = word.match(/^(\(*)([^()]+)(\)*)$/);
8624
- if (m && (m[1] || m[3])) {
8625
- return m[1] + translateWord(m[2], sourceLocale, targetLocale) + m[3];
8626
- }
8627
- }
8628
- const sourceDict = sourceLocale === "en" ? null : dictionaries[sourceLocale];
8629
- const targetDict = dictionaries[targetLocale];
8630
- if (!targetDict) return word;
8631
- let englishWord = word;
8632
- if (sourceDict) {
8633
- const found = findInDictionary(sourceDict, word);
8634
- if (found) {
8635
- englishWord = found.englishKey;
8636
- }
8637
- }
8638
- const translated = translateFromEnglish(targetDict, englishWord);
8639
- return translated ?? word;
8640
- }
8641
- var POSSESSIVE_MARKERS = {
8642
- en: { type: "suffix", marker: "'s" },
8643
- es: { type: "preposition", marker: "de" },
8644
- pt: { type: "preposition", marker: "de" },
8645
- fr: { type: "preposition", marker: "de" },
8646
- de: { type: "preposition", marker: "von" },
8647
- ja: { type: "suffix", marker: "\u306E" },
8648
- ko: { type: "suffix", marker: "\uC758" },
8649
- zh: { type: "suffix", marker: "\u7684" },
8650
- ar: { type: "preposition", marker: "\u0644\u0640" },
8651
- // Spaced genitive particle (not the glued `'ın`), so the tokenizer can split
8652
- // it off the selector — consistent with Turkish's other spaced case markers.
8653
- tr: { type: "particle", marker: "\u0131n" },
8654
- id: { type: "preposition", marker: "dari" },
8655
- // Latin-script genitive: must be a *spaced* particle (`#picker pa`), since a
8656
- // glued `#pickerpa` can't be split from the selector by the tokenizer the
8657
- // way a non-Latin suffix (の/의/র) can.
8658
- qu: { type: "particle", marker: "pa" },
8659
- // Bengali SOV postposition genitive, like ja/ko — a spaced suffix the
8660
- // tokenizer splits off as a particle. Previously absent, so it fell back to
8661
- // the English `'s` marker and its possessive property paths never parsed.
8662
- // (Hindi `का` is intentionally omitted: its `bind` lacks a verb-final
8663
- // grammar rule, so fixing its possessive alone yields a wrong `on` parse —
8664
- // tracked as separate follow-up.)
8665
- bn: { type: "suffix", marker: "\u09B0" },
8666
- sw: { type: "preposition", marker: "ya" }
8667
- };
8668
- function translatePossessive(token, sourceLocale, targetLocale) {
8669
- const possessiveMatch = token.match(/^(.+)'s$/i);
8670
- if (!possessiveMatch) {
8671
- return token;
8672
- }
8673
- const owner = possessiveMatch[1];
8674
- const targetMarker = POSSESSIVE_MARKERS[targetLocale] || POSSESSIVE_MARKERS.en;
8675
- const pronounPossessives = {
8676
- me: "my",
8677
- it: "its",
8678
- you: "your"
8679
- };
8680
- const lowerOwner = owner.toLowerCase();
8681
- if (pronounPossessives[lowerOwner]) {
8682
- const possessiveForm = pronounPossessives[lowerOwner];
8683
- return translateWord(possessiveForm, "en", targetLocale);
8684
- }
8685
- const translatedOwner = translateWord(owner, sourceLocale, targetLocale);
8686
- switch (targetMarker.type) {
8687
- case "suffix":
8688
- return `${translatedOwner}${targetMarker.marker}`;
8689
- case "particle":
8690
- return `${translatedOwner} ${targetMarker.marker}`;
8691
- case "preposition":
8692
- return `__POSS__${targetMarker.marker}__${translatedOwner}__POSS__`;
8693
- default:
8694
- return `${translatedOwner}'s`;
8695
- }
8696
- }
8697
- var POSSESSIVE_DOT_REGEX = /^(my|its|your|me|it|you)(\??\..+)$/i;
8698
- var POSSESSIVE_DOT_PRONOUNS = {
8699
- me: "my",
8700
- it: "its",
8701
- you: "your",
8702
- my: "my",
8703
- its: "its",
8704
- your: "your"
8705
- };
8706
- function translatePossessiveDotNotation(value, sourceLocale, targetLocale) {
8707
- const match = value.match(POSSESSIVE_DOT_REGEX);
8708
- if (!match) return null;
8709
- const possessiveWord = match[1].toLowerCase();
8710
- const propertySuffix = match[2];
8711
- const possessiveKey = POSSESSIVE_DOT_PRONOUNS[possessiveWord] || possessiveWord;
8712
- const translated = translateWord(possessiveKey, sourceLocale, targetLocale);
8713
- if (translated.includes(" ")) return null;
8714
- if (translated !== possessiveKey) {
8715
- return translated + propertySuffix;
8716
- }
8717
- if (possessiveWord !== possessiveKey) {
8718
- const alt = translateWord(possessiveWord, sourceLocale, targetLocale);
8719
- if (alt !== possessiveWord && !alt.includes(" ")) {
8720
- return alt + propertySuffix;
8721
- }
8722
- }
8723
- return null;
8724
- }
8725
- function translateMultiWordValue(value, sourceLocale, targetLocale) {
8726
- if (value.includes("[")) {
8727
- const guards = [];
8728
- const masked = value.replace(/\[[^\]]*\]/g, (match) => {
8729
- guards.push(match);
8730
- return `\uE000${guards.length - 1}\uE001`;
8731
- });
8732
- if (guards.length > 0) {
8733
- const translated2 = translateMultiWordValue(masked, sourceLocale, targetLocale);
8734
- return translated2.replace(/(\d+)/g, (_, n) => guards[Number(n)]);
8735
- }
8736
- }
8737
- if (!value.includes(" ")) {
8738
- if (value.includes("'s")) {
8739
- return translatePossessive(value, sourceLocale, targetLocale);
8740
- }
8741
- const dotResult = translatePossessiveDotNotation(value, sourceLocale, targetLocale);
8742
- if (dotResult !== null) return dotResult;
8743
- return translateWord(value, sourceLocale, targetLocale);
8744
- }
8745
- const words = value.split(/\s+/);
8746
- const translated = [];
8747
- let i = 0;
8748
- while (i < words.length) {
8749
- const word = words[i];
8750
- if (word.includes("'s")) {
8751
- const possessiveResult = translatePossessive(word, sourceLocale, targetLocale);
8752
- const prepMatch = possessiveResult.match(/^__POSS__(.+)__(.+)__POSS__$/);
8753
- if (prepMatch && i + 1 < words.length) {
8754
- const marker = prepMatch[1];
8755
- const owner = prepMatch[2];
8756
- const property = words[i + 1];
8757
- const translatedProperty = translateWord(property, sourceLocale, targetLocale);
8758
- translated.push(`${translatedProperty} ${marker} ${owner}`);
8759
- i += 2;
8760
- continue;
8761
- } else if (prepMatch) {
8762
- const marker = prepMatch[1];
8763
- const owner = prepMatch[2];
8764
- translated.push(`${marker} ${owner}`);
8765
- i++;
8766
- continue;
8767
- }
8768
- translated.push(possessiveResult);
8769
- i++;
8770
- continue;
8771
- }
8772
- if (/^[#.<@]/.test(word) || /^\d+/.test(word)) {
8773
- translated.push(word);
8774
- i++;
8775
- continue;
8776
- }
8777
- if (/^["'].*["']$/.test(word)) {
8778
- translated.push(word);
8779
- i++;
8780
- continue;
8781
- }
8782
- const dotResult = translatePossessiveDotNotation(word, sourceLocale, targetLocale);
8783
- if (dotResult !== null) {
8784
- translated.push(dotResult);
8785
- i++;
8786
- continue;
8787
- }
8788
- translated.push(translateWord(word, sourceLocale, targetLocale));
8789
- i++;
8790
- }
8791
- return translated.join(" ");
8792
- }
8793
- function translateElements(parsed, sourceLocale, targetLocale) {
8794
- for (const [_role, element] of parsed.roles) {
8795
- if (element.value.includes("'s")) {
8796
- element.translated = translateMultiWordValue(element.value, sourceLocale, targetLocale);
8797
- } else if (!element.isSelector && !element.isLiteral) {
8798
- element.translated = translateMultiWordValue(element.value, sourceLocale, targetLocale);
8799
- } else {
8800
- element.translated = element.value;
8801
- }
8802
- }
8803
- }
8804
- var CARET_SCOPE_OPEN = "\uE000";
8805
- var CARET_SCOPE_CLOSE = "\uE001";
8806
- var CARET_SCOPE_RE = /(\^[A-Za-z_][\w-]*)(\s+on\s+(?:[#.][\w-]+|<[^>]*\/>|\[[^\]]+\]))/g;
8807
- function maskCaretScopes(input) {
8808
- const scopes = [];
8809
- const masked = input.replace(CARET_SCOPE_RE, (_m, varTok, scope) => {
8810
- const idx = scopes.length;
8811
- scopes.push(scope);
8812
- return `${varTok}${CARET_SCOPE_OPEN}${idx}${CARET_SCOPE_CLOSE}`;
8813
- });
8814
- return scopes.length > 0 ? { masked, scopes } : null;
8815
- }
8816
- function restoreCaretScopes(input, scopes) {
8817
- return input.replace(
8818
- new RegExp(`${CARET_SCOPE_OPEN}(\\d+)${CARET_SCOPE_CLOSE}`, "g"),
8819
- (_m, n) => scopes[Number(n)] ?? ""
8820
- );
8821
- }
8822
- var VIEW_TAIL_OPEN = "\uE002";
8823
- var VIEW_TAIL_CLOSE = "\uE003";
8824
- var VIEW_TAIL_RE = /\busing\s+view\b(?:\s+(?!then\b)[A-Za-z][\w-]*)?/gi;
8825
- var VIEW_TAIL_TOKEN_RE = new RegExp(`^${VIEW_TAIL_OPEN}(\\d+)${VIEW_TAIL_CLOSE}$`);
8826
- function maskViewTransitionTails(input) {
8827
- const tails = [];
8828
- const masked = input.replace(VIEW_TAIL_RE, (match) => {
8829
- const idx = tails.length;
8830
- tails.push(match);
8831
- return `${VIEW_TAIL_OPEN}${idx}${VIEW_TAIL_CLOSE}`;
8832
- });
8833
- return tails.length > 0 ? { masked, tails } : null;
8834
- }
8835
- function restoreViewTransitionTails(input, tails) {
8836
- return input.replace(
8837
- new RegExp(`${VIEW_TAIL_OPEN}(\\d+)${VIEW_TAIL_CLOSE}`, "g"),
8838
- (_m, n) => tails[Number(n)] ?? ""
8839
- );
8840
- }
8841
- var GrammarTransformer = class {
8842
- constructor(sourceLocale = "en", targetLocale) {
8843
- const source = getProfile(sourceLocale);
8844
- const target = getProfile(targetLocale);
8845
- if (!source) throw new Error(`Unknown source locale: ${sourceLocale}`);
8846
- if (!target) throw new Error(`Unknown target locale: ${targetLocale}`);
8847
- this.sourceProfile = source;
8848
- this.targetProfile = target;
8849
- }
8850
- /**
8851
- * Transform a hyperscript statement from source to target language.
8852
- * Handles compound statements with "then" by splitting, transforming each part,
8853
- * and rejoining with the target language's "then" keyword.
8854
- *
8855
- * For multi-line input, preserves line structure (indentation, blank lines).
8856
- */
8857
- transform(input) {
8858
- const out = this.transformInternal(input);
8859
- return this.targetProfile.code === "he" ? repairHebrewFrontedAccusative(out) : out;
8860
- }
8861
- transformInternal(input) {
8862
- const viewTails = maskViewTransitionTails(input);
8863
- if (viewTails) {
8864
- return restoreViewTransitionTails(this.transformInternal(viewTails.masked), viewTails.tails);
8865
- }
8866
- const caret = maskCaretScopes(input);
8867
- if (caret) {
8868
- return restoreCaretScopes(this.transform(caret.masked), caret.scopes);
8869
- }
8870
- const targetThen = getTargetThenKeyword(this.targetProfile.code);
8871
- if (!input.includes("\n")) {
8872
- const jsBlock = this.tryTransformJsBlock(input);
8873
- if (jsBlock !== null) return jsBlock;
8874
- const eventModifier = this.tryTransformEventWithModifierBody(input);
8875
- if (eventModifier !== null) return eventModifier;
8876
- const eventBlock = this.tryTransformEventWithBlockBody(input);
8877
- if (eventBlock !== null) return eventBlock;
8878
- const eventGuard = this.tryTransformEventWithUnlessGuard(input);
8879
- if (eventGuard !== null) return eventGuard;
8880
- }
8881
- const hasMultiLineStructure = input.includes("\n");
8882
- if (hasMultiLineStructure) {
8883
- const { parts: parts2, lineMetadata, partToLineIndex } = splitCompoundStatementWithMetadata(
8884
- input,
8885
- this.sourceProfile.code
8886
- );
8887
- const transformedParts = parts2.map((part) => this.transformSingle(part));
8888
- return reconstructWithLineStructure(
8889
- transformedParts,
8890
- lineMetadata,
8891
- partToLineIndex,
8892
- targetThen
8893
- );
8894
- }
8895
- const parts = splitCompoundStatement(input, this.sourceProfile.code);
8896
- if (parts.length > 1) {
8897
- const transformedParts = parts.map((part) => this.transformSingle(part));
8898
- return transformedParts.join(` ${targetThen} `);
8899
- }
8900
- return this.transformSingle(input);
8901
- }
8902
- /**
8903
- * Transform a single hyperscript statement (no compound "then" chains).
8904
- */
8905
- transformSingle(input) {
8906
- const block = extractBlockStructure(input, this.sourceProfile.code);
8907
- if (block) {
8908
- return this.transformBlock(block);
8909
- }
8910
- const strippedEnd = this.transformWithTrailingEnd(input);
8911
- if (strippedEnd !== null) {
8912
- return strippedEnd;
8913
- }
8914
- const setScope = this.transformSetWithScope(input);
8915
- if (setScope !== null) {
8916
- return setScope;
8917
- }
8918
- const viewTail = this.transformWithViewTransitionTail(input);
8919
- if (viewTail !== null) {
8920
- return viewTail;
8921
- }
8922
- const parsed = parseStatement(input, this.sourceProfile.code);
8923
- if (!parsed) {
8924
- return input;
8925
- }
8926
- applyPrimaryRole(parsed, this.targetProfile);
8927
- translateElements(parsed, this.sourceProfile.code, this.targetProfile.code);
8928
- const rule = this.findRule(parsed);
8929
- if (rule?.transform.custom) {
8930
- return rule.transform.custom(parsed, this.targetProfile);
8931
- }
8932
- const roleOrder = rule?.transform.roleOrder || this.targetProfile.canonicalOrder;
8933
- const reordered = reorderRoles(parsed.roles, roleOrder);
8934
- const shouldInsertMarkers = rule?.transform.insertMarkers ?? true;
8935
- if (shouldInsertMarkers) {
8936
- const result = insertMarkers(
8937
- reordered,
8938
- this.targetProfile.markers,
8939
- this.targetProfile.adpositionType
8940
- );
8941
- return joinTokens(result);
8942
- }
8943
- return joinTokens(reordered.map((e) => e.translated || e.value));
8944
- }
8945
- /**
8946
- * Clause carrying a masked `using view transition` tail: strip the opaque
8947
- * token, transform the clause alone, and re-append the token at the very end.
8948
- *
8949
- * The tail is a clause-final modifier in every word order the corpus emits:
8950
- * the semantic side matches it as the literal `using view` marker plus a value
8951
- * word, and the SOV/VSO event-handler patterns admit it as an optional
8952
- * TRAILING group (after the with-marked operand). So the target position is
8953
- * "end of the transformed clause" for all 24 languages — no per-profile
8954
- * placement decision, which is what makes this a passthrough rather than a
8955
- * role.
8956
- *
8957
- * Returns null when the clause carries no masked tail, or when the token is
8958
- * not clause-final (nothing to reposition — leaving it in place still restores
8959
- * verbatim English).
8960
- */
8961
- transformWithViewTransitionTail(input) {
8962
- const trimmed = input.trim();
8963
- const tokens = trimmed.split(/\s+/);
8964
- if (tokens.length < 2) {
8965
- return null;
8966
- }
8967
- if (!VIEW_TAIL_TOKEN_RE.test(tokens[tokens.length - 1])) {
8968
- return null;
8969
- }
8970
- const tail = tokens[tokens.length - 1];
8971
- const head = tokens.slice(0, -1).join(" ");
8972
- return `${this.transformSingle(head)} ${tail}`;
8973
- }
8974
- /**
8975
- * `<command …> end` fragments: transform the command without its stranded
8976
- * terminator, then re-append the translated terminator as a standalone
8977
- * trailing token. Fragments that open a block of their own (`if … end`,
8978
- * `repeat … end`, `js … end`) bail — their terminator belongs to them and
8979
- * their dedicated paths handle it.
8980
- */
8981
- transformWithTrailingEnd(input) {
8982
- const src = this.sourceProfile.code;
8983
- const tokens = input.trim().split(/\s+/);
8984
- if (tokens.length < 2) {
8985
- return null;
8986
- }
8987
- const sourceEnd = translateWord("end", "en", src).toLowerCase();
8988
- if (tokens[tokens.length - 1].toLowerCase() !== sourceEnd) {
8989
- return null;
8990
- }
8991
- const openers = new Set(
8992
- ["if", "repeat", "unless", "while", "when", "live", "js"].map(
8993
- (k) => translateWord(k, "en", src).toLowerCase()
8994
- )
8995
- );
8996
- if (tokens.slice(0, -1).some((t) => openers.has(t.toLowerCase()))) {
8997
- return null;
8998
- }
8999
- const inner = this.transformSingle(tokens.slice(0, -1).join(" "));
9000
- const endT = translateWord(tokens[tokens.length - 1], src, this.targetProfile.code);
9001
- return `${inner} ${endT}`;
9002
- }
9003
- /**
9004
- * Detect and transform an inline JS block (`[on <event>] js <raw js> end`).
9005
- *
9006
- * The `js ... end` body is raw JavaScript: it must not be tokenized,
9007
- * translated, or word-order reordered. We mask the whole block with a single
9008
- * opaque placeholder, run the surrounding statement (the event-handler head,
9009
- * if any) through the normal reorder pipeline so the placeholder lands in the
9010
- * correct action position, then substitute the translated `js`/`end` keywords
9011
- * around the verbatim body.
9012
- *
9013
- * Returns `null` (fall through to the normal path) when there is no js block,
9014
- * no matching `end`, or trailing content after `end` (kept tight on purpose).
9015
- */
9016
- tryTransformJsBlock(input) {
9017
- const src = this.sourceProfile.code;
9018
- const dst = this.targetProfile.code;
9019
- const sourceJs = translateWord("js", "en", src);
9020
- const sourceEnd = translateWord("end", "en", src).toLowerCase();
9021
- const tokens = input.split(/\s+/).filter((t) => t.length > 0);
9022
- const escapedJs = sourceJs.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9023
- const jsRe = new RegExp(`^${escapedJs}(\\(.*\\))?$`, "i");
9024
- const jsIdx = tokens.findIndex((t) => jsRe.test(t));
9025
- if (jsIdx === -1) return null;
9026
- let endIdx = -1;
9027
- for (let i = jsIdx + 1; i < tokens.length; i++) {
9028
- if (tokens[i].toLowerCase() === sourceEnd) {
9029
- endIdx = i;
9030
- break;
9031
- }
9032
- }
9033
- if (endIdx === -1) return null;
9034
- if (endIdx !== tokens.length - 1) return null;
9035
- const jsToken = tokens[jsIdx];
9036
- const jsParen = jsToken.match(jsRe)?.[1] ?? "";
9037
- const jsKeywordRaw = jsParen ? jsToken.slice(0, jsToken.length - jsParen.length) : jsToken;
9038
- const body = tokens.slice(jsIdx + 1, endIdx).join(" ");
9039
- const targetJs = translateWord(jsKeywordRaw, src, dst) + jsParen;
9040
- const targetEnd = translateWord(tokens[endIdx], src, dst);
9041
- const replacement = [targetJs, body, targetEnd].filter((s) => s.length > 0).join(" ");
9042
- const before = tokens.slice(0, jsIdx);
9043
- if (before.length === 0) return replacement;
9044
- const placeholder = "JSBLOCKPLACEHOLDER";
9045
- const reordered = this.transformSingle([...before, placeholder].join(" "));
9046
- if (!reordered.includes(placeholder)) return null;
9047
- return reordered.replace(placeholder, replacement);
9048
- }
9049
- /**
9050
- * Transform an event handler whose body is a block command
9051
- * (`on <event> [from <src>] {if|repeat|unless|while|for} … end`).
9052
- *
9053
- * `parseEventHandler` would treat the block keyword as the action and sweep the
9054
- * condition/body into role values, then reorder them — shredding the block
9055
- * (`if event.shiftKey call submitAndContinue() end` → scattered tokens). Instead
9056
- * we mask the whole block as an opaque action placeholder, reorder the event
9057
- * head normally, transform the block as a self-contained unit, and restitch.
9058
- *
9059
- * Returns `null` (fall through) when the input isn't an event handler, has no
9060
- * block-keyword body, or has no closing `end`.
9061
- */
9062
- tryTransformEventWithBlockBody(input) {
9063
- const tokens = tokenize(input, this.sourceProfile);
9064
- if (tokens.length === 0) return null;
9065
- if (!EVENT_KEYWORDS.has(tokens[0]?.toLowerCase())) return null;
9066
- let blockIdx = -1;
9067
- for (let i = 1; i < tokens.length; i++) {
9068
- if (BLOCK_BODY_KEYWORDS.has(tokens[i].toLowerCase())) {
9069
- blockIdx = i;
9070
- break;
9071
- }
9072
- }
9073
- if (blockIdx <= 0) return null;
9074
- if (tokens[tokens.length - 1].toLowerCase() !== "end") return null;
9075
- const eventHead = tokens.slice(0, blockIdx);
9076
- const blockTokens = tokens.slice(blockIdx);
9077
- if (this.targetProfile.wordOrder === "VSO" && eventHead.some((t) => t.toLowerCase() === "from")) {
9078
- return null;
9079
- }
9080
- const placeholder = "EVENTBLOCKPLACEHOLDER";
9081
- const headOut = this.transformSingle([...eventHead, placeholder].join(" "));
9082
- if (!headOut.includes(placeholder)) return null;
9083
- const blockOut = this.transformBlockBody(blockTokens);
9084
- const eventClause = headOut.replace(placeholder, "").replace(/\s+/g, " ").trim();
9085
- return [eventClause, blockOut].filter((s) => s.length > 0).join(" ");
9086
- }
9087
- /**
9088
- * Transform an event handler whose body is an inline `unless` guard with NO
9089
- * `end` (`on <event> unless <cond> <body>` — the `unless-condition` shape).
9090
- *
9091
- * Object-marking SVO targets (he, zh). `parseEventHandler` reads `unless` as the
9092
- * action and sweeps the whole `<cond> <body>` tail into a single `patient` blob;
9093
- * the target then prefixes that blob with its object marker — Hebrew's accusative
9094
- * את (`… אלא את I match .disabled מתג .selected`) or Chinese's BA particle 把
9095
- * (`… 除非 把 I match .disabled 切换 .selected`) — and the inner toggle loses its
9096
- * own marker. The semantic parser can't recover the guard from that: the marker
9097
- * ahead of the condition blocks the `unless` pattern AND the now-markerless body
9098
- * command fails its object-marked toggle pattern, so the body collapses (`unless`
9099
- * dropped). Marker-less languages (de/it/ar/pl) tolerate the same role-blob and
9100
- * stay faithful, so this is an object-marker artifact, not a general parse gap.
9101
- *
9102
- * The standalone `unless <cond> <body>` path already produces the correct shape
9103
- * (`extractBlockStructure` → `transformBlock`: condition kept marker-free, body
9104
- * command keeps its marker — he `אלא I match .disabled מתג את .selected`, zh
9105
- * `除非 I match .disabled 切换 把 .selected`). So we split the event head off,
9106
- * transform the guard through that path, and emit the event clause first (he and
9107
- * zh are both SVO — event leads). Returns `null` (fall through) when the input
9108
- * isn't an object-marking event handler with an un-terminated inline `unless`
9109
- * guard.
9110
- */
9111
- tryTransformEventWithUnlessGuard(input) {
9112
- if (!UNLESS_GUARD_OBJECT_MARKING_LOCALES.has(this.targetProfile.code)) return null;
9113
- const tokens = tokenize(input, this.sourceProfile);
9114
- if (tokens.length === 0) return null;
9115
- if (!EVENT_KEYWORDS.has(tokens[0]?.toLowerCase())) return null;
9116
- let guardIdx = -1;
9117
- for (let i = 1; i < tokens.length; i++) {
9118
- if (tokens[i].toLowerCase() === "unless") {
9119
- guardIdx = i;
9120
- break;
9121
- }
9122
- }
9123
- if (guardIdx <= 0) return null;
9124
- if (tokens[tokens.length - 1].toLowerCase() === "end") return null;
9125
- const eventHead = tokens.slice(0, guardIdx);
9126
- const guard = tokens.slice(guardIdx).join(" ");
9127
- const guardOut = this.transform(guard);
9128
- if (!guardOut) return null;
9129
- const placeholder = "EVENTGUARDPLACEHOLDER";
9130
- const headOut = this.transformSingle([...eventHead, placeholder].join(" "));
9131
- if (!headOut.includes(placeholder)) return null;
9132
- const eventClause = headOut.replace(placeholder, "").replace(/\s+/g, " ").trim();
9133
- return [eventClause, guardOut].filter((s) => s.length > 0).join(" ");
9134
- }
9135
- /**
9136
- * Transform an event handler whose body leads with a command-modifier
9137
- * (`on <event> [from <src>] {async|once|debounced [at N]|throttled [at N]} <body>`).
9138
- *
9139
- * `parseEventHandler` reads the first token after the event as the **action**, so
9140
- * a leading modifier is mistaken for the verb and the real verb (`fetch`/`add`) is
9141
- * swept into the patient. For SOV targets the reorder then surfaces that verb
9142
- * **first** (`取得 /api/data を クリック …`), and the semantic parser matches the
9143
- * leading `<verb> <patient>` with the low-priority `*-generated-verb-first`
9144
- * command pattern — returning a bare command and discarding the event + the rest
9145
- * of the body (degenerate parse).
9146
- *
9147
- * Instead, lift the modifier out, transform the modifier-free handler through the
9148
- * normal path (which keeps the body in canonical patient-first SOV order so the
9149
- * event sits mid-stream and the existing SOV event-extraction recovers it), then
9150
- * re-emit the modifier as a **leading English literal**. The semantic parser
9151
- * strips a leading `once`/`debounced`/`throttled` (`extractStandaloneModifiers`)
9152
- * and an `async` anywhere (`stripAsyncModifier`) before parsing, so the modifier
9153
- * is consumed as handler metadata rather than shadowing the body.
9154
- *
9155
- * Returns `null` (fall through) when the input isn't an event handler or the body
9156
- * doesn't lead with a modifier — leaving simple/Mode-B handlers byte-identical.
9157
- */
9158
- tryTransformEventWithModifierBody(input) {
9159
- if (this.targetProfile.wordOrder !== "SOV") return null;
9160
- const tokens = tokenize(input, this.sourceProfile);
9161
- if (tokens.length === 0) return null;
9162
- if (!EVENT_KEYWORDS.has(tokens[0]?.toLowerCase())) return null;
9163
- let i = 1;
9164
- if (!tokens[i]) return null;
9165
- i++;
9166
- while (tokens[i] && EVENT_CONJUNCTIONS.has(tokens[i].toLowerCase()) && tokens[i + 1]) {
9167
- i += 2;
9168
- }
9169
- if (tokens[i]?.toLowerCase() === "from" && tokens[i + 1]) {
9170
- i++;
9171
- while (tokens[i] && !ENGLISH_COMMANDS.has(tokens[i].toLowerCase()) && !BODY_MODIFIER_KEYWORDS.has(tokens[i].toLowerCase())) {
9172
- i++;
9173
- }
9174
- }
9175
- const modWord = tokens[i]?.toLowerCase();
9176
- if (!modWord || !BODY_MODIFIER_KEYWORDS.has(modWord)) return null;
9177
- const modStart = i;
9178
- let modEnd = i + 1;
9179
- if (modWord !== "async" && modWord !== "once") {
9180
- if (tokens[modEnd]?.toLowerCase() === "at") modEnd++;
9181
- if (tokens[modEnd] && /^\d+(ms|s|m)?$/.test(tokens[modEnd])) modEnd++;
9182
- }
9183
- const modifierPhrase = tokens.slice(modStart, modEnd).join(" ");
9184
- const rebuilt = [...tokens.slice(0, modStart), ...tokens.slice(modEnd)].join(" ");
9185
- if (tokens.length - (modEnd - modStart) <= 2) return null;
9186
- const bodyOut = this.transform(rebuilt);
9187
- return [modifierPhrase, bodyOut].filter((s) => s.length > 0).join(" ");
9188
- }
9189
- /**
9190
- * Transform a `set <stuff> on <scope>` clause (S1 tabs-aria). The trailing
9191
- * `on <scope>` is the element(s) the attribute is set on — kept attached by
9192
- * splitOnCommandBoundaries. The semantic parser captures it as a `scope` role
9193
- * via the passthrough literal `on` (setSchema's scope markerOverride is `on`
9194
- * in every language), so `on` is emitted verbatim and only the scope *value*
9195
- * is translated (selectors pass through; `me`/`it`/`you` translate to the
9196
- * native reference, which the parser also accepts).
9197
- *
9198
- * Positioning matches where the set patterns expect the scope: at the clause
9199
- * end for verb-first orders (SVO/VSO), and immediately before the clause-final
9200
- * verb for SOV (the generated SOV pattern is `{dest} {patient} on {scope}
9201
- * {verb}`). Returns null (fall through) when there is no trailing `on <scope>`.
9202
- *
9203
- * Source is English in the sync-translations pipeline, so the `set` verb and
9204
- * `on` marker are matched as English literals.
9205
- */
9206
- transformSetWithScope(input) {
9207
- const src = this.sourceProfile.code;
9208
- const dst = this.targetProfile.code;
9209
- const m = input.match(/^(.*\bset\b.*\S)\s+on\s+([#.<@[]\S*|me|it|you)\s*$/i);
9210
- if (!m) return null;
9211
- const head = m[1];
9212
- const scopeRaw = m[2];
9213
- const headOut = this.transformSingle(head);
9214
- const scopeT = /^[#.<@[]/.test(scopeRaw) ? scopeRaw : translateWord(scopeRaw, src, dst);
9215
- if (this.targetProfile.wordOrder === "SOV") {
9216
- const verb = translateWord("set", "en", dst);
9217
- const firstTok = input.trim().split(/\s+/)[0]?.toLowerCase();
9218
- const isEventHandler = !!firstTok && EVENT_KEYWORDS.has(firstTok);
9219
- const toks = headOut.split(/\s+/).filter(Boolean);
9220
- if (!isEventHandler) {
9221
- const vIdx = toks.indexOf(verb);
9222
- if (vIdx >= 0) {
9223
- toks.splice(vIdx, 1);
9224
- toks.push("on", scopeT, verb);
9225
- return toks.join(" ");
9226
- }
9227
- } else if (toks.length > 0 && toks[toks.length - 1] === verb) {
9228
- toks.splice(toks.length - 1, 0, "on", scopeT);
9229
- return toks.join(" ");
9230
- }
9231
- return `${headOut} on ${scopeT}`;
9232
- }
9233
- return `${headOut} on ${scopeT}`;
9234
- }
9235
- /**
9236
- * Transform a self-contained block command (`{head} {clause?} {body} {end}`),
9237
- * where head ∈ {if, repeat, unless, …}. The clause (condition / `until event …`)
9238
- * runs up to the first command verb and is translated word-by-word; the body is
9239
- * recursively transformed (so its inner commands reorder for the target); the
9240
- * head/tail keywords are translated. The block is never word-order reordered as
9241
- * a whole — delimiters stay at the edges regardless of target word order.
9242
- */
9243
- transformBlockBody(blockTokens) {
9244
- const src = this.sourceProfile.code;
9245
- const dst = this.targetProfile.code;
9246
- const head = blockTokens[0];
9247
- const hasEnd = blockTokens[blockTokens.length - 1]?.toLowerCase() === "end";
9248
- const tail = hasEnd ? blockTokens[blockTokens.length - 1] : "";
9249
- const inner = blockTokens.slice(1, hasEnd ? -1 : void 0);
9250
- const commands = getCommandKeywordsForLocale(src);
9251
- const copulas = getCopulasForLocale(src);
9252
- let bodyStart = inner.findIndex(
9253
- (t, i) => commands.has(t.toLowerCase()) && !isPredicateAdjectivePosition(inner, i, copulas)
9254
- );
9255
- if (bodyStart < 0) bodyStart = inner.length;
9256
- const clause = inner.slice(0, bodyStart).join(" ");
9257
- const bodyTokens = inner.slice(bodyStart);
9258
- const headT = translateWord(head, src, dst);
9259
- const tailT = tail ? translateWord(tail, src, dst) : "";
9260
- const clauseT = clause ? translateMultiWordValue(clause, src, dst) : "";
9261
- const bodyT = this.transformConditionalBody(bodyTokens);
9262
- const POSITIONAL_BRANCH_HEADS = /* @__PURE__ */ new Set(["first", "last", "next", "previous", "closest"]);
9263
- const thenT = this.targetProfile.wordOrder === "SOV" && clauseT && POSITIONAL_BRANCH_HEADS.has(bodyTokens[1]?.toLowerCase()) && inner[bodyStart - 1]?.toLowerCase() !== "then" ? translateWord("then", src, dst) : "";
9264
- return [headT, clauseT, thenT, bodyT, tailT].filter((s) => s.length > 0).join(" ");
9265
- }
9266
- /**
9267
- * Transform an `if`/`unless` block body, splitting it at a top-level `else` into
9268
- * a then-branch and an else-branch so each is reordered as a self-contained unit
9269
- * and the `else` keyword itself is translated. Without this, the body is reordered
9270
- * as one stream: `else` rides along glued to the preceding clause (and, when that
9271
- * clause begins with a selector, is marked a selector and left *untranslated*),
9272
- * and a spurious `then` is inserted around it — both of which break the target
9273
- * text and the downstream parse. The split is depth-aware so an `else` belonging
9274
- * to a nested block is not mistaken for this block's separator. Bodies without an
9275
- * `else` transform exactly as before.
9276
- */
9277
- transformConditionalBody(bodyTokens) {
9278
- const src = this.sourceProfile.code;
9279
- const dst = this.targetProfile.code;
9280
- const sourceElse = translateWord("else", "en", src).toLowerCase();
9281
- let depth = 0;
9282
- let elseIdx = -1;
9283
- for (let i = 0; i < bodyTokens.length; i++) {
9284
- const t = bodyTokens[i].toLowerCase();
9285
- if (BLOCK_BODY_KEYWORDS.has(t)) depth++;
9286
- else if (t === "end" && depth > 0) depth--;
9287
- else if (t === sourceElse && depth === 0) {
9288
- elseIdx = i;
9289
- break;
9290
- }
9291
- }
9292
- if (elseIdx === -1) {
9293
- const body = bodyTokens.join(" ");
9294
- return body ? this.transform(body) : "";
9295
- }
9296
- const thenBranch = bodyTokens.slice(0, elseIdx).join(" ");
9297
- const elseBranch = bodyTokens.slice(elseIdx + 1).join(" ");
9298
- const elseT = translateWord(bodyTokens[elseIdx], src, dst);
9299
- return [
9300
- thenBranch ? this.transform(thenBranch) : "",
9301
- elseT,
9302
- elseBranch ? this.transform(elseBranch) : ""
9303
- ].filter((s) => s.length > 0).join(" ");
9304
- }
9305
- /**
9306
- * Translate a reactive block by translating the head/tail/connector
9307
- * via the dictionary, recursively transforming the body through the
9308
- * regular pipeline, and rejoining in source-language position order.
9309
- * Block-syntactic tokens are never reordered: they're delimiters, not
9310
- * arguments, and authors expect them at start/end positions
9311
- * regardless of target word order.
9312
- */
9313
- transformBlock(block) {
9314
- const src = this.sourceProfile.code;
9315
- const dst = this.targetProfile.code;
9316
- const head = translateWord(block.headKeyword, src, dst);
9317
- const tail = block.tailKeyword ? translateWord(block.tailKeyword, src, dst) : "";
9318
- const connector = block.connector ? translateWord(block.connector, src, dst) : "";
9319
- const prefix = block.prefixExpr ? translateMultiWordValue(block.prefixExpr, src, dst) : "";
9320
- const body = this.transform(block.body);
9321
- return [head, prefix, connector, body, tail].filter((s) => s.length > 0).join(" ");
9322
- }
9323
- /**
9324
- * Find the best matching rule for this statement
9325
- */
9326
- findRule(parsed) {
9327
- if (!this.targetProfile.rules) return void 0;
9328
- const matchingRules = this.targetProfile.rules.filter((rule) => this.matchesRule(parsed, rule)).sort((a, b) => b.priority - a.priority);
9329
- return matchingRules[0];
9330
- }
9331
- /**
9332
- * Check if a parsed statement matches a rule
9333
- */
9334
- matchesRule(parsed, rule) {
9335
- const { match } = rule;
9336
- for (const role of match.requiredRoles) {
9337
- if (!parsed.roles.has(role)) {
9338
- return false;
9339
- }
9340
- }
9341
- if (match.commands && match.commands.length > 0) {
9342
- const action = parsed.roles.get("action");
9343
- if (!action) return false;
9344
- const actionValue = action.value.toLowerCase();
9345
- if (!match.commands.some((cmd) => cmd.toLowerCase() === actionValue)) {
9346
- return false;
9347
- }
9348
- }
9349
- if (match.predicate && !match.predicate(parsed)) {
9350
- return false;
9351
- }
9352
- return true;
9353
- }
9354
- };
9355
- function toLocale(input, targetLocale) {
9356
- const transformer = new GrammarTransformer("en", targetLocale);
9357
- return transformer.transform(input);
9358
- }
9359
- function toEnglish(input, sourceLocale) {
9360
- const transformer = new GrammarTransformer(sourceLocale, "en");
9361
- return transformer.transform(input);
9362
- }
9363
- function translate(input, sourceLocale, targetLocale) {
9364
- if (sourceLocale === targetLocale) return input;
9365
- if (sourceLocale === "en") return toLocale(input, targetLocale);
9366
- if (targetLocale === "en") return toEnglish(input, sourceLocale);
9367
- if (hasDirectMapping(sourceLocale, targetLocale)) {
9368
- return translateDirect(input, sourceLocale, targetLocale);
9369
- }
9370
- const english = toEnglish(input, sourceLocale);
9371
- return toLocale(english, targetLocale);
9372
- }
9373
- function translateDirect(input, sourceLocale, targetLocale) {
9374
- const mapping = getDirectMapping(sourceLocale, targetLocale);
9375
- if (!mapping) {
9376
- return toLocale(toEnglish(input, sourceLocale), targetLocale);
9377
- }
9378
- const tokens = input.split(/\s+/);
9379
- const translated = tokens.map((token) => {
9380
- if (token.startsWith("#") || token.startsWith(".") || token.startsWith("@")) {
9381
- return token;
9382
- }
9383
- if (token.startsWith('"') || token.startsWith("'")) {
9384
- return token;
9385
- }
9386
- const directTranslation = mapping.words[token];
9387
- if (directTranslation) {
9388
- return directTranslation;
9389
- }
9390
- const suffixMatch = token.match(/^(.+?)(-.+)$/);
9391
- if (suffixMatch) {
9392
- const [, base, suffix] = suffixMatch;
9393
- const translatedBase = mapping.words[base] || base;
9394
- return translatedBase + suffix;
9395
- }
9396
- return token;
9397
- });
9398
- return translated.join(" ");
9399
- }
9400
- var examples = {
9401
- english: {
9402
- eventHandler: "on click increment #count",
9403
- putInto: "put my value into #output",
9404
- toggle: "toggle .active",
9405
- wait: "wait 2 seconds"
9406
- },
9407
- // Expected outputs (approximate, for reference)
9408
- japanese: {
9409
- eventHandler: "#count \u3092 \u30AF\u30EA\u30C3\u30AF \u3067 \u5897\u52A0",
9410
- putInto: "\u79C1\u306E \u5024 \u3092 #output \u306B \u7F6E\u304F",
9411
- toggle: ".active \u3092 \u5207\u308A\u66FF\u3048",
9412
- wait: "2\u79D2 \u5F85\u3064"
9413
- },
9414
- chinese: {
9415
- eventHandler: "\u5F53 \u70B9\u51FB \u65F6 \u589E\u52A0 #count",
9416
- putInto: "\u628A \u6211\u7684\u503C \u653E \u5230 #output",
9417
- toggle: "\u5207\u6362 .active",
9418
- wait: "\u7B49\u5F85 2\u79D2"
9419
- },
9420
- arabic: {
9421
- eventHandler: "\u0632\u0650\u062F #count \u0639\u0646\u062F \u0627\u0644\u0646\u0642\u0631",
9422
- putInto: "\u0636\u0639 \u0642\u064A\u0645\u062A\u064A \u0641\u064A #output",
9423
- toggle: "\u0628\u062F\u0651\u0644 .active",
9424
- wait: "\u0627\u0646\u062A\u0638\u0631 \u062B\u0627\u0646\u064A\u062A\u064A\u0646"
9425
- }
9426
- };
9427
-
9428
7749
  exports.ENGLISH_COMMANDS = ENGLISH_COMMANDS;
9429
7750
  exports.ENGLISH_KEYWORDS = ENGLISH_KEYWORDS;
9430
- exports.GrammarTransformer = GrammarTransformer;
9431
7751
  exports.LANGUAGE_FAMILY_DEFAULTS = LANGUAGE_FAMILY_DEFAULTS;
9432
7752
  exports.LocaleManager = LocaleManager;
9433
7753
  exports.UNIVERSAL_ENGLISH_KEYWORDS = UNIVERSAL_ENGLISH_KEYWORDS;
@@ -9461,7 +7781,6 @@ exports.getDirectMapping = getDirectMapping;
9461
7781
  exports.getProfile = getProfile;
9462
7782
  exports.getSupportedDirectPairs = getSupportedDirectPairs;
9463
7783
  exports.getSupportedLocales = getSupportedLocales;
9464
- exports.grammarExamples = examples;
9465
7784
  exports.hasDirectMapping = hasDirectMapping;
9466
7785
  exports.he = he;
9467
7786
  exports.heDictionary = he;
@@ -9491,7 +7810,6 @@ exports.malayProfile = malayProfile;
9491
7810
  exports.ms = ms;
9492
7811
  exports.msDictionary = ms;
9493
7812
  exports.msKeywords = msKeywords;
9494
- exports.parseStatement = parseStatement;
9495
7813
  exports.pl = pl;
9496
7814
  exports.plDictionary = pl;
9497
7815
  exports.plKeywords = plKeywords;
@@ -9519,13 +7837,10 @@ exports.thKeywords = thKeywords;
9519
7837
  exports.tl = tl;
9520
7838
  exports.tlDictionary = tl;
9521
7839
  exports.tlKeywords = tlKeywords;
9522
- exports.toEnglish = toEnglish;
9523
- exports.toLocale = toLocale;
9524
7840
  exports.tr = tr;
9525
7841
  exports.trDictionary = tr;
9526
7842
  exports.trKeywords = trKeywords;
9527
7843
  exports.transformStatement = transformStatement;
9528
- exports.translate = translate;
9529
7844
  exports.translateWordDirect = translateWordDirect;
9530
7845
  exports.turkishProfile = turkishProfile;
9531
7846
  exports.ukDictionary = ukrainianDictionary;