@stacksjs/stx 0.2.302 → 0.2.304

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-02hm88m5.js +2 -0
  10. package/dist/{chunk-7eea1cse.js → chunk-09zjty4k.js} +1 -1
  11. package/dist/{chunk-7nfn7nj9.js → chunk-0gz0rhvs.js} +1 -1
  12. package/dist/{chunk-jsfch50r.js → chunk-1c2j4eby.js} +1 -1
  13. package/dist/{chunk-m6wz1hf5.js → chunk-2h94c5hm.js} +2 -2
  14. package/dist/{chunk-mjpqz66q.js → chunk-2ver2s2y.js} +1 -1
  15. package/dist/{chunk-2wcd2031.js → chunk-30nbe9hr.js} +2 -2
  16. package/dist/chunk-39qzhpn6.js +18 -0
  17. package/dist/chunk-3z6bqqr7.js +2 -0
  18. package/dist/chunk-43p1qq7g.js +2 -0
  19. package/dist/{chunk-52rkkkmt.js → chunk-45y8bjrv.js} +287 -352
  20. package/dist/{chunk-2rp09y5j.js → chunk-4evbx7sz.js} +1 -1
  21. package/dist/chunk-4jgr954p.js +2 -0
  22. package/dist/chunk-51j2aqvb.js +2 -0
  23. package/dist/{chunk-8d15pd4g.js → chunk-54f8bpp6.js} +3 -3
  24. package/dist/{chunk-cbwp8prr.js → chunk-5k1hznvq.js} +2 -2
  25. package/dist/chunk-5qfpcgcs.js +2 -0
  26. package/dist/{chunk-7eg7ep8f.js → chunk-5tefa8qb.js} +2 -2
  27. package/dist/chunk-5x2fc4vk.js +30 -0
  28. package/dist/{chunk-683tfkz4.js → chunk-64djh88a.js} +1 -1
  29. package/dist/{chunk-btrmvj2y.js → chunk-695fkras.js} +1 -1
  30. package/dist/chunk-6hcc4973.js +2 -0
  31. package/dist/{chunk-svg37jzs.js → chunk-6vswphz4.js} +2 -2
  32. package/dist/chunk-7gqbr8nr.js +2 -0
  33. package/dist/{chunk-x4prtyjs.js → chunk-7kw3grq5.js} +1 -1
  34. package/dist/{chunk-7jebw3ea.js → chunk-7skk34dh.js} +2 -2
  35. package/dist/chunk-8215nhej.js +12 -0
  36. package/dist/chunk-8ee62a9q.js +2 -0
  37. package/dist/{chunk-jj6yp7gm.js → chunk-8jam44my.js} +1 -1
  38. package/dist/chunk-8z0n5mtg.js +2 -0
  39. package/dist/{chunk-3bc8bqw2.js → chunk-9368t9jm.js} +1 -1
  40. package/dist/chunk-9499k64n.js +6 -0
  41. package/dist/chunk-976g5qe5.js +2 -0
  42. package/dist/{chunk-3jwmcf4k.js → chunk-9c835qjn.js} +1 -1
  43. package/dist/chunk-9px4y692.js +2 -0
  44. package/dist/{chunk-38t0fxh0.js → chunk-9vqnrcrw.js} +2 -2
  45. package/dist/chunk-9wrrr7g3.js +4 -0
  46. package/dist/{chunk-q0y1yxg3.js → chunk-9xzszvn5.js} +1 -1
  47. package/dist/chunk-a07chbgj.js +2 -0
  48. package/dist/{chunk-454kar39.js → chunk-ankp4reb.js} +2 -2
  49. package/dist/{chunk-5d9cy7a0.js → chunk-awj7yy37.js} +1 -1
  50. package/dist/chunk-b1hd8kvy.js +2 -0
  51. package/dist/chunk-b4xwbh8a.js +2 -0
  52. package/dist/{chunk-d6wq91cw.js → chunk-bd9wrcq1.js} +277 -21
  53. package/dist/{chunk-q25mr70f.js → chunk-c131k3mt.js} +1 -1
  54. package/dist/chunk-c3tmzx7q.js +2 -0
  55. package/dist/{chunk-6btbgxh1.js → chunk-c79nfdyj.js} +1 -1
  56. package/dist/{chunk-cfgpk6bh.js → chunk-cbgh359m.js} +1 -1
  57. package/dist/chunk-ckzhp09g.js +2 -0
  58. package/dist/{chunk-weqpt9nt.js → chunk-cr8v8k53.js} +1 -1
  59. package/dist/{chunk-p3wwm6k4.js → chunk-d19tvdvv.js} +1 -1
  60. package/dist/{chunk-nb1zdh1y.js → chunk-d3srvh3q.js} +1 -1
  61. package/dist/{chunk-rqrfq305.js → chunk-d57gb0v2.js} +1 -1
  62. package/dist/{chunk-1xyhk1wr.js → chunk-d5cqnwdd.js} +1 -1
  63. package/dist/chunk-dgpjxmhs.js +2 -0
  64. package/dist/chunk-dvvx1wny.js +3 -0
  65. package/dist/{chunk-ctz53mbz.js → chunk-ej8mv2k6.js} +1 -1
  66. package/dist/{chunk-dv3z80gt.js → chunk-env6knrs.js} +1 -1
  67. package/dist/{chunk-rf10fkrf.js → chunk-ess2pgt5.js} +1 -1
  68. package/dist/chunk-ez28vck6.js +2 -0
  69. package/dist/{chunk-0tbgvp70.js → chunk-fczfdsab.js} +21 -5
  70. package/dist/{chunk-xdq52pwj.js → chunk-fp7ms6e7.js} +1 -1
  71. package/dist/{chunk-qg6pg6ze.js → chunk-fqq5k9ve.js} +1 -1
  72. package/dist/chunk-fvtv1s5j.js +3 -0
  73. package/dist/{chunk-5t0w4h6z.js → chunk-g912mb7x.js} +1 -1
  74. package/dist/chunk-g97atepq.js +2 -0
  75. package/dist/{chunk-wj25qt72.js → chunk-gbwhbasw.js} +1 -1
  76. package/dist/{chunk-38e9wgfc.js → chunk-gfc3qye3.js} +2 -2
  77. package/dist/{chunk-cratkhhb.js → chunk-ghw5p1yk.js} +1 -1
  78. package/dist/{chunk-f0g2q51j.js → chunk-gssbag3e.js} +1 -1
  79. package/dist/{chunk-c9vhtjtr.js → chunk-gt8ja700.js} +2 -2
  80. package/dist/chunk-hay1rzb0.js +3754 -0
  81. package/dist/{chunk-q5sw26s7.js → chunk-hg2afckn.js} +1 -1
  82. package/dist/chunk-hgjjnjas.js +7 -0
  83. package/dist/{chunk-hhnzd03k.js → chunk-hrcxfvh1.js} +1 -1
  84. package/dist/chunk-hzav4hyd.js +2 -0
  85. package/dist/{chunk-29gjwajm.js → chunk-jfzfrmzy.js} +1 -1
  86. package/dist/chunk-jjq9q9jr.js +2 -0
  87. package/dist/{chunk-ddqkj56r.js → chunk-jp2f8yzw.js} +1 -1
  88. package/dist/{chunk-ry3a2674.js → chunk-jsg1rthc.js} +1 -1
  89. package/dist/chunk-jxxv18a0.js +5 -0
  90. package/dist/chunk-kbw2qzqx.js +2 -0
  91. package/dist/chunk-kdxvraec.js +2 -0
  92. package/dist/chunk-krfjb7b8.js +2 -0
  93. package/dist/{chunk-6b4k8fay.js → chunk-kxavsh3m.js} +1 -1
  94. package/dist/{chunk-4tffxxpd.js → chunk-m31n9pkr.js} +1 -1
  95. package/dist/{chunk-fj6fbqgb.js → chunk-m3a20mmb.js} +1 -1
  96. package/dist/{chunk-j21csh4j.js → chunk-mbmqpaq1.js} +1 -1
  97. package/dist/{chunk-y9nyqcha.js → chunk-mwh3ymwc.js} +1 -1
  98. package/dist/{chunk-51g95yts.js → chunk-mygq61f5.js} +2 -2
  99. package/dist/chunk-nqq7y7m9.js +3 -0
  100. package/dist/chunk-nws8fbde.js +2 -0
  101. package/dist/{chunk-q6xfyasj.js → chunk-pcvayb2f.js} +1 -1
  102. package/dist/{chunk-nvxv2wxv.js → chunk-ppyz9623.js} +1 -1
  103. package/dist/chunk-pr14wjkn.js +2 -0
  104. package/dist/{chunk-jb2r696a.js → chunk-qev11kg8.js} +1 -1
  105. package/dist/{chunk-6njgsr6w.js → chunk-qeyw5za9.js} +1 -1
  106. package/dist/chunk-rpfcnq8n.js +2 -0
  107. package/dist/chunk-rrankpmj.js +3 -0
  108. package/dist/chunk-rst1rw09.js +2 -0
  109. package/dist/{chunk-3p0zgfgz.js → chunk-rzevgemj.js} +2 -2
  110. package/dist/{chunk-aa6kt84c.js → chunk-sart9ehj.js} +1 -1
  111. package/dist/chunk-sb7ana2z.js +19 -0
  112. package/dist/chunk-snt2773t.js +2 -0
  113. package/dist/{chunk-jptkc64r.js → chunk-t3qb9s6s.js} +2 -2
  114. package/dist/{chunk-w8yac9xp.js → chunk-t41aaehf.js} +1 -1
  115. package/dist/{chunk-qjkzpd68.js → chunk-t51mwjyq.js} +1 -1
  116. package/dist/chunk-tt4r8q4v.js +2 -0
  117. package/dist/chunk-vd3h9z7e.js +2 -0
  118. package/dist/{chunk-6rzwef28.js → chunk-vd5xvsnv.js} +1 -1
  119. package/dist/chunk-wbecqx03.js +2 -0
  120. package/dist/{chunk-dcxtrqfy.js → chunk-wfffa8zm.js} +1 -1
  121. package/dist/{chunk-22p0ezj6.js → chunk-wx13qmaw.js} +1 -1
  122. package/dist/chunk-xd5ahrtn.js +2 -0
  123. package/dist/{chunk-vh0qr8k9.js → chunk-xganfzgn.js} +2 -2
  124. package/dist/chunk-xq1swv2e.js +2 -0
  125. package/dist/chunk-xsfwcj6x.js +2 -0
  126. package/dist/{chunk-91007tan.js → chunk-xwxdwqn9.js} +1 -1
  127. package/dist/{chunk-634gaa9d.js → chunk-xz3evxqp.js} +1 -1
  128. package/dist/chunk-xzgvcrnz.js +2 -0
  129. package/dist/chunk-y2kmm6bt.js +43 -0
  130. package/dist/{chunk-v8474ah4.js → chunk-y4nzmkea.js} +1 -1
  131. package/dist/chunk-y7wsk78j.js +3 -0
  132. package/dist/{chunk-6w8fa3b8.js → chunk-ya5m5vbn.js} +1 -1
  133. package/dist/{chunk-ps20v1ah.js → chunk-ym3r8ktq.js} +1 -1
  134. package/dist/chunk-yyebm8q4.js +2 -0
  135. package/dist/chunk-yyyxt326.js +2 -0
  136. package/dist/chunk-yz16bgs3.js +28 -0
  137. package/dist/{chunk-em8p71et.js → chunk-z9ezmjwd.js} +2 -2
  138. package/dist/chunk-zbtfhxhn.js +2 -0
  139. package/dist/chunk-zggm7kjd.js +17 -0
  140. package/dist/{chunk-mdf3jbe6.js → chunk-zhcs8m2a.js} +2 -2
  141. package/dist/{chunk-f9d27v49.js → chunk-zs5y7xnt.js} +1 -1
  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 +8 -2
  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 +210 -17
  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-1na1dvda.js +0 -2
  226. package/dist/chunk-2yp8ang5.js +0 -2
  227. package/dist/chunk-35x7s4cr.js +0 -2
  228. package/dist/chunk-39qnycbc.js +0 -2
  229. package/dist/chunk-4qj6pq60.js +0 -2
  230. package/dist/chunk-4r1qdp25.js +0 -19
  231. package/dist/chunk-4xs545h1.js +0 -2
  232. package/dist/chunk-70cf5h11.js +0 -2
  233. package/dist/chunk-7k63nhap.js +0 -28
  234. package/dist/chunk-7w3dttqh.js +0 -2
  235. package/dist/chunk-813dt09p.js +0 -2
  236. package/dist/chunk-9cp3430d.js +0 -2
  237. package/dist/chunk-ac9vpa5z.js +0 -2
  238. package/dist/chunk-b26xazrf.js +0 -2
  239. package/dist/chunk-b2ghmxpj.js +0 -4
  240. package/dist/chunk-btnky17z.js +0 -12
  241. package/dist/chunk-c7av0px6.js +0 -2
  242. package/dist/chunk-cthpzv4p.js +0 -18
  243. package/dist/chunk-d41b0rqp.js +0 -2
  244. package/dist/chunk-dkd0bg8g.js +0 -2
  245. package/dist/chunk-e0s519df.js +0 -2
  246. package/dist/chunk-ebr2344x.js +0 -3
  247. package/dist/chunk-ehp6fez3.js +0 -2
  248. package/dist/chunk-fc5t3cxt.js +0 -2
  249. package/dist/chunk-g6ttsdz1.js +0 -2
  250. package/dist/chunk-gd73rpks.js +0 -2
  251. package/dist/chunk-gv42xz15.js +0 -17
  252. package/dist/chunk-h3t6fjba.js +0 -2
  253. package/dist/chunk-h65nep6y.js +0 -2
  254. package/dist/chunk-h7d01cy7.js +0 -2
  255. package/dist/chunk-jc57j887.js +0 -2
  256. package/dist/chunk-k5xtf38q.js +0 -3
  257. package/dist/chunk-mc4rtf5d.js +0 -2
  258. package/dist/chunk-me5kq4e6.js +0 -22
  259. package/dist/chunk-mzf6c0h7.js +0 -2
  260. package/dist/chunk-n1j7gfe1.js +0 -3
  261. package/dist/chunk-pczxwdes.js +0 -2
  262. package/dist/chunk-pq6rabcy.js +0 -3754
  263. package/dist/chunk-qr59yfq9.js +0 -2
  264. package/dist/chunk-s454ytp4.js +0 -2
  265. package/dist/chunk-s4sp78fn.js +0 -2
  266. package/dist/chunk-shr928nn.js +0 -2
  267. package/dist/chunk-that7v95.js +0 -2
  268. package/dist/chunk-vwnnbzsp.js +0 -2
  269. package/dist/chunk-w63052rn.js +0 -2
  270. package/dist/chunk-w9kzfesd.js +0 -2
  271. package/dist/chunk-zwy5e35f.js +0 -30
