@stacksjs/stx 0.2.905 → 0.2.908

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 (250) hide show
  1. package/dist/app-shell.d.ts +1 -1
  2. package/dist/app-shell.js +1 -1
  3. package/dist/{chunk-n3fgrsva.js → chunk-0d3pkkrv.js} +2 -2
  4. package/dist/{chunk-fhb86pc9.js → chunk-0ek3s3b6.js} +150 -149
  5. package/dist/{chunk-qt2mr3f0.js → chunk-0mxkw6m6.js} +14 -9
  6. package/dist/{chunk-9y83pdcb.js → chunk-0vyytd9v.js} +3 -3
  7. package/dist/{chunk-4d6p92qh.js → chunk-13awnyq0.js} +1 -1
  8. package/dist/chunk-14497kj1.js +2 -0
  9. package/dist/chunk-1dc6h93m.js +2 -0
  10. package/dist/{chunk-ffytbb4x.js → chunk-1ezcxbpg.js} +5 -5
  11. package/dist/{chunk-eb5v9npc.js → chunk-1hx6dyy9.js} +2 -2
  12. package/dist/{chunk-a7bqrjm5.js → chunk-1jxkc6d0.js} +2 -2
  13. package/dist/{chunk-db7h6mgq.js → chunk-1pdntpwe.js} +4 -4
  14. package/dist/{chunk-vw6qytwm.js → chunk-1x0wcskp.js} +4 -4
  15. package/dist/chunk-20hy5p3p.js +2 -0
  16. package/dist/chunk-2fyey6pn.js +2 -0
  17. package/dist/chunk-2jkq15je.js +2 -0
  18. package/dist/{chunk-eb5cma4b.js → chunk-2m4d8jkv.js} +2 -2
  19. package/dist/{chunk-p89rpak1.js → chunk-2qk2ppgm.js} +1 -1
  20. package/dist/{chunk-arfpzf17.js → chunk-357qjcj1.js} +2 -2
  21. package/dist/{chunk-edpsk4bg.js → chunk-3m457a9q.js} +9 -9
  22. package/dist/{chunk-ng09dc4e.js → chunk-3npzxjr4.js} +2 -2
  23. package/dist/chunk-3qneemwh.js +2 -0
  24. package/dist/{chunk-nc5d3a5r.js → chunk-3syagjd7.js} +5 -5
  25. package/dist/chunk-43kz6rx9.js +2 -0
  26. package/dist/{chunk-bzndm04n.js → chunk-45326z5v.js} +2 -2
  27. package/dist/{chunk-zrvgr3hz.js → chunk-4ajsp5dp.js} +15 -15
  28. package/dist/{chunk-hdfhaddy.js → chunk-4b110x6r.js} +2 -2
  29. package/dist/chunk-4ge69wvr.js +2 -0
  30. package/dist/{chunk-xwzefw2r.js → chunk-4hrryats.js} +2 -2
  31. package/dist/chunk-4jmztn9d.js +2 -0
  32. package/dist/{chunk-rgrzmr35.js → chunk-59bbk5gx.js} +5 -5
  33. package/dist/{chunk-az1eczs2.js → chunk-5baag5dz.js} +7 -7
  34. package/dist/{chunk-pwpge9bj.js → chunk-5jc9hmwg.js} +2 -2
  35. package/dist/{chunk-ern5hyvr.js → chunk-5jn2qyv7.js} +1 -1
  36. package/dist/chunk-6756txp1.js +2 -0
  37. package/dist/{chunk-vtc9zmp6.js → chunk-69wpv1pr.js} +6 -6
  38. package/dist/chunk-6mw288vd.js +2 -0
  39. package/dist/{chunk-ayady5ws.js → chunk-6w9av0n9.js} +2 -2
  40. package/dist/{chunk-hnjeqxqy.js → chunk-6yketqa1.js} +2 -2
  41. package/dist/{chunk-5yvgzh6n.js → chunk-72pbhpq8.js} +2 -2
  42. package/dist/chunk-7hgqyea0.js +2 -0
  43. package/dist/chunk-7k1thytm.js +2 -0
  44. package/dist/chunk-7m5rpqjy.js +2 -0
  45. package/dist/chunk-7xpez9tc.js +2 -0
  46. package/dist/chunk-8f5x16ht.js +2 -0
  47. package/dist/{chunk-vfctk20v.js → chunk-8n42epb6.js} +3 -3
  48. package/dist/{chunk-k3ytyhkr.js → chunk-8p3vqt2q.js} +3 -3
  49. package/dist/{chunk-p92272k0.js → chunk-8tfpv6zf.js} +2 -2
  50. package/dist/chunk-9343arqn.js +2 -0
  51. package/dist/chunk-94r6mkcy.js +2 -0
  52. package/dist/{chunk-rdrstnn9.js → chunk-9atdw0p8.js} +2 -2
  53. package/dist/{chunk-5jrpzepc.js → chunk-9bexzgws.js} +2 -2
  54. package/dist/{chunk-0gc1hez6.js → chunk-9tj16d70.js} +3 -3
  55. package/dist/chunk-a0esj80g.js +3 -0
  56. package/dist/chunk-abxwggen.js +2 -0
  57. package/dist/{chunk-68r2zs20.js → chunk-ahf9j8wb.js} +4 -4
  58. package/dist/{chunk-3qr9ysey.js → chunk-am610nan.js} +7 -7
  59. package/dist/chunk-amye7vb0.js +2 -0
  60. package/dist/chunk-asewbsct.js +2 -0
  61. package/dist/{chunk-t9mjgt3q.js → chunk-av45fw8a.js} +1 -1
  62. package/dist/{chunk-0b57fgpn.js → chunk-b234w3mf.js} +30 -10
  63. package/dist/chunk-b25twdd7.js +2 -0
  64. package/dist/chunk-b7fmkwz2.js +2 -0
  65. package/dist/chunk-bprjp80g.js +2 -0
  66. package/dist/{chunk-945zygwa.js → chunk-c08jvjqt.js} +27 -27
  67. package/dist/{chunk-xc1f0c64.js → chunk-c0kgwh4k.js} +9 -9
  68. package/dist/chunk-c60egpe6.js +2 -0
  69. package/dist/{chunk-kf4z4efe.js → chunk-cfbmjgd0.js} +3 -3
  70. package/dist/{chunk-zzqg8y47.js → chunk-cjntf1jg.js} +2 -2
  71. package/dist/chunk-cjq455ve.js +2 -0
  72. package/dist/{chunk-rdnpq89q.js → chunk-ck4ypzet.js} +2 -2
  73. package/dist/{chunk-46khhke2.js → chunk-cpt9sg6d.js} +1 -1
  74. package/dist/{chunk-73ebyhqq.js → chunk-cq4cwfqf.js} +2 -2
  75. package/dist/chunk-cqq68aw8.js +2 -0
  76. package/dist/chunk-cssvev8r.js +2 -0
  77. package/dist/{chunk-qs0zk04y.js → chunk-cwcmmgvz.js} +2 -2
  78. package/dist/{chunk-5gnt3qtn.js → chunk-d4hnj3ct.js} +3 -3
  79. package/dist/{chunk-3q6x62hs.js → chunk-d8mnaesb.js} +132 -51
  80. package/dist/{chunk-5dw0xnk6.js → chunk-ddn98yz4.js} +5 -5
  81. package/dist/{chunk-qykbjg3z.js → chunk-e5rag6rh.js} +2 -2
  82. package/dist/{chunk-150cz8qq.js → chunk-eca022er.js} +7 -7
  83. package/dist/{chunk-fksmr50h.js → chunk-ekyx5z50.js} +6 -6
  84. package/dist/{chunk-xr1s56k5.js → chunk-eptzpvn0.js} +3 -3
  85. package/dist/chunk-f2yqqpvr.js +2 -0
  86. package/dist/chunk-f3msm5tk.js +2 -0
  87. package/dist/chunk-f74qzgp8.js +42 -0
  88. package/dist/{chunk-de61k0ab.js → chunk-fs43342z.js} +2 -2
  89. package/dist/{chunk-54x7h3sb.js → chunk-fycxc75p.js} +1 -1
  90. package/dist/chunk-fzh73jtc.js +2 -0
  91. package/dist/{chunk-gnf1e5q7.js → chunk-fznjm7qt.js} +2 -2
  92. package/dist/chunk-g67xjfe6.js +3 -0
  93. package/dist/{chunk-r0az4z6d.js → chunk-gfp39bzr.js} +2 -2
  94. package/dist/{chunk-8xb09hnn.js → chunk-gg31th5s.js} +4 -4
  95. package/dist/chunk-gmczbe3j.js +2 -0
  96. package/dist/{chunk-7nf7mp27.js → chunk-gyv2bsmn.js} +2 -2
  97. package/dist/chunk-h7xqba9k.js +2 -0
  98. package/dist/chunk-hg4vfrxr.js +2 -0
  99. package/dist/{chunk-9w7whtbx.js → chunk-hhspwfva.js} +2 -2
  100. package/dist/chunk-hpxhxwda.js +2 -0
  101. package/dist/{chunk-4j3zmxzw.js → chunk-jg5xc2m1.js} +15 -15
  102. package/dist/{chunk-4hk1mjtv.js → chunk-jhegz7az.js} +5 -5
  103. package/dist/chunk-jnk3nk5k.js +2 -0
  104. package/dist/{chunk-mry67rsk.js → chunk-jttzrv0w.js} +6 -6
  105. package/dist/{chunk-5tm1pvt3.js → chunk-jz37h2z0.js} +2 -2
  106. package/dist/chunk-jzbte09f.js +2 -0
  107. package/dist/chunk-k5v22gn4.js +2 -0
  108. package/dist/{chunk-50wjk5ap.js → chunk-kmy34he2.js} +2 -2
  109. package/dist/chunk-kt3f4rpy.js +2 -0
  110. package/dist/chunk-kydh790y.js +2 -0
  111. package/dist/chunk-mgcakk1m.js +2 -0
  112. package/dist/{chunk-vw7crz0z.js → chunk-mpfm5ctr.js} +4 -4
  113. package/dist/{chunk-7g2snypc.js → chunk-mrx20xza.js} +3 -3
  114. package/dist/chunk-n3bt1sv5.js +2 -0
  115. package/dist/chunk-n62nqhey.js +2 -0
  116. package/dist/chunk-naj7m2av.js +2 -0
  117. package/dist/{chunk-k3566kgd.js → chunk-nan0ysys.js} +2 -2
  118. package/dist/chunk-nrap20qt.js +2 -0
  119. package/dist/chunk-p2b90rz9.js +2 -0
  120. package/dist/chunk-pb2mztar.js +2 -0
  121. package/dist/{chunk-9hwg13ec.js → chunk-pc89t52s.js} +5 -5
  122. package/dist/{chunk-7b3dqeyr.js → chunk-phzhmnnm.js} +2 -2
  123. package/dist/chunk-pp89n1et.js +2 -0
  124. package/dist/chunk-ptrz5xwt.js +2 -0
  125. package/dist/{chunk-n23btj9k.js → chunk-q4nk8sq2.js} +3 -3
  126. package/dist/chunk-q9yahsww.js +2 -0
  127. package/dist/chunk-qgc59a7d.js +2 -0
  128. package/dist/chunk-qjkpwjg6.js +2 -0
  129. package/dist/chunk-qn9rrwp8.js +2 -0
  130. package/dist/chunk-qpf782pt.js +2 -0
  131. package/dist/{chunk-5mrt1enm.js → chunk-razwegar.js} +2 -2
  132. package/dist/{chunk-d1tcw019.js → chunk-rdeje2dd.js} +43 -43
  133. package/dist/chunk-s91tcznf.js +2 -0
  134. package/dist/{chunk-67pq803s.js → chunk-sdf4c754.js} +2 -2
  135. package/dist/chunk-senrtnx2.js +2 -0
  136. package/dist/{chunk-nzegc1hd.js → chunk-skxkqh9a.js} +2 -2
  137. package/dist/{chunk-czhzr5k1.js → chunk-sxqha69q.js} +5 -5
  138. package/dist/{chunk-bgkj0rxe.js → chunk-ta7cwykn.js} +4 -4
  139. package/dist/{chunk-nzf3c6n0.js → chunk-tpryfx8t.js} +10 -10
  140. package/dist/{chunk-jsehp750.js → chunk-trnw1tg5.js} +1 -1
  141. package/dist/{chunk-vbmvft7g.js → chunk-v0yay1kw.js} +1 -1
  142. package/dist/{chunk-1pb32z4r.js → chunk-v25gm9d9.js} +19 -19
  143. package/dist/{chunk-2sz1kh9m.js → chunk-va4xam1q.js} +1 -1
  144. package/dist/{chunk-pzj2se3m.js → chunk-vkxrsy13.js} +14 -14
  145. package/dist/chunk-vqys4n8f.js +2 -0
  146. package/dist/{chunk-bzd387yx.js → chunk-w3y8408q.js} +4 -4
  147. package/dist/chunk-w4177qn3.js +3 -0
  148. package/dist/{chunk-esm0pnpz.js → chunk-w98yt4d4.js} +2 -2
  149. package/dist/{chunk-7nn5s0c3.js → chunk-wbsbrm6n.js} +30 -30
  150. package/dist/chunk-x1svtz8k.js +2 -0
  151. package/dist/chunk-xn8eabng.js +2 -0
  152. package/dist/{chunk-kgyjavqg.js → chunk-xqe3c7pa.js} +5 -5
  153. package/dist/chunk-xwarwkaw.js +2 -0
  154. package/dist/{chunk-yqpkdecx.js → chunk-y9xq82ep.js} +6 -6
  155. package/dist/{chunk-z744ry8a.js → chunk-yjhktn0b.js} +9 -9
  156. package/dist/chunk-ykx4zt07.js +2 -0
  157. package/dist/{chunk-wbpnqr7h.js → chunk-yvp5tfrz.js} +3 -3
  158. package/dist/{chunk-g32hc78c.js → chunk-yzgtsrjb.js} +2 -2
  159. package/dist/chunk-z8e2m6kz.js +2 -0
  160. package/dist/{chunk-t14bn66j.js → chunk-zk1c6tg7.js} +3 -3
  161. package/dist/chunk-zk6qmkhb.js +2 -0
  162. package/dist/{chunk-30yqa2jw.js → chunk-zkp5awqw.js} +1 -1
  163. package/dist/cli.js +21 -21
  164. package/dist/client/signals-loop-conditional-runtime.js +5 -0
  165. package/dist/component-renderer.js +2 -24
  166. package/dist/craft-entry.js +2 -2
  167. package/dist/craft.js +2 -2
  168. package/dist/native/runtime/craft-bridge.js +5 -1
  169. package/dist/native/runtime/craft.d.ts +4 -0
  170. package/dist/offline/app-service-worker.d.ts +1 -0
  171. package/dist/offline/app-service-worker.js +99 -17
  172. package/dist/production-server.d.ts +0 -9
  173. package/dist/production-server.js +26 -11
  174. package/dist/pwa.js +3 -3
  175. package/dist/route-response-cache.js +4 -3
  176. package/dist/server-bindings.js +3 -1
  177. package/dist/spa-nav.d.ts +6 -0
  178. package/dist/spa-nav.js +5 -1
  179. package/dist/ssg.js +10 -10
  180. package/dist/stx-virtual-ts.d.ts +4 -0
  181. package/dist/stx-virtual-ts.js +22 -0
  182. package/dist/utils.js +22 -2
  183. package/package.json +5 -5
  184. package/dist/chunk-0ht6exrv.js +0 -2
  185. package/dist/chunk-1pbghytr.js +0 -2
  186. package/dist/chunk-31r1tk86.js +0 -2
  187. package/dist/chunk-3vhczypz.js +0 -2
  188. package/dist/chunk-4tzay5dt.js +0 -2
  189. package/dist/chunk-5astk182.js +0 -2
  190. package/dist/chunk-5tvse0vw.js +0 -2
  191. package/dist/chunk-6heg0cza.js +0 -2
  192. package/dist/chunk-726w7fm2.js +0 -2
  193. package/dist/chunk-73t3w7fh.js +0 -2
  194. package/dist/chunk-7bjrvyqk.js +0 -2
  195. package/dist/chunk-7n4mve8h.js +0 -2
  196. package/dist/chunk-7r294vc9.js +0 -2
  197. package/dist/chunk-7rn7w53f.js +0 -2
  198. package/dist/chunk-7v3tgpws.js +0 -2
  199. package/dist/chunk-81qvg3yd.js +0 -2
  200. package/dist/chunk-9bcrr81g.js +0 -2
  201. package/dist/chunk-9g6tfcrv.js +0 -2
  202. package/dist/chunk-be8x7mkn.js +0 -2
  203. package/dist/chunk-c87cndsj.js +0 -2
  204. package/dist/chunk-cp82351f.js +0 -2
  205. package/dist/chunk-cv609hgq.js +0 -2
  206. package/dist/chunk-cvxg2rc1.js +0 -2
  207. package/dist/chunk-dmc91qke.js +0 -2
  208. package/dist/chunk-dw23nre3.js +0 -2
  209. package/dist/chunk-fk593bkb.js +0 -2
  210. package/dist/chunk-fznzn35q.js +0 -2
  211. package/dist/chunk-gfz0czma.js +0 -2
  212. package/dist/chunk-ggchpq5r.js +0 -42
  213. package/dist/chunk-ghmb45zs.js +0 -2
  214. package/dist/chunk-hc8ks7y3.js +0 -2
  215. package/dist/chunk-hs2a040z.js +0 -2
  216. package/dist/chunk-hten266c.js +0 -2
  217. package/dist/chunk-jr3fmkq7.js +0 -2
  218. package/dist/chunk-k2fw6paw.js +0 -2
  219. package/dist/chunk-k79dvx67.js +0 -2
  220. package/dist/chunk-kf6j1ht4.js +0 -2
  221. package/dist/chunk-km1k3c4e.js +0 -2
  222. package/dist/chunk-knxb6d18.js +0 -2
  223. package/dist/chunk-kvjbpbmw.js +0 -2
  224. package/dist/chunk-kx9amwwr.js +0 -2
  225. package/dist/chunk-mhv84p0x.js +0 -2
  226. package/dist/chunk-mxxb3e9v.js +0 -2
  227. package/dist/chunk-mz44m7y7.js +0 -2
  228. package/dist/chunk-p3pjfj65.js +0 -2
  229. package/dist/chunk-p8eeg64w.js +0 -2
  230. package/dist/chunk-ph74v3ag.js +0 -3
  231. package/dist/chunk-pjpy86c3.js +0 -3
  232. package/dist/chunk-pnbeey2h.js +0 -3
  233. package/dist/chunk-ps5wfd4c.js +0 -2
  234. package/dist/chunk-qzx6h6af.js +0 -2
  235. package/dist/chunk-s0dmb7me.js +0 -2
  236. package/dist/chunk-tgwwa872.js +0 -2
  237. package/dist/chunk-tspqdt8e.js +0 -2
  238. package/dist/chunk-tyv0csb4.js +0 -2
  239. package/dist/chunk-v0r6zb87.js +0 -2
  240. package/dist/chunk-vxtna1b1.js +0 -2
  241. package/dist/chunk-wwtv5cht.js +0 -2
  242. package/dist/chunk-x2x1cqr0.js +0 -2
  243. package/dist/chunk-x43x2c6v.js +0 -2
  244. package/dist/chunk-xb192088.js +0 -2
  245. package/dist/chunk-xqx8t9w5.js +0 -2
  246. package/dist/chunk-xy0f5yds.js +0 -2
  247. package/dist/chunk-z33r3pzy.js +0 -2
  248. package/dist/chunk-zkr42285.js +0 -2
  249. package/dist/chunk-zrs22j09.js +0 -2
  250. package/dist/chunk-zw6tgr0s.js +0 -2
@@ -88,6 +88,7 @@ export declare interface OfflineAppConfig {
88
88
  apiPrefix?: string
89
89
  networkTimeoutMs?: number
90
90
  precacheTimeoutMs?: number
91
+ precacheQuietMs?: number
91
92
  networkFirst?: string[]
92
93
  updateOnColdStart?: boolean
93
94
  fallback?: string
@@ -172,6 +172,7 @@ export function generateOfflineWorker(config, buildId, pagePaths = []) {
172
172
  api: config.apiPrefix || "/api/",
173
173
  timeout: Math.max(500, Number(config.networkTimeoutMs) || 1500),
174
174
  precacheTimeout: Number.isFinite(precacheTimeout) && precacheTimeout > 0 ? Math.min(2147483647, Math.max(1, Math.floor(precacheTimeout))) : 1e4,
175
+ precacheQuiet: Number.isFinite(Number(config.precacheQuietMs)) && Number(config.precacheQuietMs) >= 0 ? Math.min(60000, Math.floor(Number(config.precacheQuietMs))) : 1500,
175
176
  networkFirst: (config.networkFirst || []).filter((path) => typeof path === "string" && path.startsWith("/")),
176
177
  updateOnColdStart: config.updateOnColdStart === !0,
177
178
  fallback: config.fallback || config.pages && config.pages[0] || null,
@@ -472,26 +473,101 @@ function keepAssets(html) {
472
473
  }).catch(function () {});
473
474
  }
474
475
 
476
+ // Precaching renders each listed screen on the server, and it starts as the
477
+ // first page after sign-in loads. All at once (two at a time, about 60
478
+ // renders on one app) it took the server's CPU for minutes, and the pages a
479
+ // person was actually opening came back up to 2.7 times slower. So: one
480
+ // screen at a time; each only after the page's own requests have gone quiet;
481
+ // after a slow answer a pause as long as it took; and on 503, 408 or 429 a
482
+ // wait (Retry-After when the server gives one) and up to three more tries. A
483
+ // screen already kept for this build is not fetched again, so an install the
484
+ // browser cut short picks up where it stopped.
485
+ var foregroundAt = 0;
486
+ var foregroundOpen = 0;
487
+ var QUIET_WAIT_MAX = 30000;
488
+ var SLOW_ANSWER = 2000;
489
+ var BUSY = [503, 408, 429];
490
+ function noteForeground(event) {
491
+ foregroundAt = Date.now();
492
+ foregroundOpen++;
493
+ var settled = false;
494
+ var counted = { responded: false, settle: function () {
495
+ if (settled) return;
496
+ settled = true;
497
+ foregroundOpen = Math.max(0, foregroundOpen - 1);
498
+ foregroundAt = Date.now();
499
+ } };
500
+ try {
501
+ var respond = event.respondWith.bind(event);
502
+ event.respondWith = function (answer) {
503
+ counted.responded = true;
504
+ Promise.resolve(answer).then(counted.settle, counted.settle);
505
+ return respond(answer);
506
+ };
507
+ }
508
+ catch (error) { counted.responded = false; }
509
+ return counted;
510
+ }
511
+ function pause(ms) {
512
+ return new Promise(function (resolve) { setTimeout(resolve, Math.max(0, ms)); });
513
+ }
514
+ function quietNetwork() {
515
+ if (!S.precacheQuiet) return Promise.resolve();
516
+ var started = Date.now();
517
+ return new Promise(function (resolve) {
518
+ (function check() {
519
+ var now = Date.now();
520
+ if ((foregroundOpen === 0 && now - foregroundAt >= S.precacheQuiet) || now - started >= QUIET_WAIT_MAX) return resolve();
521
+ setTimeout(check, Math.min(250, S.precacheQuiet));
522
+ })();
523
+ });
524
+ }
525
+ function retryAfterMs(response, attempt) {
526
+ var given = response.headers.get('Retry-After');
527
+ var seconds = given === null ? NaN : Number(given);
528
+ if (isFinite(seconds) && seconds >= 0) return Math.min(60000, seconds * 1000);
529
+ var at = given === null ? NaN : Date.parse(given);
530
+ if (isFinite(at)) return Math.min(60000, Math.max(0, at - Date.now()));
531
+ return 1000 * Math.pow(2, attempt);
532
+ }
533
+ function precacheOne(cache, page, fragment, attempt) {
534
+ var key = page.key(fragment);
535
+ return cache.match(key).then(function (kept) {
536
+ if (kept) return null;
537
+ return quietNetwork().then(function () {
538
+ var headers = fragment ? { 'X-STX-Router': 'true', 'Accept': 'text/html', 'Purpose': 'prefetch' } : { 'Accept': 'text/html', 'Purpose': 'prefetch' };
539
+ var started = Date.now();
540
+ return background(function (signal) {
541
+ return fetch(page.url, { headers: headers, credentials: 'same-origin', signal: signal, priority: 'low' }).then(function (response) {
542
+ var took = Date.now() - started;
543
+ if (BUSY.indexOf(response.status) !== -1) return { busy: retryAfterMs(response, attempt), took: took, html: null };
544
+ if (response.status !== 200 || response.redirected) return { took: took, html: null };
545
+ var copy = response.clone();
546
+ return Promise.all([store(cache, [key], response), copy.text()]).then(function (parts) { return { took: took, html: parts[1] }; });
547
+ });
548
+ }).then(function (result) {
549
+ if (result.busy !== undefined) {
550
+ if (attempt >= 3) return null;
551
+ return pause(result.busy).then(function () { return precacheOne(cache, page, fragment, attempt + 1); });
552
+ }
553
+ var rest = result.took > SLOW_ANSWER ? pause(Math.min(QUIET_WAIT_MAX, result.took)) : Promise.resolve();
554
+ // Queue linked assets after releasing the page's slot. Waiting for
555
+ // child jobs inside a bounded parent job would deadlock installation.
556
+ return rest.then(function () { if (result.html !== null) return keepAssets(result.html); });
557
+ });
558
+ });
559
+ }).catch(function () {});
560
+ }
561
+
475
562
  function precache() {
476
563
  var wanted = S.pages.map(function (page) { return { url: page, key: function (fragment) { return variantUrl(page, fragment); } }; })
477
564
  .concat(S.routes.map(function (route) { return { url: route.sample, key: function (fragment) { return routeKey(route, fragment); } }; }));
478
565
  return caches.open(SHELL).then(function (cache) {
479
- return Promise.all(wanted.map(function (page) {
480
- return Promise.all([false, true].map(function (fragment) {
481
- var headers = fragment ? { 'X-STX-Router': 'true', 'Accept': 'text/html', 'Purpose': 'prefetch' } : { 'Accept': 'text/html', 'Purpose': 'prefetch' };
482
- return background(function (signal) {
483
- return fetch(page.url, { headers: headers, credentials: 'same-origin', signal: signal, priority: 'low' }).then(function (response) {
484
- if (response.status !== 200 || response.redirected) return null;
485
- var copy = response.clone();
486
- return Promise.all([store(cache, [page.key(fragment)], response), copy.text()]).then(function (parts) { return parts[1]; });
487
- });
488
- }).then(function (html) {
489
- // Queue linked assets after releasing the page's slot. Waiting for
490
- // child jobs inside a bounded parent job would deadlock installation.
491
- if (html !== null) return keepAssets(html);
492
- }).catch(function () {});
493
- }));
494
- }));
566
+ var jobs = [];
567
+ wanted.forEach(function (page) { jobs.push([page, false], [page, true]); });
568
+ return jobs.reduce(function (previous, job) {
569
+ return previous.then(function () { return precacheOne(cache, job[0], job[1], 0); });
570
+ }, Promise.resolve());
495
571
  });
496
572
  }
497
573
 
@@ -852,6 +928,12 @@ function apiResponse(request, event) {
852
928
  }
853
929
 
854
930
  self.addEventListener('fetch', function (event) {
931
+ var counted = noteForeground(event);
932
+ try { answerFetch(event); }
933
+ finally { if (!counted.responded) counted.settle(); }
934
+ });
935
+
936
+ function answerFetch(event) {
855
937
  var request = event.request;
856
938
  var url = new URL(request.url);
857
939
  if (url.origin !== self.location.origin) return;
@@ -888,6 +970,6 @@ self.addEventListener('fetch', function (event) {
888
970
  if (request.mode === 'navigate' || isFragment(request) || accept.indexOf('text/html') !== -1) {
889
971
  event.respondWith(pageResponse(request, event));
890
972
  }
891
- });
973
+ }
892
974
  `;
893
975
  }
@@ -1,13 +1,4 @@
1
1
  import { type RuntimeConfigDefaults } from './runtime-config-server.js';
2
- /**
3
- * Start the production server.
4
- *
5
- * Serves pre-built pages from .output/ with minimal per-request work:
6
- * - Static assets: served from disk with immutable cache headers
7
- * - SPA fragments: served from pre-extracted HTML files
8
- * - Static pages: served directly (zero processing)
9
- * - Dynamic pages: hydrated with request-time data
10
- */
11
2
  export declare function startProductionServer(options?: ProductionServerOptions): Promise<{ port: number, stop: () => void, invalidate: (pathname?: string) => void }>;
12
3
  /**
13
4
  * Production server configuration.
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { serve } from "bun";
4
4
  import { loadManifest } from "./manifest.js";
5
5
  import { hydrateTemplateStream } from "./template-hydrator.js";
6
- import { extractContainerContent, extractLayoutMetadata, hasContainerRegion } from "./app-shell.js";
6
+ import { extractContainerContent, extractLayoutMetadata, hasContainerRegion, layoutChanges, layoutTheRouterHas } from "./app-shell.js";
7
7
  import { pageShipsSignalsRuntime } from "./runtime-injection.js";
8
8
  import { isFileRequestPath, patternToRegex } from "stx-router";
9
9
  import { compressResponse } from "./compression.js";
@@ -42,6 +42,15 @@ const MIME_TYPES = {
42
42
  ".otf": "font/otf",
43
43
  ".eot": "application/vnd.ms-fontobject"
44
44
  };
45
+ function layoutAcrossFor(request, page) {
46
+ if (!page)
47
+ return null;
48
+ const routerHas = layoutTheRouterHas(request.headers);
49
+ return routerHas && layoutChanges(routerHas, page) ? page : null;
50
+ }
51
+ function layoutHeaders(page) {
52
+ return page ? { "X-STX-Layout": page.layout, "X-STX-Layout-Group": page.group } : {};
53
+ }
45
54
  export async function startProductionServer(options = {}) {
46
55
  const outputDir = path.resolve(options.outputDir || ".output"), port = options.port ?? 3000, manifest = loadManifest(outputDir);
47
56
  if (!manifest) {
@@ -145,8 +154,8 @@ export async function startProductionServer(options = {}) {
145
154
  }
146
155
  const rule = resolveRule(pathname), controlled = Object.keys(rule).length > 0;
147
156
  return responseCache.respond(request, rule.cache, async () => {
148
- const candidate = compiledTemplates.get(matchedRoute.pattern);
149
- if (isSpaNav && request.method === "GET" && candidate && !candidate.hasServerScripts && Object.keys(candidate.placeholders).length === 0) {
157
+ const candidate = compiledTemplates.get(matchedRoute.pattern), staticAcross = isSpaNav ? layoutAcrossFor(request, layoutMetadataCache.get(matchedRoute.pattern)) : null;
158
+ if (isSpaNav && !staticAcross && request.method === "GET" && candidate && !candidate.hasServerScripts && Object.keys(candidate.placeholders).length === 0) {
150
159
  const fragment = fragmentCache.get(matchedRoute.pattern);
151
160
  if (fragment) {
152
161
  const layoutMetadata = layoutMetadataCache.get(matchedRoute.pattern);
@@ -187,7 +196,8 @@ export async function startProductionServer(options = {}) {
187
196
  headers: {
188
197
  "Content-Type": "text/html",
189
198
  ...spaNavVaryHeaders(),
190
- "Cache-Control": "public, max-age=60"
199
+ "Cache-Control": "public, max-age=60",
200
+ ...layoutHeaders(staticAcross)
191
201
  }
192
202
  });
193
203
  try {
@@ -204,14 +214,16 @@ export async function startProductionServer(options = {}) {
204
214
  const { renderStreamingPage, streamToResponse } = await import("./streaming.js"), headers = new Headers({ ...spaNavVaryHeaders(), ...pageHeaders, "Cache-Control": "private, no-store" });
205
215
  for (const cookie of cookies ?? [])
206
216
  headers.append("Set-Cookie", cookie);
207
- if (isSpaNav && !isMutating && hasContainerRegion(html, manifest.routerContainer || "main")) {
208
- const layout = extractLayoutMetadata(html);
217
+ const streamLayout = isSpaNav && !isMutating ? extractLayoutMetadata(html) : null, streamAcross = streamLayout ? layoutAcrossFor(request, streamLayout) : null, streamFragment = isSpaNav && !isMutating && !streamAcross && hasContainerRegion(html, manifest.routerContainer || "main");
218
+ if (streamFragment && streamLayout) {
209
219
  headers.set("X-STX-Fragment", "true");
210
220
  headers.set("X-STX-Runtime", pageShipsSignalsRuntime(html) ? "true" : "false");
211
- headers.set("X-STX-Layout", layout.layout);
212
- headers.set("X-STX-Layout-Group", layout.group);
221
+ headers.set("X-STX-Layout", streamLayout.layout);
222
+ headers.set("X-STX-Layout-Group", streamLayout.group);
213
223
  }
214
- return streamToResponse(renderStreamingPage(isSpaNav && !isMutating && hasContainerRegion(html, manifest.routerContainer || "main") ? extractContainerContent(html, manifest.routerContainer || "main", !0) : html, boundaries, { timeoutMs: 30000 }), {
224
+ for (const [name, value] of Object.entries(layoutHeaders(streamAcross)))
225
+ headers.set(name, value);
226
+ return streamToResponse(renderStreamingPage(streamFragment ? extractContainerContent(html, manifest.routerContainer || "main", !0) : html, boundaries, { timeoutMs: 30000 }), {
215
227
  status: status ?? compiled.status ?? 200,
216
228
  headers
217
229
  });
@@ -226,8 +238,11 @@ export async function startProductionServer(options = {}) {
226
238
  for (const [name, value] of Object.entries(pageHeaders ?? {}))
227
239
  headers.set(name, value);
228
240
  headers.set("Vary", spaNavVaryHeaders(headers.get("Vary")).Vary);
229
- if (isSpaNav && !isMutating && hasContainerRegion(html, manifest.routerContainer || "main")) {
230
- const layout = extractLayoutMetadata(html);
241
+ const pageLayout = isSpaNav && !isMutating ? extractLayoutMetadata(html) : null, pageAcross = pageLayout ? layoutAcrossFor(request, pageLayout) : null;
242
+ for (const [name, value] of Object.entries(layoutHeaders(pageAcross)))
243
+ headers.set(name, value);
244
+ if (isSpaNav && !isMutating && !pageAcross && hasContainerRegion(html, manifest.routerContainer || "main")) {
245
+ const layout = pageLayout ?? extractLayoutMetadata(html);
231
246
  headers.set("X-STX-Fragment", "true");
232
247
  headers.set("X-STX-Runtime", pageShipsSignalsRuntime(html) ? "true" : "false");
233
248
  headers.set("X-STX-Layout", layout.layout);
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{So,tn,Zl,sm}from"./chunk-bzd387yx.js";import{xo,sa,tm,nm,rm}from"./chunk-nc5d3a5r.js";import{Xl,Jl,Yl,Qg,em}from"./chunk-g32hc78c.js";import{nt,Vn,oa}from"./chunk-xr1s56k5.js";import{om,im,am,cm,ko,qy}from"./chunk-n3fgrsva.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-4tzay5dt.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
2
+ import{_o,tn,tu,am}from"./chunk-w3y8408q.js";import{ko,aa,sm,om,im}from"./chunk-3syagjd7.js";import{Zl,Ql,eu,nm,rm}from"./chunk-yzgtsrjb.js";import{st,Vn,ca}from"./chunk-eptzpvn0.js";import{cm,lm,um,dm,Co,Gy}from"./chunk-0d3pkkrv.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-cssvev8r.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -233,4 +233,4 @@ Icon generation requires the sharp package for image processing.`),e.success=!1,
233
233
  }, 5000);
234
234
  </script>
235
235
  </body>
236
- </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=nt(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=So(n,t);if(a){let s=tn(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return sa(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,Jl as auditBuildOutput,Xl as auditConfig,re as buildPwaAssets,Yl as calculateAuditResult,em as formatAuditResult,oa as formatSize,j as generateManifest,_ as generateManifestJson,nm as generateManifestLink,F as generateOfflinePage,nt as generatePrecacheManifest,Vn as generatePrecacheManifestJs,M as generatePwaIcons,xo as generatePwaTags,So as generateServiceWorker,sm as generateServiceWorkerAuto,tm as generateSwRegistrationScript,rm as generateThemeColorMeta,N as getExpectedIconPaths,tn as getServiceWorkerFileName,sa as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,Zl as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,ko as pwaDirectives,om as pwaInstallDirective,am as pwaOfflineDirective,cm as pwaPushDirective,im as pwaUpdateDirective,qy as registerPwaDirectives,Qg as runPwaAudit,D as validateManifest};
236
+ </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=st(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=_o(n,t);if(a){let s=tn(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return aa(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,Ql as auditBuildOutput,Zl as auditConfig,re as buildPwaAssets,eu as calculateAuditResult,rm as formatAuditResult,ca as formatSize,j as generateManifest,_ as generateManifestJson,om as generateManifestLink,F as generateOfflinePage,st as generatePrecacheManifest,Vn as generatePrecacheManifestJs,M as generatePwaIcons,ko as generatePwaTags,_o as generateServiceWorker,am as generateServiceWorkerAuto,sm as generateSwRegistrationScript,im as generateThemeColorMeta,N as getExpectedIconPaths,tn as getServiceWorkerFileName,aa as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,tu as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,Co as pwaDirectives,cm as pwaInstallDirective,um as pwaOfflineDirective,dm as pwaPushDirective,lm as pwaUpdateDirective,Gy as registerPwaDirectives,nm as runPwaAudit,D as validateManifest};
@@ -1,5 +1,6 @@
1
1
  import { LRUCache } from "./performance-utils.js";
2
- import { isSpaNavRequest, spaNavVaryHeaders } from "./spa-nav.js";
2
+ import { isSpaNavRequest, SPA_LAYOUT_HEADERS, spaNavVaryHeaders } from "./spa-nav.js";
3
+ const KEYED_VARY = new Set(["x-stx-router", "accept-encoding", ...SPA_LAYOUT_HEADERS.map((name) => name.toLowerCase())]);
3
4
 
4
5
  export class RouteResponseCache {
5
6
  now;
@@ -29,7 +30,7 @@ export class RouteResponseCache {
29
30
  };
30
31
  if (!policy || request.method !== "GET" || request.headers.has("Cookie") || request.headers.has("Authorization") || request.headers.has("Range"))
31
32
  return privateResponse();
32
- const url = new URL(request.url), key = `${url.origin}${url.pathname}${url.search}|${isSpaNavRequest(request) ? "fragment" : "document"}`, cached = this.entries.get(key), reply = (entry) => {
33
+ const url = new URL(request.url), variant = isSpaNavRequest(request) ? `fragment|${SPA_LAYOUT_HEADERS.map((name) => request.headers.get(name) ?? "").join("|")}` : "document", key = `${url.origin}${url.pathname}${url.search}|${variant}`, cached = this.entries.get(key), reply = (entry) => {
33
34
  const headers = new Headers(entry.headers);
34
35
  headers.set("Cache-Control", "private, no-store");
35
36
  headers.set("Age", String(Math.max(0, Math.floor((this.now() - entry.created) / 1000))));
@@ -41,7 +42,7 @@ export class RouteResponseCache {
41
42
  const response = await render();
42
43
  original = response;
43
44
  const vary = (response.headers.get("Vary") ?? "").toLowerCase().split(",").map((value) => value.trim()).filter(Boolean);
44
- if (response.status !== 200 || response.headers.has("Set-Cookie") || /(?:private|no-store|no-cache)/i.test(response.headers.get("Cache-Control") ?? "") || vary.some((value) => value !== "x-stx-router" && value !== "accept-encoding"))
45
+ if (response.status !== 200 || response.headers.has("Set-Cookie") || /(?:private|no-store|no-cache)/i.test(response.headers.get("Cache-Control") ?? "") || vary.some((value) => !KEYED_VARY.has(value)))
45
46
  return null;
46
47
  const body = await response.clone().arrayBuffer();
47
48
  if (body.byteLength > 1048576)
@@ -128,7 +128,7 @@ export function processServerBindings(template, context) {
128
128
  const attrs = tag.attributes.trimEnd();
129
129
  if (!attrs || !attrs.includes(":"))
130
130
  continue;
131
- const nativeHost = /(?:^|\s)data-native(?:\s|=|$)/i.test(attrs.replace(/"[^"]*"|'[^']*'/g, "")), bindingRegex = /\s:([a-zA-Z_][\w-]*)\s*=\s*"([^"]*)"/g;
131
+ const nativeHost = /(?:^|\s)data-native(?:\s|=|$)/i.test(attrs.replace(/"[^"]*"|'[^']*'/g, "")), parentOwned = new Set((/(?:^|\s)data-stx-parent-bindings="([^"]*)"/.exec(attrs)?.[1] ?? "").split(/\s+/).filter(Boolean)), bindingRegex = /\s:([a-zA-Z_][\w-]*)\s*=\s*"([^"]*)"/g;
132
132
  let attrMatch, newAttrs = attrs, hadReplacement = !1;
133
133
  while ((attrMatch = bindingRegex.exec(attrs)) !== null) {
134
134
  if (classifyHtmlInterpolation(attrs, attrMatch.index, !0)?.kind === "attribute")
@@ -136,6 +136,8 @@ export function processServerBindings(template, context) {
136
136
  const attrName = attrMatch[1], expression = attrMatch[2];
137
137
  if (isRuntimeOwnedColonAttr(attrName))
138
138
  continue;
139
+ if (parentOwned.has(attrName) && !nativeHost)
140
+ continue;
139
141
  if (readsAnyName(expression, clientOwnedNames))
140
142
  continue;
141
143
  if (expression.includes("()") && !expression.includes(".get(") || expression.includes("$store") || expression.includes("$ref"))
package/dist/spa-nav.d.ts CHANGED
@@ -67,3 +67,9 @@ export declare const SPA_NAV_HEADER: 'X-STX-Router';
67
67
  * where it would otherwise be replayed into a fresh document load.
68
68
  */
69
69
  export declare const FRAGMENT_CACHE_CONTROL: 'private, no-store';
70
+ /**
71
+ * The headers the router sends with a fragment request to say which layout
72
+ * its page is on. Named here as well as in stx-router so the cache key does
73
+ * not depend on that package's build.
74
+ */
75
+ export declare const SPA_LAYOUT_HEADERS: readonly ['X-STX-Have-Layout', 'X-STX-Have-Layout-Group'];
package/dist/spa-nav.js CHANGED
@@ -20,5 +20,9 @@ export function appendVary(vary, field) {
20
20
  return vary.split(",").some((entry) => entry.trim().toLowerCase() === field.toLowerCase()) ? vary : `${vary}, ${field}`;
21
21
  }
22
22
  export function spaNavVaryHeaders(existing) {
23
- return { Vary: appendVary(existing, SPA_NAV_HEADER) };
23
+ let vary = appendVary(existing, SPA_NAV_HEADER);
24
+ for (const header of SPA_LAYOUT_HEADERS)
25
+ vary = appendVary(vary, header);
26
+ return { Vary: vary };
24
27
  }
28
+ export const SPA_LAYOUT_HEADERS = ["X-STX-Have-Layout", "X-STX-Have-Layout-Group"];
package/dist/ssg.js CHANGED
@@ -1,12 +1,12 @@
1
1
  // @bun
2
- import"./chunk-0jdz31q1.js";import"./chunk-rdnpq89q.js";import"./chunk-4d6p92qh.js";import"./chunk-qs0zk04y.js";import{_,Al}from"./chunk-945zygwa.js";import"./chunk-hdfhaddy.js";import"./chunk-7b3dqeyr.js";import{Vt,x}from"./chunk-fhb86pc9.js";import"./chunk-esm0pnpz.js";import"./chunk-xwzefw2r.js";import"./chunk-5mrt1enm.js";import{Lt,jt,Bt,Ft,zt,Ht}from"./chunk-0b57fgpn.js";import{a}from"./chunk-4j3zmxzw.js";import{Us}from"./chunk-150cz8qq.js";import"./chunk-vw7crz0z.js";import"./chunk-5dw0xnk6.js";import{Te,mn,hn}from"./chunk-db7h6mgq.js";import"./chunk-bzndm04n.js";import{S}from"./chunk-z744ry8a.js";import{Pt,i}from"./chunk-3q6x62hs.js";import"./chunk-ggchpq5r.js";import"./chunk-nzf3c6n0.js";import{Ps}from"./chunk-xc1f0c64.js";import"./chunk-vw6qytwm.js";import"./chunk-de61k0ab.js";import{kc,_c,Cc}from"./chunk-vfctk20v.js";import{fn,fr,gr}from"./chunk-arfpzf17.js";import{gn}from"./chunk-30yqa2jw.js";import"./chunk-ph74v3ag.js";import"./chunk-5jrpzepc.js";import{re,Ae}from"./chunk-az1eczs2.js";import"./chunk-vbmvft7g.js";import"./chunk-kf4z4efe.js";import{l}from"./chunk-pjpy86c3.js";import{tt}from"./chunk-qykbjg3z.js";import{t,h}from"./chunk-68r2zs20.js";import{f}from"./chunk-p92272k0.js";import R from"fs";import w from"path";import{createHash as $t}from"crypto";function kt(e){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(e).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return e}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function Rt(e){return Bun.hash(e).toString(16)}function lt(e,n={}){if(!e.includes('type="stx/island"'))return{html:e,chunks:[]};let s=new Map,o=e.replace(Dt,(r,u,g,P)=>{let b=P.trim();if(!b)return r;if(/\bdata-stx-src=/.test(g))return r;if(n.minify)b=kt(b);let p=Rt(b);if(!s.has(p))s.set(p,b);let k=n.integrity?` data-stx-integrity="sha384-${$t("sha384").update(b).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${k}${g}></script>`}),c=Array.from(s,([r,u])=>({hash:r,code:u}));return{html:o,chunks:c}}var Et=new Set(["visible","idle"]);function ut(e){if(!e.includes("data-stx-src="))return e;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(e))!==null)n.set(o[1],o[2]);let c=new Set,r=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=r.exec(e))!==null)if(Et.has(n.get(u[1])||""))c.add(u[2]);let g=/<\/head\s*>/iy,P=x(e,(p,k)=>(g.lastIndex=k,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(c.size===0||P===-1)return e;let b=Array.from(c).filter((p)=>!e.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!b)return e;return e.slice(0,P)+b+e.slice(P)}var Ct=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function Y(e){let n=e.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function It(e){for(let n of Ct){let s=e[n];if(!s)continue;let o=Y(s);if(o)return{url:o,source:"env",via:n}}return null}function dt(e){if(!e||typeof e!=="object")return null;let n=e,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?Y(s):null}async function Tt(e){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=s.resolve(e,o);if(!n(c))continue;try{let r=await import(c),u=dt(r.default??r);if(u)return u}catch{}}return null}async function gt(e={}){let n=e.cwd??process.cwd(),s=e.env??process.env;if(e.explicit){let u=Y(e.explicit);if(u)return{url:u,source:"option"}}let o=dt(e.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let c=await Tt(n);if(c)return{url:c,source:"site.config",via:"url"};let r=It(s);if(r)return r;return{url:"http://localhost",source:"fallback"}}function pt(){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
- `)}function V(e){return async()=>({paths:await e(),fallback:!1})}var At;function Ot(e){let n=t(e),{depths:s}=h(n),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,c;while((c=o.exec(n))!==null){if(s[c.index]!==0)continue;let u=_(n,"(",")",o.lastIndex-1),g=n.indexOf("{",u+1),P=_(n,"{","}",g);if(u<0||g<0||P<0)break;return e.slice(c.index,P+1)}let r=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((c=r.exec(n))!==null){if(s[c.index]!==0)continue;let u=Al(n,r.lastIndex).endPos;return e.slice(r.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function ft(e){let n="read";try{let s=await Bun.file(e).text();n="parse";let o=gn(s),c=[...o.server,...o.client,...o.signals].filter((r)=>/(?:^|\s)server(?:\s|=|$)/i.test(t(r.attrs))).sort((r,u)=>s.indexOf(r.fullTag)-s.indexOf(u.fullTag));for(let r of c){if(!/\bgetStaticPaths\b/.test(t(r.content)))continue;let u=(At??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(r.content);if(!/\bgetStaticPaths\b/.test(t(u)))continue;let g=Ot(u);if(/\bdefineStaticPaths\b/.test(t(g))&&Vt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");n="execute";let P=Function("defineStaticPaths",`return (${g})`)(V);if(typeof P!=="function")throw TypeError("getStaticPaths must be a function");let b=await P();n="result";let p=Array.isArray(b)?{paths:b}:b;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let k of p.paths)if(!k||typeof k!=="object"||!k.params||typeof k.params!=="object"||Array.isArray(k.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(s){return{kind:"error",phase:n,error:s instanceof Error?s:Error(String(s))}}}class ht{cacheDir;cache=new Map;loaded=!1;salt;constructor(e,n=""){this.cacheDir=e,this.salt=n}async load(){if(this.loaded)return;let e=w.join(this.cacheDir,"build-cache.json");if(await Bun.file(e).exists())try{let n=JSON.parse(await Bun.file(e).text());for(let[s,o]of Object.entries(n))this.cache.set(s,o)}catch{}this.loaded=!0}async save(){await R.promises.mkdir(this.cacheDir,{recursive:!0});let e=w.join(this.cacheDir,"build-cache.json"),n={};for(let[s,o]of this.cache)n[s]=o;await Bun.write(e,JSON.stringify(n))}getHash(e,n){let s=R.statSync(e),o=`${this.salt}|${e}:${s.mtimeMs}`;for(let r of n)if(R.existsSync(r)){let u=R.statSync(r);o+=`:${r}:${u.mtimeMs}`}let c=0;for(let r=0;r<o.length;r++){let u=o.charCodeAt(r);c=(c<<5)-c+u,c=c&c}return Math.abs(c).toString(36)}get(e,n){let s=this.cache.get(e);if(!s)return null;let o=wt(n).some((u)=>R.existsSync(u)),c=[n,...s.dependencies??[]].some((u)=>u.endsWith(".stx")&&R.existsSync(u)&&Ps(R.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||c)return this.cache.delete(e),null;let r=this.getHash(n,s.dependencies??[]);if(s.hash!==r)return this.cache.delete(e),null;return s.html}set(e,n,s,o){let c=this.getHash(n,s);this.cache.set(e,{hash:c,html:o,generatedAt:Date.now(),dependencies:s})}}class mt{cacheDir;constructor(e){this.cacheDir=e}getFilePath(e){let n=e.replace(/[^a-zA-Z0-9]/g,"_")+".json";return w.join(this.cacheDir,"isr",n)}async get(e){let n=this.getFilePath(e);if(!await Bun.file(n).exists())return null;try{return JSON.parse(await Bun.file(n).text())}catch{return null}}async set(e,n){let s=this.getFilePath(e);await R.promises.mkdir(w.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(n))}async invalidate(e){let n=this.getFilePath(e);if(await Bun.file(n).exists())await R.promises.unlink(n)}async invalidatePattern(e){let n=w.join(this.cacheDir,"isr");if(!R.existsSync(n))return;let s=await R.promises.readdir(n);for(let o of s){let c=o.replace(/_/g,"/").replace(".json","");if(e.test(c))await R.promises.unlink(w.join(n,o))}}async needsRevalidation(e){let n=await this.get(e);if(!n)return!0;return Date.now()>n.revalidateAfter}}async function Ut(e){let n=[];if(!e.isDynamic)n.push({url:e.pattern,params:{}});else{let s=await ft(e.filePath);if(s.kind==="error")throw Error(`getStaticPaths ${s.phase} failed for ${e.pattern} (${e.filePath}): ${s.error.message}`,{cause:s.error});if(s.kind==="absent")return console.warn(`Warning: Dynamic route ${e.pattern} (${e.filePath}) has no getStaticPaths`),n;let o=s.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${e.pattern} (${e.filePath})`),n;for(let c of o.paths){let r=e.pattern;for(let[u,g]of Object.entries(c.params))r=r.replace(`:${u}`,g).replace(`:${u}*`,g);n.push({url:r,params:c.params,props:c.props,revalidate:c.revalidate})}}return n}function wt(e){return[e.replace(/\.stx$/,".data.ts"),e.replace(/\.stx$/,".data.js"),e+".data.ts",e+".data.js"]}async function _t(e){for(let n of wt(e))if(await Bun.file(n).exists())try{let s=await import(n);if(typeof s.default==="function")return await s.default();else if(typeof s.default==="object")return s.default;else if(typeof s.getData==="function")return await s.getData();else{let{default:o,...c}=s;return c}}catch(s){console.error(`Error loading data file ${n}:`,s)}return null}async function Mt(e,n,s){let o=e.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let c=o[1];if(!c.includes("getStaticProps"))return null;try{let r=c.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!r)return null;return await Function("params",`
2
+ import"./chunk-0jdz31q1.js";import"./chunk-ck4ypzet.js";import"./chunk-13awnyq0.js";import"./chunk-cwcmmgvz.js";import{_,Ol}from"./chunk-c08jvjqt.js";import"./chunk-4b110x6r.js";import"./chunk-phzhmnnm.js";import{Ut,x}from"./chunk-0ek3s3b6.js";import"./chunk-w98yt4d4.js";import"./chunk-4hrryats.js";import"./chunk-razwegar.js";import{Lt,jt,Bt,Ft,zt,Ht}from"./chunk-b234w3mf.js";import{a}from"./chunk-jg5xc2m1.js";import{qs}from"./chunk-eca022er.js";import"./chunk-mpfm5ctr.js";import"./chunk-ddn98yz4.js";import{$e,mn,hn}from"./chunk-1pdntpwe.js";import"./chunk-45326z5v.js";import{S}from"./chunk-yjhktn0b.js";import{Pt,i}from"./chunk-d8mnaesb.js";import"./chunk-f74qzgp8.js";import"./chunk-tpryfx8t.js";import{Os}from"./chunk-c0kgwh4k.js";import"./chunk-1x0wcskp.js";import"./chunk-fs43342z.js";import{Ec,Tc,$c}from"./chunk-8n42epb6.js";import{fn,gr,mr}from"./chunk-357qjcj1.js";import{gn}from"./chunk-zkp5awqw.js";import"./chunk-g67xjfe6.js";import"./chunk-9bexzgws.js";import{re,Pe}from"./chunk-5baag5dz.js";import"./chunk-v0yay1kw.js";import"./chunk-cfbmjgd0.js";import{l}from"./chunk-w4177qn3.js";import{rt}from"./chunk-e5rag6rh.js";import{t,h}from"./chunk-ahf9j8wb.js";import{f}from"./chunk-8tfpv6zf.js";import R from"fs";import w from"path";import{createHash as $t}from"crypto";function kt(e){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(e).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return e}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function Rt(e){return Bun.hash(e).toString(16)}function lt(e,n={}){if(!e.includes('type="stx/island"'))return{html:e,chunks:[]};let s=new Map,o=e.replace(Dt,(r,u,g,P)=>{let b=P.trim();if(!b)return r;if(/\bdata-stx-src=/.test(g))return r;if(n.minify)b=kt(b);let p=Rt(b);if(!s.has(p))s.set(p,b);let k=n.integrity?` data-stx-integrity="sha384-${$t("sha384").update(b).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${k}${g}></script>`}),c=Array.from(s,([r,u])=>({hash:r,code:u}));return{html:o,chunks:c}}var Et=new Set(["visible","idle"]);function ut(e){if(!e.includes("data-stx-src="))return e;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(e))!==null)n.set(o[1],o[2]);let c=new Set,r=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=r.exec(e))!==null)if(Et.has(n.get(u[1])||""))c.add(u[2]);let g=/<\/head\s*>/iy,P=x(e,(p,k)=>(g.lastIndex=k,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(c.size===0||P===-1)return e;let b=Array.from(c).filter((p)=>!e.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!b)return e;return e.slice(0,P)+b+e.slice(P)}var Ct=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function Y(e){let n=e.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function It(e){for(let n of Ct){let s=e[n];if(!s)continue;let o=Y(s);if(o)return{url:o,source:"env",via:n}}return null}function dt(e){if(!e||typeof e!=="object")return null;let n=e,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?Y(s):null}async function Tt(e){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=s.resolve(e,o);if(!n(c))continue;try{let r=await import(c),u=dt(r.default??r);if(u)return u}catch{}}return null}async function gt(e={}){let n=e.cwd??process.cwd(),s=e.env??process.env;if(e.explicit){let u=Y(e.explicit);if(u)return{url:u,source:"option"}}let o=dt(e.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let c=await Tt(n);if(c)return{url:c,source:"site.config",via:"url"};let r=It(s);if(r)return r;return{url:"http://localhost",source:"fallback"}}function pt(){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
+ `)}function V(e){return async()=>({paths:await e(),fallback:!1})}var At;function Ot(e){let n=t(e),{depths:s}=h(n),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,c;while((c=o.exec(n))!==null){if(s[c.index]!==0)continue;let u=_(n,"(",")",o.lastIndex-1),g=n.indexOf("{",u+1),P=_(n,"{","}",g);if(u<0||g<0||P<0)break;return e.slice(c.index,P+1)}let r=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((c=r.exec(n))!==null){if(s[c.index]!==0)continue;let u=Ol(n,r.lastIndex).endPos;return e.slice(r.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function ft(e){let n="read";try{let s=await Bun.file(e).text();n="parse";let o=gn(s),c=[...o.server,...o.client,...o.signals].filter((r)=>/(?:^|\s)server(?:\s|=|$)/i.test(t(r.attrs))).sort((r,u)=>s.indexOf(r.fullTag)-s.indexOf(u.fullTag));for(let r of c){if(!/\bgetStaticPaths\b/.test(t(r.content)))continue;let u=(At??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(r.content);if(!/\bgetStaticPaths\b/.test(t(u)))continue;let g=Ot(u);if(/\bdefineStaticPaths\b/.test(t(g))&&Ut(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");n="execute";let P=Function("defineStaticPaths",`return (${g})`)(V);if(typeof P!=="function")throw TypeError("getStaticPaths must be a function");let b=await P();n="result";let p=Array.isArray(b)?{paths:b}:b;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let k of p.paths)if(!k||typeof k!=="object"||!k.params||typeof k.params!=="object"||Array.isArray(k.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(s){return{kind:"error",phase:n,error:s instanceof Error?s:Error(String(s))}}}class ht{cacheDir;cache=new Map;loaded=!1;salt;constructor(e,n=""){this.cacheDir=e,this.salt=n}async load(){if(this.loaded)return;let e=w.join(this.cacheDir,"build-cache.json");if(await Bun.file(e).exists())try{let n=JSON.parse(await Bun.file(e).text());for(let[s,o]of Object.entries(n))this.cache.set(s,o)}catch{}this.loaded=!0}async save(){await R.promises.mkdir(this.cacheDir,{recursive:!0});let e=w.join(this.cacheDir,"build-cache.json"),n={};for(let[s,o]of this.cache)n[s]=o;await Bun.write(e,JSON.stringify(n))}getHash(e,n){let s=R.statSync(e),o=`${this.salt}|${e}:${s.mtimeMs}`;for(let r of n)if(R.existsSync(r)){let u=R.statSync(r);o+=`:${r}:${u.mtimeMs}`}let c=0;for(let r=0;r<o.length;r++){let u=o.charCodeAt(r);c=(c<<5)-c+u,c=c&c}return Math.abs(c).toString(36)}get(e,n){let s=this.cache.get(e);if(!s)return null;let o=wt(n).some((u)=>R.existsSync(u)),c=[n,...s.dependencies??[]].some((u)=>u.endsWith(".stx")&&R.existsSync(u)&&Os(R.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||c)return this.cache.delete(e),null;let r=this.getHash(n,s.dependencies??[]);if(s.hash!==r)return this.cache.delete(e),null;return s.html}set(e,n,s,o){let c=this.getHash(n,s);this.cache.set(e,{hash:c,html:o,generatedAt:Date.now(),dependencies:s})}}class mt{cacheDir;constructor(e){this.cacheDir=e}getFilePath(e){let n=e.replace(/[^a-zA-Z0-9]/g,"_")+".json";return w.join(this.cacheDir,"isr",n)}async get(e){let n=this.getFilePath(e);if(!await Bun.file(n).exists())return null;try{return JSON.parse(await Bun.file(n).text())}catch{return null}}async set(e,n){let s=this.getFilePath(e);await R.promises.mkdir(w.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(n))}async invalidate(e){let n=this.getFilePath(e);if(await Bun.file(n).exists())await R.promises.unlink(n)}async invalidatePattern(e){let n=w.join(this.cacheDir,"isr");if(!R.existsSync(n))return;let s=await R.promises.readdir(n);for(let o of s){let c=o.replace(/_/g,"/").replace(".json","");if(e.test(c))await R.promises.unlink(w.join(n,o))}}async needsRevalidation(e){let n=await this.get(e);if(!n)return!0;return Date.now()>n.revalidateAfter}}async function _t(e){let n=[];if(!e.isDynamic)n.push({url:e.pattern,params:{}});else{let s=await ft(e.filePath);if(s.kind==="error")throw Error(`getStaticPaths ${s.phase} failed for ${e.pattern} (${e.filePath}): ${s.error.message}`,{cause:s.error});if(s.kind==="absent")return console.warn(`Warning: Dynamic route ${e.pattern} (${e.filePath}) has no getStaticPaths`),n;let o=s.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${e.pattern} (${e.filePath})`),n;for(let c of o.paths){let r=e.pattern;for(let[u,g]of Object.entries(c.params))r=r.replace(`:${u}`,g).replace(`:${u}*`,g);n.push({url:r,params:c.params,props:c.props,revalidate:c.revalidate})}}return n}function wt(e){return[e.replace(/\.stx$/,".data.ts"),e.replace(/\.stx$/,".data.js"),e+".data.ts",e+".data.js"]}async function Mt(e){for(let n of wt(e))if(await Bun.file(n).exists())try{let s=await import(n);if(typeof s.default==="function")return await s.default();else if(typeof s.default==="object")return s.default;else if(typeof s.getData==="function")return await s.getData();else{let{default:o,...c}=s;return c}}catch(s){console.error(`Error loading data file ${n}:`,s)}return null}async function Gt(e,n,s){let o=e.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let c=o[1];if(!c.includes("getStaticProps"))return null;try{let r=c.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!r)return null;return await Function("params",`
4
4
  return (async function getStaticProps() {
5
5
  ${r[1]}
6
6
  })()
7
- `)(n)}catch(r){return console.error(`Error executing getStaticProps in ${s}:`,r),null}}function Gt(e){return/(?:^|[^\w$.])(?:export\s+)?(?:async\s+)?function\s+action\s*\(/.test(e)||/(?:^|[^\w$.])(?:export\s+)?(?:const|let|var)\s+action\s*=/.test(e)}async function yt(e,n,s={},o,c){let r=await Bun.file(e.filePath).text(),u=await _t(e.filePath),g=await Mt(r,n,e.filePath),P={...u||{},...g||{},...s,params:n,$route:{path:e.pattern,params:n}},b=new Set,p=[],k=[],C={...c,minifyClient:!0,...o.partialsDir?{partialsDir:o.partialsDir}:{},...o.componentsDir?{componentsDir:o.componentsDir}:{},debug:!1,cache:!1,autoShell:!0,onIncludeError:(E)=>{p.push(`${w.relative(process.cwd(),E.templatePath)}: ${E.message}
8
- resolved against partialsDir: ${E.partialsDir}`)},onServerScriptError:(E)=>{k.push(`${w.relative(process.cwd(),E.sourcePath)} (${E.kind}): ${E.message}`)}};if(Gt(r))console.warn(`Warning: ${e.pattern} exports a page action, which cannot run in a static build. Its form will submit to a file. Serve this route with the production server, or point the form's action at a route handler.`);let v=await i(r,P,e.filePath,C,b);for(let E of[e.filePath,...b])for(let O of Te(E))b.add(O);if(Object.keys(n).length>0){let E=`<script>if(window.stx)window.stx._rp=${JSON.stringify(n)};else window.__stx_rp=${JSON.stringify(n)};</script>`;if(v.includes("</head>"))v=f(v,E);else v=`${E}
9
- ${v}`}if(v=await Ae(v,{router:o.router}),v=await S(v),o.minify!==!1)return{html:Nt(v),dependencies:Array.from(b),includeFailures:p,serverScriptFailures:k};return{html:v,dependencies:Array.from(b),includeFailures:p,serverScriptFailures:k}}function Nt(e){let n=[],s=0,o=/(<script[^>]*>)([\s\S]*?)(<\/script>)/gi,c;while((c=o.exec(e))!==null){let u=e.slice(s,c.index);n.push(u.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><"));let g=c[1],P=c[2],b=c[3];P=tt(P).replace(/<\/script/gi,"<\\/script"),n.push(g+P+b),s=c.index+c[0].length}let r=e.slice(s);return n.push(r.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><")),n.join("").trim()}function Wt(e){let n=0;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=(n<<5)-n+o,n=n&n}return`"${Math.abs(n).toString(36)}"`}function qt(e,n,s,o){if(s?.sitemap===!1)return!0;if(/<meta[^>]+name=["']robots["'][^>]+content=["'][^"']*noindex/i.test(n))return!0;return o.some((c)=>{if(c instanceof RegExp)return c.test(e);return c.endsWith("/")?e===c.slice(0,-1)||e.startsWith(c):e===c})}function Jt(e,n){return`<?xml version="1.0" encoding="UTF-8"?>
7
+ `)(n)}catch(r){return console.error(`Error executing getStaticProps in ${s}:`,r),null}}function Nt(e){return/(?:^|[^\w$.])(?:export\s+)?(?:async\s+)?function\s+action\s*\(/.test(e)||/(?:^|[^\w$.])(?:export\s+)?(?:const|let|var)\s+action\s*=/.test(e)}async function yt(e,n,s={},o,c){let r=await Bun.file(e.filePath).text(),u=await Mt(e.filePath),g=await Gt(r,n,e.filePath),P={...u||{},...g||{},...s,params:n,$route:{path:e.pattern,params:n}},b=new Set,p=[],k=[],C={...c,minifyClient:!0,...o.partialsDir?{partialsDir:o.partialsDir}:{},...o.componentsDir?{componentsDir:o.componentsDir}:{},debug:!1,cache:!1,autoShell:!0,onIncludeError:(E)=>{p.push(`${w.relative(process.cwd(),E.templatePath)}: ${E.message}
8
+ resolved against partialsDir: ${E.partialsDir}`)},onServerScriptError:(E)=>{k.push(`${w.relative(process.cwd(),E.sourcePath)} (${E.kind}): ${E.message}`)}};if(Nt(r))console.warn(`Warning: ${e.pattern} exports a page action, which cannot run in a static build. Its form will submit to a file. Serve this route with the production server, or point the form's action at a route handler.`);let v=await i(r,P,e.filePath,C,b);for(let E of[e.filePath,...b])for(let O of $e(E))b.add(O);if(Object.keys(n).length>0){let E=`<script>if(window.stx)window.stx._rp=${JSON.stringify(n)};else window.__stx_rp=${JSON.stringify(n)};</script>`;if(v.includes("</head>"))v=f(v,E);else v=`${E}
9
+ ${v}`}if(v=await Pe(v,{router:o.router}),v=await S(v),o.minify!==!1)return{html:Wt(v),dependencies:Array.from(b),includeFailures:p,serverScriptFailures:k};return{html:v,dependencies:Array.from(b),includeFailures:p,serverScriptFailures:k}}function Wt(e){let n=[],s=0,o=/(<script[^>]*>)([\s\S]*?)(<\/script>)/gi,c;while((c=o.exec(e))!==null){let u=e.slice(s,c.index);n.push(u.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><"));let g=c[1],P=c[2],b=c[3];P=rt(P).replace(/<\/script/gi,"<\\/script"),n.push(g+P+b),s=c.index+c[0].length}let r=e.slice(s);return n.push(r.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><")),n.join("").trim()}function qt(e){let n=0;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=(n<<5)-n+o,n=n&n}return`"${Math.abs(n).toString(36)}"`}function Jt(e,n,s,o){if(s?.sitemap===!1)return!0;if(/<meta[^>]+name=["']robots["'][^>]+content=["'][^"']*noindex/i.test(n))return!0;return o.some((c)=>{if(c instanceof RegExp)return c.test(e);return c.endsWith("/")?e===c.slice(0,-1)||e.startsWith(c):e===c})}function Vt(e,n){return`<?xml version="1.0" encoding="UTF-8"?>
10
10
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
11
11
  ${e.map((o)=>{let c=new URL(o.loc,n).href,r=` <url>
12
12
  <loc>${T(c)}</loc>`;if(o.lastmod)r+=`
@@ -36,13 +36,13 @@ ${e.map((o)=>{let c=new URL(o.loc,n).href,r=` <url>
36
36
  ${s.join(`
37
37
  `)}
38
38
  </channel>
39
- </rss>`}async function Xt(e={}){let n=Date.now();hn();let s=await a(process.cwd()),o=s.build||{},c=await gt({explicit:e.domain||o.domain,stxConfig:s});if(c.source==="fallback"&&(e.sitemap??o.sitemap??!0))console.warn(pt());let r={router:e.router??s?.router??{},pagesDir:e.pagesDir||o.pagesDir||"pages",outputDir:e.outputDir||o.outputDir||"dist",baseUrl:e.baseUrl||o.baseUrl||"/",domain:c.url,revalidate:e.revalidate??o.revalidate??!1,sitemap:e.sitemap??o.sitemap??!0,sitemapExclude:e.sitemapExclude||o.sitemapExclude||[],robots:e.robots??o.robots??!0,rss:e.rss??o.rss??!1,concurrency:e.concurrency||o.concurrency||10,cache:e.cache??o.cache??!0,cacheDir:e.cacheDir||o.cacheDir||l(process.cwd(),"ssg-cache"),contentLoaders:e.contentLoaders||[],hooks:e.hooks||{},minify:e.minify??o.minify??!0,generate404:e.generate404??o.generate404??!0,publicDir:e.publicDir||o.publicDir||"public",trailingSlash:e.trailingSlash??o.trailingSlash??!1,cleanOutput:e.cleanOutput??o.cleanOutput??!0,cacheSalt:e.cacheSalt??"",partialsDir:e.partialsDir||s?.partialsDir||"",componentsDir:e.componentsDir||s?.componentsDir||"",failOnIncludeError:e.failOnIncludeError??!0,failOnServerScriptError:e.failOnServerScriptError??!0,chunkIslands:e.chunkIslands===!0,prefetchIslands:e.prefetchIslands===!0,integrityIslands:e.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,P=0,b={},p={};await r.hooks.onBuildStart?.();try{if(r.cleanOutput&&R.existsSync(r.outputDir))await R.promises.rm(r.outputDir,{recursive:!0});await R.promises.mkdir(r.outputDir,{recursive:!0});let C=r.cacheSalt;if(!C){let{resolveUserCssConfig:d,fingerprintConfig:y}=await import("./chunk-gfz0czma.js");try{C=y(await d(process.cwd()))}catch{}}let{prepareImageDelivery:v}=await import("./chunk-9bcrr81g.js"),E=await v(r.publicDir,r.outputDir);if(E.count>0)console.log(`Optimized ${E.count} image(s) for responsive delivery`),C=[C,E.fingerprint].filter(Boolean).join(":");let O=new ht(r.cacheDir,C);if(r.cache)await O.load();try{let{generateCss:d}=await import("./chunk-gfz0czma.js");await d('<div class="bg-black"></div>')}catch{}Lt();let St=s?.routeMiddleware?.dir||"middleware";await Bt(process.cwd(),St);let K=jt();if(K.length>0)console.log(`Loaded ${K.length} middleware: ${K.join(", ")}`);let xt=s?.routeMiddleware?.global||[];Cc(s?.layoutsDir,l(process.cwd()));let Q=re(".",{pagesDir:r.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${Q.length} routes`);let U=[];for(let d of Q)try{let y=await Ut(d);for(let D of y)U.push({route:d,url:D.url,params:D.params,props:D.props,revalidate:D.revalidate??r.revalidate})}catch(y){let D=y instanceof Error?y:Error(String(y));u.failedCount++,u.errors.push({route:d.pattern,error:D}),await r.hooks.onError?.(D,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,D)}u.totalPages=U.length+u.failedCount,console.log(`Generating ${U.length} pages...`);let M=[],et=[];for(let d=0;d<U.length;d+=r.concurrency)et.push(U.slice(d,d+r.concurrency));for(let d of et)await Promise.all(d.map(async(y)=>{let{route:D,url:m,params:G,props:bt,revalidate:it}=y;try{await r.hooks.onPageStart?.(m);let H=await Bun.file(D.filePath).text(),A=Qt(H),vt=A?.middleware?Array.isArray(A.middleware)?A.middleware:[A.middleware]:[],st=[...xt,...vt];if(st.length>0){let j=Ft(m,G,A||{}),z=zt(j,null,void 0,{isServer:!0}),F=await Ht(st,z);if(F.redirect){let I=typeof F.redirect==="string"?F.redirect:F.redirect.path||F.redirect,W=te(String(I),m),L=ee(m,r);await R.promises.mkdir(w.dirname(L),{recursive:!0}),await Bun.write(L,W),u.successCount++,u.pages.push({route:m,outputPath:L,size:Buffer.byteLength(W),cached:!1}),M.push({loc:m,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${m} \u2192 redirect to ${I}`);return}if(F.abort){let I=typeof F.abort==="string"?F.abort:F.abort?.error?.message||"aborted";console.warn(` \u21B3 ${m} \u2014 middleware aborted: ${I}`);return}}let at=A?.validate;if(typeof at==="function")try{if(!await at({params:G})){console.warn(`Validation failed for ${m}, skipping...`);return}}catch{}let B=null,ot=!1;if(r.cache){if(B=O.get(m,D.filePath),B)ot=!0,u.cachedCount++}if(!B){let j=await yt(D,G,bt,r,s);if(B=j.html,r.failOnIncludeError&&j.includeFailures.length>0)throw Error(`${j.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
39
+ </rss>`}async function Xt(e={}){let n=Date.now();hn();let s=await a(process.cwd()),o=s.build||{},c=await gt({explicit:e.domain||o.domain,stxConfig:s});if(c.source==="fallback"&&(e.sitemap??o.sitemap??!0))console.warn(pt());let r={router:e.router??s?.router??{},pagesDir:e.pagesDir||o.pagesDir||"pages",outputDir:e.outputDir||o.outputDir||"dist",baseUrl:e.baseUrl||o.baseUrl||"/",domain:c.url,revalidate:e.revalidate??o.revalidate??!1,sitemap:e.sitemap??o.sitemap??!0,sitemapExclude:e.sitemapExclude||o.sitemapExclude||[],robots:e.robots??o.robots??!0,rss:e.rss??o.rss??!1,concurrency:e.concurrency||o.concurrency||10,cache:e.cache??o.cache??!0,cacheDir:e.cacheDir||o.cacheDir||l(process.cwd(),"ssg-cache"),contentLoaders:e.contentLoaders||[],hooks:e.hooks||{},minify:e.minify??o.minify??!0,generate404:e.generate404??o.generate404??!0,publicDir:e.publicDir||o.publicDir||"public",trailingSlash:e.trailingSlash??o.trailingSlash??!1,cleanOutput:e.cleanOutput??o.cleanOutput??!0,cacheSalt:e.cacheSalt??"",partialsDir:e.partialsDir||s?.partialsDir||"",componentsDir:e.componentsDir||s?.componentsDir||"",failOnIncludeError:e.failOnIncludeError??!0,failOnServerScriptError:e.failOnServerScriptError??!0,chunkIslands:e.chunkIslands===!0,prefetchIslands:e.prefetchIslands===!0,integrityIslands:e.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,P=0,b={},p={};await r.hooks.onBuildStart?.();try{if(r.cleanOutput&&R.existsSync(r.outputDir))await R.promises.rm(r.outputDir,{recursive:!0});await R.promises.mkdir(r.outputDir,{recursive:!0});let C=r.cacheSalt;if(!C){let{resolveUserCssConfig:d,fingerprintConfig:y}=await import("./chunk-hg4vfrxr.js");try{C=y(await d(process.cwd()))}catch{}}let{prepareImageDelivery:v}=await import("./chunk-3qneemwh.js"),E=await v(r.publicDir,r.outputDir);if(E.count>0)console.log(`Optimized ${E.count} image(s) for responsive delivery`),C=[C,E.fingerprint].filter(Boolean).join(":");let O=new ht(r.cacheDir,C);if(r.cache)await O.load();try{let{generateCss:d}=await import("./chunk-hg4vfrxr.js");await d('<div class="bg-black"></div>')}catch{}Lt();let St=s?.routeMiddleware?.dir||"middleware";await Bt(process.cwd(),St);let K=jt();if(K.length>0)console.log(`Loaded ${K.length} middleware: ${K.join(", ")}`);let xt=s?.routeMiddleware?.global||[];$c(s?.layoutsDir,l(process.cwd()));let Q=re(".",{pagesDir:r.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${Q.length} routes`);let U=[];for(let d of Q)try{let y=await _t(d);for(let D of y)U.push({route:d,url:D.url,params:D.params,props:D.props,revalidate:D.revalidate??r.revalidate})}catch(y){let D=y instanceof Error?y:Error(String(y));u.failedCount++,u.errors.push({route:d.pattern,error:D}),await r.hooks.onError?.(D,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,D)}u.totalPages=U.length+u.failedCount,console.log(`Generating ${U.length} pages...`);let M=[],tt=[];for(let d=0;d<U.length;d+=r.concurrency)tt.push(U.slice(d,d+r.concurrency));for(let d of tt)await Promise.all(d.map(async(y)=>{let{route:D,url:m,params:G,props:bt,revalidate:it}=y;try{await r.hooks.onPageStart?.(m);let H=await Bun.file(D.filePath).text(),A=Qt(H),vt=A?.middleware?Array.isArray(A.middleware)?A.middleware:[A.middleware]:[],st=[...xt,...vt];if(st.length>0){let j=Ft(m,G,A||{}),z=zt(j,null,void 0,{isServer:!0}),F=await Ht(st,z);if(F.redirect){let I=typeof F.redirect==="string"?F.redirect:F.redirect.path||F.redirect,W=te(String(I),m),L=ee(m,r);await R.promises.mkdir(w.dirname(L),{recursive:!0}),await Bun.write(L,W),u.successCount++,u.pages.push({route:m,outputPath:L,size:Buffer.byteLength(W),cached:!1}),M.push({loc:m,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${m} \u2192 redirect to ${I}`);return}if(F.abort){let I=typeof F.abort==="string"?F.abort:F.abort?.error?.message||"aborted";console.warn(` \u21B3 ${m} \u2014 middleware aborted: ${I}`);return}}let at=A?.validate;if(typeof at==="function")try{if(!await at({params:G})){console.warn(`Validation failed for ${m}, skipping...`);return}}catch{}let B=null,ot=!1;if(r.cache){if(B=O.get(m,D.filePath),B)ot=!0,u.cachedCount++}if(!B){let j=await yt(D,G,bt,r,s);if(B=j.html,r.failOnIncludeError&&j.includeFailures.length>0)throw Error(`${j.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
40
40
  ${j.includeFailures.join(`
41
41
  `)}
42
42
  Set ssg.failOnIncludeError to false to build anyway.`);if(r.failOnServerScriptError&&j.serverScriptFailures.length>0)throw Error(`${j.serverScriptFailures.length} <script server> block(s) failed, so this page would have shipped with the content they produce missing:
43
43
  ${j.serverScriptFailures.join(`
44
44
  `)}
45
- Set ssg.failOnServerScriptError to false to build anyway.`);if(r.cache)O.set(m,D.filePath,j.dependencies,B)}let N;if(r.trailingSlash)N=w.join(r.outputDir,m,"index.html");else N=m==="/"?w.join(r.outputDir,"index.html"):w.join(r.outputDir,`${m}.html`);if(r.chunkIslands){let{html:j,chunks:z}=lt(B,{integrity:r.integrityIslands,minify:r.minify});if(z.length>0){let F=w.join(r.outputDir,"_stx","islands");await R.promises.mkdir(F,{recursive:!0});for(let I of z){let W=w.join(F,`${I.hash}.js`);if(!await Bun.file(W).exists())await Bun.write(W,I.code);if(!g.has(I.hash)){g.add(I.hash);let L=Buffer.byteLength(I.code,"utf8");P+=L,b[I.hash]={bytes:L,file:`/_stx/islands/${I.hash}.js`}}}if(p[m]=z.map((I)=>I.hash),B=j,r.prefetchIslands)B=ut(B)}}if(await R.promises.mkdir(w.dirname(N),{recursive:!0}),await Bun.write(N,B),!qt(m,B,A,r.sitemapExclude))M.push({loc:m,lastmod:new Date().toISOString().split("T")[0],priority:m==="/"?1:0.8});let ct={route:m,outputPath:N,size:Buffer.byteLength(B,"utf8"),cached:ot};if(it!==!1)ct.revalidateAt=Date.now()+it*1000;u.pages.push(ct),u.successCount++,await r.hooks.onPageEnd?.(m,B)}catch(H){u.failedCount++,u.errors.push({route:m,error:H}),await r.hooks.onError?.(H,m),console.error(`Error generating ${m}:`,H)}}));let rt=mn();if(rt.length>0){let d=rt.map((y)=>`${y.filePath}: ${y.message}`).join(`
45
+ Set ssg.failOnServerScriptError to false to build anyway.`);if(r.cache)O.set(m,D.filePath,j.dependencies,B)}let N;if(r.trailingSlash)N=w.join(r.outputDir,m,"index.html");else N=m==="/"?w.join(r.outputDir,"index.html"):w.join(r.outputDir,`${m}.html`);if(r.chunkIslands){let{html:j,chunks:z}=lt(B,{integrity:r.integrityIslands,minify:r.minify});if(z.length>0){let F=w.join(r.outputDir,"_stx","islands");await R.promises.mkdir(F,{recursive:!0});for(let I of z){let W=w.join(F,`${I.hash}.js`);if(!await Bun.file(W).exists())await Bun.write(W,I.code);if(!g.has(I.hash)){g.add(I.hash);let L=Buffer.byteLength(I.code,"utf8");P+=L,b[I.hash]={bytes:L,file:`/_stx/islands/${I.hash}.js`}}}if(p[m]=z.map((I)=>I.hash),B=j,r.prefetchIslands)B=ut(B)}}if(await R.promises.mkdir(w.dirname(N),{recursive:!0}),await Bun.write(N,B),!Jt(m,B,A,r.sitemapExclude))M.push({loc:m,lastmod:new Date().toISOString().split("T")[0],priority:m==="/"?1:0.8});let ct={route:m,outputPath:N,size:Buffer.byteLength(B,"utf8"),cached:ot};if(it!==!1)ct.revalidateAt=Date.now()+it*1000;u.pages.push(ct),u.successCount++,await r.hooks.onPageEnd?.(m,B)}catch(H){u.failedCount++,u.errors.push({route:m,error:H}),await r.hooks.onError?.(H,m),console.error(`Error generating ${m}:`,H)}}));let et=mn();if(et.length>0){let d=et.map((y)=>`${y.filePath}: ${y.message}`).join(`
46
46
  `);throw Error(`Client script bundling failed:
47
47
  ${d}`)}if(r.cache)await O.save();if(r.generate404){let d=w.join(r.pagesDir,"404.stx");if(await Bun.file(d).exists()){let y=new Set,D={...s,minifyClient:!0,debug:!1,cache:!1},m=await i(await Bun.file(d).text(),{},d,D,y);await Bun.write(w.join(r.outputDir,"404.html"),m)}else await Bun.write(w.join(r.outputDir,"404.html"),`<!DOCTYPE html>
48
48
  <html lang="en">
@@ -65,7 +65,7 @@ ${d}`)}if(r.cache)await O.save();if(r.generate404){let d=w.join(r.pagesDir,"404.
65
65
  <a href="/">Go home</a>
66
66
  </div>
67
67
  </body>
68
- </html>`)}for(let d of[500]){let y=w.join(r.pagesDir,`${d}.stx`);if(await Bun.file(y).exists()){let D=new Set,m={...s,minifyClient:!0,debug:!1,cache:!1},G=await i(await Bun.file(y).text(),{},y,m,D);await Bun.write(w.join(r.outputDir,`${d}.html`),G)}}let X=w.join(r.pagesDir,"error.stx");if(await Bun.file(X).exists()){let d=new Set,y={...s,minifyClient:!0,debug:!1,cache:!1},D=await i(await Bun.file(X).text(),{},X,y,d);await Bun.write(w.join(r.outputDir,"error.html"),D)}if(r.sitemap&&M.length>0){let d=Jt(M,r.domain),y=w.join(r.outputDir,"sitemap.xml");await Bun.write(y,d),u.sitemapPath=y,console.log(`Generated sitemap.xml with ${M.length} URLs`)}if(r.robots!==!1){let d=typeof r.robots==="object"?r.robots:{},y=[...r.sitemapExclude.filter((m)=>typeof m==="string"),...d.disallow||[]],D=Us({rules:[{userAgent:d.userAgent||"*",allow:d.allow||["/"],...y.length>0?{disallow:y}:{}}],...d.sitemap!==!1&&u.sitemapPath?{sitemap:new URL("/sitemap.xml",r.domain).href}:{}});await Bun.write(w.join(r.outputDir,"robots.txt"),D),console.log("Generated robots.txt")}if(r.rss){let d=typeof r.rss==="object"?r.rss:{title:"Site Feed",description:"Latest updates",link:r.domain},y=[];if(d.getItems)y=await d.getItems();let D=Kt(d,y),m=w.join(r.outputDir,"rss.xml");await Bun.write(m,D),u.rssPath=m,console.log(`Generated rss.xml with ${y.length} items`)}let q=kc(r.outputDir);if(q.assets>0)console.log(`Externalized ${q.assets} asset(s) from ${q.pages} page(s) (${(q.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let J=_c(r.outputDir);if(J.assets>0)console.log(`Externalized ${J.assets} repeated asset(s) from ${J.pages} page(s) (${(J.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(r.publicDir&&R.existsSync(r.publicDir))await Z(r.publicDir,r.outputDir),console.log(`Copied public assets from ${r.publicDir}`);let nt=gr();if(nt)await Z(nt,w.join(r.outputDir,fr)),console.log(`Copied assets from ${fn}`)}catch(C){throw await r.hooks.onError?.(C),C}if(u.buildTime=Date.now()-n,g.size>0){u.islandChunks={count:g.size,totalBytes:P};let C={generatedChunks:g.size,totalBytes:P,chunks:b,pages:p};await Bun.write(w.join(r.outputDir,"_stx","islands-manifest.json"),JSON.stringify(C,null,2))}await r.hooks.onBuildEnd?.(u);let k=u.islandChunks?`
68
+ </html>`)}for(let d of[500]){let y=w.join(r.pagesDir,`${d}.stx`);if(await Bun.file(y).exists()){let D=new Set,m={...s,minifyClient:!0,debug:!1,cache:!1},G=await i(await Bun.file(y).text(),{},y,m,D);await Bun.write(w.join(r.outputDir,`${d}.html`),G)}}let X=w.join(r.pagesDir,"error.stx");if(await Bun.file(X).exists()){let d=new Set,y={...s,minifyClient:!0,debug:!1,cache:!1},D=await i(await Bun.file(X).text(),{},X,y,d);await Bun.write(w.join(r.outputDir,"error.html"),D)}if(r.sitemap&&M.length>0){let d=Vt(M,r.domain),y=w.join(r.outputDir,"sitemap.xml");await Bun.write(y,d),u.sitemapPath=y,console.log(`Generated sitemap.xml with ${M.length} URLs`)}if(r.robots!==!1){let d=typeof r.robots==="object"?r.robots:{},y=[...r.sitemapExclude.filter((m)=>typeof m==="string"),...d.disallow||[]],D=qs({rules:[{userAgent:d.userAgent||"*",allow:d.allow||["/"],...y.length>0?{disallow:y}:{}}],...d.sitemap!==!1&&u.sitemapPath?{sitemap:new URL("/sitemap.xml",r.domain).href}:{}});await Bun.write(w.join(r.outputDir,"robots.txt"),D),console.log("Generated robots.txt")}if(r.rss){let d=typeof r.rss==="object"?r.rss:{title:"Site Feed",description:"Latest updates",link:r.domain},y=[];if(d.getItems)y=await d.getItems();let D=Kt(d,y),m=w.join(r.outputDir,"rss.xml");await Bun.write(m,D),u.rssPath=m,console.log(`Generated rss.xml with ${y.length} items`)}let q=Ec(r.outputDir);if(q.assets>0)console.log(`Externalized ${q.assets} asset(s) from ${q.pages} page(s) (${(q.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let J=Tc(r.outputDir);if(J.assets>0)console.log(`Externalized ${J.assets} repeated asset(s) from ${J.pages} page(s) (${(J.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(r.publicDir&&R.existsSync(r.publicDir))await Z(r.publicDir,r.outputDir),console.log(`Copied public assets from ${r.publicDir}`);let nt=mr();if(nt)await Z(nt,w.join(r.outputDir,gr)),console.log(`Copied assets from ${fn}`)}catch(C){throw await r.hooks.onError?.(C),C}if(u.buildTime=Date.now()-n,g.size>0){u.islandChunks={count:g.size,totalBytes:P};let C={generatedChunks:g.size,totalBytes:P,chunks:b,pages:p};await Bun.write(w.join(r.outputDir,"_stx","islands-manifest.json"),JSON.stringify(C,null,2))}await r.hooks.onBuildEnd?.(u);let k=u.islandChunks?`
69
69
  Island chunks: ${u.islandChunks.count} (${(u.islandChunks.totalBytes/1024).toFixed(1)} KB lifted out of inline HTML)`:"";return console.log(`
70
70
  Build complete!
71
71
  Total: ${u.totalPages} pages
@@ -73,7 +73,7 @@ Build complete!
73
73
  Cached: ${u.cachedCount}
74
74
  Failed: ${u.failedCount}
75
75
  Time: ${u.buildTime}ms${k}
76
- `),u}async function Z(e,n){await R.promises.mkdir(n,{recursive:!0});let s=await R.promises.readdir(e,{withFileTypes:!0});for(let o of s){let c=w.join(e,o.name),r=w.join(n,o.name);if(o.isDirectory())await R.promises.mkdir(r,{recursive:!0}),await Z(c,r);else await R.promises.copyFile(c,r)}}function Yt(e={}){let n=e.cacheDir||l(process.cwd(),"ssg-cache"),s=new mt(n),o=e.revalidate||3600;return{async get(c){let r=await s.get(c);if(!r)return null;if(Date.now()>r.revalidateAfter)this.revalidate(c).catch(console.error);return{html:r.html,headers:{"Cache-Control":`public, max-age=${o}, stale-while-revalidate=${o*2}`,ETag:r.etag,"X-ISR-Generated":new Date(r.generatedAt).toISOString(),...r.headers}}},async revalidate(c){let u=re(".",{pagesDir:e.pagesDir||"pages"}).find((k)=>c.match(k.regex)!==null);if(!u){console.warn(`Route not found for revalidation: ${c}`);return}let g=c.match(u.regex),P={};if(g)u.params.forEach((k,C)=>{P[k]=g[C+1]});let b=await a(),{html:p}=await yt(u,P,{},e,b);await s.set(c,{html:p,generatedAt:Date.now(),revalidateAfter:Date.now()+o*1000,etag:Wt(p)}),console.log(`Revalidated: ${c}`)},async invalidate(c){if(typeof c==="string")await s.invalidate(c);else await s.invalidatePattern(c)}}}function Zt(){return{name:"markdown",extensions:[".md",".mdx"],async load(e){let n=await Bun.file(e).text(),s=n.match(/^---\n([\s\S]*?)\n---/),o={},c=n;if(s){let b=s[1];c=n.slice(s[0].length).trim();for(let p of b.split(`
76
+ `),u}async function Z(e,n){await R.promises.mkdir(n,{recursive:!0});let s=await R.promises.readdir(e,{withFileTypes:!0});for(let o of s){let c=w.join(e,o.name),r=w.join(n,o.name);if(o.isDirectory())await R.promises.mkdir(r,{recursive:!0}),await Z(c,r);else await R.promises.copyFile(c,r)}}function Yt(e={}){let n=e.cacheDir||l(process.cwd(),"ssg-cache"),s=new mt(n),o=e.revalidate||3600;return{async get(c){let r=await s.get(c);if(!r)return null;if(Date.now()>r.revalidateAfter)this.revalidate(c).catch(console.error);return{html:r.html,headers:{"Cache-Control":`public, max-age=${o}, stale-while-revalidate=${o*2}`,ETag:r.etag,"X-ISR-Generated":new Date(r.generatedAt).toISOString(),...r.headers}}},async revalidate(c){let u=re(".",{pagesDir:e.pagesDir||"pages"}).find((k)=>c.match(k.regex)!==null);if(!u){console.warn(`Route not found for revalidation: ${c}`);return}let g=c.match(u.regex),P={};if(g)u.params.forEach((k,C)=>{P[k]=g[C+1]});let b=await a(),{html:p}=await yt(u,P,{},e,b);await s.set(c,{html:p,generatedAt:Date.now(),revalidateAfter:Date.now()+o*1000,etag:qt(p)}),console.log(`Revalidated: ${c}`)},async invalidate(c){if(typeof c==="string")await s.invalidate(c);else await s.invalidatePattern(c)}}}function Zt(){return{name:"markdown",extensions:[".md",".mdx"],async load(e){let n=await Bun.file(e).text(),s=n.match(/^---\n([\s\S]*?)\n---/),o={},c=n;if(s){let b=s[1];c=n.slice(s[0].length).trim();for(let p of b.split(`
77
77
  `)){let k=p.indexOf(":");if(k>0){let C=p.slice(0,k).trim(),v=p.slice(k+1).trim();if(v==="true")v=!0;else if(v==="false")v=!1;else if(/^\d+$/.test(v))v=parseInt(v,10);else if(/^\d+\.\d+$/.test(v))v=parseFloat(v);else if(v.startsWith("[")&&v.endsWith("]"))v=v.slice(1,-1).split(",").map((E)=>E.trim().replace(/^['"]|['"]$/g,""));o[C]=v}}}let r=c.replace(/^### (.*$)/gim,"<h3>$1</h3>").replace(/^## (.*$)/gim,"<h2>$1</h2>").replace(/^# (.*$)/gim,"<h1>$1</h1>").replace(/\*\*(.*)\*\*/gim,"<strong>$1</strong>").replace(/\*(.*)\*/gim,"<em>$1</em>").replace(/`([^`]+)`/gim,"<code>$1</code>").replace(/\[([^\]]+)\]\(([^)]+)\)/gim,'<a href="$2">$1</a>').replace(/\n/gim,"<br>"),u=[],g=/<h([1-6])>([^<]+)<\/h[1-6]>/gi,P;while((P=g.exec(r))!==null){let b=parseInt(P[1],10),p=P[2],k=p.toLowerCase().replace(/[^a-z0-9]+/g,"-");u.push({id:k,text:p,level:b})}return{content:r,data:o,toc:u}}}}function Qt(e){return Pt(e)}function te(e,n){return`<!DOCTYPE html>
78
78
  <html>
79
79
  <head>
@@ -86,4 +86,4 @@ Build complete!
86
86
  <p>Redirecting to <a href="${e}">${e}</a>...</p>
87
87
  <script>window.location.replace('${e}')</script>
88
88
  </body>
89
- </html>`}function ee(e,n){if(e==="/"||e==="")return w.join(n.outputDir,"index.html");let s=e.replace(/^\/|\/$/g,"");if(n.trailingSlash)return w.join(n.outputDir,s,"index.html");return w.join(n.outputDir,`${s}.html`)}var Oe={generateStaticSite:Xt,createISRHandler:Yt,defineStaticPaths:V,createMarkdownLoader:Zt};export{Yt as createISRHandler,Zt as createMarkdownLoader,Gt as declaresPageAction,Oe as default,V as defineStaticPaths,Xt as generateStaticSite,qt as isExcludedFromSitemap};
89
+ </html>`}function ee(e,n){if(e==="/"||e==="")return w.join(n.outputDir,"index.html");let s=e.replace(/^\/|\/$/g,"");if(n.trailingSlash)return w.join(n.outputDir,s,"index.html");return w.join(n.outputDir,`${s}.html`)}var Oe={generateStaticSite:Xt,createISRHandler:Yt,defineStaticPaths:V,createMarkdownLoader:Zt};export{Yt as createISRHandler,Zt as createMarkdownLoader,Nt as declaresPageAction,Oe as default,V as defineStaticPaths,Xt as generateStaticSite,Jt as isExcludedFromSitemap};
@@ -409,6 +409,10 @@ export declare function isTemplateArtefact(position: ResolvedPosition, code: num
409
409
  * must be dropped rather than pointed at an arbitrary line.
410
410
  */
411
411
  export declare function resolvePosition(virtual: VirtualFile, line: number, column: number): ResolvedPosition | null;
412
+ /**
413
+ * The names a page's or component's own `<script client>` declares or imports.
414
+ */
415
+ export declare function clientScriptNames(html: string): Set<string>;
412
416
  /**
413
417
  * Placeholder for a server interpolation spliced into a client expression.
414
418
  *
@@ -1157,3 +1157,25 @@ export function resolvePosition(virtual, line, column) {
1157
1157
  inGuard: column <= (mapped.guardPrefixLength ?? 0)
1158
1158
  };
1159
1159
  }
1160
+ export function clientScriptNames(html) {
1161
+ const names = new Set;
1162
+ for (const match of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
1163
+ const attributes = match[1];
1164
+ if (!/\bclient\b/.test(attributes) || /\bserver\b/.test(attributes))
1165
+ continue;
1166
+ for (const name of collectTopLevelDeclarations(match[2]))
1167
+ names.add(name);
1168
+ for (const imported of match[2].matchAll(/^\s*import\s+(?:type\s+)?(?:([\w$]+)\s*,?\s*)?(?:\{([^}]*)\}|\*\s+as\s+([\w$]+))?\s*from\s/gm)) {
1169
+ if (imported[1])
1170
+ names.add(imported[1]);
1171
+ if (imported[3])
1172
+ names.add(imported[3]);
1173
+ for (const part of (imported[2] ?? "").split(",")) {
1174
+ const local = part.replace(/^\s*type\s+/, "").split(/\s+as\s+/).pop().trim();
1175
+ if (/^[A-Za-z_$][\w$]*$/.test(local))
1176
+ names.add(local);
1177
+ }
1178
+ }
1179
+ }
1180
+ return names;
1181
+ }