@stacksjs/stx 0.2.303 → 0.2.305

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 (271) hide show
  1. package/dist/api-client.d.ts +26 -0
  2. package/dist/api-client.js +22 -0
  3. package/dist/api-handler.d.ts +6 -0
  4. package/dist/api-handler.js +3 -0
  5. package/dist/app-shell.js +11 -2
  6. package/dist/application-layers.d.ts +30 -0
  7. package/dist/application-layers.js +202 -0
  8. package/dist/build.js +9 -1
  9. package/dist/{chunk-rdg1n42s.js → chunk-00rtz7nw.js} +2 -2
  10. package/dist/chunk-02hm88m5.js +2 -0
  11. package/dist/chunk-044mychj.js +2 -0
  12. package/dist/{chunk-7eea1cse.js → chunk-09zjty4k.js} +1 -1
  13. package/dist/{chunk-7nfn7nj9.js → chunk-0gz0rhvs.js} +1 -1
  14. package/dist/chunk-113y4ywy.js +2 -0
  15. package/dist/{chunk-jsfch50r.js → chunk-1c2j4eby.js} +1 -1
  16. package/dist/{chunk-2m6x8tcx.js → chunk-1jbjrc0w.js} +2 -2
  17. package/dist/{chunk-m6wz1hf5.js → chunk-2h94c5hm.js} +2 -2
  18. package/dist/{chunk-mjpqz66q.js → chunk-2ver2s2y.js} +1 -1
  19. package/dist/chunk-3eervtf9.js +2 -0
  20. package/dist/{chunk-2rp09y5j.js → chunk-4evbx7sz.js} +1 -1
  21. package/dist/chunk-4jgr954p.js +2 -0
  22. package/dist/chunk-4mrhxtn3.js +18 -0
  23. package/dist/chunk-57ea6ye2.js +2 -0
  24. package/dist/{chunk-7eg7ep8f.js → chunk-5tefa8qb.js} +2 -2
  25. package/dist/{chunk-683tfkz4.js → chunk-64djh88a.js} +1 -1
  26. package/dist/{chunk-btrmvj2y.js → chunk-695fkras.js} +1 -1
  27. package/dist/{chunk-y7dcdjav.js → chunk-6zt2y7q3.js} +2 -2
  28. package/dist/chunk-7gqbr8nr.js +2 -0
  29. package/dist/{chunk-x4prtyjs.js → chunk-7kw3grq5.js} +1 -1
  30. package/dist/chunk-7m4yhzhb.js +6 -0
  31. package/dist/{chunk-7jebw3ea.js → chunk-7skk34dh.js} +2 -2
  32. package/dist/chunk-8ee62a9q.js +2 -0
  33. package/dist/{chunk-jj6yp7gm.js → chunk-8jam44my.js} +1 -1
  34. package/dist/chunk-8z0n5mtg.js +2 -0
  35. package/dist/chunk-92zzryxw.js +2 -0
  36. package/dist/{chunk-3bc8bqw2.js → chunk-9368t9jm.js} +1 -1
  37. package/dist/{chunk-3jwmcf4k.js → chunk-9c835qjn.js} +1 -1
  38. package/dist/chunk-9nf3hgvq.js +7 -0
  39. package/dist/chunk-a87jqtmd.js +2 -0
  40. package/dist/{chunk-5d9cy7a0.js → chunk-awj7yy37.js} +1 -1
  41. package/dist/chunk-b4xwbh8a.js +2 -0
  42. package/dist/{chunk-1evf3bdg.js → chunk-bd9wrcq1.js} +205 -19
  43. package/dist/chunk-bezqaxqt.js +2 -0
  44. package/dist/chunk-bk95q0bw.js +12 -0
  45. package/dist/{chunk-q25mr70f.js → chunk-c131k3mt.js} +1 -1
  46. package/dist/chunk-c1ae6afc.js +30 -0
  47. package/dist/{chunk-6btbgxh1.js → chunk-c79nfdyj.js} +1 -1
  48. package/dist/{chunk-cfgpk6bh.js → chunk-cbgh359m.js} +1 -1
  49. package/dist/{chunk-weqpt9nt.js → chunk-cr8v8k53.js} +1 -1
  50. package/dist/{chunk-p3wwm6k4.js → chunk-d19tvdvv.js} +1 -1
  51. package/dist/{chunk-nb1zdh1y.js → chunk-d3srvh3q.js} +1 -1
  52. package/dist/{chunk-rqrfq305.js → chunk-d57gb0v2.js} +1 -1
  53. package/dist/{chunk-1xyhk1wr.js → chunk-d5cqnwdd.js} +1 -1
  54. package/dist/chunk-dgpjxmhs.js +2 -0
  55. package/dist/chunk-dvvx1wny.js +3 -0
  56. package/dist/chunk-eans1ct0.js +43 -0
  57. package/dist/{chunk-ctz53mbz.js → chunk-ej8mv2k6.js} +1 -1
  58. package/dist/{chunk-zn6xcc0a.js → chunk-ek8cgwcg.js} +2 -2
  59. package/dist/{chunk-dv3z80gt.js → chunk-env6knrs.js} +1 -1
  60. package/dist/chunk-er848s6f.js +2 -0
  61. package/dist/{chunk-rf10fkrf.js → chunk-ess2pgt5.js} +1 -1
  62. package/dist/chunk-f1cgyd2h.js +3 -0
  63. package/dist/{chunk-hp3rjwnb.js → chunk-f325jzsk.js} +2 -2
  64. package/dist/{chunk-0tbgvp70.js → chunk-fczfdsab.js} +21 -5
  65. package/dist/chunk-fg0nf7cv.js +3754 -0
  66. package/dist/{chunk-xdq52pwj.js → chunk-fp7ms6e7.js} +1 -1
  67. package/dist/{chunk-qg6pg6ze.js → chunk-fqq5k9ve.js} +1 -1
  68. package/dist/{chunk-5t0w4h6z.js → chunk-g912mb7x.js} +1 -1
  69. package/dist/chunk-g97atepq.js +2 -0
  70. package/dist/{chunk-wj25qt72.js → chunk-gbwhbasw.js} +1 -1
  71. package/dist/chunk-gecmqs6p.js +17 -0
  72. package/dist/{chunk-cratkhhb.js → chunk-ghw5p1yk.js} +1 -1
  73. package/dist/{chunk-f0g2q51j.js → chunk-gssbag3e.js} +1 -1
  74. package/dist/{chunk-c9vhtjtr.js → chunk-gt8ja700.js} +2 -2
  75. package/dist/chunk-hftqr8ej.js +2 -0
  76. package/dist/{chunk-ftvmk1nj.js → chunk-hg2afckn.js} +1 -1
  77. package/dist/{chunk-hhnzd03k.js → chunk-hrcxfvh1.js} +1 -1
  78. package/dist/chunk-hzav4hyd.js +2 -0
  79. package/dist/{chunk-29gjwajm.js → chunk-jfzfrmzy.js} +1 -1
  80. package/dist/{chunk-ddqkj56r.js → chunk-jp2f8yzw.js} +1 -1
  81. package/dist/{chunk-ry3a2674.js → chunk-jsg1rthc.js} +1 -1
  82. package/dist/chunk-jxxv18a0.js +5 -0
  83. package/dist/{chunk-95t0k8cz.js → chunk-k23r03qj.js} +1 -1
  84. package/dist/{chunk-6b4k8fay.js → chunk-kxavsh3m.js} +1 -1
  85. package/dist/{chunk-4tffxxpd.js → chunk-m31n9pkr.js} +1 -1
  86. package/dist/{chunk-fj6fbqgb.js → chunk-m3a20mmb.js} +1 -1
  87. package/dist/chunk-m537zgay.js +2 -0
  88. package/dist/chunk-m8n0s4tk.js +28 -0
  89. package/dist/{chunk-j21csh4j.js → chunk-mbmqpaq1.js} +1 -1
  90. package/dist/{chunk-whm6bybj.js → chunk-mv5fdcwc.js} +3 -3
  91. package/dist/{chunk-y9nyqcha.js → chunk-mwh3ymwc.js} +1 -1
  92. package/dist/{chunk-51g95yts.js → chunk-mygq61f5.js} +2 -2
  93. package/dist/chunk-n99ajrwv.js +2 -0
  94. package/dist/chunk-ncrfrp95.js +2 -0
  95. package/dist/chunk-nqq7y7m9.js +3 -0
  96. package/dist/chunk-nws8fbde.js +2 -0
  97. package/dist/{chunk-q6xfyasj.js → chunk-pcvayb2f.js} +1 -1
  98. package/dist/chunk-phcvbqzn.js +2 -0
  99. package/dist/{chunk-nvxv2wxv.js → chunk-ppyz9623.js} +1 -1
  100. package/dist/{chunk-jb2r696a.js → chunk-qev11kg8.js} +1 -1
  101. package/dist/{chunk-6njgsr6w.js → chunk-qeyw5za9.js} +1 -1
  102. package/dist/chunk-qpzxgkc5.js +2 -0
  103. package/dist/chunk-qt2dmyq5.js +2 -0
  104. package/dist/chunk-r2k2sewg.js +2 -0
  105. package/dist/chunk-r808fpme.js +2 -0
  106. package/dist/chunk-rrankpmj.js +3 -0
  107. package/dist/chunk-rvyfyc43.js +2 -0
  108. package/dist/{chunk-3p0zgfgz.js → chunk-rzevgemj.js} +2 -2
  109. package/dist/{chunk-f62fh1fw.js → chunk-s3dnk3gc.js} +2 -2
  110. package/dist/{chunk-aa6kt84c.js → chunk-sart9ehj.js} +1 -1
  111. package/dist/chunk-sen2cxqm.js +2 -0
  112. package/dist/{chunk-jptkc64r.js → chunk-t3qb9s6s.js} +2 -2
  113. package/dist/{chunk-w8yac9xp.js → chunk-t41aaehf.js} +1 -1
  114. package/dist/{chunk-qjkzpd68.js → chunk-t51mwjyq.js} +1 -1
  115. package/dist/chunk-t8fqjb25.js +19 -0
  116. package/dist/{chunk-c6b5nqct.js → chunk-ta398s3d.js} +287 -352
  117. package/dist/chunk-tc6gqeha.js +2 -0
  118. package/dist/chunk-tt4r8q4v.js +2 -0
  119. package/dist/chunk-twbw18vs.js +2 -0
  120. package/dist/{chunk-6rzwef28.js → chunk-vd5xvsnv.js} +1 -1
  121. package/dist/chunk-w6d91maa.js +4 -0
  122. package/dist/{chunk-dcxtrqfy.js → chunk-wfffa8zm.js} +1 -1
  123. package/dist/chunk-wjdfhfj6.js +2 -0
  124. package/dist/chunk-wnamjw6n.js +3 -0
  125. package/dist/{chunk-22p0ezj6.js → chunk-wx13qmaw.js} +1 -1
  126. package/dist/chunk-x10mrzgp.js +2 -0
  127. package/dist/chunk-xd5ahrtn.js +2 -0
  128. package/dist/chunk-xsfwcj6x.js +2 -0
  129. package/dist/{chunk-91007tan.js → chunk-xwxdwqn9.js} +1 -1
  130. package/dist/{chunk-634gaa9d.js → chunk-xz3evxqp.js} +1 -1
  131. package/dist/chunk-xzgvcrnz.js +2 -0
  132. package/dist/{chunk-v8474ah4.js → chunk-y4nzmkea.js} +1 -1
  133. package/dist/{chunk-6w8fa3b8.js → chunk-ya5m5vbn.js} +1 -1
  134. package/dist/chunk-yd7jyyr7.js +2 -0
  135. package/dist/{chunk-ew6tr7b1.js → chunk-ydgdq45a.js} +2 -2
  136. package/dist/{chunk-ps20v1ah.js → chunk-ym3r8ktq.js} +1 -1
  137. package/dist/chunk-yyyxt326.js +2 -0
  138. package/dist/{chunk-yfwyvh02.js → chunk-ze44hhxb.js} +2 -2
  139. package/dist/{chunk-mdf3jbe6.js → chunk-zhcs8m2a.js} +2 -2
  140. package/dist/{chunk-f9d27v49.js → chunk-zs5y7xnt.js} +1 -1
  141. package/dist/chunk-zs95z9tf.js +2 -0
  142. package/dist/cli.js +14 -14
  143. package/dist/client-script-bundler.js +22 -11
  144. package/dist/component-contract-checks.d.ts +19 -0
  145. package/dist/component-contract-checks.js +147 -0
  146. package/dist/component-contract.d.ts +20 -0
  147. package/dist/component-contract.js +108 -0
  148. package/dist/component-model.d.ts +29 -0
  149. package/dist/component-model.js +59 -0
  150. package/dist/component-registry.js +7 -64
  151. package/dist/component-renderer.d.ts +1 -26
  152. package/dist/component-renderer.js +4 -239
  153. package/dist/component-resolution.d.ts +21 -0
  154. package/dist/component-resolution.js +118 -0
  155. package/dist/component-tags.d.ts +9 -0
  156. package/dist/component-tags.js +174 -0
  157. package/dist/composable-loader.d.ts +2 -13
  158. package/dist/composable-loader.js +15 -26
  159. package/dist/composables/index.d.ts +1 -0
  160. package/dist/composables/index.js +1 -0
  161. package/dist/composables/use-fetch.d.ts +117 -42
  162. package/dist/composables/use-fetch.js +47 -4
  163. package/dist/composition-api.d.ts +43 -19
  164. package/dist/config.d.ts +1 -1
  165. package/dist/config.js +46 -4
  166. package/dist/craft-entry.js +1 -1
  167. package/dist/craft.js +1 -1
  168. package/dist/database.js +1 -1
  169. package/dist/dev-server/serve-app.js +57 -17
  170. package/dist/dev-server/serve-file.js +8 -1
  171. package/dist/expressions.js +1 -1
  172. package/dist/imported-signals.js +1 -1
  173. package/dist/includes.js +27 -3
  174. package/dist/index.d.ts +11 -0
  175. package/dist/index.js +7 -0
  176. package/dist/manifest.d.ts +6 -0
  177. package/dist/misc-directives.d.ts +2 -0
  178. package/dist/misc-directives.js +39 -1
  179. package/dist/process.js +18 -1
  180. package/dist/production-builder.d.ts +4 -0
  181. package/dist/production-builder.js +47 -8
  182. package/dist/production-server.d.ts +4 -1
  183. package/dist/production-server.js +119 -71
  184. package/dist/pwa.js +2 -2
  185. package/dist/render.js +9 -2
  186. package/dist/route-response-cache.d.ts +7 -0
  187. package/dist/route-response-cache.js +72 -0
  188. package/dist/route-rules.d.ts +17 -0
  189. package/dist/route-rules.js +40 -0
  190. package/dist/router.d.ts +1 -0
  191. package/dist/runtime-config-loader.d.ts +5 -0
  192. package/dist/runtime-config-loader.js +42 -0
  193. package/dist/runtime-config-server.d.ts +26 -0
  194. package/dist/runtime-config-server.js +77 -0
  195. package/dist/runtime-config-types.d.ts +2 -0
  196. package/dist/runtime-config-types.js +0 -0
  197. package/dist/runtime-config.d.ts +5 -0
  198. package/dist/runtime-config.js +9 -0
  199. package/dist/runtime-globals.js +3 -0
  200. package/dist/serve.js +32 -10
  201. package/dist/server-api.d.ts +27 -0
  202. package/dist/server-api.js +181 -0
  203. package/dist/server-data.d.ts +17 -0
  204. package/dist/server-data.js +40 -0
  205. package/dist/signal-processing.js +2 -2
  206. package/dist/signals.js +138 -15
  207. package/dist/ssg.js +2 -2
  208. package/dist/stx-virtual-ts.d.ts +6 -0
  209. package/dist/stx-virtual-ts.js +31 -7
  210. package/dist/stx.d.ts +28 -0
  211. package/dist/template-compiler.d.ts +1 -0
  212. package/dist/template-compiler.js +1 -1
  213. package/dist/template-hydrator.js +15 -4
  214. package/dist/typecheck.d.ts +1 -0
  215. package/dist/typecheck.js +4 -3
  216. package/dist/types/config-types.d.ts +17 -0
  217. package/dist/utils.js +15 -5
  218. package/dist/variable-extractor.d.ts +1 -1
  219. package/dist/variable-extractor.js +12 -1
  220. package/dist/visual-testing.js +1 -1
  221. package/dist/vue-template.js +19 -41
  222. package/package.json +5 -5
  223. package/stx.d.ts +28 -0
  224. package/dist/chunk-0p44z42s.js +0 -2
  225. package/dist/chunk-2jd9bxmf.js +0 -2
  226. package/dist/chunk-2yp8ang5.js +0 -2
  227. package/dist/chunk-35x7s4cr.js +0 -2
  228. package/dist/chunk-3bqz5zre.js +0 -2
  229. package/dist/chunk-48p0k8y7.js +0 -2
  230. package/dist/chunk-4b625drg.js +0 -2
  231. package/dist/chunk-593kby1d.js +0 -2
  232. package/dist/chunk-5nac67r4.js +0 -18
  233. package/dist/chunk-70cf5h11.js +0 -2
  234. package/dist/chunk-78akhaws.js +0 -2
  235. package/dist/chunk-9a4q74r6.js +0 -2
  236. package/dist/chunk-9f5329rv.js +0 -2
  237. package/dist/chunk-9rv7akqq.js +0 -30
  238. package/dist/chunk-apjy1a72.js +0 -12
  239. package/dist/chunk-b3p3bzax.js +0 -3
  240. package/dist/chunk-c5hk1fxt.js +0 -2
  241. package/dist/chunk-c9rs5g1s.js +0 -2
  242. package/dist/chunk-dkd0bg8g.js +0 -2
  243. package/dist/chunk-dxhtry04.js +0 -2
  244. package/dist/chunk-ehp6fez3.js +0 -2
  245. package/dist/chunk-em3jb1dn.js +0 -4
  246. package/dist/chunk-ev4djb0p.js +0 -2
  247. package/dist/chunk-frejnjh9.js +0 -2
  248. package/dist/chunk-fvcr26a0.js +0 -22
  249. package/dist/chunk-g6ttsdz1.js +0 -2
  250. package/dist/chunk-gd73rpks.js +0 -2
  251. package/dist/chunk-ggwnrdqz.js +0 -17
  252. package/dist/chunk-h3t6fjba.js +0 -2
  253. package/dist/chunk-jc57j887.js +0 -2
  254. package/dist/chunk-jw248h1d.js +0 -2
  255. package/dist/chunk-k5xtf38q.js +0 -3
  256. package/dist/chunk-m78y5qys.js +0 -19
  257. package/dist/chunk-mc4rtf5d.js +0 -2
  258. package/dist/chunk-mx2wcb15.js +0 -2
  259. package/dist/chunk-p4w3wjbv.js +0 -2
  260. package/dist/chunk-pm3k8dyk.js +0 -2
  261. package/dist/chunk-qr59yfq9.js +0 -2
  262. package/dist/chunk-qsmdvy1z.js +0 -2
  263. package/dist/chunk-rsxmjfxq.js +0 -3754
  264. package/dist/chunk-s4sp78fn.js +0 -2
  265. package/dist/chunk-v2fp9vkh.js +0 -2
  266. package/dist/chunk-vwnnbzsp.js +0 -2
  267. package/dist/chunk-w0g99tx9.js +0 -2
  268. package/dist/chunk-x2pk87q2.js +0 -3
  269. package/dist/chunk-xn0asg46.js +0 -2
  270. package/dist/chunk-xwmw1wtk.js +0 -2
  271. package/dist/chunk-zdx9s3z0.js +0 -28
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Jk as wq,Kk as dq,Lk as Cq,Mk as mq,Nk as gq}from"./chunk-fj6fbqgb.js";import{$k as Mq,Ok as S,Pk as Tq,Qk as _q,Rk as z,Sk as D,Tk as P,Uk as kq,Vk as vq,Wk as w,Xk as Iq,Yk as d,Zk as Hq,_k as Oq}from"./chunk-7jebw3ea.js";import{nv as Aq,ov as bq,pv as Sq,qv as zq,rv as Dq,sv as Pq}from"./chunk-xdq52pwj.js";import{wv as N}from"./chunk-ddqkj56r.js";import p from"fs";import E from"path";import C from"fs";import L from"path";var k=[72,96,128,144,152,192,384,512],v=[120,152,167,180],I=[16,32];async function H(G,B){let q={success:!0,generatedFiles:[],errors:[],warnings:[]},K=G.pwa?.icons;if(!K?.src)return q.errors.push("No source icon specified in pwa.icons.src"),q.success=!1,q;let Y=L.isAbsolute(K.src)?K.src:L.resolve(process.cwd(),K.src);if(!await Bun.file(Y).exists())return q.errors.push(`Source icon not found: ${Y}`),q.success=!1,q;let Q=L.resolve(B,K.outputDir||"pwa-icons");try{C.mkdirSync(Q,{recursive:!0})}catch{return q.errors.push(`Failed to create output directory: ${Q}`),q.success=!1,q}let X=K.sizes||k,j=K.generateWebP??!0,J=K.generateAppleIcons??!0;try{let y;try{y=await import("sharp")}catch{return q.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),q.success=!1,q}let R=await y.default(Y).metadata();if(R.width&&R.width<512)q.warnings.push(`Source icon is ${R.width}x${R.height}. Recommend using at least 512x512 for best quality.`);for(let $ of X){let x=L.join(Q,`icon-${$}x${$}.png`);if(await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x),j){let F=L.join(Q,`icon-${$}x${$}.webp`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(F),q.generatedFiles.push(F)}}if(J){for(let x of v){let F=L.join(Q,`apple-touch-icon-${x}x${x}.png`);await y.default(Y).resize(x,x,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(F),q.generatedFiles.push(F)}let $=L.join(Q,"apple-touch-icon.png");await y.default(Y).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile($),q.generatedFiles.push($)}for(let $ of I){let x=L.join(Q,`favicon-${$}x${$}.png`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x)}let U=512,T=L.join(Q,`icon-maskable-${U}x${U}.png`),Z=Math.floor(U*0.1),_=U-Z*2;await y.default(Y).resize(_,_,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:Z,bottom:Z,left:Z,right:Z,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(T),q.generatedFiles.push(T)}catch(y){let V=y instanceof Error?y.message:String(y);q.errors.push(`Icon generation failed: ${V}`),q.success=!1}return q}function n(G){let B=G.sizes||k,q=G.outputDir?`/${G.outputDir}`:"/pwa-icons",K=G.generateWebP??!0,Y=G.generateAppleIcons??!0,Q=[];for(let X of B)if(Q.push(`${q}/icon-${X}x${X}.png`),K)Q.push(`${q}/icon-${X}x${X}.webp`);if(Y){Q.push(`${q}/apple-touch-icon.png`);for(let X of v)Q.push(`${q}/apple-touch-icon-${X}x${X}.png`)}for(let X of I)Q.push(`${q}/favicon-${X}x${X}.png`);return Q.push(`${q}/icon-maskable-512x512.png`),Q}async function O(){try{return await import("sharp"),!0}catch{return!1}}function m(G,B,q,K){let Y=[],Q=K.join(" ");for(let X of G)if(Y.push({src:`${B}/icon-${X}x${X}.png`,sizes:`${X}x${X}`,type:"image/png",purpose:Q}),q)Y.push({src:`${B}/icon-${X}x${X}.webp`,sizes:`${X}x${X}`,type:"image/webp",purpose:Q});return Y}function g(G){return G.map((B)=>({name:B.name,short_name:B.shortName,description:B.description,url:B.url,icons:B.icons?.map((q)=>({src:q.src,sizes:q.sizes,type:q.type}))}))}function h(G){let B=G.pwa?.shareTarget;if(!B?.enabled)return;let q={action:B.action||"/share",method:B.method||"POST",enctype:B.enctype||"multipart/form-data",params:{title:B.params?.title||"title",text:B.params?.text||"text",url:B.params?.url||"url"}};if(B.acceptFiles&&B.acceptFiles.length>0)q.params.files=B.acceptFiles.map((K)=>({name:K.name,accept:K.accept}));return q}function c(G){let B=G.pwa?.fileHandlers;if(!B?.enabled||!B.accept)return;let q=[{action:B.action||"/",accept:B.accept,launch_type:B.launchType||"single-client"}];if(B.icons)q[0].icons=B.icons.map((K)=>({src:K.src,sizes:K.sizes,type:K.type}));return q}function l(G){let B=G.pwa?.protocolHandlers;if(!B||B.length===0)return;return B.map((q)=>({protocol:q.protocol,url:q.url}))}function u(G){let B=G.pwa;if(!B?.enabled||!B.manifest)return null;let{manifest:q,icons:K}=B,Y=K?.sizes||[72,96,128,144,152,192,384,512],Q=K?.outputDir?`/${K.outputDir}`:"/pwa-icons",X=K?.generateWebP??!0,j=K?.purpose||["any","maskable"],J={name:q.name,short_name:q.shortName||q.name,description:q.description,start_url:q.startUrl||"/",display:q.display||"standalone",display_override:q.displayOverride,orientation:q.orientation,theme_color:q.themeColor,background_color:q.backgroundColor,scope:q.scope||"/",lang:q.lang,dir:q.dir,id:q.id,categories:q.categories,icons:m(Y,Q,X,j)};if(q.shortcuts&&q.shortcuts.length>0)J.shortcuts=g(q.shortcuts);if(q.screenshots&&q.screenshots.length>0)J.screenshots=q.screenshots.map((U)=>({src:U.src,sizes:U.sizes,type:U.type,label:U.label,form_factor:U.platform}));let y=h(G);if(y)J.share_target=y;let V=c(G);if(V)J.file_handlers=V;let R=l(G);if(R)J.protocol_handlers=R;if(q.launchHandler)J.launch_handler={client_mode:q.launchHandler};if(q.handleLinks)J.handle_links=q.handleLinks;if(q.edgeSidePanel?.enabled)J.edge_side_panel={preferred_width:q.edgeSidePanel.preferredWidth};return J}function M(G){let B=u(G);if(!B)return"";let q=JSON.parse(JSON.stringify(B));return JSON.stringify(q,null,2)}function i(G,B){return{...B,...G,shortcuts:G.shortcuts||B.shortcuts,screenshots:G.screenshots||B.screenshots,categories:G.categories||B.categories}}function s(G){let B=[],q=G.pwa;if(!q?.enabled)return B;let K=q.manifest;if(!K)return B.push("PWA manifest configuration is missing"),B;if(!K.name)B.push("Manifest name is required");let Y=["fullscreen","standalone","minimal-ui","browser"];if(K.display&&!Y.includes(K.display))B.push(`Invalid display mode: ${K.display}. Must be one of: ${Y.join(", ")}`);let Q=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(K.orientation&&!Q.includes(K.orientation))B.push(`Invalid orientation: ${K.orientation}`);let X=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(K.themeColor&&!X.test(K.themeColor))B.push(`Invalid theme color: ${K.themeColor}. Must be a valid hex color.`);if(K.backgroundColor&&!X.test(K.backgroundColor))B.push(`Invalid background color: ${K.backgroundColor}. Must be a valid hex color.`);if(q.shareTarget?.enabled){if(!q.shareTarget.action)B.push("Share target action URL is required")}if(q.fileHandlers?.enabled){if(!q.fileHandlers.accept||Object.keys(q.fileHandlers.accept).length===0)B.push("File handlers must specify accepted MIME types")}if(q.protocolHandlers)for(let j of q.protocolHandlers){if(!j.protocol)B.push("Protocol handler missing protocol");if(!j.url||!j.url.includes("%s"))B.push(`Protocol handler URL must contain %s placeholder: ${j.protocol}`)}return B}import A from"path";async function b(G){let B=G.pwa?.offline;if(!B?.enabled)return"";if(B.page){let q=A.isAbsolute(B.page)?B.page:A.resolve(process.cwd(),B.page);if(await Bun.file(q).exists())try{let{processDirectives:K}=await import("./chunk-2jd9bxmf.js"),Y=await Bun.file(q).text();return await K(Y,{},q,G,new Set)}catch(K){console.warn(`[PWA] Failed to process custom offline page: ${K}`)}else console.warn(`[PWA] Custom offline page not found: ${q}`)}return f(G)}function f(G){let B=G.pwa?.offline,q=G.pwa?.manifest,K=B?.fallbackTitle||"You are offline",Y=B?.fallbackMessage||"Please check your internet connection and try again.",Q=q?.themeColor||"#4f46e5",X=q?.shortName||q?.name||"App";return`<!DOCTYPE html>
2
+ import{Ok as wq,Pk as dq,Qk as Cq,Rk as mq,Sk as gq}from"./chunk-m3a20mmb.js";import{$k as w,Tk as S,Uk as Tq,Vk as _q,Wk as z,Xk as D,Yk as P,Zk as kq,_k as vq,al as Iq,bl as d,cl as Hq,dl as Oq,el as Mq}from"./chunk-7skk34dh.js";import{Vv as Aq,Wv as bq,Xv as Sq,Yv as zq,Zv as Dq,_v as Pq}from"./chunk-fp7ms6e7.js";import{cw as N}from"./chunk-jp2f8yzw.js";import p from"fs";import E from"path";import C from"fs";import L from"path";var k=[72,96,128,144,152,192,384,512],v=[120,152,167,180],I=[16,32];async function H(G,B){let q={success:!0,generatedFiles:[],errors:[],warnings:[]},K=G.pwa?.icons;if(!K?.src)return q.errors.push("No source icon specified in pwa.icons.src"),q.success=!1,q;let Y=L.isAbsolute(K.src)?K.src:L.resolve(process.cwd(),K.src);if(!await Bun.file(Y).exists())return q.errors.push(`Source icon not found: ${Y}`),q.success=!1,q;let Q=L.resolve(B,K.outputDir||"pwa-icons");try{C.mkdirSync(Q,{recursive:!0})}catch{return q.errors.push(`Failed to create output directory: ${Q}`),q.success=!1,q}let X=K.sizes||k,j=K.generateWebP??!0,J=K.generateAppleIcons??!0;try{let y;try{y=await import("sharp")}catch{return q.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),q.success=!1,q}let R=await y.default(Y).metadata();if(R.width&&R.width<512)q.warnings.push(`Source icon is ${R.width}x${R.height}. Recommend using at least 512x512 for best quality.`);for(let $ of X){let x=L.join(Q,`icon-${$}x${$}.png`);if(await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x),j){let F=L.join(Q,`icon-${$}x${$}.webp`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(F),q.generatedFiles.push(F)}}if(J){for(let x of v){let F=L.join(Q,`apple-touch-icon-${x}x${x}.png`);await y.default(Y).resize(x,x,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(F),q.generatedFiles.push(F)}let $=L.join(Q,"apple-touch-icon.png");await y.default(Y).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile($),q.generatedFiles.push($)}for(let $ of I){let x=L.join(Q,`favicon-${$}x${$}.png`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x)}let U=512,T=L.join(Q,`icon-maskable-${U}x${U}.png`),Z=Math.floor(U*0.1),_=U-Z*2;await y.default(Y).resize(_,_,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:Z,bottom:Z,left:Z,right:Z,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(T),q.generatedFiles.push(T)}catch(y){let V=y instanceof Error?y.message:String(y);q.errors.push(`Icon generation failed: ${V}`),q.success=!1}return q}function n(G){let B=G.sizes||k,q=G.outputDir?`/${G.outputDir}`:"/pwa-icons",K=G.generateWebP??!0,Y=G.generateAppleIcons??!0,Q=[];for(let X of B)if(Q.push(`${q}/icon-${X}x${X}.png`),K)Q.push(`${q}/icon-${X}x${X}.webp`);if(Y){Q.push(`${q}/apple-touch-icon.png`);for(let X of v)Q.push(`${q}/apple-touch-icon-${X}x${X}.png`)}for(let X of I)Q.push(`${q}/favicon-${X}x${X}.png`);return Q.push(`${q}/icon-maskable-512x512.png`),Q}async function O(){try{return await import("sharp"),!0}catch{return!1}}function m(G,B,q,K){let Y=[],Q=K.join(" ");for(let X of G)if(Y.push({src:`${B}/icon-${X}x${X}.png`,sizes:`${X}x${X}`,type:"image/png",purpose:Q}),q)Y.push({src:`${B}/icon-${X}x${X}.webp`,sizes:`${X}x${X}`,type:"image/webp",purpose:Q});return Y}function g(G){return G.map((B)=>({name:B.name,short_name:B.shortName,description:B.description,url:B.url,icons:B.icons?.map((q)=>({src:q.src,sizes:q.sizes,type:q.type}))}))}function h(G){let B=G.pwa?.shareTarget;if(!B?.enabled)return;let q={action:B.action||"/share",method:B.method||"POST",enctype:B.enctype||"multipart/form-data",params:{title:B.params?.title||"title",text:B.params?.text||"text",url:B.params?.url||"url"}};if(B.acceptFiles&&B.acceptFiles.length>0)q.params.files=B.acceptFiles.map((K)=>({name:K.name,accept:K.accept}));return q}function c(G){let B=G.pwa?.fileHandlers;if(!B?.enabled||!B.accept)return;let q=[{action:B.action||"/",accept:B.accept,launch_type:B.launchType||"single-client"}];if(B.icons)q[0].icons=B.icons.map((K)=>({src:K.src,sizes:K.sizes,type:K.type}));return q}function l(G){let B=G.pwa?.protocolHandlers;if(!B||B.length===0)return;return B.map((q)=>({protocol:q.protocol,url:q.url}))}function u(G){let B=G.pwa;if(!B?.enabled||!B.manifest)return null;let{manifest:q,icons:K}=B,Y=K?.sizes||[72,96,128,144,152,192,384,512],Q=K?.outputDir?`/${K.outputDir}`:"/pwa-icons",X=K?.generateWebP??!0,j=K?.purpose||["any","maskable"],J={name:q.name,short_name:q.shortName||q.name,description:q.description,start_url:q.startUrl||"/",display:q.display||"standalone",display_override:q.displayOverride,orientation:q.orientation,theme_color:q.themeColor,background_color:q.backgroundColor,scope:q.scope||"/",lang:q.lang,dir:q.dir,id:q.id,categories:q.categories,icons:m(Y,Q,X,j)};if(q.shortcuts&&q.shortcuts.length>0)J.shortcuts=g(q.shortcuts);if(q.screenshots&&q.screenshots.length>0)J.screenshots=q.screenshots.map((U)=>({src:U.src,sizes:U.sizes,type:U.type,label:U.label,form_factor:U.platform}));let y=h(G);if(y)J.share_target=y;let V=c(G);if(V)J.file_handlers=V;let R=l(G);if(R)J.protocol_handlers=R;if(q.launchHandler)J.launch_handler={client_mode:q.launchHandler};if(q.handleLinks)J.handle_links=q.handleLinks;if(q.edgeSidePanel?.enabled)J.edge_side_panel={preferred_width:q.edgeSidePanel.preferredWidth};return J}function M(G){let B=u(G);if(!B)return"";let q=JSON.parse(JSON.stringify(B));return JSON.stringify(q,null,2)}function i(G,B){return{...B,...G,shortcuts:G.shortcuts||B.shortcuts,screenshots:G.screenshots||B.screenshots,categories:G.categories||B.categories}}function s(G){let B=[],q=G.pwa;if(!q?.enabled)return B;let K=q.manifest;if(!K)return B.push("PWA manifest configuration is missing"),B;if(!K.name)B.push("Manifest name is required");let Y=["fullscreen","standalone","minimal-ui","browser"];if(K.display&&!Y.includes(K.display))B.push(`Invalid display mode: ${K.display}. Must be one of: ${Y.join(", ")}`);let Q=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(K.orientation&&!Q.includes(K.orientation))B.push(`Invalid orientation: ${K.orientation}`);let X=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(K.themeColor&&!X.test(K.themeColor))B.push(`Invalid theme color: ${K.themeColor}. Must be a valid hex color.`);if(K.backgroundColor&&!X.test(K.backgroundColor))B.push(`Invalid background color: ${K.backgroundColor}. Must be a valid hex color.`);if(q.shareTarget?.enabled){if(!q.shareTarget.action)B.push("Share target action URL is required")}if(q.fileHandlers?.enabled){if(!q.fileHandlers.accept||Object.keys(q.fileHandlers.accept).length===0)B.push("File handlers must specify accepted MIME types")}if(q.protocolHandlers)for(let j of q.protocolHandlers){if(!j.protocol)B.push("Protocol handler missing protocol");if(!j.url||!j.url.includes("%s"))B.push(`Protocol handler URL must contain %s placeholder: ${j.protocol}`)}return B}import A from"path";async function b(G){let B=G.pwa?.offline;if(!B?.enabled)return"";if(B.page){let q=A.isAbsolute(B.page)?B.page:A.resolve(process.cwd(),B.page);if(await Bun.file(q).exists())try{let{processDirectives:K}=await import("./chunk-er848s6f.js"),Y=await Bun.file(q).text();return await K(Y,{},q,G,new Set)}catch(K){console.warn(`[PWA] Failed to process custom offline page: ${K}`)}else console.warn(`[PWA] Custom offline page not found: ${q}`)}return f(G)}function f(G){let B=G.pwa?.offline,q=G.pwa?.manifest,K=B?.fallbackTitle||"You are offline",Y=B?.fallbackMessage||"Please check your internet connection and try again.",Q=q?.themeColor||"#4f46e5",X=q?.shortName||q?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
package/dist/render.js CHANGED
@@ -6,6 +6,7 @@ import { extractBridgeData, processClientScript } from "./client-script.js";
6
6
  import { findSfcTemplateBlock } from "./sfc-template.js";
7
7
  import { isMarkdownPath, renderMarkdownView } from "./markdown-view.js";
8
8
  import { responseBindings, syncRecordedResponse } from "./page-response.js";
9
+ import { serverDataScope } from "./server-data.js";
9
10
  function parseTemplate(content) {
10
11
  let workingContent = content;
11
12
  const templateBlock = findSfcTemplateBlock(content);
@@ -73,8 +74,14 @@ export async function renderTemplate(filePath, renderOptions = {}) {
73
74
  const layoutPath = resolve(renderOptions.layout), layoutFile = Bun.file(layoutPath);
74
75
  if (!await layoutFile.exists())
75
76
  throw Error(`Layout template not found: ${layoutPath}`);
76
- const { layout, injectCSS, ...pageOptions } = renderOptions, pageHtml = await renderTemplateString(content, resolvedPath, { ...pageOptions, injectCSS: !1 }), layoutContent = await layoutFile.text(), layoutContext = {
77
- ...renderOptions.context || {},
77
+ const { layout, injectCSS, ...pageOptions } = renderOptions, sharedContext = { ...renderOptions.context || {} };
78
+ serverDataScope(sharedContext);
79
+ const pageHtml = await renderTemplateString(content, resolvedPath, {
80
+ ...pageOptions,
81
+ context: { ...sharedContext, __stx_defer_server_data: !0 },
82
+ injectCSS: !1
83
+ }), layoutContent = await layoutFile.text(), layoutContext = {
84
+ ...sharedContext,
78
85
  content: pageHtml
79
86
  }, layoutOptions = {
80
87
  ...pageOptions,
@@ -0,0 +1,7 @@
1
+ import type { RouteCacheRule } from './route-rules';
2
+ /** Process-local, bounded origin cache; never caches actions or personalized responses. */
3
+ export declare class RouteResponseCache {
4
+ constructor(now?: () => number);
5
+ invalidate(pathname?: string): void;
6
+ respond(request: Request, policy: RouteCacheRule | false | undefined, render: () => Promise<Response>): Promise<Response>;
7
+ }
@@ -0,0 +1,72 @@
1
+ import { LRUCache } from "./performance-utils.js";
2
+ import { isSpaNavRequest, spaNavVaryHeaders } from "./spa-nav.js";
3
+
4
+ export class RouteResponseCache {
5
+ now;
6
+ entries = new LRUCache(1000, {
7
+ maxBytes: 33554432,
8
+ sizeOf: (entry) => entry.body.byteLength + JSON.stringify(entry.headers).length * 2
9
+ });
10
+ pending = new Map;
11
+ generation = 0;
12
+ constructor(now = Date.now) {
13
+ this.now = now;
14
+ }
15
+ invalidate(pathname) {
16
+ this.generation++;
17
+ this.pending.clear();
18
+ for (const key of Array.from(this.entries.keys()))
19
+ if (pathname === void 0 || this.entries.get(key)?.path === pathname)
20
+ this.entries.delete(key);
21
+ }
22
+ async respond(request, policy, render) {
23
+ let original;
24
+ const privateResponse = async () => {
25
+ const response = original ?? await render();
26
+ response.headers.set("Cache-Control", "private, no-store");
27
+ response.headers.set("Vary", spaNavVaryHeaders(response.headers.get("Vary")).Vary);
28
+ return response;
29
+ };
30
+ if (!policy || request.method !== "GET" || request.headers.has("Cookie") || request.headers.has("Authorization") || request.headers.has("Range"))
31
+ 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 headers = new Headers(entry.headers);
34
+ headers.set("Cache-Control", "private, no-store");
35
+ headers.set("Age", String(Math.max(0, Math.floor((this.now() - entry.created) / 1000))));
36
+ return new Response(entry.body.slice(0), { headers });
37
+ }, age = cached ? (this.now() - cached.created) / 1000 : 1 / 0;
38
+ if (cached && age < policy.maxAge)
39
+ return reply(cached);
40
+ const generation = this.generation, refresh = async () => {
41
+ const response = await render();
42
+ original = response;
43
+ 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
+ return null;
46
+ const body = await response.clone().arrayBuffer();
47
+ if (body.byteLength > 1048576)
48
+ return null;
49
+ response.headers.set("Vary", spaNavVaryHeaders(response.headers.get("Vary")).Vary);
50
+ const entry = { body, headers: Array.from(response.headers.entries()), created: this.now(), path: url.pathname };
51
+ if (this.generation === generation)
52
+ this.entries.set(key, entry);
53
+ return entry;
54
+ };
55
+ let pending = this.pending.get(key);
56
+ if (!pending) {
57
+ if (this.pending.size >= 1000)
58
+ return privateResponse();
59
+ pending = refresh().finally(() => {
60
+ if (this.pending.get(key) === pending)
61
+ this.pending.delete(key);
62
+ });
63
+ this.pending.set(key, pending);
64
+ }
65
+ if (cached && age < policy.maxAge + (policy.swr ?? 0)) {
66
+ pending.catch(() => {});
67
+ return reply(cached);
68
+ }
69
+ const fresh = await pending;
70
+ return fresh ? reply(fresh) : privateResponse();
71
+ }
72
+ }
@@ -0,0 +1,17 @@
1
+ /** Shared build/serve route policies. The most specific matching rule wins. */
2
+ export interface RouteCacheRule {
3
+ /** Explicit promise that anonymous responses contain no personalized data. */
4
+ public: true;
5
+ /** Fresh lifetime in seconds. */
6
+ maxAge: number;
7
+ /** Additional stale-while-revalidate window in seconds (default: 0). */
8
+ swr?: number;
9
+ }
10
+ export interface RouteRule {
11
+ rendering?: 'prerender' | 'dynamic';
12
+ cache?: false | RouteCacheRule;
13
+ }
14
+ export type RouteRules = Record<string, RouteRule>;
15
+ export declare function validateRouteRules(rules: RouteRules): void;
16
+ /** Compile once. Literal > parameter > * > **, compared left to right. */
17
+ export declare function createRouteRuleResolver(rules?: RouteRules): (pathname: string) => RouteRule;
@@ -0,0 +1,40 @@
1
+ function segments(pattern) {
2
+ if (!pattern.startsWith("/") || /[?#\\]/.test(pattern))
3
+ throw Error(`Invalid route rule pattern: ${pattern}`);
4
+ const parts = pattern === "/" ? [] : pattern.slice(1).split("/");
5
+ if (parts.some((part, i) => !part || part.includes("*") && part !== "*" && part !== "**" || part === "**" && i !== parts.length - 1 || part.startsWith(":") && !/^:[\w]+$/.test(part)))
6
+ throw Error(`Unsupported route rule pattern: ${pattern}`);
7
+ return parts;
8
+ }
9
+ export function validateRouteRules(rules) {
10
+ for (const [pattern, rule] of Object.entries(rules)) {
11
+ segments(pattern);
12
+ if (!rule || typeof rule !== "object" || Object.keys(rule).some((key) => key !== "rendering" && key !== "cache"))
13
+ throw Error(`Unsupported route rule for ${pattern}`);
14
+ if (rule.rendering !== void 0 && rule.rendering !== "prerender" && rule.rendering !== "dynamic")
15
+ throw Error(`Unsupported rendering mode for ${pattern}`);
16
+ if (rule.cache !== void 0 && rule.cache !== !1) {
17
+ const cache = rule.cache;
18
+ if (!cache || cache.public !== !0 || Object.keys(cache).some((key) => !["public", "maxAge", "swr"].includes(key)) || !Number.isFinite(cache.maxAge) || cache.maxAge <= 0 || cache.swr !== void 0 && (!Number.isFinite(cache.swr) || cache.swr < 0))
19
+ throw Error(`Route cache for ${pattern} requires public: true, maxAge > 0 and swr >= 0`);
20
+ if (rule.rendering === "prerender")
21
+ throw Error(`Prerendered route ${pattern} cannot revalidate; use dynamic rendering with cache`);
22
+ }
23
+ }
24
+ }
25
+ export function createRouteRuleResolver(rules = {}) {
26
+ validateRouteRules(rules);
27
+ const score = (part) => part === "**" ? 0 : part === "*" ? 1 : part.startsWith(":") ? 2 : 3, entries = Object.entries(rules).map(([pattern, rule]) => ({ pattern, parts: segments(pattern), rule }));
28
+ entries.sort((a, b) => {
29
+ for (let i = 0;i < Math.max(a.parts.length, b.parts.length); i++) {
30
+ const diff = (b.parts[i] === void 0 ? 4 : score(b.parts[i])) - (a.parts[i] === void 0 ? 4 : score(a.parts[i]));
31
+ if (diff)
32
+ return diff;
33
+ }
34
+ return a.pattern.localeCompare(b.pattern);
35
+ });
36
+ return (pathname) => {
37
+ const input = pathname === "/" ? [] : pathname.replace(/\/$/, "").slice(1).split("/");
38
+ return entries.find(({ parts }) => parts.every((part, i) => part === "**" || input[i] !== void 0 && (part === "*" || part.startsWith(":") || part === input[i])) && (parts.at(-1) === "**" || parts.length === input.length))?.rule ?? {};
39
+ };
40
+ }
package/dist/router.d.ts CHANGED
@@ -3,6 +3,7 @@ export type { Route, RouteMatch } from 'stx-router';
3
3
  export { findErrorPage, formatRoutes, generateRouteManifest, generateRouteTypes, matchRoute } from 'stx-router';
4
4
  export interface RouterOptions {
5
5
  pagesDir?: string;
6
+ pagesDirs?: string[];
6
7
  extensions?: string[];
7
8
  }
8
9
  export declare function createRouter(baseDir: string, options?: RouterOptions): Route[];
@@ -0,0 +1,5 @@
1
+ import { type RuntimeConfigDefaults } from './runtime-config-server';
2
+ /** Also supports hosts that extract server scripts before processDirectives. */
3
+ export declare function prepareRuntimeConfig(context: Record<string, any>, filePath: string, defaults?: RuntimeConfigDefaults): Promise<void>;
4
+ /** Emit literal types only; client declarations never reference private keys. */
5
+ export declare function generateRuntimeConfigTypes(root: string, defaults: RuntimeConfigDefaults): Promise<void>;
@@ -0,0 +1,42 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { currentRuntimeConfig, resolveRuntimeConfig } from "./runtime-config-server.js";
4
+ export async function prepareRuntimeConfig(context, filePath, defaults) {
5
+ if (context.__stx_runtime_config)
6
+ return;
7
+ const active = currentRuntimeConfig();
8
+ if (active || defaults) {
9
+ context.__stx_runtime_config = active ?? resolveRuntimeConfig(defaults);
10
+ return;
11
+ }
12
+ let dir = path.dirname(path.resolve(filePath));
13
+ while (!0) {
14
+ if (["stx.config.ts", "stx.config.js", ".config/stx.config.ts", ".config/stx.config.js"].some((name) => fs.existsSync(path.join(dir, name)))) {
15
+ const { loadStxConfig } = await import("./config.js"), config = await loadStxConfig(dir);
16
+ if (config.runtimeConfig)
17
+ context.__stx_runtime_config = resolveRuntimeConfig(config.runtimeConfig);
18
+ return;
19
+ }
20
+ const parent = path.dirname(dir);
21
+ if (parent === dir)
22
+ return;
23
+ dir = parent;
24
+ }
25
+ }
26
+ export async function generateRuntimeConfigTypes(root, defaults) {
27
+ function type(value) {
28
+ if (value === null)
29
+ return "null";
30
+ if (Array.isArray(value))
31
+ return `Array<${value.length ? [...new Set(value.map(type))].join(" | ") : "unknown"}>`;
32
+ if (typeof value === "object")
33
+ return `{ ${Object.entries(value).map(([k, v]) => `readonly ${JSON.stringify(k)}: ${type(v)}`).join("; ")} }`;
34
+ return typeof value;
35
+ }
36
+ await Bun.write(path.join(root, ".stx/runtime-config.d.ts"), `import '@stacksjs/stx/runtime-config'
37
+ declare module '@stacksjs/stx/runtime-config' { interface PublicRuntimeConfig ${type(defaults.public ?? {})} }
38
+ `);
39
+ await Bun.write(path.join(root, ".stx/runtime-config-server.d.ts"), `import '@stacksjs/stx/runtime-config-server'
40
+ declare module '@stacksjs/stx/runtime-config-server' { interface PrivateRuntimeConfig ${type(defaults.private ?? {})} }
41
+ `);
42
+ }
@@ -0,0 +1,26 @@
1
+ import type { PublicRuntimeConfig } from './runtime-config';
2
+ export type RuntimeConfigValue = string | number | boolean | null | RuntimeConfigValue[] | {
3
+ [key: string]: RuntimeConfigValue;
4
+ };
5
+ export interface RuntimeConfigDefaults {
6
+ public?: Record<string, RuntimeConfigValue>;
7
+ private?: Record<string, RuntimeConfigValue>;
8
+ }
9
+ export interface PrivateRuntimeConfig {
10
+ }
11
+ export interface ResolvedRuntimeConfig {
12
+ public: Record<string, RuntimeConfigValue>;
13
+ private: Record<string, RuntimeConfigValue>;
14
+ }
15
+ export declare function withRuntimeConfig<T>(config: ResolvedRuntimeConfig, run: () => T): T;
16
+ export declare function currentRuntimeConfig(): ResolvedRuntimeConfig | undefined;
17
+ export declare function useServerRuntimeConfig(): Readonly<{
18
+ public: PublicRuntimeConfig;
19
+ private: PrivateRuntimeConfig;
20
+ }>;
21
+ /** Server version of the public-only accessor. */
22
+ export declare function useRuntimeConfig(): Readonly<PublicRuntimeConfig>;
23
+ /** Resolve ONLY declared keys. Double underscores separate path segments. */
24
+ export declare function resolveRuntimeConfig(defaults?: RuntimeConfigDefaults, env?: Record<string, string | undefined>): ResolvedRuntimeConfig;
25
+ export declare function runtimeConfigTag(config: ResolvedRuntimeConfig): string;
26
+ export declare function injectRuntimeConfig(html: string, config: ResolvedRuntimeConfig): string;
@@ -0,0 +1,77 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const key = Symbol.for("stx.runtime-config.scope"), registry = globalThis, scope = registry[key] ??= new AsyncLocalStorage;
3
+ export function withRuntimeConfig(config, run) {
4
+ return scope.run(config, run);
5
+ }
6
+ export function currentRuntimeConfig() {
7
+ return scope.getStore();
8
+ }
9
+ export function useServerRuntimeConfig() {
10
+ const config = scope.getStore();
11
+ if (!config)
12
+ throw Error("useServerRuntimeConfig requires a server request or template render");
13
+ return Object.freeze(Object.defineProperty({ public: config.public }, "private", { value: config.private }));
14
+ }
15
+ export function useRuntimeConfig() {
16
+ return useServerRuntimeConfig().public;
17
+ }
18
+ export function resolveRuntimeConfig(defaults = {}, env = process.env) {
19
+ const names = new Set;
20
+ function matchesDefault(value, shape) {
21
+ if (shape === null)
22
+ return value === null;
23
+ if (Array.isArray(shape))
24
+ return Array.isArray(value) && (!shape.length || value.every((item) => shape.some((sample) => matchesDefault(item, sample))));
25
+ if (typeof shape === "object")
26
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.entries(shape).every(([key, sample]) => Object.hasOwn(value, key) && matchesDefault(value[key], sample));
27
+ return typeof value === typeof shape;
28
+ }
29
+ function visit(value, path) {
30
+ if (value && typeof value === "object" && !Array.isArray(value)) {
31
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
32
+ throw TypeError(`Runtime config ${path.join(".")} must contain JSON values`);
33
+ const result = Object.create(null);
34
+ for (const [name, entry] of Object.entries(value)) {
35
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(name) || ["constructor", "prototype", "__proto__"].includes(name))
36
+ throw TypeError(`Invalid runtime config key: ${name}`);
37
+ result[name] = visit(entry, [...path, name]);
38
+ }
39
+ return Object.freeze(result);
40
+ }
41
+ const name = `STX_RUNTIME_${path.map((segment) => segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase()).join("__")}`;
42
+ if (names.has(name))
43
+ throw TypeError(`Ambiguous runtime config environment key: ${name}`);
44
+ names.add(name);
45
+ const raw = env[name];
46
+ let resolved = value;
47
+ if (raw !== void 0) {
48
+ try {
49
+ resolved = typeof value === "string" ? raw : JSON.parse(raw);
50
+ } catch {
51
+ throw TypeError(`Invalid runtime config override: ${name}`);
52
+ }
53
+ if (!matchesDefault(resolved, value))
54
+ throw TypeError(`Wrong runtime config override type: ${name}`);
55
+ }
56
+ function clone(entry) {
57
+ if (entry === null || typeof entry === "string" || typeof entry === "boolean")
58
+ return entry;
59
+ if (typeof entry === "number" && Number.isFinite(entry))
60
+ return entry;
61
+ if (Array.isArray(entry))
62
+ return Object.freeze(entry.map(clone));
63
+ if (entry && typeof entry === "object" && (Object.getPrototypeOf(entry) === Object.prototype || Object.getPrototypeOf(entry) === null))
64
+ return Object.freeze(Object.fromEntries(Object.entries(entry).map(([k, v]) => [k, clone(v)])));
65
+ throw TypeError(`Runtime config ${path.join(".")} must contain JSON values`);
66
+ }
67
+ return clone(resolved);
68
+ }
69
+ return Object.freeze({ public: visit(defaults.public ?? {}, ["public"]), private: visit(defaults.private ?? {}, ["private"]) });
70
+ }
71
+ export function runtimeConfigTag(config) {
72
+ return `<script data-stx-scoped data-stx-runtime-config type="application/json">${JSON.stringify(config.public).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029")}</script>`;
73
+ }
74
+ export function injectRuntimeConfig(html, config) {
75
+ const clean = html.replace(/<script\b[^>]*\bdata-stx-runtime-config\b[^>]*>[\s\S]*?<\/script>/gi, ""), head = /<head\b[^>]*>/i.exec(clean), at = head ? head.index + head[0].length : 0;
76
+ return clean.slice(0, at) + runtimeConfigTag(config) + clean.slice(at);
77
+ }
@@ -0,0 +1,2 @@
1
+ export type { RuntimeConfigDefaults } from './runtime-config-server';
2
+ export type { PublicRuntimeConfig } from './runtime-config';
File without changes
@@ -0,0 +1,5 @@
1
+ /** Augmented by .stx/runtime-config.d.ts; this module is browser-safe. */
2
+ export interface PublicRuntimeConfig {
3
+ }
4
+ /** Public values only. Import from @stacksjs/stx/runtime-config in client code. */
5
+ export declare function useRuntimeConfig(): Readonly<PublicRuntimeConfig>;
@@ -0,0 +1,9 @@
1
+ export function useRuntimeConfig() {
2
+ if (typeof document > "u")
3
+ throw Error("Use the server runtime-config accessor outside the browser");
4
+ const routed = typeof window > "u" ? void 0 : window.__STX_RUNTIME_CONFIG__;
5
+ if (routed)
6
+ return routed;
7
+ const tags = document.querySelectorAll("script[data-stx-runtime-config]"), tag = tags[tags.length - 1];
8
+ return JSON.parse(tag?.textContent || "{}");
9
+ }
@@ -1,6 +1,7 @@
1
1
  import { importsSignalDeclarations } from "./imported-signals.js";
2
2
  export const STX_RUNTIME_GLOBALS = [
3
3
  "batch",
4
+ "clearServerData",
4
5
  "computed",
5
6
  "configureFetch",
6
7
  "defineEmits",
@@ -50,6 +51,7 @@ export const STX_RUNTIME_GLOBALS = [
50
51
  "useInterval",
51
52
  "useLocalStorage",
52
53
  "useMediaQuery",
54
+ "useModel",
53
55
  "useMutation",
54
56
  "useOptimistic",
55
57
  "usePreferredContrast",
@@ -94,6 +96,7 @@ export const COMPILE_TIME_ONLY_GLOBALS = [
94
96
  "defineSlots",
95
97
  "withDefaults"
96
98
  ], NON_CLIENT_PRIMITIVES = {
99
+ useServerData: { category: "server-only", reason: "loads and serializes request-scoped data from <script server>; clients consume it through a keyed useFetch/useAsyncData." },
97
100
  redirect: { category: "server-only", reason: "returns an HTTP Response for <script server>/edge/build; use navigate() on the client." },
98
101
  useAsyncData: { category: "browser-composable", reason: "inlined on demand from src/composables when a script references it; reachable, not a bare global." },
99
102
  Teleport: { category: "compile-time-directive", reason: "template tag resolved by processTeleportDirectives; not a script callable." },
package/dist/serve.js CHANGED
@@ -7,6 +7,7 @@ import { processDirectives } from "./process.js";
7
7
  import { extractVariables } from "./utils.js";
8
8
  import { compressResponse } from "./compression.js";
9
9
  import { readResponseHeaders, readResponseStatus } from "./page-response.js";
10
+ import { createServerApi, isServerApiSource } from "./server-api.js";
10
11
  export function htmlResponse(html, status = 200, headers = {}) {
11
12
  return new Response(html, {
12
13
  status,
@@ -18,7 +19,7 @@ export function htmlResponse(html, status = 200, headers = {}) {
18
19
  }
19
20
  async function resolveStxOptions(options) {
20
21
  const { loadStxConfig } = await import("./config.js");
21
- return { ...await loadStxConfig(options.configDir ?? process.cwd()).catch(() => ({})), ...options.stxOptions ?? {} };
22
+ return { ...await loadStxConfig(options.configDir ?? process.cwd()), ...options.stxOptions ?? {} };
22
23
  }
23
24
  export async function serve(options = {}) {
24
25
  const {
@@ -30,7 +31,7 @@ export async function serve(options = {}) {
30
31
  middleware = [],
31
32
  on404,
32
33
  onError
33
- } = options, rootDir = path.resolve(root), stxOptions = await resolveStxOptions(options), fileCache = new Map;
34
+ } = options, rootDir = path.resolve(root), stxOptions = await resolveStxOptions(options), apiRoot = path.resolve(options.configDir ?? process.cwd()), handleApi = await createServerApi(apiRoot, stxOptions.serverApi), fileCache = new Map;
34
35
  async function processStxFile(filePath) {
35
36
  const stats = fs.statSync(filePath), cacheKey = `${filePath}:${stats.mtimeMs}`, cached = fileCache.get(cacheKey);
36
37
  if (cached)
@@ -55,7 +56,8 @@ export async function serve(options = {}) {
55
56
  let templateContent = workingContent.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, "");
56
57
  const context = {
57
58
  __filename: filePath,
58
- __dirname: path.dirname(filePath)
59
+ __dirname: path.dirname(filePath),
60
+ __stx_options: stxOptions
59
61
  };
60
62
  for (const scriptContent of serverScripts)
61
63
  await extractVariables(scriptContent, context, filePath);
@@ -99,14 +101,24 @@ ${scriptsHtml}`;
99
101
  path.join(relPath, "index.md"),
100
102
  path.join(relPath, "index.html")
101
103
  ];
102
- for (const possiblePath of possiblePaths) {
103
- const fullPath = path.join(rootDir, possiblePath);
104
- if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile())
105
- return fullPath;
106
- }
104
+ for (const directory of [rootDir, ...stxOptions._layerPageDirs ?? []])
105
+ for (const possiblePath of possiblePaths) {
106
+ const fullPath = path.resolve(directory, possiblePath);
107
+ if (!fullPath.startsWith(`${path.resolve(directory)}${path.sep}`))
108
+ continue;
109
+ if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile())
110
+ return fullPath;
111
+ }
107
112
  return null;
108
113
  }
109
114
  async function handleRequest(request) {
115
+ if (stxOptions._layerGraph) {
116
+ const fresh = await resolveStxOptions(options);
117
+ if (fresh._layerGraph !== stxOptions._layerGraph) {
118
+ Object.assign(stxOptions, fresh);
119
+ fileCache.clear();
120
+ }
121
+ }
110
122
  const url = new URL(request.url);
111
123
  let next = async () => {
112
124
  if (routes[url.pathname])
@@ -116,8 +128,18 @@ ${scriptsHtml}`;
116
128
  if (customResponse)
117
129
  return customResponse;
118
130
  }
131
+ if (stxOptions.apiRouter) {
132
+ const response = await stxOptions.apiRouter.handleRequest(request);
133
+ if (response.status !== 404)
134
+ return response;
135
+ }
136
+ if (stxOptions.apiRoutes?.[url.pathname])
137
+ return stxOptions.apiRoutes[url.pathname](request);
138
+ const apiResponse = await handleApi(request);
139
+ if (apiResponse)
140
+ return apiResponse;
119
141
  const filePath = resolveRequestPath(url.pathname);
120
- if (!filePath) {
142
+ if (!filePath || isServerApiSource(filePath, apiRoot, stxOptions.serverApi)) {
121
143
  if (on404)
122
144
  return await on404(request);
123
145
  return new Response("Not Found", { status: 404 });
@@ -209,7 +231,7 @@ export async function serveFile(filePath, options = {}) {
209
231
  if (scriptM[1].includes("server"))
210
232
  serverScriptContents.push(scriptM[2]);
211
233
  const scriptContent = serverScriptContents.join(`
212
- `), templateContent = fileContent.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ""), context = {};
234
+ `), templateContent = fileContent.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ""), context = { __stx_options: stxOptions };
213
235
  if (scriptContent.trim())
214
236
  await extractVariables(scriptContent, context, absolutePath);
215
237
  content = await processDirectives(templateContent, context, absolutePath, stxOptions, new Set);
@@ -0,0 +1,27 @@
1
+ import type { ApiHandlerContext } from './api-handler';
2
+ import type { ApiMethod } from './api-client';
3
+ export interface ServerApiOptions {
4
+ /** Relative to the project/config directory, not the template root. */
5
+ dir?: string;
6
+ }
7
+ export interface ServerApiRoute {
8
+ pattern: string;
9
+ method: ApiMethod;
10
+ /** Source file in dev; bundled file relative to outputDir in the manifest. */
11
+ filePath: string;
12
+ }
13
+ /** Only explicitly enabled callers scan server/api; discovery never executes user code. */
14
+ export declare function discoverServerApi(root: string, options?: ServerApiOptions): ServerApiRoute[];
15
+ /** The only generated imports are in a declaration file: no implementation enters a client graph. */
16
+ export declare function generateApiTypes(root: string, routes: ServerApiRoute[]): Promise<string>;
17
+ /** Bun bundles server code only, outside public/. Imported helpers are included. */
18
+ export declare function buildServerApi(root: string, outputDir: string, options?: ServerApiOptions): Promise<ServerApiRoute[]>;
19
+ type Handler = (request: Request, context: ApiHandlerContext) => unknown;
20
+ /** Shared dispatcher used by development, production and embedded hosts. */
21
+ export declare function createApiDispatcher(routes: ServerApiRoute[], load: (route: ServerApiRoute) => Promise<Handler>): (request: Request) => Promise<Response | null>;
22
+ export declare function productionApiDispatcher(outputDir: string, routes: ServerApiRoute[]): (request: Request) => Promise<Response | null>;
23
+ /** Development rescans and bundles per API request, including transitive edits. No stale module cache. */
24
+ export declare function createServerApi(root: string, enabled: boolean | ServerApiOptions | undefined): Promise<(request: Request) => Promise<Response | null>>;
25
+ /** Never expose endpoint source through a server that also serves the project root. */
26
+ export declare function isServerApiSource(filePath: string, root: string, enabled: boolean | ServerApiOptions | undefined): boolean;
27
+ export {};