@@ -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 {};
@@ -0,0 +1,181 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { patternToRegex } from "stx-router";
5
+ import { stateDir } from "./state-dir.js";
6
+ import { resolveRuntimeConfig, withRuntimeConfig } from "./runtime-config-server.js";
7
+ import { isLayerConfigSource } from "./application-layers.js";
8
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"], discoveredSources = new Set;
9
+ export function discoverServerApi(root, options = {}) {
10
+ const directory = path.resolve(root, options.dir ?? "server/api"), routes = [], signatures = new Map;
11
+ if (!fs.existsSync(directory))
12
+ return routes;
13
+ const files = Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({ cwd: directory })).sort();
14
+ for (const file of files) {
15
+ if (file.endsWith(".d.ts"))
16
+ continue;
17
+ const parts = file.replace(/\.(?:ts|js|mts|mjs)$/, "").split("/");
18
+ let name = parts.pop();
19
+ const dot = name.lastIndexOf("."), suffix = dot >= 0 ? name.slice(dot + 1) : "get", method = suffix.toUpperCase();
20
+ if (!METHODS.includes(method) || suffix !== suffix.toLowerCase())
21
+ throw Error(`Unsupported API method suffix in ${file}; use ${METHODS.map((value) => value.toLowerCase()).join(", ")}`);
22
+ if (dot >= 0)
23
+ name = name.slice(0, dot);
24
+ if (name !== "index")
25
+ parts.push(name);
26
+ const names = new Set, segments = parts.map((part, index) => {
27
+ const parameter = /^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(part);
28
+ if (parameter) {
29
+ if (names.has(parameter[2]) || parameter[1] && index !== parts.length - 1)
30
+ throw Error(`Invalid API parameter in ${file}`);
31
+ names.add(parameter[2]);
32
+ return `:${parameter[2]}${parameter[1] ? "*" : ""}`;
33
+ }
34
+ if (!/^[\w-]+$/.test(part))
35
+ throw Error(`Unsupported API path segment ${part} in ${file}`);
36
+ return part;
37
+ }), pattern = `/api${segments.length ? `/${segments.join("/")}` : ""}`, signature = `${method} ${pattern.replace(/:\w+/g, ":param")}`;
38
+ if (signatures.has(signature))
39
+ throw Error(`Ambiguous API route ${method} ${pattern}: ${signatures.get(signature)} and ${file}`);
40
+ signatures.set(signature, file);
41
+ const filePath = path.join(directory, file);
42
+ discoveredSources.add(path.resolve(filePath));
43
+ discoveredSources.add(fs.realpathSync(filePath));
44
+ routes.push({ pattern, method, filePath });
45
+ }
46
+ return routes.sort((a, b) => {
47
+ const left = a.pattern.split("/"), right = b.pattern.split("/"), rank = (part) => part?.endsWith("*") ? 0 : part?.startsWith(":") ? 1 : 2;
48
+ for (let i = 0;i < Math.max(left.length, right.length); i++) {
49
+ const delta = rank(right[i]) - rank(left[i]);
50
+ if (delta)
51
+ return delta;
52
+ }
53
+ return a.pattern.localeCompare(b.pattern) || a.method.localeCompare(b.method);
54
+ });
55
+ }
56
+ export async function generateApiTypes(root, routes) {
57
+ const target = stateDir(root, "api-types.d.ts"), lines = ["// Generated by stx. Include this file in tsconfig.json.", "declare module '@stacksjs/stx/api-client' {", " interface KnownApiRoutes {"];
58
+ for (const route of routes) {
59
+ const specifier = `./${path.relative(path.dirname(target), route.filePath).replace(/\\/g, "/")}`, { params } = patternToRegex(route.pattern);
60
+ lines.push(` ${JSON.stringify(`${route.method} ${route.pattern}`)}: { params: { ${params.map((name) => `${JSON.stringify(name)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(specifier)}).default>> }`);
61
+ }
62
+ lines.push(" }", "}", "export {}", "");
63
+ const content = lines.join(`
64
+ `);
65
+ if (!await Bun.file(target).exists() || await Bun.file(target).text() !== content)
66
+ await Bun.write(target, content);
67
+ return target;
68
+ }
69
+ export async function buildServerApi(root, outputDir, options = {}) {
70
+ const routes = discoverServerApi(root, options);
71
+ await generateApiTypes(root, routes);
72
+ const result = [];
73
+ for (const route of routes) {
74
+ const bundled = await Bun.build({ entrypoints: [route.filePath], target: "bun", format: "esm", minify: !1, splitting: !1 });
75
+ if (!bundled.success)
76
+ throw Error(`API build failed for ${route.filePath}: ${bundled.logs.join(`
77
+ `)}`);
78
+ const output = bundled.outputs.find((file) => file.kind === "entry-point");
79
+ if (!output)
80
+ throw Error(`No API bundle for ${route.filePath}`);
81
+ if (bundled.outputs.length !== 1)
82
+ throw Error(`API endpoint ${route.filePath} emits assets; package those explicitly instead`);
83
+ const filePath = `server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await output.arrayBuffer()).digest("hex").slice(0, 20)}.mjs`;
84
+ await Bun.write(path.join(outputDir, filePath), output);
85
+ result.push({ ...route, filePath });
86
+ }
87
+ return result;
88
+ }
89
+ export function createApiDispatcher(routes, load) {
90
+ const compiled = routes.map((route) => ({ route, ...patternToRegex(route.pattern) }));
91
+ return async (request) => {
92
+ const pathname = new URL(request.url).pathname, matches = compiled.filter((entry) => entry.regex.test(pathname));
93
+ if (!matches.length)
94
+ return null;
95
+ const pattern = matches[0].route.pattern, canonical = (value) => value.replace(/:\w+/g, ":param"), candidates = matches.filter((entry) => canonical(entry.route.pattern) === canonical(pattern)), method = request.method, matched = candidates.find((entry) => entry.route.method === method) ?? (method === "HEAD" ? candidates.find((entry) => entry.route.method === "GET") : void 0);
96
+ if (!matched) {
97
+ const allow = new Set(candidates.map((entry) => entry.route.method));
98
+ if (allow.has("GET"))
99
+ allow.add("HEAD");
100
+ allow.add("OPTIONS");
101
+ return new Response(null, { status: method === "OPTIONS" ? 204 : 405, headers: { Allow: Array.from(allow).sort().join(", ") } });
102
+ }
103
+ const match = matched.regex.exec(pathname), params = Object.create(null);
104
+ try {
105
+ matched.params.forEach((name, i) => {
106
+ params[name] = decodeURIComponent(match[i + 1]);
107
+ });
108
+ } catch {
109
+ return new Response("Invalid URL parameter encoding", { status: 400 });
110
+ }
111
+ try {
112
+ const handler = await load(matched.route);
113
+ if (typeof handler !== "function")
114
+ throw Error(`API endpoint ${matched.route.filePath} must default-export a handler`);
115
+ const value = await handler(request, { params }), response = value instanceof Response ? value : value === void 0 ? new Response(null, { status: 204 }) : Response.json(value);
116
+ if (method === "HEAD")
117
+ return new Response(null, { status: response.status, headers: response.headers });
118
+ return response;
119
+ } catch (error) {
120
+ console.error(`[stx] API error for ${method} ${pattern}:`, error);
121
+ return Response.json({ error: "Internal Server Error" }, { status: 500 });
122
+ }
123
+ };
124
+ }
125
+ export function productionApiDispatcher(outputDir, routes) {
126
+ return createApiDispatcher(routes, async (route) => (await import(pathToFileURL(path.resolve(outputDir, route.filePath)).href)).default);
127
+ }
128
+ export async function createServerApi(root, enabled) {
129
+ if (!enabled)
130
+ return async () => null;
131
+ const options = enabled === !0 ? {} : enabled, initial = discoverServerApi(root, options);
132
+ await generateApiTypes(root, initial);
133
+ return async (request) => {
134
+ if (!new URL(request.url).pathname.match(/^\/api(?:\/|$)/))
135
+ return null;
136
+ try {
137
+ const routes = discoverServerApi(root, options);
138
+ await generateApiTypes(root, routes);
139
+ const { loadStxConfig } = await import("./config.js"), runtimeConfig = resolveRuntimeConfig((await loadStxConfig(root)).runtimeConfig);
140
+ return await withRuntimeConfig(runtimeConfig, () => createApiDispatcher(routes, async (route) => {
141
+ const build = await Bun.build({ entrypoints: [route.filePath], target: "bun", format: "esm", splitting: !1 });
142
+ if (!build.success)
143
+ throw Error(build.logs.join(`
144
+ `));
145
+ const output = build.outputs.find((file) => file.kind === "entry-point");
146
+ if (!output || build.outputs.length !== 1)
147
+ throw Error(`Unsupported API bundle output: ${route.filePath}`);
148
+ return (await import(`data:text/javascript;base64,${Buffer.from(await output.text()).toString("base64")}`)).default;
149
+ })(request));
150
+ } catch (error) {
151
+ console.error("[stx] API discovery failed:", error);
152
+ return Response.json({ error: "API discovery failed; check the server log" }, { status: 500 });
153
+ }
154
+ };
155
+ }
156
+ export function isServerApiSource(filePath, root, enabled) {
157
+ if (isLayerConfigSource(filePath))
158
+ return !0;
159
+ const privateName = /^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;
160
+ if (privateName.test(path.basename(filePath)))
161
+ return !0;
162
+ try {
163
+ if (privateName.test(path.basename(fs.realpathSync(filePath))))
164
+ return !0;
165
+ } catch {}
166
+ if (discoveredSources.has(path.resolve(filePath)))
167
+ return !0;
168
+ if (!enabled)
169
+ return !1;
170
+ const apiDir = path.resolve(root, typeof enabled === "object" ? enabled.dir ?? "server/api" : "server/api"), canonical = (value) => {
171
+ try {
172
+ return fs.realpathSync(value);
173
+ } catch {
174
+ return path.resolve(value);
175
+ }
176
+ }, file = canonical(filePath);
177
+ return [apiDir, path.resolve(root, "server"), path.resolve(root, ".output/server")].some((value) => {
178
+ const directory = canonical(value);
179
+ return file === directory || file.startsWith(`${directory}${path.sep}`);
180
+ });
181
+ }