@torpor/view 1.3.3 → 1.4.1

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 (60) hide show
  1. package/dist/{Effect-Bp-BIDDm.d.cts → Effect-Bi_nt6cx.d.cts} +16 -3
  2. package/dist/Effect-Bi_nt6cx.d.cts.map +1 -0
  3. package/dist/{Effect-VsIY2vPx.d.mts → Effect-Bi_nt6cx.d.mts} +16 -3
  4. package/dist/Effect-Bi_nt6cx.d.mts.map +1 -0
  5. package/dist/ListItemSpec-DFkYr2TE.d.cts +28 -0
  6. package/dist/ListItemSpec-DFkYr2TE.d.cts.map +1 -0
  7. package/dist/ListItemSpec-DFkYr2TE.d.mts +28 -0
  8. package/dist/ListItemSpec-DFkYr2TE.d.mts.map +1 -0
  9. package/dist/{AsyncOptions-BDtArmeL.d.mts → WatchOptions--xq-Gn4e.d.cts} +77 -4
  10. package/dist/WatchOptions--xq-Gn4e.d.cts.map +1 -0
  11. package/dist/{AsyncOptions-C_7mWR6F.d.cts → WatchOptions-DWF4EqB6.d.mts} +77 -4
  12. package/dist/WatchOptions-DWF4EqB6.d.mts.map +1 -0
  13. package/dist/compile.cjs +1399 -406
  14. package/dist/compile.d.cts +26 -12
  15. package/dist/compile.d.cts.map +1 -1
  16. package/dist/compile.d.mts +26 -12
  17. package/dist/compile.d.mts.map +1 -1
  18. package/dist/compile.mjs +1399 -406
  19. package/dist/compile.mjs.map +1 -1
  20. package/dist/dev.cjs +101 -51
  21. package/dist/dev.d.cts +33 -2
  22. package/dist/dev.d.cts.map +1 -1
  23. package/dist/dev.d.mts +33 -2
  24. package/dist/dev.d.mts.map +1 -1
  25. package/dist/dev.mjs +51 -2
  26. package/dist/dev.mjs.map +1 -1
  27. package/dist/{fromWebSocket-ERhd9KZR.mjs → fromWebSocket-B22DIys7.mjs} +11 -2
  28. package/dist/fromWebSocket-B22DIys7.mjs.map +1 -0
  29. package/dist/{fromWebSocket-Cdoghvmh.cjs → fromWebSocket-C56rkQpZ.cjs} +15 -0
  30. package/dist/index.cjs +605 -266
  31. package/dist/index.d.cts +36 -129
  32. package/dist/index.d.cts.map +1 -1
  33. package/dist/index.d.mts +36 -129
  34. package/dist/index.d.mts.map +1 -1
  35. package/dist/index.mjs +593 -255
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/runtime.iife.js +1 -1
  38. package/dist/ssr.cjs +122 -22
  39. package/dist/ssr.d.cts +46 -12
  40. package/dist/ssr.d.cts.map +1 -1
  41. package/dist/ssr.d.mts +46 -12
  42. package/dist/ssr.d.mts.map +1 -1
  43. package/dist/ssr.mjs +121 -23
  44. package/dist/ssr.mjs.map +1 -1
  45. package/dist/titleWarning-BMjLAXpn.mjs +72 -0
  46. package/dist/titleWarning-BMjLAXpn.mjs.map +1 -0
  47. package/dist/titleWarning-DXp4fK7q.cjs +87 -0
  48. package/package.json +2 -1
  49. package/dist/AsyncOptions-BDtArmeL.d.mts.map +0 -1
  50. package/dist/AsyncOptions-C_7mWR6F.d.cts.map +0 -1
  51. package/dist/Cleanup-D0wvGW5d.d.cts +0 -9
  52. package/dist/Cleanup-D0wvGW5d.d.cts.map +0 -1
  53. package/dist/Cleanup-D0wvGW5d.d.mts +0 -9
  54. package/dist/Cleanup-D0wvGW5d.d.mts.map +0 -1
  55. package/dist/Effect-Bp-BIDDm.d.cts.map +0 -1
  56. package/dist/Effect-VsIY2vPx.d.mts.map +0 -1
  57. package/dist/devContext-BulTn3U5.cjs +0 -27
  58. package/dist/devContext-ZNsPyOgB.mjs +0 -24
  59. package/dist/devContext-ZNsPyOgB.mjs.map +0 -1
  60. package/dist/fromWebSocket-ERhd9KZR.mjs.map +0 -1
package/dist/compile.cjs CHANGED
@@ -513,6 +513,65 @@ function hydrationBranchComment(index) {
513
513
  return `<!^${index}>`;
514
514
  }
515
515
  //#endregion
516
+ //#region src/compile/utils/escapeRawText.ts
517
+ /**
518
+ * Escapes raw-text content for inclusion in a generated template literal.
519
+ *
520
+ * Whitespace that would be altered by fragment-text whitespace collapsing is
521
+ * escaped (`\n`, `\t`, `\x20` for runs of spaces), so raw content round-trips
522
+ * exactly -- including line breaks and indentation inside scripts. Backticks
523
+ * and `${` are escaped so the literal doesn't terminate or interpolate, and
524
+ * backslashes are escaped so JavaScript escapes in the source text (e.g.
525
+ * `"\n"` inside an inline script) aren't consumed by the template literal.
526
+ */
527
+ function escapeRawText(text) {
528
+ let result = "";
529
+ for (let i = 0; i < text.length; i++) {
530
+ const char = text[i];
531
+ if (char === "\\") result += "\\\\";
532
+ else if (char === "`") result += "\\x60";
533
+ else if (char === " ") {
534
+ let end = i + 1;
535
+ while (text[end] === " ") end++;
536
+ if (end - i > 1) {
537
+ result += "\\x20".repeat(end - i);
538
+ i = end - 1;
539
+ } else result += " ";
540
+ } else if (/\s/.test(char)) result += whitespaceEscape(char);
541
+ else if (char === "$" && text[i + 1] === "{") result += "\\x24";
542
+ else result += char;
543
+ }
544
+ return result;
545
+ }
546
+ function whitespaceEscape(char) {
547
+ switch (char) {
548
+ case "\n": return "\\n";
549
+ case "\r": return "\\r";
550
+ case " ": return "\\t";
551
+ case "\f": return "\\f";
552
+ case "\v": return "\\v";
553
+ default: return `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`;
554
+ }
555
+ }
556
+ //#endregion
557
+ //#region src/compile/utils/escapeTemplateText.ts
558
+ /**
559
+ * Escapes text for inclusion in a generated template literal: backslashes,
560
+ * backticks and `${` are all written as escapes so the text round-trips
561
+ * literally instead of ending the literal or starting an interpolation.
562
+ */
563
+ function escapeTemplateText(text) {
564
+ let result = "";
565
+ for (let i = 0; i < text.length; i++) {
566
+ const char = text[i];
567
+ if (char === "\\") result += "\\\\";
568
+ else if (char === "`") result += "\\x60";
569
+ else if (char === "$" && text[i + 1] === "{") result += "\\x24";
570
+ else result += char;
571
+ }
572
+ return result;
573
+ }
574
+ //#endregion
516
575
  //#region src/compile/utils/isControlNode.ts
517
576
  function isControlNode(node) {
518
577
  return node.type === "control";
@@ -575,16 +634,60 @@ function getSingleElementRoot(children) {
575
634
  return renderingRoot;
576
635
  }
577
636
  //#endregion
637
+ //#region src/compile/utils/interpolation.ts
638
+ /**
639
+ * Finds the `}` that closes the interpolation starting at the `{` at `start`,
640
+ * skipping braces inside strings, template strings, comments and regex
641
+ * literals. Returns -1 when the interpolation is not closed.
642
+ */
643
+ function findMatchingBrace(text, start) {
644
+ let level = 0;
645
+ for (let i = start; i < text.length; i++) {
646
+ const char = text[i];
647
+ if (char === "{") level += 1;
648
+ else if (char === "}") {
649
+ level -= 1;
650
+ if (level === 0) return i;
651
+ } else {
652
+ const skipped = skipStringOrComment(text, i);
653
+ if (skipped !== -1) i = skipped - 1;
654
+ }
655
+ }
656
+ return -1;
657
+ }
658
+ /**
659
+ * Whether template text contains a complete `{...}` interpolation. Braces
660
+ * inside the expression's strings, comments and regex literals aren't counted
661
+ * as delimiters.
662
+ */
663
+ function hasInterpolation(text) {
664
+ for (let i = 0; i < text.length; i++) {
665
+ if (text[i] !== "{") continue;
666
+ return findMatchingBrace(text, i) !== -1;
667
+ }
668
+ return false;
669
+ }
670
+ /**
671
+ * Whether the supplied text is exactly one `{...}` interpolation (ignoring
672
+ * surrounding whitespace).
673
+ */
674
+ function isSingleInterpolation(text) {
675
+ const trimmed = text.trim();
676
+ if (!trimmed.startsWith("{")) return false;
677
+ return findMatchingBrace(trimmed, 0) === trimmed.length - 1;
678
+ }
679
+ //#endregion
578
680
  //#region src/compile/utils/isReactive.ts
579
681
  /**
580
- * Checks whether the supplied string is fully or partially reactive (i.e. contains braces)
682
+ * Checks whether the supplied text contains a `{...}` interpolation. Braces
683
+ * inside the expression's strings and comments don't count as delimiters.
581
684
  *
582
- * @param text The string to check
685
+ * @param text The text to check
583
686
  *
584
- * @returns True if the supplied string is fully or partially reactive
687
+ * @returns True if the supplied text is fully or partially reactive
585
688
  */
586
689
  function isReactive(text) {
587
- return text.includes("{") && text.includes("}");
690
+ return hasInterpolation(text);
588
691
  }
589
692
  //#endregion
590
693
  //#region src/compile/utils/trimQuotes.ts
@@ -654,8 +757,11 @@ function buildNodeFragmentText(node, status, fragments, currentFragment) {
654
757
  break;
655
758
  }
656
759
  case "text": {
657
- const content = node.content;
658
- if (currentFragment) currentFragment.text += isReactive(content) ? "#" : content;
760
+ const textNode = node;
761
+ if (currentFragment) {
762
+ if (textNode.raw) currentFragment.text += escapeRawText(textNode.content);
763
+ else currentFragment.text += isReactive(textNode.content) ? "#" : textNode.content;
764
+ }
659
765
  break;
660
766
  }
661
767
  case "special": buildSpecialFragmentText(node, status, fragments, currentFragment);
@@ -730,9 +836,9 @@ function buildElementFragmentText(node, status, fragments, currentFragment) {
730
836
  if (a.name.startsWith("data-")) return `${a.name}=""`;
731
837
  } else if (a.name === "class" && node.scopeStyles) {
732
838
  needsClass = false;
733
- let value = a.value ? `"${trimQuotes(a.value)} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
839
+ let value = a.value ? `"${escapeTemplateText(trimQuotes(a.value))} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
734
840
  return `${a.name}=${value}`;
735
- } else return `${a.name}${a.value != null ? `=${a.value}` : ""}`;
841
+ } else return `${a.name}${a.value != null ? `=${escapeTemplateText(a.value)}` : ""}`;
736
842
  }).filter(Boolean).join(" ");
737
843
  if (attributesText) currentFragment.text += " " + attributesText;
738
844
  if (needsClass) currentFragment.text += ` class="torp-${status.styleHash}"`;
@@ -968,7 +1074,7 @@ function containsIdentifier(value, name) {
968
1074
  * effect to the loop variable's signal).
969
1075
  */
970
1076
  function forVarBindings(status, source) {
971
- return collectBindings(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
1077
+ return collectBindings$1(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
972
1078
  }
973
1079
  /**
974
1080
  * Like `forVarBindings`, but binds only the loop variables named in `names`.
@@ -976,9 +1082,10 @@ function forVarBindings(status, source) {
976
1082
  * the scope's directly-evaluated code reads.
977
1083
  */
978
1084
  function forVarBindingsFor(status, names) {
979
- return collectBindings(status, (forVar) => names.has(forVar.name));
1085
+ return collectBindings$1(status, (forVar) => names.has(forVar.name));
980
1086
  }
981
- function collectBindings(status, include) {
1087
+ function collectBindings$1(status, include) {
1088
+ if (status.options.check === true) return "";
982
1089
  const bound = /* @__PURE__ */ new Set();
983
1090
  let result = "";
984
1091
  for (let i = status.forVars.length - 1; i >= 0; i--) {
@@ -1096,7 +1203,8 @@ function buildAddFragment(node, status, b, parentName, anchorName) {
1096
1203
  const fragment = node.fragment;
1097
1204
  const fragmentName = `t_fragment_${fragment.number}`;
1098
1205
  if (fragment.effects.length > 0) {
1099
- status.imports.add("$run");
1206
+ const check = status.options.check === true;
1207
+ if (!check) status.imports.add("$run");
1100
1208
  let forVarMask;
1101
1209
  for (let effect of fragment.effects) if (effect.forVarMask !== void 0) {
1102
1210
  if (forVarMask === void 0) forVarMask = 0;
@@ -1104,11 +1212,11 @@ function buildAddFragment(node, status, b, parentName, anchorName) {
1104
1212
  }
1105
1213
  let trailing = "";
1106
1214
  if (forVarMask !== void 0) trailing = `, undefined, { forVarMask: ${forVarMask} }`;
1107
- b.append("$run(() => {");
1215
+ b.append(check ? "(() => {" : "$run(() => {");
1108
1216
  appendForVarBindings(b, status, fragment.effects.map((e) => e.functionBody).join("\n"));
1109
1217
  if (status.options.mapped === true) for (let effect of fragment.effects) addMappedTextWithOffsets("", effect.functionBody, "", effect.spans, effect.offsets, effect.lengths, status, b);
1110
1218
  else b.append(fragment.effects.map((e) => e.functionBody).join("\n"));
1111
- b.append(`}${status.options.dev === true ? `, "setAttributes"${trailing}` : trailing});`);
1219
+ b.append(check ? "})();" : `}${status.options.dev === true ? `, "setAttributes"${trailing}` : trailing});`);
1112
1220
  }
1113
1221
  if (fragment.singleRootElement) {
1114
1222
  status.imports.add("t_add_element");
@@ -1361,7 +1469,7 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1361
1469
  if (lastType === "text" || lastType === "space") return;
1362
1470
  let textPath = {
1363
1471
  parent: path,
1364
- type: isSpace(node.content) ? "space" : "text",
1472
+ type: !node.raw && isSpace(node.content) ? "space" : "text",
1365
1473
  children: []
1366
1474
  };
1367
1475
  path.children.push(textPath);
@@ -1381,11 +1489,12 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1381
1489
  } else {
1382
1490
  status.imports.add("t_txt");
1383
1491
  if (declareVariable) b.append(`(${node.varName} = t_txt(" ")),`);
1492
+ else if (node.raw) b.append(`t_txt(${JSON.stringify(node.content)}),`);
1384
1493
  else b.append(`t_txt("${node.content}"),`);
1385
1494
  }
1386
1495
  }
1387
1496
  function textNodeNeedsDeclaration(node, topLevel, lastChild) {
1388
- return isReactive(node.content) || topLevel && lastChild;
1497
+ return !node.raw && isReactive(node.content) || topLevel && lastChild;
1389
1498
  }
1390
1499
  function declareSpecialFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, lastChild, declare) {
1391
1500
  if (node.tagName === "slot") declareParentAndAnchorFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, "slot", declare);
@@ -1570,10 +1679,16 @@ function buildRun(functionName, functionBody, status, b) {
1570
1679
  trailing = `, "${functionName}"`;
1571
1680
  if (forVarMask !== void 0) trailing += `, { forVarMask: ${forVarMask} }`;
1572
1681
  } else if (forVarMask !== void 0) trailing = `, undefined, { forVarMask: ${forVarMask} }`;
1573
- status.imports.add("$run");
1574
- b.append("$run(() => {");
1575
- b.append(functionBody);
1576
- b.append(`}${trailing});`);
1682
+ if (status.options.check === true) {
1683
+ b.append("(() => {");
1684
+ b.append(functionBody);
1685
+ b.append("})();");
1686
+ } else {
1687
+ status.imports.add("$run");
1688
+ b.append("$run(() => {");
1689
+ b.append(functionBody);
1690
+ b.append(`}${trailing});`);
1691
+ }
1577
1692
  addPopDevBoundary(status, b);
1578
1693
  }
1579
1694
  //#endregion
@@ -1755,7 +1870,8 @@ function buildComponentNode(node, status, b, root = false) {
1755
1870
  slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>",
1756
1871
  fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"
1757
1872
  ];
1758
- b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = (\n${slotParams.join(",\n")}\n) => {`);
1873
+ const check = status.options.check === true;
1874
+ b.append(check ? `((\n${slotParams.join(",\n")}\n) => {` : `${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = (\n${slotParams.join(",\n")}\n) => {`);
1759
1875
  buildFragment(slot, status, b, "$sparent", "$sanchor");
1760
1876
  status.fragmentStack.push({
1761
1877
  fragment: slot.fragment,
@@ -1764,7 +1880,7 @@ function buildComponentNode(node, status, b, root = false) {
1764
1880
  for (let child of slot.children) buildNode(child, status, b, "$sparent", "$sanchor");
1765
1881
  status.fragmentStack.pop();
1766
1882
  buildAddFragment(slot, status, b, "$sparent", "$sanchor");
1767
- b.append(`}`);
1883
+ b.append(check ? "})(null!, null, {}, undefined);" : `}`);
1768
1884
  }
1769
1885
  }
1770
1886
  let renderParams = `${node.parentName}, ${node.varName}, ${propsName}, $context`;
@@ -1778,6 +1894,49 @@ function buildComponentNode(node, status, b, root = false) {
1778
1894
  b.append("");
1779
1895
  }
1780
1896
  //#endregion
1897
+ //#region src/compile/build/client/checkCallbacks.ts
1898
+ /**
1899
+ * Helpers for the callbacks that control blocks (`@if`, `@switch`, `@await`,
1900
+ * …) pass to their runtime functions. A check build (`BuildOptions.check`)
1901
+ * calls each callback in place instead, as an immediately-invoked function,
1902
+ * because TypeScript carries narrowing into those but not into callbacks
1903
+ * passed elsewhere: `@if ($props.user) { {$props.user.name} }` then type
1904
+ * checks as it reads.
1905
+ */
1906
+ /** The callback's parameters: the insertion point, except in the head. */
1907
+ function controlParams(status) {
1908
+ return status.inHead ? "" : "t_before";
1909
+ }
1910
+ /** The arguments a check build calls a callback with, matching its parameters. */
1911
+ function controlArgs(params) {
1912
+ return params.split(",").map((p) => p.trim()).filter((p) => p !== "").map((p) => p === "t_before" ? "null as Node | null" : "undefined as any").join(", ");
1913
+ }
1914
+ /**
1915
+ * Opens a control block's callback.
1916
+ *
1917
+ * @param call The runtime call up to the callback, e.g. `t_run_control(region, anchor, `
1918
+ * @param params The callback's parameters, by default `t_before` (or none in the head)
1919
+ */
1920
+ function openControl(call, status, params = controlParams(status)) {
1921
+ return status.options.check === true ? `((${params}) => {` : `${call}(${params}) => {`;
1922
+ }
1923
+ /**
1924
+ * Closes a control block's callback and opens the next one, for runtime
1925
+ * calls that take several (e.g. `@await`'s content and `@with` branches).
1926
+ */
1927
+ function nextControl(status, params = controlParams(status), previousParams = controlParams(status)) {
1928
+ return status.options.check === true ? `})(${controlArgs(previousParams)});\n((${params}) => {` : `}, (${params}) => {`;
1929
+ }
1930
+ /**
1931
+ * Closes a control block's last callback, and the runtime call.
1932
+ *
1933
+ * @param trailing The runtime call's remaining arguments, e.g. `, "runIf"`
1934
+ * @param params The callback's parameters, to call it with in a check build
1935
+ */
1936
+ function closeControl(trailing, status, params = controlParams(status)) {
1937
+ return status.options.check === true ? `})(${controlArgs(params)});` : `}${trailing});`;
1938
+ }
1939
+ //#endregion
1781
1940
  //#region src/compile/build/client/buildAwaitNode.ts
1782
1941
  function buildAwaitNode(node, status, b) {
1783
1942
  const anchorName = node.varName ?? "null";
@@ -1793,7 +1952,7 @@ function buildAwaitNode(node, status, b) {
1793
1952
  addPushDevBoundary("control", "@await", status, b);
1794
1953
  b.append(`
1795
1954
  const ${regionName} = t_region(${status.options.dev === true ? `"await"` : ""});
1796
- t_run_await(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
1955
+ ${openControl(`t_run_await(${regionName}, ${anchorName}, `, status)}`);
1797
1956
  appendForVarBindings(b, status);
1798
1957
  if (awaitBranch !== void 0 && awaitBranch.children.length > 0) {
1799
1958
  buildFragment(awaitBranch, status, b, parentName, "t_before");
@@ -1806,7 +1965,7 @@ function buildAwaitNode(node, status, b) {
1806
1965
  buildAddFragment(awaitBranch, status, b, parentName, "t_before");
1807
1966
  }
1808
1967
  if (withBranch !== void 0) {
1809
- b.append(`}, (${status.inHead ? "" : "t_before"}) => {`);
1968
+ b.append(nextControl(status));
1810
1969
  appendForVarBindings(b, status);
1811
1970
  if (withBranch.children.length > 0) {
1812
1971
  buildFragment(withBranch, status, b, parentName, "t_before");
@@ -1818,8 +1977,8 @@ function buildAwaitNode(node, status, b) {
1818
1977
  status.fragmentStack.pop();
1819
1978
  buildAddFragment(withBranch, status, b, parentName, "t_before");
1820
1979
  }
1821
- b.append(`}${status.options.dev === true ? `, "runAwait"` : ""});`);
1822
- } else b.append(`}, null${status.options.dev === true ? `, "runAwait"` : ""});`);
1980
+ b.append(closeControl(status.options.dev === true ? `, "runAwait"` : "", status));
1981
+ } else b.append(closeControl(`, null${status.options.dev === true ? `, "runAwait"` : ""}`, status));
1823
1982
  addPopDevBoundary(status, b);
1824
1983
  b.append("");
1825
1984
  }
@@ -1884,41 +2043,185 @@ function isForBodyLeafSafe(forBodyChildren) {
1884
2043
  }
1885
2044
  //#endregion
1886
2045
  //#region src/compile/utils/forLoopVarNames.ts
2046
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1887
2047
  /**
1888
2048
  * Extracts the declared loop variable names from a `@for` statement — the
1889
- * heuristic header parse shared by `buildForNode` (codegen) and the write
1890
- * scanners (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect
1891
- * nested loops that shadow an outer loop's variables).
2049
+ * header parse shared by `buildForNode` (codegen) and the write scanners
2050
+ * (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect nested
2051
+ * loops that shadow an outer loop's variables).
1892
2052
  *
1893
2053
  * Handles the C-style (`for (let i = 0; i < n; i++)`), for-of and for-in
1894
- * forms, with destructuring flattened to the bare names. TODO: Handle
1895
- * destructuring, quotes, comments etc (same as buildForNode's note — this is
1896
- * deliberately the same heuristic).
2054
+ * forms, including comments, strings, nested destructuring and defaults.
1897
2055
  */
1898
2056
  function forLoopVarNames(statement) {
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
- const trimMatched = (value, start, end) => {
1903
- const startIndex = value.indexOf(start);
1904
- const endIndex = value.lastIndexOf(end);
1905
- if (startIndex === -1 || endIndex === -1) return value;
1906
- return value.slice(startIndex + 1, endIndex);
1907
- };
2057
+ const source = maskComments(statement);
2058
+ const forIndex = source.indexOf("for");
2059
+ if (forIndex === -1) return [];
2060
+ const open = source.indexOf("(", forIndex + 3);
2061
+ if (open === -1) return [];
2062
+ const close = findMatching(source, open, "(", ")");
2063
+ if (close === -1) return [];
2064
+ const header = source.slice(open + 1, close);
1908
2065
  const names = [];
1909
- const forLoopMatch = statement.match(forLoopRegex);
1910
- if (forLoopMatch) {
1911
- const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1912
- for (const match of forVarMatches) names.push(match[1]);
1913
- return names;
1914
- }
1915
- const forOfMatch = statement.match(forOfRegex);
1916
- if (forOfMatch) {
1917
- const match = forOfMatch[1];
1918
- if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) names.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1919
- else names.push(match);
2066
+ const firstSemi = findTopLevel(header, (char) => char === ";");
2067
+ if (firstSemi !== -1) {
2068
+ const declaration = stripDeclarationKeyword(header.slice(0, firstSemi));
2069
+ for (const declarator of splitTopLevel(declaration, ",")) {
2070
+ const eq = findTopLevel(declarator, (char) => char === "=");
2071
+ collectBindings(eq === -1 ? declarator : declarator.slice(0, eq), names);
2072
+ }
2073
+ return [...new Set(names)];
2074
+ }
2075
+ const keyword = findLoopKeyword(header);
2076
+ if (keyword !== -1) collectBindings(stripDeclarationKeyword(header.slice(0, keyword)), names);
2077
+ return [...new Set(names)];
2078
+ }
2079
+ /** Replaces comments with spaces, preserving length and string contents. */
2080
+ function maskComments(source) {
2081
+ let masked = "";
2082
+ for (let i = 0; i < source.length; i++) {
2083
+ const skipped = skipStringOrComment(source, i);
2084
+ if (skipped === -1) {
2085
+ masked += source[i];
2086
+ continue;
2087
+ }
2088
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) masked += source.substring(i, skipped).replaceAll(/[^\r\n]/g, " ");
2089
+ else masked += source.substring(i, skipped);
2090
+ i = skipped - 1;
1920
2091
  }
1921
- return names;
2092
+ return masked;
2093
+ }
2094
+ /** Finds the close delimiter matching the opener at `start`. */
2095
+ function findMatching(source, start, open, close) {
2096
+ let depth = 0;
2097
+ for (let i = start; i < source.length; i++) {
2098
+ const skipped = skipStringOrComment(source, i);
2099
+ if (skipped !== -1) {
2100
+ i = skipped - 1;
2101
+ continue;
2102
+ }
2103
+ const char = source[i];
2104
+ if (char === open) depth += 1;
2105
+ else if (char === close) {
2106
+ depth -= 1;
2107
+ if (depth === 0) return i;
2108
+ }
2109
+ }
2110
+ return -1;
2111
+ }
2112
+ /** Finds the first match of `predicate` outside nested delimiters and strings. */
2113
+ function findTopLevel(source, predicate) {
2114
+ let depth = 0;
2115
+ for (let i = 0; i < source.length; i++) {
2116
+ const skipped = skipStringOrComment(source, i);
2117
+ if (skipped !== -1) {
2118
+ i = skipped - 1;
2119
+ continue;
2120
+ }
2121
+ const char = source[i];
2122
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2123
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2124
+ else if (depth === 0 && predicate(char, i)) return i;
2125
+ }
2126
+ return -1;
2127
+ }
2128
+ /** Finds a top-level `of` or `in` keyword. */
2129
+ function findLoopKeyword(source) {
2130
+ let depth = 0;
2131
+ for (let i = 0; i < source.length; i++) {
2132
+ const skipped = skipStringOrComment(source, i);
2133
+ if (skipped !== -1) {
2134
+ i = skipped - 1;
2135
+ continue;
2136
+ }
2137
+ const char = source[i];
2138
+ if (char === "(" || char === "[" || char === "{") {
2139
+ depth += 1;
2140
+ continue;
2141
+ }
2142
+ if (char === ")" || char === "]" || char === "}") {
2143
+ depth -= 1;
2144
+ continue;
2145
+ }
2146
+ if (depth !== 0) continue;
2147
+ for (const keyword of ["of", "in"]) {
2148
+ if (!source.startsWith(keyword, i)) continue;
2149
+ const previous = source[i - 1];
2150
+ const next = source[i + keyword.length];
2151
+ if ((previous === void 0 || !isIdentifierChar(previous)) && (next === void 0 || !isIdentifierChar(next))) return i;
2152
+ }
2153
+ }
2154
+ return -1;
2155
+ }
2156
+ /** Splits at a separator that isn't inside strings or nested delimiters. */
2157
+ function splitTopLevel(source, separator) {
2158
+ const parts = [];
2159
+ let start = 0;
2160
+ let depth = 0;
2161
+ for (let i = 0; i < source.length; i++) {
2162
+ const skipped = skipStringOrComment(source, i);
2163
+ if (skipped !== -1) {
2164
+ i = skipped - 1;
2165
+ continue;
2166
+ }
2167
+ const char = source[i];
2168
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2169
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2170
+ else if (depth === 0 && char === separator) {
2171
+ parts.push(source.slice(start, i));
2172
+ start = i + 1;
2173
+ }
2174
+ }
2175
+ parts.push(source.slice(start));
2176
+ return parts;
2177
+ }
2178
+ function stripDeclarationKeyword(declaration) {
2179
+ return declaration.trim().replace(/^(?:let|var|const)\b\s*/, "");
2180
+ }
2181
+ function collectBindings(pattern, names) {
2182
+ pattern = pattern.trim();
2183
+ if (!pattern) return;
2184
+ const open = pattern[0];
2185
+ if (open === "{") {
2186
+ const close = findMatching(pattern, 0, "{", "}");
2187
+ if (close === -1) return;
2188
+ for (const property of splitTopLevel(pattern.slice(1, close), ",")) collectObjectBinding(property.trim(), names);
2189
+ return;
2190
+ }
2191
+ if (open === "[") {
2192
+ const close = findMatching(pattern, 0, "[", "]");
2193
+ if (close === -1) return;
2194
+ for (let element of splitTopLevel(pattern.slice(1, close), ",")) {
2195
+ element = element.trim();
2196
+ if (!element) continue;
2197
+ if (element.startsWith("...")) element = element.slice(3).trim();
2198
+ const eq = findTopLevel(element, (char) => char === "=");
2199
+ collectBindings(eq === -1 ? element : element.slice(0, eq), names);
2200
+ }
2201
+ return;
2202
+ }
2203
+ const eq = findTopLevel(pattern, (char) => char === "=");
2204
+ const name = (eq === -1 ? pattern : pattern.slice(0, eq)).trim();
2205
+ if (IDENTIFIER.test(name)) names.push(name);
2206
+ }
2207
+ function collectObjectBinding(property, names) {
2208
+ property = property.trim();
2209
+ if (!property) return;
2210
+ if (property.startsWith("...")) {
2211
+ collectBindings(property.slice(3).trim(), names);
2212
+ return;
2213
+ }
2214
+ const colon = findTopLevel(property, (char) => char === ":");
2215
+ const eq = findTopLevel(property, (char) => char === "=");
2216
+ if (colon !== -1 && (eq === -1 || colon < eq)) {
2217
+ collectBindings(property.slice(colon + 1).trim(), names);
2218
+ return;
2219
+ }
2220
+ const name = (eq === -1 ? property : property.slice(0, eq)).trim();
2221
+ if (IDENTIFIER.test(name)) names.push(name);
2222
+ }
2223
+ function isIdentifierChar(char) {
2224
+ return /[A-Za-z0-9_$]/.test(char);
1922
2225
  }
1923
2226
  //#endregion
1924
2227
  //#region src/compile/utils/forVarsWrittenIn.ts
@@ -2172,6 +2475,10 @@ function buildForNode(node, status, b) {
2172
2475
  for (const name of reassignedForVars) addBuildError(status, `Cannot assign to loop variable "${name}": a @for loop variable is read-only. Assign to a property of the item (\`${name}.foo = …\`) instead, or mutate the source collection directly.`, node.span.start, node.span.end);
2173
2476
  const singleVar = noWatch && forVarNames.length === 1;
2174
2477
  const leafRow = isForBodyLeafSafe(node.children);
2478
+ if (status.options.check === true) {
2479
+ buildCheckForNode(node, status, b, parentName, forVarNames, keyStatement, key, itemName, beforeName, leafRow);
2480
+ return;
2481
+ }
2175
2482
  status.imports.add("t_region");
2176
2483
  status.imports.add("t_run_list");
2177
2484
  status.imports.add("ListItemSpec");
@@ -2231,6 +2538,32 @@ ${status.options.dev === true ? "function updateListItem(t_old_item, t_new_item)
2231
2538
  addPopDevBoundary(status, b);
2232
2539
  b.append("");
2233
2540
  }
2541
+ /**
2542
+ * Builds a `@for` for type checking only (see `BuildOptions.check`): the loop
2543
+ * runs in place, with each row's body called inside it, so loop variables
2544
+ * keep the types of the iterable's items and narrowing from around the loop
2545
+ * carries into it.
2546
+ */
2547
+ function buildCheckForNode(node, status, b, parentName, forVarNames, keyStatement, key, itemName, beforeName, leafRow) {
2548
+ b.append("");
2549
+ b.append("/* @for */");
2550
+ b.append("(() => {");
2551
+ addMappedText("", `${node.statement}`, " {", node.span, status, b);
2552
+ if (key !== void 0 && keyStatement) addMappedText("void (", keyStatement, ");", key.span, status, b);
2553
+ b.append(`((${itemName}: any, ${beforeName}: Node | null) => {`);
2554
+ const oldForVars = status.forVars;
2555
+ status.forVars = [...oldForVars, ...forVarNames.map((v) => ({
2556
+ name: v,
2557
+ path: `${itemName}.data.${v}`,
2558
+ shadow: true
2559
+ }))];
2560
+ buildForItem(node, status, b, parentName, beforeName, itemName, leafRow);
2561
+ status.forVars = oldForVars;
2562
+ b.append("})(undefined, null);");
2563
+ b.append("}");
2564
+ b.append("})();");
2565
+ b.append("");
2566
+ }
2234
2567
  function buildForItem(node, status, b, parentName, beforeName, itemName, leafRow) {
2235
2568
  const oldRegionName = nextVarName("old_region", status);
2236
2569
  if (!leafRow) {
@@ -2259,6 +2592,13 @@ function buildHtmlNode(node, status, b) {
2259
2592
  const htmlAnchorName = node.varName;
2260
2593
  const htmlParentName = node.parentName || htmlAnchorName + ".parentNode";
2261
2594
  node = node.children[0];
2595
+ if (status.options.check === true) {
2596
+ b.append("");
2597
+ b.append(`/* @html */`);
2598
+ addMappedText("", node.statement, ";", node.span, status, b);
2599
+ b.append("");
2600
+ return;
2601
+ }
2262
2602
  status.imports.add("t_region");
2263
2603
  status.imports.add("t_run_control");
2264
2604
  const firstNodeVar = nextVarName("html_first", status);
@@ -2338,11 +2678,11 @@ function buildIfNode(node, status, b) {
2338
2678
  b.append(`
2339
2679
  const ${regionName} = t_region(${status.options.dev === true ? `"if"` : ""});
2340
2680
  let ${indexName} = -1;
2341
- t_run_control(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2681
+ ${openControl(`t_run_control(${regionName}, ${anchorName}, `, status)}`);
2342
2682
  appendForVarBindings(b, status);
2343
2683
  let index = 0;
2344
2684
  for (let branch of branches) buildIfBranch(branch, status, b, parentName, regionName, indexName, index++);
2345
- b.append(`}${status.options.dev === true ? `, "runIf"` : ""});`);
2685
+ b.append(closeControl(status.options.dev === true ? `, "runIf"` : "", status));
2346
2686
  addPopDevBoundary(status, b);
2347
2687
  b.append("");
2348
2688
  }
@@ -2379,10 +2719,10 @@ function buildReplaceNode(node, status, b) {
2379
2719
  b.append(`
2380
2720
  /* @replace */
2381
2721
  const ${replaceRegionName} = t_region(${status.options.dev === true ? `"replace"` : ""});
2382
- t_run_control(${replaceRegionName}, ${replaceAnchorName}, (t_before) => {`);
2722
+ ${openControl(`t_run_control(${replaceRegionName}, ${replaceAnchorName}, `, status, "t_before")}`);
2383
2723
  appendForVarBindings(b, status);
2384
2724
  buildReplaceBranch(node, status, b, replaceParentName, replaceRegionName);
2385
- b.append(`}${status.options.dev === true ? ", \"replace\"" : ""});`);
2725
+ b.append(closeControl(status.options.dev === true ? ", \"replace\"" : "", status, "t_before"));
2386
2726
  b.append("");
2387
2727
  }
2388
2728
  function buildReplaceBranch(node, status, b, parentName, regionName) {
@@ -2439,14 +2779,13 @@ function buildSwitchNode(node, status, b) {
2439
2779
  b.append(`
2440
2780
  const ${regionName} = t_region(${status.options.dev === true ? `"switch"` : ""});
2441
2781
  let ${indexName} = -1;
2442
- t_run_control(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2782
+ ${openControl(`t_run_control(${regionName}, ${anchorName}, `, status)}`);
2443
2783
  appendForVarBindings(b, status);
2444
2784
  addMappedText("", `${node.statement}`, " {", node.span, status, b);
2445
2785
  let index = 0;
2446
2786
  for (let branch of branches) buildSwitchBranch(branch, status, b, parentName, regionName, indexName, index++);
2447
- b.append(`
2448
- }
2449
- }${status.options.dev === true ? `, "runSwitch"` : ""});`);
2787
+ b.append("}");
2788
+ b.append(closeControl(status.options.dev === true ? `, "runSwitch"` : "", status));
2450
2789
  addPopDevBoundary(status, b);
2451
2790
  b.append("");
2452
2791
  }
@@ -2504,16 +2843,20 @@ function buildTryNode(node, status, b) {
2504
2843
  addPushDevBoundary("control", "@try", status, b);
2505
2844
  b.append(`
2506
2845
  const ${regionName} = t_region(${status.options.dev === true ? `"try"` : ""});
2507
- t_run_try(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2846
+ ${openControl(`t_run_try(${regionName}, ${anchorName}, `, status)}`);
2508
2847
  appendForVarBindings(b, status);
2509
2848
  buildTryBranchBody(tryBranch, status, b, parentName);
2510
2849
  const catchVar = catchBranch ? trimMatched(catchBranch.statement.substring(5).trim(), "(", ")") || "err" : null;
2511
2850
  if (catchBranch && catchVar) {
2512
- addMappedText("},", `(${status.inHead ? "" : "t_before"}, ${catchVar}) => {`, "", catchBranch.span, status, b);
2851
+ const catchParams = `${status.inHead ? "" : "t_before"}, ${catchVar}`;
2852
+ if (status.options.check === true) {
2853
+ b.append(closeControl("", status));
2854
+ addMappedText("", `((${catchParams}) => {`, "", catchBranch.span, status, b);
2855
+ } else addMappedText("},", `(${catchParams}) => {`, "", catchBranch.span, status, b);
2513
2856
  appendForVarBindings(b, status);
2514
2857
  buildTryBranchBody(catchBranch, status, b, parentName);
2515
- b.append(`}${status.options.dev === true ? `, "runTry"` : ""});`);
2516
- } else b.append(`}, null${status.options.dev === true ? `, "runTry"` : ""});`);
2858
+ b.append(closeControl(status.options.dev === true ? `, "runTry"` : "", status, catchParams));
2859
+ } else b.append(closeControl(`, null${status.options.dev === true ? `, "runTry"` : ""}`, status));
2517
2860
  addPopDevBoundary(status, b);
2518
2861
  b.append("");
2519
2862
  }
@@ -2582,6 +2925,25 @@ function buildControlNode(node, status, b) {
2582
2925
  }
2583
2926
  }
2584
2927
  //#endregion
2928
+ //#region src/compile/utils/rawTextTags.ts
2929
+ /**
2930
+ * HTML raw-text elements. Their contents aren't parsed as markup (or as a
2931
+ * torpor template): braces, `@` and `<` are all literal, and the browser
2932
+ * doesn't decode character references inside them either. Rendered `<script>`
2933
+ * / `<style>` content is therefore emitted exactly as written.
2934
+ */
2935
+ const RAW_TEXT_TAGS = /* @__PURE__ */ new Set([
2936
+ "script",
2937
+ "style",
2938
+ "xmp",
2939
+ "iframe",
2940
+ "noembed",
2941
+ "noframes"
2942
+ ]);
2943
+ function isRawTextTag(tagName) {
2944
+ return RAW_TEXT_TAGS.has(tagName.toLowerCase());
2945
+ }
2946
+ //#endregion
2585
2947
  //#region src/compile/utils/trimEnd.ts
2586
2948
  /**
2587
2949
  * Trims a char from the end of the supplied text
@@ -2651,7 +3013,7 @@ function buildElementNode(node, status, b, parentName) {
2651
3013
  buildElementAttributes$1(node, varName, status, b);
2652
3014
  }
2653
3015
  const oldPreserveWhitespace = status.preserveWhitespace;
2654
- status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre";
3016
+ status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre" || isRawTextTag(node.tagName);
2655
3017
  for (let child of node.children) buildNode(child, status, b, parentName, "null");
2656
3018
  status.preserveWhitespace = oldPreserveWhitespace;
2657
3019
  if (svgElement) status.ns = oldns;
@@ -2662,10 +3024,13 @@ function buildDynamicElementNode(node, status, b) {
2662
3024
  status.imports.add("t_dynamic");
2663
3025
  let selfValue = selfAttribute.value;
2664
3026
  if (selfAttribute.fullyReactive) {
2665
- status.imports.add("$run");
2666
- b.append("$run(() => {");
2667
- b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
2668
- b.append(`}${status.options.dev === true ? `, "setDynamic"` : ""});`);
3027
+ if (status.options.check === true) b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
3028
+ else {
3029
+ status.imports.add("$run");
3030
+ b.append("$run(() => {");
3031
+ b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
3032
+ b.append(`}${status.options.dev === true ? `, "setDynamic"` : ""});`);
3033
+ }
2669
3034
  } else b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
2670
3035
  }
2671
3036
  buildElementAttributes$1(node, node.varName, status, b);
@@ -2689,12 +3054,28 @@ function buildTitleNode(node, status, b) {
2689
3054
  else content = `\`${content.replaceAll("{", "${t_fmt(").replaceAll("}", ")}")}\``;
2690
3055
  } else content = `"${content}"`;
2691
3056
  status.imports.add("$run");
2692
- b.append("$run(() => {");
2693
- b.append(`
3057
+ if (status.options.dev === true) {
3058
+ status.imports.add("t_dev_title");
3059
+ b.append(`{
3060
+ const t_title_dev = t_dev_title();
3061
+ $run(() => {
3062
+ const t_old_title = document.title;
3063
+ document.title = ${content};
3064
+ t_title_dev.set(document.title);
3065
+ return () => {
3066
+ t_title_dev.unset();
3067
+ document.title = t_old_title;
3068
+ };
3069
+ }, "runTitle");
3070
+ }`);
3071
+ } else {
3072
+ b.append("$run(() => {");
3073
+ b.append(`
2694
3074
  const t_old_title = document.title;
2695
3075
  document.title = ${content};
2696
3076
  return () => document.title = t_old_title;
2697
- }${status.options.dev === true ? `, "runTitle"` : ""});`);
3077
+ });`);
3078
+ }
2698
3079
  }
2699
3080
  function buildHeadNode(node, status, b) {
2700
3081
  status.imports.add("$run");
@@ -2795,12 +3176,14 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2795
3176
  let eventName = bindEventName(node, name);
2796
3177
  let defaultValue = "\"\"";
2797
3178
  let inputValue = "e.target.value";
3179
+ let setJoin = "||";
2798
3180
  if (node.tagName === "input") {
2799
3181
  let typeAttribute = node.attributes.find((a) => a.name === "type");
2800
3182
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
2801
3183
  case "number":
2802
- defaultValue = "0";
2803
- inputValue = "Number(e.target.value)";
3184
+ defaultValue = "\"\"";
3185
+ inputValue = "e.target.value === \"\" ? undefined : Number(e.target.value)";
3186
+ setJoin = "??";
2804
3187
  break;
2805
3188
  case "checkbox":
2806
3189
  defaultValue = "false";
@@ -2813,7 +3196,7 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2813
3196
  return;
2814
3197
  }
2815
3198
  }
2816
- let set = `${value} || ${defaultValue}`;
3199
+ let set = `${value} ${setJoin} ${defaultValue}`;
2817
3200
  const propName = name.substring(1);
2818
3201
  buildRun("setBinding", `${propName === "value" ? `${varName}.${propName} = String(${set})` : `${varName}.${propName} = ${set}`};`, status, b);
