@torpor/view 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/{Effect-99HYQdzZ.d.mts → Effect-Bi_nt6cx.d.cts} +31 -3
  2. package/dist/Effect-Bi_nt6cx.d.cts.map +1 -0
  3. package/dist/{Effect-Bf8fz_zC.d.cts → Effect-Bi_nt6cx.d.mts} +31 -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 +1316 -400
  14. package/dist/compile.d.cts +16 -12
  15. package/dist/compile.d.cts.map +1 -1
  16. package/dist/compile.d.mts +16 -12
  17. package/dist/compile.d.mts.map +1 -1
  18. package/dist/compile.mjs +1316 -400
  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 +621 -269
  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 +609 -258
  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-99HYQdzZ.d.mts.map +0 -1
  56. package/dist/Effect-Bf8fz_zC.d.cts.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}"`;
@@ -886,6 +992,21 @@ function isSpecialNode(node) {
886
992
  return node.type === "special";
887
993
  }
888
994
  //#endregion
995
+ //#region src/compile/utils/propKey.ts
996
+ const IDENTIFIER_REGEX = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
997
+ /**
998
+ * Formats a prop name for use as an object key in generated code. Valid
999
+ * identifiers are left unquoted; anything else (e.g. dashed props like
1000
+ * `aria-hidden`) is quoted so that the generated code stays valid.
1001
+ *
1002
+ * @param name The prop name as written on the component or slot
1003
+ *
1004
+ * @returns The name as an object key text
1005
+ */
1006
+ function propKey(name) {
1007
+ return IDENTIFIER_REGEX.test(name) ? name : JSON.stringify(name);
1008
+ }
1009
+ //#endregion
889
1010
  //#region src/compile/build/utils/nextVarName.ts
890
1011
  /**
891
1012
  * Makes a supplied variable name (hopefully!) unique by prepending `t_` and
@@ -953,7 +1074,7 @@ function containsIdentifier(value, name) {
953
1074
  * effect to the loop variable's signal).
954
1075
  */
955
1076
  function forVarBindings(status, source) {
956
- return collectBindings(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
1077
+ return collectBindings$1(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
957
1078
  }
958
1079
  /**
959
1080
  * Like `forVarBindings`, but binds only the loop variables named in `names`.
@@ -961,9 +1082,9 @@ function forVarBindings(status, source) {
961
1082
  * the scope's directly-evaluated code reads.
962
1083
  */
963
1084
  function forVarBindingsFor(status, names) {
964
- return collectBindings(status, (forVar) => names.has(forVar.name));
1085
+ return collectBindings$1(status, (forVar) => names.has(forVar.name));
965
1086
  }
966
- function collectBindings(status, include) {
1087
+ function collectBindings$1(status, include) {
967
1088
  const bound = /* @__PURE__ */ new Set();
968
1089
  let result = "";
969
1090
  for (let i = status.forVars.length - 1; i >= 0; i--) {
@@ -1346,7 +1467,7 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1346
1467
  if (lastType === "text" || lastType === "space") return;
1347
1468
  let textPath = {
1348
1469
  parent: path,
1349
- type: isSpace(node.content) ? "space" : "text",
1470
+ type: !node.raw && isSpace(node.content) ? "space" : "text",
1350
1471
  children: []
1351
1472
  };
1352
1473
  path.children.push(textPath);
@@ -1366,11 +1487,12 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1366
1487
  } else {
1367
1488
  status.imports.add("t_txt");
1368
1489
  if (declareVariable) b.append(`(${node.varName} = t_txt(" ")),`);
1490
+ else if (node.raw) b.append(`t_txt(${JSON.stringify(node.content)}),`);
1369
1491
  else b.append(`t_txt("${node.content}"),`);
1370
1492
  }
1371
1493
  }
1372
1494
  function textNodeNeedsDeclaration(node, topLevel, lastChild) {
1373
- return isReactive(node.content) || topLevel && lastChild;
1495
+ return !node.raw && isReactive(node.content) || topLevel && lastChild;
1374
1496
  }
1375
1497
  function declareSpecialFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, lastChild, declare) {
1376
1498
  if (node.tagName === "slot") declareParentAndAnchorFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, "slot", declare);
@@ -1707,8 +1829,9 @@ function buildComponentNode(node, status, b, root = false) {
1707
1829
  let value = p.value;
1708
1830
  p.preText ??= "";
1709
1831
  p.postText ??= "";
1710
- if (p.spans.length === 1) addMappedText(p.name ? `${p.name}: ` + p.preText : p.preText, value, p.postText + ",", p.spans[0], status, b);
1711
- else addMappedTextWithOffsets(p.name ? `${p.name}: ` + p.preText : p.preText, value, p.postText + ",", p.spans, p.offsets, p.lengths, status, b);
1832
+ const key = p.name ? `${propKey(p.name)}: ` : "";
1833
+ if (p.spans.length === 1) addMappedText(key + p.preText, value, p.postText + ",", p.spans[0], status, b);
1834
+ else addMappedTextWithOffsets(key + p.preText, value, p.postText + ",", p.spans, p.offsets, p.lengths, status, b);
1712
1835
  }
1713
1836
  b.append("});");
1714
1837
  if (runs.length) buildRun("setProps", runs.join("\n"), status, b);
@@ -1868,41 +1991,185 @@ function isForBodyLeafSafe(forBodyChildren) {
1868
1991
  }
1869
1992
  //#endregion
1870
1993
  //#region src/compile/utils/forLoopVarNames.ts
1994
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1871
1995
  /**
1872
1996
  * Extracts the declared loop variable names from a `@for` statement — the
1873
- * heuristic header parse shared by `buildForNode` (codegen) and the write
1874
- * scanners (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect
1875
- * nested loops that shadow an outer loop's variables).
1997
+ * header parse shared by `buildForNode` (codegen) and the write scanners
1998
+ * (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect nested
1999
+ * loops that shadow an outer loop's variables).
1876
2000
  *
1877
2001
  * Handles the C-style (`for (let i = 0; i < n; i++)`), for-of and for-in
1878
- * forms, with destructuring flattened to the bare names. TODO: Handle
1879
- * destructuring, quotes, comments etc (same as buildForNode's note — this is
1880
- * deliberately the same heuristic).
2002
+ * forms, including comments, strings, nested destructuring and defaults.
1881
2003
  */
1882
2004
  function forLoopVarNames(statement) {
1883
- const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1884
- const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
1885
- const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
1886
- const trimMatched = (value, start, end) => {
1887
- const startIndex = value.indexOf(start);
1888
- const endIndex = value.lastIndexOf(end);
1889
- if (startIndex === -1 || endIndex === -1) return value;
1890
- return value.slice(startIndex + 1, endIndex);
1891
- };
2005
+ const source = maskComments(statement);
2006
+ const forIndex = source.indexOf("for");
2007
+ if (forIndex === -1) return [];
2008
+ const open = source.indexOf("(", forIndex + 3);
2009
+ if (open === -1) return [];
2010
+ const close = findMatching(source, open, "(", ")");
2011
+ if (close === -1) return [];
2012
+ const header = source.slice(open + 1, close);
1892
2013
  const names = [];
1893
- const forLoopMatch = statement.match(forLoopRegex);
1894
- if (forLoopMatch) {
1895
- const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1896
- for (const match of forVarMatches) names.push(match[1]);
1897
- return names;
1898
- }
1899
- const forOfMatch = statement.match(forOfRegex);
1900
- if (forOfMatch) {
1901
- const match = forOfMatch[1];
1902
- if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) names.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1903
- else names.push(match);
2014
+ const firstSemi = findTopLevel(header, (char) => char === ";");
2015
+ if (firstSemi !== -1) {
2016
+ const declaration = stripDeclarationKeyword(header.slice(0, firstSemi));
2017
+ for (const declarator of splitTopLevel(declaration, ",")) {
2018
+ const eq = findTopLevel(declarator, (char) => char === "=");
2019
+ collectBindings(eq === -1 ? declarator : declarator.slice(0, eq), names);
2020
+ }
2021
+ return [...new Set(names)];
2022
+ }
2023
+ const keyword = findLoopKeyword(header);
2024
+ if (keyword !== -1) collectBindings(stripDeclarationKeyword(header.slice(0, keyword)), names);
2025
+ return [...new Set(names)];
2026
+ }
2027
+ /** Replaces comments with spaces, preserving length and string contents. */
2028
+ function maskComments(source) {
2029
+ let masked = "";
2030
+ for (let i = 0; i < source.length; i++) {
2031
+ const skipped = skipStringOrComment(source, i);
2032
+ if (skipped === -1) {
2033
+ masked += source[i];
2034
+ continue;
2035
+ }
2036
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) masked += source.substring(i, skipped).replaceAll(/[^\r\n]/g, " ");
2037
+ else masked += source.substring(i, skipped);
2038
+ i = skipped - 1;
1904
2039
  }
1905
- return names;
2040
+ return masked;
2041
+ }
2042
+ /** Finds the close delimiter matching the opener at `start`. */
2043
+ function findMatching(source, start, open, close) {
2044
+ let depth = 0;
2045
+ for (let i = start; i < source.length; i++) {
2046
+ const skipped = skipStringOrComment(source, i);
2047
+ if (skipped !== -1) {
2048
+ i = skipped - 1;
2049
+ continue;
2050
+ }
2051
+ const char = source[i];
2052
+ if (char === open) depth += 1;
2053
+ else if (char === close) {
2054
+ depth -= 1;
2055
+ if (depth === 0) return i;
2056
+ }
2057
+ }
2058
+ return -1;
2059
+ }
2060
+ /** Finds the first match of `predicate` outside nested delimiters and strings. */
2061
+ function findTopLevel(source, predicate) {
2062
+ let depth = 0;
2063
+ for (let i = 0; i < source.length; i++) {
2064
+ const skipped = skipStringOrComment(source, i);
2065
+ if (skipped !== -1) {
2066
+ i = skipped - 1;
2067
+ continue;
2068
+ }
2069
+ const char = source[i];
2070
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2071
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2072
+ else if (depth === 0 && predicate(char, i)) return i;
2073
+ }
2074
+ return -1;
2075
+ }
2076
+ /** Finds a top-level `of` or `in` keyword. */
2077
+ function findLoopKeyword(source) {
2078
+ let depth = 0;
2079
+ for (let i = 0; i < source.length; i++) {
2080
+ const skipped = skipStringOrComment(source, i);
2081
+ if (skipped !== -1) {
2082
+ i = skipped - 1;
2083
+ continue;
2084
+ }
2085
+ const char = source[i];
2086
+ if (char === "(" || char === "[" || char === "{") {
2087
+ depth += 1;
2088
+ continue;
2089
+ }
2090
+ if (char === ")" || char === "]" || char === "}") {
2091
+ depth -= 1;
2092
+ continue;
2093
+ }
2094
+ if (depth !== 0) continue;
2095
+ for (const keyword of ["of", "in"]) {
2096
+ if (!source.startsWith(keyword, i)) continue;
2097
+ const previous = source[i - 1];
2098
+ const next = source[i + keyword.length];
2099
+ if ((previous === void 0 || !isIdentifierChar(previous)) && (next === void 0 || !isIdentifierChar(next))) return i;
2100
+ }
2101
+ }
2102
+ return -1;
2103
+ }
2104
+ /** Splits at a separator that isn't inside strings or nested delimiters. */
2105
+ function splitTopLevel(source, separator) {
2106
+ const parts = [];
2107
+ let start = 0;
2108
+ let depth = 0;
2109
+ for (let i = 0; i < source.length; i++) {
2110
+ const skipped = skipStringOrComment(source, i);
2111
+ if (skipped !== -1) {
2112
+ i = skipped - 1;
2113
+ continue;
2114
+ }
2115
+ const char = source[i];
2116
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2117
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2118
+ else if (depth === 0 && char === separator) {
2119
+ parts.push(source.slice(start, i));
2120
+ start = i + 1;
2121
+ }
2122
+ }
2123
+ parts.push(source.slice(start));
2124
+ return parts;
2125
+ }
2126
+ function stripDeclarationKeyword(declaration) {
2127
+ return declaration.trim().replace(/^(?:let|var|const)\b\s*/, "");
2128
+ }
2129
+ function collectBindings(pattern, names) {
2130
+ pattern = pattern.trim();
2131
+ if (!pattern) return;
2132
+ const open = pattern[0];
2133
+ if (open === "{") {
2134
+ const close = findMatching(pattern, 0, "{", "}");
2135
+ if (close === -1) return;
2136
+ for (const property of splitTopLevel(pattern.slice(1, close), ",")) collectObjectBinding(property.trim(), names);
2137
+ return;
2138
+ }
2139
+ if (open === "[") {
2140
+ const close = findMatching(pattern, 0, "[", "]");
2141
+ if (close === -1) return;
2142
+ for (let element of splitTopLevel(pattern.slice(1, close), ",")) {
2143
+ element = element.trim();
2144
+ if (!element) continue;
2145
+ if (element.startsWith("...")) element = element.slice(3).trim();
2146
+ const eq = findTopLevel(element, (char) => char === "=");
2147
+ collectBindings(eq === -1 ? element : element.slice(0, eq), names);
2148
+ }
2149
+ return;
2150
+ }
2151
+ const eq = findTopLevel(pattern, (char) => char === "=");
2152
+ const name = (eq === -1 ? pattern : pattern.slice(0, eq)).trim();
2153
+ if (IDENTIFIER.test(name)) names.push(name);
2154
+ }
2155
+ function collectObjectBinding(property, names) {
2156
+ property = property.trim();
2157
+ if (!property) return;
2158
+ if (property.startsWith("...")) {
2159
+ collectBindings(property.slice(3).trim(), names);
2160
+ return;
2161
+ }
2162
+ const colon = findTopLevel(property, (char) => char === ":");
2163
+ const eq = findTopLevel(property, (char) => char === "=");
2164
+ if (colon !== -1 && (eq === -1 || colon < eq)) {
2165
+ collectBindings(property.slice(colon + 1).trim(), names);
2166
+ return;
2167
+ }
2168
+ const name = (eq === -1 ? property : property.slice(0, eq)).trim();
2169
+ if (IDENTIFIER.test(name)) names.push(name);
2170
+ }
2171
+ function isIdentifierChar(char) {
2172
+ return /[A-Za-z0-9_$]/.test(char);
1906
2173
  }
1907
2174
  //#endregion
1908
2175
  //#region src/compile/utils/forVarsWrittenIn.ts
@@ -2173,8 +2440,10 @@ function buildForNode(node, status, b) {
2173
2440
  appendForVarBindings(b, status, `${node.statement}\n${keyStatement}`);
2174
2441
  addMappedText("", `${node.statement}`, " {", node.span, status, b);
2175
2442
  const dataExpr = singleVar ? forVarNames[0] : `{ ${forVarNames.join(", ")} }`;
2176
- if (key !== void 0) addMappedText(`${listItemsName}.push({ data: ${dataExpr}, key: `, `${keyStatement || "undefined"}`, " });", key.span, status, b);
2177
- else b.append(`${listItemsName}.push({ data: ${dataExpr} });`);
2443
+ if (key !== void 0) {
2444
+ status.imports.add("$peek");
2445
+ addMappedText(`${listItemsName}.push({ data: ${dataExpr}, key: $peek(() => `, `${keyStatement || "undefined"}`, ") });", key.span, status, b);
2446
+ } else b.append(`${listItemsName}.push({ data: ${dataExpr} });`);
2178
2447
  b.append(`}`);
2179
2448
  b.append(`return ${listItemsName};`);
2180
2449
  b.append(`},
@@ -2564,6 +2833,25 @@ function buildControlNode(node, status, b) {
2564
2833
  }
2565
2834
  }
2566
2835
  //#endregion
2836
+ //#region src/compile/utils/rawTextTags.ts
2837
+ /**
2838
+ * HTML raw-text elements. Their contents aren't parsed as markup (or as a
2839
+ * torpor template): braces, `@` and `<` are all literal, and the browser
2840
+ * doesn't decode character references inside them either. Rendered `<script>`
2841
+ * / `<style>` content is therefore emitted exactly as written.
2842
+ */
2843
+ const RAW_TEXT_TAGS = /* @__PURE__ */ new Set([
2844
+ "script",
2845
+ "style",
2846
+ "xmp",
2847
+ "iframe",
2848
+ "noembed",
2849
+ "noframes"
2850
+ ]);
2851
+ function isRawTextTag(tagName) {
2852
+ return RAW_TEXT_TAGS.has(tagName.toLowerCase());
2853
+ }
2854
+ //#endregion
2567
2855
  //#region src/compile/utils/trimEnd.ts
2568
2856
  /**
2569
2857
  * Trims a char from the end of the supplied text
@@ -2633,7 +2921,7 @@ function buildElementNode(node, status, b, parentName) {
2633
2921
  buildElementAttributes$1(node, varName, status, b);
2634
2922
  }
2635
2923
  const oldPreserveWhitespace = status.preserveWhitespace;
2636
- status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre";
2924
+ status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre" || isRawTextTag(node.tagName);
2637
2925
  for (let child of node.children) buildNode(child, status, b, parentName, "null");
2638
2926
  status.preserveWhitespace = oldPreserveWhitespace;
2639
2927
  if (svgElement) status.ns = oldns;
@@ -2671,12 +2959,28 @@ function buildTitleNode(node, status, b) {
2671
2959
  else content = `\`${content.replaceAll("{", "${t_fmt(").replaceAll("}", ")}")}\``;
2672
2960
  } else content = `"${content}"`;
2673
2961
  status.imports.add("$run");
2674
- b.append("$run(() => {");
2675
- b.append(`
2962
+ if (status.options.dev === true) {
2963
+ status.imports.add("t_dev_title");
2964
+ b.append(`{
2965
+ const t_title_dev = t_dev_title();
2966
+ $run(() => {
2967
+ const t_old_title = document.title;
2968
+ document.title = ${content};
2969
+ t_title_dev.set(document.title);
2970
+ return () => {
2971
+ t_title_dev.unset();
2972
+ document.title = t_old_title;
2973
+ };
2974
+ }, "runTitle");
2975
+ }`);
2976
+ } else {
2977
+ b.append("$run(() => {");
2978
+ b.append(`
2676
2979
  const t_old_title = document.title;
2677
2980
  document.title = ${content};
2678
2981
  return () => document.title = t_old_title;
2679
- }${status.options.dev === true ? `, "runTitle"` : ""});`);
2982
+ });`);
2983
+ }
2680
2984
  }
2681
2985
  function buildHeadNode(node, status, b) {
2682
2986
  status.imports.add("$run");
@@ -2777,12 +3081,14 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2777
3081
  let eventName = bindEventName(node, name);
2778
3082
  let defaultValue = "\"\"";
2779
3083
  let inputValue = "e.target.value";
3084
+ let setJoin = "||";
2780
3085
  if (node.tagName === "input") {
2781
3086
  let typeAttribute = node.attributes.find((a) => a.name === "type");
2782
3087
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
2783
3088
  case "number":
2784
- defaultValue = "0";
2785
- inputValue = "Number(e.target.value)";
3089
+ defaultValue = "\"\"";
3090
+ inputValue = "e.target.value === \"\" ? undefined : Number(e.target.value)";
3091
+ setJoin = "??";
2786
3092
  break;
2787
3093
  case "checkbox":
2788
3094
  defaultValue = "false";
@@ -2795,7 +3101,7 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2795
3101
  return;
2796
3102
  }
2797
3103
  }
2798
- let set = `${value} || ${defaultValue}`;
3104
+ let set = `${value} ${setJoin} ${defaultValue}`;
2799
3105
  const propName = name.substring(1);
2800
3106
  buildRun("setBinding", `${propName === "value" ? `${varName}.${propName} = String(${set})` : `${varName}.${propName} = ${set}`};`, status, b);
2801
3107
  emitBindEvent(varName, eventName, `(e) => ${value} = ${inputValue}`, `${value} = ${inputValue};`, combined, status, b);
