@stacksjs/stx 0.2.285 → 0.2.287

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 (166) hide show
  1. package/dist/builtins/index.d.ts +4 -3
  2. package/dist/builtins/index.js +11 -11
  3. package/dist/chunk-122tyfre.js +2 -0
  4. package/dist/{chunk-0fgcnv6y.js → chunk-19nfvxfw.js} +1 -1
  5. package/dist/{chunk-f2s94353.js → chunk-1kah92n2.js} +1 -1
  6. package/dist/{chunk-90qr4f9m.js → chunk-1kms3b9d.js} +1 -1
  7. package/dist/{chunk-s2284nbk.js → chunk-1q4y74mh.js} +1 -1
  8. package/dist/{chunk-49kk0s96.js → chunk-248e84r1.js} +1 -1
  9. package/dist/{chunk-zfr4d08r.js → chunk-24ps8kft.js} +1 -1
  10. package/dist/chunk-2et5hxfv.js +2 -0
  11. package/dist/chunk-2r1rd8f0.js +2 -0
  12. package/dist/{chunk-n3qyd366.js → chunk-2tk1zkrz.js} +1 -1
  13. package/dist/{chunk-ysnk7x79.js → chunk-38ejahd9.js} +1 -1
  14. package/dist/chunk-3zv4wz87.js +2 -0
  15. package/dist/chunk-4122k1bh.js +2 -0
  16. package/dist/chunk-45az9zht.js +2 -0
  17. package/dist/{chunk-yq1d9hb3.js → chunk-4qr85f07.js} +1 -1
  18. package/dist/{chunk-9aw94jhm.js → chunk-4ww3znrr.js} +4 -4
  19. package/dist/chunk-5a19dhx5.js +2 -0
  20. package/dist/{chunk-39f40yc4.js → chunk-5kk8gsj2.js} +1 -1
  21. package/dist/{chunk-kzyhvrp8.js → chunk-5w1e3yxs.js} +1 -1
  22. package/dist/chunk-6gdycmxr.js +2 -0
  23. package/dist/{chunk-xqxg3fck.js → chunk-6hmnaza7.js} +10 -10
  24. package/dist/{chunk-zn5jgmqw.js → chunk-71t0yan0.js} +1 -1
  25. package/dist/chunk-74v15e8z.js +2 -0
  26. package/dist/{chunk-3y623mek.js → chunk-7b329e5v.js} +1 -1
  27. package/dist/{chunk-g3fy0tw8.js → chunk-866y9d8b.js} +154 -48
  28. package/dist/chunk-8fwerspy.js +2 -0
  29. package/dist/{chunk-c0an64km.js → chunk-8mjdpr94.js} +1 -1
  30. package/dist/{chunk-q68xmak4.js → chunk-92mj1t26.js} +18 -18
  31. package/dist/{chunk-f8b83xbw.js → chunk-9b22663r.js} +1 -1
  32. package/dist/chunk-9hjdgm4d.js +2 -0
  33. package/dist/{chunk-egez576q.js → chunk-9wr7zcad.js} +2 -2
  34. package/dist/{chunk-dy2y790t.js → chunk-a0nfbmeh.js} +1 -1
  35. package/dist/{chunk-7g88q9ft.js → chunk-acn1b56m.js} +2 -2
  36. package/dist/chunk-awkq3xfx.js +2 -0
  37. package/dist/{chunk-bf8wf3r2.js → chunk-b6ej2fdf.js} +2 -2
  38. package/dist/{chunk-e7jfpyqy.js → chunk-b8rrnqry.js} +1 -1
  39. package/dist/{chunk-a1g1zsbh.js → chunk-bfqfs07m.js} +1 -1
  40. package/dist/{chunk-fjkstnz3.js → chunk-bs6kapy7.js} +1 -1
  41. package/dist/{chunk-qd8ggjdx.js → chunk-btav940g.js} +1 -1
  42. package/dist/{chunk-pbk8jxe2.js → chunk-ccspd3mc.js} +1 -1
  43. package/dist/{chunk-7rxtra1g.js → chunk-csbgwaa5.js} +1 -1
  44. package/dist/chunk-d8t4sjsp.js +2 -0
  45. package/dist/chunk-dap191q2.js +2 -0
  46. package/dist/{chunk-ayrjwkyw.js → chunk-de7fye10.js} +1 -1
  47. package/dist/{chunk-2g9jwgs7.js → chunk-dgrt76d2.js} +1 -1
  48. package/dist/{chunk-9zndrzb3.js → chunk-dhh5q7qt.js} +1 -1
  49. package/dist/chunk-dsffsqnt.js +2 -0
  50. package/dist/{chunk-d0c3v7ax.js → chunk-dtq7y5ym.js} +1 -1
  51. package/dist/{chunk-w95sp0k9.js → chunk-fed3xsp9.js} +2 -2
  52. package/dist/{chunk-bxskmetn.js → chunk-ferav3bw.js} +1 -1
  53. package/dist/{chunk-a63y3aa0.js → chunk-fvhm8psm.js} +1 -1
  54. package/dist/{chunk-bz2gytfs.js → chunk-g4vpzv6b.js} +1 -1
  55. package/dist/{chunk-d34fnbpc.js → chunk-g9csmj0s.js} +1 -1
  56. package/dist/chunk-gtcrpmz1.js +2 -0
  57. package/dist/{chunk-9v5s9ax8.js → chunk-h4xh8cms.js} +1 -1
  58. package/dist/chunk-h8yqsz9m.js +2 -0
  59. package/dist/{chunk-phhzfeh9.js → chunk-hcq5dw7a.js} +1 -1
  60. package/dist/{chunk-d10btecr.js → chunk-hm0xha6c.js} +1 -1
  61. package/dist/chunk-jegt35zh.js +2 -0
  62. package/dist/{chunk-ggrzaenz.js → chunk-k56rjjc0.js} +1 -1
  63. package/dist/{chunk-ada449cq.js → chunk-kdh37tp8.js} +1 -1
  64. package/dist/{chunk-e4hhz9j3.js → chunk-kxzb4et3.js} +1 -1
  65. package/dist/{chunk-3bv8h4r6.js → chunk-mf4n3x1j.js} +1 -1
  66. package/dist/{chunk-5aq35j2e.js → chunk-mkd9kjgb.js} +1 -1
  67. package/dist/chunk-mxfh1nxg.js +2 -0
  68. package/dist/{chunk-snknv47x.js → chunk-nkb3scg6.js} +1 -1
  69. package/dist/{chunk-s67mgegv.js → chunk-nnd4wq8j.js} +1 -1
  70. package/dist/{chunk-1xfqy79h.js → chunk-nsp1cw38.js} +1 -1
  71. package/dist/chunk-p3242nck.js +2 -0
  72. package/dist/chunk-p98kfh94.js +2 -0
  73. package/dist/{chunk-t1k5dpbr.js → chunk-pkaabd8h.js} +1 -1
  74. package/dist/{chunk-t0ghjghe.js → chunk-pzm13sdc.js} +1 -1
  75. package/dist/{chunk-n32gnc22.js → chunk-q4p5k2p3.js} +1 -1
  76. package/dist/{chunk-sskbegsz.js → chunk-qc1f74ek.js} +1 -1
  77. package/dist/{chunk-nvgxjvnb.js → chunk-qpyjak7z.js} +1 -1
  78. package/dist/{chunk-0hdkedwq.js → chunk-qr82je1m.js} +1 -1
  79. package/dist/{chunk-a54n1r1q.js → chunk-qy73j6m4.js} +1 -1
  80. package/dist/{chunk-p396xrew.js → chunk-qzkhpsam.js} +1 -1
  81. package/dist/{chunk-f3hfk78e.js → chunk-r3ayvdz3.js} +1 -1
  82. package/dist/chunk-r7r66978.js +2 -0
  83. package/dist/{chunk-kpy77ys3.js → chunk-rbb7dvja.js} +1 -1
  84. package/dist/{chunk-kdrpx9ft.js → chunk-rj4kajww.js} +1 -1
  85. package/dist/{chunk-areethga.js → chunk-rp4rjjmf.js} +1 -1
  86. package/dist/{chunk-gjemavhx.js → chunk-se0p17c2.js} +1 -1
  87. package/dist/chunk-sj9pmene.js +2 -0
  88. package/dist/{chunk-a2qghr2x.js → chunk-sscwkffs.js} +1 -1
  89. package/dist/chunk-svpqxn2c.js +2 -0
  90. package/dist/chunk-t8y1ggdy.js +2 -0
  91. package/dist/{chunk-y6kw0wb7.js → chunk-tndhnk9e.js} +1 -1
  92. package/dist/{chunk-c6fw33zh.js → chunk-v5e1gxwm.js} +2 -2
  93. package/dist/{chunk-7p9ns60j.js → chunk-vrrax298.js} +1 -1
  94. package/dist/{chunk-zcmtqan3.js → chunk-wrzwgkbx.js} +3 -3
  95. package/dist/{chunk-jn6m8zf7.js → chunk-x650vjcp.js} +1 -1
  96. package/dist/{chunk-mjkfc2v6.js → chunk-xgnc1wy6.js} +1 -1
  97. package/dist/{chunk-52mh63sp.js → chunk-xpp135ad.js} +1 -1
  98. package/dist/chunk-y11cxbxd.js +3757 -0
  99. package/dist/{chunk-cvnh7dma.js → chunk-y98jsjqq.js} +1 -1
  100. package/dist/{chunk-vbdca0k1.js → chunk-ya386h70.js} +1 -1
  101. package/dist/chunk-ydrz60kr.js +2 -0
  102. package/dist/{chunk-0f1kz0x2.js → chunk-ypmqf7tm.js} +1 -1
  103. package/dist/{chunk-cb74rvec.js → chunk-z4jhj5e5.js} +1 -1
  104. package/dist/{chunk-fskfes13.js → chunk-zg75gjns.js} +1 -1
  105. package/dist/{chunk-mb518a4n.js → chunk-zqqx1qaj.js} +1 -1
  106. package/dist/cli.js +14 -14
  107. package/dist/client-script-bundler.js +7 -7
  108. package/dist/client-script.js +27 -7
  109. package/dist/component-client-factories.js +10 -5
  110. package/dist/component-processing.d.ts +13 -0
  111. package/dist/component-processing.js +37 -1
  112. package/dist/component-renderer.js +34 -15
  113. package/dist/conditionals.js +14 -3
  114. package/dist/craft-entry.js +1 -1
  115. package/dist/craft.js +1 -1
  116. package/dist/database.js +1 -1
  117. package/dist/document-shell.d.ts +1 -34
  118. package/dist/document-shell.js +19 -11
  119. package/dist/html-masking.d.ts +65 -9
  120. package/dist/html-masking.js +103 -15
  121. package/dist/misc-directives.d.ts +1 -1
  122. package/dist/misc-directives.js +48 -13
  123. package/dist/process.js +14 -4
  124. package/dist/pwa.js +2 -2
  125. package/dist/reactive-bindings.js +2 -0
  126. package/dist/runtime-globals.d.ts +7 -20
  127. package/dist/runtime-globals.js +28 -3
  128. package/dist/safe-evaluator.d.ts +15 -0
  129. package/dist/safe-evaluator.js +16 -12
  130. package/dist/server-bindings.js +21 -5
  131. package/dist/signal-processing.d.ts +17 -7
  132. package/dist/signal-processing.js +112 -43
  133. package/dist/signals-api.js +5 -2
  134. package/dist/signals.js +153 -47
  135. package/dist/ssg.js +2 -2
  136. package/dist/utils.js +23 -6
  137. package/dist/variable-extractor.js +17 -47
  138. package/dist/visual-testing.js +1 -1
  139. package/package.json +5 -5
  140. package/dist/chunk-1k957wj9.js +0 -2
  141. package/dist/chunk-43r6p08p.js +0 -2
  142. package/dist/chunk-492g6g4g.js +0 -2
  143. package/dist/chunk-60c5bvke.js +0 -2
  144. package/dist/chunk-71nr1avx.js +0 -2
  145. package/dist/chunk-7gbwa2ph.js +0 -2
  146. package/dist/chunk-8ns2r0we.js +0 -2
  147. package/dist/chunk-9rkntp0z.js +0 -3756
  148. package/dist/chunk-b29wbjs5.js +0 -2
  149. package/dist/chunk-ba6tthsm.js +0 -2
  150. package/dist/chunk-f6x9bh8n.js +0 -2
  151. package/dist/chunk-f80wwn5x.js +0 -2
  152. package/dist/chunk-fk6ssg32.js +0 -2
  153. package/dist/chunk-gkmtkzdm.js +0 -2
  154. package/dist/chunk-hzw1ekq3.js +0 -2
  155. package/dist/chunk-j03bare5.js +0 -2
  156. package/dist/chunk-jxjt1szw.js +0 -2
  157. package/dist/chunk-m2harpd3.js +0 -2
  158. package/dist/chunk-qp97dx7x.js +0 -2
  159. package/dist/chunk-stw3ej3d.js +0 -2
  160. package/dist/chunk-v4f08c2r.js +0 -2
  161. package/dist/chunk-vrvehb01.js +0 -2
  162. package/dist/chunk-y1segp76.js +0 -2
  163. package/dist/chunk-y3qng57q.js +0 -2
  164. package/dist/chunk-yqaky7fa.js +0 -2
  165. package/dist/chunk-ytgnzeeb.js +0 -2
  166. package/dist/chunk-z7cwrmgt.js +0 -2
