@stacksjs/stx 0.2.217 → 0.2.219

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 (177) hide show
  1. package/dist/{chunk-pdh79z63.js → chunk-02e5r50t.js} +1 -1
  2. package/dist/chunk-03t9yevc.js +2 -0
  3. package/dist/{chunk-z47tw39z.js → chunk-0kj7rses.js} +2 -2
  4. package/dist/{chunk-c0p9kf53.js → chunk-0m7mt6zc.js} +1 -1
  5. package/dist/{chunk-wbq7cp57.js → chunk-0wwbjhs2.js} +1 -1
  6. package/dist/chunk-1339ynfv.js +2 -0
  7. package/dist/{chunk-96kpqgh3.js → chunk-1b0yfasc.js} +1 -1
  8. package/dist/{chunk-b6jhznkh.js → chunk-1t7cy4zb.js} +1 -1
  9. package/dist/{chunk-808qy9cq.js → chunk-27crt28c.js} +196 -196
  10. package/dist/{chunk-xwc4pg5w.js → chunk-29y9cskh.js} +2 -2
  11. package/dist/{chunk-st5qggks.js → chunk-2v9qzeb5.js} +1 -1
  12. package/dist/{chunk-1bvstnz4.js → chunk-2w1qaf5b.js} +2 -2
  13. package/dist/chunk-395dm3a0.js +3 -0
  14. package/dist/{chunk-w0ng9e1m.js → chunk-3q8c4kex.js} +1 -1
  15. package/dist/{chunk-xkd164zg.js → chunk-3tm1df07.js} +1 -1
  16. package/dist/chunk-3v9drr1f.js +2 -0
  17. package/dist/chunk-40zvzck0.js +2 -0
  18. package/dist/chunk-4cm1n157.js +2 -0
  19. package/dist/{chunk-j0tfxbns.js → chunk-4q17c8sg.js} +2 -2
  20. package/dist/chunk-4v8358s4.js +2 -0
  21. package/dist/{chunk-j5vyt8wd.js → chunk-54cefpt2.js} +1 -1
  22. package/dist/chunk-55yz6apk.js +2 -0
  23. package/dist/chunk-5xg4y72b.js +2 -0
  24. package/dist/chunk-62ypndze.js +2 -0
  25. package/dist/{chunk-x8b16v5q.js → chunk-6b80avmh.js} +1 -1
  26. package/dist/chunk-6shcpcn9.js +2 -0
  27. package/dist/{chunk-s7dqawk0.js → chunk-6v2pfq30.js} +2 -2
  28. package/dist/{chunk-n8zpm7xb.js → chunk-6xtajfpz.js} +1 -1
  29. package/dist/{chunk-bsr7yrxh.js → chunk-71kpxn5y.js} +1 -1
  30. package/dist/{chunk-mxqp7x07.js → chunk-7az4zfm8.js} +2 -2
  31. package/dist/{chunk-7md45k52.js → chunk-7ftn4dpc.js} +2 -2
  32. package/dist/{chunk-y4hkqsgw.js → chunk-81jqzypz.js} +2 -2
  33. package/dist/{chunk-q8szpd6w.js → chunk-8dz63q4e.js} +1 -1
  34. package/dist/chunk-8ksdma43.js +2 -0
  35. package/dist/{chunk-weajy31v.js → chunk-937b32gs.js} +2 -2
  36. package/dist/{chunk-crmk2jzf.js → chunk-97t2tj98.js} +1 -1
  37. package/dist/chunk-99ncmbh8.js +2 -0
  38. package/dist/{chunk-9064gyt5.js → chunk-9k6890an.js} +2 -2
  39. package/dist/{chunk-pezxve4a.js → chunk-9tmcj4y7.js} +3 -3
  40. package/dist/{chunk-ymccpdg6.js → chunk-a39thx3m.js} +1 -1
  41. package/dist/{chunk-cqt6ry1e.js → chunk-a53v1er1.js} +1 -1
  42. package/dist/chunk-a7zjfav5.js +2 -0
  43. package/dist/chunk-aca3hetd.js +2 -0
  44. package/dist/{chunk-7mst8kqm.js → chunk-ags8t27c.js} +1 -1
  45. package/dist/{chunk-zgvga8rc.js → chunk-ap23bgyb.js} +1 -1
  46. package/dist/chunk-b9kdezkq.js +2 -0
  47. package/dist/{chunk-1nnpwrqj.js → chunk-bbrm07kg.js} +2 -2
  48. package/dist/{chunk-y2jr10y8.js → chunk-bhqcp8b0.js} +2 -2
  49. package/dist/{chunk-fnkxbnka.js → chunk-bx766t25.js} +1 -1
  50. package/dist/{chunk-ht51fz7w.js → chunk-c23nyjd0.js} +1 -1
  51. package/dist/chunk-c6pb88k7.js +2 -0
  52. package/dist/{chunk-47pge5gz.js → chunk-ch5n6w31.js} +1 -1
  53. package/dist/chunk-cmz46x9n.js +2 -0
  54. package/dist/{chunk-m2mhtpwy.js → chunk-cnkex10g.js} +1 -1
  55. package/dist/{chunk-3es366z4.js → chunk-dve5ehgr.js} +1 -1
  56. package/dist/{chunk-vgk5v31k.js → chunk-e31kcmmd.js} +1 -1
  57. package/dist/{chunk-gvm4dw6p.js → chunk-e4mj16za.js} +2 -2
  58. package/dist/chunk-e5s2b5z3.js +2 -0
  59. package/dist/{chunk-msjzqne1.js → chunk-es9ygzeh.js} +1 -1
  60. package/dist/{chunk-p7qqbw2k.js → chunk-ests3gcx.js} +2 -2
  61. package/dist/{chunk-jmnftb29.js → chunk-fc33v1qf.js} +2 -2
  62. package/dist/{chunk-q4se9rtw.js → chunk-fk1qyjdw.js} +1 -1
  63. package/dist/chunk-gdaq67k8.js +2 -0
  64. package/dist/{chunk-f6jm4hy3.js → chunk-gfvb1926.js} +1 -1
  65. package/dist/{chunk-9b82d4g5.js → chunk-gnmft4dz.js} +1 -1
  66. package/dist/{chunk-74gc1x9x.js → chunk-gzjnkskc.js} +2 -2
  67. package/dist/chunk-h8s4n9vj.js +2 -0
  68. package/dist/chunk-hdy6e3yf.js +2 -0
  69. package/dist/chunk-hkh1d5m5.js +18 -0
  70. package/dist/{chunk-53ajah3v.js → chunk-hnrtm6xb.js} +2 -2
  71. package/dist/chunk-hzg9r43r.js +2 -0
  72. package/dist/{chunk-zxb128xa.js → chunk-j0bcnfbq.js} +2 -2
  73. package/dist/chunk-jde8jz10.js +2 -0
  74. package/dist/chunk-jn7g22fd.js +2 -0
  75. package/dist/{chunk-hncp9gz6.js → chunk-jw93tsxz.js} +1 -1
  76. package/dist/{chunk-3twce5kp.js → chunk-jzavbzn8.js} +1 -1
  77. package/dist/{chunk-3wd9kfyz.js → chunk-k0cqdptr.js} +1 -1
  78. package/dist/{chunk-qd1nadff.js → chunk-khxs70kb.js} +2 -2
  79. package/dist/{chunk-8anh6d36.js → chunk-kqdrjd0e.js} +1 -1
  80. package/dist/{chunk-fvjh7rx0.js → chunk-kw311y8k.js} +1 -1
  81. package/dist/{chunk-zat2ndst.js → chunk-m3dcd2j3.js} +347 -347
  82. package/dist/{chunk-yckd6ks5.js → chunk-m9tpk603.js} +1 -1
  83. package/dist/{chunk-yf3bmmkk.js → chunk-mt7htpvg.js} +1 -1
  84. package/dist/{chunk-1nm2xrvq.js → chunk-n09vpazf.js} +1 -1
  85. package/dist/{chunk-dmb6t0qj.js → chunk-n98pfm3h.js} +2 -2
  86. package/dist/{chunk-6xg3j487.js → chunk-n98zvmdq.js} +1 -1
  87. package/dist/{chunk-khrtzbxd.js → chunk-p5ktexx3.js} +1 -1
  88. package/dist/{chunk-fvpaf9v5.js → chunk-p6dtgqeq.js} +2 -2
  89. package/dist/{chunk-yk1smsev.js → chunk-p9mx8rh4.js} +1 -1
  90. package/dist/{chunk-ne8sygmy.js → chunk-q98bqfzh.js} +1 -1
  91. package/dist/chunk-rr6scjzr.js +2 -0
  92. package/dist/{chunk-9xh78snm.js → chunk-s6yn1mbm.js} +1 -1
  93. package/dist/{chunk-1306tswx.js → chunk-sgncfrb3.js} +1 -1
  94. package/dist/chunk-t1fqr070.js +2 -0
  95. package/dist/{chunk-rg6v68ya.js → chunk-t9mf6ddw.js} +1 -1
  96. package/dist/{chunk-css1sfnr.js → chunk-ta43eqe0.js} +1 -1
  97. package/dist/{chunk-rczpw37w.js → chunk-tmfrweee.js} +1 -1
  98. package/dist/{chunk-j3njy10j.js → chunk-tpjekhep.js} +2 -2
  99. package/dist/chunk-tvcf5760.js +2 -0
  100. package/dist/chunk-tw2ydyww.js +4 -0
  101. package/dist/chunk-vcw2ft8z.js +2 -0
  102. package/dist/{chunk-p8pyqr7p.js → chunk-vdqbbqe2.js} +1 -1
  103. package/dist/chunk-vg9xvtqz.js +2 -0
  104. package/dist/{chunk-a2rj5ce0.js → chunk-vgtcj29n.js} +2 -2
  105. package/dist/chunk-vh7h37mn.js +2 -0
  106. package/dist/chunk-vhajz6q3.js +2 -0
  107. package/dist/{chunk-x13f5bbe.js → chunk-vhx0v4jv.js} +1 -1
  108. package/dist/{chunk-c7pvwvse.js → chunk-vswv49x0.js} +1 -1
  109. package/dist/{chunk-zj44h5kk.js → chunk-vwn8hkr2.js} +1 -1
  110. package/dist/{chunk-z2sp0k8d.js → chunk-vx8zk4yt.js} +1 -1
  111. package/dist/{chunk-aw9z3m10.js → chunk-wzjcw1h6.js} +1 -1
  112. package/dist/{chunk-tryt2h85.js → chunk-xdq4zkqk.js} +1 -1
  113. package/dist/{chunk-3fwn9edg.js → chunk-xvh1k1a4.js} +1 -1
  114. package/dist/chunk-y2j14rjd.js +2 -0
  115. package/dist/chunk-yd3rg2be.js +2 -0
  116. package/dist/{chunk-7zk48rd8.js → chunk-ynqc1gyr.js} +1 -1
  117. package/dist/{chunk-hyrjade7.js → chunk-z2gv9n8s.js} +1 -1
  118. package/dist/{chunk-trtm887x.js → chunk-z3cgw8j4.js} +1 -1
  119. package/dist/{chunk-whxregkn.js → chunk-zbww31ss.js} +1 -1
  120. package/dist/cli.js +14 -14
  121. package/dist/craft-entry.js +1 -1
  122. package/dist/craft.js +1 -1
  123. package/dist/database.js +1 -1
  124. package/dist/dev-server/serve-app.js +29 -7
  125. package/dist/page-response.d.ts +113 -0
  126. package/dist/page-response.js +106 -1
  127. package/dist/process.js +2 -0
  128. package/dist/production-server.js +7 -3
  129. package/dist/pwa.js +2 -2
  130. package/dist/render.d.ts +14 -0
  131. package/dist/render.js +3 -19
  132. package/dist/serve.js +19 -10
  133. package/dist/ssg.js +2 -2
  134. package/dist/template-compiler.d.ts +1 -0
  135. package/dist/template-compiler.js +2 -0
  136. package/dist/template-hydrator.d.ts +1 -1
  137. package/dist/template-hydrator.js +4 -3
  138. package/dist/variable-extractor.d.ts +1 -1
  139. package/dist/variable-extractor.js +6 -2
  140. package/dist/visual-testing.js +1 -1
  141. package/package.json +5 -5
  142. package/dist/chunk-10yft4b7.js +0 -2
  143. package/dist/chunk-17atrbv2.js +0 -2
  144. package/dist/chunk-23vxz3hp.js +0 -2
  145. package/dist/chunk-2me28xee.js +0 -2
  146. package/dist/chunk-2w5d5tw1.js +0 -2
  147. package/dist/chunk-2xeq5xnf.js +0 -2
  148. package/dist/chunk-2z6k7gsa.js +0 -2
  149. package/dist/chunk-3fxcwk6a.js +0 -2
  150. package/dist/chunk-4vwxgmg0.js +0 -2
  151. package/dist/chunk-5gr4vv7m.js +0 -2
  152. package/dist/chunk-775fabj4.js +0 -2
  153. package/dist/chunk-8cyv5316.js +0 -2
  154. package/dist/chunk-8xtvmwpr.js +0 -2
  155. package/dist/chunk-9db2f09j.js +0 -2
  156. package/dist/chunk-9h908knr.js +0 -2
  157. package/dist/chunk-a1ydhf5t.js +0 -3
  158. package/dist/chunk-ba18hn7n.js +0 -2
  159. package/dist/chunk-bd0yv6a0.js +0 -2
  160. package/dist/chunk-cr7s8q08.js +0 -2
  161. package/dist/chunk-d48tzd8c.js +0 -2
  162. package/dist/chunk-dcy8hg45.js +0 -2
  163. package/dist/chunk-e6377wfq.js +0 -4
  164. package/dist/chunk-jnjxf5t2.js +0 -2
  165. package/dist/chunk-n4smz31k.js +0 -18
  166. package/dist/chunk-njkv35c3.js +0 -2
  167. package/dist/chunk-q3ea7q6t.js +0 -2
  168. package/dist/chunk-qwzfdq8q.js +0 -2
  169. package/dist/chunk-r153ybwd.js +0 -2
  170. package/dist/chunk-tg0w29j1.js +0 -2
  171. package/dist/chunk-tqhwzjj7.js +0 -2
  172. package/dist/chunk-vgr8kykv.js +0 -2
  173. package/dist/chunk-w670sde5.js +0 -2
  174. package/dist/chunk-x9bsft57.js +0 -2
  175. package/dist/chunk-y05vd24g.js +0 -2
  176. package/dist/chunk-yrqnsd3a.js +0 -2
  177. package/dist/chunk-z0hkt5sk.js +0 -2