@@ -2939,7 +3245,7 @@ function buildSlotNode(node, status, b) {
2939
3245
  b.append(`const ${propsName} = $watch({`);
2940
3246
  for (let p of props) {
2941
3247
  let value = p.value;
2942
- addMappedText(`${p.name}: `, value, ",", p.span, status, b);
3248
+ addMappedText(`${propKey(p.name)}: `, value, ",", p.span, status, b);
2943
3249
  }
2944
3250
  b.append("});");
2945
3251
  if (runs.length) buildRun("setProps", runs.join("\n"), status, b);
@@ -2990,6 +3296,7 @@ function buildSpecialNode(node, status, b, parentName, root = false) {
2990
3296
  //#endregion
2991
3297
  //#region src/compile/build/client/buildTextNode.ts
2992
3298
  function buildTextNode(node, status) {
3299
+ if (node.raw) return;
2993
3300
  let fragment = status.fragmentStack.at(-1)?.fragment;
2994
3301
  if (!fragment) return;
2995
3302
  let content = node.content || "";
@@ -3134,7 +3441,8 @@ const importsMap$1 = {
3134
3441
  SlotRender: "import { type SlotRender } from \"${folder}\";",
3135
3442
  devContext: "import { devContext } from \"${folder}/dev\";",
3136
3443
  t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
3137
- t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
3444
+ t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";",
3445
+ t_dev_title: "import { t_dev_title } from \"${folder}/dev\";"
3138
3446
  };
3139
3447
  function buildCode(template, map, options, errors = [], warnings = []) {
3140
3448
  let b = new Builder(options?.mapped);
@@ -3272,10 +3580,10 @@ function buildStyles(style, styleHash) {
3272
3580
  for (let block of style.children) buildStyleNode(block, b, styleHash);
3273
3581
  return b.toString();
3274
3582
  }
3275
- function buildStyleNode(node, b, styleHash) {
3583
+ function buildStyleNode(node, b, styleHash, scoped = true) {
3276
3584
  switch (node.type) {
3277
3585
  case "block":
3278
- buildBlockNode(node, b, styleHash);
3586
+ buildBlockNode(node, b, styleHash, scoped);
3279
3587
  break;
3280
3588
  case "attribute":
3281
3589
  buildAttributeNode(node, b);
@@ -3284,55 +3592,164 @@ function buildStyleNode(node, b, styleHash) {
3284
3592
  default: throw new Error(`Invalid style node type: ${node.type}`);
3285
3593
  }
3286
3594
  }
3287
- function buildBlockNode(block, b, styleHash) {
3595
+ function buildBlockNode(block, b, styleHash, scoped) {
3596
+ const isKeyframes = block.selector.startsWith("@keyframes") || block.selector.startsWith("@-webkit-keyframes");
3288
3597
  if (block.selector.startsWith("@")) b.append(`${block.selector} {`);
3289
3598
  else {
3290
- block.selector = block.selector.replaceAll(/\s+/g, " ");
3291
- let selectors = [];
3292
- let global = false;
3293
- let start = 0;
3294
- for (let i = 0; i <= block.selector.length; i++) if (block.selector.substring(i).startsWith(":global(")) {
3295
- i += 7;
3296
- start = i + 1;
3297
- global = true;
3298
- } else if (global && block.selector[i] === ")") {
3299
- addSelector(selectors, block.selector, styleHash, start, i, global);
3300
- start = i + 1;
3301
- global = false;
3302
- } else if ("*,>+~".includes(block.selector[i])) {
3303
- addSelector(selectors, block.selector, styleHash, start, i, global);
3304
- selectors.push(block.selector[i]);
3305
- start = i + 1;
3306
- } else if (i === block.selector.length) addSelector(selectors, block.selector, styleHash, start, i, global);
3307
- else if (block.selector[i] === " ") {
3308
- addSelector(selectors, block.selector, styleHash, start, i, global);
3309
- start = i + 1;
3310
- }
3311
- b.append(`${selectors.join(" ").replaceAll(" ,", ",")} {`);
3599
+ block.selector = block.selector.replaceAll(/\s+/g, " ").trim();
3600
+ b.append(`${scoped ? scopeSelector(block.selector, styleHash) : block.selector} {`);
3312
3601
  }
3313
- for (let child of block.children) buildStyleNode(child, b, styleHash);
3602
+ for (let child of block.children) buildStyleNode(child, b, styleHash, scoped && !isKeyframes);
3314
3603
  b.append(`}`);
3315
3604
  }
3316
- function addSelector(selectors, selector, styleHash, start, end, global) {
3317
- if (end > start) {
3318
- let s = selector.substring(start, end);
3319
- if (!global) {
3320
- let pre = s;
3321
- let post = "";
3322
- let colonPosition = s.indexOf(":");
3323
- if (colonPosition !== -1) {
3324
- pre = s.substring(0, colonPosition);
3325
- post = s.substring(colonPosition);
3605
+ /**
3606
+ * Appends the component scope class to each compound selector. Both brackets
3607
+ * (`[data-x="a b"]`) and parentheses (`:is(.a, .b)`, `:global(...)`) are
3608
+ * treated as opaque, so spaces/commas inside them aren't mistaken for
3609
+ * combinators. `:global(...)` wrappers are removed without adding the scope.
3610
+ */
3611
+ function scopeSelector(selector, styleHash) {
3612
+ let result = "";
3613
+ let compound = "";
3614
+ let bracketDepth = 0;
3615
+ let parenDepth = 0;
3616
+ let quote = null;
3617
+ const flush = () => {
3618
+ if (!compound) return;
3619
+ result += scopeCompound(compound, styleHash);
3620
+ compound = "";
3621
+ };
3622
+ for (let i = 0; i < selector.length; i++) {
3623
+ const char = selector[i];
3624
+ if (quote !== null) {
3625
+ compound += char;
3626
+ if (char === "\\") compound += selector[++i] ?? "";
3627
+ else if (char === quote) quote = null;
3628
+ continue;
3629
+ }
3630
+ if (char === "\\") compound += char + (selector[++i] ?? "");
3631
+ else if (char === "\"" || char === "'") {
3632
+ quote = char;
3633
+ compound += char;
3634
+ } else if (char === "[") {
3635
+ bracketDepth += 1;
3636
+ compound += char;
3637
+ } else if (char === "]") {
3638
+ bracketDepth -= 1;
3639
+ compound += char;
3640
+ } else if (char === "(") {
3641
+ parenDepth += 1;
3642
+ compound += char;
3643
+ } else if (char === ")") {
3644
+ parenDepth -= 1;
3645
+ compound += char;
3646
+ } else if (bracketDepth === 0 && parenDepth === 0 && (char === " " || char === "," || char === ">" || char === "+" || char === "~")) {
3647
+ flush();
3648
+ result += char;
3649
+ } else compound += char;
3650
+ }
3651
+ flush();
3652
+ return result.trim();
3653
+ }
3654
+ function scopeCompound(compound, styleHash) {
3655
+ if (!compound.includes(":global(")) return addScope(compound, styleHash);
3656
+ const { text, onlyGlobal } = stripGlobal(compound);
3657
+ return onlyGlobal ? text : addScope(text, styleHash);
3658
+ }
3659
+ /** Removes `:global(...)` wrappers, reporting whether anything local remained. */
3660
+ function stripGlobal(compound) {
3661
+ let text = "";
3662
+ let hadLocal = false;
3663
+ let i = 0;
3664
+ while (i < compound.length) {
3665
+ if (compound.startsWith(":global(", i)) {
3666
+ const close = findClosingParen(compound, i + 7);
3667
+ if (close === -1) {
3668
+ text += compound.substring(i);
3669
+ break;
3326
3670
  }
3327
- s = `${pre}.torp-${styleHash}${post}`;
3671
+ text += compound.substring(i + 8, close);
3672
+ i = close + 1;
3673
+ continue;
3674
+ }
3675
+ const char = compound[i];
3676
+ if (char.trim()) hadLocal = true;
3677
+ text += char;
3678
+ i += 1;
3679
+ }
3680
+ return {
3681
+ text,
3682
+ onlyGlobal: !hadLocal
3683
+ };
3684
+ }
3685
+ function addScope(compound, styleHash) {
3686
+ const colon = findFirstPseudo(compound);
3687
+ const scope = `.torp-${styleHash}`;
3688
+ return colon === -1 ? `${compound}${scope}` : `${compound.substring(0, colon)}${scope}${compound.substring(colon)}`;
3689
+ }
3690
+ /** Finds the first top-level `:` (pseudo-class/element), skipping brackets/strings. */
3691
+ function findFirstPseudo(compound) {
3692
+ let bracketDepth = 0;
3693
+ let parenDepth = 0;
3694
+ let quote = null;
3695
+ for (let i = 0; i < compound.length; i++) {
3696
+ const char = compound[i];
3697
+ if (quote !== null) {
3698
+ if (char === "\\") i += 1;
3699
+ else if (char === quote) quote = null;
3700
+ continue;
3701
+ }
3702
+ if (char === "\\") i += 1;
3703
+ else if (char === "\"" || char === "'") quote = char;
3704
+ else if (char === "[") bracketDepth += 1;
3705
+ else if (char === "]") bracketDepth -= 1;
3706
+ else if (char === "(") parenDepth += 1;
3707
+ else if (char === ")") parenDepth -= 1;
3708
+ else if (bracketDepth === 0 && parenDepth === 0 && char === ":") return i;
3709
+ }
3710
+ return -1;
3711
+ }
3712
+ function findClosingParen(source, open) {
3713
+ let depth = 0;
3714
+ let bracketDepth = 0;
3715
+ let quote = null;
3716
+ for (let i = open; i < source.length; i++) {
3717
+ const char = source[i];
3718
+ if (quote !== null) {
3719
+ if (char === "\\") i += 1;
3720
+ else if (char === quote) quote = null;
3721
+ continue;
3722
+ }
3723
+ if (char === "\\") i += 1;
3724
+ else if (char === "\"" || char === "'") quote = char;
3725
+ else if (char === "[") bracketDepth += 1;
3726
+ else if (char === "]") bracketDepth -= 1;
3727
+ else if (bracketDepth === 0 && char === "(") depth += 1;
3728
+ else if (bracketDepth === 0 && char === ")") {
3729
+ depth -= 1;
3730
+ if (depth === 0) return i;
3328
3731
  }
3329
- selectors.push(s);
3330
3732
  }
3733
+ return -1;
3331
3734
  }
3332
3735
  function buildAttributeNode(attribute, b) {
3333
3736
  b.append(`${attribute.name}: ${attribute.value};`);
3334
3737
  }
3335
3738
  //#endregion
3739
+ //#region src/compile/utils/containsAwaitGroup.ts
3740
+ /**
3741
+ * Whether a markup tree contains an `@await` boundary, so the component's
3742
+ * render must be wrapped in a flush.
3743
+ */
3744
+ function containsAwaitGroup(node) {
3745
+ if (node === void 0 || node === null) return false;
3746
+ if (isControlNode(node) && node.operation === "@await group") return true;
3747
+ if (node.type !== "text" && node.type !== "comment") {
3748
+ for (let child of node.children) if (containsAwaitGroup(child)) return true;
3749
+ }
3750
+ return false;
3751
+ }
3752
+ //#endregion
3336
3753
  //#region src/compile/build/server/flushOutput.ts
3337
3754
  /**
3338
3755
  * Appends any pending output to the generated code, targeting the body
@@ -3375,7 +3792,7 @@ function buildServerComponentNode(node, status, b) {
3375
3792
  });
3376
3793
  }
3377
3794
  b.append(`const ${propsName} = {`);
3378
- for (let p of props) b.append(p.name ? `${p.name}: ${p.value},` : `${p.value},`);
3795
+ for (let p of props) b.append(p.name ? `${propKey(p.name)}: ${p.value},` : `${p.value},`);
3379
3796
  b.append("};");
3380
3797
  }
3381
3798
  const componentHasSlots = node.children.length;
@@ -3385,7 +3802,7 @@ function buildServerComponentNode(node, status, b) {
3385
3802
  for (let slot of node.children) if (isSpecialNode(slot) && (slot.tagName === "fill" || slot.tagName === "filldef")) {
3386
3803
  const nameAttribute = slot.attributes.find((a) => a.name === "name");
3387
3804
  const slotName = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
3388
- const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3805
+ const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) || containsAwaitGroup(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3389
3806
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = async (\n${slotParams.join(",\n")}\n) => {`);
3390
3807
  b.append(`let t_body = "";`);
3391
3808
  for (let child of slot.children) buildServerNode(child, status, b);
@@ -3441,7 +3858,7 @@ function buildServerAwaitNode(node, status, b) {
3441
3858
  for (let branch of node.children) if (isControlNode(branch) && branch.operation === "@with") for (let child of branch.children) buildServerNode(child, status, b);
3442
3859
  flushOutput(status, b);
3443
3860
  b.append(`return { body: t_body, head: t_head };`);
3444
- b.append(`});`);
3861
+ b.append(`}, $context);`);
3445
3862
  b.append(`${status.inHead ? "t_head" : "t_body"} += ${resultName}.body;`);
3446
3863
  b.append(`t_head += ${resultName}.head;`);
3447
3864
  }
@@ -3623,7 +4040,7 @@ function buildServerElementNode(node, status, b) {
3623
4040
  status.output += `<${tagName}${attributes}>`;
3624
4041
  if (!voidTags.includes(tagName)) {
3625
4042
  const oldPreserveWhitespace = status.preserveWhitespace;
3626
- status.preserveWhitespace = ["pre", "code"].includes(tagName);
4043
+ status.preserveWhitespace = ["pre", "code"].includes(tagName) || isRawTextTag(tagName);
3627
4044
  if (!tagName.startsWith("@")) status.elementStack.push(tagName);
3628
4045
  for (let child of node.children) buildServerNode(child, status, b);
3629
4046
  if (!tagName.startsWith("@")) status.elementStack.pop();
@@ -3641,16 +4058,13 @@ function buildElementAttributes(node, status) {
3641
4058
  let typeAttribute = node.attributes.find((a) => a.name === "type");
3642
4059
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
3643
4060
  case "number":
3644
- defaultValue = "0";
4061
+ defaultValue = "\"\"";
3645
4062
  break;
3646
4063
  case "checkbox": defaultValue = "false";
3647
4064
  }
3648
- if (!defaultValue) {
3649
- status.imports.add("t_attr");
3650
- value = `t_attr(${value})`;
3651
- defaultValue = "\"\"";
3652
- }
3653
- let valueOrDefault = `(${value}) || ${defaultValue}`;
4065
+ if (!defaultValue) defaultValue = "\"\"";
4066
+ status.imports.add("t_attr");
4067
+ let valueOrDefault = `t_attr(${value}) || ${defaultValue}`;
3654
4068
  const propName = name.substring(1);
3655
4069
  attributes.push(`${propName}="\${${valueOrDefault}}"`);
3656
4070
  } else if (name === "class") {
@@ -3673,9 +4087,9 @@ function buildElementAttributes(node, status) {
3673
4087
  attributes.push(`${name}="${trimQuotes(value).replaceAll("{", "${t_attr(").replaceAll("}", ")}")}"`);
3674
4088
  } else if (name === "class" && node.scopeStyles && !status.inHead) {
3675
4089
  value = value ? `"${trimQuotes(value)} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
3676
- attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4090
+ attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3677
4091
  needsClass = false;
3678
- } else if (value != null) attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4092
+ } else if (value != null) attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3679
4093
  else attributes.push(`${name}`);
3680
4094
  if (needsClass) attributes.push(`class="torp-${status.styleHash}"`);
3681
4095
  return attributes.join(" ");
@@ -3738,15 +4152,21 @@ function buildServerSpecialNode(node, status, b) {
3738
4152
  //#region src/compile/build/server/buildServerTextNode.ts
3739
4153
  function buildServerTextNode(node, status) {
3740
4154
  let content = node.content || "";
4155
+ if (node.raw) {
4156
+ status.output += escapeRawText(content);
4157
+ return;
4158
+ }
3741
4159
  if (!status.preserveWhitespace) content = content.replaceAll(/\s+/g, " ");
4160
+ const parentTag = status.elementStack[status.elementStack.length - 1];
4161
+ const formatter = parentTag !== void 0 && isRawTextTag(parentTag) ? "t_fmt_raw" : "t_fmt";
3742
4162
  let level = 0;
3743
4163
  for (let i = 0; i < content.length; i++) {
3744
4164
  const char = content[i];
3745
4165
  if (char === "{") {
3746
4166
  level++;
3747
4167
  if (level === 1) {
3748
- status.imports.add("t_fmt");
3749
- status.output += "${t_fmt(";
4168
+ status.imports.add(formatter);
4169
+ status.output += "${" + formatter + "(";
3750
4170
  continue;
3751
4171
  }
3752
4172
  } else if (char === "}") {
@@ -3809,8 +4229,10 @@ const importsMap = {
3809
4229
  $peek: "import { $peek } from \"${folder}\";",
3810
4230
  $batch: "import { $batch } from \"${folder}\";",
3811
4231
  t_server_flush: "import { t_server_flush } from \"${folder}\";",
4232
+ t_render_context: "import { t_render_context } from \"${folder}\";",
3812
4233
  t_await_server: "import { t_await_server } from \"${folder}\";",
3813
4234
  t_fmt: "import { t_fmt } from \"${folder}\";",
4235
+ t_fmt_raw: "import { t_fmt_raw } from \"${folder}\";",
3814
4236
  t_attr: "import { t_attr } from \"${folder}\";",
3815
4237
  t_attr_if: "import { t_attr_if } from \"${folder}\";",
3816
4238
  t_class: "import { t_class } from \"${folder}\";",
@@ -3858,121 +4280,118 @@ function buildServerTemplate(template, imports, b, options) {
3858
4280
  for (let [i, chunk] of template.script.entries()) if (chunk.script === "/* @params */" && i > 0) asyncChunks.add(i - 1);
3859
4281
  let currentIndex = 0;
3860
4282
  let current = template.components[0];
3861
- for (let [chunkIndex, chunk] of template.script.entries()) if (chunk.script === "/* @params */") {
3862
- let params = [
3863
- current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
3864
- `${current.contextProps?.length || current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error) ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
3865
- `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
3866
- ];
3867
- b.append(params.join(",\n") + ",");
3868
- } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
3869
- else if (chunk.script === "/* @start */") {
3870
- if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
3871
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) {
3872
- imports.add("t_server_flush");
3873
- b.append(`return t_server_flush(async () => {`);
3874
- }
3875
- b.append(`let t_body = "";`);
3876
- b.append(`let t_head = "";`);
3877
- } else if (chunk.script === "/* @render */") {
3878
- if (current.markup) {
3879
- const status = {
3880
- imports,
3881
- output: "",
3882
- styleHash: current.style?.hash || "",
3883
- varNames: {},
3884
- preserveWhitespace: false,
3885
- awaitCount: 0,
3886
- elementStack: [],
3887
- options
3888
- };
3889
- b.append("");
3890
- b.append("/* User interface */");
3891
- if (current.error) {
3892
- b.append(`const t_try_body = t_body;`);
3893
- b.append(`const t_try_head = t_head;`);
3894
- b.append("try {");
4283
+ for (let [chunkIndex, chunk] of template.script.entries()) {
4284
+ const hasAwait = current !== void 0 && (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head));
4285
+ const rendersComponent = current !== void 0 && (current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error));
4286
+ if (chunk.script === "/* @params */") {
4287
+ let params = [
4288
+ current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
4289
+ `${current.contextProps?.length || rendersComponent || hasAwait ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
4290
+ `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
4291
+ ];
4292
+ b.append(params.join(",\n") + ",");
4293
+ } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
4294
+ else if (chunk.script === "/* @start */") {
4295
+ if (rendersComponent || hasAwait) {
4296
+ imports.add("t_render_context");
4297
+ b.append(`$context = t_render_context($context);`);
3895
4298
  }
3896
- buildServerNode(current.markup, status, b);
3897
- if (status.output) {
3898
- b.append(`t_body += \`${status.output}\`;`);
3899
- status.output = "";
4299
+ if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
4300
+ if (hasAwait) {
4301
+ imports.add("t_server_flush");
4302
+ b.append(`return t_server_flush(async () => {`);
3900
4303
  }
3901
- }
3902
- } else if (chunk.script === "/* @error */") {
3903
- if (current.markup && current.error) {
3904
- const status = {
3905
- imports,
3906
- output: "",
3907
- styleHash: current.style?.hash || "",
3908
- varNames: {},
3909
- preserveWhitespace: false,
3910
- awaitCount: 0,
3911
- elementStack: [],
3912
- options
3913
- };
3914
- b.append(`} catch (${current.errorVar}) {`);
3915
- b.append("t_body = t_try_body;");
3916
- b.append("t_head = t_try_head;");
3917
- b.append("/* User interface error */");
3918
- buildServerNode(current.error, status, b);
3919
- if (status.output) {
3920
- b.append(`t_body += \`${status.output}\`;`);
3921
- status.output = "";
4304
+ b.append(`let t_body = "";`);
4305
+ b.append(`let t_head = "";`);
4306
+ } else if (chunk.script === "/* @render */") {
4307
+ if (current.markup) {
4308
+ const status = {
4309
+ imports,
4310
+ output: "",
4311
+ styleHash: current.style?.hash || "",
4312
+ varNames: {},
4313
+ preserveWhitespace: false,
4314
+ awaitCount: 0,
4315
+ elementStack: [],
4316
+ options
4317
+ };
4318
+ b.append("");
4319
+ b.append("/* User interface */");
4320
+ if (current.error) {
4321
+ b.append(`const t_try_body = t_body;`);
4322
+ b.append(`const t_try_head = t_head;`);
4323
+ b.append("try {");
4324
+ }
4325
+ buildServerNode(current.markup, status, b);
4326
+ if (status.output) {
4327
+ b.append(`t_body += \`${status.output}\`;`);
4328
+ status.output = "";
4329
+ }
3922
4330
  }
3923
- b.append("}");
3924
- }
3925
- } else if (chunk.script === "/* @head */") {
3926
- if (current.head) {
3927
- const status = {
3928
- imports,
3929
- output: "",
3930
- styleHash: current.style?.hash || "",
3931
- varNames: {},
3932
- preserveWhitespace: false,
3933
- inHead: true,
3934
- awaitCount: 0,
3935
- elementStack: [],
3936
- options
3937
- };
3938
- b.append("");
3939
- b.append("/* Head */");
3940
- buildServerNode(current.head, status, b);
3941
- flushOutput(status, b);
3942
- }
3943
- } else if (chunk.script === "/* @style */") {
3944
- if (current.style) {
3945
- b.append("");
3946
- b.append("/* Style */");
3947
- const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
3948
- b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
3949
- }
3950
- } else if (chunk.script === "/* @end */") {
3951
- b.append(`return { body: t_body, head: t_head };`);
3952
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) b.append(`});`);
3953
- currentIndex += 1;
3954
- current = template.components[currentIndex];
3955
- } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
3956
- else b.append(chunk.script);
3957
- }
3958
- /**
3959
- * Whether a markup tree contains an `@await` boundary, so the component's
3960
- * render must be wrapped in a flush.
3961
- */
3962
- function containsAwaitGroup(node) {
3963
- if (node === void 0 || node === null) return false;
3964
- if (isControlNode(node) && node.operation === "@await group") return true;
3965
- if (node.type !== "text" && node.type !== "comment") {
3966
- for (let child of node.children) if (containsAwaitGroup(child)) return true;
4331
+ } else if (chunk.script === "/* @error */") {
4332
+ if (current.markup && current.error) {
4333
+ const status = {
4334
+ imports,
4335
+ output: "",
4336
+ styleHash: current.style?.hash || "",
4337
+ varNames: {},
4338
+ preserveWhitespace: false,
4339
+ awaitCount: 0,
4340
+ elementStack: [],
4341
+ options
4342
+ };
4343
+ b.append(`} catch (${current.errorVar}) {`);
4344
+ b.append("t_body = t_try_body;");
4345
+ b.append("t_head = t_try_head;");
4346
+ b.append("/* User interface error */");
4347
+ buildServerNode(current.error, status, b);
4348
+ if (status.output) {
4349
+ b.append(`t_body += \`${status.output}\`;`);
4350
+ status.output = "";
4351
+ }
4352
+ b.append("}");
4353
+ }
4354
+ } else if (chunk.script === "/* @head */") {
4355
+ if (current.head) {
4356
+ const status = {
4357
+ imports,
4358
+ output: "",
4359
+ styleHash: current.style?.hash || "",
4360
+ varNames: {},
4361
+ preserveWhitespace: false,
4362
+ inHead: true,
4363
+ awaitCount: 0,
4364
+ elementStack: [],
4365
+ options
4366
+ };
4367
+ b.append("");
4368
+ b.append("/* Head */");
4369
+ buildServerNode(current.head, status, b);
4370
+ flushOutput(status, b);
4371
+ }
4372
+ } else if (chunk.script === "/* @style */") {
4373
+ if (current.style) {
4374
+ b.append("");
4375
+ b.append("/* Style */");
4376
+ const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
4377
+ b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
4378
+ }
4379
+ } else if (chunk.script === "/* @end */") {
4380
+ b.append(`return { body: t_body, head: t_head };`);
4381
+ if (hasAwait) b.append(`});`);
4382
+ currentIndex += 1;
4383
+ current = template.components[currentIndex];
4384
+ } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
4385
+ else b.append(chunk.script);
3967
4386
  }
3968
- return false;
3969
4387
  }
3970
4388
  //#endregion
3971
4389
  //#region src/compile/utils/trimWhitespace.ts
3972
4390
  /**
3973
4391
  * Tag names whose contents should keep all whitespace untouched, matching
3974
4392
  * native HTML rendering of `pre`/`textarea` and the existing build-time
3975
- * `preserveWhitespace` behavior for `code`.
4393
+ * `preserveWhitespace` behavior for `code`. Raw-text elements (including
4394
+ * inline `<script>` / `<style>`) keep their contents exactly as written.
3976
4395
  */
3977
4396
  const PRESERVE_TAGS = /* @__PURE__ */ new Set([
3978
4397
  "pre",
@@ -4025,7 +4444,7 @@ function trimChildren(children, preserveAll, parentTag) {
4025
4444
  const grandChildren = getChildren(child);
4026
4445
  if (grandChildren) {
4027
4446
  const childTag = getTagName(child);
4028
- trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? ""), childTag);
4447
+ trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? "") || isRawTextTag(childTag ?? ""), childTag);
4029
4448
  }
4030
4449
  }
4031
4450
  if (preserveAll) return;
@@ -4964,7 +5383,7 @@ function serializeElement(node, context) {
4964
5383
  context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4965
5384
  return;
4966
5385
  }
4967
- const childContext = node.tagName === "pre" || node.tagName === "code" ? {
5386
+ const childContext = node.tagName === "pre" || node.tagName === "code" || isRawTextTag(node.tagName) ? {
4968
5387
  ...context,
4969
5388
  preserveWhitespace: true
4970
5389
  } : context;
@@ -5294,28 +5713,566 @@ function isSpaceNode(node) {
5294
5713
  return isTextNode(node) && isSpace(node.content);
5295
5714
  }
5296
5715
  //#endregion
5297
- //#region src/compile/parse/utils/accept.ts
5716
+ //#region src/compile/utils/nativeTags.ts
5298
5717
  /**
5299
- * Checks whether the source at the current parse position matches the supplied
5300
- * string
5301
- *
5302
- * @param value The string to check
5303
- * @param status The parse status
5304
- * @param advance (Optional) If true, advances the parse position past the
5305
- * checked string (defaults to true)
5306
- *
5307
- * @returns True if the supplied string was found at the current parse position
5718
+ * Native HTML and SVG tag names, used to tell elements apart from components.
5719
+ * A tag that is neither imported nor a component declared in the same file is
5720
+ * an element when it appears here, or when it contains a dash (an HTML custom
5721
+ * element). Anything else capitalized is reported as an unknown component.
5308
5722
  */
5309
- function accept(value, status, advance = true) {
5310
- if (status.source.substring(status.i, status.i + value.length) == value) {
5311
- status.i += advance ? value.length : 0;
5312
- return true;
5313
- }
5314
- return false;
5315
- }
5316
- //#endregion
5317
- //#region src/compile/parse/parseInlineScript.ts
5318
- function parseInlineScript(status) {
5723
+ const htmlTags = [
5724
+ "a",
5725
+ "abbr",
5726
+ "address",
5727
+ "area",
5728
+ "article",
5729
+ "aside",
5730
+ "audio",
5731
+ "b",
5732
+ "base",
5733
+ "bdi",
5734
+ "bdo",
5735
+ "blockquote",
5736
+ "body",
5737
+ "br",
5738
+ "button",
5739
+ "canvas",
5740
+ "caption",
5741
+ "cite",
5742
+ "code",
5743
+ "col",
5744
+ "colgroup",
5745
+ "data",
5746
+ "datalist",
5747
+ "dd",
5748
+ "del",
5749
+ "details",
5750
+ "dfn",
5751
+ "dialog",
5752
+ "div",
5753
+ "dl",
5754
+ "dt",
5755
+ "em",
5756
+ "embed",
5757
+ "fieldset",
5758
+ "figcaption",
5759
+ "figure",
5760
+ "footer",
5761
+ "form",
5762
+ "h1",
5763
+ "h2",
5764
+ "h3",
5765
+ "h4",
5766
+ "h5",
5767
+ "h6",
5768
+ "head",
5769
+ "header",
5770
+ "hgroup",
5771
+ "hr",
5772
+ "html",
5773
+ "i",
5774
+ "iframe",
5775
+ "img",
5776
+ "input",
5777
+ "ins",
5778
+ "kbd",
5779
+ "label",
5780
+ "legend",
5781
+ "li",
5782
+ "link",
5783
+ "main",
5784
+ "map",
5785
+ "mark",
5786
+ "menu",
5787
+ "meta",
5788
+ "meter",
5789
+ "nav",
5790
+ "noscript",
5791
+ "object",
5792
+ "ol",
5793
+ "optgroup",
5794
+ "option",
5795
+ "output",
5796
+ "p",
5797
+ "picture",
5798
+ "pre",
5799
+ "progress",
5800
+ "q",
5801
+ "rp",
5802
+ "rt",
5803
+ "ruby",
5804
+ "s",
5805
+ "samp",
5806
+ "script",
5807
+ "search",
5808
+ "section",
5809
+ "select",
5810
+ "slot",
5811
+ "small",
5812
+ "source",
5813
+ "span",
5814
+ "strong",
5815
+ "style",
5816
+ "sub",
5817
+ "summary",
5818
+ "sup",
5819
+ "table",
5820
+ "tbody",
5821
+ "td",
5822
+ "template",
5823
+ "textarea",
5824
+ "tfoot",
5825
+ "th",
5826
+ "thead",
5827
+ "time",
5828
+ "title",
5829
+ "tr",
5830
+ "track",
5831
+ "u",
5832
+ "ul",
5833
+ "var",
5834
+ "video",
5835
+ "wbr"
5836
+ ];
5837
+ const svgTags = [
5838
+ "a",
5839
+ "animate",
5840
+ "animateMotion",
5841
+ "animateTransform",
5842
+ "circle",
5843
+ "clipPath",
5844
+ "defs",
5845
+ "desc",
5846
+ "discard",
5847
+ "ellipse",
5848
+ "feBlend",
5849
+ "feColorMatrix",
5850
+ "feComponentTransfer",
5851
+ "feComposite",
5852
+ "feConvolveMatrix",
5853
+ "feDiffuseLighting",
5854
+ "feDisplacementMap",
5855
+ "feDistantLight",
5856
+ "feDropShadow",
5857
+ "feFlood",
5858
+ "feFuncA",
5859
+ "feFuncB",
5860
+ "feFuncG",
5861
+ "feFuncR",
5862
+ "feGaussianBlur",
5863
+ "feImage",
5864
+ "feMerge",
5865
+ "feMergeNode",
5866
+ "feMorphology",
5867
+ "feOffset",
5868
+ "fePointLight",
5869
+ "feSpecularLighting",
5870
+ "feSpotLight",
5871
+ "feTile",
5872
+ "feTurbulence",
5873
+ "filter",
5874
+ "foreignObject",
5875
+ "g",
5876
+ "image",
5877
+ "line",
5878
+ "linearGradient",
5879
+ "marker",
5880
+ "mask",
5881
+ "metadata",
5882
+ "mpath",
5883
+ "path",
5884
+ "pattern",
5885
+ "polygon",
5886
+ "polyline",
5887
+ "radialGradient",
5888
+ "rect",
5889
+ "script",
5890
+ "set",
5891
+ "stop",
5892
+ "style",
5893
+ "svg",
5894
+ "switch",
5895
+ "symbol",
5896
+ "text",
5897
+ "textPath",
5898
+ "title",
5899
+ "tspan",
5900
+ "use",
5901
+ "view"
5902
+ ];
5903
+ const nativeTags = /* @__PURE__ */ new Set([...htmlTags, ...svgTags]);
5904
+ //#endregion
5905
+ //#region src/compile/parse/utils/usesSlot.ts
5906
+ const slotRegex = /\$slot\b/;
5907
+ /**
5908
+ * Checks whether the $slot variable is read in the nodes' own scope
5909
+ *
5910
+ * Note that the children of a component node are excluded, because they are
5911
+ * passed to the component as fills, which get their own $slot parameter.
5912
+ * The component's attributes do belong to this scope.
5913
+ *
5914
+ * @param nodes The nodes to check
5915
+ *
5916
+ * @returns True if a $slot variable is read in the nodes' own scope
5917
+ */
5918
+ function usesSlot(nodes) {
5919
+ for (let node of nodes) if (node.type === "text") {
5920
+ const text = node;
5921
+ if (slotRegex.test(text.content)) return true;
5922
+ } else if (node.type === "control") {
5923
+ const control = node;
5924
+ if (slotRegex.test(control.statement)) return true;
5925
+ if (usesSlot(control.children)) return true;
5926
+ } else if (node.type === "element" || node.type === "special" || node.type === "component") {
5927
+ const element = node;
5928
+ for (let attribute of element.attributes) {
5929
+ if (slotRegex.test(attribute.name)) return true;
5930
+ if (attribute.value && slotRegex.test(attribute.value)) return true;
5931
+ }
5932
+ if (element.type !== "component" && usesSlot(element.children)) return true;
5933
+ }
5934
+ return false;
5935
+ }
5936
+ //#endregion
5937
+ //#region src/compile/parse/slottifyChildNodes.ts
5938
+ /**
5939
+ * Moves any child nodes that aren't already in a <fill> node into a default
5940
+ * <fill> node
5941
+ */
5942
+ function slottifyChildNodes(node) {
5943
+ let nonFillNodes = [];
5944
+ for (let child of node.children) if (isFillNode(child)) {
5945
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5946
+ else break;
5947
+ } else nonFillNodes.push(child);
5948
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5949
+ if (nonFillNodes.length) {
5950
+ let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
5951
+ if (!defaultFillNode) {
5952
+ defaultFillNode = {
5953
+ type: "special",
5954
+ tagName: "filldef",
5955
+ attributes: [],
5956
+ children: nonFillNodes,
5957
+ span: {
5958
+ start: 0,
5959
+ end: 0
5960
+ },
5961
+ hasSlotProps: usesSlot(nonFillNodes)
5962
+ };
5963
+ node.children.unshift(defaultFillNode);
5964
+ }
5965
+ node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
5966
+ }
5967
+ }
5968
+ function isFillNode(n) {
5969
+ return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
5970
+ }
5971
+ //#endregion
5972
+ //#region src/compile/parse/utils/addError.ts
5973
+ /**
5974
+ * Adds an error to the parse status
5975
+ *
5976
+ * @param status The parse status
5977
+ * @param message The error message to add
5978
+ * @param start (Optional) The start position of the error (defaults to the
5979
+ * current parse position)
5980
+ */
5981
+ function addError(status, message, start = status.i, end = status.i) {
5982
+ let startLine = 0;
5983
+ let lastLineStart = 0;
5984
+ let i = 0;
5985
+ for (; i < start; i++) if (status.source[i] === "\n") {
5986
+ startLine += 1;
5987
+ lastLineStart = i + 1;
5988
+ }
5989
+ let startChar = start - lastLineStart;
5990
+ let endLine = startLine;
5991
+ for (; i < end; i++) if (status.source[i] === "\n") {
5992
+ endLine += 1;
5993
+ lastLineStart = i + 1;
5994
+ }
5995
+ let endChar = end - lastLineStart;
5996
+ status.errors.push({
5997
+ message,
5998
+ startIndex: start,
5999
+ startLine,
6000
+ startChar,
6001
+ endIndex: end,
6002
+ endLine,
6003
+ endChar
6004
+ });
6005
+ }
6006
+ //#endregion
6007
+ //#region src/compile/parse/classifyComponents.ts
6008
+ /**
6009
+ * Classifies parsed tags as components or native elements once the whole file
6010
+ * has been parsed (so forward-declared local components are known).
6011
+ *
6012
+ * A tag is a component when its name is imported or is a component declared in
6013
+ * this file. Native and custom elements (`<div>`, `<my-widget>`,
6014
+ * `<linearGradient>`) stay elements. Any other capitalized tag is reported as
6015
+ * unknown instead of silently becoming a component call, unless the caller
6016
+ * opts into assuming external components (`allowUnknownComponents`).
6017
+ */
6018
+ function classifyComponents(status, importedNames, options) {
6019
+ const localNames = new Set(status.components.map((component) => component.name).filter((name) => !!name));
6020
+ for (const component of status.components) {
6021
+ if (component.markup) classifyNode(component.markup, status, importedNames, localNames, options);
6022
+ if (component.error) classifyNode(component.error, status, importedNames, localNames, options);
6023
+ if (component.head) classifyNode(component.head, status, importedNames, localNames, options);
6024
+ }
6025
+ }
6026
+ function classifyNode(node, status, importedNames, localNames, options) {
6027
+ if (isParentNode(node)) for (const child of node.children) classifyNode(child, status, importedNames, localNames, options);
6028
+ if (!isElementNode(node)) return;
6029
+ const tagName = node.tagName;
6030
+ if (importedNames.has(tagName) || localNames.has(tagName)) {
6031
+ node.type = "component";
6032
+ slottifyChildNodes(node);
6033
+ } else if (!nativeTags.has(tagName) && !tagName.includes("-") && /^[A-Z]/.test(tagName)) {
6034
+ if (options?.allowUnknownComponents) {
6035
+ node.type = "component";
6036
+ slottifyChildNodes(node);
6037
+ } else addError(status, `Unknown component or element: ${tagName}. Import it or define it in this file.`, node.span.start, node.span.end);
6038
+ }
6039
+ }
6040
+ //#endregion
6041
+ //#region src/compile/parse/collectImportNames.ts
6042
+ /**
6043
+ * Collects the local binding names introduced by top-level import statements.
6044
+ * Used to tell component tags apart from native elements without touching the
6045
+ * filesystem or relying on a tag-name convention.
6046
+ *
6047
+ * This is a focused import scanner, not a general JS parser: it handles the
6048
+ * import forms (`default`, `* as`, named/aliased, side-effect), comments and
6049
+ * multiline clauses. Type-only imports are ignored (they don't introduce a
6050
+ * value that can be rendered as a tag).
6051
+ */
6052
+ function collectImportNames(source) {
6053
+ const names = /* @__PURE__ */ new Set();
6054
+ let depth = 0;
6055
+ let i = 0;
6056
+ while (i < source.length) {
6057
+ const skipped = skipStringOrComment(source, i);
6058
+ if (skipped !== -1) {
6059
+ i = skipped;
6060
+ continue;
6061
+ }
6062
+ const char = source[i];
6063
+ if (char === "{") {
6064
+ depth += 1;
6065
+ i += 1;
6066
+ continue;
6067
+ }
6068
+ if (char === "}") {
6069
+ depth -= 1;
6070
+ i += 1;
6071
+ continue;
6072
+ }
6073
+ if (depth === 0 && char === "i" && startsWordAt(source, i, "import") && source[i - 1] !== ".") {
6074
+ const end = parseImport(source, i + 6, names);
6075
+ if (end !== -1) {
6076
+ i = end;
6077
+ continue;
6078
+ }
6079
+ }
6080
+ i += 1;
6081
+ }
6082
+ return names;
6083
+ }
6084
+ /** Parses one import statement, adding its value bindings. Returns the end index. */
6085
+ function parseImport(source, start, names) {
6086
+ let i = skipSpaceAndComments(source, start);
6087
+ if (i >= source.length) return -1;
6088
+ if (source[i] === "." || source[i] === "(") return -1;
6089
+ if (source[i] === "\"" || source[i] === "'") return skipStringAndStatementEnd(source, i);
6090
+ let typeOnly = false;
6091
+ if (startsWordAt(source, i, "type")) {
6092
+ const afterType = skipSpaceAndComments(source, i + 4);
6093
+ const next = source[afterType];
6094
+ if (next === "{" || next === "*" || isIdentifierStart(next)) {
6095
+ if (next === "{" || next === "*" || isTypeOnlyDefault(source, afterType)) {
6096
+ typeOnly = true;
6097
+ i = afterType;
6098
+ }
6099
+ }
6100
+ }
6101
+ while (i < source.length) {
6102
+ i = skipSpaceAndComments(source, i);
6103
+ if (i >= source.length) return -1;
6104
+ if (startsWordAt(source, i, "from")) {
6105
+ i = skipStringAndStatementEnd(source, skipSpaceAndComments(source, i + 4));
6106
+ return i;
6107
+ }
6108
+ const char = source[i];
6109
+ if (char === "{") {
6110
+ i += 1;
6111
+ while (i < source.length) {
6112
+ i = skipSpaceAndComments(source, i);
6113
+ if (source[i] === "}") {
6114
+ i += 1;
6115
+ break;
6116
+ }
6117
+ const specifier = parseSpecifier(source, i);
6118
+ if (!specifier) {
6119
+ i += 1;
6120
+ continue;
6121
+ }
6122
+ i = specifier.end;
6123
+ if (!typeOnly && specifier.name) names.add(specifier.name);
6124
+ }
6125
+ continue;
6126
+ }
6127
+ if (char === "*") {
6128
+ i = skipSpaceAndComments(source, i + 1);
6129
+ if (startsWordAt(source, i, "as")) {
6130
+ i = skipSpaceAndComments(source, i + 2);
6131
+ const identifier = readIdentifier(source, i);
6132
+ if (identifier) {
6133
+ if (!typeOnly) names.add(identifier.name);
6134
+ i = identifier.end;
6135
+ }
6136
+ }
6137
+ continue;
6138
+ }
6139
+ if (char === ",") {
6140
+ i += 1;
6141
+ continue;
6142
+ }
6143
+ if (isIdentifierStart(char)) {
6144
+ const identifier = readIdentifier(source, i);
6145
+ if (identifier) {
6146
+ if (!typeOnly) names.add(identifier.name);
6147
+ i = identifier.end;
6148
+ continue;
6149
+ }
6150
+ }
6151
+ i += 1;
6152
+ }
6153
+ return -1;
6154
+ }
6155
+ function parseSpecifier(source, start) {
6156
+ let i = skipSpaceAndComments(source, start);
6157
+ if (i >= source.length) return void 0;
6158
+ let typeOnly = false;
6159
+ if (startsWordAt(source, i, "type")) {
6160
+ const afterType = skipSpaceAndComments(source, i + 4);
6161
+ const next = source[afterType];
6162
+ if (next && next !== "," && next !== "}" && !startsWordAt(source, afterType, "as")) {
6163
+ typeOnly = true;
6164
+ i = afterType;
6165
+ }
6166
+ }
6167
+ let name;
6168
+ if (source[i] === "\"" || source[i] === "'") {
6169
+ const end = skipStringOrComment(source, i);
6170
+ i = end === -1 ? i + 1 : end;
6171
+ } else {
6172
+ const identifier = readIdentifier(source, i);
6173
+ if (!identifier) return void 0;
6174
+ name = identifier.name;
6175
+ i = identifier.end;
6176
+ }
6177
+ i = skipSpaceAndComments(source, i);
6178
+ if (startsWordAt(source, i, "as")) {
6179
+ i = skipSpaceAndComments(source, i + 2);
6180
+ if (source[i] === "\"" || source[i] === "'") {
6181
+ const end = skipStringOrComment(source, i);
6182
+ i = end === -1 ? i + 1 : end;
6183
+ name = void 0;
6184
+ } else {
6185
+ const alias = readIdentifier(source, i);
6186
+ if (alias) {
6187
+ name = alias.name;
6188
+ i = alias.end;
6189
+ }
6190
+ }
6191
+ }
6192
+ i = skipSpaceAndComments(source, i);
6193
+ if (source[i] === ",") i += 1;
6194
+ return {
6195
+ name: typeOnly ? void 0 : name,
6196
+ end: i
6197
+ };
6198
+ }
6199
+ function isTypeOnlyDefault(source, start) {
6200
+ const identifier = readIdentifier(source, start);
6201
+ if (!identifier) return false;
6202
+ return startsWordAt(source, skipSpaceAndComments(source, identifier.end), "from");
6203
+ }
6204
+ function skipStringAndStatementEnd(source, start) {
6205
+ let i = start;
6206
+ if (source[i] === "\"" || source[i] === "'") {
6207
+ const end = skipStringOrComment(source, i);
6208
+ i = end === -1 ? i + 1 : end;
6209
+ }
6210
+ i = skipSpaceAndComments(source, i);
6211
+ if (source[i] === ";") i += 1;
6212
+ return i;
6213
+ }
6214
+ function skipSpaceAndComments(source, start) {
6215
+ let i = start;
6216
+ while (i < source.length) {
6217
+ if (/\s/.test(source[i])) {
6218
+ i += 1;
6219
+ continue;
6220
+ }
6221
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) {
6222
+ const skipped = skipStringOrComment(source, i);
6223
+ if (skipped !== -1) {
6224
+ i = skipped;
6225
+ continue;
6226
+ }
6227
+ }
6228
+ break;
6229
+ }
6230
+ return i;
6231
+ }
6232
+ function readIdentifier(source, start) {
6233
+ if (!isIdentifierStart(source[start])) return void 0;
6234
+ let end = start + 1;
6235
+ while (end < source.length && isIdentifierPart(source[end])) end += 1;
6236
+ return {
6237
+ name: source.substring(start, end),
6238
+ end
6239
+ };
6240
+ }
6241
+ function isIdentifierStart(char) {
6242
+ return char !== void 0 && /[A-Za-z_$]/.test(char);
6243
+ }
6244
+ function isIdentifierPart(char) {
6245
+ return /[A-Za-z0-9_$]/.test(char);
6246
+ }
6247
+ function startsWordAt(source, start, word) {
6248
+ if (!source.startsWith(word, start)) return false;
6249
+ const previous = source[start - 1];
6250
+ const next = source[start + word.length];
6251
+ return (previous === void 0 || !isIdentifierPart(previous)) && (next === void 0 || !isIdentifierPart(next));
6252
+ }
6253
+ //#endregion
6254
+ //#region src/compile/parse/utils/accept.ts
6255
+ /**
6256
+ * Checks whether the source at the current parse position matches the supplied
6257
+ * string
6258
+ *
6259
+ * @param value The string to check
6260
+ * @param status The parse status
6261
+ * @param advance (Optional) If true, advances the parse position past the
6262
+ * checked string (defaults to true)
6263
+ *
6264
+ * @returns True if the supplied string was found at the current parse position
6265
+ */
6266
+ function accept(value, status, advance = true) {
6267
+ if (status.source.substring(status.i, status.i + value.length) == value) {
6268
+ status.i += advance ? value.length : 0;
6269
+ return true;
6270
+ }
6271
+ return false;
6272
+ }
6273
+ //#endregion
6274
+ //#region src/compile/parse/parseInlineScript.ts
6275
+ function parseInlineScript(status) {
5319
6276
  const start = status.i;
5320
6277
  let braceCount = 0;
5321
6278
  while (status.i < status.source.length) {
@@ -5383,79 +6340,36 @@ function addSpaceElement(parent, status) {
5383
6340
  //#endregion
5384
6341
  //#region src/compile/utils/isFullyReactive.ts
5385
6342
  /**
5386
- * Checks whether the supplied string is fully reactive (i.e. starts and ends with braces)
6343
+ * Checks whether the supplied text is exactly one `{...}` interpolation,
6344
+ * ignoring surrounding whitespace. Braces inside the expression's strings and
6345
+ * comments don't count as delimiters.
5387
6346
  *
5388
- * @param text The string to check
6347
+ * @param text The text to check
5389
6348
  *
5390
- * @returns True if the supplied string is fully reactive
6349
+ * @returns True if the supplied text is fully reactive
5391
6350
  */
5392
6351
  function isFullyReactive(text) {
5393
- return text.trim().startsWith("{") && text.trim().endsWith("}");
6352
+ return isSingleInterpolation(text);
5394
6353
  }
5395
6354
  //#endregion
5396
- //#region src/compile/parse/utils/addError.ts
6355
+ //#region src/compile/parse/utils/consumeTagName.ts
5397
6356
  /**
5398
- * Adds an error to the parse status
6357
+ * Consumes a tag name, allowing letters, digits and dashes (custom elements
6358
+ * such as `<my-widget>`), and advances the current parse position to before
6359
+ * the next non-name character.
5399
6360
  *
5400
6361
  * @param status The parse status
5401
- * @param message The error message to add
5402
- * @param start (Optional) The start position of the error (defaults to the
5403
- * current parse position)
5404
- */
5405
- function addError(status, message, start = status.i, end = status.i) {
5406
- let startLine = 0;
5407
- let lastLineStart = 0;
5408
- let i = 0;
5409
- for (; i < start; i++) if (status.source[i] === "\n") {
5410
- startLine += 1;
5411
- lastLineStart = i + 1;
5412
- }
5413
- let startChar = start - lastLineStart;
5414
- let endLine = startLine;
5415
- for (; i < end; i++) if (status.source[i] === "\n") {
5416
- endLine += 1;
5417
- lastLineStart = i + 1;
5418
- }
5419
- let endChar = end - lastLineStart;
5420
- status.errors.push({
5421
- message,
5422
- startIndex: start,
5423
- startLine,
5424
- startChar,
5425
- endIndex: end,
5426
- endLine,
5427
- endChar
5428
- });
5429
- }
5430
- //#endregion
5431
- //#region src/compile/parse/utils/isAlphaNumericChar.ts
5432
- /**
5433
- * Checks whether the supplied character is a alpha-numeric
5434
- *
5435
- * @param text The string to check
5436
- * @param index The index of the character in the string
5437
6362
  *
5438
- * @returns True if the supplied character is alpha-numeric
6363
+ * @returns The tag name from the current parse position to the next non-name
6364
+ * character
5439
6365
  */
5440
- function isAlphaNumericChar(text, index) {
5441
- let code = text.charCodeAt(index);
5442
- return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
5443
- }
5444
- //#endregion
5445
- //#region src/compile/parse/utils/consumeAlphaNumeric.ts
5446
- /**
5447
- * Consumes alpha-numeric characters and advances the current parse position to
5448
- * before the next non-alpha character
5449
- *
5450
- * @param status The parse status
5451
- *
5452
- * @returns The string of alpha-numeric characters from the current parse position
5453
- * to the next non-alpha character
5454
- */
5455
- function consumeAlphaNumeric(status) {
6366
+ function consumeTagName(status) {
5456
6367
  const start = status.i;
5457
- for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
5458
- return "";
6368
+ for (status.i; status.i < status.source.length; status.i++) {
6369
+ const char = status.source[status.i];
6370
+ if (!/[A-Za-z0-9-]/.test(char)) return status.source.substring(start, status.i);
6371
+ }
6372
+ return status.source.substring(start, status.i);
5459
6373
  }
5460
6374
  //#endregion
5461
6375
  //#region src/compile/parse/utils/consumeUntil.ts
@@ -5482,7 +6396,7 @@ function parseTag(status) {
5482
6396
  consumeSpace(status);
5483
6397
  let tagStart = status.i + 1;
5484
6398
  let snailed = accept("@", status);
5485
- let tagName = consumeAlphaNumeric(status);
6399
+ let tagName = consumeTagName(status);
5486
6400
  let tagEnd = status.i;
5487
6401
  if (snailed) tagName = "@" + tagName;
5488
6402
  if (closeTag) tagName = "/" + tagName;
@@ -5537,14 +6451,20 @@ function parseAttribute(status) {
5537
6451
  if (accept("=", status)) {
5538
6452
  consumeSpace(status);
5539
6453
  valueStart = status.i;
5540
- value = parseAttributeValue(status);
5541
- valueEnd = status.i;
5542
- reactive = isReactive(value);
5543
- fullyReactive = isFullyReactive(value);
5544
- if (fullyReactive) {
5545
- value = value.substring(1, value.length - 1);
5546
- valueStart++;
5547
- valueEnd--;
6454
+ if (status.source[valueStart] === "`") {
6455
+ value = parseTemplateLiteral(status);
6456
+ valueEnd = status.i;
6457
+ reactive = fullyReactive = true;
6458
+ } else {
6459
+ value = parseAttributeValue(status);
6460
+ valueEnd = status.i;
6461
+ fullyReactive = isFullyReactive(value);
6462
+ reactive = fullyReactive;
6463
+ if (fullyReactive) {
6464
+ value = value.substring(1, value.length - 1);
6465
+ valueStart++;
6466
+ valueEnd--;
6467
+ }
5548
6468
  }
5549
6469
  } else if (name.startsWith("{") && name.endsWith("}")) {
5550
6470
  value = name.substring(1, name.length - 1);
@@ -5567,6 +6487,18 @@ function parseAttribute(status) {
5567
6487
  }
5568
6488
  };
5569
6489
  }
6490
+ /**
6491
+ * Consumes a backtick-delimited JavaScript template literal, reusing the
6492
+ * script scanner so `${...}` interpolations and nested strings/templates are
6493
+ * skipped correctly.
6494
+ */
6495
+ function parseTemplateLiteral(status) {
6496
+ const start = status.i;
6497
+ const end = skipStringOrComment(status.source, start);
6498
+ status.i = end === -1 ? start + 1 : end;
6499
+ if (status.source[status.i - 1] !== "`") addError(status, "Unclosed template literal in attribute", start, status.i);
6500
+ return status.source.substring(start, status.i);
6501
+ }
5570
6502
  function parseAttributeValue(status) {
5571
6503
  if (accept("\"", status)) {
5572
6504
  const value = consumeUntil("\"", status);
@@ -5647,73 +6579,6 @@ function parseText(status, element) {
5647
6579
  } else status.i += 1;
5648
6580
  }
5649
6581
  //#endregion
5650
- //#region src/compile/parse/utils/usesSlot.ts
5651
- const slotRegex = /\$slot\b/;
5652
- /**
5653
- * Checks whether the $slot variable is read in the nodes' own scope
5654
- *
5655
- * Note that the children of a component node are excluded, because they are
5656
- * passed to the component as fills, which get their own $slot parameter.
5657
- * The component's attributes do belong to this scope.
5658
- *
5659
- * @param nodes The nodes to check
5660
- *
5661
- * @returns True if a $slot variable is read in the nodes' own scope
5662
- */
5663
- function usesSlot(nodes) {
5664
- for (let node of nodes) if (node.type === "text") {
5665
- const text = node;
5666
- if (slotRegex.test(text.content)) return true;
5667
- } else if (node.type === "control") {
5668
- const control = node;
5669
- if (slotRegex.test(control.statement)) return true;
5670
- if (usesSlot(control.children)) return true;
5671
- } else if (node.type === "element" || node.type === "special" || node.type === "component") {
5672
- const element = node;
5673
- for (let attribute of element.attributes) {
5674
- if (slotRegex.test(attribute.name)) return true;
5675
- if (attribute.value && slotRegex.test(attribute.value)) return true;
5676
- }
5677
- if (element.type !== "component" && usesSlot(element.children)) return true;
5678
- }
5679
- return false;
5680
- }
5681
- //#endregion
5682
- //#region src/compile/parse/slottifyChildNodes.ts
5683
- /**
5684
- * Moves any child nodes that aren't already in a <fill> node into a default
5685
- * <fill> node
5686
- */
5687
- function slottifyChildNodes(node) {
5688
- let nonFillNodes = [];
5689
- for (let child of node.children) if (isFillNode(child)) {
5690
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5691
- else break;
5692
- } else nonFillNodes.push(child);
5693
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5694
- if (nonFillNodes.length) {
5695
- let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
5696
- if (!defaultFillNode) {
5697
- defaultFillNode = {
5698
- type: "special",
5699
- tagName: "filldef",
5700
- attributes: [],
5701
- children: nonFillNodes,
5702
- span: {
5703
- start: 0,
5704
- end: 0
5705
- },
5706
- hasSlotProps: usesSlot(nonFillNodes)
5707
- };
5708
- node.children.unshift(defaultFillNode);
5709
- }
5710
- node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
5711
- }
5712
- }
5713
- function isFillNode(n) {
5714
- return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
5715
- }
5716
- //#endregion
5717
6582
  //#region src/compile/parse/parseElement.ts
5718
6583
  function parseElement(status) {
5719
6584
  const current = status.components.at(-1);
@@ -5727,6 +6592,7 @@ function parseElement(status) {
5727
6592
  if (voidTags.includes(element.tagName)) checkVoidElement(status, element);
5728
6593
  if (!element.selfClosed && !voidTags.includes(element.tagName)) {
5729
6594
  status.stack.push(element);
6595
+ if (isRawTextTag(element.tagName)) parseRawText(status, element);
5730
6596
  while (status.i < status.source.length) {
5731
6597
  addSpaceElement(element, status);
5732
6598
  if (accept("}", status, false)) break;
@@ -5767,10 +6633,6 @@ function parseElement(status) {
5767
6633
  }
5768
6634
  status.stack.pop();
5769
6635
  }
5770
- if (/[A-Z]/.test(element.tagName[0])) {
5771
- element.type = "component";
5772
- slottifyChildNodes(element);
5773
- }
5774
6636
  if (isSpecialNode(element)) {
5775
6637
  if (element.tagName === "slot") {
5776
6638
  slottifyChildNodes(element);
@@ -5808,6 +6670,32 @@ function parseElement(status) {
5808
6670
  if (!element.closed && !voidTags.includes(element.tagName)) addError(status, `Unclosed non-void element: ${element.tagName}`, start, start + element.tagName.length + 1);
5809
6671
  return element;
5810
6672
  }
6673
+ /**
6674
+ * Consumes a raw-text element's content as a single literal text node. The
6675
+ * content ends at the first matching close tag (which the caller's child loop
6676
+ * then handles), or at the end of the source when the element is unclosed.
6677
+ */
6678
+ function parseRawText(status, element) {
6679
+ const start = status.i;
6680
+ const end = findRawTextEnd(status.source, element.tagName, start);
6681
+ if (end > start) {
6682
+ const text = {
6683
+ type: "text",
6684
+ content: status.source.substring(start, end),
6685
+ start,
6686
+ spans: [],
6687
+ raw: true
6688
+ };
6689
+ element.children.push(text);
6690
+ }
6691
+ status.i = end;
6692
+ }
6693
+ function findRawTextEnd(source, tagName, start) {
6694
+ const pattern = new RegExp(`</${tagName}(?=[\\s/>])`, "gi");
6695
+ pattern.lastIndex = start;
6696
+ const match = pattern.exec(source);
6697
+ return match ? match.index : source.length;
6698
+ }
5811
6699
  function checkVoidElement(status, element) {
5812
6700
  let i = status.i;
5813
6701
  consumeSpace(status);
@@ -5827,7 +6715,7 @@ function checkCloseTag(status, element) {
5827
6715
  accept("</", status);
5828
6716
  consumeSpace(status);
5829
6717
  let snailed = accept("@", status);
5830
- let closingTagName = consumeAlphaNumeric(status);
6718
+ let closingTagName = consumeTagName(status);
5831
6719
  if (snailed) closingTagName = "@" + closingTagName;
5832
6720
  consumeSpace(status);
5833
6721
  accept(">", status);
@@ -5937,6 +6825,8 @@ function parseControlOpen(status) {
5937
6825
  };
5938
6826
  }
5939
6827
  function parseControlStatement(start, operation, status) {
6828
+ const standalone = standaloneOperations.includes(operation);
6829
+ const braceStartsBody = !standalone || operation === "@function" || operation === "@async function";
5940
6830
  let parenCount = 0;
5941
6831
  while (status.i < status.source.length) {
5942
6832
  const skipped = skipStringOrComment(status.source, status.i);
@@ -5946,11 +6836,11 @@ function parseControlStatement(start, operation, status) {
5946
6836
  }
5947
6837
  if (accept("(", status)) parenCount += 1;
5948
6838
  else if (accept(")", status)) parenCount -= 1;
5949
- else if (accept("{", status) || accept("\n", status) && standaloneOperations.includes(operation)) {
6839
+ else if (accept("{", status) && braceStartsBody || accept("\n", status) && standalone) {
5950
6840
  if (parenCount === 0) return trimStart(status.source.substring(start, status.i - 1).trim(), "@");
5951
6841
  } else status.i += 1;
5952
6842
  }
5953
- return "";
6843
+ return trimStart(status.source.substring(start, status.i).trim(), "@");
5954
6844
  }
5955
6845
  /**
5956
6846
  * Groups the control node into the correct parent e.g. if/else into an if group
@@ -6203,7 +7093,6 @@ function parseStyles(source, status) {
6203
7093
  marker: 0,
6204
7094
  level: 0,
6205
7095
  braces: [],
6206
- imports: [],
6207
7096
  script: [],
6208
7097
  components: [],
6209
7098
  stack: [],
@@ -6282,37 +7171,64 @@ function parseStyleAttribute(status) {
6282
7171
  }
6283
7172
  //#endregion
6284
7173
  //#region src/compile/parse/scopeStyles.ts
7174
+ /**
7175
+ * Marks every element in a component that has scoped styles with the
7176
+ * component's scope class. This is intentionally not selector-based: deciding
7177
+ * which elements a CSS selector can match requires parsing selectors, and
7178
+ * pseudo-classes, attribute selectors and `@media` rules make compile-time
7179
+ * matching unreliable. Marking every element lets `buildStyles` append the
7180
+ * scope class to selectors without needing to understand their shape.
7181
+ */
6285
7182
  function scopeStyles(status) {
6286
- let selectors = [];
6287
- for (let component of status.components) if (component.style && component.markup) {
6288
- for (let block of component.style.children) if (block.type === "block") collectStyleSelectors(block, selectors);
6289
- scopeStylesOnNode(component.markup, selectors);
7183
+ for (let component of status.components) {
7184
+ if (!component.style) continue;
7185
+ if (component.markup) scopeStylesOnNode(component.markup);
7186
+ if (component.error) scopeStylesOnNode(component.error);
6290
7187
  }
6291
7188
  }
6292
- function scopeStylesOnNode(node, selectors) {
6293
- if (isElementNode(node) || isComponentNode(node)) node.scopeStyles = selectors.includes(node.tagName) || node.attributes.find((a) => {
6294
- if (a.name === "class" && a.reactive) return true;
6295
- else if (a.name === "id" && a.value) {
6296
- if (selectors.includes(`#${trimQuotes(a.value)}`)) return true;
6297
- } else if (a.name === "class" && a.value) {
6298
- for (let classname of trimQuotes(a.value).split(/\s+/)) if (selectors.includes(`.${classname}`)) return true;
6299
- }
6300
- }) !== void 0;
6301
- if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child, selectors);
7189
+ function scopeStylesOnNode(node) {
7190
+ if (isElementNode(node) || isComponentNode(node) || isSpecialNode(node) && (node.tagName === "@element" || node.tagName === "@component")) node.scopeStyles = true;
7191
+ if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child);
6302
7192
  }
6303
- function collectStyleSelectors(block, selectors) {
6304
- for (let s of block.selector.split(/[\s*,>+~[\]]/)) selectors.push(s);
7193
+ //#endregion
7194
+ //#region src/compile/parse/utils/isAlphaNumericChar.ts
7195
+ /**
7196
+ * Checks whether the supplied character is a alpha-numeric
7197
+ *
7198
+ * @param text The string to check
7199
+ * @param index The index of the character in the string
7200
+ *
7201
+ * @returns True if the supplied character is alpha-numeric
7202
+ */
7203
+ function isAlphaNumericChar(text, index) {
7204
+ let code = text.charCodeAt(index);
7205
+ return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
7206
+ }
7207
+ //#endregion
7208
+ //#region src/compile/parse/utils/consumeAlphaNumeric.ts
7209
+ /**
7210
+ * Consumes alpha-numeric characters and advances the current parse position to
7211
+ * before the next non-alpha character
7212
+ *
7213
+ * @param status The parse status
7214
+ *
7215
+ * @returns The string of alpha-numeric characters from the current parse position
7216
+ * to the next non-alpha character
7217
+ */
7218
+ function consumeAlphaNumeric(status) {
7219
+ const start = status.i;
7220
+ for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
7221
+ return "";
6305
7222
  }
6306
7223
  //#endregion
6307
7224
  //#region src/compile/parse/parseCode.ts
6308
- function parseCode(source) {
7225
+ function parseCode(source, options) {
6309
7226
  const status = {
6310
7227
  source,
6311
7228
  i: 0,
6312
7229
  marker: 0,
6313
7230
  level: 0,
6314
7231
  braces: [],
6315
- imports: [],
6316
7232
  script: [],
6317
7233
  components: [],
6318
7234
  stack: [],
@@ -6368,6 +7284,7 @@ function parseCode(source) {
6368
7284
  end: source.length
6369
7285
  }
6370
7286
  });
7287
+ classifyComponents(status, collectImportNames(source), options);
6371
7288
  scopeStyles(status);
6372
7289
  const ok = !status.errors.length;
6373
7290
  if (!ok) status.errors = status.errors.sort((a, b) => a.startIndex - b.startIndex);
@@ -6375,7 +7292,6 @@ function parseCode(source) {
6375
7292
  ok,
6376
7293
  errors: status.errors,
6377
7294
  template: ok ? {
6378
- imports: status.imports,
6379
7295
  script: status.script,
6380
7296
  components: status.components
6381
7297
  } : void 0
@@ -6471,7 +7387,6 @@ function parseComponentStart(status) {
6471
7387
  marker: 0,
6472
7388
  level: 0,
6473
7389
  braces: [],
6474
- imports: [],
6475
7390
  script: [],
6476
7391
  components: [],
6477
7392
  stack: [],
@@ -6732,12 +7647,13 @@ function consumeScriptComments(status) {
6732
7647
  * Parses source code into a component template
6733
7648
  *
6734
7649
  * @param source The source code
7650
+ * @param options Optional parse behaviour
6735
7651
  *
6736
7652
  * @returns A result indicating whether parsing was ok, and if so, containing
6737
7653
  * the component template's parts such as script, markup and styles
6738
7654
  */
6739
- function parse(source) {
6740
- return parseCode(source);
7655
+ function parse(source, options) {
7656
+ return parseCode(source, options);
6741
7657
  }
6742
7658
  //#endregion
6743
7659
  //#region src/compile/parse/bindDataTemplate.ts