@@ -5,30 +5,48 @@ import { escapeScriptBody } from "./script-emit.js";
5
5
  import { transformStoreImports } from "./store-imports.js";
6
6
  import { shouldTranspileTypeScript, transpileTypeScript } from "./utils.js";
7
7
  import { injectSignalsRuntime } from "./runtime-injection.js";
8
- import { matchScriptElement, scanAtElementPosition } from "./html-masking.js";
8
+ import { evictOldest, matchScriptElement, scanAtElementPosition } from "./html-masking.js";
9
9
  import { importOnce } from "./lazy-module.js";
10
10
  let signalSetupCounter = 0;
11
- const TAG_ATTR_RUN = `(?:"[^"]*"|'[^']*'|[^>"'])*`, SINGLE_ELEMENT_RE = /^<([a-zA-Z][a-zA-Z0-9-]*)\b((?:\s+[^=\s>]+(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s*)>([\s\S]*)<\/\1>$/s;
12
- export function scanScriptTags(html, opts = {}) {
11
+ const TAG_ATTR_RUN = `(?:"[^"]*"|'[^']*'|[^>"'])*`, SINGLE_ELEMENT_RE = /^<([a-zA-Z][a-zA-Z0-9-]*)\b((?:\s+[^=\s>]+(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s*)>([\s\S]*)<\/\1>$/s, SCRIPT_SCAN_CACHE_MIN_BYTES = 65536, SCRIPT_SCAN_CACHE_MAX_ENTRIES = 4, scriptScanCache = new Map;
12
+ export function clearScriptScanCache() {
13
+ scriptScanCache.clear();
14
+ }
15
+ function scanScriptTagsUncached(html) {
13
16
  const out = [];
14
17
  for (const item of scanAtElementPosition(html, matchScriptElement)) {
15
18
  const opening = item.token.match(/^<script\b([^>]*)>/i), closing = item.token.match(/<\/script\s*>$/i);
16
19
  if (!opening || !closing)
17
20
  continue;
18
- const attrs = opening[1];
19
- if (opts.skipAttrs) {
20
- opts.skipAttrs.lastIndex = 0;
21
- if (opts.skipAttrs.test(attrs))
22
- continue;
23
- }
24
21
  const bodyStart = opening[0].length, bodyEnd = item.token.length - closing[0].length;
25
- out.push({
22
+ out.push(Object.freeze({
26
23
  fullMatch: item.token,
27
- attrs,
24
+ attrs: opening[1],
28
25
  body: item.token.slice(bodyStart, bodyEnd),
29
26
  start: item.start,
30
27
  end: item.end
31
- });
28
+ }));
29
+ }
30
+ return out;
31
+ }
32
+ export function scanScriptTags(html, opts = {}) {
33
+ const cacheable = html.length >= SCRIPT_SCAN_CACHE_MIN_BYTES;
34
+ let all = cacheable ? scriptScanCache.get(html) : void 0;
35
+ if (all === void 0) {
36
+ all = scanScriptTagsUncached(html);
37
+ if (cacheable) {
38
+ evictOldest(scriptScanCache, SCRIPT_SCAN_CACHE_MAX_ENTRIES);
39
+ scriptScanCache.set(html, all);
40
+ }
41
+ }
42
+ const skip = opts.skipAttrs;
43
+ if (!skip)
44
+ return all.slice();
45
+ const out = [];
46
+ for (const tag of all) {
47
+ skip.lastIndex = 0;
48
+ if (!skip.test(tag.attrs))
49
+ out.push(tag);
32
50
  }
33
51
  return out;
34
52
  }
@@ -324,11 +342,11 @@ const VOID_ELEMENT_TAGS = new Set([
324
342
  "source",
325
343
  "track",
326
344
  "wbr"
327
- ]);
345
+ ]), RAW_TEXT_OPEN_TAG = /<(script|style)\b/iy, SCRIPT_CLOSE_PREFIX = /<\/script/gi, STYLE_CLOSE_PREFIX = /<\/style/gi;
328
346
  function findElementEnd(output, startIdx, tag, startTagEnd) {
329
347
  if (VOID_ELEMENT_TAGS.has(tag.toLowerCase()))
330
348
  return startTagEnd;
331
- const lower = tag.toLowerCase(), lowerOut = output.toLowerCase(), len = output.length;
349
+ const lower = tag.toLowerCase(), len = output.length;
332
350
  let depth = 1, i = startTagEnd;
333
351
  while (i < len) {
334
352
  const lt = output.indexOf("<", i);
@@ -342,7 +360,8 @@ function findElementEnd(output, startIdx, tag, startTagEnd) {
342
360
  i = c + 3;
343
361
  continue;
344
362
  }
345
- const raw = /^<(script|style)\b/i.exec(output.slice(i, i + 8));
363
+ RAW_TEXT_OPEN_TAG.lastIndex = i;
364
+ const raw = RAW_TEXT_OPEN_TAG.exec(output);
346
365
  if (raw) {
347
366
  const startGt = output.indexOf(">", i);
348
367
  if (startGt === -1)
@@ -351,10 +370,12 @@ function findElementEnd(output, startIdx, tag, startTagEnd) {
351
370
  i = startGt + 1;
352
371
  continue;
353
372
  }
354
- const close = lowerOut.indexOf(`</${raw[1].toLowerCase()}`, i);
355
- if (close === -1)
373
+ const closeRe = raw[1].toLowerCase() === "script" ? SCRIPT_CLOSE_PREFIX : STYLE_CLOSE_PREFIX;
374
+ closeRe.lastIndex = i;
375
+ const close = closeRe.exec(output);
376
+ if (close === null)
356
377
  return -1;
357
- const gt = output.indexOf(">", close);
378
+ const gt = output.indexOf(">", close.index);
358
379
  if (gt === -1)
359
380
  return -1;
360
381
  i = gt + 1;
@@ -678,6 +699,67 @@ function dedupeTopLevelDeclarations(code) {
678
699
  }
679
700
  return out.join("");
680
701
  }
702
+ const SETUP_MARKER_SKIP_TAGS = new Set(["script", "style", "html", "head", "meta", "link", "title", "!doctype"]);
703
+ function overlapsSignalScript(start, end, ranges) {
704
+ for (const range of ranges) {
705
+ if (range.start >= end)
706
+ return !1;
707
+ if (range.end > start)
708
+ return !0;
709
+ }
710
+ return !1;
711
+ }
712
+ function hasTextOutsideSignalScripts(template, text, ranges) {
713
+ let from = 0;
714
+ while (from < template.length) {
715
+ const index = template.indexOf(text, from);
716
+ if (index === -1)
717
+ return !1;
718
+ if (!overlapsSignalScript(index, index + text.length, ranges))
719
+ return !0;
720
+ from = index + text.length;
721
+ }
722
+ return !1;
723
+ }
724
+ function findSetupMarkerInsertion(template, ranges) {
725
+ if (hasTextOutsideSignalScripts(template, "<body", ranges)) {
726
+ const bodyTagRe = new RegExp(`<body(${TAG_ATTR_RUN})>`, "g");
727
+ let match;
728
+ while ((match = bodyTagRe.exec(template)) !== null)
729
+ if (!overlapsSignalScript(match.index, match.index + match[0].length, ranges))
730
+ return match.index + match[0].length - 1;
731
+ return null;
732
+ }
733
+ const openingTagRe = new RegExp(`<([a-zA-Z][a-zA-Z0-9-]*)\\b(${TAG_ATTR_RUN})>`, "gi");
734
+ let match;
735
+ while ((match = openingTagRe.exec(template)) !== null) {
736
+ if (overlapsSignalScript(match.index, match.index + match[0].length, ranges))
737
+ continue;
738
+ if (SETUP_MARKER_SKIP_TAGS.has(match[1].toLowerCase()))
739
+ continue;
740
+ return match.index + match[0].length - 1;
741
+ }
742
+ return null;
743
+ }
744
+ function rebuildSetupOwner(template, ranges, markerAt, setupFnName) {
745
+ const chunks = [], marker = ` data-stx="${setupFnName}"`;
746
+ let cursor = 0, markerWritten = !1;
747
+ const appendThrough = (end) => {
748
+ if (markerAt !== null && !markerWritten && markerAt >= cursor && markerAt <= end) {
749
+ chunks.push(template.slice(cursor, markerAt), marker, template.slice(markerAt, end));
750
+ markerWritten = !0;
751
+ } else
752
+ chunks.push(template.slice(cursor, end));
753
+ };
754
+ for (const range of ranges) {
755
+ if (range.start < cursor)
756
+ continue;
757
+ appendThrough(range.start);
758
+ cursor = range.end;
759
+ }
760
+ appendThrough(template.length);
761
+ return chunks.join("");
762
+ }
681
763
  export async function processScriptSetup(template, filePath, serverData) {
682
764
  const scripts = scanScriptTags(template, {
683
765
  skipAttrs: /\bserver\b|\bsrc\s*=|\bdata-stx-scoped\b|\bdata-stx-router\b/
@@ -687,7 +769,7 @@ export async function processScriptSetup(template, filePath, serverData) {
687
769
  if (shouldTranspileTypeScript(s.attrs))
688
770
  content = transpileTypeScript(content);
689
771
  if (SIGNAL_API_RE.test(content)) {
690
- signalScripts.push({ fullMatch: s.fullMatch, attrs: s.attrs, content });
772
+ signalScripts.push({ content, start: s.start, end: s.end });
691
773
  continue;
692
774
  }
693
775
  if (!hasUserImports(content))
@@ -697,7 +779,7 @@ export async function processScriptSetup(template, filePath, serverData) {
697
779
  projectRoot: process.cwd()
698
780
  });
699
781
  if (SIGNAL_API_RE.test(bundled))
700
- signalScripts.push({ fullMatch: s.fullMatch, attrs: s.attrs, content, bundled });
782
+ signalScripts.push({ content, start: s.start, end: s.end, bundled });
701
783
  } catch {}
702
784
  }
703
785
  if (signalScripts.length === 0)
@@ -727,23 +809,8 @@ ${escapeScriptBody(`${bridge}${mergedContent}`)}
727
809
  }
728
810
  window.__stx_latestSetup=${setupFnName};
729
811
  if(window.stx)window.stx._latestSetup=${setupFnName};
730
- </script>`;
731
- let output = template;
732
- for (const s of signalScripts)
733
- output = output.split(s.fullMatch).join("");
734
- if (output.includes("<body"))
735
- output = output.replace(new RegExp(`<body(${TAG_ATTR_RUN})>`), `<body$1 data-stx="${setupFnName}">`);
736
- else {
737
- const skipTags = ["script", "style", "html", "head", "meta", "link", "title", "!doctype"];
738
- let marked = !1;
739
- output = output.replace(new RegExp(`<([a-zA-Z][a-zA-Z0-9-]*)\\b(${TAG_ATTR_RUN})>`, "gi"), (match, tag, attrs) => {
740
- if (marked || skipTags.includes(tag.toLowerCase()))
741
- return match;
742
- marked = !0;
743
- return `<${tag}${attrs} data-stx="${setupFnName}">`;
744
- });
745
- }
746
- return { output, setupCode };
812
+ </script>`, markerAt = findSetupMarkerInsertion(template, signalScripts);
813
+ return { output: rebuildSetupOwner(template, signalScripts, markerAt, setupFnName), setupCode };
747
814
  }
748
815
  export function extractExports(setupContent) {
749
816
  const code = setupContent, names = [], seen = new Set;
@@ -963,12 +1030,14 @@ ${setupCode}${output.slice(insertAt)}`;
963
1030
  output = `${output}
964
1031
  ${setupCode}`;
965
1032
  }
966
- const bodyMatch = output.replace(/<script\b[\s\S]*?<\/script>/gi, "").replace(/<style\b[\s\S]*?<\/style>/gi, "").match(/<body([^>]*)>/i), bodyHasDataStx = bodyMatch && /data-stx/.test(bodyMatch[1]);
967
- if (!setupCode && !bodyHasDataStx && bodyMatch && !/data-stx-auto/.test(bodyMatch[1])) {
968
- const bodyTagRe = /<body[^>]*>/i, bodyIdx = findMarkupIndexOutsideScripts(output, bodyTagRe);
969
- if (bodyIdx !== -1) {
970
- const before = output.slice(0, bodyIdx), after = output.slice(bodyIdx).replace(bodyTagRe, (m) => m.replace(/^<body([^>]*)>$/i, "<body$1 data-stx-auto>"));
971
- output = before + after;
1033
+ if (!setupCode) {
1034
+ const bodyMatch = output.replace(/<script\b[\s\S]*?<\/script>/gi, "").replace(/<style\b[\s\S]*?<\/style>/gi, "").match(/<body([^>]*)>/i);
1035
+ if (!(bodyMatch && /data-stx/.test(bodyMatch[1])) && bodyMatch && !/data-stx-auto/.test(bodyMatch[1])) {
1036
+ const bodyTagRe = /<body[^>]*>/i, bodyIdx = findMarkupIndexOutsideScripts(output, bodyTagRe);
1037
+ if (bodyIdx !== -1) {
1038
+ const before = output.slice(0, bodyIdx), after = output.slice(bodyIdx).replace(bodyTagRe, (m) => m.replace(/^<body([^>]*)>$/i, "<body$1 data-stx-auto>"));
1039
+ output = before + after;
1040
+ }
972
1041
  }
973
1042
  }
974
1043
  return output;
@@ -95,8 +95,11 @@ export function effect(fn, options = {}) {
95
95
  runEffect();
96
96
  return () => {
97
97
  isDisposed = !0;
98
- if (cleanup)
99
- cleanup();
98
+ if (cleanup) {
99
+ const pending = cleanup;
100
+ cleanup = void 0;
101
+ pending();
102
+ }
100
103
  };
101
104
  }
102
105
  export function batch(fn) {
package/dist/signals.js CHANGED
@@ -781,7 +781,16 @@ finally {
781
781
  if (options.immediate !== false) runEffect();
782
782
  const dispose = () => {
783
783
  isDisposed = true;
784
- if (cleanup) cleanup();
784
+ // Idempotent. A removed :for row is disposed on removal, and the page
785
+ // tracker that collected its effects on first render still holds the
786
+ // same disposer, which cleanupContainer calls on SPA navigation (#1954).
787
+ // Clearing cleanup before calling it stops that second call running it
788
+ // twice.
789
+ if (cleanup) {
790
+ const pending = cleanup;
791
+ cleanup = undefined;
792
+ pending();
793
+ }
785
794
  };
786
795
  // Auto-register with active tracker
787
796
  if (activeDisposers) activeDisposers.push(dispose);
@@ -3778,9 +3787,10 @@ else {
3778
3787
  const removeGroup = (group) => {
3779
3788
  const liveNodes = liveGroupNodes(group);
3780
3789
  const liveSet = new Set(liveNodes);
3781
- liveNodes.forEach(e => { disposeSubtreeScopes(e); e.remove(); });
3790
+ liveNodes.forEach(e => { disposeSubtreeEffects(e); disposeSubtreeScopes(e); e.remove(); });
3782
3791
  group.forEach(groupNode => {
3783
3792
  if (liveSet.has(groupNode)) return;
3793
+ disposeSubtreeEffects(groupNode);
3784
3794
  disposeSubtreeScopes(groupNode);
3785
3795
  groupNode.remove();
3786
3796
  });
@@ -3865,13 +3875,15 @@ catch (e) {
3865
3875
  if (emptyTemplate) {
3866
3876
  emptyElement = emptyTemplate.cloneNode(true);
3867
3877
  parent.insertBefore(emptyElement, placeholder);
3868
- processElement(emptyElement);
3878
+ const shownEmpty = emptyElement;
3879
+ shownEmpty.__stx_effect_disposers = trackEffects(function() { processElement(shownEmpty); });
3869
3880
  }
3870
3881
  };
3871
3882
 
3872
3883
  // Helper to hide empty state
3873
3884
  const hideEmpty = () => {
3874
3885
  if (emptyElement) {
3886
+ disposeSubtreeEffects(emptyElement);
3875
3887
  emptyElement.remove();
3876
3888
  emptyElement = null;
3877
3889
  }
@@ -4142,8 +4154,11 @@ catch (e) {
4142
4154
  if (el.nodeType === 1) {
4143
4155
  var itemScope = el.__stx_for_scope || passedScope;
4144
4156
  delete el.__stx_for_scope;
4157
+ // Tracked so removeGroup can dispose the row's effects (#1954). Kept
4158
+ // off __stx_disposers, which marks a hydrated component root here
4159
+ // and in the deferred :if pass.
4145
4160
  if (!el.__stx_disposers && el.tagName !== 'SCRIPT')
4146
- processElement(el, itemScope);
4161
+ el.__stx_effect_disposers = trackEffects(function() { processElement(el, itemScope); });
4147
4162
  el.removeAttribute('x-cloak');
4148
4163
  el.querySelectorAll('[x-cloak]').forEach(c => c.removeAttribute('x-cloak'));
4149
4164
  }
@@ -4166,12 +4181,14 @@ catch (e) {
4166
4181
  const liveNodes = liveGroupNodes(group);
4167
4182
  const transitioned = new Set();
4168
4183
  liveNodes.forEach((el) => {
4184
+ disposeSubtreeEffects(el);
4169
4185
  disposeSubtreeScopes(el);
4170
4186
  if (tgLeave(el, tgName)) transitioned.add(el);
4171
4187
  else el.remove();
4172
4188
  });
4173
4189
  group.forEach((el) => {
4174
4190
  if (transitioned.has(el) || liveNodes.includes(el)) return;
4191
+ disposeSubtreeEffects(el);
4175
4192
  disposeSubtreeScopes(el);
4176
4193
  el.remove();
4177
4194
  });
@@ -4361,7 +4378,16 @@ catch (e2) {
4361
4378
  // still handled by bindFor (item removal) and cleanupContainer (SPA nav).
4362
4379
  if (currentIdx !== -1) {
4363
4380
  chain[currentIdx].el.__stx_chain_active = false;
4364
- chain[currentIdx].nodes.forEach(function (n) { if (n.parentNode) n.parentNode.removeChild(n); });
4381
+ chain[currentIdx].nodes.forEach(function (n) {
4382
+ if (!n.parentNode) return;
4383
+ // Detached nodes are out of reach of a DOM walk, so a row removed
4384
+ // while this branch is hidden could not dispose the effects it was
4385
+ // processed with (#1954). Same registry the single-element :if uses.
4386
+ var host = n.parentNode;
4387
+ if (!host.__stx_detached_if) host.__stx_detached_if = new Set();
4388
+ host.__stx_detached_if.add(n);
4389
+ host.removeChild(n);
4390
+ });
4365
4391
  }
4366
4392
 
4367
4393
  // Insert + process the newly-picked branch.
@@ -4371,7 +4397,11 @@ catch (e2) {
4371
4397
  // Insert this branch's node(s) before the placeholder's next sibling.
4372
4398
  // The anchor is captured once so the nodes stack in source order.
4373
4399
  var anchor = pick.placeholder.nextSibling;
4374
- pick.nodes.forEach(function (n) { pick.placeholder.parentNode.insertBefore(n, anchor); });
4400
+ pick.nodes.forEach(function (n) {
4401
+ var host = pick.placeholder.parentNode;
4402
+ if (host.__stx_detached_if) host.__stx_detached_if.delete(n);
4403
+ host.insertBefore(n, anchor);
4404
+ });
4375
4405
  pick.el.__stx_shown_at = performance.now();
4376
4406
  if (!pick.childrenProcessed) {
4377
4407
  pick.childrenProcessed = true;
@@ -4381,6 +4411,10 @@ catch (e2) {
4381
4411
  // to process projected slot expressions without the loop caller
4382
4412
  // scope. peek() keeps this synchronous pass from subscribing child
4383
4413
  // reads to the current chain effect.
4414
+ // Tracked on the branch element: this runs inside the chain effect,
4415
+ // where no tracker is active, so without a handle the effects of a
4416
+ // branch picked after render survive their row's removal (#1954).
4417
+ pick.el.__stx_chain_disposers = trackEffects(function () {
4384
4418
  peek(function () {
4385
4419
  var childScope = { ...globalHelpers, ...capturedComponentScope, ...(pick.capturedElementScope || {}) };
4386
4420
  // Components compiled inside any branch of an if/else-if/else
@@ -4407,6 +4441,7 @@ catch (e2) {
4407
4441
  n.querySelectorAll('[x-cloak]').forEach(function (c) { c.removeAttribute('x-cloak'); });
4408
4442
  });
4409
4443
  });
4444
+ });
4410
4445
  }
4411
4446
  }
4412
4447
 
@@ -4429,6 +4464,14 @@ catch (e2) {
4429
4464
  }
4430
4465
 
4431
4466
  const placeholder = document.createComment('stx-if');
4467
+ // Marks where this branch's rendered content ENDS (stacksjs/stx#1955).
4468
+ // Hiding used to remove only the cloned nodes, but a structural directive
4469
+ // directly inside the template renders its own output as siblings that are
4470
+ // not among those clones -- a <template :for> at the top level of a
4471
+ // <template :if> left every row on screen after the branch went false.
4472
+ // Only the template branch needs it; the single-element branch owns exactly
4473
+ // the node it was bound to.
4474
+ let endMarker = null;
4432
4475
  let isInserted = true;
4433
4476
 
4434
4477
  // Handle <template> elements specially - clone their content
@@ -4455,6 +4498,13 @@ catch (e2) {
4455
4498
  // multi-root template branch.
4456
4499
  const initialAnchor = placeholder.nextSibling;
4457
4500
  currentNodes.forEach(node => parent.insertBefore(node, initialAnchor));
4501
+ // The end of this branch's range, bound at the same time as the content
4502
+ // it closes (#1955). Needed here too, not only on re-show: the first
4503
+ // hide of a branch that was never toggled removes THIS content, and a
4504
+ // nested :for renders rows that are siblings of these clones rather than
4505
+ // among them.
4506
+ endMarker = document.createComment('stx-if-end');
4507
+ parent.insertBefore(endMarker, initialAnchor);
4458
4508
  el.remove(); // Remove the template element itself
4459
4509
  }
4460
4510
 
@@ -4520,7 +4570,7 @@ catch (e2) {
4520
4570
  hydrateComponentScopes(nodes, childScope);
4521
4571
  nodes.forEach(node => {
4522
4572
  if (!node.__stx_disposers && node.tagName !== 'SCRIPT')
4523
- processElement(node, childScope);
4573
+ node.__stx_effect_disposers = trackEffects(function() { processElement(node, childScope); });
4524
4574
  if (node.nodeType === 1) {
4525
4575
  node.removeAttribute('x-cloak');
4526
4576
  node.querySelectorAll('[x-cloak]').forEach(c => c.removeAttribute('x-cloak'));
@@ -4548,6 +4598,10 @@ catch (e2) {
4548
4598
  currentNodes = Array.from(el.content.childNodes).map(n => n.cloneNode(true));
4549
4599
  const insertionAnchor = placeholder.nextSibling;
4550
4600
  currentNodes.forEach(node => parent.insertBefore(node, insertionAnchor));
4601
+ // Bound AFTER the clones, so hiding can remove whatever a nested
4602
+ // structural directive rendered as their sibling (#1955).
4603
+ if (!endMarker) endMarker = document.createComment('stx-if-end');
4604
+ parent.insertBefore(endMarker, insertionAnchor);
4551
4605
  processTemplateNodes(currentNodes);
4552
4606
  childrenProcessed = true;
4553
4607
  // Stamp insertion time for click propagation guard
@@ -4557,8 +4611,28 @@ catch (e2) {
4557
4611
  else if (!value && isInserted) {
4558
4612
  // Remove all current nodes. Do NOT disposeSubtreeScopes \u2014 :if is a
4559
4613
  // toggle, not a permanent unmount; see the single-element branch
4560
- // below and #1737.
4561
- currentNodes.forEach(node => node.remove());
4614
+ // below and #1737. Effects are disposed, though: these clones are never
4615
+ // reused, and a re-show clones afresh, so leaving them bound only
4616
+ // accumulates work (#1954).
4617
+ //
4618
+ // Everything between the placeholder and the end marker goes, not
4619
+ // just the clones: a nested :for or :if renders siblings of its own
4620
+ // that no clone list contains (#1955).
4621
+ // Only walk the range when THIS binding inserted the content and
4622
+ // left its marker. Without that guard the walk ran to the end of the
4623
+ // parent and took a sibling <template :if> with it -- the initial
4624
+ // server-rendered state has no marker to stop at.
4625
+ if (endMarker && endMarker.parentNode === parent) {
4626
+ var doomed = placeholder.nextSibling;
4627
+ while (doomed && doomed !== endMarker) {
4628
+ var nextDoomed = doomed.nextSibling;
4629
+ disposeSubtreeEffects(doomed);
4630
+ doomed.remove();
4631
+ doomed = nextDoomed;
4632
+ }
4633
+ endMarker.remove();
4634
+ }
4635
+ currentNodes.forEach(node => { disposeSubtreeEffects(node); node.remove(); });
4562
4636
  currentNodes = [];
4563
4637
  isInserted = false;
4564
4638
  childrenProcessed = false;
@@ -4580,6 +4654,7 @@ else {
4580
4654
  console.log('[stx] bindIf INSERTING element for :if=' + expr);
4581
4655
  const insertionAnchor = placeholder.nextSibling;
4582
4656
  currentNodes.forEach(node => parent.insertBefore(node, insertionAnchor));
4657
+ if (parent && parent.__stx_detached_if) currentNodes.forEach(node => parent.__stx_detached_if.delete(node));
4583
4658
  el.__stx_shown_at = performance.now();
4584
4659
  isInserted = true;
4585
4660
  }
@@ -4595,6 +4670,13 @@ else if (!value && isInserted) {
4595
4670
  // and cleanupContainer (SPA navigation). The double-bind guards make
4596
4671
  // re-show idempotent, so toggling doesn't leak.
4597
4672
  currentNodes.forEach(node => node.remove());
4673
+ // Detached nodes are out of reach of a DOM walk, so an ancestor row or
4674
+ // branch removed while this is hidden could not dispose their effects
4675
+ // (#1954). Record them on the parent that keeps the placeholder.
4676
+ if (parent) {
4677
+ if (!parent.__stx_detached_if) parent.__stx_detached_if = new Set();
4678
+ currentNodes.forEach(node => parent.__stx_detached_if.add(node));
4679
+ }
4598
4680
  isInserted = false;
4599
4681
  console.log('[stx] bindIf REMOVED, el.isConnected:', el.isConnected);
4600
4682
  }
@@ -4613,6 +4695,14 @@ else if (!value && isInserted) {
4613
4695
  // in a :if binds a macrotask after the synchronous stx:load audit (#1773).
4614
4696
  el.__stx_if_pending = true;
4615
4697
  setTimeout(function() {
4698
+ // Removed with its row, or hidden again, before this ran. Hydrating
4699
+ // a detached element now creates effects nothing will dispose
4700
+ // (#1954). Leave it unprocessed so the next show schedules the pass.
4701
+ if (!el.isConnected) {
4702
+ childrenProcessed = false;
4703
+ el.__stx_if_pending = false;
4704
+ return;
4705
+ }
4616
4706
  var childScope = { ...globalHelpers, ...capturedComponentScope, ...(capturedElementScope || {}) };
4617
4707
  // A false single-element conditional is detached before the
4618
4708
  // DOMContentLoaded component-scope pass. When it becomes visible,
@@ -4621,8 +4711,11 @@ else if (!value && isInserted) {
4621
4711
  // the same lifecycle as components inserted by template :if.
4622
4712
  var wasTrackedBeforeConditionalHydration = !!el.__stx_disposers;
4623
4713
  hydrateComponentScopes(currentNodes, childScope);
4714
+ // Tracked on its own property so an ancestor row or branch removal
4715
+ // reaches these effects too (#1954). This runs after the enclosing
4716
+ // tracker has closed, so nothing else would collect them.
4624
4717
  if (wasTrackedBeforeConditionalHydration || !el.__stx_disposers)
4625
- processElement(el, childScope);
4718
+ el.__stx_if_disposers = trackEffects(function() { processElement(el, childScope); });
4626
4719
  // Remove x-cloak from the inserted subtree \u2014 the initial
4627
4720
  // cloak removal (after processElement on the root) already
4628
4721
  // ran before this deferred processing, so newly-inserted
@@ -7554,6 +7647,51 @@ catch (e) {
7554
7647
  // indefinitely. Now bindIf, bindFor, and cleanupContainer all funnel
7555
7648
  // through this helper so the cleanup is symmetric regardless of who
7556
7649
  // initiated the removal.
7650
+ // Dispose the EFFECTS bound inside a subtree leaving the page for good: a
7651
+ // removed :for row, a hidden template :if clone, a hidden :for empty
7652
+ // placeholder, or a container on SPA navigation (#1954).
7653
+ // disposeSubtreeScopes only releases scope registrations. Without this, the
7654
+ // effects that bound the subtree stay subscribed to every signal they read
7655
+ // and keep running, so work per update grows with every removal.
7656
+ // Descendants first, then the root, the order cleanupContainer always used.
7657
+ function disposeSubtreeEffects(root) {
7658
+ if (!root) return;
7659
+ var nodes = [];
7660
+ if (root.querySelectorAll) {
7661
+ var all = root.querySelectorAll('*');
7662
+ for (var i = 0; i < all.length; i++) nodes.push(all[i]);
7663
+ }
7664
+ nodes.push(root);
7665
+ var owned = ['__stx_disposers', '__stx_effect_disposers', '__stx_if_disposers', '__stx_chain_disposers'];
7666
+ for (var n = 0; n < nodes.length; n++) {
7667
+ var el = nodes[n];
7668
+ if (typeof el.__stx_hydration_cancel === 'function') {
7669
+ try { el.__stx_hydration_cancel(); } catch (e) { /* noop */ }
7670
+ el.__stx_hydration_cancel = null;
7671
+ }
7672
+ if (Array.isArray(el.__stx_destroy)) {
7673
+ var hooks = el.__stx_destroy;
7674
+ el.__stx_destroy = null;
7675
+ hooks.forEach(function(fn) {
7676
+ try { fn(); }
7677
+ catch (e) { console.warn('[stx] destroy hook error:', e); }
7678
+ });
7679
+ }
7680
+ if (el.__stx_detached_if) {
7681
+ var detached = el.__stx_detached_if;
7682
+ el.__stx_detached_if = null;
7683
+ detached.forEach(function(node) { disposeSubtreeEffects(node); });
7684
+ }
7685
+ for (var k = 0; k < owned.length; k++) {
7686
+ var disposeOwned = el[owned[k]];
7687
+ if (typeof disposeOwned === 'function') {
7688
+ el[owned[k]] = null;
7689
+ disposeOwned();
7690
+ }
7691
+ }
7692
+ }
7693
+ }
7694
+
7557
7695
  function disposeSubtreeScopes(root) {
7558
7696
  if (!root || !window.stx || !window.stx._scopes) return;
7559
7697
  // Build the list of nodes to inspect: root + descendants with the
@@ -7842,43 +7980,11 @@ catch (e) {
7842
7980
  if (el.__stx_scope) Object.assign(componentScope, el.__stx_scope);
7843
7981
  });
7844
7982
 
7845
- // 1. Walk all child elements \u2014 fire destroy hooks and dispose effects
7846
- container.querySelectorAll('*').forEach(function(el) {
7847
- // Cancel a still-pending island hydration trigger (#1746) so its
7848
- // observer/timer/listener doesn't fire on this detached element.
7849
- if (typeof el.__stx_hydration_cancel === 'function') {
7850
- try { el.__stx_hydration_cancel(); } catch (e) { /* noop */ }
7851
- el.__stx_hydration_cancel = null;
7852
- }
7853
- if (el.__stx_destroy && Array.isArray(el.__stx_destroy)) {
7854
- el.__stx_destroy.forEach(function(fn) {
7855
- try { fn(); }
7856
- catch (e) { console.warn('[stx] destroy hook error:', e); }
7857
- });
7858
- el.__stx_destroy = null;
7859
- }
7860
- if (el.__stx_disposers && typeof el.__stx_disposers === 'function') {
7861
- el.__stx_disposers();
7862
- el.__stx_disposers = null;
7863
- }
7864
- });
7865
-
7866
- // 2. Check container itself
7867
- if (typeof container.__stx_hydration_cancel === 'function') {
7868
- try { container.__stx_hydration_cancel(); } catch (e) { /* noop */ }
7869
- container.__stx_hydration_cancel = null;
7870
- }
7871
- if (container.__stx_destroy) {
7872
- container.__stx_destroy.forEach(function(fn) {
7873
- try { fn(); }
7874
- catch (e) { console.warn('[stx] destroy hook error:', e); }
7875
- });
7876
- container.__stx_destroy = null;
7877
- }
7878
- if (container.__stx_disposers) {
7879
- container.__stx_disposers();
7880
- container.__stx_disposers = null;
7881
- }
7983
+ // 1-2. Every descendant, then the container: cancel pending island
7984
+ // hydration (#1746), fire destroy hooks, dispose effects. Shared with
7985
+ // :for row removal and template :if hide so all three release the same
7986
+ // trackers, including the row and branch ones added for #1954.
7987
+ disposeSubtreeEffects(container);
7882
7988
  // Clear __stx_scope so _handleStxLoad's processElement guard doesn't skip it
7883
7989
  container.__stx_scope = null;
7884
7990
 
package/dist/ssg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Dk as Fq,yk as Uq,zk as Iq}from"./chunk-zn5jgmqw.js";import{Ek as Eq,Fk as Tq,Gk as Dq}from"./chunk-58f0mthg.js";import{$k as _q,cl as zq,dl as Aq}from"./chunk-9aw94jhm.js";import{Fm as Oq,Fp as P,So as Bq,_n as l,bo as Hq,cr as n}from"./chunk-9rkntp0z.js";import"./chunk-q68xmak4.js";import"./chunk-c0an64km.js";import"./chunk-t1k5dpbr.js";import"./chunk-52mh63sp.js";import{rt as Xq}from"./chunk-zcmtqan3.js";import{wt as d}from"./chunk-39f40yc4.js";import"./chunk-ysnk7x79.js";import"./chunk-0f1kz0x2.js";import"./chunk-ayrjwkyw.js";import"./chunk-c6fw33zh.js";import{Ku as Yq,Lu as Vq,Mu as jq,Nu as Gq,Ou as Lq,Pu as Nq}from"./chunk-bf8wf3r2.js";import"./chunk-jn6m8zf7.js";import{dv as y}from"./chunk-sskbegsz.js";import O from"fs";import j from"path";import{createHash as xq}from"crypto";function yq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var Pq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function Cq(q){return Bun.hash(q).toString(16)}function Qq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(Pq,(J,W,z,A)=>{let G=A.trim();if(!G)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)G=yq(G);let X=Cq(G);if(!$.has(X))$.set(X,G);let B=Z.integrity?` data-stx-integrity="sha384-${xq("sha384").update(G).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${B}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var gq=new Set(["visible","idle"]);function Zq(q){if(!q.includes("data-stx-src="))return q;let Z=new Map,$=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,Q;while((Q=$.exec(q))!==null)Z.set(Q[1],Q[2]);let K=new Set,J=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,W;while((W=J.exec(q))!==null)if(gq.has(Z.get(W[1])||""))K.add(W[2]);let z=q.lastIndexOf("</head>");if(K.size===0||z===-1)return q;let A=Array.from(K).filter((G)=>!q.includes(`rel="prefetch" href="${G}"`)).map((G)=>`<link rel="prefetch" href="${G}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var fq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function h(q){let Z=q.trim();if(!Z)return null;let $=/^https?:\/\//i.test(Z)?Z:`https://${Z}`;try{return new URL($).origin+new URL($).pathname.replace(/\/$/,"")}catch{return null}}function mq(q){for(let Z of fq){let $=q[Z];if(!$)continue;let Q=h($);if(Q)return{url:Q,source:"env",via:Z}}return null}function $q(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?h($):null}async function dq(q){let{existsSync:Z}=await import("fs"),$=await import("path");for(let Q of["site.config.ts","site.config.js",".config/site.config.ts"]){let K=$.resolve(q,Q);if(!Z(K))continue;try{let J=await import(K),W=$q(J.default??J);if(W)return W}catch{}}return null}async function Kq(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=h(q.explicit);if(W)return{url:W,source:"option"}}let Q=$q(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await dq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=mq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Wq(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
2
+ import{Dk as Fq,yk as Uq,zk as Iq}from"./chunk-71t0yan0.js";import{Ek as Eq,Fk as Tq,Gk as Dq}from"./chunk-58f0mthg.js";import{$k as _q,cl as zq,dl as Aq}from"./chunk-4ww3znrr.js";import{Fm as Oq,Gp as P,To as Bq,_n as l,bo as Hq,dr as n}from"./chunk-y11cxbxd.js";import"./chunk-92mj1t26.js";import"./chunk-8mjdpr94.js";import"./chunk-pkaabd8h.js";import"./chunk-xpp135ad.js";import{tt as Xq}from"./chunk-wrzwgkbx.js";import{yt as d}from"./chunk-5kk8gsj2.js";import"./chunk-38ejahd9.js";import"./chunk-ypmqf7tm.js";import"./chunk-de7fye10.js";import"./chunk-v5e1gxwm.js";import{Nu as Yq,Ou as Vq,Pu as jq,Qu as Gq,Ru as Lq,Su as Nq}from"./chunk-b6ej2fdf.js";import"./chunk-x650vjcp.js";import{gv as y}from"./chunk-qc1f74ek.js";import O from"fs";import j from"path";import{createHash as xq}from"crypto";function yq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var Pq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function Cq(q){return Bun.hash(q).toString(16)}function Qq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(Pq,(J,W,z,A)=>{let G=A.trim();if(!G)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)G=yq(G);let X=Cq(G);if(!$.has(X))$.set(X,G);let B=Z.integrity?` data-stx-integrity="sha384-${xq("sha384").update(G).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${B}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var gq=new Set(["visible","idle"]);function Zq(q){if(!q.includes("data-stx-src="))return q;let Z=new Map,$=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,Q;while((Q=$.exec(q))!==null)Z.set(Q[1],Q[2]);let K=new Set,J=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,W;while((W=J.exec(q))!==null)if(gq.has(Z.get(W[1])||""))K.add(W[2]);let z=q.lastIndexOf("</head>");if(K.size===0||z===-1)return q;let A=Array.from(K).filter((G)=>!q.includes(`rel="prefetch" href="${G}"`)).map((G)=>`<link rel="prefetch" href="${G}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var fq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function h(q){let Z=q.trim();if(!Z)return null;let $=/^https?:\/\//i.test(Z)?Z:`https://${Z}`;try{return new URL($).origin+new URL($).pathname.replace(/\/$/,"")}catch{return null}}function mq(q){for(let Z of fq){let $=q[Z];if(!$)continue;let Q=h($);if(Q)return{url:Q,source:"env",via:Z}}return null}function $q(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?h($):null}async function dq(q){let{existsSync:Z}=await import("fs"),$=await import("path");for(let Q of["site.config.ts","site.config.js",".config/site.config.ts"]){let K=$.resolve(q,Q);if(!Z(K))continue;try{let J=await import(K),W=$q(J.default??J);if(W)return W}catch{}}return null}async function Kq(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=h(q.explicit);if(W)return{url:W,source:"option"}}let Q=$q(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await dq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=mq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Wq(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
3
  `)}class wq{cacheDir;cache=new Map;loaded=!1;salt;constructor(q,Z=""){this.cacheDir=q,this.salt=Z}async load(){if(this.loaded)return;let q=j.join(this.cacheDir,"build-cache.json");if(await Bun.file(q).exists())try{let Z=JSON.parse(await Bun.file(q).text());for(let[$,Q]of Object.entries(Z))this.cache.set($,Q)}catch{}this.loaded=!0}async save(){await O.promises.mkdir(this.cacheDir,{recursive:!0});let q=j.join(this.cacheDir,"build-cache.json"),Z={};for(let[$,Q]of this.cache)Z[$]=Q;await Bun.write(q,JSON.stringify(Z))}getHash(q,Z){let $=O.statSync(q),Q=`${this.salt}|${q}:${$.mtimeMs}`;for(let J of Z)if(O.existsSync(J)){let W=O.statSync(J);Q+=`:${J}:${W.mtimeMs}`}let K=0;for(let J=0;J<Q.length;J++){let W=Q.charCodeAt(J);K=(K<<5)-K+W,K=K&K}return Math.abs(K).toString(36)}get(q,Z){let $=this.cache.get(q);if(!$)return null;let Q=this.getHash(Z,$.dependencies??[]);if($.hash!==Q)return this.cache.delete(q),null;return $.html}set(q,Z,$,Q){let K=this.getHash(Z,$);this.cache.set(q,{hash:K,html:Q,generatedAt:Date.now(),dependencies:$})}}class Rq{cacheDir;constructor(q){this.cacheDir=q}getFilePath(q){let Z=q.replace(/[^a-zA-Z0-9]/g,"_")+".json";return j.join(this.cacheDir,"isr",Z)}async get(q){let Z=this.getFilePath(q);if(!await Bun.file(Z).exists())return null;try{return JSON.parse(await Bun.file(Z).text())}catch{return null}}async set(q,Z){let $=this.getFilePath(q);await O.promises.mkdir(j.dirname($),{recursive:!0}),await Bun.write($,JSON.stringify(Z))}async invalidate(q){let Z=this.getFilePath(q);if(await Bun.file(Z).exists())await O.promises.unlink(Z)}async invalidatePattern(q){let Z=j.join(this.cacheDir,"isr");if(!O.existsSync(Z))return;let $=await O.promises.readdir(Z);for(let Q of $){let K=Q.replace(/_/g,"/").replace(".json","");if(q.test(K))await O.promises.unlink(j.join(Z,Q))}}async needsRevalidation(q){let Z=await this.get(q);if(!Z)return!0;return Date.now()>Z.revalidateAfter}}async function pq(q){try{let $=(await Bun.file(q).text()).match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!$)return null;let Q=$[1];if(!Q.includes("getStaticPaths"))return null;let K=Q.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticPaths\s*\([^)]*\)\s*\{([\s\S]*?)\n[\t ]*\}/);if(!K)return null;return await Function(`
4
4
  return (async function getStaticPaths() {
5
5
  ${K[1]}
@@ -41,7 +41,7 @@ ${q.map((Q)=>{let K=new URL(Q.loc,Z).href,J=` <url>
41
41
  ${$.join(`
42
42
  `)}
43
43
  </channel>
44
- </rss>`}async function aq(q={}){let Z=Date.now();Aq();let $=await n(process.cwd()),Q=$.build||{},K=await Kq({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Wq());let J={router:q.router??$?.router??{},pagesDir:q.pagesDir||Q.pagesDir||"pages",outputDir:q.outputDir||Q.outputDir||"dist",baseUrl:q.baseUrl||Q.baseUrl||"/",domain:K.url,revalidate:q.revalidate??Q.revalidate??!1,sitemap:q.sitemap??Q.sitemap??!0,sitemapExclude:q.sitemapExclude||Q.sitemapExclude||[],robots:q.robots??Q.robots??!0,rss:q.rss??Q.rss??!1,concurrency:q.concurrency||Q.concurrency||10,cache:q.cache??Q.cache??!0,cacheDir:q.cacheDir||Q.cacheDir||d(process.cwd(),"ssg-cache"),contentLoaders:q.contentLoaders||[],hooks:q.hooks||{},minify:q.minify??Q.minify??!0,generate404:q.generate404??Q.generate404??!0,publicDir:q.publicDir||Q.publicDir||"public",trailingSlash:q.trailingSlash??Q.trailingSlash??!1,cleanOutput:q.cleanOutput??Q.cleanOutput??!0,cacheSalt:q.cacheSalt??"",partialsDir:q.partialsDir||$?.partialsDir||"",componentsDir:q.componentsDir||$?.componentsDir||"",failOnIncludeError:q.failOnIncludeError??!0,chunkIslands:q.chunkIslands===!0,prefetchIslands:q.prefetchIslands===!0,integrityIslands:q.integrityIslands===!0},W={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},z=new Set,A=0,G={},X={};await J.hooks.onBuildStart?.();try{if(J.cleanOutput&&O.existsSync(J.outputDir))await O.promises.rm(J.outputDir,{recursive:!0});await O.promises.mkdir(J.outputDir,{recursive:!0});let L=J.cacheSalt;if(!L){let{resolveUserCssConfig:Y,fingerprintConfig:N}=await import("./chunk-n3qyd366.js");try{L=N(await Y(process.cwd()))}catch{}}let{prepareImageDelivery:_}=await import("./chunk-ytgnzeeb.js"),F=await _(J.publicDir,J.outputDir);if(F.count>0)console.log(`Optimized ${F.count} image(s) for responsive delivery`),L=[L,F.fingerprint].filter(Boolean).join(":");let C=new wq(J.cacheDir,L);if(J.cache)await C.load();try{let{generateCss:Y}=await import("./chunk-n3qyd366.js");await Y('<div class="bg-black"></div>')}catch{}Yq();let kq=$?.routeMiddleware?.dir||"middleware";await jq(process.cwd(),kq);let p=Vq();if(p.length>0)console.log(`Loaded ${p.length} middleware: ${p.join(", ")}`);let bq=$?.routeMiddleware?.global||[];Fq($?.layoutsDir,d(process.cwd()));let i=l(".",{pagesDir:J.pagesDir});console.log(`Found ${i.length} routes`);let g=[];for(let Y of i){let N=await uq(Y);for(let H of N)g.push({route:Y,url:H.url,params:H.params,props:H.props,revalidate:H.revalidate??J.revalidate})}W.totalPages=g.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],s=[];for(let Y=0;Y<g.length;Y+=J.concurrency)s.push(g.slice(Y,Y+J.concurrency));for(let Y of s)await Promise.all(Y.map(async(N)=>{let{route:H,url:V,params:S,props:Sq,revalidate:a}=N;try{await J.hooks.onPageStart?.(V);let w=await Bun.file(H.filePath).text(),R=JJ(w),vq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],t=[...bq,...vq];if(t.length>0){let D=Gq(V,S,R||{}),M=Lq(D,null,void 0,{isServer:!0}),E=await Nq(t,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,x=QJ(String(U),V),k=ZJ(V,J);await O.promises.mkdir(j.dirname(k),{recursive:!0}),await Bun.write(k,x),W.successCount++,W.pages.push({route:V,outputPath:k,size:Buffer.byteLength(x),cached:!1}),b.push({loc:V,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${V} \u2192 redirect to ${U}`);return}if(E.abort){let U=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${V} \u2014 middleware aborted: ${U}`);return}}let e=w.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(e)try{if(!await Function("route",`
44
+ </rss>`}async function aq(q={}){let Z=Date.now();Aq();let $=await n(process.cwd()),Q=$.build||{},K=await Kq({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Wq());let J={router:q.router??$?.router??{},pagesDir:q.pagesDir||Q.pagesDir||"pages",outputDir:q.outputDir||Q.outputDir||"dist",baseUrl:q.baseUrl||Q.baseUrl||"/",domain:K.url,revalidate:q.revalidate??Q.revalidate??!1,sitemap:q.sitemap??Q.sitemap??!0,sitemapExclude:q.sitemapExclude||Q.sitemapExclude||[],robots:q.robots??Q.robots??!0,rss:q.rss??Q.rss??!1,concurrency:q.concurrency||Q.concurrency||10,cache:q.cache??Q.cache??!0,cacheDir:q.cacheDir||Q.cacheDir||d(process.cwd(),"ssg-cache"),contentLoaders:q.contentLoaders||[],hooks:q.hooks||{},minify:q.minify??Q.minify??!0,generate404:q.generate404??Q.generate404??!0,publicDir:q.publicDir||Q.publicDir||"public",trailingSlash:q.trailingSlash??Q.trailingSlash??!1,cleanOutput:q.cleanOutput??Q.cleanOutput??!0,cacheSalt:q.cacheSalt??"",partialsDir:q.partialsDir||$?.partialsDir||"",componentsDir:q.componentsDir||$?.componentsDir||"",failOnIncludeError:q.failOnIncludeError??!0,chunkIslands:q.chunkIslands===!0,prefetchIslands:q.prefetchIslands===!0,integrityIslands:q.integrityIslands===!0},W={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},z=new Set,A=0,G={},X={};await J.hooks.onBuildStart?.();try{if(J.cleanOutput&&O.existsSync(J.outputDir))await O.promises.rm(J.outputDir,{recursive:!0});await O.promises.mkdir(J.outputDir,{recursive:!0});let L=J.cacheSalt;if(!L){let{resolveUserCssConfig:Y,fingerprintConfig:N}=await import("./chunk-2tk1zkrz.js");try{L=N(await Y(process.cwd()))}catch{}}let{prepareImageDelivery:_}=await import("./chunk-mxfh1nxg.js"),F=await _(J.publicDir,J.outputDir);if(F.count>0)console.log(`Optimized ${F.count} image(s) for responsive delivery`),L=[L,F.fingerprint].filter(Boolean).join(":");let C=new wq(J.cacheDir,L);if(J.cache)await C.load();try{let{generateCss:Y}=await import("./chunk-2tk1zkrz.js");await Y('<div class="bg-black"></div>')}catch{}Yq();let kq=$?.routeMiddleware?.dir||"middleware";await jq(process.cwd(),kq);let p=Vq();if(p.length>0)console.log(`Loaded ${p.length} middleware: ${p.join(", ")}`);let bq=$?.routeMiddleware?.global||[];Fq($?.layoutsDir,d(process.cwd()));let i=l(".",{pagesDir:J.pagesDir});console.log(`Found ${i.length} routes`);let g=[];for(let Y of i){let N=await uq(Y);for(let H of N)g.push({route:Y,url:H.url,params:H.params,props:H.props,revalidate:H.revalidate??J.revalidate})}W.totalPages=g.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],s=[];for(let Y=0;Y<g.length;Y+=J.concurrency)s.push(g.slice(Y,Y+J.concurrency));for(let Y of s)await Promise.all(Y.map(async(N)=>{let{route:H,url:V,params:S,props:Sq,revalidate:a}=N;try{await J.hooks.onPageStart?.(V);let w=await Bun.file(H.filePath).text(),R=JJ(w),vq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],t=[...bq,...vq];if(t.length>0){let D=Gq(V,S,R||{}),M=Lq(D,null,void 0,{isServer:!0}),E=await Nq(t,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,x=QJ(String(U),V),k=ZJ(V,J);await O.promises.mkdir(j.dirname(k),{recursive:!0}),await Bun.write(k,x),W.successCount++,W.pages.push({route:V,outputPath:k,size:Buffer.byteLength(x),cached:!1}),b.push({loc:V,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${V} \u2192 redirect to ${U}`);return}if(E.abort){let U=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${V} \u2014 middleware aborted: ${U}`);return}}let e=w.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(e)try{if(!await Function("route",`
45
45
  const validate = ${e[1]};
46
46
  return validate(route);
47
47
  `)({params:S})){console.warn(`Validation failed for ${V}, skipping...`);return}}catch{}let I=null,qq=!1;if(J.cache){if(I=C.get(V,H.filePath),I)qq=!0,W.cachedCount++}if(!I){let D=await Mq(H,S,Sq,J,$);if(I=D.html,J.failOnIncludeError&&D.includeFailures.length>0)throw Error(`${D.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be: