@torpor/view 1.2.5 → 1.3.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 (44) hide show
  1. package/dist/{AsyncOptions-ClS1_ERX.d.mts → AsyncOptions-BDtArmeL.d.mts} +2 -8
  2. package/dist/AsyncOptions-BDtArmeL.d.mts.map +1 -0
  3. package/dist/{AsyncOptions-BtMe2PAd.d.cts → AsyncOptions-C_7mWR6F.d.cts} +2 -8
  4. package/dist/AsyncOptions-C_7mWR6F.d.cts.map +1 -0
  5. package/dist/{Effect-DazmAdyC.d.mts → Effect-99HYQdzZ.d.mts} +50 -33
  6. package/dist/Effect-99HYQdzZ.d.mts.map +1 -0
  7. package/dist/{Effect-Dewn7MLc.d.cts → Effect-Bf8fz_zC.d.cts} +50 -33
  8. package/dist/Effect-Bf8fz_zC.d.cts.map +1 -0
  9. package/dist/compile.cjs +1509 -120
  10. package/dist/compile.d.cts +268 -1
  11. package/dist/compile.d.cts.map +1 -1
  12. package/dist/compile.d.mts +268 -1
  13. package/dist/compile.d.mts.map +1 -1
  14. package/dist/compile.mjs +1506 -121
  15. package/dist/compile.mjs.map +1 -1
  16. package/dist/dev.d.cts +1 -1
  17. package/dist/dev.d.mts +1 -1
  18. package/dist/{fromWebSocket-DrN-IduP.cjs → fromWebSocket-Cdoghvmh.cjs} +15 -0
  19. package/dist/{fromWebSocket-CFGoMkV2.mjs → fromWebSocket-ERhd9KZR.mjs} +11 -2
  20. package/dist/fromWebSocket-ERhd9KZR.mjs.map +1 -0
  21. package/dist/index.cjs +223 -158
  22. package/dist/index.d.cts +24 -8
  23. package/dist/index.d.cts.map +1 -1
  24. package/dist/index.d.mts +24 -8
  25. package/dist/index.d.mts.map +1 -1
  26. package/dist/index.mjs +223 -158
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/runtime.iife.js +1 -0
  29. package/dist/slotAutoClose-BbKfzpkz.cjs +177 -0
  30. package/dist/slotAutoClose-CgDkf8fM.mjs +156 -0
  31. package/dist/slotAutoClose-CgDkf8fM.mjs.map +1 -0
  32. package/dist/ssr.cjs +57 -3
  33. package/dist/ssr.d.cts +53 -2
  34. package/dist/ssr.d.cts.map +1 -1
  35. package/dist/ssr.d.mts +53 -2
  36. package/dist/ssr.d.mts.map +1 -1
  37. package/dist/ssr.mjs +51 -2
  38. package/dist/ssr.mjs.map +1 -1
  39. package/package.json +8 -5
  40. package/dist/AsyncOptions-BtMe2PAd.d.cts.map +0 -1
  41. package/dist/AsyncOptions-ClS1_ERX.d.mts.map +0 -1
  42. package/dist/Effect-DazmAdyC.d.mts.map +0 -1
  43. package/dist/Effect-Dewn7MLc.d.cts.map +0 -1
  44. package/dist/fromWebSocket-CFGoMkV2.mjs.map +0 -1
package/dist/compile.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_slotAutoClose = require("./slotAutoClose-BbKfzpkz.cjs");
2
3
  //#region src/compile/utils/endOfString.ts
3
4
  function endOfString(char, content, start) {
4
5
  for (let j = start + 1; j < content.length; j++) if (content[j] === char && content[j - 1] !== "\\") return j;
@@ -349,6 +350,114 @@ function nodeRendersComponent(node) {
349
350
  return false;
350
351
  }
351
352
  //#endregion
353
+ //#region src/compile/utils/stalePropLets.ts
354
+ /**
355
+ * Detects the "plain `let` initialized from `$props`, read from markup"
356
+ * stale-capture trap. A component instantiated from a keyed `@for` stays
357
+ * alive across list mutations while its props are updated in place — reads
358
+ * of `$props.x` in template expressions track correctly, but a plain `let x =
359
+ * ...$props.y...` is evaluated once at setup, so template effects reading
360
+ * `x` never re-run and silently keep the previous row's values.
361
+ *
362
+ * Detection is best-effort and syntactic: top-level `let` declarations in the
363
+ * component script whose initializer (up to the first `;` or newline) mentions
364
+ * `$props`, and whose name then appears in a markup expression. Deliberately a
365
+ * warning, not an error — capturing a prop value once is sometimes intended,
366
+ * and destructured/renamed forms (`let { x } = $props`) aren't detected.
367
+ */
368
+ function stalePropLets(segments, markup, source) {
369
+ let script = "";
370
+ const deltas = [];
371
+ for (const segment of segments) {
372
+ deltas.push({
373
+ localStart: script.length,
374
+ delta: segment.fileStart
375
+ });
376
+ script += segment.text;
377
+ }
378
+ const toFileOffset = (local) => {
379
+ let delta = deltas[0].delta;
380
+ for (const entry of deltas) if (entry.localStart <= local) delta = entry.delta - entry.localStart;
381
+ else break;
382
+ return local + delta;
383
+ };
384
+ const names = [];
385
+ const LET = /^let[\s\n]/;
386
+ for (let i = 0; i < script.length; i++) {
387
+ const char = script[i];
388
+ if (char === "'" || char === "\"" || char === "`" || char === "/") {
389
+ const skipped = skipStringOrComment(script, i);
390
+ if (skipped !== -1) {
391
+ i = skipped - 1;
392
+ continue;
393
+ }
394
+ }
395
+ if (!LET.test(script.slice(i, i + 4))) continue;
396
+ if (i > 0 && /[\w$]/.test(script[i - 1])) continue;
397
+ let j = i + 3;
398
+ while (/\s/.test(script[j] ?? "")) j++;
399
+ let name = "";
400
+ while (/[\w$]/.test(script[j] ?? "")) {
401
+ name += script[j];
402
+ j++;
403
+ }
404
+ if (!name) continue;
405
+ while (/\s/.test(script[j] ?? "")) j++;
406
+ if (script[j] === ":") {
407
+ j++;
408
+ while (script[j] !== void 0 && script[j] !== "=" && script[j] !== "\n") j++;
409
+ }
410
+ while (/\s/.test(script[j] ?? "")) j++;
411
+ if (script[j] !== "=" || script[j + 1] === "=") continue;
412
+ j++;
413
+ let init = "";
414
+ while (j < script.length && script[j] !== ";" && script[j] !== "\n") {
415
+ if (script[j] === "'" || script[j] === "\"" || script[j] === "`") {
416
+ const skipped = skipStringOrComment(script, j);
417
+ if (skipped !== -1) {
418
+ init += script.slice(j, skipped);
419
+ j = skipped;
420
+ continue;
421
+ }
422
+ }
423
+ init += script[j];
424
+ j++;
425
+ }
426
+ if (/\$props\b/.test(init)) names.push({
427
+ name,
428
+ local: i
429
+ });
430
+ i = j;
431
+ }
432
+ if (names.length === 0 || !markup) return [];
433
+ const expressions = collectMarkupExpressions(markup);
434
+ if (!expressions) return [];
435
+ const warnings = [];
436
+ for (const { name, local } of names) {
437
+ const escaped = name.replace(/\$/g, "\\$");
438
+ if (!new RegExp(`(^|[^\\w$])${escaped}([^\\w$]|$)`).test(expressions)) continue;
439
+ const absolute = toFileOffset(local);
440
+ let startLine = 0;
441
+ let lastLineStart = 0;
442
+ if (source !== void 0) {
443
+ for (let i = 0; i < absolute && i < source.length; i++) if (source[i] === "\n") {
444
+ startLine += 1;
445
+ lastLineStart = i + 1;
446
+ }
447
+ }
448
+ warnings.push({
449
+ message: `'${name}' is a plain let initialized from $props. Its value is captured once at setup, so template expressions reading it won't update when the component's props change (keyed lists keep components alive and update props in place). Use a getter or $cache if it should stay live.`,
450
+ startIndex: absolute,
451
+ startLine,
452
+ startChar: absolute - lastLineStart,
453
+ endIndex: absolute,
454
+ endLine: startLine,
455
+ endChar: absolute - lastLineStart
456
+ });
457
+ }
458
+ return warnings;
459
+ }
460
+ //#endregion
352
461
  //#region src/compile/build/client/addMappedText.ts
353
462
  function addMappedText(preText, text, postText, span, status, b) {
354
463
  if (status.options.mapped === true) {
@@ -718,6 +827,59 @@ function bindingTarget(value, right, name, imports) {
718
827
  return `const t_bind_${varSuffix} = ${right};\nconst t_target_${varSuffix} = $peek(() => ${guard});\nif (t_target_${varSuffix} != null) t_target_${varSuffix}${suffix} = t_bind_${varSuffix};`;
719
828
  }
720
829
  //#endregion
830
+ //#region src/compile/utils/getContextUsage.ts
831
+ /**
832
+ * Gets the `$context` names that the compiled output references. The input is
833
+ * code-only text (a component's script plus markup expressions, or a slot
834
+ * fill's collected expressions), with `ranges` marking the positions that are
835
+ * code — matches that start inside a string, comment or regex literal are
836
+ * ignored, so mentions inside sample-code strings don't count.
837
+ */
838
+ function getContextUsage(source, ranges) {
839
+ const contextsMatches = source.matchAll(/\$context\??\s*(?:\.([\d\w]+)|\[([^\]]+)\])/g);
840
+ const contexts = [];
841
+ for (let match of contextsMatches) {
842
+ if (!isInCode(ranges, match.index)) continue;
843
+ const name = trimQuotes(match[1] || match[2]);
844
+ if (!contexts.includes(name)) contexts.push(name);
845
+ }
846
+ if (!contexts.length) for (let match of source.matchAll(/(?<![\w$])\$context(?![\w])(?!\s*:)(?!<)/g)) {
847
+ if (!isInCode(ranges, match.index)) continue;
848
+ contexts.push("$context");
849
+ break;
850
+ }
851
+ return contexts.length ? contexts : void 0;
852
+ }
853
+ /**
854
+ * Returns true if `index` falls inside one of the (sorted, non-overlapping)
855
+ * code ranges — i.e. not inside a string, comment or regex literal.
856
+ */
857
+ function isInCode(ranges, index) {
858
+ for (const [start, end] of ranges) {
859
+ if (index >= start && index < end) return true;
860
+ if (index < start) return false;
861
+ }
862
+ return false;
863
+ }
864
+ //#endregion
865
+ //#region src/compile/utils/fillUsesContext.ts
866
+ /**
867
+ * Returns true if a slot fill's content uses the `$context` parameter that
868
+ * the generated fill function declares: rendering a child component or slot
869
+ * forwards `$context` positionally (see buildComponentNode / buildSlotNode
870
+ * and their server counterparts), and a direct `$context` read in one of the
871
+ * fill's own expressions (interpolation, reactive attribute, event handler,
872
+ * control statement) reads it.
873
+ *
874
+ * Bias is towards `true`: when uncertain we keep `$context` named, which is
875
+ * always safe at the cost of a missed unused-parameter cleanup.
876
+ */
877
+ function fillUsesContext(fill) {
878
+ if (markupRendersComponent({ children: fill.children ?? [] })) return true;
879
+ const expressions = collectMarkupExpressions(fill);
880
+ return getContextUsage(expressions, codeRanges(expressions)) !== void 0;
881
+ }
882
+ //#endregion
721
883
  //#region src/compile/utils/isSpecialNode.ts
722
884
  function isSpecialNode(node) {
723
885
  return node.type === "special";
@@ -935,10 +1097,6 @@ function buildAddFragment(node, status, b, parentName, anchorName) {
935
1097
  if (fragment.singleRootElement) {
936
1098
  status.imports.add("t_add_element");
937
1099
  b.append(`t_add_element(${fragment.endVarName ?? fragmentName}, ${parentName}, ${anchorName});`);
938
- if (fragment.endVarName) {
939
- status.imports.add("t_next");
940
- b.append(`t_next(${fragment.endVarName});`);
941
- }
942
1100
  } else {
943
1101
  status.imports.add("t_add_fragment");
944
1102
  let params = [
@@ -949,10 +1107,6 @@ function buildAddFragment(node, status, b, parentName, anchorName) {
949
1107
  if (fragment.endVarName) params.push(fragment.endVarName);
950
1108
  if (fragment.endVarName && fragment.rootVarName) params.push(fragment.rootVarName);
951
1109
  b.append(`t_add_fragment(${params.join(", ")});`);
952
- if (fragment.endVarName) {
953
- status.imports.add("t_next");
954
- b.append(`t_next(${fragment.endVarName});`);
955
- }
956
1110
  }
957
1111
  }
958
1112
  }
@@ -1291,23 +1445,52 @@ function getFragmentVarPath(fragment, status, name, path, varPaths) {
1291
1445
  varPaths.set(varPath, name);
1292
1446
  varPaths.set(name, name);
1293
1447
  }
1294
- while (varPath.includes("t_next(t_next(")) {
1448
+ while (/(?:t_next_text\(|t_next\(){2,}/.test(varPath)) {
1295
1449
  status.imports.add("t_skip");
1296
- const match = varPath.match(/(t_next\(){2,}/)[0];
1297
- const count = match.length / 7;
1298
- const pos = varPath.indexOf("t_next(t_next(");
1299
- const head = varPath.substring(0, pos);
1300
- let level = 0;
1301
- let end = 0;
1302
- for (let i = pos + match.length; i < varPath.length; i++) if (varPath[i] === "(") level++;
1303
- else if (varPath[i] === ")") {
1304
- if (level === 0) {
1305
- end = i;
1450
+ const runStart = /(?:t_next_text\(|t_next\(){2,}/.exec(varPath).index;
1451
+ const openings = [];
1452
+ let j = runStart;
1453
+ for (;;) {
1454
+ const open = /^(t_next_text|t_next)\(/.exec(varPath.slice(j));
1455
+ if (!open) break;
1456
+ openings.push({
1457
+ text: open[1] === "t_next_text",
1458
+ openEnd: j + open[0].length
1459
+ });
1460
+ j += open[0].length;
1461
+ }
1462
+ if (openings.length < 2) break;
1463
+ const count = openings.length;
1464
+ const innermostOpenEnd = openings[openings.length - 1].openEnd;
1465
+ let innerDepth = 0;
1466
+ let innermostClose = -1;
1467
+ for (let k = innermostOpenEnd; k < varPath.length; k++) if (varPath[k] === "(") innerDepth++;
1468
+ else if (varPath[k] === ")") {
1469
+ if (innerDepth === 0) {
1470
+ innermostClose = k;
1471
+ break;
1472
+ }
1473
+ innerDepth--;
1474
+ }
1475
+ if (innermostClose === -1) break;
1476
+ let outerDepth = 1;
1477
+ let outerClose = -1;
1478
+ for (let k = openings[0].openEnd; k < varPath.length; k++) if (varPath[k] === "(") outerDepth++;
1479
+ else if (varPath[k] === ")") {
1480
+ outerDepth--;
1481
+ if (outerDepth === 0) {
1482
+ outerClose = k;
1306
1483
  break;
1307
- } else level--;
1484
+ }
1308
1485
  }
1309
- const tail = varPath.substring(end + count);
1310
- varPath = `${head}t_skip(${varPath.substring(pos + match.length, end)}, ${count})${tail}`;
1486
+ if (outerClose === -1) break;
1487
+ let mask = 0;
1488
+ for (let k = 0; k < count; k++) if (openings[k].text) mask |= 1 << count - 1 - k;
1489
+ let param = varPath.substring(innermostOpenEnd, innermostClose);
1490
+ if (openings[openings.length - 1].text && param.endsWith(", true")) param = param.slice(0, -6);
1491
+ const head = varPath.substring(0, runStart);
1492
+ const tail = varPath.substring(outerClose + 1);
1493
+ varPath = `${head}t_skip(${param}, ${count}${mask ? `, ${mask}` : ""})${tail}`;
1311
1494
  }
1312
1495
  varPath = varPath.replaceAll("t_next_text", "t_next");
1313
1496
  return varPath;
@@ -1322,8 +1505,10 @@ function getFragmentVarPathPart(path, varPath, status, root = false, rootFn = "t
1322
1505
  }
1323
1506
  for (let [i, child] of path.children.entries()) {
1324
1507
  if (i > 0) {
1325
- if (child.type === "text" || child.type === "space") varPath = `t_next_text(${varPath}, true)`;
1326
- else {
1508
+ if (child.type === "text" || child.type === "space") {
1509
+ status.imports.add("t_next");
1510
+ varPath = `t_next_text(${varPath}, true)`;
1511
+ } else {
1327
1512
  status.imports.add("t_next");
1328
1513
  varPath = `t_next(${varPath})`;
1329
1514
  }
@@ -1551,7 +1736,7 @@ function buildComponentNode(node, status, b, root = false) {
1551
1736
  "$sparent: ParentNode",
1552
1737
  "$sanchor: Node | null",
1553
1738
  slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>",
1554
- "// @ts-ignore\n// eslint-disable-next-line no-unused-vars\n$context?: Record<PropertyKey, any>"
1739
+ fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"
1555
1740
  ];
1556
1741
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = (\n${slotParams.join(",\n")}\n) => {`);
1557
1742
  buildFragment(slot, status, b, "$sparent", "$sanchor");
@@ -1681,6 +1866,44 @@ function isForBodyLeafSafe(forBodyChildren) {
1681
1866
  return !hasNestedControl(forBodyChildren);
1682
1867
  }
1683
1868
  //#endregion
1869
+ //#region src/compile/utils/forLoopVarNames.ts
1870
+ /**
1871
+ * Extracts the declared loop variable names from a `@for` statement — the
1872
+ * heuristic header parse shared by `buildForNode` (codegen) and the write
1873
+ * scanners (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect
1874
+ * nested loops that shadow an outer loop's variables).
1875
+ *
1876
+ * Handles the C-style (`for (let i = 0; i < n; i++)`), for-of and for-in
1877
+ * forms, with destructuring flattened to the bare names. TODO: Handle
1878
+ * destructuring, quotes, comments etc (same as buildForNode's note — this is
1879
+ * deliberately the same heuristic).
1880
+ */
1881
+ function forLoopVarNames(statement) {
1882
+ const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1883
+ const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
1884
+ const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
1885
+ const trimMatched = (value, start, end) => {
1886
+ const startIndex = value.indexOf(start);
1887
+ const endIndex = value.lastIndexOf(end);
1888
+ if (startIndex === -1 || endIndex === -1) return value;
1889
+ return value.slice(startIndex + 1, endIndex);
1890
+ };
1891
+ const names = [];
1892
+ const forLoopMatch = statement.match(forLoopRegex);
1893
+ if (forLoopMatch) {
1894
+ const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1895
+ for (const match of forVarMatches) names.push(match[1]);
1896
+ return names;
1897
+ }
1898
+ const forOfMatch = statement.match(forOfRegex);
1899
+ if (forOfMatch) {
1900
+ const match = forOfMatch[1];
1901
+ if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) names.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1902
+ else names.push(match);
1903
+ }
1904
+ return names;
1905
+ }
1906
+ //#endregion
1684
1907
  //#region src/compile/utils/forVarsWrittenIn.ts
1685
1908
  /**
1686
1909
  * Returns the set of `forVars` that are written anywhere in `children`,
@@ -1712,13 +1935,16 @@ function scan(children, forVars, bareWritePattern) {
1712
1935
  const found = /* @__PURE__ */ new Set();
1713
1936
  if (forVars.length === 0) return found;
1714
1937
  const collected = [];
1715
- for (const child of children) collectExpressionStrings(child, collected);
1938
+ for (const child of children) collectExpressionStrings(child, collected, /* @__PURE__ */ new Set());
1716
1939
  for (const varName of forVars) {
1717
1940
  const escaped = varName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1718
1941
  const writePattern = new RegExp(`(?<![\\w$.\\])\\)])\\[\\s*${escaped}\\s*\\]\\s*=(?![=>])|(?<![\\w$.\\])\\)])\\{\\s*${escaped}\\s*(:[^}]+)?\\}\\s*=(?![=>])|` + bareWritePattern(escaped) + `|(?<![\\w$.])(?:\\+\\+|--)\\s*${escaped}(?![\\w$])`);
1719
- for (const text of collected) if (writePattern.test(text)) {
1720
- found.add(varName);
1721
- break;
1942
+ for (const entry of collected) {
1943
+ if (entry.shadows.has(varName)) continue;
1944
+ if (writePattern.test(entry.text)) {
1945
+ found.add(varName);
1946
+ break;
1947
+ }
1722
1948
  }
1723
1949
  }
1724
1950
  return found;
@@ -1730,26 +1956,53 @@ function isElementLike(node) {
1730
1956
  * Collects every expression-like string from the body, including attribute
1731
1957
  * values (with `&`-binding targets marked by a trailing `=`), text
1732
1958
  * interpolations, and control statements (recursing into nested controls).
1959
+ *
1960
+ * Nested `@for` loops are special: their own statement is skipped entirely
1961
+ * (its declarations and init/update expressions belong to the inner loop's
1962
+ * variables — a C-style header's `i++` is the inner loop's own bookkeeping,
1963
+ * not a write of an outer loop's variable), and every string beneath it is
1964
+ * recorded with the inner loop's variable names as shadowing it.
1733
1965
  */
1734
- function collectExpressionStrings(node, out) {
1966
+ function collectExpressionStrings(node, out, shadows) {
1735
1967
  if (isTextNode(node)) {
1736
- out.push(node.content);
1968
+ out.push({
1969
+ text: node.content,
1970
+ shadows
1971
+ });
1737
1972
  return;
1738
1973
  }
1739
1974
  if (isElementLike(node)) {
1740
1975
  for (const attr of node.attributes) {
1741
1976
  if (attr.value !== void 0) {
1742
- if (attr.name.startsWith("&")) out.push(`${attr.value} =`);
1743
- else out.push(attr.value);
1977
+ if (attr.name.startsWith("&")) out.push({
1978
+ text: `${attr.value} =`,
1979
+ shadows
1980
+ });
1981
+ else out.push({
1982
+ text: attr.value,
1983
+ shadows
1984
+ });
1744
1985
  }
1745
- if (attr.fullyReactive && attr.name !== attr.value) out.push(attr.name);
1986
+ if (attr.fullyReactive && attr.name !== attr.value) out.push({
1987
+ text: attr.name,
1988
+ shadows
1989
+ });
1746
1990
  }
1747
- for (const child of node.children) collectExpressionStrings(child, out);
1991
+ for (const child of node.children) collectExpressionStrings(child, out, shadows);
1748
1992
  return;
1749
1993
  }
1750
1994
  if (isControlNode(node)) {
1751
- out.push(node.statement);
1752
- for (const child of node.children) collectExpressionStrings(child, out);
1995
+ if (node.operation === "@for") {
1996
+ const nested = new Set(shadows);
1997
+ for (const name of forLoopVarNames(node.statement)) nested.add(name);
1998
+ for (const child of node.children) collectExpressionStrings(child, out, nested);
1999
+ return;
2000
+ }
2001
+ out.push({
2002
+ text: node.statement,
2003
+ shadows
2004
+ });
2005
+ for (const child of node.children) collectExpressionStrings(child, out, shadows);
1753
2006
  }
1754
2007
  }
1755
2008
  //#endregion
@@ -1840,24 +2093,6 @@ function collectDirect(nodes, out) {
1840
2093
  }
1841
2094
  }
1842
2095
  //#endregion
1843
- //#region src/compile/utils/trimMatched.ts
1844
- /**
1845
- * Trims chars from the start and end of the supplied text when both the start and end match
1846
- *
1847
- * @param text The text to trim
1848
- *
1849
- * @returns The text without the chars at the start or the end
1850
- */
1851
- function trimMatched(text, startChar, endChar) {
1852
- let start = 0;
1853
- let end = text.length;
1854
- while (text[start] === startChar && text[end - 1] === endChar) {
1855
- start += 1;
1856
- end -= 1;
1857
- }
1858
- return text.substring(start, end);
1859
- }
1860
- //#endregion
1861
2096
  //#region src/compile/build/client/addBuildError.ts
1862
2097
  /**
1863
2098
  * Adds an error to the build status. Mirrors `parse/utils/addError`, but is
@@ -1896,26 +2131,11 @@ function addBuildError(status, message, start, end = start) {
1896
2131
  }
1897
2132
  //#endregion
1898
2133
  //#region src/compile/build/client/buildForNode.ts
1899
- const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1900
- const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
1901
- const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
1902
2134
  function buildForNode(node, status, b) {
1903
2135
  const parentName = node.parentName;
1904
2136
  const anchorName = node.varName ?? "null";
1905
2137
  node = node.children[0];
1906
- const forVarNames = [];
1907
- const forLoopMatch = node.statement.match(forLoopRegex);
1908
- if (forLoopMatch) {
1909
- const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1910
- for (let match of forVarMatches) forVarNames.push(match[1]);
1911
- } else {
1912
- const forOfMatch = node.statement.match(forOfRegex);
1913
- if (forOfMatch) {
1914
- const match = forOfMatch[1];
1915
- if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) forVarNames.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1916
- else forVarNames.push(match);
1917
- }
1918
- }
2138
+ const forVarNames = forLoopVarNames(node.statement);
1919
2139
  const regionName = nextVarName("for_region", status);
1920
2140
  const listItemsName = nextVarName("new_items", status);
1921
2141
  const itemName = nextVarName("item", status);
@@ -1951,10 +2171,9 @@ function buildForNode(node, status, b) {
1951
2171
  let ${listItemsName}: ListItemSpec[] = [];`);
1952
2172
  appendForVarBindings(b, status, `${node.statement}\n${keyStatement}`);
1953
2173
  addMappedText("", `${node.statement}`, " {", node.span, status, b);
1954
- if (singleVar) b.append(`${listItemsName}.push({ data: ${forVarNames[0]}, key: `);
1955
- else b.append(`${listItemsName}.push({ data: { ${forVarNames.join(", ")} }, key: `);
1956
- if (key !== void 0) addMappedText("", `${keyStatement || "undefined"}`, " });", key.span, status, b);
1957
- else b.append(`undefined });`);
2174
+ const dataExpr = singleVar ? forVarNames[0] : `{ ${forVarNames.join(", ")} }`;
2175
+ if (key !== void 0) addMappedText(`${listItemsName}.push({ data: ${dataExpr}, key: `, `${keyStatement || "undefined"}`, " });", key.span, status, b);
2176
+ else b.append(`${listItemsName}.push({ data: ${dataExpr} });`);
1958
2177
  b.append(`}`);
1959
2178
  b.append(`return ${listItemsName};`);
1960
2179
  b.append(`},
@@ -2246,6 +2465,24 @@ function buildSwitchBranch(node, status, b, parentName, regionName, indexName, i
2246
2465
  }`);
2247
2466
  }
2248
2467
  //#endregion
2468
+ //#region src/compile/utils/trimMatched.ts
2469
+ /**
2470
+ * Trims chars from the start and end of the supplied text when both the start and end match
2471
+ *
2472
+ * @param text The text to trim
2473
+ *
2474
+ * @returns The text without the chars at the start or the end
2475
+ */
2476
+ function trimMatched(text, startChar, endChar) {
2477
+ let start = 0;
2478
+ let end = text.length;
2479
+ while (text[start] === startChar && text[end - 1] === endChar) {
2480
+ start += 1;
2481
+ end -= 1;
2482
+ }
2483
+ return text.substring(start, end);
2484
+ }
2485
+ //#endregion
2249
2486
  //#region src/compile/build/client/buildTryNode.ts
2250
2487
  function buildTryNode(node, status, b) {
2251
2488
  const anchorName = node.varName ?? "null";
@@ -2911,11 +3148,11 @@ const importsMap$1 = {
2911
3148
  t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
2912
3149
  t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
2913
3150
  };
2914
- function buildCode(template, map, options, errors = []) {
3151
+ function buildCode(template, map, options, errors = [], warnings = []) {
2915
3152
  let b = new Builder(options?.mapped);
2916
3153
  let imports = /* @__PURE__ */ new Set();
2917
3154
  imports.add("SlotRender");
2918
- buildTemplate(template, map, imports, b, options, errors);
3155
+ buildTemplate(template, map, imports, b, options, errors, warnings);
2919
3156
  let startSize = b.toString().length;
2920
3157
  if (imports.size) {
2921
3158
  const folder = options?.renderFolder ?? "@torpor/view";
@@ -2932,7 +3169,7 @@ function buildCode(template, map, options, errors = []) {
2932
3169
  }
2933
3170
  return b.toString();
2934
3171
  }
2935
- function buildTemplate(template, map, imports, b, options, errors = []) {
3172
+ function buildTemplate(template, map, imports, b, options, errors = [], warnings = []) {
2936
3173
  let script = template.script.map((s) => s.script).join("\n");
2937
3174
  for (const component of template.components) {
2938
3175
  if (component.markup) script += "\n" + collectMarkupExpressions(component.markup);
@@ -2959,9 +3196,11 @@ function buildTemplate(template, map, imports, b, options, errors = []) {
2959
3196
  let current = template.components[0];
2960
3197
  let status = makeStatus(imports, map, current, options, errors);
2961
3198
  let first = true;
3199
+ let componentScript = [];
2962
3200
  for (let chunk of template.script) if (chunk.script === "/* @params */") {
2963
3201
  if (!first) status = makeStatus(imports, map, current, options, errors);
2964
3202
  first = false;
3203
+ componentScript = [];
2965
3204
  b.append(`
2966
3205
  ${current.markup ? "$parent" : "_$parent"}: ParentNode,
2967
3206
  ${current.markup ? "$anchor" : "_$anchor"}: Node | null,`);
@@ -3007,10 +3246,17 @@ function buildTemplate(template, map, imports, b, options, errors = []) {
3007
3246
  status.inHead = false;
3008
3247
  }
3009
3248
  } else if (chunk.script === "/* @style */") {} else if (chunk.script === "/* @end */") {
3249
+ if (current.markup && warnings !== void 0) warnings.push(...stalePropLets(componentScript, current.markup, options?.source));
3010
3250
  addPopDevBoundary(status, b);
3011
3251
  currentIndex += 1;
3012
3252
  current = template.components[currentIndex];
3013
- } else addMappedText("", chunk.script, "", chunk.span, status, b);
3253
+ } else {
3254
+ addMappedText("", chunk.script, "", chunk.span, status, b);
3255
+ componentScript.push({
3256
+ text: chunk.script,
3257
+ fileStart: chunk.span.start
3258
+ });
3259
+ }
3014
3260
  }
3015
3261
  function makeStatus(imports, map, current, options, errors = []) {
3016
3262
  return {
@@ -3150,7 +3396,7 @@ function buildServerComponentNode(node, status, b) {
3150
3396
  for (let slot of node.children) if (isSpecialNode(slot) && (slot.tagName === "fill" || slot.tagName === "filldef")) {
3151
3397
  const nameAttribute = slot.attributes.find((a) => a.name === "name");
3152
3398
  const slotName = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
3153
- const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", "// @ts-ignore\n// eslint-disable-next-line no-unused-vars\n$context?: Record<PropertyKey, any>"];
3399
+ const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3154
3400
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = async (\n${slotParams.join(",\n")}\n) => {`);
3155
3401
  b.append(`let t_body = "";`);
3156
3402
  for (let child of slot.children) buildServerNode(child, status, b);
@@ -3389,7 +3635,9 @@ function buildServerElementNode(node, status, b) {
3389
3635
  if (!voidTags.includes(tagName)) {
3390
3636
  const oldPreserveWhitespace = status.preserveWhitespace;
3391
3637
  status.preserveWhitespace = ["pre", "code"].includes(tagName);
3638
+ if (!tagName.startsWith("@")) status.elementStack.push(tagName);
3392
3639
  for (let child of node.children) buildServerNode(child, status, b);
3640
+ if (!tagName.startsWith("@")) status.elementStack.pop();
3393
3641
  status.preserveWhitespace = oldPreserveWhitespace;
3394
3642
  status.output += `</${tagName}>`;
3395
3643
  }
@@ -3418,16 +3666,15 @@ function buildElementAttributes(node, status) {
3418
3666
  attributes.push(`${propName}="\${${valueOrDefault}}"`);
3419
3667
  } else if (name === "class") {
3420
3668
  status.imports.add("t_class");
3421
- let params = [value];
3669
+ let params = value;
3422
3670
  if (node.scopeStyles && !status.inHead) {
3423
- params.push(`"torp-${status.styleHash}"`);
3671
+ params = `${value}, "torp-${status.styleHash}"`;
3424
3672
  needsClass = false;
3425
3673
  }
3426
- value = params.join(", ");
3427
- attributes.push(`\${t_class(${value}) !== "" ? \`class="\${t_class(${value})}"\` : ""}`);
3674
+ attributes.push(`\${t_class(${params})}`);
3428
3675
  } else if (name === "style") {
3429
3676
  status.imports.add("t_style");
3430
- attributes.push(`\${t_style(${value}) !== "" ? \`style="\${t_style(${value})}"\` : ""}`);
3677
+ attributes.push(`\${t_style(${value})}`);
3431
3678
  } else {
3432
3679
  status.imports.add("t_attr");
3433
3680
  attributes.push(`\${(${value}) ? \`${name}="\${t_attr(${value})}"\` : ""}`);
@@ -3464,8 +3711,12 @@ function buildServerSlotNode(node, status, b) {
3464
3711
  for (let { name, value } of slotAttributes) if (value != null) b.append(`${propsName}["${name}"] = ${value};`);
3465
3712
  else b.append(`${propsName}["${name}"] = true;`);
3466
3713
  }
3714
+ const closeTags = status.elementStack.filter((tag) => require_slotAutoClose.AUTO_CLOSEABLE.has(tag));
3467
3715
  b.append(`if ($slots && $slots["${slotName}"]) {`);
3468
- b.append(`${status.inHead ? "t_head" : "t_body"} += await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context);`);
3716
+ if (closeTags.length > 0) {
3717
+ status.imports.add("t_slot_guard");
3718
+ b.append(`${status.inHead ? "t_head" : "t_body"} += t_slot_guard([${closeTags.map((tag) => `"${tag}"`).join(", ")}], await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context), "${slotName}");`);
3719
+ } else b.append(`${status.inHead ? "t_head" : "t_body"} += await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context);`);
3469
3720
  const fill = node.children.find((c) => isSpecialNode(c) && (c.tagName === "fill" || c.tagName === "filldef"));
3470
3721
  if (fill && isSpecialNode(fill) && fill.children.length) {
3471
3722
  b.append(`} else {`);
@@ -3574,6 +3825,7 @@ const importsMap = {
3574
3825
  t_attr: "import { t_attr } from \"${folder}\";",
3575
3826
  t_class: "import { t_class } from \"${folder}\";",
3576
3827
  t_style: "import { t_style } from \"${folder}\";",
3828
+ t_slot_guard: "import { t_slot_guard } from \"${folder}\";",
3577
3829
  ServerSlotRender: "import { type ServerSlotRender } from \"${folder}\";"
3578
3830
  };
3579
3831
  function buildServerCode(template, options) {
@@ -3641,6 +3893,7 @@ function buildServerTemplate(template, imports, b, options) {
3641
3893
  varNames: {},
3642
3894
  preserveWhitespace: false,
3643
3895
  awaitCount: 0,
3896
+ elementStack: [],
3644
3897
  options
3645
3898
  };
3646
3899
  b.append("");
@@ -3665,6 +3918,7 @@ function buildServerTemplate(template, imports, b, options) {
3665
3918
  varNames: {},
3666
3919
  preserveWhitespace: false,
3667
3920
  awaitCount: 0,
3921
+ elementStack: [],
3668
3922
  options
3669
3923
  };
3670
3924
  b.append(`} catch (${current.errorVar}) {`);
@@ -3688,6 +3942,7 @@ function buildServerTemplate(template, imports, b, options) {
3688
3942
  preserveWhitespace: false,
3689
3943
  inHead: true,
3690
3944
  awaitCount: 0,
3945
+ elementStack: [],
3691
3946
  options
3692
3947
  };
3693
3948
  b.append("");
@@ -3842,16 +4097,1156 @@ function build(template, options) {
3842
4097
  }
3843
4098
  let map = [];
3844
4099
  let errors = [];
4100
+ let warnings = [];
3845
4101
  return {
3846
- code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options, errors),
4102
+ code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options, errors, warnings),
3847
4103
  styles: template.components.map((c) => c.style ? {
3848
4104
  style: buildStyles(c.style, c.style.hash),
3849
4105
  hash: c.style.hash
3850
4106
  } : void 0).filter((c) => c !== void 0),
3851
4107
  map,
4108
+ errors,
4109
+ warnings
4110
+ };
4111
+ }
4112
+ //#endregion
4113
+ //#region src/compile/build/restricted/scanState.ts
4114
+ /**
4115
+ * Matches `let|const|var <name> [type] = $watch(` at exactly the scan
4116
+ * position (sticky), tolerating a type annotation.
4117
+ */
4118
+ const DECLARATION = /(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?\s*=\s*\$watch\s*(?:<[^>(]*>)?\s*\(/y;
4119
+ /**
4120
+ * Finds `let <name> = $watch(<initializer>)` declarations in a component's
4121
+ * script chunks (restricted mode's client state). Scans the code with
4122
+ * strings, comments and regex literals skipped — so a `$watch` inside a
4123
+ * string never matches — and returns each initializer source with its
4124
+ * absolute offset, so it can be parsed into a restricted expression with
4125
+ * correct error positions.
4126
+ */
4127
+ function scanStateInitializers(chunks) {
4128
+ let text = "";
4129
+ const offsets = [];
4130
+ for (const chunk of chunks) {
4131
+ for (let i = 0; i < chunk.script.length; i++) offsets.push(chunk.span.start + i);
4132
+ text += chunk.script;
4133
+ }
4134
+ const results = [];
4135
+ let i = 0;
4136
+ while (i < text.length) {
4137
+ const skipped = skipStringOrComment(text, i);
4138
+ if (skipped !== -1) {
4139
+ i = skipped;
4140
+ continue;
4141
+ }
4142
+ DECLARATION.lastIndex = i;
4143
+ const match = DECLARATION.exec(text);
4144
+ if (match === null || match.index !== i) {
4145
+ i += 1;
4146
+ continue;
4147
+ }
4148
+ const name = match[1];
4149
+ const open = i + match[0].length - 1;
4150
+ let level = 0;
4151
+ let close = -1;
4152
+ let j = open;
4153
+ while (j < text.length) {
4154
+ const skipped = skipStringOrComment(text, j);
4155
+ if (skipped !== -1) {
4156
+ j = skipped;
4157
+ continue;
4158
+ }
4159
+ if (text[j] === "(") level += 1;
4160
+ else if (text[j] === ")") {
4161
+ level -= 1;
4162
+ if (level === 0) {
4163
+ close = j;
4164
+ break;
4165
+ }
4166
+ }
4167
+ j += 1;
4168
+ }
4169
+ if (close === -1) break;
4170
+ const initStart = open + 1;
4171
+ results.push({
4172
+ name,
4173
+ initSource: text.substring(initStart, close),
4174
+ start: offsets[initStart] ?? i
4175
+ });
4176
+ i = close;
4177
+ }
4178
+ return results;
4179
+ }
4180
+ //#endregion
4181
+ //#region src/compile/build/restricted/parseExpression.ts
4182
+ /**
4183
+ * Parses a restricted template expression into the serialized op set.
4184
+ *
4185
+ * This is intentionally a small, hand-written parser rather than a general
4186
+ * JS parser: the grammar *is* the restricted op set (the permanent format
4187
+ * API), so anything outside it is rejected with a positioned error instead
4188
+ * of being parsed and then policed. Regex-based tokenizing was rejected --
4189
+ * operators inside string literals and operator precedence make it
4190
+ * unsound.
4191
+ *
4192
+ * Supported: literals, identifiers (props/data/loop variables), property
4193
+ * and index access, unary `! - + typeof`, arithmetic/comparison/logic
4194
+ * (`* / %`, `+ -`, `< <= > >=`, `== != === !==`, `&&`, `||`, `??`),
4195
+ * ternaries, and array/object literals.
4196
+ *
4197
+ * Deliberately not supported (each gets a targeted error): calls (format
4198
+ * in `derive` instead), authored functions/arrows, `new`, `await`,
4199
+ * assignments and updates, optional chaining, template literals, spread.
4200
+ */
4201
+ var RestrictedSyntaxError = class extends Error {
4202
+ /** Absolute index (including the parser's offset) where the error starts. */
4203
+ start;
4204
+ /** Absolute index where the error ends. */
4205
+ end;
4206
+ constructor(message, start, end) {
4207
+ super(message);
4208
+ this.name = "RestrictedSyntaxError";
4209
+ this.start = start;
4210
+ this.end = end;
4211
+ }
4212
+ };
4213
+ const MULTI_PUNCT = [
4214
+ "===",
4215
+ "!==",
4216
+ "&&=",
4217
+ "||=",
4218
+ "??=",
4219
+ "...",
4220
+ "=>",
4221
+ "?.",
4222
+ "==",
4223
+ "!=",
4224
+ "<=",
4225
+ ">=",
4226
+ "&&",
4227
+ "||",
4228
+ "??",
4229
+ "++",
4230
+ "--",
4231
+ "+=",
4232
+ "-=",
4233
+ "*=",
4234
+ "/=",
4235
+ "%="
4236
+ ];
4237
+ const SINGLE_PUNCT = new Set("+-*/%!<>=?:.,()[]{}".split(""));
4238
+ const ASSIGNMENT = /* @__PURE__ */ new Set([
4239
+ "=",
4240
+ "+=",
4241
+ "-=",
4242
+ "*=",
4243
+ "/=",
4244
+ "%=",
4245
+ "&&=",
4246
+ "||=",
4247
+ "??="
4248
+ ]);
4249
+ /** Binary operators from lowest to highest precedence. */
4250
+ const BINARY_LEVELS = [
4251
+ ["??"],
4252
+ ["||"],
4253
+ ["&&"],
4254
+ [
4255
+ "==",
4256
+ "!=",
4257
+ "===",
4258
+ "!=="
4259
+ ],
4260
+ [
4261
+ "<",
4262
+ "<=",
4263
+ ">",
4264
+ ">="
4265
+ ],
4266
+ ["+", "-"],
4267
+ [
4268
+ "*",
4269
+ "/",
4270
+ "%"
4271
+ ]
4272
+ ];
4273
+ const UNARY_PUNCT = /* @__PURE__ */ new Set([
4274
+ "!",
4275
+ "-",
4276
+ "+"
4277
+ ]);
4278
+ const DANGEROUS_KEYS = /* @__PURE__ */ new Set([
4279
+ "__proto__",
4280
+ "prototype",
4281
+ "constructor"
4282
+ ]);
4283
+ const RESERVED = {
4284
+ new: "`new` isn't supported in restricted expressions.",
4285
+ await: "`await` isn't supported in restricted expressions; SSR data comes from `data` requirements.",
4286
+ this: "`this` isn't supported in restricted expressions.",
4287
+ super: "`super` isn't supported in restricted expressions.",
4288
+ function: "Function expressions aren't supported in restricted expressions.",
4289
+ class: "Classes aren't supported in restricted expressions.",
4290
+ yield: "`yield` isn't supported in restricted expressions.",
4291
+ delete: "`delete` isn't supported in restricted expressions.",
4292
+ void: "`void` isn't supported in restricted expressions.",
4293
+ in: "`in` isn't supported in restricted expressions.",
4294
+ instanceof: "`instanceof` isn't supported in restricted expressions.",
4295
+ const: "Declarations aren't supported in restricted expressions.",
4296
+ let: "Declarations aren't supported in restricted expressions.",
4297
+ var: "Declarations aren't supported in restricted expressions.",
4298
+ return: "`return` isn't supported in restricted expressions."
4299
+ };
4300
+ const CALLS_UNSUPPORTED = "Function calls aren't supported in restricted template expressions. Compute formatted/derived values in the data layer instead, e.g. `data view from derive { of: …, map: { formattedX: format($item.x) } }`, or have the host shape the requirement's result.";
4301
+ const ARROWS_UNSUPPORTED = "Arrow functions aren't supported in restricted expressions. Move the logic into a `derive` requirement, a host formatter, or the client build.";
4302
+ function tokenize(source, offset) {
4303
+ const tokens = [];
4304
+ let i = 0;
4305
+ const error = (message, start, end) => {
4306
+ throw new RestrictedSyntaxError(message, offset + start, offset + end);
4307
+ };
4308
+ while (i < source.length) {
4309
+ const char = source[i];
4310
+ if (char === " " || char === " " || char === "\n" || char === "\r") {
4311
+ i += 1;
4312
+ continue;
4313
+ }
4314
+ const start = i;
4315
+ if (char >= "0" && char <= "9") {
4316
+ i += 1;
4317
+ while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
4318
+ if (source[i] === "." && source[i + 1] >= "0" && source[i + 1] <= "9") {
4319
+ i += 1;
4320
+ while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
4321
+ }
4322
+ if (source[i] === "e" || source[i] === "E") {
4323
+ const exponentStart = i;
4324
+ i += 1;
4325
+ if (source[i] === "+" || source[i] === "-") i += 1;
4326
+ if (source[i] >= "0" && source[i] <= "9") while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
4327
+ else i = exponentStart;
4328
+ }
4329
+ tokens.push({
4330
+ type: "num",
4331
+ value: source.substring(start, i),
4332
+ start: offset + start,
4333
+ end: offset + i
4334
+ });
4335
+ continue;
4336
+ }
4337
+ if (char === "\"" || char === "'") {
4338
+ const quote = char;
4339
+ i += 1;
4340
+ let value = "";
4341
+ let closed = false;
4342
+ while (i < source.length) {
4343
+ const current = source[i];
4344
+ if (current === quote) {
4345
+ i += 1;
4346
+ closed = true;
4347
+ break;
4348
+ }
4349
+ if (current === "\n") break;
4350
+ if (current === "\\") {
4351
+ i += 1;
4352
+ const escape = source[i];
4353
+ if (escape === void 0) break;
4354
+ switch (escape) {
4355
+ case "n":
4356
+ value += "\n";
4357
+ break;
4358
+ case "r":
4359
+ value += "\r";
4360
+ break;
4361
+ case "t":
4362
+ value += " ";
4363
+ break;
4364
+ case "b":
4365
+ value += "\b";
4366
+ break;
4367
+ case "f":
4368
+ value += "\f";
4369
+ break;
4370
+ case "v":
4371
+ value += "\v";
4372
+ break;
4373
+ case "0":
4374
+ value += "\0";
4375
+ break;
4376
+ case "\\":
4377
+ value += "\\";
4378
+ break;
4379
+ case "'":
4380
+ value += "'";
4381
+ break;
4382
+ case "\"":
4383
+ value += "\"";
4384
+ break;
4385
+ case "u": {
4386
+ const hex = source.substring(i + 1, i + 5);
4387
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) error("Invalid unicode escape sequence", i - 1, i + 2);
4388
+ value += String.fromCharCode(parseInt(hex, 16));
4389
+ i += 4;
4390
+ break;
4391
+ }
4392
+ default: error(`Invalid escape sequence "\\${escape}"`, i - 1, i + 1);
4393
+ }
4394
+ i += 1;
4395
+ continue;
4396
+ }
4397
+ value += current;
4398
+ i += 1;
4399
+ }
4400
+ if (!closed) error("Unterminated string literal", start, i);
4401
+ tokens.push({
4402
+ type: "str",
4403
+ value,
4404
+ start: offset + start,
4405
+ end: offset + i
4406
+ });
4407
+ continue;
4408
+ }
4409
+ if (char === "`") error("Template literals aren't supported in restricted expressions; use string concatenation with `+`.", start, start + 1);
4410
+ if (char === "$" || char === "_" || /[A-Za-z]/.test(char)) {
4411
+ i += 1;
4412
+ while (i < source.length && /[A-Za-z0-9_$]/.test(source[i])) i += 1;
4413
+ tokens.push({
4414
+ type: "ident",
4415
+ value: source.substring(start, i),
4416
+ start: offset + start,
4417
+ end: offset + i
4418
+ });
4419
+ continue;
4420
+ }
4421
+ let matched;
4422
+ for (const punct of MULTI_PUNCT) if (source.startsWith(punct, i)) {
4423
+ matched = punct;
4424
+ break;
4425
+ }
4426
+ if (matched === void 0 && SINGLE_PUNCT.has(char)) matched = char;
4427
+ if (matched !== void 0) {
4428
+ i += matched.length;
4429
+ tokens.push({
4430
+ type: "punct",
4431
+ value: matched,
4432
+ start: offset + start,
4433
+ end: offset + i
4434
+ });
4435
+ continue;
4436
+ }
4437
+ error(`Unexpected character "${char}"`, start, start + 1);
4438
+ }
4439
+ tokens.push({
4440
+ type: "eof",
4441
+ value: "",
4442
+ start: offset + source.length,
4443
+ end: offset + source.length
4444
+ });
4445
+ return tokens;
4446
+ }
4447
+ /**
4448
+ * Parses one restricted expression.
4449
+ *
4450
+ * @param source The expression source text
4451
+ * @param offset The source index the expression starts at, so errors point
4452
+ * into the original file
4453
+ */
4454
+ function parseExpression(source, offset = 0, options) {
4455
+ return parseCore(source, offset, false, options).expression;
4456
+ }
4457
+ /**
4458
+ * Parses an expression that is followed by more text (e.g. a requirement
4459
+ * spec's `,` or the end of the spec). Returns where the expression ended so
4460
+ * callers can continue scanning.
4461
+ */
4462
+ function parseExpressionPrefix(source, offset = 0, options) {
4463
+ return parseCore(source, offset, true, options);
4464
+ }
4465
+ function parseCore(source, offset, allowTrailing, options) {
4466
+ const allowCalls = options?.allowCalls === true;
4467
+ const tokens = tokenize(source, offset);
4468
+ let index = 0;
4469
+ const peek = () => tokens[index];
4470
+ const next = () => tokens[index++];
4471
+ const error = (message, token = peek()) => {
4472
+ throw new RestrictedSyntaxError(message, token.start, token.end);
4473
+ };
4474
+ const expect = (value) => {
4475
+ const token = next();
4476
+ if (token.type === "eof" || token.value !== value) error(`Expected "${value}"${token.type === "eof" ? " but reached the end of the expression" : ` but found "${token.value}"`}`, token);
4477
+ return token;
4478
+ };
4479
+ const isPunct = (value) => peek().type === "punct" && peek().value === value;
4480
+ function parseTernary() {
4481
+ const test = parseBinary(0);
4482
+ if (!isPunct("?")) return test;
4483
+ next();
4484
+ const consequent = parseTernary();
4485
+ expect(":");
4486
+ return {
4487
+ op: "ternary",
4488
+ test,
4489
+ consequent,
4490
+ alternate: parseTernary()
4491
+ };
4492
+ }
4493
+ function parseBinary(level) {
4494
+ if (level >= BINARY_LEVELS.length) return parseUnary();
4495
+ const operators = BINARY_LEVELS[level];
4496
+ let left = parseBinary(level + 1);
4497
+ while (peek().type === "punct" && operators.includes(peek().value)) {
4498
+ const operator = next().value;
4499
+ const right = parseBinary(level + 1);
4500
+ left = {
4501
+ op: "binary",
4502
+ operator,
4503
+ left,
4504
+ right
4505
+ };
4506
+ }
4507
+ return left;
4508
+ }
4509
+ function parseUnary() {
4510
+ const token = peek();
4511
+ if (token.type === "punct" && UNARY_PUNCT.has(token.value) || token.type === "ident" && token.value === "typeof") {
4512
+ next();
4513
+ const operand = parseUnary();
4514
+ return {
4515
+ op: "unary",
4516
+ operator: token.value,
4517
+ operand
4518
+ };
4519
+ }
4520
+ return parsePostfix();
4521
+ }
4522
+ function parsePostfix() {
4523
+ let expression = parsePrimary();
4524
+ while (true) {
4525
+ const token = peek();
4526
+ if (token.type !== "punct") return expression;
4527
+ if (token.value === "." || token.value === "?.") {
4528
+ const optional = token.value === "?.";
4529
+ next();
4530
+ if (optional && peek().type === "punct" && peek().value === "[") {
4531
+ next();
4532
+ const indexExpr = parseTernary();
4533
+ expect("]");
4534
+ expression = {
4535
+ op: "index",
4536
+ object: expression,
4537
+ index: indexExpr,
4538
+ optional: true
4539
+ };
4540
+ continue;
4541
+ }
4542
+ const key = next();
4543
+ if (key.type !== "ident") error(`Expected a property name after "${token.value}"`, key);
4544
+ if (DANGEROUS_KEYS.has(key.value)) error(`Dangerous property name "${key.value}" isn't allowed in restricted expressions`, key);
4545
+ expression = optional ? {
4546
+ op: "get",
4547
+ object: expression,
4548
+ key: key.value,
4549
+ optional: true
4550
+ } : {
4551
+ op: "get",
4552
+ object: expression,
4553
+ key: key.value
4554
+ };
4555
+ continue;
4556
+ }
4557
+ if (token.value === "[") {
4558
+ next();
4559
+ const indexExpr = parseTernary();
4560
+ expect("]");
4561
+ expression = {
4562
+ op: "index",
4563
+ object: expression,
4564
+ index: indexExpr
4565
+ };
4566
+ continue;
4567
+ }
4568
+ if (token.value === "(") {
4569
+ if (!allowCalls) error(CALLS_UNSUPPORTED, token);
4570
+ if (expression.op !== "ref") error("Only named host functions can be called; method calls (a.b()) aren't supported in restricted expressions.", token);
4571
+ next();
4572
+ const args = [];
4573
+ while (!isPunct(")")) {
4574
+ if (peek().type === "eof") expect(")");
4575
+ args.push(parseTernary());
4576
+ if (isPunct(",")) next();
4577
+ }
4578
+ expect(")");
4579
+ expression = {
4580
+ op: "call",
4581
+ name: expression.name,
4582
+ args
4583
+ };
4584
+ continue;
4585
+ }
4586
+ if (token.value === "++" || token.value === "--") error("Updates (`++`/`--`) aren't supported in restricted expressions.", token);
4587
+ return expression;
4588
+ }
4589
+ }
4590
+ function parsePrimary() {
4591
+ const token = next();
4592
+ switch (token.type) {
4593
+ case "num": return {
4594
+ op: "lit",
4595
+ value: Number(token.value)
4596
+ };
4597
+ case "str": return {
4598
+ op: "lit",
4599
+ value: token.value
4600
+ };
4601
+ case "ident": {
4602
+ const name = token.value;
4603
+ if (name === "true") return {
4604
+ op: "lit",
4605
+ value: true
4606
+ };
4607
+ if (name === "false") return {
4608
+ op: "lit",
4609
+ value: false
4610
+ };
4611
+ if (name === "null" || name === "undefined") return {
4612
+ op: "lit",
4613
+ value: null
4614
+ };
4615
+ const reserved = RESERVED[name];
4616
+ if (reserved !== void 0) error(reserved, token);
4617
+ return {
4618
+ op: "ref",
4619
+ name
4620
+ };
4621
+ }
4622
+ case "punct":
4623
+ if (token.value === "(") {
4624
+ const expression = parseTernary();
4625
+ expect(")");
4626
+ return expression;
4627
+ }
4628
+ if (token.value === "[") {
4629
+ const items = [];
4630
+ while (!isPunct("]")) {
4631
+ if (peek().type === "eof") expect("]");
4632
+ if (isPunct(",")) {
4633
+ next();
4634
+ continue;
4635
+ }
4636
+ items.push(parseTernary());
4637
+ if (isPunct(",")) next();
4638
+ }
4639
+ expect("]");
4640
+ return {
4641
+ op: "array",
4642
+ items
4643
+ };
4644
+ }
4645
+ if (token.value === "{") {
4646
+ const entries = {};
4647
+ while (!isPunct("}")) {
4648
+ if (peek().type === "eof") expect("}");
4649
+ if (isPunct(",")) {
4650
+ next();
4651
+ continue;
4652
+ }
4653
+ const key = next();
4654
+ if (key.type !== "ident" && key.type !== "str" && key.type !== "num") error("Expected an object key (identifier, string or number)", key);
4655
+ if (DANGEROUS_KEYS.has(key.value)) error(`Dangerous property name "${key.value}" isn't allowed in restricted expressions`, key);
4656
+ expect(":");
4657
+ entries[key.value] = parseTernary();
4658
+ if (isPunct(",")) next();
4659
+ }
4660
+ expect("}");
4661
+ return {
4662
+ op: "object",
4663
+ entries
4664
+ };
4665
+ }
4666
+ if (token.value === "...") error("Spread isn't supported in restricted expressions.", token);
4667
+ if (token.value === "=>") error(ARROWS_UNSUPPORTED, token);
4668
+ if (ASSIGNMENT.has(token.value)) error("Assignments aren't supported in restricted expressions.", token);
4669
+ error(`Unexpected "${token.value}"`, token);
4670
+ }
4671
+ error("Unexpected end of expression", token);
4672
+ }
4673
+ const expression = parseTernary();
4674
+ const trailing = peek();
4675
+ if (trailing.type !== "eof" && !allowTrailing) {
4676
+ if (trailing.type === "punct" && trailing.value === "=>") error(ARROWS_UNSUPPORTED, trailing);
4677
+ if (trailing.type === "punct" && ASSIGNMENT.has(trailing.value)) error("Assignments aren't supported in restricted expressions.", trailing);
4678
+ if (trailing.type === "ident" && RESERVED[trailing.value] !== void 0) error(RESERVED[trailing.value], trailing);
4679
+ error(`Unexpected "${trailing.value}" after expression`, trailing);
4680
+ }
4681
+ return {
4682
+ expression,
4683
+ end: trailing.type === "eof" ? offset + source.length : trailing.start
4684
+ };
4685
+ }
4686
+ //#endregion
4687
+ //#region src/compile/build/restricted/buildRestricted.ts
4688
+ /**
4689
+ * Builds a template into a serialized restricted program: the server-side
4690
+ * instruction tree interpreted by `renderRestricted` (no `eval`, so it is
4691
+ * legal on workerd).
4692
+ *
4693
+ * Must be called on a **freshly parsed** template: it maps text
4694
+ * interpolations through the parse-time source spans. Trimming whitespace
4695
+ * nodes here is safe (only whitespace-only nodes change), and matches the
4696
+ * JS build; `build()` calling `trimWhitespace` again is idempotent.
4697
+ */
4698
+ function buildRestricted(template, options) {
4699
+ const source = options?.source ?? "";
4700
+ const errors = [];
4701
+ const report = (message, start, end = start) => {
4702
+ errors.push(compileError(message, start, end, source));
4703
+ };
4704
+ const components = [];
4705
+ const styles = [];
4706
+ for (let componentIndex = 0; componentIndex < template.components.length; componentIndex++) {
4707
+ const component = template.components[componentIndex];
4708
+ const styleHash = component.style?.hash ?? "";
4709
+ if (component.style) styles.push({
4710
+ style: buildStyles(component.style, styleHash),
4711
+ hash: styleHash
4712
+ });
4713
+ if (component.head) report("@head content isn't supported in restricted mode yet.", component.start ?? 0);
4714
+ if (component.error) report("@error blocks aren't supported in restricted mode yet.", component.start ?? 0);
4715
+ const state = [];
4716
+ const stateNames = [];
4717
+ const allowedRefs = /* @__PURE__ */ new Set(["$props", "$data"]);
4718
+ const context = {
4719
+ source,
4720
+ styleHash,
4721
+ preserveWhitespace: options?.preserveWhitespace === true,
4722
+ errors,
4723
+ report,
4724
+ allowedRefs,
4725
+ stateNames,
4726
+ loopVars: [],
4727
+ elementStack: []
4728
+ };
4729
+ if (component.markup && options?.preserveWhitespace !== true) trimWhitespace(component.markup);
4730
+ const nextStart = template.components[componentIndex + 1]?.scriptStart ?? template.script.length;
4731
+ const componentChunks = template.script.slice(component.scriptStart ?? 0, nextStart);
4732
+ for (const scanned of scanStateInitializers(componentChunks)) try {
4733
+ const init = parseExprAt(scanned.initSource, scanned.start, context);
4734
+ validateRefs(init, /* @__PURE__ */ new Set(["$props"]), context, scanned.start, `state initializer "${scanned.name}"`, []);
4735
+ state.push({
4736
+ name: scanned.name,
4737
+ init
4738
+ });
4739
+ stateNames.push(scanned.name);
4740
+ allowedRefs.add(scanned.name);
4741
+ } catch (error) {
4742
+ if (error instanceof RestrictedSyntaxError) report(error.message, error.start, error.end);
4743
+ else throw error;
4744
+ }
4745
+ const markup = component.markup ? serializeChildren(component.markup.children, context) : [];
4746
+ components.push({
4747
+ name: component.name,
4748
+ default: component.default,
4749
+ markup,
4750
+ state: state.length > 0 ? state : void 0
4751
+ });
4752
+ }
4753
+ errors.sort((a, b) => a.startIndex - b.startIndex);
4754
+ return {
4755
+ program: {
4756
+ requirements: [],
4757
+ components
4758
+ },
4759
+ styles,
3852
4760
  errors
3853
4761
  };
3854
4762
  }
4763
+ function compileError(message, start, end, source) {
4764
+ let startLine = 0;
4765
+ let lastLineStart = 0;
4766
+ let i = 0;
4767
+ for (; i < start && i < source.length; i++) if (source[i] === "\n") {
4768
+ startLine += 1;
4769
+ lastLineStart = i + 1;
4770
+ }
4771
+ const startChar = start - lastLineStart;
4772
+ let endLine = startLine;
4773
+ for (; i < end && i < source.length; i++) if (source[i] === "\n") {
4774
+ endLine += 1;
4775
+ lastLineStart = i + 1;
4776
+ }
4777
+ return {
4778
+ message,
4779
+ startIndex: start,
4780
+ startLine,
4781
+ startChar,
4782
+ endIndex: end,
4783
+ endLine,
4784
+ endChar: end - lastLineStart
4785
+ };
4786
+ }
4787
+ function serializeChildren(nodes, context) {
4788
+ const result = [];
4789
+ for (const node of nodes) {
4790
+ const serialized = serializeNode(node, context);
4791
+ if (serialized !== void 0) result.push(serialized);
4792
+ }
4793
+ return result;
4794
+ }
4795
+ function serializeNode(node, context) {
4796
+ if (isTextNode(node)) return serializeText(node, context);
4797
+ if (isControlNode(node)) return serializeControl(node, context);
4798
+ if (node.type === "comment") return;
4799
+ if (isComponentNode(node)) return serializeComponent(node, context);
4800
+ if (isSpecialNode(node)) {
4801
+ if (node.tagName === "slot") return serializeSlotElement(node, context);
4802
+ context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4803
+ return;
4804
+ }
4805
+ return serializeElement(node, context);
4806
+ }
4807
+ /** Component attributes: static values and fully-reactive expressions only. */
4808
+ function serializeComponentProps(node, context) {
4809
+ const attributes = [];
4810
+ let needsClass = node.scopeStyles === true && context.styleHash !== "";
4811
+ for (const attribute of node.attributes) {
4812
+ const { name, value, fullyReactive, reactive } = attribute;
4813
+ if (name.startsWith("on") || name.startsWith(":on")) continue;
4814
+ if (name.startsWith("&")) {
4815
+ context.report(`Bindings ("${name}") aren't supported on components in restricted mode.`, attribute.span.start, attribute.span.end);
4816
+ continue;
4817
+ }
4818
+ if (name.startsWith(":")) {
4819
+ context.report(`Directives ("${name}") aren't supported on components in restricted mode.`, attribute.span.start, attribute.span.end);
4820
+ continue;
4821
+ }
4822
+ if (value === void 0) {
4823
+ attributes.push({ name });
4824
+ continue;
4825
+ }
4826
+ if (fullyReactive) {
4827
+ const expr = parseExprAt(value, attribute.span.start, context);
4828
+ if (name === "class" && needsClass) {
4829
+ attributes.push({
4830
+ name,
4831
+ expr,
4832
+ scoped: `torp-${context.styleHash}`
4833
+ });
4834
+ needsClass = false;
4835
+ } else attributes.push({
4836
+ name,
4837
+ expr
4838
+ });
4839
+ } else if (reactive) context.report(`Mixed static/dynamic prop values aren't supported in restricted mode; compute the whole "${name}" value with an expression.`, attribute.span.start, attribute.span.end);
4840
+ else {
4841
+ const literal = trimQuotes(value);
4842
+ if (name === "class" && needsClass) {
4843
+ attributes.push({
4844
+ name,
4845
+ value: literal,
4846
+ scoped: `torp-${context.styleHash}`
4847
+ });
4848
+ needsClass = false;
4849
+ } else attributes.push({
4850
+ name,
4851
+ value: literal
4852
+ });
4853
+ }
4854
+ }
4855
+ return attributes;
4856
+ }
4857
+ /**
4858
+ * Component children are slot fills: loose children become the default fill
4859
+ * (`_`) and `<fill name="x">` children become named fills. Fill children may
4860
+ * read `$slot.<name>` for the slot props the host component passes; other
4861
+ * attributes on fills aren't supported.
4862
+ */
4863
+ function serializeComponent(node, context) {
4864
+ const fills = [];
4865
+ const defaultFill = [];
4866
+ const fillContext = {
4867
+ ...context,
4868
+ allowedRefs: /* @__PURE__ */ new Set([...context.allowedRefs, "$slot"]),
4869
+ elementStack: []
4870
+ };
4871
+ for (const child of node.children) if (isFill(child)) {
4872
+ if (child.attributes.filter((attribute) => attribute.name !== "name").length > 0) {
4873
+ context.report(`Unexpected attributes on <fill>. Slot props are read as $slot.<name> inside the fill; only "name" is allowed here.`, child.span.start, child.span.end);
4874
+ continue;
4875
+ }
4876
+ const nameAttribute = child.attributes.find((attribute) => attribute.name === "name");
4877
+ const name = nameAttribute ? trimQuotes(nameAttribute.value ?? "") || "_" : "_";
4878
+ fills.push({
4879
+ name,
4880
+ children: serializeChildren(child.children, fillContext)
4881
+ });
4882
+ } else if (isTextNode(child) && child.content.trim() === "") continue;
4883
+ else {
4884
+ const serialized = serializeNode(child, fillContext);
4885
+ if (serialized !== void 0) defaultFill.push(serialized);
4886
+ }
4887
+ if (defaultFill.length > 0) fills.unshift({
4888
+ name: "_",
4889
+ children: defaultFill
4890
+ });
4891
+ return {
4892
+ t: "component",
4893
+ name: node.tagName,
4894
+ props: serializeComponentProps(node, context),
4895
+ fills
4896
+ };
4897
+ }
4898
+ function isFill(node) {
4899
+ return isSpecialNode(node) && (node.tagName === "fill" || node.tagName === "filldef");
4900
+ }
4901
+ /** `<slot name="…">fallback</slot>` in a restricted template. Slot props
4902
+ * (`<slot item={row}/>` — anything but `name`) are evaluated in the
4903
+ * artifact's scope and passed to the incoming slot render, matching the JS
4904
+ * server build. */
4905
+ function serializeSlotElement(node, context) {
4906
+ const nameAttribute = node.attributes.find((attribute) => attribute.name === "name");
4907
+ const name = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
4908
+ const props = [];
4909
+ for (const attribute of node.attributes) {
4910
+ const { name: propName, value, fullyReactive, reactive } = attribute;
4911
+ if (propName === "name") continue;
4912
+ if (propName.startsWith("on") || propName.startsWith(":on")) continue;
4913
+ if (propName.startsWith("&")) {
4914
+ context.report(`Bindings ("${propName}") aren't supported on slot elements in restricted mode.`, attribute.span.start, attribute.span.end);
4915
+ continue;
4916
+ }
4917
+ if (propName.startsWith(":")) {
4918
+ context.report(`Directives ("${propName}") aren't supported on slot elements in restricted mode.`, attribute.span.start, attribute.span.end);
4919
+ continue;
4920
+ }
4921
+ if (value === void 0) {
4922
+ props.push({ name: propName });
4923
+ continue;
4924
+ }
4925
+ if (fullyReactive) props.push({
4926
+ name: propName,
4927
+ expr: parseExprAt(value, attribute.span.start, context)
4928
+ });
4929
+ else if (reactive) context.report(`Mixed static/dynamic slot prop values aren't supported in restricted mode; compute the whole "${propName}" value with an expression.`, attribute.span.start, attribute.span.end);
4930
+ else props.push({
4931
+ name: propName,
4932
+ value: trimQuotes(value)
4933
+ });
4934
+ }
4935
+ const autoClose = context.elementStack.filter((tag) => require_slotAutoClose.AUTO_CLOSEABLE.has(tag));
4936
+ const fallbackTag = firstFallbackTag(node.children);
4937
+ if (fallbackTag !== void 0 && require_slotAutoClose.closesAncestor(fallbackTag, context.elementStack)) {
4938
+ const ancestor = [...context.elementStack].reverse().find((ancestor) => require_slotAutoClose.closesAncestor(fallbackTag, [ancestor]));
4939
+ context.report(`Slot fallback starts with <${fallbackTag}>, which auto-closes the enclosing <${ancestor}>: ` + require_slotAutoClose.autoCloseMessage(fallbackTag, ancestor), node.span.start, node.span.end);
4940
+ }
4941
+ const children = [];
4942
+ for (const child of node.children) if (isFill(child)) children.push(...serializeChildren(child.children, context));
4943
+ else {
4944
+ const serialized = serializeNode(child, context);
4945
+ if (serialized !== void 0) children.push(serialized);
4946
+ }
4947
+ const slot = {
4948
+ t: "slot",
4949
+ name,
4950
+ props,
4951
+ children
4952
+ };
4953
+ if (autoClose.length > 0) slot.autoClose = autoClose;
4954
+ return slot;
4955
+ }
4956
+ /** The tag of the first meaningful child (skipping whitespace text). */
4957
+ function firstFallbackTag(children) {
4958
+ for (const child of children) {
4959
+ if (isFill(child)) return firstFallbackTag(child.children);
4960
+ if (isTextNode(child)) {
4961
+ if (child.content.trim() === "") continue;
4962
+ return;
4963
+ }
4964
+ if (child.type === "element") return child.tagName;
4965
+ return;
4966
+ }
4967
+ }
4968
+ function serializeElement(node, context) {
4969
+ if (node.type === "component") {
4970
+ context.report(`Nested components ("<${node.tagName}>") aren't supported in restricted mode yet. Inline the markup, or render it client-side.`, node.span.start, node.span.end);
4971
+ return;
4972
+ }
4973
+ if (node.type === "special") {
4974
+ context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4975
+ return;
4976
+ }
4977
+ const childContext = node.tagName === "pre" || node.tagName === "code" ? {
4978
+ ...context,
4979
+ preserveWhitespace: true
4980
+ } : context;
4981
+ if (!voidTags.includes(node.tagName)) childContext.elementStack.push(node.tagName);
4982
+ const children = voidTags.includes(node.tagName) ? [] : serializeChildren(node.children, childContext);
4983
+ if (!voidTags.includes(node.tagName)) childContext.elementStack.pop();
4984
+ return {
4985
+ t: "el",
4986
+ tag: node.tagName,
4987
+ attrs: serializeAttributes(node, context),
4988
+ children
4989
+ };
4990
+ }
4991
+ function serializeAttributes(node, context) {
4992
+ const attributes = [];
4993
+ let needsClass = node.scopeStyles === true && context.styleHash !== "";
4994
+ for (const attribute of node.attributes) {
4995
+ const { name, value, fullyReactive, reactive } = attribute;
4996
+ if (name === "self" && node.tagName === "@element") continue;
4997
+ if (name === "&ref") continue;
4998
+ if (name.startsWith("on") || name.startsWith(":on")) continue;
4999
+ if (name.startsWith("transition")) continue;
5000
+ if (name.startsWith("&")) {
5001
+ context.report(`Form bindings ("${name}") aren't supported in restricted mode yet; use ${name.substring(1)}={…} instead.`, attribute.span.start, attribute.span.end);
5002
+ continue;
5003
+ }
5004
+ if (name.startsWith(":")) {
5005
+ context.report(`Directives ("${name}") aren't supported in restricted mode yet.`, attribute.span.start, attribute.span.end);
5006
+ continue;
5007
+ }
5008
+ if (value === void 0) {
5009
+ if (name === "class" && needsClass) {
5010
+ attributes.push({
5011
+ name: "class",
5012
+ value: `torp-${context.styleHash}`
5013
+ });
5014
+ needsClass = false;
5015
+ } else attributes.push({ name });
5016
+ continue;
5017
+ }
5018
+ if (fullyReactive) {
5019
+ const expr = parseExprAt(value, attribute.span.start, context);
5020
+ if (name === "class") {
5021
+ attributes.push({
5022
+ name,
5023
+ expr,
5024
+ format: "class",
5025
+ scoped: needsClass ? `torp-${context.styleHash}` : void 0
5026
+ });
5027
+ needsClass = false;
5028
+ } else if (name === "style") attributes.push({
5029
+ name,
5030
+ expr,
5031
+ format: "style"
5032
+ });
5033
+ else attributes.push({
5034
+ name,
5035
+ expr,
5036
+ format: "attr"
5037
+ });
5038
+ } else if (reactive) context.report(`Mixed static/dynamic attribute values aren't supported in restricted mode; compute the whole "${name}" value with an expression.`, attribute.span.start, attribute.span.end);
5039
+ else {
5040
+ let literal = trimQuotes(value);
5041
+ if (name === "class" && needsClass) {
5042
+ literal = literal ? `${literal} torp-${context.styleHash}` : `torp-${context.styleHash}`;
5043
+ needsClass = false;
5044
+ }
5045
+ attributes.push({
5046
+ name,
5047
+ value: literal
5048
+ });
5049
+ }
5050
+ }
5051
+ if (needsClass) attributes.push({
5052
+ name: "class",
5053
+ value: `torp-${context.styleHash}`
5054
+ });
5055
+ return attributes;
5056
+ }
5057
+ function serializeText(node, context) {
5058
+ const parts = [];
5059
+ const pushLiteral = (literal) => {
5060
+ const collapsed = context.preserveWhitespace ? literal : literal.replace(/\s+/g, " ");
5061
+ if (collapsed.length === 0) return;
5062
+ const last = parts[parts.length - 1];
5063
+ if (typeof last === "string") parts[parts.length - 1] = last + collapsed;
5064
+ else parts.push(collapsed);
5065
+ };
5066
+ if (node.spans.length === 0 || node.start === void 0) pushLiteral(node.content);
5067
+ else {
5068
+ const start = node.start;
5069
+ let cursor = 0;
5070
+ for (const span of node.spans) {
5071
+ const literalEnd = span.start - start - 1;
5072
+ pushLiteral(node.content.substring(cursor, literalEnd));
5073
+ parts.push(parseExprAt(context.source.substring(span.start, span.end), span.start, context));
5074
+ cursor = span.end - start + 1;
5075
+ }
5076
+ pushLiteral(node.content.substring(cursor));
5077
+ }
5078
+ if (parts.length === 0) return void 0;
5079
+ return {
5080
+ t: "text",
5081
+ parts
5082
+ };
5083
+ }
5084
+ function serializeControl(node, context) {
5085
+ if (node.operation === "@if group") return {
5086
+ t: "if",
5087
+ branches: node.children.filter(isControlNode).map((branch) => {
5088
+ if (branch.operation === "@else") return { children: serializeChildren(branch.children, context) };
5089
+ const statement = branch.statement;
5090
+ const open = statement.indexOf("(");
5091
+ if (open === -1) {
5092
+ context.report(`Malformed ${branch.operation} statement.`, branch.span.start, branch.span.end);
5093
+ return {
5094
+ test: {
5095
+ op: "lit",
5096
+ value: null
5097
+ },
5098
+ children: []
5099
+ };
5100
+ }
5101
+ const { inner, innerStart } = extractBalanced(statement, open, branch, context);
5102
+ return {
5103
+ test: parseExprAt(inner, branch.span.start + innerStart, context),
5104
+ children: serializeChildren(branch.children, context)
5105
+ };
5106
+ })
5107
+ };
5108
+ if (node.operation === "@for group") {
5109
+ const forNode = node.children.find((child) => isControlNode(child) && child.operation === "@for");
5110
+ if (!forNode) {
5111
+ context.report("Malformed @for block.", node.span.start, node.span.end);
5112
+ return;
5113
+ }
5114
+ const open = forNode.statement.indexOf("(");
5115
+ if (open === -1) {
5116
+ context.report("Malformed @for statement.", forNode.span.start, forNode.span.end);
5117
+ return;
5118
+ }
5119
+ const { inner, innerStart } = extractBalanced(forNode.statement, open, forNode, context);
5120
+ const match = /^\s*(?:(?:let|const|var)\s+)?([A-Za-z_$][\w$]*)\s+(of|in)\s+([\s\S]+)$/.exec(inner);
5121
+ if (!match) {
5122
+ context.report("Only `@for (item of list)` is supported in restricted mode yet (no destructuring, index variables, or C-style loops).", forNode.span.start, forNode.span.end);
5123
+ return;
5124
+ }
5125
+ if (match[2] === "in") {
5126
+ context.report("`in` loops aren't supported in restricted mode; use `of`.", forNode.span.start, forNode.span.end);
5127
+ return;
5128
+ }
5129
+ const item = match[1];
5130
+ const listSource = match[3].trim();
5131
+ const listIndex = inner.lastIndexOf(listSource);
5132
+ const list = parseExprAt(listSource, forNode.span.start + innerStart + listIndex, context);
5133
+ const keyNode = forNode.children.find((child) => isControlNode(child) && child.operation === "@key");
5134
+ let key;
5135
+ if (keyNode) {
5136
+ const keyContext = {
5137
+ ...context,
5138
+ loopVars: [...context.loopVars, item]
5139
+ };
5140
+ const equal = keyNode.statement.indexOf("=");
5141
+ const keySource = keyNode.statement.substring(equal + 1).replace(/;\s*$/, "").trim();
5142
+ key = parseExprAt(keySource, keyNode.span.start + keyNode.statement.indexOf(keySource), keyContext);
5143
+ }
5144
+ const childContext = {
5145
+ ...context,
5146
+ loopVars: [...context.loopVars, item]
5147
+ };
5148
+ return {
5149
+ t: "for",
5150
+ item,
5151
+ list,
5152
+ key,
5153
+ children: serializeChildren(forNode.children.filter((child) => !(isControlNode(child) && child.operation === "@key")), childContext)
5154
+ };
5155
+ }
5156
+ context.report(`"${node.operation}" isn't supported in restricted mode yet.`, controlSpan(node).start, controlSpan(node).end);
5157
+ }
5158
+ /** Group nodes (`@if group`, `@html group`…) carry zero spans; their first
5159
+ * control child has the real source span. */
5160
+ function controlSpan(node) {
5161
+ if (node.span.start === 0 && node.span.end === 0) {
5162
+ const child = node.children.find(isControlNode);
5163
+ if (child) return child.span;
5164
+ }
5165
+ return node.span;
5166
+ }
5167
+ /**
5168
+ * Extracts the text between `source[open]` and its matching `)`, skipping
5169
+ * strings and comments. `innerStart` is the index just after the `(`.
5170
+ */
5171
+ function extractBalanced(source, open, node, context) {
5172
+ let level = 0;
5173
+ for (let i = open; i < source.length; i++) {
5174
+ const skipped = skipStringOrComment(source, i);
5175
+ if (skipped !== -1) {
5176
+ i = skipped - 1;
5177
+ continue;
5178
+ }
5179
+ if (source[i] === "(") level += 1;
5180
+ else if (source[i] === ")") {
5181
+ level -= 1;
5182
+ if (level === 0) return {
5183
+ inner: source.substring(open + 1, i),
5184
+ innerStart: open + 1
5185
+ };
5186
+ }
5187
+ }
5188
+ context.report("Unbalanced parentheses in a control statement.", node.span.start, node.span.end);
5189
+ return {
5190
+ inner: source.substring(open + 1),
5191
+ innerStart: open + 1
5192
+ };
5193
+ }
5194
+ function parseExprAt(source, offset, context) {
5195
+ try {
5196
+ const expr = parseExpression(source, offset);
5197
+ validateRefs(expr, context.allowedRefs, context, offset, "template");
5198
+ return expr;
5199
+ } catch (error) {
5200
+ if (error instanceof RestrictedSyntaxError) {
5201
+ context.report(error.message, error.start, error.end);
5202
+ return {
5203
+ op: "lit",
5204
+ value: null
5205
+ };
5206
+ }
5207
+ throw error;
5208
+ }
5209
+ }
5210
+ /**
5211
+ * Validates that every identifier reference in a serialized expression is
5212
+ * available in the scope the interpreter will run it with -- so typos and
5213
+ * unknown roots are compile errors instead of render errors.
5214
+ */
5215
+ function validateRefs(expr, allowed, context, start, where, loopVars = context.loopVars) {
5216
+ switch (expr.op) {
5217
+ case "ref":
5218
+ if (!allowed.has(expr.name) && !loopVars.includes(expr.name)) {
5219
+ const available = [...allowed, ...loopVars].join(", ");
5220
+ context.report(`Unknown identifier "${expr.name}" in ${where}. Available: ${available || "(none)"}.`, start, start + expr.name.length + 2);
5221
+ }
5222
+ return;
5223
+ case "get":
5224
+ validateRefs(expr.object, allowed, context, start, where, loopVars);
5225
+ return;
5226
+ case "index":
5227
+ validateRefs(expr.object, allowed, context, start, where, loopVars);
5228
+ validateRefs(expr.index, allowed, context, start, where, loopVars);
5229
+ return;
5230
+ case "unary":
5231
+ validateRefs(expr.operand, allowed, context, start, where, loopVars);
5232
+ return;
5233
+ case "binary":
5234
+ validateRefs(expr.left, allowed, context, start, where, loopVars);
5235
+ validateRefs(expr.right, allowed, context, start, where, loopVars);
5236
+ return;
5237
+ case "ternary":
5238
+ validateRefs(expr.test, allowed, context, start, where, loopVars);
5239
+ validateRefs(expr.consequent, allowed, context, start, where, loopVars);
5240
+ validateRefs(expr.alternate, allowed, context, start, where, loopVars);
5241
+ return;
5242
+ case "array":
5243
+ for (const item of expr.items) validateRefs(item, allowed, context, start, where, loopVars);
5244
+ return;
5245
+ case "object":
5246
+ for (const value of Object.values(expr.entries)) validateRefs(value, allowed, context, start, where, loopVars);
5247
+ return;
5248
+ }
5249
+ }
3855
5250
  //#endregion
3856
5251
  //#region src/compile/buildType.ts
3857
5252
  /**
@@ -4245,12 +5640,14 @@ function parseText(status, element) {
4245
5640
  if (content || spaceContent) {
4246
5641
  const previousNode = element.children[element.children.length - 1];
4247
5642
  if (previousNode && isTextNode(previousNode)) {
5643
+ if (previousNode.start === void 0) previousNode.start = start - previousNode.content.length;
4248
5644
  previousNode.content += content + spaceContent;
4249
5645
  previousNode.spans.push(...spans);
4250
5646
  } else {
4251
5647
  const text = {
4252
5648
  type: "text",
4253
5649
  content: content + spaceContent,
5650
+ start,
4254
5651
  spans
4255
5652
  };
4256
5653
  element.children.push(text);
@@ -5327,39 +6724,6 @@ function getPropsUsage(source, ranges) {
5327
6724
  }
5328
6725
  return props.length ? props : void 0;
5329
6726
  }
5330
- /**
5331
- * Gets the `$context` names that the compiled output references. The input is
5332
- * the component's code-only text (script plus markup expressions), with
5333
- * `ranges` marking the positions that are code — matches that start inside a
5334
- * string, comment or regex literal are ignored, so mentions inside
5335
- * sample-code strings or prose don't count.
5336
- */
5337
- function getContextUsage(source, ranges) {
5338
- const contextsMatches = source.matchAll(/\$context\??\s*(?:\.([\d\w]+)|\[([^\]]+)\])/g);
5339
- const contexts = [];
5340
- for (let match of contextsMatches) {
5341
- if (!isInCode(ranges, match.index)) continue;
5342
- const name = trimQuotes(match[1] || match[2]);
5343
- if (!contexts.includes(name)) contexts.push(name);
5344
- }
5345
- if (!contexts.length) for (let match of source.matchAll(/(?<![\w$])\$context(?![\w])(?!\s*:)(?!<)/g)) {
5346
- if (!isInCode(ranges, match.index)) continue;
5347
- contexts.push("$context");
5348
- break;
5349
- }
5350
- return contexts.length ? contexts : void 0;
5351
- }
5352
- /**
5353
- * Returns true if `index` falls inside one of the (sorted, non-overlapping)
5354
- * code ranges — i.e. not inside a string, comment or regex literal.
5355
- */
5356
- function isInCode(ranges, index) {
5357
- for (const [start, end] of ranges) {
5358
- if (index >= start && index < end) return true;
5359
- if (index < start) return false;
5360
- }
5361
- return false;
5362
- }
5363
6727
  function consumeScriptComments(status) {
5364
6728
  const skipped = skipStringOrComment(status.source, status.i);
5365
6729
  if (skipped !== -1) {
@@ -5382,6 +6746,31 @@ function parse(source) {
5382
6746
  return parseCode(source);
5383
6747
  }
5384
6748
  //#endregion
6749
+ //#region src/compile/parse/bindDataTemplate.ts
6750
+ /**
6751
+ * Binds `$data` in a parsed template whose requirements come from an app
6752
+ * manifest (see `@torpor/embed/app`): inserts the `let $data = …` chunk
6753
+ * after the start-marker chunk and keeps `$props` from being renamed as an
6754
+ * unused param. Without it, builds reference an undeclared `$data`.
6755
+ */
6756
+ function bindDataTemplate(template) {
6757
+ for (let i = 0; i < template.script.length; i++) if (template.script[i].script === "/* @start */") {
6758
+ template.script.splice(i + 1, 0, {
6759
+ script: " let $data = $props?.$data ?? {};",
6760
+ span: {
6761
+ start: 0,
6762
+ end: 0
6763
+ }
6764
+ });
6765
+ i += 1;
6766
+ }
6767
+ for (const component of template.components) if (!component.props?.length) component.props = ["$data"];
6768
+ }
6769
+ //#endregion
6770
+ exports.RestrictedSyntaxError = RestrictedSyntaxError;
6771
+ exports.bindDataTemplate = bindDataTemplate;
5385
6772
  exports.build = build;
6773
+ exports.buildRestricted = buildRestricted;
5386
6774
  exports.buildType = buildType;
5387
6775
  exports.parse = parse;
6776
+ exports.parseExpressionPrefix = parseExpressionPrefix;