@@ -1,12 +1,117 @@
1
+ import { safeEvaluate } from "./safe-evaluator.js";
1
2
  const MIN_HTTP_STATUS = 100, MAX_HTTP_STATUS = 599;
3
+ export const RESPONSE_STATUS_KEY = "__stxResponseStatus", RESPONSE_HEADERS_KEY = "__stxResponseHeaders";
4
+ export function isHttpStatus(value) {
5
+ return typeof value === "number" && Number.isInteger(value) && value >= MIN_HTTP_STATUS && value <= MAX_HTTP_STATUS;
6
+ }
2
7
  export function extractPageResponseStatus(source) {
3
8
  for (const call of source.matchAll(/\bdefinePageMeta\s*\(\s*\{([\s\S]*?)\}\s*\)/g)) {
4
9
  const match = call[1].match(/(?:^|,)\s*status\s*:\s*(\d{3})(?=\s*(?:,|$))/);
5
10
  if (!match)
6
11
  continue;
7
12
  const status = Number(match[1]);
8
- if (Number.isInteger(status) && status >= MIN_HTTP_STATUS && status <= MAX_HTTP_STATUS)
13
+ if (isHttpStatus(status))
9
14
  return status;
10
15
  }
11
16
  return;
12
17
  }
18
+ export function recordResponseStatus(context, status) {
19
+ if (!context || typeof context !== "object")
20
+ return !1;
21
+ const code = typeof status === "string" && /^\d+$/.test(status.trim()) ? Number(status.trim()) : status;
22
+ if (!isHttpStatus(code))
23
+ return !1;
24
+ context[RESPONSE_STATUS_KEY] = code;
25
+ return !0;
26
+ }
27
+ export function recordResponseHeader(context, name, value) {
28
+ if (!context || typeof context !== "object")
29
+ return;
30
+ const header = String(name ?? "").trim();
31
+ if (!header)
32
+ return;
33
+ context[RESPONSE_HEADERS_KEY] = { ...context[RESPONSE_HEADERS_KEY], [header]: String(value) };
34
+ }
35
+ export function readResponseStatus(context) {
36
+ const status = context?.[RESPONSE_STATUS_KEY];
37
+ return isHttpStatus(status) ? status : void 0;
38
+ }
39
+ export function readResponseHeaders(context) {
40
+ const headers = context?.[RESPONSE_HEADERS_KEY];
41
+ if (!headers || typeof headers !== "object")
42
+ return;
43
+ const entries = Object.entries(headers).map(([k, v]) => [k, String(v)]);
44
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
45
+ }
46
+ export function syncRecordedResponse(from, to) {
47
+ if (!from || !to || from === to || typeof to !== "object")
48
+ return;
49
+ const status = readResponseStatus(from);
50
+ if (status !== void 0)
51
+ to[RESPONSE_STATUS_KEY] = status;
52
+ const headers = readResponseHeaders(from);
53
+ if (headers)
54
+ to[RESPONSE_HEADERS_KEY] = { ...to[RESPONSE_HEADERS_KEY], ...headers };
55
+ }
56
+ export function responseBindings(context) {
57
+ return {
58
+ setResponseStatus: (status) => {
59
+ recordResponseStatus(context, status);
60
+ },
61
+ notFound: (status = 404) => {
62
+ const code = isHttpStatus(status) && status >= 400 ? status : 404;
63
+ recordResponseStatus(context, code);
64
+ },
65
+ setResponseHeader: (name, value) => {
66
+ recordResponseHeader(context, name, value);
67
+ }
68
+ };
69
+ }
70
+ export function processStatusDirective(template, context, options = {}) {
71
+ if (!template.includes("@status"))
72
+ return template;
73
+ const { filePath, buildMode } = options, precompiling = buildMode === "compile";
74
+ let result = "", cursor = 0;
75
+ const pattern = /@status\s*\(/g;
76
+ let match;
77
+ while ((match = pattern.exec(template)) !== null) {
78
+ const close = closingParen(template, match.index + match[0].length - 1);
79
+ if (close < 0)
80
+ break;
81
+ const arg = template.slice(match.index + match[0].length, close).trim(), value = /^\d+$/.test(arg) ? Number(arg) : safeEvaluate(arg, context), where = filePath ? ` in ${filePath}` : "";
82
+ if (precompiling)
83
+ console.warn(`[stx] @status(${arg})${where} is skipped when precompiling: the build has no request, so the branch it sits in is not the one a visitor will get. Call notFound() or setResponseStatus(${arg}) from <script server> instead \u2014 that runs per request.`);
84
+ else if (!recordResponseStatus(context, value))
85
+ console.warn(`[stx] @status(${arg})${where} is not an HTTP status (100-599) \u2014 ignoring it.`);
86
+ result += template.slice(cursor, match.index);
87
+ cursor = close + 1 + (template.slice(close + 1).match(/^[^\S\n]*\n?/)?.[0].length ?? 0);
88
+ pattern.lastIndex = cursor;
89
+ }
90
+ return cursor === 0 ? template : result + template.slice(cursor);
91
+ }
92
+ function closingParen(source, open) {
93
+ let depth = 1, quote = null, escaped = !1;
94
+ for (let i = open + 1;i < source.length; i++) {
95
+ const char = source[i];
96
+ if (escaped) {
97
+ escaped = !1;
98
+ continue;
99
+ }
100
+ if (quote) {
101
+ if (char === "\\")
102
+ escaped = !0;
103
+ else if (char === quote)
104
+ quote = null;
105
+ continue;
106
+ }
107
+ if (char === '"' || char === "'" || char === "`") {
108
+ quote = char;
109
+ continue;
110
+ }
111
+ if (char === "(")
112
+ depth++;
113
+ else if (char === ")" && --depth === 0)
114
+ return i;
115
+ }
116
+ return -1;
117
+ }
package/dist/process.js CHANGED
@@ -12,6 +12,7 @@ import { processAnimationDirectives } from "./animation.js";
12
12
  import { generateRuntimeScript, processEventDirectives } from "./events.js";
13
13
  import { extractBridgeData, processClientScript } from "./client-script.js";
14
14
  import { extractPageMetaFromSource, pageMetaLayout } from "./page-meta.js";
15
+ import { processStatusDirective } from "./page-response.js";
15
16
  import { processReactiveDirectives } from "./reactive.js";
16
17
  import { processMarkdownFileDirectives } from "./assets.js";
17
18
  import { processAuthDirectives, processConditionals, processEnvDirective, processIssetEmptyDirectives } from "./conditionals.js";
@@ -694,6 +695,7 @@ async function processOtherDirectives(template, context, filePath, options, depe
694
695
  output = output.replace(/@push\s*\(\s*['"][^'"]+['"]\s*\)[\s\S]*?@endpush/g, "");
695
696
  output = processRefAttributes(output);
696
697
  output = processConditionals(output, context, filePath);
698
+ output = processStatusDirective(output, context, { filePath, buildMode: opts.buildMode });
697
699
  output = processIssetEmptyDirectives(output, context);
698
700
  output = processEnvDirective(output, context);
699
701
  output = processBasicFormDirectives(output, context);
@@ -159,13 +159,14 @@ export async function startProductionServer(options = {}) {
159
159
  }
160
160
  if (!isMutating && !compiled.hasServerScripts && Object.keys(compiled.placeholders).length === 0)
161
161
  return new Response(compiled.html, {
162
+ status: compiled.status ?? 200,
162
163
  headers: {
163
164
  "Content-Type": "text/html",
164
165
  "Cache-Control": "public, max-age=60"
165
166
  }
166
167
  });
167
168
  try {
168
- const { html, boundaries, redirect, cookies } = await hydrateTemplateStream(compiled, {
169
+ const { html, boundaries, redirect, cookies, status, headers: pageHeaders } = await hydrateTemplateStream(compiled, {
169
170
  params,
170
171
  request,
171
172
  method: request.method
@@ -175,7 +176,8 @@ export async function startProductionServer(options = {}) {
175
176
  if (boundaries && boundaries.length > 0) {
176
177
  const { renderStreamingPage, streamToResponse } = await import("./streaming.js");
177
178
  return streamToResponse(renderStreamingPage(html, boundaries, { timeoutMs: 30000 }), {
178
- headers: { "Cache-Control": "no-cache" }
179
+ status: status ?? compiled.status ?? 200,
180
+ headers: { "Cache-Control": "no-cache", ...pageHeaders }
179
181
  });
180
182
  }
181
183
  const headers = new Headers({
@@ -184,7 +186,9 @@ export async function startProductionServer(options = {}) {
184
186
  });
185
187
  for (const cookie of cookies ?? [])
186
188
  headers.append("Set-Cookie", cookie);
187
- return new Response(html, { headers });
189
+ for (const [name, value] of Object.entries(pageHeaders ?? {}))
190
+ headers.set(name, value);
191
+ return new Response(html, { status: status ?? compiled.status ?? 200, headers });
188
192
  } catch (error) {
189
193
  console.error(`[stx] Hydration error for ${pathname}:`, error);
190
194
  return new Response(compiled.html, {
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Bk as wq,Ck as dq,Dk as Cq,Ek as mq,Fk as gq}from"./chunk-yf3bmmkk.js";import{Gk as S,Hk as Tq,Ik as _q,Jk as z,Kk as D,Lk as P,Mk as kq,Nk as vq,Ok as w,Pk as Iq,Qk as d,Rk as Hq,Sk as Oq,Tk as Mq}from"./chunk-53ajah3v.js";import{$t as Aq,au as bq,bu as Sq,cu as zq,du as Dq,eu as Pq}from"./chunk-3wd9kfyz.js";import{iu as N}from"./chunk-trtm887x.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-17atrbv2.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{Ak as wq,Bk as dq,Ck as Cq,Dk as mq,Ek as gq}from"./chunk-mt7htpvg.js";import{Fk as S,Gk as Tq,Hk as _q,Ik as z,Jk as D,Kk as P,Lk as kq,Mk as vq,Nk as w,Ok as Iq,Pk as d,Qk as Hq,Rk as Oq,Sk as Mq}from"./chunk-hnrtm6xb.js";import{ju as Aq,ku as bq,lu as Sq,mu as zq,nu as Dq,ou as Pq}from"./chunk-k0cqdptr.js";import{su as N}from"./chunk-z3cgw8j4.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-b9kdezkq.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.d.ts CHANGED
@@ -1,4 +1,18 @@
1
1
  import type { StxOptions } from './types';
2
+ /**
3
+ * Render a .stx template file to an HTML string.
4
+ *
5
+ * This is the primary rendering API. It:
6
+ * 1. Reads the template file
7
+ * 2. Extracts and executes server-side scripts
8
+ * 3. Processes all stx directives (conditionals, loops, expressions, etc.)
9
+ * 4. Injects client-side scripts
10
+ * 5. Returns the final HTML string
11
+ *
12
+ * @param filePath - Path to the .stx template file
13
+ * @param renderOptions - Additional rendering options
14
+ * @returns The rendered HTML string
15
+ */
2
16
  export declare function renderTemplate(filePath: string, renderOptions?: RenderOptions): Promise<string>;
3
17
  /**
4
18
  * Render an inline stx template string to HTML.
package/dist/render.js CHANGED
@@ -5,6 +5,7 @@ import { injectRouterScript, processDirectives } from "./process.js";
5
5
  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
+ import { responseBindings, syncRecordedResponse } from "./page-response.js";
8
9
  function parseTemplate(content) {
9
10
  let workingContent = content;
10
11
  const templateBlock = findSfcTemplateBlock(content);
@@ -53,10 +54,6 @@ ${html}
53
54
  </body>
54
55
  </html>`;
55
56
  }
56
- function recordOn(target, key, value) {
57
- if (target && typeof target === "object")
58
- target[key] = value;
59
- }
60
57
  export async function renderTemplate(filePath, renderOptions = {}) {
61
58
  const resolvedPath = resolve(filePath), file = Bun.file(resolvedPath);
62
59
  if (!await file.exists())
@@ -103,21 +100,7 @@ export async function renderTemplateString(content, filePath, renderOptions = {}
103
100
  __stx_sfc_mode: !0,
104
101
  __stx_inject_css: renderOptions.injectCSS === !0,
105
102
  __stxServeContext: void 0,
106
- setResponseStatus: (status) => {
107
- if (Number.isInteger(status) && status >= 100 && status <= 599)
108
- recordOn(renderOptions.context, "__stxResponseStatus", status);
109
- },
110
- notFound: (status = 404) => {
111
- const code = Number.isInteger(status) && status >= 400 && status <= 599 ? status : 404;
112
- recordOn(renderOptions.context, "__stxResponseStatus", code);
113
- },
114
- setResponseHeader: (name, value) => {
115
- if (!name)
116
- return;
117
- const headers = renderOptions.context?.__stxResponseHeaders || {};
118
- headers[String(name)] = String(value);
119
- recordOn(renderOptions.context, "__stxResponseHeaders", headers);
120
- },
103
+ ...responseBindings(renderOptions.context ?? {}),
121
104
  definePageMeta: () => {},
122
105
  ...renderOptions.context || {}
123
106
  };
@@ -126,6 +109,7 @@ export async function renderTemplateString(content, filePath, renderOptions = {}
126
109
  const dependencies = new Set;
127
110
  let output = templateContent;
128
111
  output = await processDirectives(output, context, filePath, options, dependencies);
112
+ syncRecordedResponse(context, renderOptions.context);
129
113
  if (renderOptions.templateOnly) {
130
114
  output = output.replace(/<script data-stx-scoped>[\s\S]*?<\/script>\s*/gi, "");
131
115
  output = output.replace(/<!-- stx SEO Tags -->[\s\S]*?(?=<)/i, "");
package/dist/serve.js CHANGED
@@ -6,6 +6,7 @@ import { readMarkdownFile } from "./assets.js";
6
6
  import { processDirectives } from "./process.js";
7
7
  import { extractVariables } from "./utils.js";
8
8
  import { compressResponse } from "./compression.js";
9
+ import { readResponseHeaders, readResponseStatus } from "./page-response.js";
9
10
  export function htmlResponse(html, status = 200, headers = {}) {
10
11
  return new Response(html, {
11
12
  status,
@@ -33,7 +34,7 @@ export async function serve(options = {}) {
33
34
  async function processStxFile(filePath) {
34
35
  const stats = fs.statSync(filePath), cacheKey = `${filePath}:${stats.mtimeMs}`, cached = fileCache.get(cacheKey);
35
36
  if (cached)
36
- return cached.content;
37
+ return { content: cached.content, status: cached.status, headers: cached.headers };
37
38
  for (const key of fileCache.keys())
38
39
  if (key.startsWith(`${filePath}:`) && key !== cacheKey)
39
40
  fileCache.delete(key);
@@ -76,8 +77,9 @@ $1`);
76
77
  output += `
77
78
  ${scriptsHtml}`;
78
79
  }
79
- fileCache.set(cacheKey, { content: output, mtime: stats.mtimeMs });
80
- return output;
80
+ const status = readResponseStatus(context), headers = readResponseHeaders(context);
81
+ fileCache.set(cacheKey, { content: output, mtime: stats.mtimeMs, status, headers });
82
+ return { content: output, status, headers };
81
83
  }
82
84
  async function processMarkdownFile(filePath) {
83
85
  const stats = fs.statSync(filePath), cacheKey = `${filePath}:${stats.mtimeMs}`, cached = fileCache.get(cacheKey);
@@ -121,10 +123,13 @@ ${scriptsHtml}`;
121
123
  return new Response("Not Found", { status: 404 });
122
124
  }
123
125
  try {
124
- let content, contentType = "text/html";
125
- if (filePath.endsWith(".stx"))
126
- content = await processStxFile(filePath);
127
- else if (filePath.endsWith(".md"))
126
+ let content, contentType = "text/html", pageStatus, pageHeaders;
127
+ if (filePath.endsWith(".stx")) {
128
+ const page = await processStxFile(filePath);
129
+ content = page.content;
130
+ pageStatus = page.status;
131
+ pageHeaders = page.headers;
132
+ } else if (filePath.endsWith(".md"))
128
133
  content = await processMarkdownFile(filePath);
129
134
  else if (filePath.endsWith(".html"))
130
135
  content = await Bun.file(filePath).text();
@@ -140,7 +145,8 @@ ${scriptsHtml}`;
140
145
  } else
141
146
  return new Response(Bun.file(filePath));
142
147
  return new Response(content, {
143
- headers: { "Content-Type": contentType }
148
+ status: pageStatus ?? 200,
149
+ headers: { "Content-Type": contentType, ...pageHeaders }
144
150
  });
145
151
  } catch (error) {
146
152
  if (onError)
@@ -192,7 +198,7 @@ export async function serveFile(filePath, options = {}) {
192
198
  root: path.dirname(absolutePath),
193
199
  routes: {
194
200
  "/": async () => {
195
- let content;
201
+ let content, status = 200, headers;
196
202
  if (isMarkdown) {
197
203
  const { content: md } = await readMarkdownFile(absolutePath, stxOptions);
198
204
  content = md;
@@ -207,9 +213,12 @@ export async function serveFile(filePath, options = {}) {
207
213
  if (scriptContent.trim())
208
214
  await extractVariables(scriptContent, context, absolutePath);
209
215
  content = await processDirectives(templateContent, context, absolutePath, stxOptions, new Set);
216
+ status = readResponseStatus(context) ?? 200;
217
+ headers = readResponseHeaders(context);
210
218
  }
211
219
  return new Response(content, {
212
- headers: { "Content-Type": "text/html" }
220
+ status,
221
+ headers: { "Content-Type": "text/html", ...headers }
213
222
  });
214
223
  },
215
224
  ...options.routes
package/dist/ssg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{sk as Bq,tk as Hq,xk as Tq}from"./chunk-1nnpwrqj.js";import{Ak as Eq,yk as Uq,zk as Iq}from"./chunk-yckd6ks5.js";import{Wk as Nq,Xk as _q}from"./chunk-dmb6t0qj.js";import"./chunk-zgvga8rc.js";import{Cm as Aq,Lr as l,Wp as c,Zp as Oq,lp as Xq,mq as x}from"./chunk-zat2ndst.js";import"./chunk-j0tfxbns.js";import"./chunk-khrtzbxd.js";import"./chunk-8anh6d36.js";import"./chunk-3fwn9edg.js";import{Hs as zq}from"./chunk-pezxve4a.js";import{Ms as f}from"./chunk-m2mhtpwy.js";import"./chunk-6xg3j487.js";import"./chunk-q4se9rtw.js";import"./chunk-1nm2xrvq.js";import{Pt as Wq,Qt as Yq,Rt as Vq,St as jq,Tt as Gq,Ut as Lq}from"./chunk-z47tw39z.js";import"./chunk-3wd9kfyz.js";import{iu as g}from"./chunk-trtm887x.js";import O from"fs";import j from"path";import{createHash as kq}from"crypto";function Sq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var vq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function xq(q){return Bun.hash(q).toString(16)}function Jq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(vq,(J,W,z,A)=>{let N=A.trim();if(!N)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)N=Sq(N);let X=xq(N);if(!$.has(X))$.set(X,N);let H=Z.integrity?` data-stx-integrity="sha384-${kq("sha384").update(N).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${H}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var yq=new Set(["visible","idle"]);function Qq(q){if(!q.includes("data-stx-src="))return q;let Z=new Map,$=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,Q;while((Q=$.exec(q))!==null)Z.set(Q[1],Q[2]);let K=new Set,J=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,W;while((W=J.exec(q))!==null)if(yq.has(Z.get(W[1])||""))K.add(W[2]);let z=q.lastIndexOf("</head>");if(K.size===0||z===-1)return q;let A=Array.from(K).filter((N)=>!q.includes(`rel="prefetch" href="${N}"`)).map((N)=>`<link rel="prefetch" href="${N}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var Pq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function u(q){let Z=q.trim();if(!Z)return null;let $=/^https?:\/\//i.test(Z)?Z:`https://${Z}`;try{return new URL($).origin+new URL($).pathname.replace(/\/$/,"")}catch{return null}}function Cq(q){for(let Z of Pq){let $=q[Z];if(!$)continue;let Q=u($);if(Q)return{url:Q,source:"env",via:Z}}return null}function Zq(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?u($):null}async function gq(q){let{existsSync:Z}=await import("fs"),$=await import("path");for(let Q of["site.config.ts","site.config.js",".config/site.config.ts"]){let K=$.resolve(q,Q);if(!Z(K))continue;try{let J=await import(K),W=Zq(J.default??J);if(W)return W}catch{}}return null}async function $q(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=u(q.explicit);if(W)return{url:W,source:"option"}}let Q=Zq(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await gq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=Cq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Kq(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
2
+ import{rk as Bq,sk as Hq,wk as Tq}from"./chunk-bbrm07kg.js";import{xk as Uq,yk as Iq,zk as Eq}from"./chunk-m9tpk603.js";import{Vk as Nq,Wk as _q}from"./chunk-n98pfm3h.js";import"./chunk-ap23bgyb.js";import{Bm as Aq,Vr as l,eq as c,hq as Oq,vp as Xq,wq as x}from"./chunk-m3dcd2j3.js";import"./chunk-4q17c8sg.js";import"./chunk-p5ktexx3.js";import"./chunk-kqdrjd0e.js";import"./chunk-xvh1k1a4.js";import{Rs as zq}from"./chunk-9tmcj4y7.js";import{Ws as f}from"./chunk-cnkex10g.js";import"./chunk-n98zvmdq.js";import"./chunk-fk1qyjdw.js";import"./chunk-n09vpazf.js";import{$t as Vq,Zt as Wq,_t as Yq,au as jq,bu as Gq,cu as Lq}from"./chunk-0kj7rses.js";import"./chunk-k0cqdptr.js";import{su as g}from"./chunk-z3cgw8j4.js";import O from"fs";import j from"path";import{createHash as kq}from"crypto";function Sq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var vq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function xq(q){return Bun.hash(q).toString(16)}function Jq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(vq,(J,W,z,A)=>{let N=A.trim();if(!N)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)N=Sq(N);let X=xq(N);if(!$.has(X))$.set(X,N);let H=Z.integrity?` data-stx-integrity="sha384-${kq("sha384").update(N).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${H}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var yq=new Set(["visible","idle"]);function Qq(q){if(!q.includes("data-stx-src="))return q;let Z=new Map,$=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,Q;while((Q=$.exec(q))!==null)Z.set(Q[1],Q[2]);let K=new Set,J=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,W;while((W=J.exec(q))!==null)if(yq.has(Z.get(W[1])||""))K.add(W[2]);let z=q.lastIndexOf("</head>");if(K.size===0||z===-1)return q;let A=Array.from(K).filter((N)=>!q.includes(`rel="prefetch" href="${N}"`)).map((N)=>`<link rel="prefetch" href="${N}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var Pq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function u(q){let Z=q.trim();if(!Z)return null;let $=/^https?:\/\//i.test(Z)?Z:`https://${Z}`;try{return new URL($).origin+new URL($).pathname.replace(/\/$/,"")}catch{return null}}function Cq(q){for(let Z of Pq){let $=q[Z];if(!$)continue;let Q=u($);if(Q)return{url:Q,source:"env",via:Z}}return null}function Zq(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?u($):null}async function gq(q){let{existsSync:Z}=await import("fs"),$=await import("path");for(let Q of["site.config.ts","site.config.js",".config/site.config.ts"]){let K=$.resolve(q,Q);if(!Z(K))continue;try{let J=await import(K),W=Zq(J.default??J);if(W)return W}catch{}}return null}async function $q(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=u(q.explicit);if(W)return{url:W,source:"option"}}let Q=Zq(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await gq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=Cq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Kq(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
3
  `)}class Dq{cacheDir;cache=new Map;loaded=!1;salt;constructor(q,Z=""){this.cacheDir=q,this.salt=Z}async load(){if(this.loaded)return;let q=j.join(this.cacheDir,"build-cache.json");if(await Bun.file(q).exists())try{let Z=JSON.parse(await Bun.file(q).text());for(let[$,Q]of Object.entries(Z))this.cache.set($,Q)}catch{}this.loaded=!0}async save(){await O.promises.mkdir(this.cacheDir,{recursive:!0});let q=j.join(this.cacheDir,"build-cache.json"),Z={};for(let[$,Q]of this.cache)Z[$]=Q;await Bun.write(q,JSON.stringify(Z))}getHash(q,Z){let $=O.statSync(q),Q=`${this.salt}|${q}:${$.mtimeMs}`;for(let J of Z)if(O.existsSync(J)){let W=O.statSync(J);Q+=`:${J}:${W.mtimeMs}`}let K=0;for(let J=0;J<Q.length;J++){let W=Q.charCodeAt(J);K=(K<<5)-K+W,K=K&K}return Math.abs(K).toString(36)}get(q,Z){let $=this.cache.get(q);if(!$)return null;let Q=this.getHash(Z,$.dependencies??[]);if($.hash!==Q)return this.cache.delete(q),null;return $.html}set(q,Z,$,Q){let K=this.getHash(Z,$);this.cache.set(q,{hash:K,html:Q,generatedAt:Date.now(),dependencies:$})}}class Fq{cacheDir;constructor(q){this.cacheDir=q}getFilePath(q){let Z=q.replace(/[^a-zA-Z0-9]/g,"_")+".json";return j.join(this.cacheDir,"isr",Z)}async get(q){let Z=this.getFilePath(q);if(!await Bun.file(Z).exists())return null;try{return JSON.parse(await Bun.file(Z).text())}catch{return null}}async set(q,Z){let $=this.getFilePath(q);await O.promises.mkdir(j.dirname($),{recursive:!0}),await Bun.write($,JSON.stringify(Z))}async invalidate(q){let Z=this.getFilePath(q);if(await Bun.file(Z).exists())await O.promises.unlink(Z)}async invalidatePattern(q){let Z=j.join(this.cacheDir,"isr");if(!O.existsSync(Z))return;let $=await O.promises.readdir(Z);for(let Q of $){let K=Q.replace(/_/g,"/").replace(".json","");if(q.test(K))await O.promises.unlink(j.join(Z,Q))}}async needsRevalidation(q){let Z=await this.get(q);if(!Z)return!0;return Date.now()>Z.revalidateAfter}}async function fq(q){try{let $=(await Bun.file(q).text()).match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!$)return null;let Q=$[1];if(!Q.includes("getStaticPaths"))return null;let K=Q.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticPaths\s*\([^)]*\)\s*\{([\s\S]*?)\n[\t ]*\}/);if(!K)return null;return await Function(`
4
4
  return (async function getStaticPaths() {
5
5
  ${K[1]}
@@ -41,7 +41,7 @@ ${q.map((Q)=>{let K=new URL(Q.loc,Z).href,J=` <url>
41
41
  ${$.join(`
42
42
  `)}
43
43
  </channel>
44
- </rss>`}async function sq(q={}){let Z=Date.now();_q();let $=await l(process.cwd()),Q=$.build||{},K=await $q({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Kq());let J={pagesDir:q.pagesDir||Q.pagesDir||"pages",outputDir:q.outputDir||Q.outputDir||"dist",baseUrl:q.baseUrl||Q.baseUrl||"/",domain:K.url,revalidate:q.revalidate??Q.revalidate??!1,sitemap:q.sitemap??Q.sitemap??!0,sitemapExclude:q.sitemapExclude||Q.sitemapExclude||[],robots:q.robots??Q.robots??!0,rss:q.rss??Q.rss??!1,concurrency:q.concurrency||Q.concurrency||10,cache:q.cache??Q.cache??!0,cacheDir:q.cacheDir||Q.cacheDir||f(process.cwd(),"ssg-cache"),contentLoaders:q.contentLoaders||[],hooks:q.hooks||{},minify:q.minify??Q.minify??!0,generate404:q.generate404??Q.generate404??!0,publicDir:q.publicDir||Q.publicDir||"public",trailingSlash:q.trailingSlash??Q.trailingSlash??!1,cleanOutput:q.cleanOutput??Q.cleanOutput??!0,cacheSalt:q.cacheSalt??"",partialsDir:q.partialsDir||$?.partialsDir||"",componentsDir:q.componentsDir||$?.componentsDir||"",failOnIncludeError:q.failOnIncludeError??!0,chunkIslands:q.chunkIslands===!0,prefetchIslands:q.prefetchIslands===!0,integrityIslands:q.integrityIslands===!0},W={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},z=new Set,A=0,N={},X={};await J.hooks.onBuildStart?.();try{if(J.cleanOutput&&O.existsSync(J.outputDir))await O.promises.rm(J.outputDir,{recursive:!0});await O.promises.mkdir(J.outputDir,{recursive:!0});let _=J.cacheSalt;if(!_){let{resolveUserCrosswindConfig:Y,fingerprintConfig:L}=await import("./chunk-css1sfnr.js");try{_=L(await Y(process.cwd()))}catch{}}let G=new Dq(J.cacheDir,_);if(J.cache)await G.load();try{let{generateCrosswindCSS:Y}=await import("./chunk-css1sfnr.js");await Y('<div class="bg-black"></div>')}catch{}Wq();let m=$?.routeMiddleware?.dir||"middleware";await Vq(process.cwd(),m);let d=Yq();if(d.length>0)console.log(`Loaded ${d.length} middleware: ${d.join(", ")}`);let Mq=$?.routeMiddleware?.global||[];Tq($?.layoutsDir,f(process.cwd()));let n=c(".",{pagesDir:J.pagesDir});console.log(`Found ${n.length} routes`);let y=[];for(let Y of n){let L=await mq(Y);for(let B of L)y.push({route:Y,url:B.url,params:B.params,props:B.props,revalidate:B.revalidate??J.revalidate})}W.totalPages=y.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],i=[];for(let Y=0;Y<y.length;Y+=J.concurrency)i.push(y.slice(Y,Y+J.concurrency));for(let Y of i)await Promise.all(Y.map(async(L)=>{let{route:B,url:V,params:k,props:wq,revalidate:a}=L;try{await J.hooks.onPageStart?.(V);let F=await Bun.file(B.filePath).text(),R=tq(F),bq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],r=[...Mq,...bq];if(r.length>0){let D=jq(V,k,R||{}),M=Gq(D,null,void 0,{isServer:!0}),E=await Lq(r,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,v=eq(String(U),V),w=qJ(V,J);await O.promises.mkdir(j.dirname(w),{recursive:!0}),await Bun.write(w,v),W.successCount++,W.pages.push({route:V,outputPath:w,size:Buffer.byteLength(v),cached:!1}),b.push({loc:V,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${V} \u2192 redirect to ${U}`);return}if(E.abort){let U=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${V} \u2014 middleware aborted: ${U}`);return}}let t=F.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(t)try{if(!await Function("route",`
44
+ </rss>`}async function sq(q={}){let Z=Date.now();_q();let $=await l(process.cwd()),Q=$.build||{},K=await $q({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Kq());let J={pagesDir:q.pagesDir||Q.pagesDir||"pages",outputDir:q.outputDir||Q.outputDir||"dist",baseUrl:q.baseUrl||Q.baseUrl||"/",domain:K.url,revalidate:q.revalidate??Q.revalidate??!1,sitemap:q.sitemap??Q.sitemap??!0,sitemapExclude:q.sitemapExclude||Q.sitemapExclude||[],robots:q.robots??Q.robots??!0,rss:q.rss??Q.rss??!1,concurrency:q.concurrency||Q.concurrency||10,cache:q.cache??Q.cache??!0,cacheDir:q.cacheDir||Q.cacheDir||f(process.cwd(),"ssg-cache"),contentLoaders:q.contentLoaders||[],hooks:q.hooks||{},minify:q.minify??Q.minify??!0,generate404:q.generate404??Q.generate404??!0,publicDir:q.publicDir||Q.publicDir||"public",trailingSlash:q.trailingSlash??Q.trailingSlash??!1,cleanOutput:q.cleanOutput??Q.cleanOutput??!0,cacheSalt:q.cacheSalt??"",partialsDir:q.partialsDir||$?.partialsDir||"",componentsDir:q.componentsDir||$?.componentsDir||"",failOnIncludeError:q.failOnIncludeError??!0,chunkIslands:q.chunkIslands===!0,prefetchIslands:q.prefetchIslands===!0,integrityIslands:q.integrityIslands===!0},W={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},z=new Set,A=0,N={},X={};await J.hooks.onBuildStart?.();try{if(J.cleanOutput&&O.existsSync(J.outputDir))await O.promises.rm(J.outputDir,{recursive:!0});await O.promises.mkdir(J.outputDir,{recursive:!0});let _=J.cacheSalt;if(!_){let{resolveUserCrosswindConfig:Y,fingerprintConfig:L}=await import("./chunk-ta43eqe0.js");try{_=L(await Y(process.cwd()))}catch{}}let G=new Dq(J.cacheDir,_);if(J.cache)await G.load();try{let{generateCrosswindCSS:Y}=await import("./chunk-ta43eqe0.js");await Y('<div class="bg-black"></div>')}catch{}Wq();let m=$?.routeMiddleware?.dir||"middleware";await Vq(process.cwd(),m);let d=Yq();if(d.length>0)console.log(`Loaded ${d.length} middleware: ${d.join(", ")}`);let Mq=$?.routeMiddleware?.global||[];Tq($?.layoutsDir,f(process.cwd()));let n=c(".",{pagesDir:J.pagesDir});console.log(`Found ${n.length} routes`);let y=[];for(let Y of n){let L=await mq(Y);for(let B of L)y.push({route:Y,url:B.url,params:B.params,props:B.props,revalidate:B.revalidate??J.revalidate})}W.totalPages=y.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],i=[];for(let Y=0;Y<y.length;Y+=J.concurrency)i.push(y.slice(Y,Y+J.concurrency));for(let Y of i)await Promise.all(Y.map(async(L)=>{let{route:B,url:V,params:k,props:wq,revalidate:a}=L;try{await J.hooks.onPageStart?.(V);let F=await Bun.file(B.filePath).text(),R=tq(F),bq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],r=[...Mq,...bq];if(r.length>0){let D=jq(V,k,R||{}),M=Gq(D,null,void 0,{isServer:!0}),E=await Lq(r,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,v=eq(String(U),V),w=qJ(V,J);await O.promises.mkdir(j.dirname(w),{recursive:!0}),await Bun.write(w,v),W.successCount++,W.pages.push({route:V,outputPath:w,size:Buffer.byteLength(v),cached:!1}),b.push({loc:V,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${V} \u2192 redirect to ${U}`);return}if(E.abort){let U=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${V} \u2014 middleware aborted: ${U}`);return}}let t=F.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(t)try{if(!await Function("route",`
45
45
  const validate = ${t[1]};
46
46
  return validate(route);
47
47
  `)({params:k})){console.warn(`Validation failed for ${V}, skipping...`);return}}catch{}let I=null,e=!1;if(J.cache){if(I=G.get(V,B.filePath),I)e=!0,W.cachedCount++}if(!I){let D=await Rq(B,k,wq,J,$);if(I=D.html,J.failOnIncludeError&&D.includeFailures.length>0)throw Error(`${D.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
@@ -28,5 +28,6 @@ export declare interface CompiledTemplate {
28
28
  serverScriptContent: string[]
29
29
  dependencies: string[]
30
30
  contentHash: string
31
+ status?: number
31
32
  streamTemplates?: Record<string, string>
32
33
  }
@@ -6,6 +6,7 @@ import { createPlaceholder, resetPlaceholders, getPlaceholderRegistry } from "./
6
6
  import { stripDocumentWrapper } from "./app-shell.js";
7
7
  import { createHash } from "node:crypto";
8
8
  import { collectBlockDeclarations } from "./stx-virtual-ts.js";
9
+ import { extractPageResponseStatus } from "./page-response.js";
9
10
  function createRecordingContext(baseContext = {}) {
10
11
  const accessedKeys = new Set;
11
12
  return { context: new Proxy(baseContext, {
@@ -60,6 +61,7 @@ export async function compileTemplate(filePath, route, options = {}) {
60
61
  serverScriptContent,
61
62
  dependencies: Array.from(dependencies),
62
63
  contentHash,
64
+ status: extractPageResponseStatus(content),
63
65
  streamTemplates: context.__streamTemplates
64
66
  };
65
67
  }
@@ -20,7 +20,7 @@ export declare function hydrateTemplate(compiled: CompiledTemplate, requestConte
20
20
  * templates aren't serialized into the compiled template, so use the function
21
21
  * form in production.)
22
22
  */
23
- export declare function hydrateTemplateStream(compiled: CompiledTemplate, requestContext?: Record<string, any>): Promise<{ html: string, boundaries?: { id: string, render: () => Promise<string> }[], redirect?: string, cookies?: string[] }>;
23
+ export declare function hydrateTemplateStream(compiled: CompiledTemplate, requestContext?: Record<string, any>): Promise<{ html: string, boundaries?: { id: string, render: () => Promise<string> }[], redirect?: string, cookies?: string[], status?: number, headers?: Record<string, string> }>;
24
24
  /**
25
25
  * Hydrate a fragment (for SPA navigation).
26
26
  * Same as hydrateTemplate but returns the fragment portion.
@@ -2,13 +2,14 @@ import { extractVariables } from "./variable-extractor.js";
2
2
  import { evaluateExpression, escapeHtmlValue } from "./expressions.js";
3
3
  import { replacePlaceholders, hasPlaceholders } from "./placeholder.js";
4
4
  import { runPageAction } from "./page-action.js";
5
+ import { readResponseHeaders, readResponseStatus } from "./page-response.js";
5
6
  export async function hydrateTemplate(compiled, requestContext = {}) {
6
7
  return (await runHydration(compiled, requestContext)).html;
7
8
  }
8
9
  export async function hydrateTemplateStream(compiled, requestContext = {}) {
9
- const { html, context, redirect, cookies } = await runHydration(compiled, requestContext);
10
+ const { html, context, redirect, cookies } = await runHydration(compiled, requestContext), status = readResponseStatus(context), headers = readResponseHeaders(context);
10
11
  if (redirect)
11
- return { html, redirect, cookies };
12
+ return { html, redirect, cookies, status, headers };
12
13
  const { extractStreamBoundaries } = await import("./streaming.js");
13
14
  let boundaries = extractStreamBoundaries(context);
14
15
  const templates = compiled.streamTemplates;
@@ -22,7 +23,7 @@ export async function hydrateTemplateStream(compiled, requestContext = {}) {
22
23
  })), tplIds = new Set(tplBoundaries.map((b) => b.id));
23
24
  boundaries = [...(boundaries || []).filter((b) => !tplIds.has(b.id)), ...tplBoundaries];
24
25
  }
25
- return { html, boundaries: boundaries && boundaries.length > 0 ? boundaries : void 0, cookies };
26
+ return { html, boundaries: boundaries && boundaries.length > 0 ? boundaries : void 0, cookies, status, headers };
26
27
  }
27
28
  async function runHydration(compiled, requestContext) {
28
29
  const context = {
@@ -19,7 +19,7 @@
19
19
  * generated `await import('stx')` rejected and the shadowing binding was never
20
20
  * created. The failure needed a real install to appear.
21
21
  */
22
- export declare const STX_ENGINE_BINDING_NAMES: readonly ['module', 'exports', 'require', 'props', '$props', 'defineProps', 'withDefaults', 'defineClientPayload', 'state', 'derived', 'effect', 'batch', 'onMount', 'onDestroy', 'definePageMeta', 'useRoute', 'useRouter', 'useHead', 'useSeoMeta', 'ref', 'reactive', 'computed', 'watch', 'onMounted', 'onUnmounted', 'nextTick', 'defineEmits', 'defineExpose', 'defineSlots', 'provide', 'inject', 'useColorMode', 'useDark', 'useMediaQuery', 'useScrollLock', 'usePreferredDark', 'usePreferredLight', 'usePreferredReducedMotion', 'usePreferredContrast', 'window', 'document', 'console', 'confirm', 'alert', 'fetch', 'params'];
22
+ export declare const STX_ENGINE_BINDING_NAMES: readonly ['module', 'exports', 'require', 'props', '$props', 'defineProps', 'withDefaults', 'defineClientPayload', 'state', 'derived', 'effect', 'batch', 'onMount', 'onDestroy', 'definePageMeta', 'useRoute', 'useRouter', 'useHead', 'useSeoMeta', 'setResponseStatus', 'setResponseHeader', 'notFound', 'ref', 'reactive', 'computed', 'watch', 'onMounted', 'onUnmounted', 'nextTick', 'defineEmits', 'defineExpose', 'defineSlots', 'provide', 'inject', 'useColorMode', 'useDark', 'useMediaQuery', 'useScrollLock', 'usePreferredDark', 'usePreferredLight', 'usePreferredReducedMotion', 'usePreferredContrast', 'window', 'document', 'console', 'confirm', 'alert', 'fetch', 'params'];
23
23
  /**
24
24
  * Strip TypeScript-specific syntax to make it executable as JavaScript
25
25
  *
@@ -21,6 +21,9 @@ export const STX_ENGINE_BINDING_NAMES = [
21
21
  "useRouter",
22
22
  "useHead",
23
23
  "useSeoMeta",
24
+ "setResponseStatus",
25
+ "setResponseHeader",
26
+ "notFound",
24
27
  "ref",
25
28
  "reactive",
26
29
  "computed",
@@ -54,6 +57,7 @@ import { findMatchingDelimiter } from "./parser/tokenizer.js";
54
57
  import { mergeHeadConfigs, seoMetaToHeadConfig } from "./head.js";
55
58
  import { getPublicEnvDefine } from "./public-env.js";
56
59
  import { safeEvaluate } from "./safe-evaluator.js";
60
+ import { responseBindings } from "./page-response.js";
57
61
  function extractDeclaredVariableNames(script) {
58
62
  const names = [];
59
63
  let depth = 0;
@@ -372,7 +376,7 @@ export async function extractVariables(scriptContent, context, filePath, options
372
376
  }
373
377
  return cached;
374
378
  };
375
- }, effect = (_fn) => {}, batch = (fn) => fn(), onMount = (_fn) => {}, onDestroy = (_fn) => {};
379
+ }, effect = (_fn) => {}, batch = (fn) => fn(), onMount = (_fn) => {}, onDestroy = (_fn) => {}, responseApi = responseBindings(context);
376
380
  function definePageMeta(meta) {
377
381
  const config = meta || {};
378
382
  if (config.title !== void 0 || config.description !== void 0)
@@ -545,7 +549,7 @@ export async function extractVariables(scriptContent, context, filePath, options
545
549
  ${convertedScript}
546
550
  ${reSyncCode}
547
551
  return module.exports
548
- })()`)(module, exports, requireFn, propsObj, $props, defineProps, withDefaults, defineClientPayload, state, derived, effect, batch, onMount, onDestroy, definePageMeta, useRoute, useRouter, useHead, useSeoMeta, ref, reactive, computed, watch, onMounted, onUnmounted, nextTick, defineEmits, defineExpose, defineSlots, provide, inject, useColorMode, useDark, useMediaQuery, useScrollLock, usePreferredDark, usePreferredLight, usePreferredReducedMotion, usePreferredContrast, windowProxy, mockDocument, mockConsole, mockWindow.confirm, mockWindow.alert, mockWindow.fetch, paramsObj, ...propArgValues, ...scriptContextValues);
552
+ })()`)(module, exports, requireFn, propsObj, $props, defineProps, withDefaults, defineClientPayload, state, derived, effect, batch, onMount, onDestroy, definePageMeta, useRoute, useRouter, useHead, useSeoMeta, responseApi.setResponseStatus, responseApi.setResponseHeader, responseApi.notFound, ref, reactive, computed, watch, onMounted, onUnmounted, nextTick, defineEmits, defineExpose, defineSlots, provide, inject, useColorMode, useDark, useMediaQuery, useScrollLock, usePreferredDark, usePreferredLight, usePreferredReducedMotion, usePreferredContrast, windowProxy, mockDocument, mockConsole, mockWindow.confirm, mockWindow.alert, mockWindow.fetch, paramsObj, ...propArgValues, ...scriptContextValues);
549
553
  if (options.preserveExisting) {
550
554
  for (const [key, value] of Object.entries(result))
551
555
  if (!(key in context) || context[key] === void 0)
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunk-trtm887x.js";import B from"fs";import $ from"path";import k from"crypto";var V=[{name:"mobile",width:375,height:667,isMobile:!0,hasTouch:!0},{name:"tablet",width:768,height:1024,isMobile:!0,hasTouch:!0},{name:"desktop",width:1280,height:800,isMobile:!1,hasTouch:!1},{name:"wide",width:1920,height:1080,isMobile:!1,hasTouch:!1}];function J(N={}){let Y={snapshotDir:N.snapshotDir||"__snapshots__",screenshotDir:N.screenshotDir||"__screenshots__",updateSnapshots:N.updateSnapshots||process.env.UPDATE_SNAPSHOTS==="true",threshold:N.threshold??0.01,viewports:N.viewports||V,generateDiff:N.generateDiff??!0,diffDir:N.diffDir||"__diffs__",compare:N.compare||b,ci:N.ci??process.env.CI==="true",retries:N.retries??(N.ci?3:1)};return{async snapshot(M,X){let q=$.join(Y.snapshotDir,`${X}.html`),G=C(M),Q=K(G);if(await Bun.file(q).exists()){let W=await Bun.file(q).text(),Z=K(C(W));if(Q===Z)return{passed:!0,snapshotPath:q,message:"Snapshot matches"};if(Y.updateSnapshots)return await B.promises.mkdir($.dirname(q),{recursive:!0}),await Bun.write(q,G),{passed:!0,snapshotPath:q,message:"Snapshot updated"};let F=$.join(Y.diffDir,`${X}.actual.html`),U=$.join(Y.diffDir,`${X}.diff.html`);return await B.promises.mkdir(Y.diffDir,{recursive:!0}),await Bun.write(F,G),await Bun.write(U,I(W,G)),{passed:!1,snapshotPath:q,actualPath:F,diffPath:U,message:"Snapshot does not match"}}return await B.promises.mkdir($.dirname(q),{recursive:!0}),await Bun.write(q,G),{passed:!0,snapshotPath:q,message:"New snapshot created"}},async snapshotJson(M,X){let q=$.join(Y.snapshotDir,`${X}.json`),G=JSON.stringify(M,null,2);if(await Bun.file(q).exists()){let Q=await Bun.file(q).text();if(G===Q)return{passed:!0,snapshotPath:q};if(Y.updateSnapshots)return await Bun.write(q,G),{passed:!0,snapshotPath:q,message:"Snapshot updated"};return{passed:!1,snapshotPath:q,message:`JSON snapshot mismatch:
2
+ import"./chunk-z3cgw8j4.js";import B from"fs";import $ from"path";import k from"crypto";var V=[{name:"mobile",width:375,height:667,isMobile:!0,hasTouch:!0},{name:"tablet",width:768,height:1024,isMobile:!0,hasTouch:!0},{name:"desktop",width:1280,height:800,isMobile:!1,hasTouch:!1},{name:"wide",width:1920,height:1080,isMobile:!1,hasTouch:!1}];function J(N={}){let Y={snapshotDir:N.snapshotDir||"__snapshots__",screenshotDir:N.screenshotDir||"__screenshots__",updateSnapshots:N.updateSnapshots||process.env.UPDATE_SNAPSHOTS==="true",threshold:N.threshold??0.01,viewports:N.viewports||V,generateDiff:N.generateDiff??!0,diffDir:N.diffDir||"__diffs__",compare:N.compare||b,ci:N.ci??process.env.CI==="true",retries:N.retries??(N.ci?3:1)};return{async snapshot(M,X){let q=$.join(Y.snapshotDir,`${X}.html`),G=C(M),Q=K(G);if(await Bun.file(q).exists()){let W=await Bun.file(q).text(),Z=K(C(W));if(Q===Z)return{passed:!0,snapshotPath:q,message:"Snapshot matches"};if(Y.updateSnapshots)return await B.promises.mkdir($.dirname(q),{recursive:!0}),await Bun.write(q,G),{passed:!0,snapshotPath:q,message:"Snapshot updated"};let F=$.join(Y.diffDir,`${X}.actual.html`),U=$.join(Y.diffDir,`${X}.diff.html`);return await B.promises.mkdir(Y.diffDir,{recursive:!0}),await Bun.write(F,G),await Bun.write(U,I(W,G)),{passed:!1,snapshotPath:q,actualPath:F,diffPath:U,message:"Snapshot does not match"}}return await B.promises.mkdir($.dirname(q),{recursive:!0}),await Bun.write(q,G),{passed:!0,snapshotPath:q,message:"New snapshot created"}},async snapshotJson(M,X){let q=$.join(Y.snapshotDir,`${X}.json`),G=JSON.stringify(M,null,2);if(await Bun.file(q).exists()){let Q=await Bun.file(q).text();if(G===Q)return{passed:!0,snapshotPath:q};if(Y.updateSnapshots)return await Bun.write(q,G),{passed:!0,snapshotPath:q,message:"Snapshot updated"};return{passed:!1,snapshotPath:q,message:`JSON snapshot mismatch:
3
3
  ${z(Q,G)}`}}return await B.promises.mkdir($.dirname(q),{recursive:!0}),await Bun.write(q,G),{passed:!0,snapshotPath:q,message:"New snapshot created"}},matchInlineSnapshot(M,X){let q=C(M);if(X===void 0)return{passed:!0,expected:q};let G=C(X);return{passed:q===G,expected:q}},getConfig(){return Y}}}function D(N={}){let Y=J(N),M=Y.getConfig();return{async compareScreenshots(X,q,G="desktop"){let Q=$.join(M.screenshotDir,G,`${X}.png`),W=$.join(M.diffDir,G,`${X}.actual.png`),Z=$.join(M.diffDir,G,`${X}.diff.png`);if(await Bun.file(Q).exists()){let F=await Bun.file(Q).arrayBuffer(),U=Buffer.from(F),_=await M.compare(q,U);if(_.match||_.diffPercentage<=M.threshold)return{viewport:G,passed:!0,baselinePath:Q};if(M.updateSnapshots)return await B.promises.mkdir($.dirname(Q),{recursive:!0}),await Bun.write(Q,q),{viewport:G,passed:!0,baselinePath:Q};if(await B.promises.mkdir($.dirname(W),{recursive:!0}),await Bun.write(W,q),_.diffImage&&M.generateDiff)await Bun.write(Z,_.diffImage);return{viewport:G,passed:!1,baselinePath:Q,actualPath:W,diffPath:M.generateDiff?Z:void 0,diffPercentage:_.diffPercentage}}return await B.promises.mkdir($.dirname(Q),{recursive:!0}),await Bun.write(Q,q),{viewport:G,passed:!0,baselinePath:Q}},async testViewports(X,q,G=M.viewports){let Q=[];for(let W of G){let Z=null;for(let F=0;F<M.retries;F++)try{let U=await q(W),_=await this.compareScreenshots(X,U,W.name);Q.push(_),Z=null;break}catch(U){if(Z=U,F<M.retries-1)await new Promise((_)=>setTimeout(_,100*(F+1)))}if(Z)Q.push({viewport:W.name,passed:!1,baselinePath:"",diffPercentage:100})}return Q},getSnapshotTester(){return Y}}}function L(N={}){let M=D(N).getSnapshotTester(),X=new Map;return{addStory(q){X.set(`${q.component}/${q.name}`,q)},addStories(q){for(let G of q)this.addStory(G)},getStories(){return Array.from(X.values())},getStoriesForComponent(q){return Array.from(X.values()).filter((G)=>G.component===q)},async testStory(q){let G=X.get(q);if(!G)return{name:q,passed:!1,duration:0,snapshots:[],screenshots:[],errors:[Error(`Story not found: ${q}`)]};let Q=Date.now(),W={name:q,passed:!0,duration:0,snapshots:[],screenshots:[],errors:[]};try{let Z=await G.render(),F=await M.snapshot(Z,q.replace(/\//g,"-"));if(W.snapshots.push(F),!F.passed)W.passed=!1}catch(Z){W.passed=!1,W.errors.push(Z)}return W.duration=Date.now()-Q,W},async testAllStories(){let q=[];for(let G of X.keys()){let Q=await this.testStory(G);q.push(Q)}return q},async generateStoryIndex(){let q={};for(let G of X.values()){if(!q[G.component])q[G.component]=[];q[G.component].push({name:G.name,args:G.args})}return JSON.stringify(q,null,2)}}}async function S(N,Y={}){let M={outputDir:Y.outputDir||"visual-test-report",format:Y.format||"html",title:Y.title||"Visual Test Report",includeScreenshots:Y.includeScreenshots??!0};await B.promises.mkdir(M.outputDir,{recursive:!0});let X=N.length,q=N.filter((F)=>F.passed).length,G=X-q,Q=N.reduce((F,U)=>F+U.duration,0);if(M.format==="json"){let F={title:M.title,summary:{total:X,passed:q,failed:G,duration:Q},results:N,generatedAt:new Date().toISOString()},U=$.join(M.outputDir,"report.json");return await Bun.write(U,JSON.stringify(F,null,2)),U}if(M.format==="markdown"){let F=`# ${M.title}
4
4
 
5
5
  `;F+=`## Summary
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/stx",
3
3
  "type": "module",
4
- "version": "0.2.217",
4
+ "version": "0.2.219",
5
5
  "description": "A performant UI Framework. Powered by Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -117,12 +117,12 @@
117
117
  "dependencies": {
118
118
  "@cwcss/crosswind": "^0.2.14",
119
119
  "@stacksjs/clapp": "^0.2.0",
120
- "@stacksjs/desktop": "0.2.217",
121
- "@stacksjs/sanitizer": "0.2.217",
120
+ "@stacksjs/desktop": "0.2.219",
121
+ "@stacksjs/sanitizer": "0.2.219",
122
122
  "@stacksjs/ts-i18n": "^0.1.11",
123
- "bun-plugin-stx": "0.2.217",
123
+ "bun-plugin-stx": "0.2.219",
124
124
  "bunfig": "^0.15.17",
125
- "stx-router": "0.2.217",
125
+ "stx-router": "0.2.219",
126
126
  "ts-broadcasting": "^0.0.9",
127
127
  "ts-images": "^0.2.11",
128
128
  "ts-syntax-highlighter": "^0.2.1"
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ef as a}from"./chunk-fvpaf9v5.js";import"./chunk-zat2ndst.js";import"./chunk-j0tfxbns.js";import"./chunk-khrtzbxd.js";import"./chunk-8anh6d36.js";import"./chunk-3fwn9edg.js";import"./chunk-pezxve4a.js";import"./chunk-m2mhtpwy.js";import"./chunk-6xg3j487.js";import"./chunk-q4se9rtw.js";import"./chunk-1nm2xrvq.js";import"./chunk-z47tw39z.js";import"./chunk-3wd9kfyz.js";import"./chunk-trtm887x.js";export{a as startInteractive};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Zp as a,jq as b,kq as c,lq as d,mq as e}from"./chunk-zat2ndst.js";import"./chunk-j0tfxbns.js";import"./chunk-khrtzbxd.js";import"./chunk-8anh6d36.js";import"./chunk-3fwn9edg.js";import"./chunk-pezxve4a.js";import"./chunk-m2mhtpwy.js";import"./chunk-6xg3j487.js";import"./chunk-q4se9rtw.js";import"./chunk-1nm2xrvq.js";import"./chunk-z47tw39z.js";import"./chunk-3wd9kfyz.js";import"./chunk-trtm887x.js";export{d as validateClientScript,c as processOnceDirective,b as processJsonDirective,e as processDirectives,a as injectRouterScript};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Jo as a,Ko as b,Lo as c,Mo as d,No as e,Oo as f,Po as g,Qo as h,Ro as i,So as j}from"./chunk-zat2ndst.js";import"./chunk-j0tfxbns.js";import"./chunk-khrtzbxd.js";import"./chunk-8anh6d36.js";import"./chunk-3fwn9edg.js";import"./chunk-pezxve4a.js";import"./chunk-m2mhtpwy.js";import"./chunk-6xg3j487.js";import"./chunk-q4se9rtw.js";import"./chunk-1nm2xrvq.js";import"./chunk-z47tw39z.js";import"./chunk-3wd9kfyz.js";import"./chunk-trtm887x.js";export{b as stripTypeScript,h as splitDeclaration,c as isModuleResolutionFailure,d as isMissingBindingFailure,f as isCompleteImport,j as hasVariables,e as extractVariables,i as extractScriptFromTemplate,g as convertToCommonJS,a as STX_ENGINE_BINDING_NAMES};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Tj as a,Uj as b,Vj as c,Wj as d}from"./chunk-hncp9gz6.js";import"./chunk-trtm887x.js";export{d as default,c as createHotReloadServer,b as compileToNative,a as NATIVE_COMPONENTS};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Qh as a,Rh as b,Sh as c,Th as d,Uh as e}from"./chunk-w0ng9e1m.js";import"./chunk-trtm887x.js";export{c as renderSSRSuspense,a as processSuspenseDirectives,e as generateSuspenseRuntime,d as generateSuspenseCSS,b as createSSRSuspense};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{eh as a}from"./chunk-z2sp0k8d.js";import"./chunk-trtm887x.js";export{a as rewriteImagesWithSiblings};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{$k as h,Uk as a,Vk as b,Wk as c,Xk as d,Yk as e,Zk as f,_k as g,al as i}from"./chunk-dmb6t0qj.js";import"./chunk-zgvga8rc.js";import"./chunk-zat2ndst.js";import"./chunk-j0tfxbns.js";import"./chunk-khrtzbxd.js";import"./chunk-8anh6d36.js";import"./chunk-3fwn9edg.js";import"./chunk-pezxve4a.js";import"./chunk-m2mhtpwy.js";import"./chunk-6xg3j487.js";import"./chunk-q4se9rtw.js";import"./chunk-1nm2xrvq.js";import"./chunk-z47tw39z.js";import"./chunk-3wd9kfyz.js";import"./chunk-trtm887x.js";export{a as shouldLogBundlerDiagnostics,e as setBundlerFallbackMode,f as resolveBundlerFallback,b as recordBundleFailure,h as queueClientBundleBuild,g as hasUserImports,c as getBundleFailures,d as clearBundleFailures,i as bundleClientScript};