rosetack 0.1.0 → 0.1.2

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 (52) hide show
  1. package/deploy/k8s/rosetack.yaml +107 -0
  2. package/dist-cli/compiler.mjs +2783 -0
  3. package/dist-cli/edge.mjs +332 -0
  4. package/dist-cli/rosetack.mjs +4230 -0
  5. package/dist-cli/runtime.mjs +703 -0
  6. package/dist-cli/test.mjs +3202 -0
  7. package/pack.mjs +49 -0
  8. package/package.json +25 -7
  9. package/src/FRAMEWORK_VERSION +1 -1
  10. package/src/cli/edge.ts +67 -25
  11. package/src/cli/index.ts +858 -94
  12. package/src/cli/prompt.ts +127 -0
  13. package/src/cli/shell.ts +133 -30
  14. package/src/cli/test.ts +400 -0
  15. package/src/compiler/errors.ts +74 -0
  16. package/src/compiler/index.ts +1955 -264
  17. package/src/runtime/index.ts +465 -66
  18. package/src/types/rosetack.d.ts +151 -0
  19. package/.github/workflows/ci.yml +0 -72
  20. package/.github/workflows/release.yml +0 -122
  21. package/benchmark.ts +0 -227
  22. package/example/public/favicon.ico +0 -0
  23. package/example/public/logo.svg +0 -148
  24. package/example/public/rose-mark-black.png +0 -0
  25. package/example/public/rose-mark.png +0 -0
  26. package/example/public/rose-mono.png +0 -0
  27. package/example/rosetack.config.js +0 -10
  28. package/example/src/locales/en.json +0 -8
  29. package/example/src/locales/zh.json +0 -8
  30. package/example/src/pages/404.rose +0 -15
  31. package/example/src/pages/500.rose +0 -10
  32. package/example/src/pages/[lang]/about.rose +0 -40
  33. package/example/src/pages/_layout.rose +0 -33
  34. package/example/src/pages/_middleware.rose +0 -37
  35. package/example/src/pages/about.rose +0 -67
  36. package/example/src/pages/admin.rose +0 -27
  37. package/example/src/pages/api/hello.rose +0 -19
  38. package/example/src/pages/api/login.rose +0 -55
  39. package/example/src/pages/api/posts.rose +0 -80
  40. package/example/src/pages/api/secret.rose +0 -14
  41. package/example/src/pages/blog/[id].rose +0 -25
  42. package/example/src/pages/broken.rose +0 -16
  43. package/example/src/pages/fresh.rose +0 -22
  44. package/example/src/pages/garden.rose +0 -27
  45. package/example/src/pages/index.rose +0 -84
  46. package/example/src/pages/sign.rose +0 -45
  47. package/example/src/pages/thorn.rose +0 -23
  48. package/example/src/pages/vault.rose +0 -14
  49. package/go.mod +0 -3
  50. package/main.go +0 -470
  51. package/tools/release-notes.mjs +0 -113
  52. package/tsconfig.json +0 -17
@@ -0,0 +1,3202 @@
1
+ // src/cli/test.ts
2
+ import * as fs3 from "fs";
3
+ import * as os from "os";
4
+ import * as path3 from "path";
5
+ import { pathToFileURL as pathToFileURL2 } from "url";
6
+
7
+ // src/compiler/index.ts
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import { pathToFileURL, fileURLToPath } from "url";
11
+ import * as esbuild from "esbuild";
12
+
13
+ // src/compiler/errors.ts
14
+ var RoseError = class extends Error {
15
+ code;
16
+ file;
17
+ line;
18
+ hint;
19
+ constructor(code, message, opts = {}) {
20
+ super(message);
21
+ this.name = "RoseError";
22
+ this.code = code;
23
+ this.file = opts.file;
24
+ this.line = opts.line;
25
+ this.hint = opts.hint;
26
+ }
27
+ info() {
28
+ const info = { code: this.code };
29
+ if (this.file !== void 0) info.file = this.file;
30
+ if (this.line !== void 0) info.line = this.line;
31
+ info.message = this.message;
32
+ if (this.hint !== void 0) info.hint = this.hint;
33
+ return info;
34
+ }
35
+ };
36
+ function lineOf(src, index) {
37
+ let line = 1;
38
+ const end = Math.min(index, src.length);
39
+ for (let i = 0; i < end; i++) {
40
+ if (src[i] === "\n") line++;
41
+ }
42
+ return line;
43
+ }
44
+ function lineAt(src, match) {
45
+ return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
46
+ }
47
+
48
+ // src/compiler/index.ts
49
+ var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
50
+ var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
51
+ var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
52
+ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
53
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
54
+ var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
55
+ var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
56
+ var SLOT_RE = /<slot\s*\/?>/g;
57
+ var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
58
+ function encodeSlotCall(attrs) {
59
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
60
+ if (!name) throw new RoseError("E-TEMPLATE", '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
61
+ const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
62
+ return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
63
+ }
64
+ var BOUNDARY_FALLBACK = "<p>This section failed to render.</p>";
65
+ var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
66
+ var TS_LOADER = { loader: { ".js": "ts" } };
67
+ function callifyStateReads(script, names) {
68
+ if (names.length === 0) return script;
69
+ const scan = (src) => {
70
+ let out = "";
71
+ let i = 0;
72
+ while (i < src.length) {
73
+ const ch = src[i];
74
+ if (ch === "'" || ch === '"') {
75
+ let j = i + 1;
76
+ while (j < src.length && src[j] !== ch) {
77
+ if (src[j] === "\\") j++;
78
+ j++;
79
+ }
80
+ out += src.slice(i, Math.min(j + 1, src.length));
81
+ i = j + 1;
82
+ continue;
83
+ }
84
+ if (ch === "`") {
85
+ out += ch;
86
+ i++;
87
+ while (i < src.length && src[i] !== "`") {
88
+ if (src[i] === "\\") {
89
+ out += src.slice(i, i + 2);
90
+ i += 2;
91
+ continue;
92
+ }
93
+ if (src[i] === "$" && src[i + 1] === "{") {
94
+ let depth = 1;
95
+ let j = i + 2;
96
+ while (j < src.length && depth > 0) {
97
+ if (src[j] === "{") depth++;
98
+ else if (src[j] === "}") depth--;
99
+ if (depth === 0) break;
100
+ j++;
101
+ }
102
+ out += "${" + scan(src.slice(i + 2, j)) + "}";
103
+ i = j + 1;
104
+ continue;
105
+ }
106
+ out += src[i];
107
+ i++;
108
+ }
109
+ out += "`";
110
+ i++;
111
+ continue;
112
+ }
113
+ if (ch === "/" && src[i + 1] === "/") {
114
+ const nl = src.indexOf("\n", i);
115
+ const end = nl === -1 ? src.length : nl;
116
+ out += src.slice(i, end);
117
+ i = end;
118
+ continue;
119
+ }
120
+ if (ch === "/" && src[i + 1] === "*") {
121
+ const close = src.indexOf("*/", i + 2);
122
+ const end = close === -1 ? src.length : close + 2;
123
+ out += src.slice(i, end);
124
+ i = end;
125
+ continue;
126
+ }
127
+ if (/[A-Za-z_$]/.test(ch)) {
128
+ let j = i;
129
+ while (j < src.length && /[\w$]/.test(src[j])) j++;
130
+ const word = src.slice(i, j);
131
+ const prev = out.length ? out[out.length - 1] : "";
132
+ const next = src[j] ?? "";
133
+ const rewrite = names.includes(word) && !/[\w$.]/.test(prev) && !/[\w$:(]/.test(next);
134
+ out += rewrite ? `${word}()` : word;
135
+ i = j;
136
+ continue;
137
+ }
138
+ out += ch;
139
+ i++;
140
+ }
141
+ return out;
142
+ };
143
+ return scan(script);
144
+ }
145
+ function callifyTemplateExprs(template, names) {
146
+ if (names.length === 0) return template;
147
+ let out = "";
148
+ let last = 0;
149
+ for (const s of templateExprSpans(template)) {
150
+ out += template.slice(last, s.start) + "{" + callifyStateReads(s.expr, names) + "}";
151
+ last = s.end + 1;
152
+ }
153
+ return out + template.slice(last);
154
+ }
155
+ function templateExprSpans(src) {
156
+ const spans = [];
157
+ let i = 0;
158
+ while (i < src.length) {
159
+ if (src[i] === "{") {
160
+ const end = scanExprEnd(src, i);
161
+ if (end > i + 1) {
162
+ spans.push({ start: i, end, expr: src.slice(i + 1, end) });
163
+ i = end + 1;
164
+ continue;
165
+ }
166
+ }
167
+ i++;
168
+ }
169
+ return spans;
170
+ }
171
+ function scanExprEnd(src, open) {
172
+ let depth = 0;
173
+ let i = open;
174
+ while (i < src.length) {
175
+ const ch = src[i];
176
+ if (ch === "'" || ch === '"') {
177
+ i = skipQuoted(src, i);
178
+ continue;
179
+ }
180
+ if (ch === "`") {
181
+ i = skipTemplate(src, i);
182
+ continue;
183
+ }
184
+ if (ch === "{") depth++;
185
+ else if (ch === "}" && --depth === 0) return i;
186
+ i++;
187
+ }
188
+ return -1;
189
+ }
190
+ function skipQuoted(src, i) {
191
+ const q = src[i];
192
+ let j = i + 1;
193
+ while (j < src.length) {
194
+ if (src[j] === "\\") {
195
+ j += 2;
196
+ continue;
197
+ }
198
+ if (src[j] === q) return j + 1;
199
+ j++;
200
+ }
201
+ return j;
202
+ }
203
+ function skipTemplate(src, i) {
204
+ let j = i + 1;
205
+ while (j < src.length) {
206
+ const ch = src[j];
207
+ if (ch === "\\") {
208
+ j += 2;
209
+ continue;
210
+ }
211
+ if (ch === "`") return j + 1;
212
+ if (ch === "$" && src[j + 1] === "{") {
213
+ const end = scanExprEnd(src, j + 1);
214
+ j = end < 0 ? src.length : end + 1;
215
+ continue;
216
+ }
217
+ j++;
218
+ }
219
+ return j;
220
+ }
221
+ function stripComments(src) {
222
+ let out = "";
223
+ let i = 0;
224
+ while (i < src.length) {
225
+ const q = src[i];
226
+ if (q === '"' || q === "'") {
227
+ const end = skipQuoted(src, i);
228
+ out += src.slice(i, end);
229
+ i = end;
230
+ continue;
231
+ }
232
+ if (q === "`") {
233
+ const end = skipTemplate(src, i);
234
+ out += src.slice(i, end);
235
+ i = end;
236
+ continue;
237
+ }
238
+ if (src.startsWith("//", i)) {
239
+ while (i < src.length && src[i] !== "\n") i++;
240
+ continue;
241
+ }
242
+ if (src.startsWith("/*", i)) {
243
+ i += 2;
244
+ while (i < src.length && !src.startsWith("*/", i)) i++;
245
+ i = Math.min(i + 2, src.length);
246
+ continue;
247
+ }
248
+ if (src.startsWith("<!--", i)) {
249
+ i += 4;
250
+ while (i < src.length && !src.startsWith("-->", i)) i++;
251
+ i = Math.min(i + 3, src.length);
252
+ continue;
253
+ }
254
+ out += src[i++];
255
+ }
256
+ return out;
257
+ }
258
+ async function loadConfig(root) {
259
+ const file = path.join(root, "rosetack.config.js");
260
+ if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
261
+ const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
262
+ return {
263
+ plugins: mod.default ?? [],
264
+ i18n: mod.i18n ?? {}
265
+ };
266
+ }
267
+ function resolveRoseImports(script, fromFile, registry) {
268
+ const imports = [];
269
+ const resolve3 = (spec, at) => {
270
+ const abs = path.resolve(path.dirname(fromFile), spec);
271
+ const hit = registry.get(abs);
272
+ if (!hit) {
273
+ throw new RoseError(
274
+ "E-IMPORT",
275
+ `${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
276
+ {
277
+ file: fromFile,
278
+ line: lineOf(script, at),
279
+ hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`
280
+ }
281
+ );
282
+ }
283
+ return hit;
284
+ };
285
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at) => {
286
+ const hit = resolve3(spec, at);
287
+ imports.push({ name, specifier: spec, index: hit.index });
288
+ return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
289
+ });
290
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at) => {
291
+ const hit = resolve3(spec, at);
292
+ const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
293
+ imports.push({ name: alias, specifier: spec, index: hit.index });
294
+ return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
295
+ });
296
+ return { script: rewritten, imports };
297
+ }
298
+ function rewriteRoseImports(script, kind) {
299
+ return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
300
+ }
301
+ var NODE_ONLY_SPEC = /^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream|child_process|worker_threads|dns|cluster|better-sqlite3|sqlite3|pg|mysql2|mongodb|redis|ioredis)$)/;
302
+ function nodeOnlyImports(importStmts) {
303
+ const out = [];
304
+ for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
305
+ if (m[1]) continue;
306
+ if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
307
+ }
308
+ return out;
309
+ }
310
+ function wireEventBindings(template, actionNames) {
311
+ const bindings = [];
312
+ let out = "";
313
+ let rest = template;
314
+ for (; ; ) {
315
+ const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
316
+ if (!m) {
317
+ out += rest;
318
+ break;
319
+ }
320
+ out += rest.slice(0, m.index);
321
+ let i = m.index + m[0].length;
322
+ let depth = 1;
323
+ while (i < rest.length) {
324
+ const ch = rest[i];
325
+ if (ch === '"' || ch === "'") {
326
+ i = skipQuoted(rest, i);
327
+ continue;
328
+ }
329
+ if (ch === "`") {
330
+ i = skipTemplate(rest, i);
331
+ continue;
332
+ }
333
+ if (ch === "{") depth++;
334
+ else if (ch === "}") {
335
+ depth--;
336
+ if (depth === 0) break;
337
+ }
338
+ i++;
339
+ }
340
+ const expr = rest.slice(m.index + m[0].length, i).trim();
341
+ if (actionNames.has(expr)) {
342
+ out += `data-on-${m[1]}="$action:${expr}"`;
343
+ } else if (/^\w+$/.test(expr)) {
344
+ out += `data-on-${m[1]}="${expr}"`;
345
+ bindings.push({ event: m[1], fn: expr });
346
+ } else {
347
+ const name = `__h${bindings.length}`;
348
+ out += `data-on-${m[1]}="${name}"`;
349
+ bindings.push({ event: m[1], fn: `${name}: ${expr}` });
350
+ }
351
+ rest = rest.slice(i + 1);
352
+ }
353
+ return { template: out, bindings };
354
+ }
355
+ function scanSlotDecls(filePath) {
356
+ let src;
357
+ try {
358
+ src = fs.readFileSync(filePath, "utf-8");
359
+ } catch {
360
+ return [];
361
+ }
362
+ const noBlocks = src.replace(STYLE_RE, "");
363
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
364
+ const out = [];
365
+ for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
366
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
367
+ if (!name) continue;
368
+ const props = [...m[1].matchAll(/\b(\w+)\s*=\s*\{/g)].map((x) => x[1]).filter((n) => n !== "name");
369
+ out.push({ name: name[1], props });
370
+ }
371
+ return out;
372
+ }
373
+ function hoistImports(script) {
374
+ const imports = [];
375
+ const rest = [];
376
+ let buf = null;
377
+ let depth = 0;
378
+ const done = (line) => depth <= 0 && /from\s*['"][^'"]+['"]\s*;?\s*$/.test(line);
379
+ for (const line of script.split("\n")) {
380
+ if (buf) {
381
+ buf.push(line);
382
+ for (const ch of line) {
383
+ if (ch === "{" || ch === "(") depth++;
384
+ else if (ch === "}" || ch === ")") depth--;
385
+ }
386
+ if (done(line)) {
387
+ imports.push(buf.join("\n"));
388
+ buf = null;
389
+ }
390
+ continue;
391
+ }
392
+ if (/^\s*import\b/.test(line)) {
393
+ buf = [line];
394
+ depth = 0;
395
+ for (const ch of line) {
396
+ if (ch === "{" || ch === "(") depth++;
397
+ else if (ch === "}" || ch === ")") depth--;
398
+ }
399
+ if (done(line)) {
400
+ imports.push(line);
401
+ buf = null;
402
+ }
403
+ continue;
404
+ }
405
+ rest.push(line);
406
+ }
407
+ if (buf) imports.push(buf.join("\n"));
408
+ return { imports: imports.join("\n"), rest: rest.join("\n") };
409
+ }
410
+ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
411
+ let source = await fs.promises.readFile(filePath, "utf-8");
412
+ for (const p of plugins) {
413
+ if (!p.transform) continue;
414
+ try {
415
+ source = await p.transform(source, filePath);
416
+ } catch (err) {
417
+ throw new RoseError(
418
+ "E-PLUGIN",
419
+ `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
420
+ { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
421
+ );
422
+ }
423
+ }
424
+ if (isApi) {
425
+ const scriptMatch2 = source.match(COMPONENT_RE);
426
+ const rawScript2 = scriptMatch2?.[1] ?? "";
427
+ const apiMethods = [...rawScript2.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)].map((m) => m[1]).filter((name) => HTTP_METHODS.has(name));
428
+ const usesContext2 = /getContext\s*\(/.test(rawScript2);
429
+ const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
430
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
431
+ return {
432
+ ssr: "",
433
+ client: "",
434
+ stateKeys: [],
435
+ actionNames: [],
436
+ guardName: null,
437
+ style: "",
438
+ hasParams: false,
439
+ api: `import { getContext, $query } from './runtime.js';
440
+ ${rewriteRoseImports(`${hoisted.imports}
441
+ ${hoisted.rest}`, "ssr").trim()}`,
442
+ apiMethods,
443
+ hasPrerender,
444
+ usesContext: usesContext2
445
+ };
446
+ }
447
+ const sourceNoHead = source.replace(HEAD_RE, "");
448
+ const styleMatch = sourceNoHead.match(STYLE_RE);
449
+ const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
450
+ const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
451
+ const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
452
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
453
+ const rawScript = roseResolved.script;
454
+ const roseImports = roseResolved.imports;
455
+ const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
456
+ if (path.basename(filePath) !== "_middleware.rose") {
457
+ for (const spec of nodeOnlyImports(importStmts)) {
458
+ const at = importStmts.indexOf(spec);
459
+ throw new RoseError(
460
+ "E-NODE-ONLY",
461
+ `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
462
+ {
463
+ file: filePath,
464
+ line: at >= 0 ? lineOf(importStmts, at) : void 0,
465
+ hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`
466
+ }
467
+ );
468
+ }
469
+ }
470
+ const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
471
+ if (isComponent && /\$data\s*\(/.test(rawScript)) {
472
+ throw new RoseError(
473
+ "E-EXPORT",
474
+ `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
475
+ { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
476
+ );
477
+ }
478
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
479
+ const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
480
+ const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
481
+ const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
482
+ const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
483
+ const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
484
+ if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
485
+ throw new RoseError(
486
+ "E-EXPORT",
487
+ `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
488
+ { file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
489
+ );
490
+ }
491
+ const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
492
+ const vitals = vitalsMatch ? vitalsMatch[1].trim() === "true" : void 0;
493
+ if (vitalsMatch && !vitals) {
494
+ throw new RoseError(
495
+ "E-EXPORT",
496
+ `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
497
+ { file: filePath, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
498
+ );
499
+ }
500
+ const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
501
+ const bundle = bundleMatch ? bundleMatch[1] : void 0;
502
+ if (bundle && !["inline", "split"].includes(bundle)) {
503
+ throw new RoseError(
504
+ "E-EXPORT",
505
+ `${filePath}: export const bundle must be 'inline' or 'split'`,
506
+ { file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
507
+ );
508
+ }
509
+ const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
510
+ const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
511
+ const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
512
+ const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
513
+ if (csr === false) {
514
+ const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
515
+ if (dead) {
516
+ const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
517
+ throw new RoseError(
518
+ "E-EXPORT",
519
+ `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
520
+ {
521
+ file: filePath,
522
+ line: lineAt(deadSrc, dead),
523
+ hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'
524
+ }
525
+ );
526
+ }
527
+ }
528
+ let headers;
529
+ const headersLiteral = extractObjectLiteral(rawScript, "headers");
530
+ if (headersLiteral) {
531
+ let value;
532
+ try {
533
+ value = new Function(`return ${headersLiteral}`)();
534
+ } catch {
535
+ throw new RoseError(
536
+ "E-EXPORT",
537
+ `${filePath}: export const headers must be an object literal`,
538
+ { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
539
+ );
540
+ }
541
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
542
+ throw new RoseError(
543
+ "E-EXPORT",
544
+ `${filePath}: export const headers must be a flat map of string -> string`,
545
+ { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
546
+ );
547
+ }
548
+ headers = value;
549
+ }
550
+ let cspNonce;
551
+ const cspLiteral = extractObjectLiteral(rawScript, "csp");
552
+ if (cspLiteral) {
553
+ let value;
554
+ try {
555
+ value = new Function(`return ${cspLiteral}`)();
556
+ } catch {
557
+ throw new RoseError(
558
+ "E-EXPORT",
559
+ `${filePath}: export const csp must be an object literal`,
560
+ { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
561
+ );
562
+ }
563
+ const nonce = value?.nonce;
564
+ if (nonce !== void 0 && typeof nonce !== "boolean") {
565
+ throw new RoseError(
566
+ "E-EXPORT",
567
+ `${filePath}: csp.nonce must be a boolean`,
568
+ { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
569
+ );
570
+ }
571
+ cspNonce = nonce === true;
572
+ }
573
+ const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
574
+ const script = scriptNoExports;
575
+ const actionNames = new Set(actions.map((a) => a.name));
576
+ const clientReasons = [];
577
+ if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
578
+ if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
579
+ clientReasons.push("a form bound to a client dispatch ($action)");
580
+ }
581
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
582
+ if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
583
+ const needsClient = clientReasons.length > 0;
584
+ const jsWarnings = [];
585
+ if (!needsClient) {
586
+ const codeOnly = stripComments(source);
587
+ const scriptCodeOnly = stripComments(rawScript);
588
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
589
+ jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
590
+ }
591
+ if (/javascript:/i.test(codeOnly)) {
592
+ jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
593
+ }
594
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
595
+ jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
596
+ }
597
+ if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(scriptCodeOnly)) {
598
+ jsWarnings.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true");
599
+ }
600
+ }
601
+ const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
602
+ const headContent = source.match(HEAD_RE)?.[1] ?? "";
603
+ const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
604
+ const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
605
+ const decls = extractDecls(script);
606
+ const stateDecls = decls.filter((d) => d.kind === "state");
607
+ const setterNames = /* @__PURE__ */ new Map();
608
+ stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
609
+ const declCode = (d) => {
610
+ const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
611
+ if (d.kind === "state") {
612
+ return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
613
+ }
614
+ const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
615
+ const fn = isFn ? d.expr : `() => (${d.expr})`;
616
+ return `const __had_${d.name} = hasState(${JSON.stringify(key)});
617
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
618
+ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
619
+ };
620
+ const nestedDecls = [];
621
+ let spliced = "";
622
+ let pos = 0;
623
+ decls.forEach((d, i) => {
624
+ const top = braceDepthAt(script, d.start) === 0;
625
+ if (!top) nestedDecls.push(d);
626
+ spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
627
+ pos = d.end;
628
+ });
629
+ spliced += script.slice(pos);
630
+ let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
631
+ const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
632
+ const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
633
+ return `${setter}(${val})`;
634
+ });
635
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
636
+ cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
637
+ const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
638
+ const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
639
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
640
+ const wired = wireEventBindings(templateCalled, actionNames);
641
+ const eventBindings = wired.bindings;
642
+ const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
643
+ const stateKeys = decls.map((d) => d.name);
644
+ const comps = new Map(roseImports.map((r) => {
645
+ const abs = path.resolve(path.dirname(filePath), r.specifier);
646
+ const hit = registry.get(abs);
647
+ return [r.name, { index: hit.index, slots: hit.slots }];
648
+ }));
649
+ const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
650
+ const compiledHead = headContent.trim() ? compileHead(headContent) : "";
651
+ const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
652
+ const ssrExports = actions.length > 0 ? `${exportStmts}
653
+ ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
654
+ const ssrGuard = guard ? `
655
+ ${guard}` : "";
656
+ const isMiddleware = path.basename(filePath) === "_middleware.rose";
657
+ const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
658
+
659
+ ${importStmts}
660
+
661
+ ${ssrExports}
662
+ ${ssrGuard}
663
+
664
+ ${cleanScript}
665
+ ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
666
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
667
+ return {
668
+ ssr: rewriteRoseImports(ssr, "ssr"),
669
+ client: rewriteRoseImports(client, "client"),
670
+ stateKeys,
671
+ actionNames: [...actionNames],
672
+ guardName: guard ? "beforeAction" : null,
673
+ style: scopedStyle,
674
+ hasParams,
675
+ usesContext,
676
+ revalidate,
677
+ csr,
678
+ buffer,
679
+ prefetch,
680
+ vitals,
681
+ bundle,
682
+ needsClient,
683
+ clientReasons,
684
+ jsWarnings,
685
+ headers,
686
+ cspNonce,
687
+ props,
688
+ roseImports,
689
+ isComponent
690
+ };
691
+ }
692
+ function minifyDecls(block) {
693
+ return block.replace(
694
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
695
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
696
+ ).trim();
697
+ }
698
+ function scopeCss(css, key) {
699
+ const attr = `[data-rosetack-c="${key}"]`;
700
+ const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
701
+ let out = "";
702
+ let prelude = "";
703
+ let i = 0;
704
+ while (i < clean.length) {
705
+ const ch = clean[i];
706
+ if (ch === "{") {
707
+ let depth = 1;
708
+ let j = i + 1;
709
+ while (j < clean.length && depth > 0) {
710
+ if (clean[j] === "{") depth++;
711
+ else if (clean[j] === "}") depth--;
712
+ j++;
713
+ }
714
+ const block = clean.slice(i + 1, j - 1);
715
+ const sel = prelude.trim();
716
+ if (sel.startsWith("@")) {
717
+ out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
718
+ } else if (sel) {
719
+ const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
720
+ out += `${scoped}{${minifyDecls(block)}}`;
721
+ }
722
+ prelude = "";
723
+ i = j;
724
+ continue;
725
+ }
726
+ if (ch !== "}" && ch !== "\n" && ch !== "\r") prelude += ch;
727
+ else if (ch === "}") prelude = "";
728
+ i++;
729
+ }
730
+ return out.trim();
731
+ }
732
+ function injectScopeAttr(template, key) {
733
+ const attr = ` data-rosetack-c="${key}"`;
734
+ let out = "";
735
+ let depth = 0;
736
+ let i = 0;
737
+ while (i < template.length) {
738
+ const lt = template.indexOf("<", i);
739
+ if (lt === -1) {
740
+ out += template.slice(i);
741
+ break;
742
+ }
743
+ out += template.slice(i, lt);
744
+ let j = lt + 1;
745
+ let quote = "";
746
+ while (j < template.length) {
747
+ const c = template[j];
748
+ if (quote) {
749
+ if (c === quote) quote = "";
750
+ } else if (c === '"' || c === "'") quote = c;
751
+ else if (c === ">") break;
752
+ j++;
753
+ }
754
+ const tagText = template.slice(lt, j + 1);
755
+ const closing = /^<\//.test(tagText);
756
+ const nameMatch = tagText.match(/^<\/?([a-zA-Z][\w-]*)/);
757
+ const selfClosing = /\/>$/.test(tagText) || nameMatch && VOID_TAGS.has(nameMatch[1].toLowerCase());
758
+ if (nameMatch && !closing && depth === 0 && !selfClosing) {
759
+ const injectAt = tagText.endsWith("/>") ? tagText.length - 2 : tagText.length - 1;
760
+ out += tagText.slice(0, injectAt) + attr + tagText.slice(injectAt);
761
+ depth++;
762
+ } else {
763
+ out += tagText;
764
+ if (nameMatch) depth += closing ? -1 : selfClosing ? 0 : 1;
765
+ }
766
+ i = j + 1;
767
+ }
768
+ return out;
769
+ }
770
+ var VOID_TAGS = /* @__PURE__ */ new Set(["img", "br", "hr", "input", "meta", "link", "source", "wbr"]);
771
+ var EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
772
+ function extractObjectLiteral(script, name) {
773
+ const m = new RegExp(`(?:^|\\n)\\s*export\\s+(?:const|let|var)\\s+${name}\\s*=\\s*`).exec(script);
774
+ if (!m) return null;
775
+ let i = m.index + m[0].length;
776
+ if (script[i] !== "{") return null;
777
+ const start = i;
778
+ let depth = 0;
779
+ for (; i < script.length; i++) {
780
+ const ch = script[i];
781
+ if (ch === "{") depth++;
782
+ else if (ch === "}") {
783
+ depth--;
784
+ if (depth === 0) {
785
+ i++;
786
+ break;
787
+ }
788
+ }
789
+ }
790
+ return script.slice(start, i);
791
+ }
792
+ function extractExports(script) {
793
+ const stmts = [];
794
+ const actions = [];
795
+ const props = [];
796
+ const guards = [];
797
+ let out = "";
798
+ let pos = 0;
799
+ let m;
800
+ EXPORT_RE.lastIndex = 0;
801
+ while (m = EXPORT_RE.exec(script)) {
802
+ const kind = m[1];
803
+ const start = m.index + m[0].indexOf("export");
804
+ let i = start + m[0].length - m[0].indexOf("export");
805
+ if (kind) {
806
+ let depth = 0;
807
+ while (i < script.length) {
808
+ const ch = script[i];
809
+ if (ch === "(" || ch === "{" || ch === "[") depth++;
810
+ else if (ch === ")" || ch === "}" || ch === "]") {
811
+ depth--;
812
+ if (depth === 0) {
813
+ i++;
814
+ break;
815
+ }
816
+ } else if (depth === 0 && ch === ";") {
817
+ i++;
818
+ break;
819
+ } else if (depth === 0 && ch === "\n") {
820
+ const rest = script.slice(i + 1);
821
+ if (!/^\s*[.([{+\-*/?:,=&|]/.test(rest)) {
822
+ i++;
823
+ break;
824
+ }
825
+ }
826
+ i++;
827
+ }
828
+ if (script[i] === ";") i++;
829
+ } else {
830
+ while (i < script.length && script[i] !== "{") i++;
831
+ let depth = 0;
832
+ while (i < script.length) {
833
+ const ch = script[i];
834
+ if (ch === "{") depth++;
835
+ else if (ch === "}") {
836
+ depth--;
837
+ if (depth === 0) {
838
+ i++;
839
+ break;
840
+ }
841
+ }
842
+ i++;
843
+ }
844
+ }
845
+ out += script.slice(pos, start);
846
+ const stmt = script.slice(start, i).trim();
847
+ const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
848
+ const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
849
+ if (anyFn?.[1] === "beforeAction") {
850
+ guards.push(stmt);
851
+ } else if (asyncFn) {
852
+ actions.push({ name: asyncFn[1], stmt });
853
+ } else if (kind === "let") {
854
+ const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
855
+ if (pm) props.push({ name: pm[1], def: pm[2]?.trim() ?? null });
856
+ else stmts.push(stmt);
857
+ } else {
858
+ stmts.push(stmt);
859
+ }
860
+ pos = i;
861
+ }
862
+ out += script.slice(pos);
863
+ return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
864
+ }
865
+ function extractDecls(script) {
866
+ const decls = [];
867
+ DECL_RE.lastIndex = 0;
868
+ let m;
869
+ while (m = DECL_RE.exec(script)) {
870
+ let j = m.index + m[0].length;
871
+ const skipSpace = () => {
872
+ while (j < script.length && /\s/.test(script[j])) j++;
873
+ };
874
+ skipSpace();
875
+ if (script[j] === "<") {
876
+ let depth2 = 0;
877
+ while (j < script.length) {
878
+ const ch = script[j];
879
+ if (ch === "<") depth2++;
880
+ else if (ch === ">" && script[j - 1] !== "=") {
881
+ depth2--;
882
+ if (depth2 === 0) {
883
+ j++;
884
+ break;
885
+ }
886
+ } else if (ch === "=" && script[j + 1] === ">") j++;
887
+ j++;
888
+ }
889
+ skipSpace();
890
+ }
891
+ if (script[j] !== "(") continue;
892
+ const open = j + 1;
893
+ let depth = 1;
894
+ let i = open;
895
+ while (i < script.length && depth > 0) {
896
+ const ch = script[i];
897
+ if (ch === "(") depth++;
898
+ else if (ch === ")") depth--;
899
+ i++;
900
+ }
901
+ let end = i;
902
+ const cast = DECL_CAST_RE.exec(script.slice(i));
903
+ if (cast) end = i + cast[0].length;
904
+ if (script[end] === ";") end++;
905
+ decls.push({
906
+ name: m[1],
907
+ kind: m[2],
908
+ expr: script.slice(open, i - 1).trim(),
909
+ start: m.index,
910
+ end
911
+ });
912
+ }
913
+ return decls;
914
+ }
915
+ function braceDepthAt(src, index) {
916
+ let depth = 0;
917
+ let i = 0;
918
+ while (i < index) {
919
+ const ch = src[i];
920
+ if (ch === "'" || ch === '"' || ch === "`") {
921
+ const quote = ch;
922
+ i++;
923
+ while (i < index) {
924
+ if (src[i] === "\\") {
925
+ i += 2;
926
+ continue;
927
+ }
928
+ if (src[i] === quote) {
929
+ i++;
930
+ break;
931
+ }
932
+ if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
933
+ let d = 1;
934
+ i += 2;
935
+ while (i < index && d > 0) {
936
+ if (src[i] === "{") d++;
937
+ else if (src[i] === "}") d--;
938
+ i++;
939
+ }
940
+ continue;
941
+ }
942
+ i++;
943
+ }
944
+ continue;
945
+ }
946
+ if (ch === "/" && src[i + 1] === "/") {
947
+ const nl = src.indexOf("\n", i);
948
+ i = nl === -1 ? src.length : nl;
949
+ continue;
950
+ }
951
+ if (ch === "/" && src[i + 1] === "*") {
952
+ const close = src.indexOf("*/", i + 2);
953
+ i = close === -1 ? src.length : close + 2;
954
+ continue;
955
+ }
956
+ if (ch === "{") depth++;
957
+ else if (ch === "}") depth--;
958
+ i++;
959
+ }
960
+ return depth;
961
+ }
962
+ function autoCall(expr) {
963
+ const e = expr.trim();
964
+ return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
965
+ }
966
+ function findBlock(src, kind) {
967
+ const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
968
+ const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
969
+ let open;
970
+ while (open = head.exec(src)) {
971
+ const start = open.index;
972
+ const afterOpen = start + open[0].length;
973
+ let depth = 1;
974
+ let i = afterOpen;
975
+ for (; ; ) {
976
+ head.lastIndex = i;
977
+ closeRe.lastIndex = i;
978
+ const nextOpen = head.exec(src);
979
+ const nextClose = closeRe.exec(src);
980
+ if (!nextClose) break;
981
+ if (nextOpen && nextOpen.index < nextClose.index) {
982
+ depth++;
983
+ i = nextOpen.index + nextOpen[0].length;
984
+ continue;
985
+ }
986
+ i = nextClose.index + nextClose[0].length;
987
+ if (--depth === 0) {
988
+ const content = src.slice(afterOpen, nextClose.index);
989
+ const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
990
+ const arr = [src.slice(start, i), ...groups];
991
+ arr.index = start;
992
+ return arr;
993
+ }
994
+ }
995
+ head.lastIndex = afterOpen;
996
+ }
997
+ return null;
998
+ }
999
+ function compileHead(head) {
1000
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
1001
+ let out = "";
1002
+ let buf = "";
1003
+ let seg = 0;
1004
+ let i = 0;
1005
+ const flush = () => {
1006
+ if (buf.trim()) out += compileTemplate(buf, "__hd", "__hc", null, seg++, false);
1007
+ buf = "";
1008
+ };
1009
+ while (i < head.length) {
1010
+ if (head.startsWith("<!--", i)) {
1011
+ const end = head.indexOf("-->", i + 4);
1012
+ i = end < 0 ? head.length : end + 3;
1013
+ continue;
1014
+ }
1015
+ RAW_OPEN.lastIndex = i;
1016
+ const open = RAW_OPEN.exec(head);
1017
+ if (open) {
1018
+ const tag = open[1].toLowerCase();
1019
+ const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
1020
+ const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
1021
+ const end = gt < 0 ? head.length : gt + 1;
1022
+ flush();
1023
+ out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
1024
+ i = end;
1025
+ continue;
1026
+ }
1027
+ buf += head[i++];
1028
+ }
1029
+ flush();
1030
+ return out;
1031
+ }
1032
+ function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
1033
+ let result = "";
1034
+ let remaining = template;
1035
+ let blockId = 0;
1036
+ const nextId = () => `${depth}_${blockId++}`;
1037
+ while (remaining.length > 0) {
1038
+ const ifMatch = findBlock(remaining, "if");
1039
+ const eachMatch = findBlock(remaining, "each");
1040
+ const boundaryMatch = findBlock(remaining, "boundary");
1041
+ const firstExpr = templateExprSpans(remaining)[0];
1042
+ const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
1043
+ const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
1044
+ const candidates = [];
1045
+ if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
1046
+ if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
1047
+ if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
1048
+ if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
1049
+ if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
1050
+ const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
1051
+ if (!earliest) {
1052
+ result += emitChunk(remaining, acc, closes, scope);
1053
+ break;
1054
+ }
1055
+ if (earliest.type === "if") {
1056
+ const [, cond, content] = earliest.match;
1057
+ const before = remaining.substring(0, earliest.index);
1058
+ if (before) result += emitChunk(before, acc, closes, scope);
1059
+ const call = autoCall(cond);
1060
+ const id = nextId();
1061
+ const innerScope = scope ?? "__s";
1062
+ const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, markers, comps);
1063
+ result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
1064
+ `;
1065
+ if (markers) {
1066
+ result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
1067
+ `;
1068
+ } else {
1069
+ result += `${acc} += (${call}) ? __b${id}(${scope ?? "undefined"}, []) : '';
1070
+ `;
1071
+ }
1072
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1073
+ } else if (earliest.type === "each") {
1074
+ const [, items, item, content] = earliest.match;
1075
+ const before = remaining.substring(0, earliest.index);
1076
+ if (before) result += emitChunk(before, acc, closes, scope);
1077
+ const call = autoCall(items);
1078
+ const id = nextId();
1079
+ const itemRe = new RegExp(`\\b${item}\\b`, "g");
1080
+ let scoped = "";
1081
+ let lastSpan = 0;
1082
+ for (const s of templateExprSpans(content.trim())) {
1083
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
1084
+ lastSpan = s.end + 1;
1085
+ }
1086
+ scoped += content.trim().slice(lastSpan);
1087
+ const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
1088
+ result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
1089
+ `;
1090
+ if (markers) {
1091
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
1092
+ `;
1093
+ } else {
1094
+ result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');
1095
+ `;
1096
+ }
1097
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1098
+ } else if (earliest.type === "boundary") {
1099
+ const [, content] = earliest.match;
1100
+ const before = remaining.substring(0, earliest.index);
1101
+ if (before) result += emitChunk(before, acc, closes, scope);
1102
+ const id = nextId();
1103
+ const catchesAction = /\$action:|<form[\s>]/.test(content);
1104
+ const inner = compileTemplate(content.trim(), "h", closes, scope, depth + 1, markers, comps);
1105
+ result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
1106
+ `;
1107
+ result += `let __bd${id} = '';
1108
+ `;
1109
+ result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
1110
+ ` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
1111
+ `;
1112
+ result += `${acc} += __bd${id};
1113
+ `;
1114
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1115
+ } else if (earliest.type === "comp") {
1116
+ const tag = earliest.tag;
1117
+ if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
1118
+ const entry = comps.get(tag.name);
1119
+ const id = nextId();
1120
+ let childrenSrc = "";
1121
+ let rest;
1122
+ if (tag.selfClosing) {
1123
+ rest = remaining.substring(tag.end);
1124
+ } else {
1125
+ const closeIdx = findClose(remaining, tag.end, tag.name);
1126
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${tag.name}> - every component tag needs its matching close tag`, { hint: `add the matching </${tag.name}> (or close the tag with /> when it takes no children)` });
1127
+ childrenSrc = remaining.substring(tag.end, closeIdx);
1128
+ rest = remaining.substring(closeIdx + tag.name.length + 3);
1129
+ }
1130
+ const { def, named } = splitSlots(childrenSrc);
1131
+ const hasChildren = def.trim().length > 0;
1132
+ if (hasChildren) {
1133
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, markers, comps)} return h; };
1134
+ `;
1135
+ }
1136
+ const slotFns = named.map(([nm, src]) => {
1137
+ const decl = entry.slots.find((s) => s.name === nm);
1138
+ let content = src;
1139
+ for (const p of decl?.props ?? []) {
1140
+ const pRe = new RegExp(`\\b${p}\\b`, "g");
1141
+ let out = "";
1142
+ let lastSpan = 0;
1143
+ for (const s of templateExprSpans(content)) {
1144
+ out += content.slice(lastSpan, s.start) + "{" + s.expr.replace(pRe, `__s.${p}`) + "}";
1145
+ lastSpan = s.end + 1;
1146
+ }
1147
+ content = out + content.slice(lastSpan);
1148
+ }
1149
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
1150
+ });
1151
+ const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
1152
+ const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
1153
+ const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
1154
+ return `${JSON.stringify(key)}: ${val}`;
1155
+ }).join(", ");
1156
+ const childrenArg = hasChildren ? `__ch${id}(${scope ?? "undefined"}, ${closes})` : `''`;
1157
+ result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
1158
+ `;
1159
+ remaining = rest;
1160
+ } else {
1161
+ const [, expr] = earliest.match;
1162
+ const trimmed = expr.trim();
1163
+ const before = remaining.substring(0, earliest.index);
1164
+ if (trimmed === "__slot__") {
1165
+ if (before) result += emitChunk(before, acc, closes, scope);
1166
+ result += compileSlot(acc);
1167
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1168
+ continue;
1169
+ }
1170
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
1171
+ if (slotCall) {
1172
+ if (before) result += emitChunk(before, acc, closes, scope);
1173
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);
1174
+ `;
1175
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1176
+ continue;
1177
+ }
1178
+ const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
1179
+ if (rawMatch) {
1180
+ if (before) result += emitChunk(before, acc, closes, scope);
1181
+ const expr2 = rawMatch[1].trim();
1182
+ if (!markers) {
1183
+ result += `${acc} += String(${expr2} ?? '');
1184
+ `;
1185
+ } else {
1186
+ const fn = scope ? `(${scope}) => (${expr2})` : `() => (${expr2})`;
1187
+ result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ""});
1188
+ `;
1189
+ }
1190
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1191
+ continue;
1192
+ }
1193
+ const attrMatch = before.match(/([\w-]+)=\s*$/);
1194
+ if (attrMatch) {
1195
+ const lit = before.slice(0, before.length - attrMatch[0].length);
1196
+ if (lit) result += emitChunk(lit, acc, closes, scope);
1197
+ result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
1198
+ } else {
1199
+ if (before) result += emitChunk(before, acc, closes, scope);
1200
+ const after = remaining.substring(earliest.index + earliest.match[0].length);
1201
+ const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
1202
+ result += emitText(trimmed, acc, closes, scope, markers, pair);
1203
+ }
1204
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1205
+ }
1206
+ }
1207
+ return result;
1208
+ }
1209
+ function scanTagEnd(src, start) {
1210
+ let j = start + 1;
1211
+ let quote = "";
1212
+ let brace = 0;
1213
+ while (j < src.length) {
1214
+ const c = src[j];
1215
+ if (quote) {
1216
+ if (c === quote) quote = "";
1217
+ } else if (c === '"' || c === "'") quote = c;
1218
+ else if (c === "{") brace++;
1219
+ else if (c === "}") brace = Math.max(0, brace - 1);
1220
+ else if (c === ">" && brace === 0) return j + 1;
1221
+ j++;
1222
+ }
1223
+ return -1;
1224
+ }
1225
+ function findCompTag(src, comps) {
1226
+ let i = 0;
1227
+ while (i < src.length) {
1228
+ const lt = src.indexOf("<", i);
1229
+ if (lt < 0) return null;
1230
+ const nm = /^<([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
1231
+ if (nm && comps.has(nm[1])) {
1232
+ const end = scanTagEnd(src, lt);
1233
+ if (end > 0) {
1234
+ const raw = src.slice(lt, end);
1235
+ const selfClosing = /\/>$/.test(raw);
1236
+ return { start: lt, end, name: nm[1], attrs: raw.slice(1 + nm[1].length, selfClosing ? -2 : -1), selfClosing };
1237
+ }
1238
+ }
1239
+ i = lt + 1;
1240
+ }
1241
+ return null;
1242
+ }
1243
+ function findClose(src, from, name) {
1244
+ const re = new RegExp(`<(/?)${name}(?=[\\s/>])`, "g");
1245
+ re.lastIndex = from;
1246
+ let depth = 1;
1247
+ let m;
1248
+ while (m = re.exec(src)) {
1249
+ const end = scanTagEnd(src, m.index);
1250
+ if (end < 0) return -1;
1251
+ if (m[1] === "/") {
1252
+ depth--;
1253
+ if (depth === 0) return m.index;
1254
+ } else if (!/\/>$/.test(src.slice(m.index, end))) depth++;
1255
+ }
1256
+ return -1;
1257
+ }
1258
+ function parseCompAttrs(attrs) {
1259
+ const out = [];
1260
+ let i = 0;
1261
+ while (i < attrs.length) {
1262
+ const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
1263
+ if (!nm) break;
1264
+ i += nm[0].length;
1265
+ const eq = /^\s*=\s*/.exec(attrs.slice(i));
1266
+ if (!eq) {
1267
+ out.push({ name: nm[1], kind: "bool", value: "" });
1268
+ continue;
1269
+ }
1270
+ i += eq[0].length;
1271
+ const ch = attrs[i];
1272
+ if (ch === "{") {
1273
+ let depth = 1;
1274
+ let j = i + 1;
1275
+ while (j < attrs.length && depth > 0) {
1276
+ if (attrs[j] === "{") depth++;
1277
+ else if (attrs[j] === "}") depth--;
1278
+ j++;
1279
+ }
1280
+ out.push({ name: nm[1], kind: "expr", value: attrs.slice(i + 1, j - 1).trim() });
1281
+ i = j;
1282
+ } else if (ch === '"' || ch === "'") {
1283
+ const j = attrs.indexOf(ch, i + 1);
1284
+ out.push({ name: nm[1], kind: "str", value: attrs.slice(i + 1, j < 0 ? attrs.length : j) });
1285
+ i = j < 0 ? attrs.length : j + 1;
1286
+ } else break;
1287
+ }
1288
+ return out;
1289
+ }
1290
+ function rejectNestedSlot(src, outer) {
1291
+ let i = 0;
1292
+ while (i < src.length) {
1293
+ const lt = src.indexOf("<", i);
1294
+ if (lt < 0) return;
1295
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
1296
+ if (!nm) {
1297
+ i = lt + 1;
1298
+ continue;
1299
+ }
1300
+ const end = scanTagEnd(src, lt);
1301
+ if (end < 0) return;
1302
+ const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
1303
+ if (hit && nm[1] !== "/") {
1304
+ throw new RoseError("E-TEMPLATE", `slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`, { hint: "move the inner <slot> out of the outer one - a slot is a direct child of the component tag, never nested in another slot" });
1305
+ }
1306
+ i = end;
1307
+ }
1308
+ }
1309
+ function splitSlots(src) {
1310
+ let def = "";
1311
+ const named = /* @__PURE__ */ new Map();
1312
+ let i = 0;
1313
+ let elemDepth = 0;
1314
+ let blockDepth = 0;
1315
+ while (i < src.length) {
1316
+ const lt = src.indexOf("<", i);
1317
+ const ob = src.indexOf("{#", i);
1318
+ const cb = src.indexOf("{/", i);
1319
+ const cands = [lt, ob, cb].filter((x) => x >= 0);
1320
+ if (cands.length === 0) {
1321
+ def += src.slice(i);
1322
+ break;
1323
+ }
1324
+ const next = Math.min(...cands);
1325
+ if (next > i) def += src.slice(i, next);
1326
+ if (next === ob || next === cb) {
1327
+ const close = src.indexOf("}", next);
1328
+ const token = src.slice(next, close < 0 ? src.length : close + 1);
1329
+ if (next === ob) blockDepth++;
1330
+ else blockDepth = Math.max(0, blockDepth - 1);
1331
+ def += token;
1332
+ i = next + token.length;
1333
+ continue;
1334
+ }
1335
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(next, next + 64));
1336
+ if (!nm) {
1337
+ def += "<";
1338
+ i = next + 1;
1339
+ continue;
1340
+ }
1341
+ const end = scanTagEnd(src, next);
1342
+ if (end < 0) {
1343
+ def += src.slice(next);
1344
+ break;
1345
+ }
1346
+ const tagText = src.slice(next, end);
1347
+ const selfClosing = /\/>$/.test(tagText);
1348
+ const isVoid = VOID_TAGS.has(nm[2].toLowerCase());
1349
+ if (nm[1] === "/") {
1350
+ elemDepth = Math.max(0, elemDepth - 1);
1351
+ def += tagText;
1352
+ i = end;
1353
+ continue;
1354
+ }
1355
+ if (!selfClosing && !isVoid) elemDepth++;
1356
+ const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
1357
+ if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
1358
+ throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
1359
+ }
1360
+ if (slotName) {
1361
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
1362
+ if (selfClosing || isVoid) {
1363
+ named.set(slotName, (named.get(slotName) ?? "") + stripped);
1364
+ } else {
1365
+ const closeIdx = findClose(src, end, nm[2]);
1366
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
1367
+ const tail = `</${nm[2]}>`;
1368
+ const inner = src.slice(end, closeIdx);
1369
+ rejectNestedSlot(inner, slotName);
1370
+ named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
1371
+ elemDepth = Math.max(0, elemDepth - 1);
1372
+ i = closeIdx + tail.length;
1373
+ continue;
1374
+ }
1375
+ i = end;
1376
+ continue;
1377
+ }
1378
+ def += tagText;
1379
+ i = end;
1380
+ }
1381
+ return { def, named: [...named.entries()] };
1382
+ }
1383
+ function emitChunk(text, acc, closes, scope) {
1384
+ if (!text) return "";
1385
+ return `${acc} += ${JSON.stringify(text)};
1386
+ `;
1387
+ }
1388
+ var IMG_RE = /<img\b(?:[^<>]|\{[^{}]*\})*>/g;
1389
+ var IMG_MIME = {
1390
+ ".png": "image/png",
1391
+ ".jpg": "image/jpeg",
1392
+ ".jpeg": "image/jpeg",
1393
+ ".gif": "image/gif",
1394
+ ".webp": "image/webp",
1395
+ ".svg": "image/svg+xml",
1396
+ ".ico": "image/x-icon"
1397
+ };
1398
+ var INLINE_IMG_MAX = 4096;
1399
+ function inlineImages(template, publicDir) {
1400
+ return template.replace(IMG_RE, (tag) => {
1401
+ const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
1402
+ if (!src) return tag;
1403
+ const ext = path.extname(src[1]).toLowerCase();
1404
+ const mime = IMG_MIME[ext];
1405
+ if (!mime) return tag;
1406
+ let file;
1407
+ try {
1408
+ file = fs.readFileSync(path.join(publicDir, src[1]));
1409
+ } catch {
1410
+ return tag;
1411
+ }
1412
+ if (file.length > INLINE_IMG_MAX) return tag;
1413
+ const uri = ext === ".svg" ? `data:image/svg+xml,${file.toString("utf-8").replace(/%/g, "%25").replace(/#/g, "%23").replace(/\{/g, "%7B").replace(/\}/g, "%7D").replace(/"/g, "%22")}` : `data:${mime};base64,${file.toString("base64")}`;
1414
+ return tag.replace(src[0], `src="${uri}"`);
1415
+ });
1416
+ }
1417
+ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
1418
+ if (!markers) {
1419
+ return `${acc} += esc(${expr});
1420
+ `;
1421
+ }
1422
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1423
+ let extra = pair ? ", 1" : scope ? ", 0" : "";
1424
+ if (scope) extra += `, ${scope}`;
1425
+ return `${acc} += textMark(${closes}, ${fn}${extra});
1426
+ `;
1427
+ }
1428
+ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1429
+ if (!markers) {
1430
+ return `${acc} += '${attr}="' + esc(${expr}) + '"';
1431
+ `;
1432
+ }
1433
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1434
+ const arg = scope ? `, ${scope}` : "";
1435
+ return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
1436
+ `;
1437
+ }
1438
+ function compileSlot(acc) {
1439
+ return `${acc} += String(children);
1440
+ `;
1441
+ }
1442
+ var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark } from './runtime.js';`;
1443
+ function propsCode(props) {
1444
+ if (props.length === 0) return "";
1445
+ return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
1446
+ }
1447
+ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1448
+ const fn = sl[name];
1449
+ if (typeof fn !== 'function') return null;
1450
+ const o = {};
1451
+ for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1452
+ return { o, fn };
1453
+ };
1454
+ const __slotBlock = (closes, sl, name, pairs) => {
1455
+ const hit = __slot(sl, name, pairs);
1456
+ const idx = closes.length;
1457
+ closes.push(() => {
1458
+ if (!hit) return null;
1459
+ const c = [];
1460
+ return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
1461
+ });
1462
+ return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1463
+ };`;
1464
+ function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1465
+ const headCode = headFn ? `
1466
+ const __head = () => { let __hd = ''; ${headFn} return __hd; };
1467
+ __html += headMark(closes, __head);` : "";
1468
+ const actionState = hasActions ? `
1469
+ const $setState = (key, value) => setState(key, value);` : "";
1470
+ return `
1471
+ ${RUNTIME_IMPORTS}
1472
+
1473
+ ${imports}
1474
+
1475
+ ${exports}
1476
+ ${guard}
1477
+ ${actionState}
1478
+
1479
+ ${namedSlots ? SLOT_HELPER : ""}
1480
+
1481
+ export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1482
+ ${props.length > 0 ? "const __p = __props || {};" : ""}
1483
+ ${namedSlots ? "const __sl = __slots || {};" : ""}
1484
+ ${propsCode(props)}
1485
+ ${script}
1486
+ ${stateDeclsCode}
1487
+ ${dataDeclsCode}
1488
+ // The incremental patches of the action that produced THIS response,
1489
+ // applied to the state the declarations above just established (a no-op on
1490
+ // every path that is not a server action's re-render - see the runtime).
1491
+ ${isComponent ? "" : "applyStateDeltas();"}
1492
+ const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1493
+ let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1494
+ return __html;
1495
+ }
1496
+ `;
1497
+ }
1498
+ function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1499
+ const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1500
+ const headCode = headFn ? `
1501
+ const __head = () => { let __hd = ''; ${headFn} return __hd; };
1502
+ __html += headMark(closes, __head);` : "";
1503
+ return `
1504
+ ${RUNTIME_IMPORTS}
1505
+
1506
+ ${imports}
1507
+
1508
+ ${exports}
1509
+
1510
+ ${namedSlots ? SLOT_HELPER : ""}
1511
+
1512
+ export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1513
+ ${props.length > 0 ? "const __p = __props || {};" : ""}
1514
+ ${namedSlots ? "const __sl = __slots || {};" : ""}
1515
+ ${propsCode(props)}
1516
+ ${script}
1517
+ ${stateDeclsCode}
1518
+ ${dataDeclsCode}
1519
+ ${handlerRegistry}
1520
+ const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1521
+ let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1522
+ return __html;
1523
+ }
1524
+ `;
1525
+ }
1526
+ var layoutsOf = (infos, idx) => infos.map((li, i) => ({ li, i })).filter(({ li }) => li.isLayout && isAncestorDir(li.filePath, infos[idx].filePath)).sort((a, b) => b.li.filePath.length - a.li.filePath.length).map(({ i }) => i);
1527
+ var routeShipsNoJs = (infos, compiled, i) => {
1528
+ if (compiled[i].csr === true) return false;
1529
+ if (compiled[i].needsClient) return false;
1530
+ return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1531
+ };
1532
+ function buildReport(infos, compiled) {
1533
+ return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
1534
+ if (routeShipsNoJs(infos, compiled, i)) {
1535
+ return `${info.routePath} zero-JS nothing in the chain needs the client`;
1536
+ }
1537
+ const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path.basename(infos[ci].filePath)}`).join("; ");
1538
+ const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
1539
+ return `${info.routePath} client JS ${why}${forced}`;
1540
+ });
1541
+ }
1542
+ async function buildProject(root, outDir) {
1543
+ await fs.promises.mkdir(outDir, { recursive: true });
1544
+ const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
1545
+ await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
1546
+ const pageFiles = await scanRoseFiles(root);
1547
+ const compFiles = await scanComponentFiles(root);
1548
+ const files = [...pageFiles, ...compFiles];
1549
+ if (pageFiles.length === 0) {
1550
+ throw new RoseError(
1551
+ "E-ROUTE",
1552
+ `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1553
+ { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1554
+ );
1555
+ }
1556
+ const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1557
+ const config = await loadConfig(root);
1558
+ const plugins = config.plugins;
1559
+ const scopeKeys = files.map((f, i) => {
1560
+ const base = infos[i].isComponent ? path.join(root, "src") : path.join(root, "src", "pages");
1561
+ return path.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
1562
+ });
1563
+ const registry = new Map(
1564
+ files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1565
+ );
1566
+ const compiled = await Promise.all(
1567
+ files.map((f, i) => compileComponent(f, path.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
1568
+ );
1569
+ const importsOf = /* @__PURE__ */ new Map();
1570
+ files.forEach((_, i) => {
1571
+ const list = [];
1572
+ for (const r of compiled[i].roseImports ?? []) {
1573
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1574
+ const hit = registry.get(abs);
1575
+ if (hit) list.push(hit.index);
1576
+ }
1577
+ importsOf.set(i, list);
1578
+ });
1579
+ const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
1580
+ if (compiled[i].needsClient) return path.basename(files[i]);
1581
+ if (seen.has(i)) return null;
1582
+ seen.add(i);
1583
+ for (const dep of importsOf.get(i) ?? []) {
1584
+ const hit = needyDep(dep, seen);
1585
+ if (hit) return hit;
1586
+ }
1587
+ return null;
1588
+ };
1589
+ compiled.forEach((c, i) => {
1590
+ if (c.needsClient) return;
1591
+ const who = needyDep(i);
1592
+ if (who) {
1593
+ c.needsClient = true;
1594
+ c.clientReasons = [...c.clientReasons ?? [], `imported component ${who} needs the client`];
1595
+ }
1596
+ });
1597
+ const reachable = /* @__PURE__ */ new Set();
1598
+ const visit = (i) => {
1599
+ if (reachable.has(i)) return;
1600
+ reachable.add(i);
1601
+ for (const r of compiled[i].roseImports ?? []) {
1602
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1603
+ const hit = registry.get(abs);
1604
+ if (hit) visit(hit.index);
1605
+ }
1606
+ };
1607
+ files.forEach((_, i) => {
1608
+ if (!infos[i].isComponent) visit(i);
1609
+ });
1610
+ const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
1611
+ if (styles) await fs.promises.writeFile(path.join(outDir, "styles.css"), styles);
1612
+ else await fs.promises.rm(path.join(outDir, "styles.css"), { force: true });
1613
+ let locales = {};
1614
+ try {
1615
+ for (const f of await fs.promises.readdir(path.join(root, "src", "locales"))) {
1616
+ if (!f.endsWith(".json")) continue;
1617
+ locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, "src", "locales", f), "utf-8"));
1618
+ }
1619
+ } catch {
1620
+ locales = {};
1621
+ }
1622
+ const defaultLocale = locales.en ? "en" : Object.keys(locales).sort()[0] ?? "en";
1623
+ const localesJson = JSON.stringify(locales).replace(/</g, "\\u003c");
1624
+ const preload = config.i18n.preload ?? Object.keys(locales);
1625
+ const packed = Object.keys(locales).filter((l) => !preload.includes(l));
1626
+ for (const l of preload) {
1627
+ if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
1628
+ }
1629
+ await fs.promises.rm(path.join(outDir, "locales"), { recursive: true, force: true });
1630
+ if (packed.length > 0) {
1631
+ const packDir = path.join(outDir, "locales");
1632
+ await fs.promises.mkdir(packDir, { recursive: true });
1633
+ for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
1634
+ }
1635
+ const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
1636
+ const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
1637
+ const buildDir = path.join(outDir, ".build");
1638
+ await fs.promises.rm(buildDir, { recursive: true, force: true });
1639
+ await fs.promises.mkdir(buildDir, { recursive: true });
1640
+ const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1641
+ if (runtimePlugins.length > 0) {
1642
+ const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
1643
+ await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
1644
+ // Bundled into dist/server.js: these hooks run per request on every server
1645
+ // (Node, dev/preview, edge). Transform hooks already ran at build time.
1646
+ import config from ${JSON.stringify(configRel)};
1647
+
1648
+ const list = Array.isArray(config) ? config : [];
1649
+ export const hooks = list
1650
+ .filter((p) => p && (p.onRequest || p.onResponse))
1651
+ .map((p) => ({ name: p.name, onRequest: p.onRequest ? p.onRequest.bind(p) : null, onResponse: p.onResponse ? p.onResponse.bind(p) : null }));
1652
+
1653
+ export const hasRequestHooks = hooks.some((p) => p.onRequest);
1654
+ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1655
+ `);
1656
+ }
1657
+ const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
1658
+ if (!runtimeEntry) throw new RoseError("E-INTERNAL", "rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler", { hint: "the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout" });
1659
+ await esbuild.build({
1660
+ entryPoints: [runtimeEntry],
1661
+ bundle: true,
1662
+ outfile: path.join(buildDir, "runtime.js"),
1663
+ format: "esm",
1664
+ platform: "browser",
1665
+ write: true
1666
+ });
1667
+ for (let i = 0; i < compiled.length; i++) {
1668
+ const src = compiled[i].api ?? compiled[i].ssr;
1669
+ await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
1670
+ if (!infos[i].isApi) {
1671
+ await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1672
+ }
1673
+ }
1674
+ const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1675
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi);
1676
+ const compose = (idx) => {
1677
+ let expr = `render_${idx}`;
1678
+ for (const i of layoutsOf(infos, idx)) {
1679
+ expr = `(async (closes, children) => await render_${i}(closes, await (${expr})(closes, children)))`;
1680
+ }
1681
+ return expr;
1682
+ };
1683
+ const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? "inline";
1684
+ const split = bundleMode === "split";
1685
+ const chainOf = (idx) => [idx, ...layoutsOf(infos, idx)];
1686
+ const loaderInner = (idx) => `load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(", ")}])`;
1687
+ const loaderOf = (idx) => `{ ${loaderInner(idx)} }`;
1688
+ const routeNoJs = (i) => routeShipsNoJs(infos, compiled, i);
1689
+ const serverImports = compiled.map((_, i) => {
1690
+ if (!reachable.has(i)) return "";
1691
+ if (infos[i].isMiddleware) {
1692
+ return `import * as middlewareMod from './comp-${i}.ssr.js';`;
1693
+ }
1694
+ if (infos[i].isApi) {
1695
+ const names2 = compiled[i].apiMethods ?? [];
1696
+ const handlerImports = names2.map((n) => `${n} as ${n}_${i}`).join(", ");
1697
+ return handlerImports ? `import { ${handlerImports} } from './comp-${i}.ssr.js';` : `import './comp-${i}.ssr.js';`;
1698
+ }
1699
+ const isPage = !infos[i].isLayout && !infos[i].isNotFound;
1700
+ const names = isPage ? compiled[i].actionNames : [];
1701
+ const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(", ");
1702
+ const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : "";
1703
+ const named = [actionImports, guardImport].filter(Boolean).join(", ");
1704
+ return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1705
+ }).join("\n");
1706
+ const nfIdx = infos.findIndex((info) => info.isNotFound);
1707
+ const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
1708
+ const errIdx = infos.findIndex((info) => info.isError);
1709
+ const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
1710
+ const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
1711
+ const serverRoutes = pages.map(({ info, i }) => {
1712
+ const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
1713
+ if (compiled[i].csr === false && compiled[i].needsClient) {
1714
+ throw new RoseError(
1715
+ "E-EXPORT",
1716
+ `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`,
1717
+ { file: info.filePath, hint: "remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above" }
1718
+ );
1719
+ }
1720
+ if (compiled[i].csr === false) {
1721
+ const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1722
+ if (needy !== void 0) {
1723
+ throw new RoseError(
1724
+ "E-EXPORT",
1725
+ `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`,
1726
+ { file: info.filePath, hint: "a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only" }
1727
+ );
1728
+ }
1729
+ }
1730
+ const csrFlag = routeNoJs(i) ? ", csr: false" : "";
1731
+ const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
1732
+ const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1733
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
1734
+ }).join(",\n ");
1735
+ const serverEntry = `
1736
+ ${serverImports}
1737
+ import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1738
+ ${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
1739
+ // module to import - the runners below stay no-ops and the servers call them
1740
+ // unconditionally (one code path, no flags to keep in sync).
1741
+ const __pluginHooks = [];
1742
+ const __hasRequestHooks = false;
1743
+ const __hasResponseHooks = false;`}
1744
+
1745
+ // The runtime plugin hooks. onRequest runs before routing and
1746
+ // middleware and may short-circuit the request with its own Response; onResponse
1747
+ // runs once the response exists and may replace it. Both are no-ops when the
1748
+ // project declares no runtime hooks. A throwing hook is logged and skipped -
1749
+ // the request continues - so a broken logging plugin can never take a site
1750
+ // down (a build-time transform, by contrast, fails loudly).
1751
+ export async function runRequestHooks(ctx) {
1752
+ for (const p of __pluginHooks) {
1753
+ if (!p.onRequest) continue;
1754
+ try {
1755
+ const r = await p.onRequest(ctx);
1756
+ if (r instanceof Response) return r;
1757
+ } catch (err) {
1758
+ console.error('rosetack: plugin', p.name, 'onRequest failed:', err instanceof Error ? err.message : err);
1759
+ }
1760
+ }
1761
+ return null;
1762
+ }
1763
+
1764
+ export async function runResponseHooks(ctx, res) {
1765
+ let out = res;
1766
+ for (const p of __pluginHooks) {
1767
+ if (!p.onResponse) continue;
1768
+ try {
1769
+ const r = await p.onResponse(ctx, out);
1770
+ if (r instanceof Response) out = r;
1771
+ } catch (err) {
1772
+ console.error('rosetack: plugin', p.name, 'onResponse failed:', err instanceof Error ? err.message : err);
1773
+ }
1774
+ }
1775
+ return out;
1776
+ }
1777
+
1778
+ // The servers read these to skip building the hook context entirely when no
1779
+ // hook exists - the hot path pays nothing for the feature.
1780
+ export const hasRequestHooks = __hasRequestHooks;
1781
+ export const hasResponseHooks = __hasResponseHooks;
1782
+
1783
+ // P0-1: the query of the request being rendered, for $query(). The servers
1784
+ // call this before every render (stream, buffered, POST, api) with the parsed
1785
+ // query string; routing itself matches the pathname, which is what fixed the
1786
+ // query-404. A render with no query (the build's prerender, the ISR
1787
+ // background pass) passes {} explicitly - the bag is per request, so a stale
1788
+ // one must never leak into the next.
1789
+ export function setQuery(query) {
1790
+ setRequestQuery(query || {});
1791
+ }
1792
+
1793
+ // i18n: the dictionaries baked at build time from
1794
+ // src/locales/*.json. A route segment named [lang] is the locale: the value
1795
+ // must name one of these dictionaries, and $t resolves keys against it.
1796
+ setLocales(${localesJson}, '${defaultLocale}');
1797
+
1798
+ // The store transport. Under "rosetack serve" every worker is its
1799
+ // own process with its own dist/server.js module, so a $store write must
1800
+ // travel: this worker -> primary -> every other worker. process.send exists
1801
+ // only inside cluster workers, so a single-process runner (dev, preview,
1802
+ // the edge adapter) keeps the transport null and $store stays plain
1803
+ // per-process state - the documented boundary, not a bug.
1804
+ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1805
+ setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1806
+ process.on('message', (msg) => {
1807
+ if (msg && msg.type === 'rosetack:store') applyStorePatch(msg.name, msg.value);
1808
+ });
1809
+ }
1810
+
1811
+ export { localeList };
1812
+ export const defaultLocale = '${defaultLocale}';
1813
+
1814
+ // Route params maps, re-exported for the build's prerender step: routePath
1815
+ // -> the component's exported params (a static map or a function). Reading
1816
+ // them through the server bundle keeps the deploy dir free of component
1817
+ // modules - both bundles are self-contained, nothing else may ship. Only
1818
+ // components that actually export params appear here (a missing export
1819
+ // means the dynamic route renders on demand).
1820
+ ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1821
+
1822
+ export const routeParams = {
1823
+ ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1824
+ };
1825
+
1826
+ // Routes whose component reads the request context (getContext()), mutates a
1827
+ // shared store ($store()), reads the query ($query(), P0-1), opted into
1828
+ // nonce-based CSP or into the buffered path (buffer = true, P0-2):
1829
+ // the bag is per-request, the store is per-process, a nonce is per-response,
1830
+ // and a buffered route's hooks must run per request - so these are dynamic.
1831
+ // The build never bakes them and the servers never answer them from a
1832
+ // prerendered file. Public routes keep the static fast path (file cache,
1833
+ // ETag/304, streaming) untouched.
1834
+ export const dynamicRoutes = [
1835
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1836
+ ];
1837
+
1838
+ // Which api routes opt into build-time baking (export const prerender = true):
1839
+ // routePath -> boolean. The build calls the GET handler once and writes the
1840
+ // body to dist/, so the Go single binary serves read-only APIs without Node.
1841
+ ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1842
+
1843
+ export const apiPrerender = {
1844
+ ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1845
+ };
1846
+
1847
+ // Stale-while-revalidate windows (export const revalidate = N): the build
1848
+ // bakes these routes like any other, and the preview server serves the
1849
+ // baked file for up to N seconds - after which the next request is answered
1850
+ // STALE (instant, from disk) while a background pass re-renders and swaps
1851
+ // the file (ISR). Routes that read the request context are
1852
+ // excluded: they render per request and have no baked file to revalidate.
1853
+ // The dev server ignores the window (it rebuilds on change), the edge
1854
+ // adapter renders live (always fresh), and the Go binary serves the baked
1855
+ // file forever - the same static-half boundary as page POSTs.
1856
+ export const revalidate = [
1857
+ ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1858
+ ];
1859
+
1860
+ // pages/_middleware.rose: a Web-standard request handler that runs before
1861
+ // every render on the server (pages, POSTs, api calls alike). Returning a
1862
+ // Response short-circuits the whole request - a redirect, an auth wall, a
1863
+ // rewrite; returning nothing continues, and getContext() hands the
1864
+ // per-request bag to $data, server actions and api handlers. Absent -> null,
1865
+ // and the servers keep their static fast paths.
1866
+ export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1867
+
1868
+ // Routes whose DOCUMENTS ship without the client bundle (
1869
+ // decided by the compiler since #29): HTML + CSS only - no runtime, no
1870
+ // state script, zero JavaScript for whoever lands on them. The compiler
1871
+ // picks these automatically: a route whose whole chain needs nothing from
1872
+ // the client (no event wiring, no lifecycle, no action, no form) is a
1873
+ // content route. An exported "csr = true" forces the bundle back in; an
1874
+ // exported "csr = false" is the same decision, asserted. The route's render
1875
+ // function still rides in the client bundle, so a client-side navigation
1876
+ // from an interactive page paints it normally and a static deploy's SPA
1877
+ // fallback can render it too; only the document is JS-free.
1878
+ // isNoJs() lets the servers keep these routes on the buffered path: a
1879
+ // streamed no-JS document would carry the shell's default <title> (the
1880
+ // route head is applied client-side at boot, and there is no client).
1881
+ export const noJsRoutes = [
1882
+ ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1883
+ ];
1884
+
1885
+ export function isNoJs(pathname) {
1886
+ return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1887
+ }
1888
+
1889
+ // P0-2 (bug report): routes that exported "buffer = true". The servers ask
1890
+ // this BEFORE choosing a path: a streamed response commits its status and
1891
+ // headers before the body exists, so its onResponse hooks cannot see the
1892
+ // document and a render that throws mid-flight still answers 200. A buffered
1893
+ // route keeps every capability and gives up the early flush - the trade is
1894
+ // the route's to make, per route, not the framework's.
1895
+ export function isBuffered(pathname) {
1896
+ return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
1897
+ }
1898
+
1899
+ // Per-route response headers: a route exporting a headers
1900
+ // map carries them into every response the servers write for it, merged
1901
+ // OVER the framework defaults (the strict CSP) - so an app can tighten or
1902
+ // relax the policy per route. Absent -> null, and the servers keep sending
1903
+ // the defaults alone.
1904
+ export const routeHeaders = [
1905
+ ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1906
+ ];
1907
+
1908
+ export function headersFor(pathname) {
1909
+ const hit = routeHeaders.find((r) => matchRoute(r.pattern, pathname));
1910
+ return hit ? hit.headers : null;
1911
+ }
1912
+
1913
+ // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
1914
+ // ). The servers ask this BEFORE writing a document: when it is true they
1915
+ // mint one random nonce per response, put it in the CSP header ('nonce-...'
1916
+ // plus 'strict-dynamic', so the document's own code may load more code) and
1917
+ // stamp the same value on the script tag. The default policy stays a hash -
1918
+ // cspNonceRoutes is empty for an app that never asks, so the fast path is
1919
+ // unchanged. The Go binary never sees this: these routes are dynamic, so it
1920
+ // has no baked file for them to serve.
1921
+ export const cspNonceRoutes = [
1922
+ ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1923
+ ];
1924
+
1925
+ export function cspNonce(pathname) {
1926
+ return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1927
+ }
1928
+
1929
+ // A Web-standard Request from whatever the host provides: the edge adapter
1930
+ // passes one already; the Node server passes its IncomingMessage (plus the
1931
+ // already-parsed FormData for POSTs, so middleware can read form fields).
1932
+ function toWebRequest(raw, form) {
1933
+ if (raw instanceof Request) return raw;
1934
+ const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
1935
+ if (form) init.body = form;
1936
+ return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1937
+ }
1938
+
1939
+ // Runs the middleware (if the project has one) for this request and returns
1940
+ // its short-circuit Response, or null to continue. The servers call this
1941
+ // EXACTLY ONCE per request, before anything else: it resets the per-request
1942
+ // context bag and the middleware fills it via getContext(), which $data,
1943
+ // server actions and api handlers then read while rendering. rawReq: the
1944
+ // host's request (Node IncomingMessage or a Web-standard Request); form:
1945
+ // the already-parsed FormData of a POST.
1946
+ export async function runMiddleware(rawReq, form) {
1947
+ resetRequestContext();
1948
+ if (!middleware || !rawReq) return null;
1949
+ const res = await middleware(toWebRequest(rawReq, form));
1950
+ return res || null;
1951
+ }
1952
+
1953
+ const routes = [
1954
+ ${serverRoutes}
1955
+ ];
1956
+
1957
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
1958
+ // render HTML and never reach the client bundle. The middleware ran before
1959
+ // this (the servers call runMiddleware() first), so handlers can read
1960
+ // getContext() for auth without re-running anything.
1961
+ const apiRoutes = [
1962
+ ${apiRoutes.map(({ info, i }) => {
1963
+ const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
1964
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', handlers: { ${handlers} } }`;
1965
+ }).join(",\n ")}
1966
+ ];
1967
+
1968
+ // pages/404.rose (with its layouts) or null -> built-in plain 404
1969
+ const notFound = ${notFoundRender};
1970
+
1971
+ // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1972
+ // whose render throws degrades to this instead of failing the response.
1973
+ const errorPage = ${errorRender};
1974
+
1975
+ // The <html> attributes of the document for a pathname - the locale
1976
+ // of its [lang] segment (the default when there is none, or when the segment
1977
+ // names no dictionary: that request 404s in the default language) and the
1978
+ // reading direction that locale implies. The buffered render returns the same
1979
+ // pair; the streaming path needs it BEFORE the shell flushes, which is why
1980
+ // the servers ask for it by pathname.
1981
+ export function docAttrs(pathname) {
1982
+ for (const route of routes) {
1983
+ if (!matchRoute(route.pattern, pathname)) continue;
1984
+ const parts = route.pattern.split('/');
1985
+ const langIdx = parts.indexOf(':lang');
1986
+ if (langIdx >= 0) {
1987
+ const lang = pathname.split('/')[langIdx];
1988
+ if (isLocale(lang)) return { lang, dir: localeDir(lang) };
1989
+ }
1990
+ break; // matched, but not a localized route (or a bogus locale): the default
1991
+ }
1992
+ return { lang: defaultLocale, dir: localeDir(defaultLocale) };
1993
+ }
1994
+
1995
+ // Paint a fallback page (404/500) and serialize its state.
1996
+ async function renderFallback(pathname, render) {
1997
+ const { html, head } = extractHead(await render([], ''));
1998
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1999
+ return { html, state, head, ...docAttrs(pathname) };
2000
+ }
2001
+
2002
+ export function matchRoute(pattern, pathname) {
2003
+ const patternParts = pattern.split('/');
2004
+ const pathParts = pathname.split('/');
2005
+ if (patternParts.length !== pathParts.length) return false;
2006
+ for (let i = 0; i < patternParts.length; i++) {
2007
+ if (patternParts[i].startsWith(':')) continue;
2008
+ if (patternParts[i] !== pathParts[i]) return false;
2009
+ }
2010
+ return true;
2011
+ }
2012
+
2013
+ // Head blocks (one per component in the route chain) are pulled out of the
2014
+ // page html: the shell injects them into <head>, and the client re-applies
2015
+ // them on navigation. Document order is page-first, so the shell's keyed
2016
+ // merge lets a page override its layouts. The EMPTY marker pair stays in the
2017
+ // body so the client's wire() still finds the block: at boot it adopts the
2018
+ // shell-injected elements in place (marked with the same keys, so no
2019
+ // duplicates) and keeps the head reactive.
2020
+ function extractHead(rendered) {
2021
+ const head = [];
2022
+ const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
2023
+ head.push(content);
2024
+ return '<!--\u27E6h:' + id + '\u27E7--><!--\u27E6/h:' + id + '\u27E7-->';
2025
+ });
2026
+ return { html, head };
2027
+ }
2028
+
2029
+ // form: the submitted FormData of a progressive-enhancement POST. The
2030
+ // selected server action runs first and returns a state patch (e.g.
2031
+ // { guests: [...] }); seeding those keys BEFORE the render makes state()
2032
+ // adopt them, so the response is the page as it looks AFTER the action -
2033
+ // with or without JS. A __action field picks the action by name (default
2034
+ // 'action', the conventional <form method="POST"> target); a click handler
2035
+ // bound to an action ($action('like')) sends the same field.
2036
+ // A route whose render throws degrades to pages/500.rose (status 500) - or
2037
+ // the built-in plain 500 - instead of failing the whole response.
2038
+ // The middleware does NOT run here: the servers run it once per request via
2039
+ // runMiddleware() (which also seeds the request context), so a page render
2040
+ // never re-runs it.
2041
+ export async function renderPage(pathname, form) {
2042
+ clearRequestState();
2043
+ for (const route of routes) {
2044
+ if (matchRoute(route.pattern, pathname)) {
2045
+ const patternParts = route.pattern.split('/');
2046
+ const pathParts = pathname.split('/');
2047
+ for (let i = 0; i < patternParts.length; i++) {
2048
+ if (patternParts[i].startsWith(':')) {
2049
+ setState(patternParts[i].slice(1), pathParts[i]);
2050
+ }
2051
+ }
2052
+ // i18n: a [lang] segment naming no dictionary is a
2053
+ // 404 - the URL is the contract, and rendering the page with fallback
2054
+ // strings would serve duplicate content under a bogus language
2055
+ const langIdx = patternParts.indexOf(':lang');
2056
+ if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
2057
+ if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
2058
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2059
+ }
2060
+ // The document's <html lang>/<dir> follow this route's locale
2061
+ // (the default's when the route is not localized)
2062
+ const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
2063
+ // The action dispatch. The page's guard (exported
2064
+ // beforeAction) runs FIRST and vetoes with an ActionError - the
2065
+ // action-level permission check. Then the selected action runs and its
2066
+ // return value seeds this render's state, per key, so an incremental
2067
+ // patch ($append and friends) grows a large list by one row instead of
2068
+ // re-sending the whole thing. An ActionError from either half is a
2069
+ // BUSINESS failure: it is seeded as the 'actionError' state, the
2070
+ // response carries its status, and the page renders with the failure
2071
+ // visible (a {#boundary} around the action's widget contains it).
2072
+ // Anything else is a bug and keeps going to the 500 page.
2073
+ let actionStatus = 0;
2074
+ if (form && route.actions) {
2075
+ const actionName = form.get('__action') || 'action';
2076
+ const fn = route.actions[actionName];
2077
+ if (fn) {
2078
+ try {
2079
+ if (route.guard) await route.guard(actionName, form);
2080
+ const patch = await fn(form);
2081
+ if (patch && typeof patch === 'object') {
2082
+ for (const key of Object.keys(patch)) {
2083
+ const v = patch[key];
2084
+ // An incremental patch is RECORDED, not applied: the render's
2085
+ // own state declarations apply it, so the delta is relative to
2086
+ // the value the page was going to render anyway.
2087
+ if (v instanceof StateDelta) setStateDelta(key, v);
2088
+ else setState(key, v);
2089
+ }
2090
+ }
2091
+ } catch (err) {
2092
+ if (err instanceof ActionError) {
2093
+ setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
2094
+ actionStatus = err.code;
2095
+ } else {
2096
+ throw err;
2097
+ }
2098
+ }
2099
+ }
2100
+ }
2101
+ let rendered;
2102
+ try {
2103
+ rendered = extractHead(await route.render([], ''));
2104
+ } catch (err) {
2105
+ console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2106
+ if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
2107
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2108
+ }
2109
+ // __route tells the bootstrap which route this document was rendered for.
2110
+ // A static-file server may serve another route's document (SPA fallback);
2111
+ // the bootstrap then client-renders instead of adopting mismatched DOM.
2112
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2113
+ // csr ( auto since #29): false when the compiler found
2114
+ // nothing in the route's chain that needs the client (or the route
2115
+ // asserted csr = false) - the document ships no runtime, no state
2116
+ // script, zero JavaScript. Every other route keeps the bundle. The
2117
+ // caller passes this straight to the shell as js.
2118
+ // Status is the failed action's code when one failed - the page
2119
+ // rendered fine, so the body is the page with the failure visible, and
2120
+ // the status says what happened (a 403 from the guard, a 422 from a
2121
+ // validation action). 200 otherwise.
2122
+ // Lang/dir are the document's <html> attributes - the locale
2123
+ // this route rendered in, and its reading direction.
2124
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
2125
+ }
2126
+ }
2127
+ if (notFound) {
2128
+ return { ...(await renderFallback(pathname, notFound)), status: 404 };
2129
+ }
2130
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2131
+ }
2132
+
2133
+ // Would renderPageStream handle this path? (matched route = stream, anything
2134
+ // else = buffered 404/500). Lets the servers pick the path before headers.
2135
+ export function canStream(pathname) {
2136
+ return routes.some((route) => {
2137
+ if (!matchRoute(route.pattern, pathname)) return false;
2138
+ // i18n: an unknown locale must answer 404, and a
2139
+ // streamed response cannot change its status - so it takes the buffered
2140
+ // path (renderPage returns the real 404), never the streaming one
2141
+ const langIdx = route.pattern.split('/').indexOf(':lang');
2142
+ return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
2143
+ });
2144
+ }
2145
+
2146
+ // === API routes ===
2147
+ // The /api namespace answers JSON, never HTML: an API client that hits an
2148
+ // unknown path must not receive the SPA shell. Handlers receive a
2149
+ // Web-standard Request and return a plain object (serialized as JSON, 200),
2150
+ // a Response (passed through), or nothing (204). A method the route does
2151
+ // not export answers 405 with an Allow header. Same code path on the Node
2152
+ // server and the edge adapter - Response is a global in both.
2153
+ export function isApi(pathname) {
2154
+ return pathname === '/api' || pathname.startsWith('/api/');
2155
+ }
2156
+
2157
+ function toResponse(out) {
2158
+ if (out instanceof Response) return out;
2159
+ if (out === undefined || out === null) return new Response(null, { status: 204 });
2160
+ return new Response(JSON.stringify(out), {
2161
+ status: 200,
2162
+ headers: { 'content-type': 'application/json' },
2163
+ });
2164
+ }
2165
+
2166
+ export async function handleApi(method, pathname, request) {
2167
+ for (const route of apiRoutes) {
2168
+ if (matchRoute(route.pattern, pathname)) {
2169
+ const fn = route.handlers[method];
2170
+ if (!fn) {
2171
+ return new Response(JSON.stringify({ error: 'method not allowed' }), {
2172
+ status: 405,
2173
+ headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
2174
+ });
2175
+ }
2176
+ return toResponse(await fn(request));
2177
+ }
2178
+ }
2179
+ return new Response(JSON.stringify({ error: 'not found' }), {
2180
+ status: 404,
2181
+ headers: { 'content-type': 'application/json' },
2182
+ });
2183
+ }
2184
+
2185
+ // === Streaming SSR ===
2186
+ // The static shell (doctype, <head>, body + container open) flushes BEFORE
2187
+ // the - possibly slow - render completes: the first byte leaves in
2188
+ // microseconds instead of after every $data resolves. The route HTML, the
2189
+ // state script, and the inlined bundle follow as later chunks of one chunked
2190
+ // response - still exactly one request.
2191
+ // The route's <head> tags are NOT in the streamed document: the client
2192
+ // applies them at boot from the body's head markers, so JS users see the
2193
+ // correct head immediately; no-JS consumers of streamed responses get the
2194
+ // static shell head (prerendered files stay complete documents).
2195
+ // Returns 200 (matched; a render throw degrades to the error-page body) or
2196
+ // 404 (unmatched - nothing written, so the caller can still buffer).
2197
+ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2198
+ clearRequestState();
2199
+ for (const route of routes) {
2200
+ if (matchRoute(route.pattern, pathname)) {
2201
+ const patternParts = route.pattern.split('/');
2202
+ const pathParts = pathname.split('/');
2203
+ for (let i = 0; i < patternParts.length; i++) {
2204
+ if (patternParts[i].startsWith(':')) {
2205
+ setState(patternParts[i].slice(1), pathParts[i]);
2206
+ }
2207
+ }
2208
+ // i18n: an unknown locale must 404 BEFORE the shell flushes - a
2209
+ // streamed response cannot change its status afterwards
2210
+ const langIdx = patternParts.indexOf(':lang');
2211
+ if (langIdx >= 0 && !isLocale(pathParts[langIdx])) return 404;
2212
+ write(shellOpen);
2213
+ let html;
2214
+ try {
2215
+ html = extractHead(await route.render([], '')).html;
2216
+ } catch (err) {
2217
+ // the shell is already on the wire: degrade to the error page BODY
2218
+ // (the status stays 200 - a real 500 needs the buffered path, which
2219
+ // the server picks for routes known-broken at build time)
2220
+ console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2221
+ html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
2222
+ }
2223
+ write(html);
2224
+ // csr: false ( auto since #29): a no-JS route's document
2225
+ // ends here - no state script, no inlined bundle. (The servers keep
2226
+ // these routes off the streaming path so their <head> is complete;
2227
+ // this is the correctness floor if one streams anyway.)
2228
+ if (route.csr === false) {
2229
+ write('</div>\\n</body>\\n</html>');
2230
+ return 200;
2231
+ }
2232
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2233
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
2234
+ return 200;
2235
+ }
2236
+ }
2237
+ return 404;
2238
+ }
2239
+ `;
2240
+ await fs.promises.writeFile(path.join(buildDir, "server-entry.js"), serverEntry);
2241
+ await esbuild.build({
2242
+ entryPoints: [path.join(buildDir, "server-entry.js")],
2243
+ bundle: true,
2244
+ outfile: path.join(outDir, "server.js"),
2245
+ format: "esm",
2246
+ platform: "node",
2247
+ write: true,
2248
+ ...TS_LOADER
2249
+ });
2250
+ const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
2251
+ const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
2252
+ const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
2253
+ const vitalsOn = compiled.some((c) => c.vitals === true);
2254
+ const vitalsBlock = vitalsOn ? `
2255
+ // the app asked for web-vitals - measure once, at boot, and let the
2256
+ // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2257
+ reportVitals;
2258
+ ` : "";
2259
+ const hasLang = infos.some((i) => i.pattern.includes(":lang"));
2260
+ const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
2261
+ // client-side navigation cannot leave stale (screen readers and CSS
2262
+ // logical properties both read it). A route with no [lang] segment
2263
+ // returns to the default locale, and a bogus segment falls back to it
2264
+ // too, exactly like the server's docAttrs.
2265
+ const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
2266
+ const known = !seg || isLocale(seg);
2267
+ const docLang = known && seg ? seg : __defLocale;
2268
+ document.documentElement.lang = docLang;
2269
+ const docDir = localeDir(docLang);
2270
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
2271
+ else document.documentElement.removeAttribute('dir');
2272
+ if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2273
+ const clientEntry = `
2274
+ ${clientImports}
2275
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
2276
+
2277
+ // i18n: the dictionaries baked at build time - the client
2278
+ // renders any PRELOADED locale from the bundle, so switching language costs
2279
+ // zero requests (the same bet as the inlined route table). a locale
2280
+ // the app left out of the preload (i18n.preload in rosetack.config.js) is a
2281
+ // pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
2282
+ // on first use - one request per language per session, then it renders from
2283
+ // memory like any other. The default build preloads everything and ships no
2284
+ // packs at all.
2285
+ setLocales(${clientLocalesJson}, '${defaultLocale}');
2286
+ setLocalePacks(${JSON.stringify(packed)});
2287
+ ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
2288
+ // follow a route that carries no [lang] segment (a non-i18n page)
2289
+ const __defLocale = '${defaultLocale}';` : ""}
2290
+ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2291
+ // reportVitals alive through minification and tree-shaking; the call is one
2292
+ // statement at boot, before the first render.
2293
+ import { reportVitals } from './runtime.js';` : ""}
2294
+ // The two pack doors, re-exported for an app that wants to warm a language
2295
+ // before its visitor asks for it (ensureLocale) or to feed a dictionary it
2296
+ // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
2297
+ // is what applyParams calls - so the re-export costs the statement alone.
2298
+ export { ensureLocale, loadLocale } from './runtime.js';
2299
+ ${vitalsBlock}
2300
+
2301
+ const routes = [
2302
+ ${clientRoutes}
2303
+ ];
2304
+
2305
+ // === Mode B: lazy route chunks ===
2306
+ // Split mode's registry entries arrive without a render function: loadChain
2307
+ // loads the route's module graph (the page plus its layouts, one chunk per
2308
+ // module, the shared runtime in its own vendor chunk) in parallel and
2309
+ // composes it at runtime - the exact nesting compose() built at compile
2310
+ // time for inline mode. getRender memoizes the composed function on the
2311
+ // entry, so a chunk loads once per session; inline mode's entries are the
2312
+ // render functions themselves, so the helper is a pass-through there.
2313
+ const loadChain = async (loaders) => {
2314
+ const mods = await Promise.all(loaders.map((load) => load()));
2315
+ let expr = (closes, children) => mods[0].render(closes, children);
2316
+ for (let k = 1; k < mods.length; k++) {
2317
+ const inner = expr;
2318
+ const outer = mods[k].render;
2319
+ expr = async (closes, children) => await outer(closes, await inner(closes, children));
2320
+ }
2321
+ return { render: expr };
2322
+ };
2323
+ const getRender = async (route) => {
2324
+ if (typeof route === 'function') return route; // inline mode: the render itself
2325
+ return (route.render ??= (await route.load()).render);
2326
+ };
2327
+
2328
+ // pages/404.rose (with its layouts) or null -> built-in plain 404
2329
+ const notFound = ${notFoundRender};
2330
+
2331
+ // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
2332
+ // whose render throws on the client degrades to this instead of breaking
2333
+ // navigation.
2334
+ const errorPage = ${errorRender};
2335
+
2336
+ // Paint a fallback page (404/500) into the container, wired like any render.
2337
+ async function paintFallback(container, page, builtin) {
2338
+ resetEffects();
2339
+ clearRequestState();
2340
+ clearMounts(); // a failed render leaves stale mounts behind
2341
+ // inline mode passes the render itself; split mode passes a loader
2342
+ const render = page ? await getRender(page) : null;
2343
+ if (render) {
2344
+ const closes = [];
2345
+ const html = await render(closes, '');
2346
+ container.innerHTML = html;
2347
+ wire(container, closes);
2348
+ bindEvents(container);
2349
+ flushMounts();
2350
+ return;
2351
+ }
2352
+ container.innerHTML = builtin;
2353
+ }
2354
+
2355
+ export function matchRoute(pattern, pathname) {
2356
+ const patternParts = pattern.split('/');
2357
+ const pathParts = pathname.split('/');
2358
+ if (patternParts.length !== pathParts.length) return false;
2359
+ for (let i = 0; i < patternParts.length; i++) {
2360
+ if (patternParts[i].startsWith(':')) continue;
2361
+ if (patternParts[i] !== pathParts[i]) return false;
2362
+ }
2363
+ return true;
2364
+ }
2365
+
2366
+ // === Link prefetch ===
2367
+ // Hover / focus / touch an internal link and the target route renders NOW -
2368
+ // $data included - against a throwaway signal map. The click that follows
2369
+ // paints from the cached HTML: no await, no request, no spinner. Other
2370
+ // frameworks prefetch data only; rosetack prefetches the whole render because
2371
+ // the inlined bundle already contains every route.
2372
+ // Trade-off: the cache holds either a result or the in-flight promise (dedupes
2373
+ // hover storms); one isolated render runs at a time so signal-map swapping
2374
+ // stays correct without any merging logic. Entries are single-use: a consumed
2375
+ // entry disappears from the cache, which is also how tests observe a hit.
2376
+ // P1, three guards for link-heavy pages:
2377
+ // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
2378
+ // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
2379
+ // Trade-off: app-global, not per-route - per-route would carry the mode
2380
+ // in each document's shell.
2381
+ // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
2382
+ // the budget caps the QUEUE: a hover storm past it drops the excess
2383
+ // instead of rendering fifty routes nobody clicks.
2384
+ // 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
2385
+ // is evicted first (Map iteration order; entries are single-use, so
2386
+ // insertion order IS the recency order).
2387
+ let prefetchMode = ${JSON.stringify(prefetchMode)};
2388
+ export function setPrefetchMode(mode) { prefetchMode = mode; }
2389
+ const PREFETCH_BUDGET = 8;
2390
+ const PREFETCH_MAX_CACHED = 4;
2391
+ const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
2392
+ let prefetchQueue = Promise.resolve();
2393
+ let prefetchPending = 0;
2394
+
2395
+ // Applies the route's params to state. A [lang] segment whose dictionary is
2396
+ // a runtime pack (i18n.preload) is awaited HERE - the one place every client
2397
+ // render path goes through (navigation, prefetch, action adopt) - so a packed
2398
+ // locale costs one request per session and then renders from memory. A
2399
+ // preloaded locale (the default: every dictionary inline) resolves without
2400
+ // touching the network, so the common path stays synchronous in spirit.
2401
+ async function applyParams(route, pathname) {
2402
+ const patternParts = route.pattern.split('/');
2403
+ const pathParts = pathname.split('/');
2404
+ for (let i = 0; i < patternParts.length; i++) {
2405
+ if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
2406
+ }
2407
+ const langIdx = patternParts.indexOf(':lang');
2408
+ if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
2409
+ }
2410
+
2411
+ export function prefetch(pathname, source = 'hover') {
2412
+ if (prefetchMode === 'off') return;
2413
+ if (prefetchMode === 'hover' && source !== 'hover') return;
2414
+ if (prefetchMode === 'viewport' && source !== 'viewport') return;
2415
+ if (prefetchCache.has(pathname)) return;
2416
+ if (pathname === location.pathname) return; // already here: nothing to prefetch
2417
+ const route = routes.find((r) => matchRoute(r.pattern, pathname));
2418
+ if (!route) return;
2419
+ if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
2420
+ // P0-1: the link may carry a query (/search?q=cats). $query() reads the
2421
+ // browser's own URL, which is the page being LEFT - so the prefetched
2422
+ // render would see the wrong one. Override it for the duration and clear
2423
+ // it after; the queue below serializes renders, so one slot is enough.
2424
+ const qi = pathname.indexOf('?');
2425
+ const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
2426
+ const p = prefetchQueue.then(async () => {
2427
+ try {
2428
+ setPrefetchOverride(qOverride);
2429
+ // the isolated render also captures the onMount callbacks the route
2430
+ // queued and the onCleanup disposers it registered: the paint that
2431
+ // consumes this entry replays the mounts after wiring and adopts the
2432
+ // cleanups, so the prefetched route's timers are disposed on the next
2433
+ // navigation like any live route's
2434
+ const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
2435
+ await applyParams(route, pathname); // a packed locale's dictionary lands before the render
2436
+ const closes = [];
2437
+ const render = await getRender(route); // split mode: loads the route's chunk here
2438
+ const html = await render(closes, '');
2439
+ return { html, closes };
2440
+ });
2441
+ const entry = { ...result, state, mounts, cleanups };
2442
+ prefetchCache.set(pathname, entry); // promise -> result
2443
+ // evict oldest-first; in-flight promises are never evicted (evicting
2444
+ // one would only force a duplicate render)
2445
+ while (prefetchCache.size > PREFETCH_MAX_CACHED) {
2446
+ const oldest = prefetchCache.keys().next().value;
2447
+ if (prefetchCache.get(oldest) instanceof Promise) break;
2448
+ prefetchCache.delete(oldest);
2449
+ }
2450
+ return entry;
2451
+ } catch {
2452
+ prefetchCache.delete(pathname); // failed: the next hover retries
2453
+ return null;
2454
+ } finally {
2455
+ setPrefetchOverride(null);
2456
+ prefetchPending--;
2457
+ }
2458
+ });
2459
+ prefetchPending++;
2460
+ prefetchCache.set(pathname, p);
2461
+ prefetchQueue = p;
2462
+ }
2463
+
2464
+ export function prefetchStats() {
2465
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
2466
+ }
2467
+
2468
+ // One delegated listener per event type on the app container: survives DOM
2469
+ // swaps and cloned blocks, so handlers never need re-binding. A handler
2470
+ // compiled from a server action (data-on-*="$action:name") dispatches to
2471
+ // $action instead of the local handler registry.
2472
+ const DELEGATED = ['click', 'input', 'change', 'submit'];
2473
+ function bindEvents(container) {
2474
+ if (container.__rosetack_bound) return;
2475
+ container.__rosetack_bound = true;
2476
+ for (const ev of DELEGATED) {
2477
+ container.addEventListener(ev, (e) => {
2478
+ const el = e.target.closest('[data-on-' + ev + ']');
2479
+ if (!el || !container.contains(el)) return;
2480
+ const fn = el.getAttribute('data-on-' + ev);
2481
+ if (fn.startsWith('$action:')) return $action(fn.slice(8), e);
2482
+ const h = handlers[fn];
2483
+ if (h) h(e);
2484
+ });
2485
+ }
2486
+ }
2487
+
2488
+ // === Server actions from any event ===
2489
+ // POST the body to the current route and adopt the response in place: the
2490
+ // server runs the selected action, seeds its state patch, and re-renders, so
2491
+ // the swapped DOM is the page as it looks AFTER the action - one request, no
2492
+ // reload, and wire() patches only the marked nodes (no re-render). The
2493
+ // bootstrap's <form method="POST"> interception goes through the same door.
2494
+ async function postForm(body) {
2495
+ const res = await fetch(location.pathname, { method: 'POST', body });
2496
+ const html = await res.text();
2497
+ const doc = new DOMParser().parseFromString(html, 'text/html');
2498
+ const next = doc.getElementById('app');
2499
+ const st = doc.getElementById('__rosetack_state');
2500
+ const paint = () => {
2501
+ const container = document.getElementById('app');
2502
+ adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
2503
+ };
2504
+ if (document.startViewTransition) document.startViewTransition(paint);
2505
+ else paint();
2506
+ }
2507
+
2508
+ // Call a page's server action by name from any event handler:
2509
+ // <button on:click={like}> compiles to $action('like'). Without JS the
2510
+ // binding is inert - the progressive-enhancement story stays with forms.
2511
+ export async function $action(name, e) {
2512
+ if (e && e.preventDefault) e.preventDefault();
2513
+ const body = new FormData();
2514
+ body.append('__action', name);
2515
+ return postForm(body);
2516
+ }
2517
+
2518
+ export { postForm };
2519
+
2520
+ // The live signal graph as JSON - the same serializeState the zero-hydration
2521
+ // resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
2522
+ // can hand it to the dev server's reload bridge and to a devtools extension.
2523
+ // A local re-export on purpose: it keeps the binding alive through minification
2524
+ // for the bootstrap text appended after the bundle.
2525
+ export { serializeState };
2526
+
2527
+ // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2528
+ // the existing nodes and bind events. initial=false: client-side navigation -
2529
+ // re-render the route chain from scratch and wire the fresh DOM.
2530
+ export async function start(container, pathname, initial) {
2531
+ clearMounts(); // stale mounts from a failed render never fire
2532
+ if (initial) {
2533
+ const el = document.getElementById('__rosetack_state');
2534
+ if (el) resumeState(el.textContent);
2535
+ }
2536
+ for (const route of routes) {
2537
+ if (matchRoute(route.pattern, pathname)) {
2538
+ // i18n: an unknown locale paints the 404 page, same as the server
2539
+ // (before the prefetch check: a cached entry for a bogus locale is
2540
+ // discarded, never painted)
2541
+ const langIdx = route.pattern.split('/').indexOf(':lang');
2542
+ ${langDirBlock}
2543
+ await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2544
+ return;
2545
+ }
2546
+ // Prefetched on hover/focus/touch: the render already ran, so paint its
2547
+ // HTML and adopt its signal entries - events then patch the very nodes
2548
+ // we wire, and no $data re-runs on click.
2549
+ let hit = initial ? undefined : prefetchCache.get(pathname);
2550
+ if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2551
+ if (hit) {
2552
+ prefetchCache.delete(pathname); // single-use: the next hover refetches
2553
+ resetEffects();
2554
+ restoreState(hit.state);
2555
+ container.innerHTML = hit.html;
2556
+ wire(container, hit.closes);
2557
+ bindEvents(container);
2558
+ hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2559
+ adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
2560
+ return;
2561
+ }
2562
+ if (!initial) {
2563
+ resetEffects();
2564
+ clearRequestState();
2565
+ }
2566
+ await applyParams(route, pathname);
2567
+ const closes = [];
2568
+ let html;
2569
+ try {
2570
+ const render = await getRender(route); // split mode: loads the route's chunk here
2571
+ html = await render(closes, '');
2572
+ } catch {
2573
+ // the route itself is broken: degrade to pages/500.rose (or the
2574
+ // built-in plain 500) instead of leaving the container empty
2575
+ await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2576
+ return;
2577
+ }
2578
+ if (!initial) container.innerHTML = html;
2579
+ wire(container, closes);
2580
+ bindEvents(container);
2581
+ flushMounts();
2582
+ return;
2583
+ }
2584
+ }
2585
+ // unmatched route: pages/404.rose renders (with its head + interactivity),
2586
+ // else the built-in plain 404 - and an i18n app's document returns to the
2587
+ // default locale, the same one the server stamps on its 404
2588
+ ${hasLang ? ` document.documentElement.lang = __defLocale;
2589
+ document.documentElement.removeAttribute('dir');` : ""}
2590
+ await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2591
+ }
2592
+
2593
+ // Adopt a server-rendered response in place - the JS-enabled half of
2594
+ // progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
2595
+ // via fetch and hands the response here. The DOM is swapped and wired with
2596
+ // the same zero-render trick as boot: re-run the route's render to rebuild
2597
+ // the marker closures, wire them against the adopted nodes. The page never
2598
+ // re-renders visibly, no hydration payload, no second request beyond the POST.
2599
+ export async function adopt(container, html, stateJson) {
2600
+ resetEffects();
2601
+ clearRequestState();
2602
+ clearMounts(); // stale mounts from a failed render never fire
2603
+ resumeState(stateJson);
2604
+ container.innerHTML = html;
2605
+ // keep the embedded state in sync so a later SPA-fallback check agrees
2606
+ const st = document.getElementById('__rosetack_state');
2607
+ if (st) st.textContent = stateJson;
2608
+ for (const route of routes) {
2609
+ if (matchRoute(route.pattern, location.pathname)) {
2610
+ await applyParams(route, location.pathname);
2611
+ const closes = [];
2612
+ try {
2613
+ const render = await getRender(route); // split mode: loads the route's chunk here
2614
+ await render(closes, '');
2615
+ } catch {
2616
+ // the adopted response's route is broken (e.g. the action's page
2617
+ // throws): keep the swapped DOM but skip wiring it
2618
+ return;
2619
+ }
2620
+ wire(container, closes);
2621
+ bindEvents(container);
2622
+ flushMounts();
2623
+ return;
2624
+ }
2625
+ }
2626
+ }
2627
+ // === refresh() implementation ===
2628
+ // Re-render the current route in place: the client half of router.refresh()
2629
+ // (a router refresh) / (a full invalidation). Same machinery as a client-side
2630
+ // navigation to the current path - $data re-runs, state re-seeds from the
2631
+ // fresh render, wire() patches the marked nodes - but a refresh never lands
2632
+ // a prefetch entry: a hover from a minute ago is exactly what it exists to
2633
+ // bypass. Zero requests: the render (and its $data) runs in the page.
2634
+ // Trade-off: state resets like navigation (no per-key retention); add
2635
+ // retention when an app needs refresh-without-losing-input.
2636
+ setRefreshHook(async () => {
2637
+ prefetchCache.delete(location.pathname);
2638
+ await start(document.getElementById('app'), location.pathname, false);
2639
+ });
2640
+ `;
2641
+ await fs.promises.writeFile(path.join(buildDir, "client-entry.js"), clientEntry);
2642
+ if (split) {
2643
+ await fs.promises.rm(path.join(outDir, "chunks"), { recursive: true, force: true });
2644
+ await esbuild.build({
2645
+ entryPoints: [path.join(buildDir, "client-entry.js")],
2646
+ bundle: true,
2647
+ format: "esm",
2648
+ platform: "browser",
2649
+ minify: true,
2650
+ splitting: true,
2651
+ outdir: outDir,
2652
+ entryNames: "client",
2653
+ chunkNames: "chunks/[name]-[hash]",
2654
+ write: true,
2655
+ ...TS_LOADER
2656
+ });
2657
+ } else {
2658
+ await esbuild.build({
2659
+ entryPoints: [path.join(buildDir, "client-entry.js")],
2660
+ bundle: true,
2661
+ outfile: path.join(outDir, "client.js"),
2662
+ format: "esm",
2663
+ platform: "browser",
2664
+ minify: true,
2665
+ write: true,
2666
+ ...TS_LOADER
2667
+ });
2668
+ }
2669
+ await fs.promises.rm(buildDir, { recursive: true, force: true });
2670
+ const publicDir = path.join(root, "public");
2671
+ if (fs.existsSync(publicDir)) {
2672
+ const outPublic = path.join(outDir, "public");
2673
+ await fs.promises.mkdir(outPublic, { recursive: true });
2674
+ const assets = await fs.promises.readdir(publicDir);
2675
+ await Promise.all(
2676
+ assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
2677
+ );
2678
+ }
2679
+ console.log("rosetack zero-JS report:");
2680
+ for (const line of buildReport(infos, compiled)) console.log(" " + line);
2681
+ for (const { info, i } of pages) {
2682
+ if (!routeShipsNoJs(infos, compiled, i)) continue;
2683
+ for (const ci of [i, ...layoutsOf(infos, i)]) {
2684
+ for (const w of compiled[ci].jsWarnings ?? []) {
2685
+ console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
2686
+ }
2687
+ }
2688
+ }
2689
+ return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2690
+ }
2691
+ async function scanRoseFiles(root) {
2692
+ const pagesDir = path.join(root, "src", "pages");
2693
+ if (!fs.existsSync(pagesDir)) return [];
2694
+ async function scan(dir) {
2695
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
2696
+ const files = [];
2697
+ for (const entry of entries) {
2698
+ const full = path.join(dir, entry.name);
2699
+ if (entry.isDirectory()) files.push(...await scan(full));
2700
+ else if (entry.name.endsWith(".rose")) files.push(full);
2701
+ }
2702
+ return files;
2703
+ }
2704
+ return scan(pagesDir);
2705
+ }
2706
+ async function scanComponentFiles(root) {
2707
+ const compDir = path.join(root, "src", "components");
2708
+ if (!fs.existsSync(compDir)) return [];
2709
+ async function scan(dir) {
2710
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
2711
+ const files = [];
2712
+ for (const entry of entries) {
2713
+ const full = path.join(dir, entry.name);
2714
+ if (entry.isDirectory()) files.push(...await scan(full));
2715
+ else if (entry.name.endsWith(".rose")) files.push(full);
2716
+ }
2717
+ return files;
2718
+ }
2719
+ return scan(compDir);
2720
+ }
2721
+ function isAncestorDir(layoutPath, pagePath) {
2722
+ const layoutDir = path.dirname(layoutPath);
2723
+ const pageDir = path.dirname(pagePath);
2724
+ return pageDir === layoutDir || pageDir.startsWith(layoutDir + path.sep);
2725
+ }
2726
+ function getRouteInfo(filePath, root) {
2727
+ const pagesDir = path.join(root, "src", "pages");
2728
+ const relative3 = path.relative(pagesDir, filePath).replace(/\\/g, "/");
2729
+ const withoutExt = relative3.replace(/\.rose$/, "");
2730
+ const base = path.posix.basename(withoutExt);
2731
+ const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2732
+ const isLayout = !isComponent && base === "_layout";
2733
+ const isNotFound = !isComponent && base === "404";
2734
+ const isError = !isComponent && base === "500";
2735
+ const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2736
+ const isMiddleware = !isComponent && withoutExt === "_middleware";
2737
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout");
2738
+ if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
2739
+ const routeParts = parts.map(
2740
+ (part) => part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part
2741
+ );
2742
+ let routePath;
2743
+ if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2744
+ routePath = "/";
2745
+ } else {
2746
+ routePath = "/" + routeParts.join("/");
2747
+ }
2748
+ return {
2749
+ filePath,
2750
+ routePath,
2751
+ pattern: routePath,
2752
+ paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
2753
+ isLayout,
2754
+ isNotFound,
2755
+ isError,
2756
+ isApi,
2757
+ isMiddleware,
2758
+ isComponent
2759
+ };
2760
+ }
2761
+ function capitalize(s) {
2762
+ return s.charAt(0).toUpperCase() + s.slice(1);
2763
+ }
2764
+
2765
+ // src/cli/shell.ts
2766
+ import * as fs2 from "fs";
2767
+ import * as path2 from "path";
2768
+ import * as esbuild2 from "esbuild";
2769
+ var OUT_DIR = path2.join(process.cwd(), "dist");
2770
+ var styleCache = null;
2771
+ function getStyles() {
2772
+ const file = path2.join(OUT_DIR, "styles.css");
2773
+ try {
2774
+ const st = fs2.statSync(file);
2775
+ if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
2776
+ styleCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
2777
+ }
2778
+ return styleCache.source;
2779
+ } catch {
2780
+ return "";
2781
+ }
2782
+ }
2783
+ var BOOTSTRAP = esbuild2.transformSync(`
2784
+ const __app = document.getElementById('app');
2785
+ // Native View Transitions around client-side navigation (progressive:
2786
+ // browsers without the API navigate normally, no polyfill, no CSS required).
2787
+ function __navigate(pathname) {
2788
+ const paint = () => start(__app, pathname);
2789
+ if (document.startViewTransition) {
2790
+ return document.startViewTransition(paint).updateCallbackDone;
2791
+ }
2792
+ return paint();
2793
+ }
2794
+ window.addEventListener('popstate', () => __navigate(window.location.pathname));
2795
+ document.addEventListener('click', (e) => {
2796
+ const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
2797
+ if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
2798
+ e.preventDefault();
2799
+ history.pushState(null, '', a.getAttribute('href'));
2800
+ __navigate(window.location.pathname);
2801
+ }
2802
+ });
2803
+ // Prefetch the target route's full render (including $data) on hover, keyboard
2804
+ // focus, or touch - the click that follows paints from cache: no await, no
2805
+ // request. Other frameworks prefetch data only; rosetack prefetches the render
2806
+ // because the inlined bundle already contains every route.
2807
+ function __prefetchHandler(e) {
2808
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
2809
+ if (a && prefetch) prefetch(a.getAttribute('href'), 'hover');
2810
+ }
2811
+ document.addEventListener('mouseover', __prefetchHandler);
2812
+ document.addEventListener('focusin', __prefetchHandler);
2813
+ document.addEventListener('touchstart', __prefetchHandler, { passive: true });
2814
+ // Viewport + idle prefetch (viewport-triggered): once a link scrolls into view and the
2815
+ // browser is idle, its route renders ahead of any interaction. trade-off: both
2816
+ // APIs are feature-detected; without them the hover/focus/touch path above
2817
+ // still covers every link.
2818
+ if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
2819
+ const io = new IntersectionObserver((entries) => {
2820
+ for (const e of entries) {
2821
+ if (!e.isIntersecting) continue;
2822
+ io.unobserve(e.target); // one-shot per element; fresh links re-observe after nav
2823
+ requestIdleCallback(() => prefetch(e.target.getAttribute('href'), 'viewport'));
2824
+ }
2825
+ });
2826
+ // observing an already-observed element is a no-op, so re-sweeping is cheap
2827
+ const observeLinks = () => {
2828
+ for (const a of document.querySelectorAll('a[href^="/"]')) io.observe(a);
2829
+ };
2830
+ observeLinks();
2831
+ // navigation swaps the container's innerHTML: re-observe the fresh links
2832
+ const __rawNav = __navigate;
2833
+ __navigate = (p) => __rawNav(p).then(observeLinks, () => {});
2834
+ }
2835
+ // Progressive-enhancement forms: <form method="POST"> backed by a server
2836
+ // action. With JS the submit is intercepted and handed to postForm (one
2837
+ // request, in-place adopt). Without JS the browser performs the native POST
2838
+ // and the server re-renders the page: the same form works with JavaScript
2839
+ // disabled, which Server Actions in other frameworks do not.
2840
+ document.addEventListener('submit', (e) => {
2841
+ const f = e.target;
2842
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
2843
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
2844
+ e.preventDefault();
2845
+ postForm(new FormData(f));
2846
+ });
2847
+ // Dev seam: the live signal graph, readable as JSON. Two callers, one
2848
+ // implementation: the dev server's reload bridge snapshots it before a
2849
+ // rebuild-triggered reload so the edit lands on the state the developer had,
2850
+ // and a devtools extension reads it the same way. It is the same
2851
+ // serializeState the zero-hydration resume already ships, so the only new
2852
+ // bytes are the assignment.
2853
+ window.__rosetack = { state: () => serializeState() };
2854
+ // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
2855
+ // If the document was rendered for a DIFFERENT route (a static-file server's
2856
+ // SPA fallback serves index.html for unknown paths), adopt nothing - let the
2857
+ // client router render the requested route from scratch.
2858
+ const __st = document.getElementById('__rosetack_state');
2859
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
2860
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
2861
+ // the next document (window.__rosetack_resume). The resumed values win over the
2862
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
2863
+ // the route renders client-side from the bundle rather than adopting the SSR
2864
+ // DOM, because a resumed list can be longer than the document's rows and
2865
+ // adoption could not add them. Absent in every non-dev document.
2866
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
2867
+ if (__resumed) {
2868
+ const __route = __state.__route;
2869
+ __state = Object.assign(__state, __resumed);
2870
+ __state.__route = __route;
2871
+ }
2872
+ if (__resumed) {
2873
+ start(__app, window.location.pathname);
2874
+ } else if (__state.__route === window.location.pathname) {
2875
+ start(__app, window.location.pathname, true);
2876
+ } else {
2877
+ start(__app, window.location.pathname);
2878
+ }
2879
+ `, { minify: true }).code;
2880
+ var EXTERNAL_BOOTSTRAP = `
2881
+ import { start, prefetch, postForm } from '/client.js';
2882
+ ${BOOTSTRAP}`;
2883
+ function inlineScript(client) {
2884
+ return `
2885
+ ${client}
2886
+ ${BOOTSTRAP}`;
2887
+ }
2888
+ var FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
2889
+ var STYLES = `
2890
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
2891
+ button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
2892
+ a { color: #e91e63; text-decoration: none; font-weight: bold; }
2893
+ a:hover { text-decoration: underline; }
2894
+ nav a { margin-right: 1rem; }
2895
+ .rh { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; border-bottom: 2px solid #e91e63; margin-bottom: 1.5rem; padding-bottom: 0.75rem; }
2896
+ .rb { font-size: 1.6rem; }
2897
+ .rbrand { display: inline-flex; align-items: center; gap: 0.5em; }
2898
+ .rlogo { height: 1em; width: 1em; vertical-align: -0.08em; margin-right: 0.2em; }
2899
+ @media (max-width: 640px) {
2900
+ .rh { flex-direction: column; align-items: flex-start; gap: 0.75rem; }
2901
+ nav a:last-child { margin-right: 0; }
2902
+ }
2903
+ .rn { display: inline-block; margin-left: 1.5rem; }
2904
+ .rf { margin-top: 2rem; color: #888; font-size: 0.85rem; }
2905
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
2906
+ `;
2907
+ var STYLES_MIN = STYLES.replace(
2908
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
2909
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
2910
+ ).trim();
2911
+ function mergeHeadBlocks(blocks) {
2912
+ const byKey = /* @__PURE__ */ new Map();
2913
+ const order = [];
2914
+ const positional = /* @__PURE__ */ new Map();
2915
+ const put = (key, html) => {
2916
+ if (!byKey.has(key)) {
2917
+ byKey.set(key, html);
2918
+ order.push(key);
2919
+ }
2920
+ };
2921
+ for (const block of blocks) {
2922
+ for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
2923
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
2924
+ const tag = m[1].toLowerCase();
2925
+ if (tag === "title") continue;
2926
+ const attrs = m[2];
2927
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
2928
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
2929
+ let key;
2930
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
2931
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
2932
+ else {
2933
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
2934
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
2935
+ }
2936
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
2937
+ put(key, marked);
2938
+ }
2939
+ }
2940
+ return order.map((k) => byKey.get(k)).join("\n ");
2941
+ }
2942
+ function clientScriptTag(client, nonce = "") {
2943
+ const n = nonce ? ` nonce="${nonce}"` : "";
2944
+ return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
2945
+ <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
2946
+ }
2947
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
2948
+ const clientTag = clientScriptTag(client, nonce);
2949
+ const mergedHead = mergeHeadBlocks(head);
2950
+ const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
2951
+ const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
2952
+ ${FAVICON}`;
2953
+ const headTags = mergedHead ? `
2954
+ ${mergedHead}` : "";
2955
+ const styleTag = styles ? `
2956
+ <style>${styles}</style>` : "";
2957
+ const jsTail = js ? `
2958
+ <script type="application/json" id="__rosetack_state">${stateJson}</script>
2959
+ ${clientTag}` : "";
2960
+ const open = js ? '<div id="app">' : "";
2961
+ const close = js ? "</div>" : "";
2962
+ const shellStyles = js ? `
2963
+ <style>${STYLES_MIN}</style>` : "";
2964
+ return `<!DOCTYPE html>
2965
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
2966
+ <head>
2967
+ <meta charset="UTF-8">
2968
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
2969
+ ${titleTag}${shellStyles}${styleTag}
2970
+ </head>
2971
+ <body>
2972
+ ${open}${ssrHtml}${close}${jsTail}
2973
+ </body>
2974
+ </html>`;
2975
+ }
2976
+
2977
+ // src/cli/test.ts
2978
+ var GRAFTED = ["document", "Node", "NodeFilter", "FormData", "DOMParser", "location", "fetch", "Event", "CustomEvent", "MutationObserver", "requestAnimationFrame"];
2979
+ function projectRootOf(file) {
2980
+ let dir = path3.dirname(path3.resolve(file));
2981
+ for (; ; ) {
2982
+ if (fs3.existsSync(path3.join(dir, "src", "pages"))) return dir;
2983
+ const parent = path3.dirname(dir);
2984
+ if (parent === dir) throw new Error(`rosetack/test: ${file} is not inside a project (no src/pages found above it)`);
2985
+ dir = parent;
2986
+ }
2987
+ }
2988
+ function routeOf(file, root) {
2989
+ const rel = path3.relative(path3.join(root, "src", "pages"), path3.resolve(file)).replace(/\\/g, "/").replace(/\.rose$/, "");
2990
+ if (rel === "index") return "/";
2991
+ const segs = rel.split("/").map((s) => s.startsWith("[") && s.endsWith("]") ? `:${s.slice(1, -1)}` : s);
2992
+ return "/" + segs.join("/");
2993
+ }
2994
+ function copyTree(from, to) {
2995
+ fs3.mkdirSync(to, { recursive: true });
2996
+ for (const e of fs3.readdirSync(from, { withFileTypes: true })) {
2997
+ const src = path3.join(from, e.name);
2998
+ const dst = path3.join(to, e.name);
2999
+ if (e.isDirectory()) copyTree(src, dst);
3000
+ else fs3.copyFileSync(src, dst);
3001
+ }
3002
+ }
3003
+ function propAttrs(props) {
3004
+ return Object.entries(props).map(([k, v]) => `${k}={${JSON.stringify(v) ?? "undefined"}}`).join(" ");
3005
+ }
3006
+ async function test(file, opts = {}) {
3007
+ const target = path3.resolve(file);
3008
+ if (!fs3.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
3009
+ const root = projectRootOf(target);
3010
+ const rel = path3.relative(root, target).replace(/\\/g, "/");
3011
+ const isComponent = rel.startsWith("src/components/");
3012
+ const dir = opts.dir ?? fs3.mkdtempSync(path3.join(os.tmpdir(), "rosetack-test-"));
3013
+ for (const item of ["src", "public"]) {
3014
+ const from = path3.join(root, item);
3015
+ if (fs3.existsSync(from)) copyTree(from, path3.join(dir, item));
3016
+ }
3017
+ for (const item of ["rosetack.config.js"]) {
3018
+ const from = path3.join(root, item);
3019
+ if (fs3.existsSync(from)) fs3.copyFileSync(from, path3.join(dir, item));
3020
+ }
3021
+ let route;
3022
+ if (isComponent) {
3023
+ const specifier = path3.relative(path3.join(dir, "src", "pages"), path3.join(dir, rel)).replace(/\\/g, "/");
3024
+ const attrs = propAttrs(opts.props ?? {});
3025
+ const page = `<script>
3026
+ import Target from '${specifier}';
3027
+ </script>
3028
+
3029
+ <template>
3030
+ <Target ${attrs} />
3031
+ </template>
3032
+ `;
3033
+ fs3.writeFileSync(path3.join(dir, "src", "pages", "__rosetack_test.rose"), page);
3034
+ route = "/__rosetack_test";
3035
+ } else {
3036
+ route = opts.route ?? routeOf(target, root);
3037
+ }
3038
+ const outDir = path3.join(dir, "dist");
3039
+ await buildProject(dir, outDir);
3040
+ const serverUrl = pathToFileURL2(path3.join(outDir, "server.js")).href;
3041
+ const clientUrl = pathToFileURL2(path3.join(outDir, "client.js")).href;
3042
+ const mod = await import(serverUrl);
3043
+ const clientSource = fs3.readFileSync(path3.join(outDir, "client.js"), "utf-8");
3044
+ let styles = "";
3045
+ try {
3046
+ styles = fs3.readFileSync(path3.join(outDir, "styles.css"), "utf-8");
3047
+ } catch {
3048
+ }
3049
+ if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
3050
+ if (!opts.dir && !opts.keep) {
3051
+ process.once("exit", () => {
3052
+ try {
3053
+ fs3.rmSync(dir, { recursive: true, force: true });
3054
+ } catch {
3055
+ }
3056
+ });
3057
+ }
3058
+ const result = (page, redirect) => ({
3059
+ status: page.status ?? 200,
3060
+ html: page.html,
3061
+ state: page.state ? JSON.parse(page.state) : {},
3062
+ head: page.head ?? [],
3063
+ csr: page.csr,
3064
+ lang: page.lang ?? "en",
3065
+ dir: page.dir ?? "",
3066
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? ""),
3067
+ redirect
3068
+ });
3069
+ const toRequest = (pathname, req = {}, body) => {
3070
+ const headers = new Headers(req.headers ?? {});
3071
+ for (const [k, v] of Object.entries(req.cookies ?? {})) headers.append("cookie", `${k}=${v}`);
3072
+ return new Request(`http://localhost${pathname}`, { method: body ? "POST" : "GET", headers, body });
3073
+ };
3074
+ const request = async (pathname, req, body) => {
3075
+ if (mod.middleware) {
3076
+ const mw = await mod.runMiddleware(toRequest(pathname, req, body), body);
3077
+ if (mw) return { status: mw.status, html: await mw.text(), state: {}, head: [], lang: "en", dir: "", document: await mw.text(), redirect: mw.headers.get("location") ?? void 0 };
3078
+ }
3079
+ const page = await mod.renderPage(pathname, body);
3080
+ return result(page);
3081
+ };
3082
+ let requests = 0;
3083
+ let currentRoute = route;
3084
+ const mount = async (req = {}) => {
3085
+ const win = opts.dom?.window ?? opts.dom ?? globalThis;
3086
+ if (!win?.document || !win?.DOMParser) {
3087
+ throw new Error('rosetack/test: mount() needs a DOM. Pass one - test("src/components/Counter.rose", { dom: new JSDOM() }) - or run under a jsdom environment.');
3088
+ }
3089
+ const page = await request(route, req);
3090
+ const doc = win.document;
3091
+ const app = doc.getElementById("app") ?? doc.body;
3092
+ let stateEl = doc.getElementById("__rosetack_state");
3093
+ if (!stateEl) {
3094
+ stateEl = doc.createElement("script");
3095
+ stateEl.id = "__rosetack_state";
3096
+ doc.body.appendChild(stateEl);
3097
+ }
3098
+ stateEl.textContent = page.state;
3099
+ app.innerHTML = page.html;
3100
+ const saved = /* @__PURE__ */ new Map();
3101
+ for (const key of GRAFTED) {
3102
+ saved.set(key, globalThis[key]);
3103
+ globalThis[key] = win[key] ?? globalThis[key];
3104
+ }
3105
+ globalThis.location = { pathname: currentRoute, href: `http://localhost${currentRoute}` };
3106
+ globalThis.fetch = async (url, init) => {
3107
+ const pathname = String(url).startsWith("http") ? new URL(String(url)).pathname : String(url);
3108
+ if (pathname.startsWith("/locales/") && pathname.endsWith(".json")) {
3109
+ const file2 = path3.join(outDir, pathname.slice(1));
3110
+ if (!fs3.existsSync(file2)) return { ok: false, json: async () => ({}) };
3111
+ return { ok: true, json: async () => JSON.parse(fs3.readFileSync(file2, "utf-8")) };
3112
+ }
3113
+ requests++;
3114
+ const next = await request(pathname, req, init?.body);
3115
+ return { ok: next.status < 400, status: next.status, text: async () => next.document };
3116
+ };
3117
+ const client = await import(clientUrl);
3118
+ await client.start(app, route, true);
3119
+ const one = (sel) => sel ? doc.querySelector(sel) : app;
3120
+ const handle = {
3121
+ route,
3122
+ document: doc,
3123
+ window: win,
3124
+ text: (sel) => one(sel)?.textContent ?? "",
3125
+ html: (sel) => one(sel)?.outerHTML ?? null,
3126
+ exists: (sel) => !!doc.querySelector(sel),
3127
+ click: async (sel) => {
3128
+ const el = doc.querySelector(sel);
3129
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
3130
+ el.dispatchEvent(new win.MouseEvent("click", { bubbles: true, cancelable: true }));
3131
+ await new Promise((r) => setTimeout(r, 0));
3132
+ },
3133
+ fill: (sel, value) => {
3134
+ const el = doc.querySelector(sel);
3135
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
3136
+ el.value = value;
3137
+ },
3138
+ submit: async (formSel = "form", fields) => {
3139
+ const form = doc.querySelector(formSel);
3140
+ if (!form) throw new Error(`rosetack/test: no form matches ${formSel}`);
3141
+ const body = new win.FormData(form);
3142
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
3143
+ await client.postForm(body);
3144
+ },
3145
+ action: async (name, fields) => {
3146
+ const body = new win.FormData();
3147
+ body.append("__action", name);
3148
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
3149
+ await client.postForm(body);
3150
+ },
3151
+ navigate: async (pathname) => {
3152
+ currentRoute = pathname;
3153
+ globalThis.location = { pathname, href: `http://localhost${pathname}` };
3154
+ await client.start(app, pathname, false);
3155
+ },
3156
+ state: () => {
3157
+ const el = doc.getElementById("__rosetack_state");
3158
+ return el?.textContent ? JSON.parse(el.textContent) : {};
3159
+ },
3160
+ requestCount: () => requests
3161
+ };
3162
+ handle.restore = () => {
3163
+ for (const [k, v] of saved) globalThis[k] = v;
3164
+ };
3165
+ return handle;
3166
+ };
3167
+ return {
3168
+ route,
3169
+ dir,
3170
+ get: async (pathname = route, req) => request(pathname, req ?? {}),
3171
+ post: async (fields, req = {}) => {
3172
+ const pathname = req.route ?? route;
3173
+ const body = new FormData();
3174
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
3175
+ return request(pathname, req, body);
3176
+ },
3177
+ api: async (method, pathname, req = {}) => {
3178
+ if (mod.middleware) {
3179
+ const mw = await mod.runMiddleware(toRequest(pathname, req));
3180
+ if (mw) return { status: mw.status, body: await mw.text(), headers: { location: mw.headers.get("location") ?? "" } };
3181
+ }
3182
+ const res = await mod.handleApi(method, pathname, toRequest(pathname, req));
3183
+ const text = await res.text();
3184
+ let body = text;
3185
+ try {
3186
+ body = JSON.parse(text);
3187
+ } catch {
3188
+ }
3189
+ const headers = {};
3190
+ res.headers.forEach((v, k) => {
3191
+ headers[k] = v;
3192
+ });
3193
+ return { status: res.status, body, headers };
3194
+ },
3195
+ mount
3196
+ };
3197
+ }
3198
+ var test_default = test;
3199
+ export {
3200
+ test_default as default,
3201
+ test
3202
+ };