@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
@@ -1,4 +1,5 @@
1
1
  import { errorLogger } from "./error-handling.js";
2
+ import { mightContainOwnTextMustache } from "./html-masking.js";
2
3
  import { createSafeFunction, isExpressionSafe } from "./safe-evaluator.js";
3
4
  export function processJsonDirective(template, context) {
4
5
  let result = template;
@@ -153,7 +154,13 @@ const VOID_TAGS = new Set([
153
154
  "source",
154
155
  "track",
155
156
  "wbr"
156
- ]), NO_CLOAK_RE = /(?:^|\s)x-no-cloak(?:=|\s|\/|>|$)/;
157
+ ]), NO_CLOAK_RE = /(?:^|\s)x-no-cloak(?:=|\s|\/|>|$)/, TAG_NAME_AT = /<\/?\s*([a-z][\w-]*)/iy, WHITESPACE = /\s/;
158
+ function isSelfClosingBefore(html, tagEnd) {
159
+ let j = tagEnd - 1;
160
+ while (j >= 0 && WHITESPACE.test(html[j]))
161
+ j--;
162
+ return j >= 0 && html[j] === "/";
163
+ }
157
164
  function findTagEnd(html, from) {
158
165
  let inSingleQuote = !1, inDoubleQuote = !1;
159
166
  for (let i = from;i < html.length; i++) {
@@ -173,14 +180,40 @@ function findTagEnd(html, from) {
173
180
  }
174
181
  return -1;
175
182
  }
176
- function ownText(html, contentStart) {
177
- let depth = 0, text = "", i = contentStart;
183
+ function ownTextContainsMustache(html, contentStart) {
184
+ if (html.indexOf("{", contentStart) === -1 || html.indexOf("}", contentStart) === -1)
185
+ return !1;
186
+ let depth = 0, i = contentStart, openingBrace = !1, opened = !1, closingBrace = !1;
178
187
  while (i < html.length) {
179
- const ch = html[i];
180
- if (ch !== "<") {
188
+ const nextTag = html.indexOf("<", i), textEnd = nextTag === -1 ? html.length : nextTag;
189
+ if (textEnd > i) {
181
190
  if (depth === 0)
182
- text += ch;
183
- i++;
191
+ while (i < textEnd) {
192
+ const brace = html.indexOf(opened ? "}" : "{", i);
193
+ if (brace === -1 || brace >= textEnd) {
194
+ if (opened)
195
+ closingBrace = !1;
196
+ else
197
+ openingBrace = !1;
198
+ break;
199
+ }
200
+ if (brace > i)
201
+ if (opened)
202
+ closingBrace = !1;
203
+ else
204
+ openingBrace = !1;
205
+ if (opened) {
206
+ if (closingBrace)
207
+ return !0;
208
+ closingBrace = !0;
209
+ } else if (openingBrace) {
210
+ opened = !0;
211
+ closingBrace = !1;
212
+ } else
213
+ openingBrace = !0;
214
+ i = brace + 1;
215
+ }
216
+ i = textEnd;
184
217
  continue;
185
218
  }
186
219
  if (html.startsWith("<!--", i)) {
@@ -191,18 +224,21 @@ function ownText(html, contentStart) {
191
224
  const tagEnd = findTagEnd(html, i);
192
225
  if (tagEnd === -1)
193
226
  break;
194
- const tag = html.slice(i, tagEnd + 1), name = /^<\/?\s*([a-z][\w-]*)/i.exec(tag)?.[1]?.toLowerCase() ?? "";
195
- if (tag[1] === "/") {
227
+ TAG_NAME_AT.lastIndex = i;
228
+ const name = TAG_NAME_AT.exec(html)?.[1]?.toLowerCase() ?? "";
229
+ if (html[i + 1] === "/") {
196
230
  if (depth === 0)
197
231
  break;
198
232
  depth--;
199
- } else if (!/\/\s*>$/.test(tag) && !VOID_TAGS.has(name))
233
+ } else if (!isSelfClosingBefore(html, tagEnd) && !VOID_TAGS.has(name))
200
234
  depth++;
201
235
  i = tagEnd + 1;
202
236
  }
203
- return text;
237
+ return !1;
204
238
  }
205
239
  export function addCloakToUnresolvedExpressions(html) {
240
+ if (html.length >= 32768 && !mightContainOwnTextMustache(html))
241
+ return html;
206
242
  const tagStartRe = new RegExp(`<(${"div|span|p|h[1-6]|td|th|li|a|button|label|section|article|header|footer|main|nav|aside|dd|dt|figcaption|summary|caption|blockquote|pre|code|em|strong|small|sub|sup|time|mark|abbr|cite|q|s|u|b|i"})\\b`, "gi");
207
243
  let result = "", lastIndex = 0, tagMatch;
208
244
  while ((tagMatch = tagStartRe.exec(html)) !== null) {
@@ -233,8 +269,7 @@ export function addCloakToUnresolvedExpressions(html) {
233
269
  continue;
234
270
  if (fullTag.includes("x-cloak"))
235
271
  continue;
236
- const textContent = ownText(html, tagCloseIdx + 1);
237
- if (/\{\{[\s\S]*?\}\}/.test(textContent)) {
272
+ if (ownTextContainsMustache(html, tagCloseIdx + 1)) {
238
273
  result += html.slice(lastIndex, tagCloseIdx) + " x-cloak>";
239
274
  lastIndex = tagCloseIdx + 1;
240
275
  }
package/dist/process.js CHANGED
@@ -247,6 +247,9 @@ function placeSignalsRuntimeBeforeScripts(html) {
247
247
  const firstScript = findFirstScriptTag(html);
248
248
  if (firstScript === -1 || firstScript === runtime.start)
249
249
  return html;
250
+ if (firstScript < runtime.start)
251
+ return html.slice(0, firstScript) + html.slice(runtime.start, runtime.end) + `
252
+ ` + html.slice(firstScript, runtime.start) + html.slice(runtime.end);
250
253
  const runtimeTag = html.slice(runtime.start, runtime.end), withoutRuntime = html.slice(0, runtime.start) + html.slice(runtime.end), insertionPoint = findFirstScriptTag(withoutRuntime);
251
254
  if (insertionPoint === -1)
252
255
  return runtimeTag + `
@@ -302,7 +305,7 @@ export async function processDirectives(template, context, filePath, options, de
302
305
  result = ensureDocumentShell(result, headConfig, {
303
306
  ...titleIsHtml && { titleIsHtml: !0 },
304
307
  ...options.app?.colorMode && { colorMode: options.app.colorMode }
305
- });
308
+ }, alreadyShelled);
306
309
  if (alreadyShelled) {
307
310
  result = injectConfigHeadTags(result, baseHeadConfig);
308
311
  result = applyHtmlAttrs(result, headConfig.htmlAttrs);
@@ -824,9 +827,16 @@ ${runtimeScript}`);
824
827
  rangeEnd++;
825
828
  serverRemoveRanges.push({ start: script.start, end: rangeEnd });
826
829
  }
827
- for (let ri = serverRemoveRanges.length - 1;ri >= 0; ri--) {
828
- const { start, end } = serverRemoveRanges[ri];
829
- output = output.substring(0, start) + output.substring(end);
830
+ if (serverRemoveRanges.length > 0) {
831
+ const kept = Array(serverRemoveRanges.length + 1);
832
+ let cursor = 0;
833
+ for (let ri = 0;ri < serverRemoveRanges.length; ri++) {
834
+ const { start, end } = serverRemoveRanges[ri];
835
+ kept[ri] = output.slice(cursor, start);
836
+ cursor = end;
837
+ }
838
+ kept[serverRemoveRanges.length] = output.slice(cursor);
839
+ output = kept.join("");
830
840
  }
831
841
  }
832
842
  const scopedResult = processScopedStyles(output, filePath);
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Hk as wq,Ik as dq,Jk as Cq,Kk as mq,Lk as gq}from"./chunk-hpybjwwf.js";import{Mk as S,Nk as Tq,Ok as _q,Pk as z,Qk as D,Rk as P,Sk as kq,Tk as vq,Uk as w,Vk as Iq,Wk as d,Xk as Hq,Yk as Oq,Zk as Mq}from"./chunk-s2284nbk.js";import{$u as Pq,Wu as Aq,Xu as bq,Yu as Sq,Zu as zq,_u as Dq}from"./chunk-jn6m8zf7.js";import{dv as N}from"./chunk-sskbegsz.js";import p from"fs";import E from"path";import C from"fs";import L from"path";var k=[72,96,128,144,152,192,384,512],v=[120,152,167,180],I=[16,32];async function H(G,B){let q={success:!0,generatedFiles:[],errors:[],warnings:[]},K=G.pwa?.icons;if(!K?.src)return q.errors.push("No source icon specified in pwa.icons.src"),q.success=!1,q;let Y=L.isAbsolute(K.src)?K.src:L.resolve(process.cwd(),K.src);if(!await Bun.file(Y).exists())return q.errors.push(`Source icon not found: ${Y}`),q.success=!1,q;let Q=L.resolve(B,K.outputDir||"pwa-icons");try{C.mkdirSync(Q,{recursive:!0})}catch{return q.errors.push(`Failed to create output directory: ${Q}`),q.success=!1,q}let X=K.sizes||k,j=K.generateWebP??!0,J=K.generateAppleIcons??!0;try{let y;try{y=await import("sharp")}catch{return q.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),q.success=!1,q}let R=await y.default(Y).metadata();if(R.width&&R.width<512)q.warnings.push(`Source icon is ${R.width}x${R.height}. Recommend using at least 512x512 for best quality.`);for(let $ of X){let x=L.join(Q,`icon-${$}x${$}.png`);if(await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x),j){let F=L.join(Q,`icon-${$}x${$}.webp`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(F),q.generatedFiles.push(F)}}if(J){for(let x of v){let F=L.join(Q,`apple-touch-icon-${x}x${x}.png`);await y.default(Y).resize(x,x,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(F),q.generatedFiles.push(F)}let $=L.join(Q,"apple-touch-icon.png");await y.default(Y).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile($),q.generatedFiles.push($)}for(let $ of I){let x=L.join(Q,`favicon-${$}x${$}.png`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x)}let U=512,T=L.join(Q,`icon-maskable-${U}x${U}.png`),Z=Math.floor(U*0.1),_=U-Z*2;await y.default(Y).resize(_,_,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:Z,bottom:Z,left:Z,right:Z,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(T),q.generatedFiles.push(T)}catch(y){let V=y instanceof Error?y.message:String(y);q.errors.push(`Icon generation failed: ${V}`),q.success=!1}return q}function n(G){let B=G.sizes||k,q=G.outputDir?`/${G.outputDir}`:"/pwa-icons",K=G.generateWebP??!0,Y=G.generateAppleIcons??!0,Q=[];for(let X of B)if(Q.push(`${q}/icon-${X}x${X}.png`),K)Q.push(`${q}/icon-${X}x${X}.webp`);if(Y){Q.push(`${q}/apple-touch-icon.png`);for(let X of v)Q.push(`${q}/apple-touch-icon-${X}x${X}.png`)}for(let X of I)Q.push(`${q}/favicon-${X}x${X}.png`);return Q.push(`${q}/icon-maskable-512x512.png`),Q}async function O(){try{return await import("sharp"),!0}catch{return!1}}function m(G,B,q,K){let Y=[],Q=K.join(" ");for(let X of G)if(Y.push({src:`${B}/icon-${X}x${X}.png`,sizes:`${X}x${X}`,type:"image/png",purpose:Q}),q)Y.push({src:`${B}/icon-${X}x${X}.webp`,sizes:`${X}x${X}`,type:"image/webp",purpose:Q});return Y}function g(G){return G.map((B)=>({name:B.name,short_name:B.shortName,description:B.description,url:B.url,icons:B.icons?.map((q)=>({src:q.src,sizes:q.sizes,type:q.type}))}))}function h(G){let B=G.pwa?.shareTarget;if(!B?.enabled)return;let q={action:B.action||"/share",method:B.method||"POST",enctype:B.enctype||"multipart/form-data",params:{title:B.params?.title||"title",text:B.params?.text||"text",url:B.params?.url||"url"}};if(B.acceptFiles&&B.acceptFiles.length>0)q.params.files=B.acceptFiles.map((K)=>({name:K.name,accept:K.accept}));return q}function c(G){let B=G.pwa?.fileHandlers;if(!B?.enabled||!B.accept)return;let q=[{action:B.action||"/",accept:B.accept,launch_type:B.launchType||"single-client"}];if(B.icons)q[0].icons=B.icons.map((K)=>({src:K.src,sizes:K.sizes,type:K.type}));return q}function l(G){let B=G.pwa?.protocolHandlers;if(!B||B.length===0)return;return B.map((q)=>({protocol:q.protocol,url:q.url}))}function u(G){let B=G.pwa;if(!B?.enabled||!B.manifest)return null;let{manifest:q,icons:K}=B,Y=K?.sizes||[72,96,128,144,152,192,384,512],Q=K?.outputDir?`/${K.outputDir}`:"/pwa-icons",X=K?.generateWebP??!0,j=K?.purpose||["any","maskable"],J={name:q.name,short_name:q.shortName||q.name,description:q.description,start_url:q.startUrl||"/",display:q.display||"standalone",display_override:q.displayOverride,orientation:q.orientation,theme_color:q.themeColor,background_color:q.backgroundColor,scope:q.scope||"/",lang:q.lang,dir:q.dir,id:q.id,categories:q.categories,icons:m(Y,Q,X,j)};if(q.shortcuts&&q.shortcuts.length>0)J.shortcuts=g(q.shortcuts);if(q.screenshots&&q.screenshots.length>0)J.screenshots=q.screenshots.map((U)=>({src:U.src,sizes:U.sizes,type:U.type,label:U.label,form_factor:U.platform}));let y=h(G);if(y)J.share_target=y;let V=c(G);if(V)J.file_handlers=V;let R=l(G);if(R)J.protocol_handlers=R;if(q.launchHandler)J.launch_handler={client_mode:q.launchHandler};if(q.handleLinks)J.handle_links=q.handleLinks;if(q.edgeSidePanel?.enabled)J.edge_side_panel={preferred_width:q.edgeSidePanel.preferredWidth};return J}function M(G){let B=u(G);if(!B)return"";let q=JSON.parse(JSON.stringify(B));return JSON.stringify(q,null,2)}function i(G,B){return{...B,...G,shortcuts:G.shortcuts||B.shortcuts,screenshots:G.screenshots||B.screenshots,categories:G.categories||B.categories}}function s(G){let B=[],q=G.pwa;if(!q?.enabled)return B;let K=q.manifest;if(!K)return B.push("PWA manifest configuration is missing"),B;if(!K.name)B.push("Manifest name is required");let Y=["fullscreen","standalone","minimal-ui","browser"];if(K.display&&!Y.includes(K.display))B.push(`Invalid display mode: ${K.display}. Must be one of: ${Y.join(", ")}`);let Q=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(K.orientation&&!Q.includes(K.orientation))B.push(`Invalid orientation: ${K.orientation}`);let X=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(K.themeColor&&!X.test(K.themeColor))B.push(`Invalid theme color: ${K.themeColor}. Must be a valid hex color.`);if(K.backgroundColor&&!X.test(K.backgroundColor))B.push(`Invalid background color: ${K.backgroundColor}. Must be a valid hex color.`);if(q.shareTarget?.enabled){if(!q.shareTarget.action)B.push("Share target action URL is required")}if(q.fileHandlers?.enabled){if(!q.fileHandlers.accept||Object.keys(q.fileHandlers.accept).length===0)B.push("File handlers must specify accepted MIME types")}if(q.protocolHandlers)for(let j of q.protocolHandlers){if(!j.protocol)B.push("Protocol handler missing protocol");if(!j.url||!j.url.includes("%s"))B.push(`Protocol handler URL must contain %s placeholder: ${j.protocol}`)}return B}import A from"path";async function b(G){let B=G.pwa?.offline;if(!B?.enabled)return"";if(B.page){let q=A.isAbsolute(B.page)?B.page:A.resolve(process.cwd(),B.page);if(await Bun.file(q).exists())try{let{processDirectives:K}=await import("./chunk-y3qng57q.js"),Y=await Bun.file(q).text();return await K(Y,{},q,G,new Set)}catch(K){console.warn(`[PWA] Failed to process custom offline page: ${K}`)}else console.warn(`[PWA] Custom offline page not found: ${q}`)}return f(G)}function f(G){let B=G.pwa?.offline,q=G.pwa?.manifest,K=B?.fallbackTitle||"You are offline",Y=B?.fallbackMessage||"Please check your internet connection and try again.",Q=q?.themeColor||"#4f46e5",X=q?.shortName||q?.name||"App";return`<!DOCTYPE html>
2
+ import{Hk as wq,Ik as dq,Jk as Cq,Kk as mq,Lk as gq}from"./chunk-hpybjwwf.js";import{Mk as S,Nk as Tq,Ok as _q,Pk as z,Qk as D,Rk as P,Sk as kq,Tk as vq,Uk as w,Vk as Iq,Wk as d,Xk as Hq,Yk as Oq,Zk as Mq}from"./chunk-1q4y74mh.js";import{$u as Sq,Zu as Aq,_u as bq,av as zq,bv as Dq,cv as Pq}from"./chunk-x650vjcp.js";import{gv as N}from"./chunk-qc1f74ek.js";import p from"fs";import E from"path";import C from"fs";import L from"path";var k=[72,96,128,144,152,192,384,512],v=[120,152,167,180],I=[16,32];async function H(G,B){let q={success:!0,generatedFiles:[],errors:[],warnings:[]},K=G.pwa?.icons;if(!K?.src)return q.errors.push("No source icon specified in pwa.icons.src"),q.success=!1,q;let Y=L.isAbsolute(K.src)?K.src:L.resolve(process.cwd(),K.src);if(!await Bun.file(Y).exists())return q.errors.push(`Source icon not found: ${Y}`),q.success=!1,q;let Q=L.resolve(B,K.outputDir||"pwa-icons");try{C.mkdirSync(Q,{recursive:!0})}catch{return q.errors.push(`Failed to create output directory: ${Q}`),q.success=!1,q}let X=K.sizes||k,j=K.generateWebP??!0,J=K.generateAppleIcons??!0;try{let y;try{y=await import("sharp")}catch{return q.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),q.success=!1,q}let R=await y.default(Y).metadata();if(R.width&&R.width<512)q.warnings.push(`Source icon is ${R.width}x${R.height}. Recommend using at least 512x512 for best quality.`);for(let $ of X){let x=L.join(Q,`icon-${$}x${$}.png`);if(await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x),j){let F=L.join(Q,`icon-${$}x${$}.webp`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(F),q.generatedFiles.push(F)}}if(J){for(let x of v){let F=L.join(Q,`apple-touch-icon-${x}x${x}.png`);await y.default(Y).resize(x,x,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(F),q.generatedFiles.push(F)}let $=L.join(Q,"apple-touch-icon.png");await y.default(Y).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile($),q.generatedFiles.push($)}for(let $ of I){let x=L.join(Q,`favicon-${$}x${$}.png`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x)}let U=512,T=L.join(Q,`icon-maskable-${U}x${U}.png`),Z=Math.floor(U*0.1),_=U-Z*2;await y.default(Y).resize(_,_,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:Z,bottom:Z,left:Z,right:Z,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(T),q.generatedFiles.push(T)}catch(y){let V=y instanceof Error?y.message:String(y);q.errors.push(`Icon generation failed: ${V}`),q.success=!1}return q}function n(G){let B=G.sizes||k,q=G.outputDir?`/${G.outputDir}`:"/pwa-icons",K=G.generateWebP??!0,Y=G.generateAppleIcons??!0,Q=[];for(let X of B)if(Q.push(`${q}/icon-${X}x${X}.png`),K)Q.push(`${q}/icon-${X}x${X}.webp`);if(Y){Q.push(`${q}/apple-touch-icon.png`);for(let X of v)Q.push(`${q}/apple-touch-icon-${X}x${X}.png`)}for(let X of I)Q.push(`${q}/favicon-${X}x${X}.png`);return Q.push(`${q}/icon-maskable-512x512.png`),Q}async function O(){try{return await import("sharp"),!0}catch{return!1}}function m(G,B,q,K){let Y=[],Q=K.join(" ");for(let X of G)if(Y.push({src:`${B}/icon-${X}x${X}.png`,sizes:`${X}x${X}`,type:"image/png",purpose:Q}),q)Y.push({src:`${B}/icon-${X}x${X}.webp`,sizes:`${X}x${X}`,type:"image/webp",purpose:Q});return Y}function g(G){return G.map((B)=>({name:B.name,short_name:B.shortName,description:B.description,url:B.url,icons:B.icons?.map((q)=>({src:q.src,sizes:q.sizes,type:q.type}))}))}function h(G){let B=G.pwa?.shareTarget;if(!B?.enabled)return;let q={action:B.action||"/share",method:B.method||"POST",enctype:B.enctype||"multipart/form-data",params:{title:B.params?.title||"title",text:B.params?.text||"text",url:B.params?.url||"url"}};if(B.acceptFiles&&B.acceptFiles.length>0)q.params.files=B.acceptFiles.map((K)=>({name:K.name,accept:K.accept}));return q}function c(G){let B=G.pwa?.fileHandlers;if(!B?.enabled||!B.accept)return;let q=[{action:B.action||"/",accept:B.accept,launch_type:B.launchType||"single-client"}];if(B.icons)q[0].icons=B.icons.map((K)=>({src:K.src,sizes:K.sizes,type:K.type}));return q}function l(G){let B=G.pwa?.protocolHandlers;if(!B||B.length===0)return;return B.map((q)=>({protocol:q.protocol,url:q.url}))}function u(G){let B=G.pwa;if(!B?.enabled||!B.manifest)return null;let{manifest:q,icons:K}=B,Y=K?.sizes||[72,96,128,144,152,192,384,512],Q=K?.outputDir?`/${K.outputDir}`:"/pwa-icons",X=K?.generateWebP??!0,j=K?.purpose||["any","maskable"],J={name:q.name,short_name:q.shortName||q.name,description:q.description,start_url:q.startUrl||"/",display:q.display||"standalone",display_override:q.displayOverride,orientation:q.orientation,theme_color:q.themeColor,background_color:q.backgroundColor,scope:q.scope||"/",lang:q.lang,dir:q.dir,id:q.id,categories:q.categories,icons:m(Y,Q,X,j)};if(q.shortcuts&&q.shortcuts.length>0)J.shortcuts=g(q.shortcuts);if(q.screenshots&&q.screenshots.length>0)J.screenshots=q.screenshots.map((U)=>({src:U.src,sizes:U.sizes,type:U.type,label:U.label,form_factor:U.platform}));let y=h(G);if(y)J.share_target=y;let V=c(G);if(V)J.file_handlers=V;let R=l(G);if(R)J.protocol_handlers=R;if(q.launchHandler)J.launch_handler={client_mode:q.launchHandler};if(q.handleLinks)J.handle_links=q.handleLinks;if(q.edgeSidePanel?.enabled)J.edge_side_panel={preferred_width:q.edgeSidePanel.preferredWidth};return J}function M(G){let B=u(G);if(!B)return"";let q=JSON.parse(JSON.stringify(B));return JSON.stringify(q,null,2)}function i(G,B){return{...B,...G,shortcuts:G.shortcuts||B.shortcuts,screenshots:G.screenshots||B.screenshots,categories:G.categories||B.categories}}function s(G){let B=[],q=G.pwa;if(!q?.enabled)return B;let K=q.manifest;if(!K)return B.push("PWA manifest configuration is missing"),B;if(!K.name)B.push("Manifest name is required");let Y=["fullscreen","standalone","minimal-ui","browser"];if(K.display&&!Y.includes(K.display))B.push(`Invalid display mode: ${K.display}. Must be one of: ${Y.join(", ")}`);let Q=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(K.orientation&&!Q.includes(K.orientation))B.push(`Invalid orientation: ${K.orientation}`);let X=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(K.themeColor&&!X.test(K.themeColor))B.push(`Invalid theme color: ${K.themeColor}. Must be a valid hex color.`);if(K.backgroundColor&&!X.test(K.backgroundColor))B.push(`Invalid background color: ${K.backgroundColor}. Must be a valid hex color.`);if(q.shareTarget?.enabled){if(!q.shareTarget.action)B.push("Share target action URL is required")}if(q.fileHandlers?.enabled){if(!q.fileHandlers.accept||Object.keys(q.fileHandlers.accept).length===0)B.push("File handlers must specify accepted MIME types")}if(q.protocolHandlers)for(let j of q.protocolHandlers){if(!j.protocol)B.push("Protocol handler missing protocol");if(!j.url||!j.url.includes("%s"))B.push(`Protocol handler URL must contain %s placeholder: ${j.protocol}`)}return B}import A from"path";async function b(G){let B=G.pwa?.offline;if(!B?.enabled)return"";if(B.page){let q=A.isAbsolute(B.page)?B.page:A.resolve(process.cwd(),B.page);if(await Bun.file(q).exists())try{let{processDirectives:K}=await import("./chunk-r7r66978.js"),Y=await Bun.file(q).text();return await K(Y,{},q,G,new Set)}catch(K){console.warn(`[PWA] Failed to process custom offline page: ${K}`)}else console.warn(`[PWA] Custom offline page not found: ${q}`)}return f(G)}function f(G){let B=G.pwa?.offline,q=G.pwa?.manifest,K=B?.fallbackTitle||"You are offline",Y=B?.fallbackMessage||"Please check your internet connection and try again.",Q=q?.themeColor||"#4f46e5",X=q?.shortName||q?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -14,6 +14,8 @@ function hasStoreRefs(expression) {
14
14
  return /\$\w+\./.test(expression);
15
15
  }
16
16
  export function processReactiveBindings(html) {
17
+ if (!html.includes("{{") || !/\$\w+\./.test(html))
18
+ return { html, bindings: [], stores: new Set };
17
19
  const bindings = [], stores = new Set, tagPattern = /<(\w+)([^>]*?)(\s*\/?>)/g;
18
20
  let result = html;
19
21
  result = result.replace(tagPattern, (match, tagName, attributes, closing) => {
@@ -225,25 +225,12 @@ export declare const COMPONENT_PASSTHROUGH_X_ATTRS: readonly string[];
225
225
  /** The `X_HANDLED` lookup the generated runtime embeds, as JS source. */
226
226
  export declare function runtimeHandledXAttrsLiteral(): string;
227
227
  /**
228
- * Blank the parts of an HTML template that cannot carry a live directive,
229
- * for DETECTION only — never for output.
230
- *
231
- * `hasSignalsSyntax` and friends scan raw template text, so a documentation
232
- * page quoting stx syntax inside a code sample counted as reactive and shipped
233
- * the whole ~159KB signals runtime for markup that is inert text
234
- * (stacksjs/stx#1835).
235
- *
236
- * Only TEXT is blanked, and only inside `<pre>` / `<code>` and HTML comments.
237
- * Tags are kept intact, including their attributes, because that is where a
238
- * directive actually lives:
239
- *
240
- * <pre><code>&lt;div :if="open"&gt;</code></pre> -> blanked, it is text
241
- * <pre><code><span>&lt;div :if="x"&gt;</span></pre> -> span kept, text blanked
242
- * <pre><button @click="go()">run</button></pre> -> kept, it is a real button
243
- *
244
- * Dropping whole regions instead would have been simpler and wrong in the
245
- * expensive direction: a page whose only reactive element sits inside a `<pre>`
246
- * would lose its runtime and break, which is worse than shipping bytes it does
247
- * not need.
228
+ * Drop cached blanked documents.
229
+ *
230
+ * Nothing in the framework calls this, and nothing needs to. Entries are keyed
231
+ * on the input document itself, so an edited template is a different key and
232
+ * can never be answered with a stale result -- there is no invalidation to
233
+ * perform. It exists for callers that want a cold cache, such as tests.
248
234
  */
235
+ export declare function clearBlankCache(): void;
249
236
  export declare function blankInertHtmlRegions(html: string): string;
@@ -135,6 +135,9 @@ export function templateHasReactiveContext(template, filePath) {
135
135
  if (!template)
136
136
  return !1;
137
137
  const live = blankInertHtmlRegions(template);
138
+ return liveTemplateHasReactiveContext(live, filePath);
139
+ }
140
+ function liveTemplateHasReactiveContext(live, filePath) {
138
141
  if (TEMPLATE_REACTIVE_PATTERNS.some((pattern) => pattern.test(live)))
139
142
  return !0;
140
143
  if (usesReactiveRuntime(live))
@@ -152,7 +155,8 @@ function scriptsImportSignals(template, filePath) {
152
155
  export function templateNeedsRuntime(template, filePath) {
153
156
  if (!template)
154
157
  return !1;
155
- return HAS_EVENT_HANDLER.test(blankInertHtmlRegions(template)) || templateHasReactiveContext(template, filePath);
158
+ const live = blankInertHtmlRegions(template);
159
+ return HAS_EVENT_HANDLER.test(live) || liveTemplateHasReactiveContext(live, filePath);
156
160
  }
157
161
  export const RUNTIME_OWNED_COLON_ATTRS = [
158
162
  "if",
@@ -197,9 +201,30 @@ export const RUNTIME_HANDLED_X_ATTRS = [
197
201
  export function runtimeHandledXAttrsLiteral() {
198
202
  return `{${RUNTIME_HANDLED_X_ATTRS.map((n) => `'${n}':1`).join(",")}}`;
199
203
  }
204
+ const BLANK_CACHE_MIN_BYTES = 65536, BLANK_CACHE_MAX_ENTRIES = 4, blankCache = new Map;
205
+ export function clearBlankCache() {
206
+ blankCache.clear();
207
+ }
200
208
  export function blankInertHtmlRegions(html) {
201
209
  if (!html)
202
210
  return html;
203
- const blankText = (segment) => segment.replace(/(<[^>]*>)|([^<]+)/g, (_match, tag, text) => tag ?? " ".repeat(text.length));
204
- return html.replace(/(<pre\b[^>]*>)([\s\S]*?)(<\/pre>)/gi, (_m, open, body, close) => open + blankText(body) + close).replace(/(<code\b[^>]*>)([\s\S]*?)(<\/code>)/gi, (_m, open, body, close) => open + blankText(body) + close).replace(/<!--[\s\S]*?-->/g, (match) => " ".repeat(match.length));
211
+ if (!html.includes("<!--") && !/<(?:pre|code)\b/i.test(html))
212
+ return html;
213
+ const cacheable = html.length >= BLANK_CACHE_MIN_BYTES;
214
+ if (cacheable) {
215
+ const hit = blankCache.get(html);
216
+ if (hit !== void 0)
217
+ return hit;
218
+ }
219
+ const blankText = (segment) => segment.replace(/(<[^>]*>)|([^<]+)/g, (_match, tag, text) => tag ?? " ".repeat(text.length)), blanked = html.replace(/(<pre\b[^>]*>)([\s\S]*?)(<\/pre>)/gi, (_m, open, body, close) => open + blankText(body) + close).replace(/(<code\b[^>]*>)([\s\S]*?)(<\/code>)/gi, (_m, open, body, close) => open + blankText(body) + close).replace(/<!--[\s\S]*?-->/g, (match) => " ".repeat(match.length));
220
+ if (cacheable) {
221
+ while (blankCache.size >= BLANK_CACHE_MAX_ENTRIES) {
222
+ const oldest = blankCache.keys().next();
223
+ if (oldest.done)
224
+ break;
225
+ blankCache.delete(oldest.value);
226
+ }
227
+ blankCache.set(html, blanked);
228
+ }
229
+ return blanked;
205
230
  }
@@ -127,6 +127,21 @@ export declare function safeEvaluateObject(expression: string, context: Record<s
127
127
  * asked.
128
128
  */
129
129
  export declare function freeIdentifiers(expression: string): string[];
130
+ /**
131
+ * Whether `name` can be a `new Function` parameter name.
132
+ *
133
+ * Rejects the three classes JS refuses: non-identifiers (`data-id`, `1bad`),
134
+ * reserved words (`class`, `true`, `if`) and strict-mode-reserved words
135
+ * (`let`, `static`) -- the bodies here are always strict.
136
+ *
137
+ * Exported because every caller that spreads a template context into
138
+ * `new Function` needs exactly this test, and a near-miss copy is worse than
139
+ * none: an `isIdentifier`-only filter in variable-extractor.ts let `true`
140
+ * through, and one such key threw before the function was built, so the whole
141
+ * server script of six shipped components fell back to static extraction on
142
+ * every render (stacksjs/stx#1945 profiling, found via the fallback's cost).
143
+ */
144
+ export declare function isUsableParamName(name: string): boolean;
130
145
  export declare function createSafeFunction(expression: string, contextKeys: string[]): (...args: unknown[]) => unknown;
131
146
  export declare function safeEvaluateCode(code: string, context: Record<string, unknown>): unknown;
132
147
  /**
@@ -312,18 +312,19 @@ function compileFunctionBody(params, body) {
312
312
  export function freeIdentifiers(expression) {
313
313
  return expression.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`/g, " ").replace(/\??\.\s*[a-zA-Z_$][\w$]*/g, " ").replace(/([{,]\s*)[a-zA-Z_$][\w$]*(\s*:)/g, "$1$2").match(/\b[a-zA-Z_$][\w$]*\b/g) || [];
314
314
  }
315
+ const VALID_PARAM_IDENT = /^[A-Za-z_$][\w$]*$/;
316
+ export function isUsableParamName(name) {
317
+ return VALID_PARAM_IDENT.test(name) && !RESERVED_PARAM_NAMES.has(name);
318
+ }
315
319
  export function createSafeFunction(expression, contextKeys) {
316
- const sanitizedExpr = sanitizeExpression(expression), validIdent = /^[A-Za-z_$][\w$]*$/, validIndices = [], filteredKeys = [];
320
+ const sanitizedExpr = sanitizeExpression(expression), validEntries = [];
317
321
  for (let i = 0;i < contextKeys.length; i++) {
318
- const key = contextKeys[i];
319
- if (!validIdent.test(key))
320
- continue;
321
- if (RESERVED_PARAM_NAMES.has(key))
322
+ if (!isUsableParamName(contextKeys[i]))
322
323
  continue;
323
- validIndices.push(i);
324
- filteredKeys.push(key);
324
+ validEntries.push({ key: contextKeys[i], index: i });
325
325
  }
326
- const buildFunc = (extraParams) => compileFunctionBody([...filteredKeys, ...extraParams], `
326
+ validEntries.sort((a, b) => a.key.localeCompare(b.key));
327
+ const filteredKeys = validEntries.map((entry) => entry.key), validIndices = validEntries.map((entry) => entry.index), buildFunc = (extraParams) => compileFunctionBody([...filteredKeys, ...extraParams], `
327
328
  'use strict';
328
329
  try {
329
330
  return ${sanitizedExpr};
@@ -336,7 +337,8 @@ catch (e) {
336
337
  }
337
338
  `);
338
339
  let func = buildFunc([]);
339
- if (filteredKeys.length === contextKeys.length)
340
+ const alreadyCanonical = validEntries.every((entry, index) => entry.index === index);
341
+ if (filteredKeys.length === contextKeys.length && alreadyCanonical)
340
342
  return wrapWithMissingIdentifierRetry(func, filteredKeys, buildFunc);
341
343
  return wrapWithMissingIdentifierRetry((...args) => {
342
344
  const projected = Array(validIndices.length);
@@ -364,8 +366,10 @@ function wrapWithMissingIdentifierRetry(initialFunc, filteredKeys, buildFunc, on
364
366
  return;
365
367
  knownNames.add(missingName);
366
368
  extraParams.push(missingName);
367
- func = buildFunc(extraParams);
368
- onRebuild?.(extraParams);
369
+ if (onRebuild)
370
+ onRebuild(extraParams);
371
+ else
372
+ func = buildFunc(extraParams);
369
373
  }
370
374
  return;
371
375
  };
@@ -380,7 +384,7 @@ export function safeEvaluateCode(code, context) {
380
384
  for (const pattern of DANGEROUS_PATTERNS)
381
385
  if (pattern.test(code))
382
386
  throw Error("Potentially unsafe code detected");
383
- const safeContext = createSafeContext(context), keys = Object.keys(safeContext), values = Object.values(safeContext);
387
+ const safeContext = createSafeContext(context), keys = Object.keys(safeContext).filter(isUsableParamName), values = keys.map((key) => safeContext[key]);
384
388
  return Function(...keys, `
385
389
  'use strict';
386
390
  ${code}
@@ -86,7 +86,7 @@ export function processServerBindings(template, context) {
86
86
  function isProtected(pos) {
87
87
  return protectedRanges.some(([start, end]) => pos >= start && pos < end);
88
88
  }
89
- const tagRegex = /<([a-zA-Z][a-zA-Z0-9-]*)\b((?:[^>"']|"[^"]*"|'[^']*')*)\s*\/?>/g, replacements = [];
89
+ const tagRegex = /<([a-zA-Z][a-zA-Z0-9-]*)\b((?:[^>"']|"[^"]*"|'[^']*')*)\s*\/?>/g, replacements = [], compiledBindings = new Map, maxCompiledBindings = 256;
90
90
  while ((match = tagRegex.exec(output)) !== null) {
91
91
  if (isProtected(match.index))
92
92
  continue;
@@ -105,7 +105,15 @@ export function processServerBindings(template, context) {
105
105
  const contextKeys = Object.keys(context), contextValues = Object.values(context), identMatch = expression.match(/^([a-zA-Z_$][\w$]*)/);
106
106
  if (identMatch && !contextKeys.includes(identMatch[1]) && !["true", "false", "null", "undefined", "Math", "JSON", "String", "Number", "Array", "Object", "Date", "parseInt", "parseFloat"].includes(identMatch[1]))
107
107
  continue;
108
- const value = Function(...contextKeys, `return (${expression})`)(...contextValues);
108
+ const compileKey = JSON.stringify([contextKeys, expression]);
109
+ let fn = compiledBindings.get(compileKey);
110
+ if (!fn) {
111
+ fn = Function(...contextKeys, `return (${expression})`);
112
+ if (compiledBindings.size >= maxCompiledBindings)
113
+ compiledBindings.clear();
114
+ compiledBindings.set(compileKey, fn);
115
+ }
116
+ const value = fn(...contextValues);
109
117
  if (attrName === "class") {
110
118
  const classStr = resolveClassBinding(value);
111
119
  if (classStr) {
@@ -147,9 +155,17 @@ export function processServerBindings(template, context) {
147
155
  });
148
156
  }
149
157
  }
150
- for (let i = replacements.length - 1;i >= 0; i--) {
151
- const { start, end, replacement } = replacements[i];
152
- output = output.slice(0, start) + replacement + output.slice(end);
158
+ if (replacements.length > 0) {
159
+ const chunks = Array(replacements.length * 2 + 1);
160
+ let cursor = 0;
161
+ for (let i = 0;i < replacements.length; i++) {
162
+ const { start, end, replacement } = replacements[i];
163
+ chunks[i * 2] = output.slice(cursor, start);
164
+ chunks[i * 2 + 1] = replacement;
165
+ cursor = end;
166
+ }
167
+ chunks[replacements.length * 2] = output.slice(cursor);
168
+ output = chunks.join("");
153
169
  }
154
170
  return output;
155
171
  }
@@ -23,15 +23,25 @@ import type { StxOptions } from './types';
23
23
  * `skipAttrs` lets callers drop tags whose attribute string contains certain
24
24
  * patterns (e.g. `server`, `src=`, `data-stx-scoped`).
25
25
  */
26
+ export interface ScannedScriptTag {
27
+ readonly fullMatch: string;
28
+ readonly attrs: string;
29
+ readonly body: string;
30
+ readonly start: number;
31
+ readonly end: number;
32
+ }
33
+ /**
34
+ * Drop cached script scans.
35
+ *
36
+ * Nothing in the framework calls this, and nothing needs to. Entries are keyed
37
+ * on the input document itself, so an edited template is a different key and
38
+ * can never be answered with a stale result -- there is no invalidation to
39
+ * perform. It exists for callers that want a cold cache, such as tests.
40
+ */
41
+ export declare function clearScriptScanCache(): void;
26
42
  export declare function scanScriptTags(html: string, opts?: {
27
43
  skipAttrs?: RegExp;
28
- }): Array<{
29
- fullMatch: string;
30
- attrs: string;
31
- body: string;
32
- start: number;
33
- end: number;
34
- }>;
44
+ }): ScannedScriptTag[];
35
45
  /**
36
46
  * Parsed form of a loop expression (`@for` / `@foreach` argument).
37
47
  *