2819
3202
  emitBindEvent(varName, eventName, `(e) => ${value} = ${inputValue}`, `${value} = ${inputValue};`, combined, status, b);
@@ -3008,6 +3391,7 @@ function buildSpecialNode(node, status, b, parentName, root = false) {
3008
3391
  //#endregion
3009
3392
  //#region src/compile/build/client/buildTextNode.ts
3010
3393
  function buildTextNode(node, status) {
3394
+ if (node.raw) return;
3011
3395
  let fragment = status.fragmentStack.at(-1)?.fragment;
3012
3396
  if (!fragment) return;
3013
3397
  let content = node.content || "";
@@ -3152,7 +3536,8 @@ const importsMap$1 = {
3152
3536
  SlotRender: "import { type SlotRender } from \"${folder}\";",
3153
3537
  devContext: "import { devContext } from \"${folder}/dev\";",
3154
3538
  t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
3155
- t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
3539
+ t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";",
3540
+ t_dev_title: "import { t_dev_title } from \"${folder}/dev\";"
3156
3541
  };
3157
3542
  function buildCode(template, map, options, errors = [], warnings = []) {
3158
3543
  let b = new Builder(options?.mapped);
@@ -3228,7 +3613,7 @@ function buildTemplate(template, map, imports, b, options, errors = [], warnings
3228
3613
  status.imports.add("t_region");
3229
3614
  status.imports.add("t_run_try");
3230
3615
  b.append(`const t_error_region = t_region();`);
3231
- b.append(`t_run_try(t_error_region, $anchor, () => {`);
3616
+ b.append(status.options.check === true ? "(() => {" : `t_run_try(t_error_region, $anchor, () => {`);
3232
3617
  }
3233
3618
  buildFragmentText(current.markup, status, b);
3234
3619
  b.append("");
@@ -3236,13 +3621,13 @@ function buildTemplate(template, map, imports, b, options, errors = [], warnings
3236
3621
  }
3237
3622
  } else if (chunk.script === "/* @error */") {
3238
3623
  if (current.markup && current.error) {
3239
- b.append(`}, (_, ${current.errorVar ?? "err"}) => {`);
3624
+ b.append(status.options.check === true ? `})();\n((_: Node | null, ${current.errorVar ?? "err"}: any) => {` : `}, (_, ${current.errorVar ?? "err"}) => {`);
3240
3625
  b.append("");
3241
3626
  b.append("/* User interface error */");
3242
3627
  buildFragmentText(current.error, status, b);
3243
3628
  b.append("");
3244
3629
  buildNode(current.error, status, b, "$parent", "$anchor", true);
3245
- b.append(`}${status.options.dev === true ? ", \"runError\"" : ""});`);
3630
+ b.append(status.options.check === true ? "})(null, undefined);" : `}${status.options.dev === true ? ", \"runError\"" : ""});`);
3246
3631
  }
3247
3632
  } else if (chunk.script === "/* @head */") {
3248
3633
  if (current.head) {
@@ -3290,10 +3675,10 @@ function buildStyles(style, styleHash) {
3290
3675
  for (let block of style.children) buildStyleNode(block, b, styleHash);
3291
3676
  return b.toString();
3292
3677
  }
3293
- function buildStyleNode(node, b, styleHash) {
3678
+ function buildStyleNode(node, b, styleHash, scoped = true) {
3294
3679
  switch (node.type) {
3295
3680
  case "block":
3296
- buildBlockNode(node, b, styleHash);
3681
+ buildBlockNode(node, b, styleHash, scoped);
3297
3682
  break;
3298
3683
  case "attribute":
3299
3684
  buildAttributeNode(node, b);
@@ -3302,55 +3687,164 @@ function buildStyleNode(node, b, styleHash) {
3302
3687
  default: throw new Error(`Invalid style node type: ${node.type}`);
3303
3688
  }
3304
3689
  }
3305
- function buildBlockNode(block, b, styleHash) {
3690
+ function buildBlockNode(block, b, styleHash, scoped) {
3691
+ const isKeyframes = block.selector.startsWith("@keyframes") || block.selector.startsWith("@-webkit-keyframes");
3306
3692
  if (block.selector.startsWith("@")) b.append(`${block.selector} {`);
3307
3693
  else {
3308
- block.selector = block.selector.replaceAll(/\s+/g, " ");
3309
- let selectors = [];
3310
- let global = false;
3311
- let start = 0;
3312
- for (let i = 0; i <= block.selector.length; i++) if (block.selector.substring(i).startsWith(":global(")) {
3313
- i += 7;
3314
- start = i + 1;
3315
- global = true;
3316
- } else if (global && block.selector[i] === ")") {
3317
- addSelector(selectors, block.selector, styleHash, start, i, global);
3318
- start = i + 1;
3319
- global = false;
3320
- } else if ("*,>+~".includes(block.selector[i])) {
3321
- addSelector(selectors, block.selector, styleHash, start, i, global);
3322
- selectors.push(block.selector[i]);
3323
- start = i + 1;
3324
- } else if (i === block.selector.length) addSelector(selectors, block.selector, styleHash, start, i, global);
3325
- else if (block.selector[i] === " ") {
3326
- addSelector(selectors, block.selector, styleHash, start, i, global);
3327
- start = i + 1;
3328
- }
3329
- b.append(`${selectors.join(" ").replaceAll(" ,", ",")} {`);
3694
+ block.selector = block.selector.replaceAll(/\s+/g, " ").trim();
3695
+ b.append(`${scoped ? scopeSelector(block.selector, styleHash) : block.selector} {`);
3330
3696
  }
3331
- for (let child of block.children) buildStyleNode(child, b, styleHash);
3697
+ for (let child of block.children) buildStyleNode(child, b, styleHash, scoped && !isKeyframes);
3332
3698
  b.append(`}`);
3333
3699
  }
3334
- function addSelector(selectors, selector, styleHash, start, end, global) {
3335
- if (end > start) {
3336
- let s = selector.substring(start, end);
3337
- if (!global) {
3338
- let pre = s;
3339
- let post = "";
3340
- let colonPosition = s.indexOf(":");
3341
- if (colonPosition !== -1) {
3342
- pre = s.substring(0, colonPosition);
3343
- post = s.substring(colonPosition);
3700
+ /**
3701
+ * Appends the component scope class to each compound selector. Both brackets
3702
+ * (`[data-x="a b"]`) and parentheses (`:is(.a, .b)`, `:global(...)`) are
3703
+ * treated as opaque, so spaces/commas inside them aren't mistaken for
3704
+ * combinators. `:global(...)` wrappers are removed without adding the scope.
3705
+ */
3706
+ function scopeSelector(selector, styleHash) {
3707
+ let result = "";
3708
+ let compound = "";
3709
+ let bracketDepth = 0;
3710
+ let parenDepth = 0;
3711
+ let quote = null;
3712
+ const flush = () => {
3713
+ if (!compound) return;
3714
+ result += scopeCompound(compound, styleHash);
3715
+ compound = "";
3716
+ };
3717
+ for (let i = 0; i < selector.length; i++) {
3718
+ const char = selector[i];
3719
+ if (quote !== null) {
3720
+ compound += char;
3721
+ if (char === "\\") compound += selector[++i] ?? "";
3722
+ else if (char === quote) quote = null;
3723
+ continue;
3724
+ }
3725
+ if (char === "\\") compound += char + (selector[++i] ?? "");
3726
+ else if (char === "\"" || char === "'") {
3727
+ quote = char;
3728
+ compound += char;
3729
+ } else if (char === "[") {
3730
+ bracketDepth += 1;
3731
+ compound += char;
3732
+ } else if (char === "]") {
3733
+ bracketDepth -= 1;
3734
+ compound += char;
3735
+ } else if (char === "(") {
3736
+ parenDepth += 1;
3737
+ compound += char;
3738
+ } else if (char === ")") {
3739
+ parenDepth -= 1;
3740
+ compound += char;
3741
+ } else if (bracketDepth === 0 && parenDepth === 0 && (char === " " || char === "," || char === ">" || char === "+" || char === "~")) {
3742
+ flush();
3743
+ result += char;
3744
+ } else compound += char;
3745
+ }
3746
+ flush();
3747
+ return result.trim();
3748
+ }
3749
+ function scopeCompound(compound, styleHash) {
3750
+ if (!compound.includes(":global(")) return addScope(compound, styleHash);
3751
+ const { text, onlyGlobal } = stripGlobal(compound);
3752
+ return onlyGlobal ? text : addScope(text, styleHash);
3753
+ }
3754
+ /** Removes `:global(...)` wrappers, reporting whether anything local remained. */
3755
+ function stripGlobal(compound) {
3756
+ let text = "";
3757
+ let hadLocal = false;
3758
+ let i = 0;
3759
+ while (i < compound.length) {
3760
+ if (compound.startsWith(":global(", i)) {
3761
+ const close = findClosingParen(compound, i + 7);
3762
+ if (close === -1) {
3763
+ text += compound.substring(i);
3764
+ break;
3344
3765
  }
3345
- s = `${pre}.torp-${styleHash}${post}`;
3766
+ text += compound.substring(i + 8, close);
3767
+ i = close + 1;
3768
+ continue;
3769
+ }
3770
+ const char = compound[i];
3771
+ if (char.trim()) hadLocal = true;
3772
+ text += char;
3773
+ i += 1;
3774
+ }
3775
+ return {
3776
+ text,
3777
+ onlyGlobal: !hadLocal
3778
+ };
3779
+ }
3780
+ function addScope(compound, styleHash) {
3781
+ const colon = findFirstPseudo(compound);
3782
+ const scope = `.torp-${styleHash}`;
3783
+ return colon === -1 ? `${compound}${scope}` : `${compound.substring(0, colon)}${scope}${compound.substring(colon)}`;
3784
+ }
3785
+ /** Finds the first top-level `:` (pseudo-class/element), skipping brackets/strings. */
3786
+ function findFirstPseudo(compound) {
3787
+ let bracketDepth = 0;
3788
+ let parenDepth = 0;
3789
+ let quote = null;
3790
+ for (let i = 0; i < compound.length; i++) {
3791
+ const char = compound[i];
3792
+ if (quote !== null) {
3793
+ if (char === "\\") i += 1;
3794
+ else if (char === quote) quote = null;
3795
+ continue;
3796
+ }
3797
+ if (char === "\\") i += 1;
3798
+ else if (char === "\"" || char === "'") quote = char;
3799
+ else if (char === "[") bracketDepth += 1;
3800
+ else if (char === "]") bracketDepth -= 1;
3801
+ else if (char === "(") parenDepth += 1;
3802
+ else if (char === ")") parenDepth -= 1;
3803
+ else if (bracketDepth === 0 && parenDepth === 0 && char === ":") return i;
3804
+ }
3805
+ return -1;
3806
+ }
3807
+ function findClosingParen(source, open) {
3808
+ let depth = 0;
3809
+ let bracketDepth = 0;
3810
+ let quote = null;
3811
+ for (let i = open; i < source.length; i++) {
3812
+ const char = source[i];
3813
+ if (quote !== null) {
3814
+ if (char === "\\") i += 1;
3815
+ else if (char === quote) quote = null;
3816
+ continue;
3817
+ }
3818
+ if (char === "\\") i += 1;
3819
+ else if (char === "\"" || char === "'") quote = char;
3820
+ else if (char === "[") bracketDepth += 1;
3821
+ else if (char === "]") bracketDepth -= 1;
3822
+ else if (bracketDepth === 0 && char === "(") depth += 1;
3823
+ else if (bracketDepth === 0 && char === ")") {
3824
+ depth -= 1;
3825
+ if (depth === 0) return i;
3346
3826
  }
3347
- selectors.push(s);
3348
3827
  }
3828
+ return -1;
3349
3829
  }
3350
3830
  function buildAttributeNode(attribute, b) {
3351
3831
  b.append(`${attribute.name}: ${attribute.value};`);
3352
3832
  }
3353
3833
  //#endregion
3834
+ //#region src/compile/utils/containsAwaitGroup.ts
3835
+ /**
3836
+ * Whether a markup tree contains an `@await` boundary, so the component's
3837
+ * render must be wrapped in a flush.
3838
+ */
3839
+ function containsAwaitGroup(node) {
3840
+ if (node === void 0 || node === null) return false;
3841
+ if (isControlNode(node) && node.operation === "@await group") return true;
3842
+ if (node.type !== "text" && node.type !== "comment") {
3843
+ for (let child of node.children) if (containsAwaitGroup(child)) return true;
3844
+ }
3845
+ return false;
3846
+ }
3847
+ //#endregion
3354
3848
  //#region src/compile/build/server/flushOutput.ts
3355
3849
  /**
3356
3850
  * Appends any pending output to the generated code, targeting the body
@@ -3403,7 +3897,7 @@ function buildServerComponentNode(node, status, b) {
3403
3897
  for (let slot of node.children) if (isSpecialNode(slot) && (slot.tagName === "fill" || slot.tagName === "filldef")) {
3404
3898
  const nameAttribute = slot.attributes.find((a) => a.name === "name");
3405
3899
  const slotName = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
3406
- const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3900
+ const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) || containsAwaitGroup(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3407
3901
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = async (\n${slotParams.join(",\n")}\n) => {`);
3408
3902
  b.append(`let t_body = "";`);
3409
3903
  for (let child of slot.children) buildServerNode(child, status, b);
@@ -3459,7 +3953,7 @@ function buildServerAwaitNode(node, status, b) {
3459
3953
  for (let branch of node.children) if (isControlNode(branch) && branch.operation === "@with") for (let child of branch.children) buildServerNode(child, status, b);
3460
3954
  flushOutput(status, b);
3461
3955
  b.append(`return { body: t_body, head: t_head };`);
3462
- b.append(`});`);
3956
+ b.append(`}, $context);`);
3463
3957
  b.append(`${status.inHead ? "t_head" : "t_body"} += ${resultName}.body;`);
3464
3958
  b.append(`t_head += ${resultName}.head;`);
3465
3959
  }
@@ -3641,7 +4135,7 @@ function buildServerElementNode(node, status, b) {
3641
4135
  status.output += `<${tagName}${attributes}>`;
3642
4136
  if (!voidTags.includes(tagName)) {
3643
4137
  const oldPreserveWhitespace = status.preserveWhitespace;
3644
- status.preserveWhitespace = ["pre", "code"].includes(tagName);
4138
+ status.preserveWhitespace = ["pre", "code"].includes(tagName) || isRawTextTag(tagName);
3645
4139
  if (!tagName.startsWith("@")) status.elementStack.push(tagName);
3646
4140
  for (let child of node.children) buildServerNode(child, status, b);
3647
4141
  if (!tagName.startsWith("@")) status.elementStack.pop();
@@ -3659,16 +4153,13 @@ function buildElementAttributes(node, status) {
3659
4153
  let typeAttribute = node.attributes.find((a) => a.name === "type");
3660
4154
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
3661
4155
  case "number":
3662
- defaultValue = "0";
4156
+ defaultValue = "\"\"";
3663
4157
  break;
3664
4158
  case "checkbox": defaultValue = "false";
3665
4159
  }
3666
- if (!defaultValue) {
3667
- status.imports.add("t_attr");
3668
- value = `t_attr(${value})`;
3669
- defaultValue = "\"\"";
3670
- }
3671
- let valueOrDefault = `(${value}) || ${defaultValue}`;
4160
+ if (!defaultValue) defaultValue = "\"\"";
4161
+ status.imports.add("t_attr");
4162
+ let valueOrDefault = `t_attr(${value}) || ${defaultValue}`;
3672
4163
  const propName = name.substring(1);
3673
4164
  attributes.push(`${propName}="\${${valueOrDefault}}"`);
3674
4165
  } else if (name === "class") {
@@ -3691,9 +4182,9 @@ function buildElementAttributes(node, status) {
3691
4182
  attributes.push(`${name}="${trimQuotes(value).replaceAll("{", "${t_attr(").replaceAll("}", ")}")}"`);
3692
4183
  } else if (name === "class" && node.scopeStyles && !status.inHead) {
3693
4184
  value = value ? `"${trimQuotes(value)} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
3694
- attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4185
+ attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3695
4186
  needsClass = false;
3696
- } else if (value != null) attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4187
+ } else if (value != null) attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3697
4188
  else attributes.push(`${name}`);
3698
4189
  if (needsClass) attributes.push(`class="torp-${status.styleHash}"`);
3699
4190
  return attributes.join(" ");
@@ -3756,15 +4247,21 @@ function buildServerSpecialNode(node, status, b) {
3756
4247
  //#region src/compile/build/server/buildServerTextNode.ts
3757
4248
  function buildServerTextNode(node, status) {
3758
4249
  let content = node.content || "";
4250
+ if (node.raw) {
4251
+ status.output += escapeRawText(content);
4252
+ return;
4253
+ }
3759
4254
  if (!status.preserveWhitespace) content = content.replaceAll(/\s+/g, " ");
4255
+ const parentTag = status.elementStack[status.elementStack.length - 1];
4256
+ const formatter = parentTag !== void 0 && isRawTextTag(parentTag) ? "t_fmt_raw" : "t_fmt";
3760
4257
  let level = 0;
3761
4258
  for (let i = 0; i < content.length; i++) {
3762
4259
  const char = content[i];
3763
4260
  if (char === "{") {
3764
4261
  level++;
3765
4262
  if (level === 1) {
3766
- status.imports.add("t_fmt");
3767
- status.output += "${t_fmt(";
4263
+ status.imports.add(formatter);
4264
+ status.output += "${" + formatter + "(";
3768
4265
  continue;
3769
4266
  }
3770
4267
  } else if (char === "}") {
@@ -3827,8 +4324,10 @@ const importsMap = {
3827
4324
  $peek: "import { $peek } from \"${folder}\";",
3828
4325
  $batch: "import { $batch } from \"${folder}\";",
3829
4326
  t_server_flush: "import { t_server_flush } from \"${folder}\";",
4327
+ t_render_context: "import { t_render_context } from \"${folder}\";",
3830
4328
  t_await_server: "import { t_await_server } from \"${folder}\";",
3831
4329
  t_fmt: "import { t_fmt } from \"${folder}\";",
4330
+ t_fmt_raw: "import { t_fmt_raw } from \"${folder}\";",
3832
4331
  t_attr: "import { t_attr } from \"${folder}\";",
3833
4332
  t_attr_if: "import { t_attr_if } from \"${folder}\";",
3834
4333
  t_class: "import { t_class } from \"${folder}\";",
@@ -3876,121 +4375,118 @@ function buildServerTemplate(template, imports, b, options) {
3876
4375
  for (let [i, chunk] of template.script.entries()) if (chunk.script === "/* @params */" && i > 0) asyncChunks.add(i - 1);
3877
4376
  let currentIndex = 0;
3878
4377
  let current = template.components[0];
3879
- for (let [chunkIndex, chunk] of template.script.entries()) if (chunk.script === "/* @params */") {
3880
- let params = [
3881
- current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
3882
- `${current.contextProps?.length || current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error) ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
3883
- `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
3884
- ];
3885
- b.append(params.join(",\n") + ",");
3886
- } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
3887
- else if (chunk.script === "/* @start */") {
3888
- if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
3889
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) {
3890
- imports.add("t_server_flush");
3891
- b.append(`return t_server_flush(async () => {`);
3892
- }
3893
- b.append(`let t_body = "";`);
3894
- b.append(`let t_head = "";`);
3895
- } else if (chunk.script === "/* @render */") {
3896
- if (current.markup) {
3897
- const status = {
3898
- imports,
3899
- output: "",
3900
- styleHash: current.style?.hash || "",
3901
- varNames: {},
3902
- preserveWhitespace: false,
3903
- awaitCount: 0,
3904
- elementStack: [],
3905
- options
3906
- };
3907
- b.append("");
3908
- b.append("/* User interface */");
3909
- if (current.error) {
3910
- b.append(`const t_try_body = t_body;`);
3911
- b.append(`const t_try_head = t_head;`);
3912
- b.append("try {");
4378
+ for (let [chunkIndex, chunk] of template.script.entries()) {
4379
+ const hasAwait = current !== void 0 && (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head));
4380
+ const rendersComponent = current !== void 0 && (current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error));
4381
+ if (chunk.script === "/* @params */") {
4382
+ let params = [
4383
+ current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
4384
+ `${current.contextProps?.length || rendersComponent || hasAwait ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
4385
+ `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
4386
+ ];
4387
+ b.append(params.join(",\n") + ",");
4388
+ } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
4389
+ else if (chunk.script === "/* @start */") {
4390
+ if (rendersComponent || hasAwait) {
4391
+ imports.add("t_render_context");
4392
+ b.append(`$context = t_render_context($context);`);
3913
4393
  }
3914
- buildServerNode(current.markup, status, b);
3915
- if (status.output) {
3916
- b.append(`t_body += \`${status.output}\`;`);
3917
- status.output = "";
4394
+ if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
4395
+ if (hasAwait) {
4396
+ imports.add("t_server_flush");
4397
+ b.append(`return t_server_flush(async () => {`);
3918
4398
  }
3919
- }
3920
- } else if (chunk.script === "/* @error */") {
3921
- if (current.markup && current.error) {
3922
- const status = {
3923
- imports,
3924
- output: "",
3925
- styleHash: current.style?.hash || "",
3926
- varNames: {},
3927
- preserveWhitespace: false,
3928
- awaitCount: 0,
3929
- elementStack: [],
3930
- options
3931
- };
3932
- b.append(`} catch (${current.errorVar}) {`);
3933
- b.append("t_body = t_try_body;");
3934
- b.append("t_head = t_try_head;");
3935
- b.append("/* User interface error */");
3936
- buildServerNode(current.error, status, b);
3937
- if (status.output) {
3938
- b.append(`t_body += \`${status.output}\`;`);
3939
- status.output = "";
4399
+ b.append(`let t_body = "";`);
4400
+ b.append(`let t_head = "";`);
4401
+ } else if (chunk.script === "/* @render */") {
4402
+ if (current.markup) {
4403
+ const status = {
4404
+ imports,
4405
+ output: "",
4406
+ styleHash: current.style?.hash || "",
4407
+ varNames: {},
4408
+ preserveWhitespace: false,
4409
+ awaitCount: 0,
4410
+ elementStack: [],
4411
+ options
4412
+ };
4413
+ b.append("");
4414
+ b.append("/* User interface */");
4415
+ if (current.error) {
4416
+ b.append(`const t_try_body = t_body;`);
4417
+ b.append(`const t_try_head = t_head;`);
4418
+ b.append("try {");
4419
+ }
4420
+ buildServerNode(current.markup, status, b);
4421
+ if (status.output) {
4422
+ b.append(`t_body += \`${status.output}\`;`);
4423
+ status.output = "";
4424
+ }
3940
4425
  }
3941
- b.append("}");
3942
- }
3943
- } else if (chunk.script === "/* @head */") {
3944
- if (current.head) {
3945
- const status = {
3946
- imports,
3947
- output: "",
3948
- styleHash: current.style?.hash || "",
3949
- varNames: {},
3950
- preserveWhitespace: false,
3951
- inHead: true,
3952
- awaitCount: 0,
3953
- elementStack: [],
3954
- options
3955
- };
3956
- b.append("");
3957
- b.append("/* Head */");
3958
- buildServerNode(current.head, status, b);
3959
- flushOutput(status, b);
3960
- }
3961
- } else if (chunk.script === "/* @style */") {
3962
- if (current.style) {
3963
- b.append("");
3964
- b.append("/* Style */");
3965
- const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
3966
- b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
3967
- }
3968
- } else if (chunk.script === "/* @end */") {
3969
- b.append(`return { body: t_body, head: t_head };`);
3970
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) b.append(`});`);
3971
- currentIndex += 1;
3972
- current = template.components[currentIndex];
3973
- } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
3974
- else b.append(chunk.script);
3975
- }
3976
- /**
3977
- * Whether a markup tree contains an `@await` boundary, so the component's
3978
- * render must be wrapped in a flush.
3979
- */
3980
- function containsAwaitGroup(node) {
3981
- if (node === void 0 || node === null) return false;
3982
- if (isControlNode(node) && node.operation === "@await group") return true;
3983
- if (node.type !== "text" && node.type !== "comment") {
3984
- for (let child of node.children) if (containsAwaitGroup(child)) return true;
4426
+ } else if (chunk.script === "/* @error */") {
4427
+ if (current.markup && current.error) {
4428
+ const status = {
4429
+ imports,
4430
+ output: "",
4431
+ styleHash: current.style?.hash || "",
4432
+ varNames: {},
4433
+ preserveWhitespace: false,
4434
+ awaitCount: 0,
4435
+ elementStack: [],
4436
+ options
4437
+ };
4438
+ b.append(`} catch (${current.errorVar}) {`);
4439
+ b.append("t_body = t_try_body;");
4440
+ b.append("t_head = t_try_head;");
4441
+ b.append("/* User interface error */");
4442
+ buildServerNode(current.error, status, b);
4443
+ if (status.output) {
4444
+ b.append(`t_body += \`${status.output}\`;`);
4445
+ status.output = "";
4446
+ }
4447
+ b.append("}");
4448
+ }
4449
+ } else if (chunk.script === "/* @head */") {
4450
+ if (current.head) {
4451
+ const status = {
4452
+ imports,
4453
+ output: "",
4454
+ styleHash: current.style?.hash || "",
4455
+ varNames: {},
4456
+ preserveWhitespace: false,
4457
+ inHead: true,
4458
+ awaitCount: 0,
4459
+ elementStack: [],
4460
+ options
4461
+ };
4462
+ b.append("");
4463
+ b.append("/* Head */");
4464
+ buildServerNode(current.head, status, b);
4465
+ flushOutput(status, b);
4466
+ }
4467
+ } else if (chunk.script === "/* @style */") {
4468
+ if (current.style) {
4469
+ b.append("");
4470
+ b.append("/* Style */");
4471
+ const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
4472
+ b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
4473
+ }
4474
+ } else if (chunk.script === "/* @end */") {
4475
+ b.append(`return { body: t_body, head: t_head };`);
4476
+ if (hasAwait) b.append(`});`);
4477
+ currentIndex += 1;
4478
+ current = template.components[currentIndex];
4479
+ } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
4480
+ else b.append(chunk.script);
3985
4481
  }
3986
- return false;
3987
4482
  }
3988
4483
  //#endregion
3989
4484
  //#region src/compile/utils/trimWhitespace.ts
3990
4485
  /**
3991
4486
  * Tag names whose contents should keep all whitespace untouched, matching
3992
4487
  * native HTML rendering of `pre`/`textarea` and the existing build-time
3993
- * `preserveWhitespace` behavior for `code`.
4488
+ * `preserveWhitespace` behavior for `code`. Raw-text elements (including
4489
+ * inline `<script>` / `<style>`) keep their contents exactly as written.
3994
4490
  */
3995
4491
  const PRESERVE_TAGS = /* @__PURE__ */ new Set([
3996
4492
  "pre",
@@ -4043,7 +4539,7 @@ function trimChildren(children, preserveAll, parentTag) {
4043
4539
  const grandChildren = getChildren(child);
4044
4540
  if (grandChildren) {
4045
4541
  const childTag = getTagName(child);
4046
- trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? ""), childTag);
4542
+ trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? "") || isRawTextTag(childTag ?? ""), childTag);
4047
4543
  }
4048
4544
  }
4049
4545
  if (preserveAll) return;
@@ -4982,7 +5478,7 @@ function serializeElement(node, context) {
4982
5478
  context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4983
5479
  return;
4984
5480
  }
4985
- const childContext = node.tagName === "pre" || node.tagName === "code" ? {
5481
+ const childContext = node.tagName === "pre" || node.tagName === "code" || isRawTextTag(node.tagName) ? {
4986
5482
  ...context,
4987
5483
  preserveWhitespace: true
4988
5484
  } : context;
@@ -5312,6 +5808,544 @@ function isSpaceNode(node) {
5312
5808
  return isTextNode(node) && isSpace(node.content);
5313
5809
  }
5314
5810
  //#endregion
5811
+ //#region src/compile/utils/nativeTags.ts
5812
+ /**
5813
+ * Native HTML and SVG tag names, used to tell elements apart from components.
5814
+ * A tag that is neither imported nor a component declared in the same file is
5815
+ * an element when it appears here, or when it contains a dash (an HTML custom
5816
+ * element). Anything else capitalized is reported as an unknown component.
5817
+ */
5818
+ const htmlTags = [
5819
+ "a",
5820
+ "abbr",
5821
+ "address",
5822
+ "area",
5823
+ "article",
5824
+ "aside",
5825
+ "audio",
5826
+ "b",
5827
+ "base",
5828
+ "bdi",
5829
+ "bdo",
5830
+ "blockquote",
5831
+ "body",
5832
+ "br",
5833
+ "button",
5834
+ "canvas",
5835
+ "caption",
5836
+ "cite",
5837
+ "code",
5838
+ "col",
5839
+ "colgroup",
5840
+ "data",
5841
+ "datalist",
5842
+ "dd",
5843
+ "del",
5844
+ "details",
5845
+ "dfn",
5846
+ "dialog",
5847
+ "div",
5848
+ "dl",
5849
+ "dt",
5850
+ "em",
5851
+ "embed",
5852
+ "fieldset",
5853
+ "figcaption",
5854
+ "figure",
5855
+ "footer",
5856
+ "form",
5857
+ "h1",
5858
+ "h2",
5859
+ "h3",
5860
+ "h4",
5861
+ "h5",
5862
+ "h6",
5863
+ "head",
5864
+ "header",
5865
+ "hgroup",
5866
+ "hr",
5867
+ "html",
5868
+ "i",
5869
+ "iframe",
5870
+ "img",
5871
+ "input",
5872
+ "ins",
5873
+ "kbd",
5874
+ "label",
5875
+ "legend",
5876
+ "li",
5877
+ "link",
5878
+ "main",
5879
+ "map",
5880
+ "mark",
5881
+ "menu",
5882
+ "meta",
5883
+ "meter",
5884
+ "nav",
5885
+ "noscript",
5886
+ "object",
5887
+ "ol",
5888
+ "optgroup",
5889
+ "option",
5890
+ "output",
5891
+ "p",
5892
+ "picture",
5893
+ "pre",
5894
+ "progress",
5895
+ "q",
5896
+ "rp",
5897
+ "rt",
5898
+ "ruby",
5899
+ "s",
5900
+ "samp",
5901
+ "script",
5902
+ "search",
5903
+ "section",
5904
+ "select",
5905
+ "slot",
5906
+ "small",
5907
+ "source",
5908
+ "span",
5909
+ "strong",
5910
+ "style",
5911
+ "sub",
5912
+ "summary",
5913
+ "sup",
5914
+ "table",
5915
+ "tbody",
5916
+ "td",
5917
+ "template",
5918
+ "textarea",
5919
+ "tfoot",
5920
+ "th",
5921
+ "thead",
5922
+ "time",
5923
+ "title",
5924
+ "tr",
5925
+ "track",
5926
+ "u",
5927
+ "ul",
5928
+ "var",
5929
+ "video",
5930
+ "wbr"
5931
+ ];
5932
+ const svgTags = [
5933
+ "a",
5934
+ "animate",
5935
+ "animateMotion",
5936
+ "animateTransform",
5937
+ "circle",
5938
+ "clipPath",
5939
+ "defs",
5940
+ "desc",
5941
+ "discard",
5942
+ "ellipse",
5943
+ "feBlend",
5944
+ "feColorMatrix",
5945
+ "feComponentTransfer",
5946
+ "feComposite",
5947
+ "feConvolveMatrix",
5948
+ "feDiffuseLighting",
5949
+ "feDisplacementMap",
5950
+ "feDistantLight",
5951
+ "feDropShadow",
5952
+ "feFlood",
5953
+ "feFuncA",
5954
+ "feFuncB",
5955
+ "feFuncG",
5956
+ "feFuncR",
5957
+ "feGaussianBlur",
5958
+ "feImage",
5959
+ "feMerge",
5960
+ "feMergeNode",
5961
+ "feMorphology",
5962
+ "feOffset",
5963
+ "fePointLight",
5964
+ "feSpecularLighting",
5965
+ "feSpotLight",
5966
+ "feTile",
5967
+ "feTurbulence",
5968
+ "filter",
5969
+ "foreignObject",
5970
+ "g",
5971
+ "image",
5972
+ "line",
5973
+ "linearGradient",
5974
+ "marker",
5975
+ "mask",
5976
+ "metadata",
5977
+ "mpath",
5978
+ "path",
5979
+ "pattern",
5980
+ "polygon",
5981
+ "polyline",
5982
+ "radialGradient",
5983
+ "rect",
5984
+ "script",
5985
+ "set",
5986
+ "stop",
5987
+ "style",
5988
+ "svg",
5989
+ "switch",
5990
+ "symbol",
5991
+ "text",
5992
+ "textPath",
5993
+ "title",
5994
+ "tspan",
5995
+ "use",
5996
+ "view"
5997
+ ];
5998
+ const nativeTags = /* @__PURE__ */ new Set([...htmlTags, ...svgTags]);
5999
+ //#endregion
6000
+ //#region src/compile/parse/utils/usesSlot.ts
6001
+ const slotRegex = /\$slot\b/;
6002
+ /**
6003
+ * Checks whether the $slot variable is read in the nodes' own scope
6004
+ *
6005
+ * Note that the children of a component node are excluded, because they are
6006
+ * passed to the component as fills, which get their own $slot parameter.
6007
+ * The component's attributes do belong to this scope.
6008
+ *
6009
+ * @param nodes The nodes to check
6010
+ *
6011
+ * @returns True if a $slot variable is read in the nodes' own scope
6012
+ */
6013
+ function usesSlot(nodes) {
6014
+ for (let node of nodes) if (node.type === "text") {
6015
+ const text = node;
6016
+ if (slotRegex.test(text.content)) return true;
6017
+ } else if (node.type === "control") {
6018
+ const control = node;
6019
+ if (slotRegex.test(control.statement)) return true;
6020
+ if (usesSlot(control.children)) return true;
6021
+ } else if (node.type === "element" || node.type === "special" || node.type === "component") {
6022
+ const element = node;
6023
+ for (let attribute of element.attributes) {
6024
+ if (slotRegex.test(attribute.name)) return true;
6025
+ if (attribute.value && slotRegex.test(attribute.value)) return true;
6026
+ }
6027
+ if (element.type !== "component" && usesSlot(element.children)) return true;
6028
+ }
6029
+ return false;
6030
+ }
6031
+ //#endregion
6032
+ //#region src/compile/parse/slottifyChildNodes.ts
6033
+ /**
6034
+ * Moves any child nodes that aren't already in a <fill> node into a default
6035
+ * <fill> node
6036
+ */
6037
+ function slottifyChildNodes(node) {
6038
+ let nonFillNodes = [];
6039
+ for (let child of node.children) if (isFillNode(child)) {
6040
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
6041
+ else break;
6042
+ } else nonFillNodes.push(child);
6043
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
6044
+ if (nonFillNodes.length) {
6045
+ let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
6046
+ if (!defaultFillNode) {
6047
+ defaultFillNode = {
6048
+ type: "special",
6049
+ tagName: "filldef",
6050
+ attributes: [],
6051
+ children: nonFillNodes,
6052
+ span: {
6053
+ start: 0,
6054
+ end: 0
6055
+ },
6056
+ hasSlotProps: usesSlot(nonFillNodes)
6057
+ };
6058
+ node.children.unshift(defaultFillNode);
6059
+ }
6060
+ node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
6061
+ }
6062
+ }
6063
+ function isFillNode(n) {
6064
+ return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
6065
+ }
6066
+ //#endregion
6067
+ //#region src/compile/parse/utils/addError.ts
6068
+ /**
6069
+ * Adds an error to the parse status
6070
+ *
6071
+ * @param status The parse status
6072
+ * @param message The error message to add
6073
+ * @param start (Optional) The start position of the error (defaults to the
6074
+ * current parse position)
6075
+ */
6076
+ function addError(status, message, start = status.i, end = status.i) {
6077
+ let startLine = 0;
6078
+ let lastLineStart = 0;
6079
+ let i = 0;
6080
+ for (; i < start; i++) if (status.source[i] === "\n") {
6081
+ startLine += 1;
6082
+ lastLineStart = i + 1;
6083
+ }
6084
+ let startChar = start - lastLineStart;
6085
+ let endLine = startLine;
6086
+ for (; i < end; i++) if (status.source[i] === "\n") {
6087
+ endLine += 1;
6088
+ lastLineStart = i + 1;
6089
+ }
6090
+ let endChar = end - lastLineStart;
6091
+ status.errors.push({
6092
+ message,
6093
+ startIndex: start,
6094
+ startLine,
6095
+ startChar,
6096
+ endIndex: end,
6097
+ endLine,
6098
+ endChar
6099
+ });
6100
+ }
6101
+ //#endregion
6102
+ //#region src/compile/parse/classifyComponents.ts
6103
+ /**
6104
+ * Classifies parsed tags as components or native elements once the whole file
6105
+ * has been parsed (so forward-declared local components are known).
6106
+ *
6107
+ * A tag is a component when its name is imported or is a component declared in
6108
+ * this file. Native and custom elements (`<div>`, `<my-widget>`,
6109
+ * `<linearGradient>`) stay elements. Any other capitalized tag is reported as
6110
+ * unknown instead of silently becoming a component call, unless the caller
6111
+ * opts into assuming external components (`allowUnknownComponents`).
6112
+ */
6113
+ function classifyComponents(status, importedNames, options) {
6114
+ const localNames = new Set(status.components.map((component) => component.name).filter((name) => !!name));
6115
+ for (const component of status.components) {
6116
+ if (component.markup) classifyNode(component.markup, status, importedNames, localNames, options);
6117
+ if (component.error) classifyNode(component.error, status, importedNames, localNames, options);
6118
+ if (component.head) classifyNode(component.head, status, importedNames, localNames, options);
6119
+ }
6120
+ }
6121
+ function classifyNode(node, status, importedNames, localNames, options) {
6122
+ if (isParentNode(node)) for (const child of node.children) classifyNode(child, status, importedNames, localNames, options);
6123
+ if (!isElementNode(node)) return;
6124
+ const tagName = node.tagName;
6125
+ if (importedNames.has(tagName) || localNames.has(tagName)) {
6126
+ node.type = "component";
6127
+ slottifyChildNodes(node);
6128
+ } else if (!nativeTags.has(tagName) && !tagName.includes("-") && /^[A-Z]/.test(tagName)) {
6129
+ if (options?.allowUnknownComponents) {
6130
+ node.type = "component";
6131
+ slottifyChildNodes(node);
6132
+ } else addError(status, `Unknown component or element: ${tagName}. Import it or define it in this file.`, node.span.start, node.span.end);
6133
+ }
6134
+ }
6135
+ //#endregion
6136
+ //#region src/compile/parse/collectImportNames.ts
6137
+ /**
6138
+ * Collects the local binding names introduced by top-level import statements.
6139
+ * Used to tell component tags apart from native elements without touching the
6140
+ * filesystem or relying on a tag-name convention.
6141
+ *
6142
+ * This is a focused import scanner, not a general JS parser: it handles the
6143
+ * import forms (`default`, `* as`, named/aliased, side-effect), comments and
6144
+ * multiline clauses. Type-only imports are ignored (they don't introduce a
6145
+ * value that can be rendered as a tag).
6146
+ */
6147
+ function collectImportNames(source) {
6148
+ const names = /* @__PURE__ */ new Set();
6149
+ let depth = 0;
6150
+ let i = 0;
6151
+ while (i < source.length) {
6152
+ const skipped = skipStringOrComment(source, i);
6153
+ if (skipped !== -1) {
6154
+ i = skipped;
6155
+ continue;
6156
+ }
6157
+ const char = source[i];
6158
+ if (char === "{") {
6159
+ depth += 1;
6160
+ i += 1;
6161
+ continue;
6162
+ }
6163
+ if (char === "}") {
6164
+ depth -= 1;
6165
+ i += 1;
6166
+ continue;
6167
+ }
6168
+ if (depth === 0 && char === "i" && startsWordAt(source, i, "import") && source[i - 1] !== ".") {
6169
+ const end = parseImport(source, i + 6, names);
6170
+ if (end !== -1) {
6171
+ i = end;
6172
+ continue;
6173
+ }
6174
+ }
6175
+ i += 1;
6176
+ }
6177
+ return names;
6178
+ }
6179
+ /** Parses one import statement, adding its value bindings. Returns the end index. */
6180
+ function parseImport(source, start, names) {
6181
+ let i = skipSpaceAndComments(source, start);
6182
+ if (i >= source.length) return -1;
6183
+ if (source[i] === "." || source[i] === "(") return -1;
6184
+ if (source[i] === "\"" || source[i] === "'") return skipStringAndStatementEnd(source, i);
6185
+ let typeOnly = false;
6186
+ if (startsWordAt(source, i, "type")) {
6187
+ const afterType = skipSpaceAndComments(source, i + 4);
6188
+ const next = source[afterType];
6189
+ if (next === "{" || next === "*" || isIdentifierStart(next)) {
6190
+ if (next === "{" || next === "*" || isTypeOnlyDefault(source, afterType)) {
6191
+ typeOnly = true;
6192
+ i = afterType;
6193
+ }
6194
+ }
6195
+ }
6196
+ while (i < source.length) {
6197
+ i = skipSpaceAndComments(source, i);
6198
+ if (i >= source.length) return -1;
6199
+ if (startsWordAt(source, i, "from")) {
6200
+ i = skipStringAndStatementEnd(source, skipSpaceAndComments(source, i + 4));
6201
+ return i;
6202
+ }
6203
+ const char = source[i];
6204
+ if (char === "{") {
6205
+ i += 1;
6206
+ while (i < source.length) {
6207
+ i = skipSpaceAndComments(source, i);
6208
+ if (source[i] === "}") {
6209
+ i += 1;
6210
+ break;
6211
+ }
6212
+ const specifier = parseSpecifier(source, i);
6213
+ if (!specifier) {
6214
+ i += 1;
6215
+ continue;
6216
+ }
6217
+ i = specifier.end;
6218
+ if (!typeOnly && specifier.name) names.add(specifier.name);
6219
+ }
6220
+ continue;
6221
+ }
6222
+ if (char === "*") {
6223
+ i = skipSpaceAndComments(source, i + 1);
6224
+ if (startsWordAt(source, i, "as")) {
6225
+ i = skipSpaceAndComments(source, i + 2);
6226
+ const identifier = readIdentifier(source, i);
6227
+ if (identifier) {
6228
+ if (!typeOnly) names.add(identifier.name);
6229
+ i = identifier.end;
6230
+ }
6231
+ }
6232
+ continue;
6233
+ }
6234
+ if (char === ",") {
6235
+ i += 1;
6236
+ continue;
6237
+ }
6238
+ if (isIdentifierStart(char)) {
6239
+ const identifier = readIdentifier(source, i);
6240
+ if (identifier) {
6241
+ if (!typeOnly) names.add(identifier.name);
6242
+ i = identifier.end;
6243
+ continue;
6244
+ }
6245
+ }
6246
+ i += 1;
6247
+ }
6248
+ return -1;
6249
+ }
6250
+ function parseSpecifier(source, start) {
6251
+ let i = skipSpaceAndComments(source, start);
6252
+ if (i >= source.length) return void 0;
6253
+ let typeOnly = false;
6254
+ if (startsWordAt(source, i, "type")) {
6255
+ const afterType = skipSpaceAndComments(source, i + 4);
6256
+ const next = source[afterType];
6257
+ if (next && next !== "," && next !== "}" && !startsWordAt(source, afterType, "as")) {
6258
+ typeOnly = true;
6259
+ i = afterType;
6260
+ }
6261
+ }
6262
+ let name;
6263
+ if (source[i] === "\"" || source[i] === "'") {
6264
+ const end = skipStringOrComment(source, i);
6265
+ i = end === -1 ? i + 1 : end;
6266
+ } else {
6267
+ const identifier = readIdentifier(source, i);
6268
+ if (!identifier) return void 0;
6269
+ name = identifier.name;
6270
+ i = identifier.end;
6271
+ }
6272
+ i = skipSpaceAndComments(source, i);
6273
+ if (startsWordAt(source, i, "as")) {
6274
+ i = skipSpaceAndComments(source, i + 2);
6275
+ if (source[i] === "\"" || source[i] === "'") {
6276
+ const end = skipStringOrComment(source, i);
6277
+ i = end === -1 ? i + 1 : end;
6278
+ name = void 0;
6279
+ } else {
6280
+ const alias = readIdentifier(source, i);
6281
+ if (alias) {
6282
+ name = alias.name;
6283
+ i = alias.end;
6284
+ }
6285
+ }
6286
+ }
6287
+ i = skipSpaceAndComments(source, i);
6288
+ if (source[i] === ",") i += 1;
6289
+ return {
6290
+ name: typeOnly ? void 0 : name,
6291
+ end: i
6292
+ };
6293
+ }
6294
+ function isTypeOnlyDefault(source, start) {
6295
+ const identifier = readIdentifier(source, start);
6296
+ if (!identifier) return false;
6297
+ return startsWordAt(source, skipSpaceAndComments(source, identifier.end), "from");
6298
+ }
6299
+ function skipStringAndStatementEnd(source, start) {
6300
+ let i = start;
6301
+ if (source[i] === "\"" || source[i] === "'") {
6302
+ const end = skipStringOrComment(source, i);
6303
+ i = end === -1 ? i + 1 : end;
6304
+ }
6305
+ i = skipSpaceAndComments(source, i);
6306
+ if (source[i] === ";") i += 1;
6307
+ return i;
6308
+ }
6309
+ function skipSpaceAndComments(source, start) {
6310
+ let i = start;
6311
+ while (i < source.length) {
6312
+ if (/\s/.test(source[i])) {
6313
+ i += 1;
6314
+ continue;
6315
+ }
6316
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) {
6317
+ const skipped = skipStringOrComment(source, i);
6318
+ if (skipped !== -1) {
6319
+ i = skipped;
6320
+ continue;
6321
+ }
6322
+ }
6323
+ break;
6324
+ }
6325
+ return i;
6326
+ }
6327
+ function readIdentifier(source, start) {
6328
+ if (!isIdentifierStart(source[start])) return void 0;
6329
+ let end = start + 1;
6330
+ while (end < source.length && isIdentifierPart(source[end])) end += 1;
6331
+ return {
6332
+ name: source.substring(start, end),
6333
+ end
6334
+ };
6335
+ }
6336
+ function isIdentifierStart(char) {
6337
+ return char !== void 0 && /[A-Za-z_$]/.test(char);
6338
+ }
6339
+ function isIdentifierPart(char) {
6340
+ return /[A-Za-z0-9_$]/.test(char);
6341
+ }
6342
+ function startsWordAt(source, start, word) {
6343
+ if (!source.startsWith(word, start)) return false;
6344
+ const previous = source[start - 1];
6345
+ const next = source[start + word.length];
6346
+ return (previous === void 0 || !isIdentifierPart(previous)) && (next === void 0 || !isIdentifierPart(next));
6347
+ }
6348
+ //#endregion
5315
6349
  //#region src/compile/parse/utils/accept.ts
5316
6350
  /**
5317
6351
  * Checks whether the source at the current parse position matches the supplied
@@ -5401,79 +6435,36 @@ function addSpaceElement(parent, status) {
5401
6435
  //#endregion
5402
6436
  //#region src/compile/utils/isFullyReactive.ts
5403
6437
  /**
5404
- * Checks whether the supplied string is fully reactive (i.e. starts and ends with braces)
6438
+ * Checks whether the supplied text is exactly one `{...}` interpolation,
6439
+ * ignoring surrounding whitespace. Braces inside the expression's strings and
6440
+ * comments don't count as delimiters.
5405
6441
  *
5406
- * @param text The string to check
6442
+ * @param text The text to check
5407
6443
  *
5408
- * @returns True if the supplied string is fully reactive
6444
+ * @returns True if the supplied text is fully reactive
5409
6445
  */
5410
6446
  function isFullyReactive(text) {
5411
- return text.trim().startsWith("{") && text.trim().endsWith("}");
6447
+ return isSingleInterpolation(text);
5412
6448
  }
5413
6449
  //#endregion
5414
- //#region src/compile/parse/utils/addError.ts
6450
+ //#region src/compile/parse/utils/consumeTagName.ts
5415
6451
  /**
5416
- * Adds an error to the parse status
6452
+ * Consumes a tag name, allowing letters, digits and dashes (custom elements
6453
+ * such as `<my-widget>`), and advances the current parse position to before
6454
+ * the next non-name character.
5417
6455
  *
5418
6456
  * @param status The parse status
5419
- * @param message The error message to add
5420
- * @param start (Optional) The start position of the error (defaults to the
5421
- * current parse position)
5422
- */
5423
- function addError(status, message, start = status.i, end = status.i) {
5424
- let startLine = 0;
5425
- let lastLineStart = 0;
5426
- let i = 0;
5427
- for (; i < start; i++) if (status.source[i] === "\n") {
5428
- startLine += 1;
5429
- lastLineStart = i + 1;
5430
- }
5431
- let startChar = start - lastLineStart;
5432
- let endLine = startLine;
5433
- for (; i < end; i++) if (status.source[i] === "\n") {
5434
- endLine += 1;
5435
- lastLineStart = i + 1;
5436
- }
5437
- let endChar = end - lastLineStart;
5438
- status.errors.push({
5439
- message,
5440
- startIndex: start,
5441
- startLine,
5442
- startChar,
5443
- endIndex: end,
5444
- endLine,
5445
- endChar
5446
- });
5447
- }
5448
- //#endregion
5449
- //#region src/compile/parse/utils/isAlphaNumericChar.ts
5450
- /**
5451
- * Checks whether the supplied character is a alpha-numeric
5452
6457
  *
5453
- * @param text The string to check
5454
- * @param index The index of the character in the string
5455
- *
5456
- * @returns True if the supplied character is alpha-numeric
6458
+ * @returns The tag name from the current parse position to the next non-name
6459
+ * character
5457
6460
  */
5458
- function isAlphaNumericChar(text, index) {
5459
- let code = text.charCodeAt(index);
5460
- return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
5461
- }
5462
- //#endregion
5463
- //#region src/compile/parse/utils/consumeAlphaNumeric.ts
5464
- /**
5465
- * Consumes alpha-numeric characters and advances the current parse position to
5466
- * before the next non-alpha character
5467
- *
5468
- * @param status The parse status
5469
- *
5470
- * @returns The string of alpha-numeric characters from the current parse position
5471
- * to the next non-alpha character
5472
- */
5473
- function consumeAlphaNumeric(status) {
6461
+ function consumeTagName(status) {
5474
6462
  const start = status.i;
5475
- for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
5476
- return "";
6463
+ for (status.i; status.i < status.source.length; status.i++) {
6464
+ const char = status.source[status.i];
6465
+ if (!/[A-Za-z0-9-]/.test(char)) return status.source.substring(start, status.i);
6466
+ }
6467
+ return status.source.substring(start, status.i);
5477
6468
  }
5478
6469
  //#endregion
5479
6470
  //#region src/compile/parse/utils/consumeUntil.ts
@@ -5500,7 +6491,7 @@ function parseTag(status) {
5500
6491
  consumeSpace(status);
5501
6492
  let tagStart = status.i + 1;
5502
6493
  let snailed = accept("@", status);
5503
- let tagName = consumeAlphaNumeric(status);
6494
+ let tagName = consumeTagName(status);
5504
6495
  let tagEnd = status.i;
5505
6496
  if (snailed) tagName = "@" + tagName;
5506
6497
  if (closeTag) tagName = "/" + tagName;
@@ -5555,14 +6546,20 @@ function parseAttribute(status) {
5555
6546
  if (accept("=", status)) {
5556
6547
  consumeSpace(status);
5557
6548
  valueStart = status.i;
5558
- value = parseAttributeValue(status);
5559
- valueEnd = status.i;
5560
- reactive = isReactive(value);
5561
- fullyReactive = isFullyReactive(value);
5562
- if (fullyReactive) {
5563
- value = value.substring(1, value.length - 1);
5564
- valueStart++;
5565
- valueEnd--;
6549
+ if (status.source[valueStart] === "`") {
6550
+ value = parseTemplateLiteral(status);
6551
+ valueEnd = status.i;
6552
+ reactive = fullyReactive = true;
6553
+ } else {
6554
+ value = parseAttributeValue(status);
6555
+ valueEnd = status.i;
6556
+ fullyReactive = isFullyReactive(value);
6557
+ reactive = fullyReactive;
6558
+ if (fullyReactive) {
6559
+ value = value.substring(1, value.length - 1);
6560
+ valueStart++;
6561
+ valueEnd--;
6562
+ }
5566
6563
  }
5567
6564
  } else if (name.startsWith("{") && name.endsWith("}")) {
5568
6565
  value = name.substring(1, name.length - 1);
@@ -5585,6 +6582,18 @@ function parseAttribute(status) {
5585
6582
  }
5586
6583
  };
5587
6584
  }
6585
+ /**
6586
+ * Consumes a backtick-delimited JavaScript template literal, reusing the
6587
+ * script scanner so `${...}` interpolations and nested strings/templates are
6588
+ * skipped correctly.
6589
+ */
6590
+ function parseTemplateLiteral(status) {
6591
+ const start = status.i;
6592
+ const end = skipStringOrComment(status.source, start);
6593
+ status.i = end === -1 ? start + 1 : end;
6594
+ if (status.source[status.i - 1] !== "`") addError(status, "Unclosed template literal in attribute", start, status.i);
6595
+ return status.source.substring(start, status.i);
6596
+ }
5588
6597
  function parseAttributeValue(status) {
5589
6598
  if (accept("\"", status)) {
5590
6599
  const value = consumeUntil("\"", status);
@@ -5665,73 +6674,6 @@ function parseText(status, element) {
5665
6674
  } else status.i += 1;
5666
6675
  }
5667
6676
  //#endregion
5668
- //#region src/compile/parse/utils/usesSlot.ts
5669
- const slotRegex = /\$slot\b/;
5670
- /**
5671
- * Checks whether the $slot variable is read in the nodes' own scope
5672
- *
5673
- * Note that the children of a component node are excluded, because they are
5674
- * passed to the component as fills, which get their own $slot parameter.
5675
- * The component's attributes do belong to this scope.
5676
- *
5677
- * @param nodes The nodes to check
5678
- *
5679
- * @returns True if a $slot variable is read in the nodes' own scope
5680
- */
5681
- function usesSlot(nodes) {
5682
- for (let node of nodes) if (node.type === "text") {
5683
- const text = node;
5684
- if (slotRegex.test(text.content)) return true;
5685
- } else if (node.type === "control") {
5686
- const control = node;
5687
- if (slotRegex.test(control.statement)) return true;
5688
- if (usesSlot(control.children)) return true;
5689
- } else if (node.type === "element" || node.type === "special" || node.type === "component") {
5690
- const element = node;
5691
- for (let attribute of element.attributes) {
5692
- if (slotRegex.test(attribute.name)) return true;
5693
- if (attribute.value && slotRegex.test(attribute.value)) return true;
5694
- }
5695
- if (element.type !== "component" && usesSlot(element.children)) return true;
5696
- }
5697
- return false;
5698
- }
5699
- //#endregion
5700
- //#region src/compile/parse/slottifyChildNodes.ts
5701
- /**
5702
- * Moves any child nodes that aren't already in a <fill> node into a default
5703
- * <fill> node
5704
- */
5705
- function slottifyChildNodes(node) {
5706
- let nonFillNodes = [];
5707
- for (let child of node.children) if (isFillNode(child)) {
5708
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5709
- else break;
5710
- } else nonFillNodes.push(child);
5711
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5712
- if (nonFillNodes.length) {
5713
- let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
5714
- if (!defaultFillNode) {
5715
- defaultFillNode = {
5716
- type: "special",
5717
- tagName: "filldef",
5718
- attributes: [],
5719
- children: nonFillNodes,
5720
- span: {
5721
- start: 0,
5722
- end: 0
5723
- },
5724
- hasSlotProps: usesSlot(nonFillNodes)
5725
- };
5726
- node.children.unshift(defaultFillNode);
5727
- }
5728
- node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
5729
- }
5730
- }
5731
- function isFillNode(n) {
5732
- return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
5733
- }
5734
- //#endregion
5735
6677
  //#region src/compile/parse/parseElement.ts
5736
6678
  function parseElement(status) {
5737
6679
  const current = status.components.at(-1);
@@ -5745,6 +6687,7 @@ function parseElement(status) {
5745
6687
  if (voidTags.includes(element.tagName)) checkVoidElement(status, element);
5746
6688
  if (!element.selfClosed && !voidTags.includes(element.tagName)) {
5747
6689
  status.stack.push(element);
6690
+ if (isRawTextTag(element.tagName)) parseRawText(status, element);
5748
6691
  while (status.i < status.source.length) {
5749
6692
  addSpaceElement(element, status);
5750
6693
  if (accept("}", status, false)) break;
@@ -5785,10 +6728,6 @@ function parseElement(status) {
5785
6728
  }
5786
6729
  status.stack.pop();
5787
6730
  }
5788
- if (/[A-Z]/.test(element.tagName[0])) {
5789
- element.type = "component";
5790
- slottifyChildNodes(element);
5791
- }
5792
6731
  if (isSpecialNode(element)) {
5793
6732
  if (element.tagName === "slot") {
5794
6733
  slottifyChildNodes(element);
@@ -5826,6 +6765,32 @@ function parseElement(status) {
5826
6765
  if (!element.closed && !voidTags.includes(element.tagName)) addError(status, `Unclosed non-void element: ${element.tagName}`, start, start + element.tagName.length + 1);
5827
6766
  return element;
5828
6767
  }
6768
+ /**
6769
+ * Consumes a raw-text element's content as a single literal text node. The
6770
+ * content ends at the first matching close tag (which the caller's child loop
6771
+ * then handles), or at the end of the source when the element is unclosed.
6772
+ */
6773
+ function parseRawText(status, element) {
6774
+ const start = status.i;
6775
+ const end = findRawTextEnd(status.source, element.tagName, start);
6776
+ if (end > start) {
6777
+ const text = {
6778
+ type: "text",
6779
+ content: status.source.substring(start, end),
6780
+ start,
6781
+ spans: [],
6782
+ raw: true
6783
+ };
6784
+ element.children.push(text);
6785
+ }
6786
+ status.i = end;
6787
+ }
6788
+ function findRawTextEnd(source, tagName, start) {
6789
+ const pattern = new RegExp(`</${tagName}(?=[\\s/>])`, "gi");
6790
+ pattern.lastIndex = start;
6791
+ const match = pattern.exec(source);
6792
+ return match ? match.index : source.length;
6793
+ }
5829
6794
  function checkVoidElement(status, element) {
5830
6795
  let i = status.i;
5831
6796
  consumeSpace(status);
@@ -5845,7 +6810,7 @@ function checkCloseTag(status, element) {
5845
6810
  accept("</", status);
5846
6811
  consumeSpace(status);
5847
6812
  let snailed = accept("@", status);
5848
- let closingTagName = consumeAlphaNumeric(status);
6813
+ let closingTagName = consumeTagName(status);
5849
6814
  if (snailed) closingTagName = "@" + closingTagName;
5850
6815
  consumeSpace(status);
5851
6816
  accept(">", status);
@@ -5955,6 +6920,8 @@ function parseControlOpen(status) {
5955
6920
  };
5956
6921
  }
5957
6922
  function parseControlStatement(start, operation, status) {
6923
+ const standalone = standaloneOperations.includes(operation);
6924
+ const braceStartsBody = !standalone || operation === "@function" || operation === "@async function";
5958
6925
  let parenCount = 0;
5959
6926
  while (status.i < status.source.length) {
5960
6927
  const skipped = skipStringOrComment(status.source, status.i);
@@ -5964,11 +6931,11 @@ function parseControlStatement(start, operation, status) {
5964
6931
  }
5965
6932
  if (accept("(", status)) parenCount += 1;
5966
6933
  else if (accept(")", status)) parenCount -= 1;
5967
- else if (accept("{", status) || accept("\n", status) && standaloneOperations.includes(operation)) {
6934
+ else if (accept("{", status) && braceStartsBody || accept("\n", status) && standalone) {
5968
6935
  if (parenCount === 0) return trimStart(status.source.substring(start, status.i - 1).trim(), "@");
5969
6936
  } else status.i += 1;
5970
6937
  }
5971
- return "";
6938
+ return trimStart(status.source.substring(start, status.i).trim(), "@");
5972
6939
  }
5973
6940
  /**
5974
6941
  * Groups the control node into the correct parent e.g. if/else into an if group
@@ -6221,7 +7188,6 @@ function parseStyles(source, status) {
6221
7188
  marker: 0,
6222
7189
  level: 0,
6223
7190
  braces: [],
6224
- imports: [],
6225
7191
  script: [],
6226
7192
  components: [],
6227
7193
  stack: [],
@@ -6300,37 +7266,64 @@ function parseStyleAttribute(status) {
6300
7266
  }
6301
7267
  //#endregion
6302
7268
  //#region src/compile/parse/scopeStyles.ts
7269
+ /**
7270
+ * Marks every element in a component that has scoped styles with the
7271
+ * component's scope class. This is intentionally not selector-based: deciding
7272
+ * which elements a CSS selector can match requires parsing selectors, and
7273
+ * pseudo-classes, attribute selectors and `@media` rules make compile-time
7274
+ * matching unreliable. Marking every element lets `buildStyles` append the
7275
+ * scope class to selectors without needing to understand their shape.
7276
+ */
6303
7277
  function scopeStyles(status) {
6304
- let selectors = [];
6305
- for (let component of status.components) if (component.style && component.markup) {
6306
- for (let block of component.style.children) if (block.type === "block") collectStyleSelectors(block, selectors);
6307
- scopeStylesOnNode(component.markup, selectors);
7278
+ for (let component of status.components) {
7279
+ if (!component.style) continue;
7280
+ if (component.markup) scopeStylesOnNode(component.markup);
7281
+ if (component.error) scopeStylesOnNode(component.error);
6308
7282
  }
6309
7283
  }
6310
- function scopeStylesOnNode(node, selectors) {
6311
- if (isElementNode(node) || isComponentNode(node)) node.scopeStyles = selectors.includes(node.tagName) || node.attributes.find((a) => {
6312
- if (a.name === "class" && a.reactive) return true;
6313
- else if (a.name === "id" && a.value) {
6314
- if (selectors.includes(`#${trimQuotes(a.value)}`)) return true;
6315
- } else if (a.name === "class" && a.value) {
6316
- for (let classname of trimQuotes(a.value).split(/\s+/)) if (selectors.includes(`.${classname}`)) return true;
6317
- }
6318
- }) !== void 0;
6319
- if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child, selectors);
7284
+ function scopeStylesOnNode(node) {
7285
+ if (isElementNode(node) || isComponentNode(node) || isSpecialNode(node) && (node.tagName === "@element" || node.tagName === "@component")) node.scopeStyles = true;
7286
+ if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child);
6320
7287
  }
6321
- function collectStyleSelectors(block, selectors) {
6322
- for (let s of block.selector.split(/[\s*,>+~[\]]/)) selectors.push(s);
7288
+ //#endregion
7289
+ //#region src/compile/parse/utils/isAlphaNumericChar.ts
7290
+ /**
7291
+ * Checks whether the supplied character is a alpha-numeric
7292
+ *
7293
+ * @param text The string to check
7294
+ * @param index The index of the character in the string
7295
+ *
7296
+ * @returns True if the supplied character is alpha-numeric
7297
+ */
7298
+ function isAlphaNumericChar(text, index) {
7299
+ let code = text.charCodeAt(index);
7300
+ return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
7301
+ }
7302
+ //#endregion
7303
+ //#region src/compile/parse/utils/consumeAlphaNumeric.ts
7304
+ /**
7305
+ * Consumes alpha-numeric characters and advances the current parse position to
7306
+ * before the next non-alpha character
7307
+ *
7308
+ * @param status The parse status
7309
+ *
7310
+ * @returns The string of alpha-numeric characters from the current parse position
7311
+ * to the next non-alpha character
7312
+ */
7313
+ function consumeAlphaNumeric(status) {
7314
+ const start = status.i;
7315
+ for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
7316
+ return "";
6323
7317
  }
6324
7318
  //#endregion
6325
7319
  //#region src/compile/parse/parseCode.ts
6326
- function parseCode(source) {
7320
+ function parseCode(source, options) {
6327
7321
  const status = {
6328
7322
  source,
6329
7323
  i: 0,
6330
7324
  marker: 0,
6331
7325
  level: 0,
6332
7326
  braces: [],
6333
- imports: [],
6334
7327
  script: [],
6335
7328
  components: [],
6336
7329
  stack: [],
@@ -6386,6 +7379,7 @@ function parseCode(source) {
6386
7379
  end: source.length
6387
7380
  }
6388
7381
  });
7382
+ classifyComponents(status, collectImportNames(source), options);
6389
7383
  scopeStyles(status);
6390
7384
  const ok = !status.errors.length;
6391
7385
  if (!ok) status.errors = status.errors.sort((a, b) => a.startIndex - b.startIndex);
@@ -6393,7 +7387,6 @@ function parseCode(source) {
6393
7387
  ok,
6394
7388
  errors: status.errors,
6395
7389
  template: ok ? {
6396
- imports: status.imports,
6397
7390
  script: status.script,
6398
7391
  components: status.components
6399
7392
  } : void 0
@@ -6489,7 +7482,6 @@ function parseComponentStart(status) {
6489
7482
  marker: 0,
6490
7483
  level: 0,
6491
7484
  braces: [],
6492
- imports: [],
6493
7485
  script: [],
6494
7486
  components: [],
6495
7487
  stack: [],
@@ -6750,12 +7742,13 @@ function consumeScriptComments(status) {
6750
7742
  * Parses source code into a component template
6751
7743
  *
6752
7744
  * @param source The source code
7745
+ * @param options Optional parse behaviour
6753
7746
  *
6754
7747
  * @returns A result indicating whether parsing was ok, and if so, containing
6755
7748
  * the component template's parts such as script, markup and styles
6756
7749
  */
6757
- function parse(source) {
6758
- return parseCode(source);
7750
+ function parse(source, options) {
7751
+ return parseCode(source, options);
6759
7752
  }
6760
7753
  //#endregion
6761
7754
  //#region src/compile/parse/bindDataTemplate.ts