rosetack 0.1.2 → 0.1.4

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 (57) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/netlify/functions/rosetack.ts +38 -0
  4. package/deploy/netlify.toml +17 -0
  5. package/devtools/devtools.html +7 -0
  6. package/devtools/devtools.js +1 -0
  7. package/devtools/manifest.json +8 -0
  8. package/devtools/panel.html +28 -0
  9. package/devtools/panel.js +54 -0
  10. package/dist-cli/compiler.mjs +2194 -561
  11. package/dist-cli/edge.mjs +159 -48
  12. package/dist-cli/rosetack.mjs +2899 -739
  13. package/dist-cli/runtime.mjs +305 -43
  14. package/dist-cli/test.mjs +2332 -630
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/content.ts +186 -0
  18. package/src/cli/edge.ts +78 -62
  19. package/src/cli/image-size.ts +83 -0
  20. package/src/cli/index.ts +391 -334
  21. package/src/cli/prod-server.ts +324 -0
  22. package/src/cli/prompt.ts +51 -20
  23. package/src/cli/shell.ts +105 -74
  24. package/src/cli/test.ts +9 -70
  25. package/src/compiler/index.ts +2107 -913
  26. package/src/runtime/index.ts +367 -168
  27. package/src/types/rosetack.d.ts +16 -66
  28. package/templates/admin/package.json +14 -0
  29. package/templates/admin/rosetack.config.js +1 -0
  30. package/templates/admin/src/pages/_middleware.rose +33 -0
  31. package/templates/admin/src/pages/api/items.rose +37 -0
  32. package/templates/admin/src/pages/api/login.rose +25 -0
  33. package/templates/admin/src/pages/index.rose +79 -0
  34. package/templates/api/package.json +14 -0
  35. package/templates/api/rosetack.config.js +1 -0
  36. package/templates/api/src/pages/api/health.rose +7 -0
  37. package/templates/api/src/pages/api/items.rose +46 -0
  38. package/templates/api/src/pages/api/login.rose +24 -0
  39. package/templates/api/src/pages/index.rose +25 -0
  40. package/templates/blog/package.json +14 -0
  41. package/templates/blog/rosetack.config.js +1 -0
  42. package/templates/blog/src/pages/404.rose +2 -0
  43. package/templates/blog/src/pages/_layout.rose +42 -0
  44. package/templates/blog/src/pages/_middleware.rose +74 -0
  45. package/templates/blog/src/pages/admin.rose +85 -0
  46. package/templates/blog/src/pages/api/login.rose +46 -0
  47. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  48. package/templates/blog/src/pages/api/posts.rose +72 -0
  49. package/templates/blog/src/pages/index.rose +31 -0
  50. package/templates/blog/src/pages/post/[id].rose +36 -0
  51. package/templates/site/package.json +14 -0
  52. package/templates/site/rosetack.config.js +1 -0
  53. package/templates/site/src/pages/404.rose +2 -0
  54. package/templates/site/src/pages/_layout.rose +40 -0
  55. package/templates/site/src/pages/about.rose +6 -0
  56. package/templates/site/src/pages/index.rose +13 -0
  57. package/templates/site/src/pages/pricing.rose +8 -0
package/dist-cli/test.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  // src/cli/test.ts
2
- import * as fs3 from "fs";
2
+ import * as fs5 from "fs";
3
3
  import * as os from "os";
4
- import * as path3 from "path";
4
+ import * as path4 from "path";
5
5
  import { pathToFileURL as pathToFileURL2 } from "url";
6
6
 
7
7
  // src/compiler/index.ts
8
- import * as fs from "fs";
9
- import * as path from "path";
8
+ import * as fs3 from "fs";
9
+ import * as path2 from "path";
10
10
  import { pathToFileURL, fileURLToPath } from "url";
11
11
  import * as esbuild from "esbuild";
12
12
 
@@ -45,16 +45,209 @@ function lineAt(src, match) {
45
45
  return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
46
46
  }
47
47
 
48
+ // src/cli/image-size.ts
49
+ import fs from "node:fs";
50
+ function readImageSize(filePath) {
51
+ try {
52
+ const fd = fs.openSync(filePath, "r");
53
+ const buf = Buffer.alloc(64);
54
+ const read = fs.readSync(fd, buf, 0, 64, 0);
55
+ fs.closeSync(fd);
56
+ if (read < 24) return null;
57
+ if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
58
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
59
+ }
60
+ if (buf.slice(0, 3).toString("latin1") === "GIF") {
61
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
62
+ }
63
+ if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP") {
64
+ return parseWebP(buf);
65
+ }
66
+ if (buf[0] === 255 && buf[1] === 216) {
67
+ return parseJpeg(filePath);
68
+ }
69
+ return null;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+ function parseWebP(buf) {
75
+ const format = buf.slice(12, 16).toString("latin1");
76
+ if (format === "VP8 ") {
77
+ return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
78
+ }
79
+ if (format === "VP8L") {
80
+ const b = buf.readUInt32LE(21);
81
+ return { width: (b & 16383) + 1, height: (b >> 14 & 16383) + 1 };
82
+ }
83
+ if (format === "VP8X") {
84
+ const w = buf.readUIntLE(24, 3) + 1;
85
+ const h = buf.readUIntLE(27, 3) + 1;
86
+ return { width: w, height: h };
87
+ }
88
+ return null;
89
+ }
90
+ function parseJpeg(filePath) {
91
+ const fd = fs.openSync(filePath, "r");
92
+ try {
93
+ const buf = Buffer.alloc(4);
94
+ let pos = 2;
95
+ for (let guard = 0; guard < 64; guard++) {
96
+ if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
97
+ if (buf[0] !== 255) {
98
+ pos += 1;
99
+ continue;
100
+ }
101
+ const marker = buf[1];
102
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
103
+ pos += 2;
104
+ continue;
105
+ }
106
+ const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
107
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
108
+ const seg = Buffer.alloc(8);
109
+ fs.readSync(fd, seg, 0, 8, pos + 4);
110
+ return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
111
+ }
112
+ pos += 2 + len;
113
+ }
114
+ return null;
115
+ } finally {
116
+ fs.closeSync(fd);
117
+ }
118
+ }
119
+
120
+ // src/cli/content.ts
121
+ import fs2 from "node:fs";
122
+ import path from "node:path";
123
+ function parseFrontmatter(raw) {
124
+ if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
125
+ const end = raw.indexOf("\n---", 3);
126
+ if (end < 0) return { frontmatter: {}, body: raw };
127
+ const head = raw.slice(4, end);
128
+ const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
129
+ const frontmatter = {};
130
+ for (const line of head.split("\n")) {
131
+ const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
132
+ if (!m) continue;
133
+ const [, k, v] = m;
134
+ const arr = /^\[(.+)\]$/.exec(v.trim());
135
+ frontmatter[k] = arr ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")) : v.trim().replace(/^["']|["']$/g, "");
136
+ }
137
+ return { frontmatter, body };
138
+ }
139
+ function interpolate(md, vars) {
140
+ return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
141
+ const v = k.split(".").reduce((o, p) => o == null ? o : o[p], vars);
142
+ return v === void 0 || v === null ? "" : String(v);
143
+ });
144
+ }
145
+ function renderMarkdown(md, vars) {
146
+ if (vars) md = interpolate(md, vars);
147
+ const blocks = [];
148
+ let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
149
+ blocks.push(
150
+ `<pre data-lang="${lang}"><code>${code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</code></pre>`
151
+ );
152
+ return `\0CODE${blocks.length - 1}\0`;
153
+ });
154
+ const inline = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
155
+ /\[([^\]]+)\]\(([^)]+)\)/g,
156
+ '<a href="$2" rel="noopener">$1</a>'
157
+ );
158
+ const out = [];
159
+ let listOpen = null;
160
+ const closeList = () => {
161
+ if (listOpen) {
162
+ out.push(`</${listOpen}>`);
163
+ listOpen = null;
164
+ }
165
+ };
166
+ for (const line of src.split("\n")) {
167
+ const h = /^(#{1,4})\s+(.*)$/.exec(line);
168
+ const li = /^\s*[-*]\s+(.*)$/.exec(line);
169
+ const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
170
+ if (h) {
171
+ closeList();
172
+ out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
173
+ } else if (li) {
174
+ if (listOpen !== "ul") {
175
+ closeList();
176
+ out.push("<ul>");
177
+ listOpen = "ul";
178
+ }
179
+ out.push(`<li>${inline(li[1])}</li>`);
180
+ } else if (oli) {
181
+ if (listOpen !== "ol") {
182
+ closeList();
183
+ out.push("<ol>");
184
+ listOpen = "ol";
185
+ }
186
+ out.push(`<li>${inline(oli[1])}</li>`);
187
+ } else if (line.trim() === "") {
188
+ closeList();
189
+ } else if (line.startsWith("\0CODE")) {
190
+ closeList();
191
+ out.push(line);
192
+ } else {
193
+ closeList();
194
+ out.push(`<p>${inline(line)}</p>`);
195
+ }
196
+ }
197
+ closeList();
198
+ return out.join("\n").replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
199
+ }
200
+ function scanContentDir(contentDir) {
201
+ const collections = {};
202
+ if (!fs2.existsSync(contentDir)) return collections;
203
+ for (const coll of fs2.readdirSync(contentDir, { withFileTypes: true })) {
204
+ if (!coll.isDirectory()) continue;
205
+ const entries = [];
206
+ const dir = path.join(contentDir, coll.name);
207
+ for (const f of fs2.readdirSync(dir)) {
208
+ if (!f.endsWith(".md")) continue;
209
+ const raw = fs2.readFileSync(path.join(dir, f), "utf-8");
210
+ const { frontmatter, body } = parseFrontmatter(raw);
211
+ if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
212
+ const slug = f.replace(/\.md$/, "");
213
+ const html = renderMarkdown(body);
214
+ const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
215
+ const headings = [];
216
+ const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl, txt) => {
217
+ const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
218
+ headings.push({ level: Number(lvl), text: txt, id });
219
+ return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
220
+ });
221
+ entries.push({
222
+ slug,
223
+ frontmatter,
224
+ body,
225
+ html: tocHtml,
226
+ readingTime: Math.max(1, Math.round(words / 200)),
227
+ wordCount: words,
228
+ toc: headings,
229
+ excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160)
230
+ });
231
+ }
232
+ entries.sort(
233
+ (a, b) => String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? ""))
234
+ );
235
+ collections[coll.name] = entries;
236
+ }
237
+ return collections;
238
+ }
239
+ globalThis.__rosetackContentMk = renderMarkdown;
240
+
48
241
  // src/compiler/index.ts
49
242
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
50
243
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
51
244
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
52
245
  var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
53
- var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
246
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
54
247
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
55
248
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
56
- var SLOT_RE = /<slot\s*\/?>/g;
57
- var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
249
+ var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
250
+ var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
58
251
  function encodeSlotCall(attrs) {
59
252
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
60
253
  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} />' });
@@ -218,21 +411,50 @@ function skipTemplate(src, i) {
218
411
  }
219
412
  return j;
220
413
  }
414
+ function skipLiteral(src, i) {
415
+ const q = src[i];
416
+ if (q === '"' || q === "'") return skipQuoted(src, i);
417
+ if (q === "`") return skipTemplate(src, i);
418
+ if (q !== "/") return null;
419
+ if (src[i + 1] === "/" || src[i + 1] === "*") return null;
420
+ let b = i - 1;
421
+ while (b >= 0 && /\s/.test(src[b])) b--;
422
+ if (b >= 0) {
423
+ if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
424
+ const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
425
+ if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
426
+ }
427
+ }
428
+ let j = i + 1;
429
+ let inClass = false;
430
+ while (j < src.length) {
431
+ const c = src[j];
432
+ if (c === "\\") {
433
+ j += 2;
434
+ continue;
435
+ }
436
+ if (c === "\n") return null;
437
+ if (inClass) {
438
+ if (c === "]") inClass = false;
439
+ } else if (c === "[") inClass = true;
440
+ else if (c === "/") {
441
+ j++;
442
+ break;
443
+ }
444
+ j++;
445
+ }
446
+ if (j > src.length) return null;
447
+ while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
448
+ return j;
449
+ }
221
450
  function stripComments(src) {
222
451
  let out = "";
223
452
  let i = 0;
224
453
  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;
454
+ const lit = skipLiteral(src, i);
455
+ if (lit !== null) {
456
+ out += src.slice(i, lit);
457
+ i = lit;
236
458
  continue;
237
459
  }
238
460
  if (src.startsWith("//", i)) {
@@ -255,9 +477,170 @@ function stripComments(src) {
255
477
  }
256
478
  return out;
257
479
  }
480
+ function stripGuardedBranches(src) {
481
+ const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
482
+ const ws = (i2) => {
483
+ while (i2 < src.length && /\s/.test(src[i2])) i2++;
484
+ return i2;
485
+ };
486
+ const ternaryColon = (q) => {
487
+ let depth = 0;
488
+ let i2 = q + 1;
489
+ while (i2 < src.length) {
490
+ const c = src[i2];
491
+ const lit = skipLiteral(src, i2);
492
+ if (lit !== null) {
493
+ i2 = lit;
494
+ continue;
495
+ }
496
+ if (c === "(" || c === "[" || c === "{") depth++;
497
+ else if (c === ")" || c === "]" || c === "}") {
498
+ depth--;
499
+ if (depth < 0) return -1;
500
+ } else if (depth === 0 && c === ":") return i2;
501
+ else if (depth === 0 && c === "?") {
502
+ const inner = ternaryColon(i2);
503
+ if (inner < 0) return -1;
504
+ i2 = inner + 1;
505
+ continue;
506
+ }
507
+ i2++;
508
+ }
509
+ return -1;
510
+ };
511
+ const exprEnd = (i2) => {
512
+ let depth = 0;
513
+ while (i2 < src.length) {
514
+ const c = src[i2];
515
+ const lit = skipLiteral(src, i2);
516
+ if (lit !== null) {
517
+ i2 = lit;
518
+ continue;
519
+ }
520
+ if (c === "(" || c === "[" || c === "{") depth++;
521
+ else if (c === ")" || c === "]" || c === "}") {
522
+ if (depth === 0) return i2;
523
+ depth--;
524
+ } else if (depth === 0 && (c === "," || c === ";")) return i2;
525
+ else if (depth === 0 && c === "?") {
526
+ const inner = ternaryColon(i2);
527
+ if (inner < 0) return src.length;
528
+ i2 = inner + 1;
529
+ continue;
530
+ }
531
+ i2++;
532
+ }
533
+ return src.length;
534
+ };
535
+ const braceEnd = (b) => {
536
+ let depth = 0;
537
+ let i2 = b;
538
+ while (i2 < src.length) {
539
+ const c = src[i2];
540
+ const lit = skipLiteral(src, i2);
541
+ if (lit !== null) {
542
+ i2 = lit;
543
+ continue;
544
+ }
545
+ if (c === "{") depth++;
546
+ else if (c === "}") {
547
+ depth--;
548
+ if (depth === 0) return i2;
549
+ }
550
+ i2++;
551
+ }
552
+ return src.length;
553
+ };
554
+ const stmtEnd = (i2) => {
555
+ let depth = 0;
556
+ while (i2 < src.length) {
557
+ const c = src[i2];
558
+ const lit = skipLiteral(src, i2);
559
+ if (lit !== null) {
560
+ i2 = lit;
561
+ continue;
562
+ }
563
+ if (c === "(" || c === "[" || c === "{") depth++;
564
+ else if (c === ")" || c === "]" || c === "}") {
565
+ if (depth === 0) return i2;
566
+ depth--;
567
+ } else if (depth === 0 && (c === ";" || c === "\n")) return i2;
568
+ i2++;
569
+ }
570
+ return src.length;
571
+ };
572
+ const isIfGuard = (src2, at) => {
573
+ let b = at - 1;
574
+ while (b >= 0 && /\s/.test(src2[b])) b--;
575
+ if (b < 0 || src2[b] !== "(") return false;
576
+ b--;
577
+ while (b >= 0 && /\s/.test(src2[b])) b--;
578
+ return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
579
+ };
580
+ const blanks = [];
581
+ let i = 0;
582
+ while (i < src.length) {
583
+ const lit = skipLiteral(src, i);
584
+ if (lit !== null) {
585
+ i = lit;
586
+ continue;
587
+ }
588
+ GUARD.lastIndex = i;
589
+ const m = GUARD.exec(src);
590
+ if (!m) {
591
+ i++;
592
+ continue;
593
+ }
594
+ const browserAfter = m[1] === "!==";
595
+ const j = ws(i + m[0].length);
596
+ const two = src.slice(j, j + 2);
597
+ if (two === "&&" && browserAfter) {
598
+ blanks.push([j + 2, exprEnd(j + 2)]);
599
+ } else if (two === "||" && !browserAfter) {
600
+ blanks.push([j + 2, exprEnd(j + 2)]);
601
+ } else if (src[j] === "?") {
602
+ const colon = ternaryColon(j);
603
+ if (colon < 0) {
604
+ if (browserAfter) blanks.push([j + 1, src.length]);
605
+ } else if (browserAfter) {
606
+ blanks.push([j + 1, colon]);
607
+ } else {
608
+ blanks.push([colon + 1, exprEnd(colon + 1)]);
609
+ }
610
+ } else if (src[j] === ")" && isIfGuard(src, i)) {
611
+ let bodyEnd;
612
+ const k = ws(j + 1);
613
+ if (src[k] === "{") {
614
+ bodyEnd = braceEnd(k);
615
+ if (browserAfter) blanks.push([k + 1, bodyEnd]);
616
+ } else {
617
+ bodyEnd = stmtEnd(k);
618
+ if (browserAfter) blanks.push([k, bodyEnd]);
619
+ }
620
+ const after = ws(bodyEnd + 1);
621
+ if (src.startsWith("else", after)) {
622
+ const e = ws(after + 4);
623
+ if (src[e] === "{") {
624
+ const close = braceEnd(e);
625
+ if (!browserAfter) blanks.push([e + 1, close]);
626
+ } else {
627
+ const stop = stmtEnd(e);
628
+ if (!browserAfter) blanks.push([e, stop]);
629
+ }
630
+ }
631
+ }
632
+ i = j;
633
+ }
634
+ if (blanks.length === 0) return src;
635
+ const out = [...src];
636
+ for (const [a, b] of blanks) {
637
+ for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
638
+ }
639
+ return out.join("");
640
+ }
258
641
  async function loadConfig(root) {
259
- const file = path.join(root, "rosetack.config.js");
260
- if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
642
+ const file = path2.join(root, "rosetack.config.js");
643
+ if (!fs3.existsSync(file)) return { plugins: [], i18n: {} };
261
644
  const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
262
645
  return {
263
646
  plugins: mod.default ?? [],
@@ -267,12 +650,12 @@ async function loadConfig(root) {
267
650
  function resolveRoseImports(script, fromFile, registry) {
268
651
  const imports = [];
269
652
  const resolve3 = (spec, at) => {
270
- const abs = path.resolve(path.dirname(fromFile), spec);
653
+ const abs = path2.resolve(path2.dirname(fromFile), spec);
271
654
  const hit = registry.get(abs);
272
655
  if (!hit) {
273
656
  throw new RoseError(
274
657
  "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.`,
658
+ `${path2.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
659
  {
277
660
  file: fromFile,
278
661
  line: lineOf(script, at),
@@ -307,16 +690,45 @@ function nodeOnlyImports(importStmts) {
307
690
  }
308
691
  return out;
309
692
  }
310
- function wireEventBindings(template, actionNames) {
693
+ function wireEventBindings(template, actionNames, filePath = "<template>") {
311
694
  const bindings = [];
312
695
  let out = "";
313
696
  let rest = template;
697
+ const TARGET_MODS = { window: "w", document: "d" };
698
+ const MOD_PRE = {
699
+ preventDefault: () => "e.preventDefault()",
700
+ stopPropagation: () => "e.stopPropagation()",
701
+ self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`
702
+ };
703
+ const MOD_POST = {
704
+ once: (p) => `const __o = e.target && e.target.closest ? e.target.closest('[data-${p}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${p}-' + e.type);`
705
+ };
706
+ const KNOWN_MODS = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
314
707
  for (; ; ) {
315
- const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
708
+ const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
316
709
  if (!m) {
317
710
  out += rest;
318
711
  break;
319
712
  }
713
+ const mods = m[2] ? m[2].slice(1).split("|") : [];
714
+ const targets = mods.filter((mod) => TARGET_MODS[mod]);
715
+ if (targets.length > 1) {
716
+ throw new RoseError(
717
+ "E-TEMPLATE",
718
+ `${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
719
+ { hint: "a handler binds to one target - the element (default), |window or |document" }
720
+ );
721
+ }
722
+ const prefix = targets.length ? "on" + TARGET_MODS[targets[0]] : "on";
723
+ for (const mod of mods) {
724
+ if (!KNOWN_MODS.includes(mod)) {
725
+ throw new RoseError(
726
+ "E-TEMPLATE",
727
+ `${filePath}: unknown event modifier |${mod}`,
728
+ { hint: `the supported modifiers are ${KNOWN_MODS.map((k) => "|" + k).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` }
729
+ );
730
+ }
731
+ }
320
732
  out += rest.slice(0, m.index);
321
733
  let i = m.index + m[0].length;
322
734
  let depth = 1;
@@ -338,7 +750,24 @@ function wireEventBindings(template, actionNames) {
338
750
  i++;
339
751
  }
340
752
  const expr = rest.slice(m.index + m[0].length, i).trim();
341
- if (actionNames.has(expr)) {
753
+ const wrap = (body) => {
754
+ if (!mods.length) return body;
755
+ const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
756
+ const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
757
+ return `(e) => {${pre.length ? " " + pre.join("; ") + ";" : ""} (${body})(e);${post.length ? " " + post.join("; ") + ";" : ""} }`;
758
+ };
759
+ if (mods.length && actionNames.has(expr)) {
760
+ throw new RoseError(
761
+ "E-TEMPLATE",
762
+ `${filePath}: event modifiers are not supported on the server action ${expr}`,
763
+ { hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
764
+ );
765
+ }
766
+ if (mods.length) {
767
+ const name = `__h${bindings.length}`;
768
+ out += `data-${prefix}-${m[1]}="${name}"`;
769
+ bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
770
+ } else if (actionNames.has(expr)) {
342
771
  out += `data-on-${m[1]}="$action:${expr}"`;
343
772
  } else if (/^\w+$/.test(expr)) {
344
773
  out += `data-on-${m[1]}="${expr}"`;
@@ -355,12 +784,13 @@ function wireEventBindings(template, actionNames) {
355
784
  function scanSlotDecls(filePath) {
356
785
  let src;
357
786
  try {
358
- src = fs.readFileSync(filePath, "utf-8");
787
+ src = fs3.readFileSync(filePath, "utf-8");
359
788
  } catch {
360
789
  return [];
361
790
  }
362
- const noBlocks = src.replace(STYLE_RE, "");
363
- const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
791
+ const noScript = src.replace(COMPONENT_RE, "");
792
+ const noBlocks = noScript.replace(STYLE_RE, "");
793
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
364
794
  const out = [];
365
795
  for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
366
796
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
@@ -408,7 +838,7 @@ function hoistImports(script) {
408
838
  return { imports: imports.join("\n"), rest: rest.join("\n") };
409
839
  }
410
840
  async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
411
- let source = await fs.promises.readFile(filePath, "utf-8");
841
+ let source = await fs3.promises.readFile(filePath, "utf-8");
412
842
  for (const p of plugins) {
413
843
  if (!p.transform) continue;
414
844
  try {
@@ -416,7 +846,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
416
846
  } catch (err) {
417
847
  throw new RoseError(
418
848
  "E-PLUGIN",
419
- `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
849
+ `plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
420
850
  { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
421
851
  );
422
852
  }
@@ -428,6 +858,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
428
858
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
429
859
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
430
860
  const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
861
+ const ownRuntimeImports = new Set(
862
+ [...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
863
+ );
864
+ const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
865
+ const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
866
+ ` : "";
431
867
  return {
432
868
  ssr: "",
433
869
  client: "",
@@ -436,24 +872,24 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
436
872
  guardName: null,
437
873
  style: "",
438
874
  hasParams: false,
439
- api: `import { getContext, $query } from './runtime.js';
440
- ${rewriteRoseImports(`${hoisted.imports}
875
+ api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
441
876
  ${hoisted.rest}`, "ssr").trim()}`,
442
877
  apiMethods,
443
878
  hasPrerender,
444
879
  usesContext: usesContext2
445
880
  };
446
881
  }
447
- const sourceNoHead = source.replace(HEAD_RE, "");
882
+ const sourceNoScript = source.replace(COMPONENT_RE, "");
883
+ const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
448
884
  const styleMatch = sourceNoHead.match(STYLE_RE);
449
885
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
450
886
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
451
- const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
887
+ const scriptMatch = source.match(COMPONENT_RE);
452
888
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
453
889
  const rawScript = roseResolved.script;
454
890
  const roseImports = roseResolved.imports;
455
891
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
456
- if (path.basename(filePath) !== "_middleware.rose") {
892
+ if (path2.basename(filePath) !== "_middleware.rose") {
457
893
  for (const spec of nodeOnlyImports(importStmts)) {
458
894
  const at = importStmts.indexOf(spec);
459
895
  throw new RoseError(
@@ -479,6 +915,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
479
915
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
480
916
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
481
917
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
918
+ const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
919
+ const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : void 0;
482
920
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
483
921
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
484
922
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
@@ -508,8 +946,11 @@ ${hoisted.rest}`, "ssr").trim()}`,
508
946
  }
509
947
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
510
948
  const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
949
+ const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
950
+ const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
511
951
  const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
512
952
  const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
953
+ const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
513
954
  if (csr === false) {
514
955
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
515
956
  if (dead) {
@@ -580,30 +1021,32 @@ ${hoisted.rest}`, "ssr").trim()}`,
580
1021
  }
581
1022
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
582
1023
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
1024
+ if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
583
1025
  const needsClient = clientReasons.length > 0;
584
1026
  const jsWarnings = [];
585
1027
  if (!needsClient) {
586
1028
  const codeOnly = stripComments(source);
587
1029
  const scriptCodeOnly = stripComments(rawScript);
1030
+ const scriptScannable = stripGuardedBranches(scriptCodeOnly);
588
1031
  if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
589
1032
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
590
1033
  }
591
1034
  if (/javascript:/i.test(codeOnly)) {
592
1035
  jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
593
1036
  }
594
- if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
1037
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
595
1038
  jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
596
1039
  }
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)) {
1040
+ 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(scriptScannable)) {
598
1041
  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
1042
  }
600
1043
  }
601
1044
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
602
- const headContent = source.match(HEAD_RE)?.[1] ?? "";
1045
+ const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
603
1046
  const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
604
1047
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
605
1048
  const decls = extractDecls(script);
606
- const stateDecls = decls.filter((d) => d.kind === "state");
1049
+ const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
607
1050
  const setterNames = /* @__PURE__ */ new Map();
608
1051
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
609
1052
  const declCode = (d) => {
@@ -613,6 +1056,17 @@ ${hoisted.rest}`, "ssr").trim()}`,
613
1056
  }
614
1057
  const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
615
1058
  const fn = isFn ? d.expr : `() => (${d.expr})`;
1059
+ if (d.kind === "persist") {
1060
+ return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1061
+ }
1062
+ if (d.kind === "kv") {
1063
+ const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1064
+ const fnExpr = mTtl ? mTtl[1] : d.expr;
1065
+ const ttl = mTtl ? mTtl[2] : "300";
1066
+ return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1067
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1068
+ if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}));`;
1069
+ }
616
1070
  return `const __had_${d.name} = hasState(${JSON.stringify(key)});
617
1071
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
618
1072
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
@@ -637,15 +1091,120 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
637
1091
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
638
1092
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
639
1093
  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__}");
1094
+ const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
1095
+ const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
643
1096
  const stateKeys = decls.map((d) => d.name);
1097
+ const bindBindings = [];
1098
+ let bindCounter = 0;
1099
+ const bindExpanded = wired.template.replace(
1100
+ /\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1101
+ (whole, kind, name) => {
1102
+ if (!stateKeys.includes(name)) {
1103
+ throw new Error(
1104
+ `${filePath}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1105
+ );
1106
+ }
1107
+ if (kind === "this") return ` data-bind-this="${name}"`;
1108
+ const setter = setterNames.get(name);
1109
+ const evt = kind === "checked" ? "change" : "input";
1110
+ const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1111
+ bindBindings.push({
1112
+ event: evt,
1113
+ fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`
1114
+ });
1115
+ const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
1116
+ return ` ${kind}={${name}()}${evtAttr}`;
1117
+ }
1118
+ );
644
1119
  const comps = new Map(roseImports.map((r) => {
645
- const abs = path.resolve(path.dirname(filePath), r.specifier);
1120
+ const abs = path2.resolve(path2.dirname(filePath), r.specifier);
646
1121
  const hit = registry.get(abs);
647
1122
  return [r.name, { index: hit.index, slots: hit.slots }];
648
1123
  }));
1124
+ const groupBindings = [];
1125
+ let groupCounter = 0;
1126
+ const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1127
+ const groupExpanded = (() => {
1128
+ if (!bindExpanded.includes("bind:group")) return bindExpanded;
1129
+ let out = "";
1130
+ let pos2 = 0;
1131
+ let m;
1132
+ TAG_SCAN_RE.lastIndex = 0;
1133
+ while (m = TAG_SCAN_RE.exec(bindExpanded)) {
1134
+ const [whole, tag, attrs, selfClose] = m;
1135
+ const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
1136
+ if (!gm) continue;
1137
+ const name = gm[1];
1138
+ if (!stateKeys.includes(name)) {
1139
+ throw new RoseError(
1140
+ "E-TEMPLATE",
1141
+ `${filePath}: bind:group={${name}} must name a $state declaration`,
1142
+ { hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
1143
+ );
1144
+ }
1145
+ if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
1146
+ throw new RoseError(
1147
+ "E-TEMPLATE",
1148
+ `${filePath}: bind:group is for radio and checkbox inputs`,
1149
+ { hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' }
1150
+ );
1151
+ }
1152
+ const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
1153
+ const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
1154
+ if (!vm || /\{/.test(vm[0])) {
1155
+ throw new RoseError(
1156
+ "E-TEMPLATE",
1157
+ `${filePath}: a bind:group input needs a static value attribute`,
1158
+ { hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
1159
+ );
1160
+ }
1161
+ if (/\schecked\s*=/.test(attrs)) {
1162
+ throw new RoseError(
1163
+ "E-TEMPLATE",
1164
+ `${filePath}: a bind:group input cannot also carry checked=`,
1165
+ { hint: "the group state alone decides which inputs are checked" }
1166
+ );
1167
+ }
1168
+ const setter = setterNames.get(name);
1169
+ const hname = `__rvbg_${scopeKey.replace(/\W/g, "_")}_${groupCounter++}`;
1170
+ const groupValue = JSON.stringify(vm[1] ?? vm[2]);
1171
+ const checkedExpr = isArrayGroup ? `${name}().includes(${groupValue})` : `${name}() === ${groupValue}`;
1172
+ const handlerBody = isArrayGroup ? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))` : `${setter}(e.target.value)`;
1173
+ groupBindings.push({ event: "change", fn: `${hname}: (e) => { ${handlerBody}; }` });
1174
+ const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
1175
+ out += bindExpanded.slice(pos2, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1176
+ pos2 = m.index + whole.length;
1177
+ }
1178
+ if (pos2 === 0) return bindExpanded;
1179
+ out += bindExpanded.slice(pos2);
1180
+ return out;
1181
+ })();
1182
+ const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
1183
+ const useExpanded = groupExpanded.replace(
1184
+ /\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
1185
+ (_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
1186
+ );
1187
+ const classExpanded = expandClassDirectives(useExpanded, filePath);
1188
+ const styleExpanded = expandStyleDirectives(classExpanded, filePath);
1189
+ const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
1190
+ const elseExpanded = expandIfElse(keyExpanded);
1191
+ const deferExpanded = expandDeferBlocks(elseExpanded);
1192
+ const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
1193
+ const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
1194
+ const call = `{__slot(${encodeSlotCall(attrs)})}`;
1195
+ if (fallback) {
1196
+ if (/\{[^{}]*\}/.test(fallback)) {
1197
+ throw new RoseError(
1198
+ "E-TEMPLATE",
1199
+ `${filePath}: slot fallback content must be static markup`,
1200
+ { hint: "a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content" }
1201
+ );
1202
+ }
1203
+ return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
1204
+ }
1205
+ return call;
1206
+ }).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
1207
+ assertKnownDirectives(ssrTemplate, filePath);
649
1208
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
650
1209
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
651
1210
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -653,7 +1212,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
653
1212
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
654
1213
  const ssrGuard = guard ? `
655
1214
  ${guard}` : "";
656
- const isMiddleware = path.basename(filePath) === "_middleware.rose";
1215
+ const isMiddleware = path2.basename(filePath) === "_middleware.rose";
657
1216
  const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
658
1217
 
659
1218
  ${importStmts}
@@ -662,8 +1221,8 @@ ${ssrExports}
662
1221
  ${ssrGuard}
663
1222
 
664
1223
  ${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);
1224
+ ` : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1225
+ const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
667
1226
  return {
668
1227
  ssr: rewriteRoseImports(ssr, "ssr"),
669
1228
  client: rewriteRoseImports(client, "client"),
@@ -674,8 +1233,11 @@ ${cleanScript}
674
1233
  hasParams,
675
1234
  usesContext,
676
1235
  revalidate,
1236
+ cache: cacheSeconds,
677
1237
  csr,
1238
+ shell,
678
1239
  buffer,
1240
+ controlSignal,
679
1241
  prefetch,
680
1242
  vitals,
681
1243
  bundle,
@@ -862,6 +1424,20 @@ function extractExports(script) {
862
1424
  out += script.slice(pos);
863
1425
  return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
864
1426
  }
1427
+ var REGEX_PRECEDERS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
1428
+ function isRegexStart(src, i) {
1429
+ let j = i - 1;
1430
+ while (j >= 0 && /\s/.test(src[j])) j--;
1431
+ if (j < 0) return true;
1432
+ const p = src[j];
1433
+ if (REGEX_PRECEDERS.has(p)) return true;
1434
+ if (/[A-Za-z0-9_$]/.test(p)) {
1435
+ const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
1436
+ if (!w) return false;
1437
+ return ["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else"].includes(w[1]);
1438
+ }
1439
+ return false;
1440
+ }
865
1441
  function extractDecls(script) {
866
1442
  const decls = [];
867
1443
  DECL_RE.lastIndex = 0;
@@ -953,6 +1529,35 @@ function braceDepthAt(src, index) {
953
1529
  i = close === -1 ? src.length : close + 2;
954
1530
  continue;
955
1531
  }
1532
+ if (ch === "/" && isRegexStart(src, i)) {
1533
+ i++;
1534
+ let inClass = false;
1535
+ while (i < index) {
1536
+ const c2 = src[i];
1537
+ if (c2 === "\\") {
1538
+ i += 2;
1539
+ continue;
1540
+ }
1541
+ if (inClass) {
1542
+ if (c2 === "]") inClass = false;
1543
+ i++;
1544
+ continue;
1545
+ }
1546
+ if (c2 === "[") {
1547
+ inClass = true;
1548
+ i++;
1549
+ continue;
1550
+ }
1551
+ if (c2 === "/") {
1552
+ i++;
1553
+ break;
1554
+ }
1555
+ if (c2 === "\n") break;
1556
+ i++;
1557
+ }
1558
+ while (i < index && /[a-z]/.test(src[i])) i++;
1559
+ continue;
1560
+ }
956
1561
  if (ch === "{") depth++;
957
1562
  else if (ch === "}") depth--;
958
1563
  i++;
@@ -963,8 +1568,410 @@ function autoCall(expr) {
963
1568
  const e = expr.trim();
964
1569
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
965
1570
  }
1571
+ var DEFER_ENABLED = true;
1572
+ function expandKeyBlocks(template, filePath) {
1573
+ if (!template.includes("{#key")) return template;
1574
+ for (let pass = 0; pass < 10; pass++) {
1575
+ const OPEN_RE = /\{#key\s+([^}]+)\}/g;
1576
+ OPEN_RE.lastIndex = 0;
1577
+ const openM = OPEN_RE.exec(template);
1578
+ if (!openM) return template;
1579
+ const expr = openM[1].trim();
1580
+ const bodyStart = openM.index + openM[0].length;
1581
+ const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
1582
+ TOK_RE.lastIndex = bodyStart;
1583
+ let depth = 1;
1584
+ let closeAt = -1;
1585
+ let tm;
1586
+ while (tm = TOK_RE.exec(template)) {
1587
+ if (tm[0].startsWith("{#")) {
1588
+ depth++;
1589
+ continue;
1590
+ }
1591
+ depth--;
1592
+ if (depth === 0) {
1593
+ closeAt = tm.index;
1594
+ break;
1595
+ }
1596
+ }
1597
+ if (closeAt < 0) {
1598
+ throw new RoseError(
1599
+ "E-TEMPLATE",
1600
+ `${filePath}: {#key ${expr}} is never closed`,
1601
+ { hint: "every {#key} needs its {/key}" }
1602
+ );
1603
+ }
1604
+ template = template.slice(0, openM.index) + `{#each [${expr}] as __rvkv}` + template.slice(bodyStart, closeAt) + "{/each}" + template.slice(closeAt + "{/key}".length);
1605
+ }
1606
+ return template;
1607
+ }
1608
+ function expandIfElseOnce(template) {
1609
+ const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
1610
+ let out = "";
1611
+ let pos = 0;
1612
+ let changed = false;
1613
+ for (; ; ) {
1614
+ const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
1615
+ if (!openM) {
1616
+ out += template.slice(pos);
1617
+ break;
1618
+ }
1619
+ const kind = openM[1];
1620
+ const head = openM[2];
1621
+ const start = pos + openM.index;
1622
+ const cond = kind === "if" ? head.trim() : "";
1623
+ const bodyStart = start + openM[0].length;
1624
+ out += template.slice(pos, start);
1625
+ TOK_RE.lastIndex = bodyStart;
1626
+ let depth = 1;
1627
+ let closeAt = -1;
1628
+ let closeLen = 0;
1629
+ const elses = [];
1630
+ let tm;
1631
+ while (tm = TOK_RE.exec(template)) {
1632
+ const tok = tm[0];
1633
+ if (tok.startsWith("{:else")) {
1634
+ if (depth === 1) {
1635
+ const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
1636
+ elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
1637
+ }
1638
+ continue;
1639
+ }
1640
+ if (tok.startsWith("{#")) {
1641
+ depth++;
1642
+ continue;
1643
+ }
1644
+ depth--;
1645
+ if (depth === 0) {
1646
+ closeAt = tm.index;
1647
+ closeLen = tok.length;
1648
+ break;
1649
+ }
1650
+ }
1651
+ if (closeAt < 0 || elses.length === 0) {
1652
+ out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
1653
+ if (closeAt < 0) break;
1654
+ pos = closeAt + closeLen;
1655
+ continue;
1656
+ }
1657
+ const body = template.slice(bodyStart, closeAt);
1658
+ if (kind === "each") {
1659
+ const lastBare = [...elses].reverse().find((e) => e.cond === null);
1660
+ if (!lastBare) {
1661
+ out += template.slice(start, closeAt + closeLen);
1662
+ pos = closeAt + closeLen;
1663
+ continue;
1664
+ }
1665
+ const relLast = lastBare.at - bodyStart;
1666
+ const eachBody = body.slice(0, relLast);
1667
+ const elseBody = body.slice(relLast + lastBare.len);
1668
+ const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, "").trim();
1669
+ out += template.slice(start, bodyStart) + eachBody + `{/each}{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
1670
+ pos = closeAt + closeLen;
1671
+ changed = true;
1672
+ continue;
1673
+ }
1674
+ const branches = [];
1675
+ let cursor = 0;
1676
+ for (let i = 0; i < elses.length; i++) {
1677
+ const e = elses[i];
1678
+ const rel = e.at - bodyStart;
1679
+ branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
1680
+ cursor = rel + e.len;
1681
+ }
1682
+ branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
1683
+ const first = branches.shift();
1684
+ const build2 = (bs) => {
1685
+ if (!bs.length) return "";
1686
+ const head2 = bs[0];
1687
+ const rest = bs.slice(1);
1688
+ if (head2.cond == null) return head2.body;
1689
+ let s = `{#if ${head2.cond}}${head2.body}{/if}`;
1690
+ if (rest.length) s += `{#if !(${head2.cond})}` + build2(rest) + `{/if}`;
1691
+ return s;
1692
+ };
1693
+ let emitted = `{#if ${cond}}${first.body}{/if}`;
1694
+ if (branches.length) emitted += `{#if !(${cond})}` + build2(branches) + `{/if}`;
1695
+ out += emitted;
1696
+ pos = closeAt + closeLen;
1697
+ changed = true;
1698
+ }
1699
+ return { template: out, changed };
1700
+ }
1701
+ function expandClassDirectives(template, filePath) {
1702
+ if (!template.includes("class:")) return template;
1703
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1704
+ let out = "";
1705
+ let pos = 0;
1706
+ let m;
1707
+ TAG_RE.lastIndex = 0;
1708
+ while (m = TAG_RE.exec(template)) {
1709
+ const [whole, tag, attrs, selfClose] = m;
1710
+ if (!attrs.includes("class:")) continue;
1711
+ const pairs = [];
1712
+ const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
1713
+ let nm;
1714
+ while (nm = NAME_RE.exec(attrs)) {
1715
+ let i = nm.index + nm[0].length;
1716
+ let depth = 1;
1717
+ while (i < attrs.length && depth > 0) {
1718
+ const ch = attrs[i];
1719
+ if (ch === '"' || ch === "'") {
1720
+ i = skipQuoted(attrs, i);
1721
+ continue;
1722
+ }
1723
+ if (ch === "{") depth++;
1724
+ else if (ch === "}") depth--;
1725
+ i++;
1726
+ }
1727
+ if (depth !== 0) {
1728
+ throw new RoseError("E-TEMPLATE", `${filePath}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
1729
+ }
1730
+ pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1731
+ }
1732
+ const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1733
+ const clsM = clsRe.exec(attrs);
1734
+ if (clsM && clsM[2].startsWith("{")) {
1735
+ throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both class={...} and class: directives`, { file: filePath, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
1736
+ }
1737
+ const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
1738
+ let closure = `(${JSON.stringify(staticCls)}`;
1739
+ for (const p of pairs) {
1740
+ closure += `+((${p.expr})?${JSON.stringify(" " + p.name)}:'')`;
1741
+ }
1742
+ closure += `)`;
1743
+ let newAttrs = attrs;
1744
+ for (let k = pairs.length - 1; k >= 0; k--) {
1745
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1746
+ }
1747
+ if (clsM) {
1748
+ newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
1749
+ } else {
1750
+ newAttrs = ` class={${closure}}` + newAttrs;
1751
+ }
1752
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1753
+ pos = m.index + whole.length;
1754
+ }
1755
+ if (pos === 0) return template;
1756
+ out += template.slice(pos);
1757
+ return out;
1758
+ }
1759
+ function expandStyleDirectives(template, filePath) {
1760
+ if (!template.includes("style:")) return template;
1761
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1762
+ let out = "";
1763
+ let pos = 0;
1764
+ let m;
1765
+ TAG_RE.lastIndex = 0;
1766
+ while (m = TAG_RE.exec(template)) {
1767
+ const [whole, tag, attrs, selfClose] = m;
1768
+ if (!attrs.includes("style:")) continue;
1769
+ const pairs = [];
1770
+ const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
1771
+ let nm;
1772
+ while (nm = NAME_RE.exec(attrs)) {
1773
+ let i = nm.index + nm[0].length;
1774
+ let depth = 1;
1775
+ while (i < attrs.length && depth > 0) {
1776
+ const ch = attrs[i];
1777
+ if (ch === '"' || ch === "'") {
1778
+ i = skipQuoted(attrs, i);
1779
+ continue;
1780
+ }
1781
+ if (ch === "{") depth++;
1782
+ else if (ch === "}") depth--;
1783
+ i++;
1784
+ }
1785
+ if (depth !== 0) {
1786
+ throw new RoseError("E-TEMPLATE", `${filePath}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
1787
+ }
1788
+ pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1789
+ }
1790
+ const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1791
+ const stM = styleRe.exec(attrs);
1792
+ if (stM && stM[2].startsWith("{")) {
1793
+ throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both style={...} and style: directives`, { file: filePath, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
1794
+ }
1795
+ const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
1796
+ let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
1797
+ for (const p of pairs) {
1798
+ closure += `+${JSON.stringify(p.prop + ":")}+(${p.expr})+';'`;
1799
+ }
1800
+ let newAttrs = attrs;
1801
+ for (let k = pairs.length - 1; k >= 0; k--) {
1802
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1803
+ }
1804
+ if (stM) {
1805
+ newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
1806
+ } else {
1807
+ newAttrs = ` style={${closure}}` + newAttrs;
1808
+ }
1809
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1810
+ pos = m.index + whole.length;
1811
+ }
1812
+ if (pos === 0) return template;
1813
+ out += template.slice(pos);
1814
+ return out;
1815
+ }
1816
+ function expandBoundaryFallbacks(template, filePath) {
1817
+ if (!template.includes("{:fallback")) return template;
1818
+ for (let pass = 0; pass < 10; pass++) {
1819
+ const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
1820
+ let out = "";
1821
+ let pos = 0;
1822
+ let changed = false;
1823
+ let tm;
1824
+ while (tm = TOK_RE.exec(template)) {
1825
+ if (tm[0] !== "{#boundary}") continue;
1826
+ const start = tm.index;
1827
+ const bodyStart = start + tm[0].length;
1828
+ let depth = 1;
1829
+ let closeAt = -1;
1830
+ let tm2;
1831
+ while (tm2 = TOK_RE.exec(template)) {
1832
+ if (tm2[0] === "{#boundary}") {
1833
+ depth++;
1834
+ continue;
1835
+ }
1836
+ if (tm2[0] === "{/boundary}") {
1837
+ depth--;
1838
+ if (depth === 0) {
1839
+ closeAt = tm2.index;
1840
+ break;
1841
+ }
1842
+ }
1843
+ }
1844
+ if (closeAt < 0) break;
1845
+ const body = template.slice(bodyStart, closeAt);
1846
+ const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
1847
+ const kindStack = ["boundary"];
1848
+ let d = 1;
1849
+ let fbAt = -1;
1850
+ let fbLen = 0;
1851
+ let tm3;
1852
+ BTOK2.lastIndex = 0;
1853
+ while (tm3 = BTOK2.exec(body)) {
1854
+ const tok = tm3[0];
1855
+ if (tok === "{:fallback}") {
1856
+ const top = kindStack[kindStack.length - 1];
1857
+ if (top !== "boundary") {
1858
+ throw new RoseError(
1859
+ "E-TEMPLATE",
1860
+ `${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
1861
+ { hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
1862
+ );
1863
+ }
1864
+ if (fbAt >= 0) {
1865
+ throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
1866
+ }
1867
+ fbAt = tm3.index;
1868
+ fbLen = tok.length;
1869
+ continue;
1870
+ }
1871
+ if (tok.startsWith("{#")) {
1872
+ d++;
1873
+ kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]);
1874
+ continue;
1875
+ }
1876
+ d--;
1877
+ kindStack.pop();
1878
+ }
1879
+ if (fbAt < 0) continue;
1880
+ const custom = body.slice(0, fbAt);
1881
+ const fbMarkup = body.slice(fbAt + fbLen);
1882
+ const b64 = Buffer.from(fbMarkup, "utf-8").toString("base64");
1883
+ out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + "{/boundary}";
1884
+ pos = closeAt + "{/boundary}".length;
1885
+ changed = true;
1886
+ }
1887
+ if (!changed) break;
1888
+ template = out + template.slice(pos);
1889
+ }
1890
+ return template;
1891
+ }
1892
+ function expandIfElse(template) {
1893
+ for (let pass = 0; pass < 10; pass++) {
1894
+ if (!/\{:else\b/.test(template)) return template;
1895
+ const r = expandIfElseOnce(template);
1896
+ template = r.template;
1897
+ if (!r.changed) return template;
1898
+ }
1899
+ return template;
1900
+ }
1901
+ function expandDeferBlocks(template) {
1902
+ if (!DEFER_ENABLED) {
1903
+ const openRe2 = /\{#defer(?:\s+hold=\\d+)?\}/g;
1904
+ let out2 = "";
1905
+ let dpos = 0;
1906
+ for (; ; ) {
1907
+ openRe2.lastIndex = dpos;
1908
+ const openM = openRe2.exec(template);
1909
+ if (!openM) break;
1910
+ const openAt = openM.index;
1911
+ const openLen = openM[0].length;
1912
+ const closeAt = template.indexOf("{/defer}", openAt + openLen);
1913
+ if (closeAt < 0) break;
1914
+ out2 += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
1915
+ dpos = closeAt + 8;
1916
+ }
1917
+ return { template: dpos === 0 ? template : out2, count: 0, holds: [] };
1918
+ }
1919
+ let count = 0;
1920
+ const holds = [];
1921
+ let out = "";
1922
+ let pos = 0;
1923
+ const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
1924
+ for (; ; ) {
1925
+ openRe.lastIndex = pos;
1926
+ const openM = openRe.exec(template);
1927
+ if (!openM) break;
1928
+ const openAt = openM.index;
1929
+ const openLen = openM[0].length;
1930
+ const hold = openM[1] ? Number(openM[1]) : 0;
1931
+ let depth = 1;
1932
+ let i = openAt + openLen;
1933
+ let closeAt = -1;
1934
+ while (i < template.length) {
1935
+ openRe.lastIndex = i;
1936
+ const nextOpenM = openRe.exec(template);
1937
+ const nextOpen = nextOpenM ? nextOpenM.index : -1;
1938
+ const nextClose = template.indexOf("{/defer}", i);
1939
+ if (nextClose < 0) break;
1940
+ if (nextOpen >= 0 && nextOpen < nextClose) {
1941
+ depth++;
1942
+ i = nextOpen + nextOpenM[0].length;
1943
+ continue;
1944
+ }
1945
+ depth--;
1946
+ if (depth === 0) {
1947
+ closeAt = nextClose;
1948
+ break;
1949
+ }
1950
+ i = nextClose + 8;
1951
+ }
1952
+ if (closeAt < 0) break;
1953
+ const content = template.slice(openAt + openLen, closeAt);
1954
+ holds.push(hold);
1955
+ const n = ++count;
1956
+ out += template.slice(pos, openAt);
1957
+ out += "{#if __rvDefer" + n + "()}" + content + "{/if}\n{#if !__rvDefer" + n + '()}<div class="rv-defer-loading"></div>{/if}';
1958
+ pos = closeAt + 8;
1959
+ }
1960
+ if (count === 0) return { template, count: 0, holds: [] };
1961
+ out += template.slice(pos);
1962
+ return { template: out, count, holds };
1963
+ }
1964
+ function deferBootCode(count, holds = []) {
1965
+ let code = "";
1966
+ for (let n = 1; n <= count; n++) {
1967
+ code += "const [__rvDefer" + n + ", set__rvDefer" + n + '] = state("__rvdefer' + n + '", false);\n';
1968
+ const hold = holds[n - 1] || 0;
1969
+ code += hold > 0 ? "onMount(function () { setTimeout(function () { set__rvDefer" + n + "(true); }, " + hold + "); });\n" : "onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer" + n + "(true); }); }); });\n";
1970
+ }
1971
+ return code;
1972
+ }
966
1973
  function findBlock(src, kind) {
967
- const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
1974
+ const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
968
1975
  const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
969
1976
  let open;
970
1977
  while (open = head.exec(src)) {
@@ -986,7 +1993,7 @@ function findBlock(src, kind) {
986
1993
  i = nextClose.index + nextClose[0].length;
987
1994
  if (--depth === 0) {
988
1995
  const content = src.slice(afterOpen, nextClose.index);
989
- const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
1996
+ const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", content];
990
1997
  const arr = [src.slice(start, i), ...groups];
991
1998
  arr.index = start;
992
1999
  return arr;
@@ -1012,27 +2019,138 @@ function compileHead(head) {
1012
2019
  i = end < 0 ? head.length : end + 3;
1013
2020
  continue;
1014
2021
  }
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;
2022
+ RAW_OPEN.lastIndex = i;
2023
+ const open = RAW_OPEN.exec(head);
2024
+ if (open) {
2025
+ const tag = open[1].toLowerCase();
2026
+ const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
2027
+ const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
2028
+ const end = gt < 0 ? head.length : gt + 1;
2029
+ flush();
2030
+ out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
2031
+ i = end;
2032
+ continue;
2033
+ }
2034
+ buf += head[i++];
2035
+ }
2036
+ flush();
2037
+ return out;
2038
+ }
2039
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
2040
+ function assertKnownDirectives(template, filePath) {
2041
+ const rawRanges = [];
2042
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
2043
+ let raw;
2044
+ while (raw = RAW_OPEN.exec(template)) {
2045
+ const tag = raw[1].toLowerCase();
2046
+ const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
2047
+ const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
2048
+ const end = gt < 0 ? template.length : gt + 1;
2049
+ rawRanges.push([raw.index, end]);
2050
+ RAW_OPEN.lastIndex = end;
2051
+ }
2052
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
2053
+ let note;
2054
+ while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
2055
+ rawRanges.sort((a, b) => a[0] - b[0]);
2056
+ const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
2057
+ const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
2058
+ let m;
2059
+ while (m = DIRECTIVE_RE.exec(template)) {
2060
+ if (inRaw(m.index)) continue;
2061
+ const [, sigil, word] = m;
2062
+ if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
2063
+ if (sigil === "/") {
2064
+ throw new RoseError(
2065
+ "E-TEMPLATE",
2066
+ `${filePath}: {/${word}} does not close anything`,
2067
+ { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2068
+ );
2069
+ }
2070
+ if (word === "else") {
2071
+ throw new RoseError(
2072
+ "E-TEMPLATE",
2073
+ `${filePath}: a stray {:else} with no {#if} above it`,
2074
+ { file: filePath, line: lineAt(template, m), hint: "{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}" }
2075
+ );
2076
+ }
2077
+ if (word === "fallback") {
2078
+ throw new RoseError(
2079
+ "E-TEMPLATE",
2080
+ `${filePath}: a stray {:fallback} with no {#boundary} above it`,
2081
+ { file: filePath, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
2082
+ );
2083
+ }
2084
+ throw new RoseError(
2085
+ "E-TEMPLATE",
2086
+ `${filePath}: {:${word}} is not a rosetack directive`,
2087
+ { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
2088
+ );
2089
+ }
2090
+ const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
2091
+ while (m = OPENER_RE.exec(template)) {
2092
+ if (inRaw(m.index)) continue;
2093
+ const [, kind, head] = m;
2094
+ if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
2095
+ throw new RoseError(
2096
+ "E-TEMPLATE",
2097
+ `${filePath}: {#each ${head.trim()}} is missing its item name`,
2098
+ { file: filePath, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
2099
+ );
2100
+ }
2101
+ const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
2102
+ const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
2103
+ let depth = 1;
2104
+ let i = m.index + m[0].length;
2105
+ for (; ; ) {
2106
+ OPEN_RE.lastIndex = i;
2107
+ CLOSE_RE.lastIndex = i;
2108
+ const nextOpen = OPEN_RE.exec(template);
2109
+ const nextClose = CLOSE_RE.exec(template);
2110
+ if (!nextClose) break;
2111
+ if (nextOpen && nextOpen.index < nextClose.index) {
2112
+ i = nextOpen.index + nextOpen[0].length;
2113
+ continue;
2114
+ }
2115
+ i = nextClose.index + nextClose[0].length;
2116
+ if (--depth === 0) break;
2117
+ }
2118
+ if (depth !== 0) {
2119
+ throw new RoseError(
2120
+ "E-TEMPLATE",
2121
+ `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2122
+ { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2123
+ );
1026
2124
  }
1027
- buf += head[i++];
1028
2125
  }
1029
- flush();
1030
- return out;
1031
2126
  }
1032
- function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
2127
+ function rewriteQuotedExprAttrs(template, comps) {
2128
+ const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
2129
+ return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
2130
+ if (comps.has(name) || !/\{/.test(attrs)) return tag;
2131
+ const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
2132
+ if (!/\{/.test(value) || value.includes("`")) return whole;
2133
+ const spans = templateExprSpans(value);
2134
+ if (spans.length === 0) return whole;
2135
+ let expr = "";
2136
+ let last = 0;
2137
+ for (const s of spans) {
2138
+ if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
2139
+ expr += (expr ? " + " : "") + `(${s.expr})`;
2140
+ last = s.end + 1;
2141
+ }
2142
+ if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
2143
+ return `${attr}={${expr}}`;
2144
+ });
2145
+ return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
2146
+ });
2147
+ }
2148
+ function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map(), islandDepth = 0) {
1033
2149
  let result = "";
1034
2150
  let remaining = template;
1035
2151
  let blockId = 0;
2152
+ const islandsMode = /\{#island\b/.test(template);
2153
+ const effMarkers = markers && (!islandsMode || islandDepth > 0);
1036
2154
  const nextId = () => `${depth}_${blockId++}`;
1037
2155
  while (remaining.length > 0) {
1038
2156
  const ifMatch = findBlock(remaining, "if");
@@ -1041,13 +2159,34 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1041
2159
  const firstExpr = templateExprSpans(remaining)[0];
1042
2160
  const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
1043
2161
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2162
+ const islandMatch = findBlock(remaining, "island");
1044
2163
  const candidates = [];
1045
2164
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
1046
2165
  if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
1047
2166
  if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
2167
+ if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
1048
2168
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
1049
2169
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
1050
2170
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
2171
+ const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
2172
+ const rawHit = rawOpenRe.exec(remaining);
2173
+ if (rawHit && earliest && rawHit.index < earliest.index) {
2174
+ const tag = rawHit[1].toLowerCase();
2175
+ const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
2176
+ const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
2177
+ const end = gt < 0 ? remaining.length : gt + 1;
2178
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
2179
+ remaining = remaining.substring(end);
2180
+ continue;
2181
+ }
2182
+ const noteAt = remaining.indexOf("<!--");
2183
+ if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
2184
+ const noteEnd = remaining.indexOf("-->", noteAt + 4);
2185
+ const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
2186
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
2187
+ remaining = remaining.substring(end);
2188
+ continue;
2189
+ }
1051
2190
  if (!earliest) {
1052
2191
  result += emitChunk(remaining, acc, closes, scope);
1053
2192
  break;
@@ -1059,10 +2198,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1059
2198
  const call = autoCall(cond);
1060
2199
  const id = nextId();
1061
2200
  const innerScope = scope ?? "__s";
1062
- const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, markers, comps);
2201
+ const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, effMarkers, comps, islandDepth);
1063
2202
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
1064
2203
  `;
1065
- if (markers) {
2204
+ if (effMarkers) {
1066
2205
  result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
1067
2206
  `;
1068
2207
  } else {
@@ -1071,43 +2210,62 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1071
2210
  }
1072
2211
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1073
2212
  } else if (earliest.type === "each") {
1074
- const [, items, item, content] = earliest.match;
2213
+ const [, items, item, index, content] = earliest.match;
1075
2214
  const before = remaining.substring(0, earliest.index);
1076
2215
  if (before) result += emitChunk(before, acc, closes, scope);
1077
2216
  const call = autoCall(items);
1078
2217
  const id = nextId();
1079
- const itemRe = new RegExp(`\\b${item}\\b`, "g");
2218
+ const isDestructure = /^[{[]/.test(item);
2219
+ const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, "g");
2220
+ const indexRe = index ? new RegExp(`\\b${index}\\b`, "g") : null;
1080
2221
  let scoped = "";
1081
2222
  let lastSpan = 0;
1082
2223
  for (const s of templateExprSpans(content.trim())) {
1083
- scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
2224
+ let expr = itemRe ? s.expr.replace(itemRe, "__s") : s.expr;
2225
+ if (indexRe) expr = expr.replace(indexRe, "__i");
2226
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + expr + "}";
1084
2227
  lastSpan = s.end + 1;
1085
2228
  }
1086
2229
  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; };
2230
+ const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2231
+ const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2232
+ result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
1089
2233
  `;
1090
- if (markers) {
2234
+ if (effMarkers) {
1091
2235
  result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
1092
2236
  `;
1093
2237
  } else {
1094
- result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');
2238
+ const param = isDestructure ? "__s" : item;
2239
+ result += `${acc} += (${call}).map((${param}${index ? ", __i" : ""}) => __b${id}(${param}, []${index ? ", __i" : ""}))).join('');
1095
2240
  `;
1096
2241
  }
1097
2242
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1098
2243
  } else if (earliest.type === "boundary") {
1099
- const [, content] = earliest.match;
2244
+ const [, fbAttr, content] = earliest.match;
2245
+ let fallbackSrc = "";
2246
+ if (fbAttr) {
2247
+ const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
2248
+ if (fbM) fallbackSrc = Buffer.from(fbM[1], "base64").toString("utf-8");
2249
+ }
2250
+ const custom = content;
1100
2251
  const before = remaining.substring(0, earliest.index);
1101
2252
  if (before) result += emitChunk(before, acc, closes, scope);
1102
2253
  const id = nextId();
1103
- const catchesAction = /\$action:|<form[\s>]/.test(content);
1104
- const inner = compileTemplate(content.trim(), "h", closes, scope, depth + 1, markers, comps);
2254
+ const catchesAction = /\$action:|<form[\s>]/.test(custom);
2255
+ const inner = compileTemplate(custom.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
1105
2256
  result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
1106
2257
  `;
2258
+ let fbBlock = "";
2259
+ if (fallbackSrc.trim()) {
2260
+ const fbInner = compileTemplate(fallbackSrc.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
2261
+ fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };
2262
+ `;
2263
+ }
2264
+ result += fbBlock;
1107
2265
  result += `let __bd${id} = '';
1108
2266
  `;
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)}; }
2267
+ result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : "$boundaryFallback(e)"}; }
2268
+ ` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
1111
2269
  `;
1112
2270
  result += `${acc} += __bd${id};
1113
2271
  `;
@@ -1130,7 +2288,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1130
2288
  const { def, named } = splitSlots(childrenSrc);
1131
2289
  const hasChildren = def.trim().length > 0;
1132
2290
  if (hasChildren) {
1133
- result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, markers, comps)} return h; };
2291
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; };
1134
2292
  `;
1135
2293
  }
1136
2294
  const slotFns = named.map(([nm, src]) => {
@@ -1146,9 +2304,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1146
2304
  }
1147
2305
  content = out + content.slice(lastSpan);
1148
2306
  }
1149
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
2307
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
1150
2308
  });
1151
2309
  const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
2310
+ if (a.kind === "spread") return `...(${a.value})`;
1152
2311
  const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
1153
2312
  const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
1154
2313
  return `${JSON.stringify(key)}: ${val}`;
@@ -1157,20 +2316,49 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1157
2316
  result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
1158
2317
  `;
1159
2318
  remaining = rest;
2319
+ } else if (earliest.type === "island") {
2320
+ const [, name, hydrate, content] = earliest.match;
2321
+ const before = remaining.substring(0, earliest.index);
2322
+ if (before) result += emitChunk(before, acc, closes, scope);
2323
+ const hydrateAttr = hydrate === "visible" || hydrate === "idle" ? ` data-rv-island-hydrate="${hydrate}"` : "";
2324
+ result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ""}"${hydrateAttr}>`)};
2325
+ `;
2326
+ const inner = compileTemplate(content.trim(), "h", "__c", scope, depth + 1, markers, comps, islandDepth + 1);
2327
+ result += inner;
2328
+ result += `${acc} += '</div>';
2329
+ `;
2330
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1160
2331
  } else {
1161
2332
  const [, expr] = earliest.match;
1162
2333
  const trimmed = expr.trim();
1163
2334
  const before = remaining.substring(0, earliest.index);
2335
+ const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
2336
+ if (constMatch) {
2337
+ if (before) result += emitChunk(before, acc, closes, scope);
2338
+ result += `const ${constMatch[1]} = (${constMatch[2].trim()});
2339
+ `;
2340
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2341
+ continue;
2342
+ }
1164
2343
  if (trimmed === "__slot__") {
1165
2344
  if (before) result += emitChunk(before, acc, closes, scope);
1166
2345
  result += compileSlot(acc);
1167
2346
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1168
2347
  continue;
1169
2348
  }
1170
- const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
2349
+ const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
2350
+ if (slotDefault) {
2351
+ if (before) result += emitChunk(before, acc, closes, scope);
2352
+ result += `${acc} += __slotDefault(children, ${slotDefault[1]});
2353
+ `;
2354
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2355
+ continue;
2356
+ }
2357
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
1171
2358
  if (slotCall) {
1172
2359
  if (before) result += emitChunk(before, acc, closes, scope);
1173
- result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);
2360
+ const fb = slotCall[4] ? `, ${slotCall[4]}` : "";
2361
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});
1174
2362
  `;
1175
2363
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1176
2364
  continue;
@@ -1179,7 +2367,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1179
2367
  if (rawMatch) {
1180
2368
  if (before) result += emitChunk(before, acc, closes, scope);
1181
2369
  const expr2 = rawMatch[1].trim();
1182
- if (!markers) {
2370
+ if (!effMarkers) {
1183
2371
  result += `${acc} += String(${expr2} ?? '');
1184
2372
  `;
1185
2373
  } else {
@@ -1194,12 +2382,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1194
2382
  if (attrMatch) {
1195
2383
  const lit = before.slice(0, before.length - attrMatch[0].length);
1196
2384
  if (lit) result += emitChunk(lit, acc, closes, scope);
1197
- result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
2385
+ result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
1198
2386
  } else {
1199
2387
  if (before) result += emitChunk(before, acc, closes, scope);
1200
2388
  const after = remaining.substring(earliest.index + earliest.match[0].length);
1201
2389
  const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
1202
- result += emitText(trimmed, acc, closes, scope, markers, pair);
2390
+ result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
1203
2391
  }
1204
2392
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1205
2393
  }
@@ -1259,6 +2447,12 @@ function parseCompAttrs(attrs) {
1259
2447
  const out = [];
1260
2448
  let i = 0;
1261
2449
  while (i < attrs.length) {
2450
+ const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
2451
+ if (spread) {
2452
+ out.push({ name: "...", kind: "spread", value: spread[1].trim() });
2453
+ i += spread[0].length;
2454
+ continue;
2455
+ }
1262
2456
  const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
1263
2457
  if (!nm) break;
1264
2458
  i += nm[0].length;
@@ -1396,22 +2590,55 @@ var IMG_MIME = {
1396
2590
  ".ico": "image/x-icon"
1397
2591
  };
1398
2592
  var INLINE_IMG_MAX = 4096;
2593
+ function listImageVariants(publicDir, url) {
2594
+ const ext = path2.extname(url);
2595
+ const base = path2.basename(url, ext);
2596
+ const dirUrl = url.slice(0, url.length - (base + ext).length);
2597
+ let entries;
2598
+ try {
2599
+ entries = fs3.readdirSync(path2.join(publicDir, path2.dirname(url)));
2600
+ } catch {
2601
+ return [];
2602
+ }
2603
+ const re = new RegExp(
2604
+ "^" + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.w(\\d+)" + ext.replace(".", "\\.") + "$",
2605
+ "i"
2606
+ );
2607
+ const out = [];
2608
+ for (const e of entries) {
2609
+ const m = re.exec(e);
2610
+ const width = m ? Number(m[1]) : 0;
2611
+ if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
2612
+ }
2613
+ return out.sort((a, b) => a.width - b.width);
2614
+ }
1399
2615
  function inlineImages(template, publicDir) {
1400
2616
  return template.replace(IMG_RE, (tag) => {
1401
2617
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
1402
2618
  if (!src) return tag;
1403
- const ext = path.extname(src[1]).toLowerCase();
2619
+ const ext = path2.extname(src[1]).toLowerCase();
1404
2620
  const mime = IMG_MIME[ext];
1405
2621
  if (!mime) return tag;
2622
+ const rel = src[1].replace(/^\/public(?=\/)/, "");
2623
+ const filePath = path2.join(publicDir, rel);
1406
2624
  let file;
1407
2625
  try {
1408
- file = fs.readFileSync(path.join(publicDir, src[1]));
2626
+ file = fs3.readFileSync(filePath);
1409
2627
  } catch {
1410
2628
  return tag;
1411
2629
  }
1412
- if (file.length > INLINE_IMG_MAX) return tag;
2630
+ const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
2631
+ const dims = authorDims ? null : readImageSize(filePath);
2632
+ const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
2633
+ if (file.length > INLINE_IMG_MAX) {
2634
+ const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
2635
+ const variants = hasSS ? [] : listImageVariants(publicDir, rel);
2636
+ if (!variants.length) return withDims(tag);
2637
+ const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(", ");
2638
+ return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
2639
+ }
1413
2640
  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}"`);
2641
+ return withDims(tag.replace(src[0], `src="${uri}"`));
1415
2642
  });
1416
2643
  }
1417
2644
  function emitText(expr, acc, closes, scope, markers = true, pair = false) {
@@ -1425,6 +2652,7 @@ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
1425
2652
  return `${acc} += textMark(${closes}, ${fn}${extra});
1426
2653
  `;
1427
2654
  }
2655
+ var BOOLEAN_ATTRS = /* @__PURE__ */ new Set(["checked", "disabled", "readonly", "required", "selected", "multiple", "autofocus", "open"]);
1428
2656
  function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1429
2657
  if (!markers) {
1430
2658
  return `${acc} += '${attr}="' + esc(${expr}) + '"';
@@ -1432,6 +2660,10 @@ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1432
2660
  }
1433
2661
  const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1434
2662
  const arg = scope ? `, ${scope}` : "";
2663
+ if (BOOLEAN_ATTRS.has(attr)) {
2664
+ return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});
2665
+ `;
2666
+ }
1435
2667
  return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
1436
2668
  `;
1437
2669
  }
@@ -1439,7 +2671,8 @@ function compileSlot(acc) {
1439
2671
  return `${acc} += String(children);
1440
2672
  `;
1441
2673
  }
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';`;
2674
+ var RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
2675
+ var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1443
2676
  function propsCode(props) {
1444
2677
  if (props.length === 0) return "";
1445
2678
  return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
@@ -1451,15 +2684,15 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1451
2684
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1452
2685
  return { o, fn };
1453
2686
  };
1454
- const __slotBlock = (closes, sl, name, pairs) => {
2687
+ const __slotBlock = (closes, sl, name, pairs, fallback) => {
1455
2688
  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-->";
2689
+ if (hit) return slotBlockMark(closes, hit);
2690
+ return fallback || '';
2691
+ };
2692
+ const __slotDefault = (children, fallback) => {
2693
+ const c = children == null ? '' : String(children);
2694
+ if (c.trim()) return c;
2695
+ return fallback || '';
1463
2696
  };`;
1464
2697
  function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1465
2698
  const headCode = headFn ? `
@@ -1485,9 +2718,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1485
2718
  ${script}
1486
2719
  ${stateDeclsCode}
1487
2720
  ${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).
2721
+
1491
2722
  ${isComponent ? "" : "applyStateDeltas();"}
1492
2723
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1493
2724
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
@@ -1497,6 +2728,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1497
2728
  }
1498
2729
  function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1499
2730
  const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
2731
+ const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
1500
2732
  const headCode = headFn ? `
1501
2733
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1502
2734
  __html += headMark(closes, __head);` : "";
@@ -1506,7 +2738,9 @@ ${RUNTIME_IMPORTS}
1506
2738
  ${imports}
1507
2739
 
1508
2740
  ${exports}
1509
-
2741
+ ${clientSetState ? `
2742
+ ${clientSetState}
2743
+ ` : ""}
1510
2744
  ${namedSlots ? SLOT_HELPER : ""}
1511
2745
 
1512
2746
  export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
@@ -1529,55 +2763,98 @@ var routeShipsNoJs = (infos, compiled, i) => {
1529
2763
  if (compiled[i].needsClient) return false;
1530
2764
  return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1531
2765
  };
2766
+ var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
1532
2767
  function buildReport(infos, compiled) {
1533
2768
  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
2769
  if (routeShipsNoJs(infos, compiled, i)) {
1535
2770
  return `${info.routePath} zero-JS nothing in the chain needs the client`;
1536
2771
  }
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("; ");
2772
+ const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path2.basename(infos[ci].filePath)}`).join("; ");
1538
2773
  const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
1539
2774
  return `${info.routePath} client JS ${why}${forced}`;
1540
2775
  });
1541
2776
  }
2777
+ var MOUNT_ENTRY = `
2778
+ import { start, postForm } from '/client.js';
2779
+
2780
+ for (const el of document.querySelectorAll('[data-rosetack]')) {
2781
+ const route = el.getAttribute('data-rosetack');
2782
+ const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
2783
+ const parsed = new DOMParser().parseFromString(doc, 'text/html');
2784
+ // A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
2785
+ const app = parsed.getElementById('app');
2786
+ if (app) {
2787
+ el.innerHTML = app.innerHTML;
2788
+ } else {
2789
+ for (const node of Array.from(parsed.body.children)) {
2790
+ if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
2791
+ }
2792
+ }
2793
+ // start() resumes from #__rosetack_state (zero hydration), so the state
2794
+
2795
+ const state = parsed.getElementById('__rosetack_state');
2796
+ if (state) el.appendChild(state);
2797
+
2798
+ const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
2799
+ await start(el, route, rendered === route);
2800
+ if (state) state.remove();
2801
+
2802
+ el.addEventListener('click', (e) => {
2803
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
2804
+ if (!a || !el.contains(a)) return;
2805
+ e.preventDefault();
2806
+ el.setAttribute('data-rosetack', a.getAttribute('href'));
2807
+ start(el, a.getAttribute('href'), false);
2808
+ });
2809
+ // Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
2810
+ el.addEventListener('submit', (e) => {
2811
+ const f = e.target;
2812
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
2813
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
2814
+ e.preventDefault();
2815
+ postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
2816
+ });
2817
+ }
2818
+ `;
1542
2819
  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 })));
2820
+ await fs3.promises.mkdir(outDir, { recursive: true });
2821
+ const stale = (await fs3.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
2822
+ await Promise.all(stale.map((f) => fs3.promises.rm(path2.join(outDir, f), { force: true })));
1546
2823
  const pageFiles = await scanRoseFiles(root);
1547
2824
  const compFiles = await scanComponentFiles(root);
1548
2825
  const files = [...pageFiles, ...compFiles];
1549
2826
  if (pageFiles.length === 0) {
1550
2827
  throw new RoseError(
1551
2828
  "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)" }
2829
+ `no .rose pages found under ${path2.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
2830
+ { file: path2.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1554
2831
  );
1555
2832
  }
1556
2833
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1557
2834
  const config = await loadConfig(root);
1558
2835
  const plugins = config.plugins;
1559
2836
  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$/, "");
2837
+ const base = infos[i].isComponent ? path2.join(root, "src") : path2.join(root, "src", "pages");
2838
+ return path2.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
1562
2839
  });
1563
2840
  const registry = new Map(
1564
2841
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1565
2842
  );
1566
2843
  const compiled = await Promise.all(
1567
- files.map((f, i) => compileComponent(f, path.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
2844
+ files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
1568
2845
  );
1569
2846
  const importsOf = /* @__PURE__ */ new Map();
1570
2847
  files.forEach((_, i) => {
1571
2848
  const list = [];
1572
2849
  for (const r of compiled[i].roseImports ?? []) {
1573
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
2850
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1574
2851
  const hit = registry.get(abs);
1575
2852
  if (hit) list.push(hit.index);
1576
2853
  }
1577
2854
  importsOf.set(i, list);
1578
2855
  });
1579
2856
  const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
1580
- if (compiled[i].needsClient) return path.basename(files[i]);
2857
+ if (compiled[i].needsClient) return path2.basename(files[i]);
1581
2858
  if (seen.has(i)) return null;
1582
2859
  seen.add(i);
1583
2860
  for (const dep of importsOf.get(i) ?? []) {
@@ -1599,7 +2876,7 @@ async function buildProject(root, outDir) {
1599
2876
  if (reachable.has(i)) return;
1600
2877
  reachable.add(i);
1601
2878
  for (const r of compiled[i].roseImports ?? []) {
1602
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
2879
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1603
2880
  const hit = registry.get(abs);
1604
2881
  if (hit) visit(hit.index);
1605
2882
  }
@@ -1608,13 +2885,13 @@ async function buildProject(root, outDir) {
1608
2885
  if (!infos[i].isComponent) visit(i);
1609
2886
  });
1610
2887
  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 });
2888
+ if (styles) await fs3.promises.writeFile(path2.join(outDir, "styles.css"), styles);
2889
+ else await fs3.promises.rm(path2.join(outDir, "styles.css"), { force: true });
1613
2890
  let locales = {};
1614
2891
  try {
1615
- for (const f of await fs.promises.readdir(path.join(root, "src", "locales"))) {
2892
+ for (const f of await fs3.promises.readdir(path2.join(root, "src", "locales"))) {
1616
2893
  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"));
2894
+ locales[f.slice(0, -5)] = JSON.parse(await fs3.promises.readFile(path2.join(root, "src", "locales", f), "utf-8"));
1618
2895
  }
1619
2896
  } catch {
1620
2897
  locales = {};
@@ -1626,23 +2903,24 @@ async function buildProject(root, outDir) {
1626
2903
  for (const l of preload) {
1627
2904
  if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
1628
2905
  }
1629
- await fs.promises.rm(path.join(outDir, "locales"), { recursive: true, force: true });
2906
+ await fs3.promises.rm(path2.join(outDir, "locales"), { recursive: true, force: true });
1630
2907
  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]));
2908
+ const packDir = path2.join(outDir, "locales");
2909
+ await fs3.promises.mkdir(packDir, { recursive: true });
2910
+ for (const l of packed) await fs3.promises.writeFile(path2.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
1634
2911
  }
1635
2912
  const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
1636
2913
  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 });
2914
+ const buildDir = path2.join(outDir, ".build");
2915
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
2916
+ await fs3.promises.mkdir(buildDir, { recursive: true });
2917
+ const contentSrcCands = [path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "cli", "content.ts"), path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "src", "cli", "content.ts")];
2918
+ const contentSrc = contentSrcCands.find((c) => fs3.existsSync(c)) ?? contentSrcCands[0];
2919
+ fs3.copyFileSync(contentSrc, path2.join(buildDir, "content-md.ts"));
1640
2920
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1641
2921
  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.
2922
+ const configRel = path2.relative(buildDir, path2.join(root, "rosetack.config.js")).replace(/\\/g, "/");
2923
+ await fs3.promises.writeFile(path2.join(buildDir, "plugins.js"), `
1646
2924
  import config from ${JSON.stringify(configRel)};
1647
2925
 
1648
2926
  const list = Array.isArray(config) ? config : [];
@@ -1654,25 +2932,51 @@ export const hasRequestHooks = hooks.some((p) => p.onRequest);
1654
2932
  export const hasResponseHooks = hooks.some((p) => p.onResponse);
1655
2933
  `);
1656
2934
  }
1657
- const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
2935
+ const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs3.existsSync(p));
1658
2936
  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
2937
  await esbuild.build({
1660
2938
  entryPoints: [runtimeEntry],
1661
2939
  bundle: true,
1662
- outfile: path.join(buildDir, "runtime.js"),
2940
+ outfile: path2.join(buildDir, "runtime.js"),
1663
2941
  format: "esm",
1664
2942
  platform: "browser",
1665
2943
  write: true
1666
2944
  });
1667
2945
  for (let i = 0; i < compiled.length; i++) {
1668
2946
  const src = compiled[i].api ?? compiled[i].ssr;
1669
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
2947
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.ssr.js`), src);
1670
2948
  if (!infos[i].isApi) {
1671
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
2949
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1672
2950
  }
1673
2951
  }
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);
2952
+ const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).sort((a, b) => {
2953
+ const rank = (pattern) => {
2954
+ const segs = pattern.split("/");
2955
+ return [
2956
+ segs.filter((s) => s.startsWith("**")).length,
2957
+ segs.filter((s) => s.startsWith("*")).length,
2958
+ segs.filter((s) => s.startsWith(":")).length
2959
+ ];
2960
+ };
2961
+ const ra = rank(a.info.pattern);
2962
+ const rb = rank(b.info.pattern);
2963
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2964
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2965
+ });
2966
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
2967
+ const rank = (pattern) => {
2968
+ const segs = pattern.split("/");
2969
+ return [
2970
+ segs.filter((s) => s.startsWith("**")).length,
2971
+ segs.filter((s) => s.startsWith("*")).length,
2972
+ segs.filter((s) => s.startsWith(":")).length
2973
+ ];
2974
+ };
2975
+ const ra = rank(a.info.pattern);
2976
+ const rb = rank(b.info.pattern);
2977
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2978
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2979
+ });
1676
2980
  const compose = (idx) => {
1677
2981
  let expr = `render_${idx}`;
1678
2982
  for (const i of layoutsOf(infos, idx)) {
@@ -1703,10 +3007,18 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1703
3007
  const named = [actionImports, guardImport].filter(Boolean).join(", ");
1704
3008
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1705
3009
  }).join("\n");
1706
- const nfIdx = infos.findIndex((info) => info.isNotFound);
1707
- const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
3010
+ const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
3011
+ const rel = path2.relative(path2.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
3012
+ const dir = path2.posix.dirname(rel);
3013
+ const prefix = dir === "." ? "/" : "/" + dir;
3014
+ const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
3015
+ return { prefix, render: compose(i), flags };
3016
+ }).sort((a, b) => b.prefix.length - a.prefix.length);
3017
+ const notFoundTable = `[
3018
+ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
3019
+ ]`;
1708
3020
  const errIdx = infos.findIndex((info) => info.isError);
1709
- const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
3021
+ const errorRender = errIdx >= 0 ? compose(errIdx) : "null";
1710
3022
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
1711
3023
  const serverRoutes = pages.map(({ info, i }) => {
1712
3024
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -1728,13 +3040,17 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1728
3040
  }
1729
3041
  }
1730
3042
  const csrFlag = routeNoJs(i) ? ", csr: false" : "";
3043
+ const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
1731
3044
  const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
3045
+ const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
1732
3046
  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} }`;
3047
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
1734
3048
  }).join(",\n ");
1735
3049
  const serverEntry = `
1736
3050
  ${serverImports}
1737
- import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
3051
+ import { renderMarkdown } from './content-md.ts';
3052
+ import crypto from 'node:crypto';
3053
+ import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
1738
3054
  ${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
3055
  // module to import - the runners below stay no-ops and the servers call them
1740
3056
  // unconditionally (one code path, no flags to keep in sync).
@@ -1742,12 +3058,7 @@ const __pluginHooks = [];
1742
3058
  const __hasRequestHooks = false;
1743
3059
  const __hasResponseHooks = false;`}
1744
3060
 
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).
3061
+
1751
3062
  export async function runRequestHooks(ctx) {
1752
3063
  for (const p of __pluginHooks) {
1753
3064
  if (!p.onRequest) continue;
@@ -1775,32 +3086,20 @@ export async function runResponseHooks(ctx, res) {
1775
3086
  return out;
1776
3087
  }
1777
3088
 
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.
3089
+
3090
+
1780
3091
  export const hasRequestHooks = __hasRequestHooks;
1781
3092
  export const hasResponseHooks = __hasResponseHooks;
1782
3093
 
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.
3094
+ // P0-1: the query of the request being rendered, for $query().
1789
3095
  export function setQuery(query) {
1790
3096
  setRequestQuery(query || {});
1791
3097
  }
1792
3098
 
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.
3099
+
1796
3100
  setLocales(${localesJson}, '${defaultLocale}');
1797
3101
 
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.
3102
+
1804
3103
  if (typeof process !== 'undefined' && typeof process.send === 'function') {
1805
3104
  setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1806
3105
  process.on('message', (msg) => {
@@ -1808,76 +3107,274 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1808
3107
  });
1809
3108
  }
1810
3109
 
3110
+ // (the cross-machine seam): the cluster relay above covers ONE machine.
3111
+ export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
3112
+ setStoreTransport(send);
3113
+ }
3114
+ export function __deliverStorePatch(name: string, value: unknown): void {
3115
+ applyStorePatch(name, value);
3116
+ }
3117
+
1811
3118
  export { localeList };
1812
3119
  export const defaultLocale = '${defaultLocale}';
1813
3120
 
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).
3121
+ // Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
1820
3122
  ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1821
3123
 
1822
3124
  export const routeParams = {
1823
3125
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1824
3126
  };
1825
3127
 
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.
3128
+ // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
1834
3129
  export const dynamicRoutes = [
1835
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3130
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1836
3131
  ];
1837
3132
 
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.
3133
+ // Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
1841
3134
  ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1842
3135
 
1843
3136
  export const apiPrerender = {
1844
3137
  ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1845
3138
  };
1846
3139
 
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.
3140
+
1856
3141
  export const revalidate = [
1857
3142
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1858
3143
  ];
1859
3144
 
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.
3145
+ // Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
3146
+ export const routeCaches = [
3147
+ ${pages.filter(({ i }) => compiled[i].cache !== void 0).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(",\n ")}
3148
+ ];
3149
+ const __dynCache = new Map();
3150
+ export function invalidateRenderCache(): void {
3151
+ __dynCache.clear();
3152
+ }
3153
+ // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3154
+ const __kvStore = new Map<string, { v: unknown; exp: number }>();
3155
+ // Content collections: src/content/<coll>/*.md scanned once at build time,
3156
+
3157
+ const contentCollections = ${JSON.stringify(scanContentDir(path2.join(root, "src", "content")))};
3158
+ export const kv = {
3159
+ get(key: string): unknown {
3160
+ const e = __kvStore.get(key);
3161
+ if (!e) return undefined;
3162
+ if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
3163
+ return e.v;
3164
+ },
3165
+ set(key: string, value: unknown, ttlSeconds = 300): void {
3166
+ if (__kvStore.size > 1000) {
3167
+ const cutoff = Date.now();
3168
+ for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
3169
+ if (__kvStore.size > 2000) __kvStore.clear();
3170
+ }
3171
+ __kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
3172
+ },
3173
+ del(key: string): void { __kvStore.delete(key); },
3174
+ has(key: string): boolean {
3175
+ const e = __kvStore.get(key);
3176
+ return !!e && e.exp >= Date.now();
3177
+ },
3178
+ };
3179
+ globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
3180
+ globalThis.__rosetackContent = {
3181
+ list: (coll: string, filter?: { tag: string }) => {
3182
+ let items = contentCollections[coll] ?? [];
3183
+ if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
3184
+ return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
3185
+ },
3186
+ rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
3187
+ return buildRss(contentCollections[coll] ?? [], opts);
3188
+ },
3189
+ get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
3190
+ const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
3191
+ if (!e) return null;
3192
+ return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
3193
+ },
3194
+ };
3195
+
3196
+ const v = {
3197
+ validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
3198
+ const errors: Record<string, string> = {};
3199
+ const values: Record<string, unknown> = {};
3200
+ for (const [field, ruleList] of Object.entries(rules)) {
3201
+ let val = body[field];
3202
+ for (const rule of ruleList) {
3203
+ if (val === undefined || val === null || val === "") {
3204
+ if (rule === "required") errors[field] = field + " is required";
3205
+ else if (rule.startsWith("default:")) val = rule.slice(8);
3206
+ continue;
3207
+ }
3208
+ if (rule === "string") val = String(val);
3209
+ else if (rule === "trim") val = String(val).trim();
3210
+ else if (rule === "number") {
3211
+ const num = Number(val);
3212
+ if (Number.isNaN(num)) errors[field] = field + " must be a number";
3213
+ else val = num;
3214
+ } else if (rule === "email") {
3215
+ if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
3216
+ } else if (rule.startsWith("min:")) {
3217
+ const min = Number(rule.slice(4));
3218
+ if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
3219
+ } else if (rule.startsWith("max:")) {
3220
+ const max = Number(rule.slice(4));
3221
+ if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
3222
+ }
3223
+ }
3224
+ values[field] = val;
3225
+ }
3226
+ return { ok: Object.keys(errors).length === 0, errors, values };
3227
+ },
3228
+ };
3229
+
3230
+ const jobs = {
3231
+ _timers: new Map<string, ReturnType<typeof setInterval>>(),
3232
+ every(name: string, seconds: number, fn: () => void | Promise<void>): void {
3233
+ if (this._timers.has(name)) return;
3234
+ const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
3235
+ this._timers.set(name, t as any);
3236
+ },
3237
+ cancel(name: string): void {
3238
+ const t = this._timers.get(name);
3239
+ if (t) { clearInterval(t); this._timers.delete(name); }
3240
+ },
3241
+ cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
3242
+ };
3243
+
3244
+ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
3245
+ const encoder = new TextEncoder();
3246
+ const stream = new ReadableStream({
3247
+ async start(controller) {
3248
+ let closed = false;
3249
+ const send = (event: string, data: unknown) => {
3250
+ if (closed) return;
3251
+ controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
3252
+ };
3253
+ try {
3254
+ await handler(send);
3255
+ } finally {
3256
+ closed = true;
3257
+ try { controller.close(); } catch { }
3258
+ }
3259
+ },
3260
+ });
3261
+ return new Response(stream, {
3262
+ headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
3263
+ });
3264
+ }
3265
+ globalThis.__rosetackExtras = { v, jobs, sse };
3266
+ const auth = {
3267
+ hashPassword(password: string): string {
3268
+ const salt = crypto.randomBytes(16).toString("hex");
3269
+ const hash = crypto.scryptSync(password, salt, 32).toString("hex");
3270
+ return salt + ":" + hash;
3271
+ },
3272
+ verifyPassword(password: string, stored: string): boolean {
3273
+ const [salt, hash] = stored.split(":");
3274
+ if (!salt || !hash) return false;
3275
+ return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
3276
+ },
3277
+ signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
3278
+ const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
3279
+ const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3280
+ return payload + "." + sig;
3281
+ },
3282
+ verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
3283
+ const dot = token.lastIndexOf(".");
3284
+ if (dot < 0) return null;
3285
+ const payload = token.slice(0, dot);
3286
+ const sig = token.slice(dot + 1);
3287
+ const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3288
+ try {
3289
+ if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
3290
+ } catch { return null; }
3291
+ try {
3292
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString());
3293
+ if (data.exp < Date.now()) return null;
3294
+ return data as T;
3295
+ } catch { return null; }
3296
+ },
3297
+ csrfToken(secret: string, sessionId: string): string {
3298
+ return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
3299
+ },
3300
+ verifyCsrf(token: string, secret: string, sessionId: string): boolean {
3301
+ try {
3302
+ return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
3303
+ } catch { return false; }
3304
+ },
3305
+ };
3306
+ globalThis.__rosetackAuth = auth;
3307
+
3308
+ export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3309
+ const hit = kv.get(key);
3310
+ if (hit !== undefined) return hit;
3311
+ const v = await compute();
3312
+ if (v !== undefined) kv.set(key, v, ttlSeconds);
3313
+ return v;
3314
+ }
3315
+ export function isCachedRoute(pathname: string): boolean {
3316
+ return routeCaches.some((r) => matchRoute(r.pattern, pathname));
3317
+ }
3318
+ export function invalidatePath(pathname: string): number {
3319
+ let n = 0;
3320
+ for (const key of [...__dynCache.keys()]) {
3321
+ if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
3322
+ }
3323
+ return n;
3324
+ }
3325
+ export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
3326
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3327
+ if (!cfg) return null;
3328
+ let h = 0x811c9dc5;
3329
+ const c = cookieHeader || '';
3330
+ for (let i = 0; i < c.length; i++) {
3331
+ h ^= c.charCodeAt(i);
3332
+ h = (h * 0x01000193) >>> 0;
3333
+ }
3334
+ const hit = __dynCache.get(pathname + '|' + h.toString(16));
3335
+ return hit && hit.expires > Date.now() ? hit.page : null;
3336
+ }
3337
+ export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
3338
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3339
+ if (!cfg) return renderPage(pathname);
3340
+ let h = 0x811c9dc5;
3341
+ for (let i = 0; i < cookieHeader.length; i++) {
3342
+ h ^= cookieHeader.charCodeAt(i);
3343
+ h = (h * 0x01000193) >>> 0;
3344
+ }
3345
+ const key = pathname + '|' + h.toString(16);
3346
+ const hit = __dynCache.get(key);
3347
+ if (hit && hit.expires > Date.now()) {
3348
+ __dynCache.delete(key);
3349
+ __dynCache.set(key, hit);
3350
+ return hit.page;
3351
+ }
3352
+ // Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
3353
+ if (hit && !hit.refreshing) {
3354
+ hit.refreshing = true;
3355
+ renderPage(pathname).then((fresh: any) => {
3356
+ if (fresh.status === 200 && !fresh.redirect) {
3357
+ __dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
3358
+ } else {
3359
+ __dynCache.delete(key);
3360
+ }
3361
+ }).catch(() => { __dynCache.delete(key); });
3362
+ return hit.page;
3363
+ }
3364
+ const page = await renderPage(pathname);
3365
+ if (page.status === 200 && !page.redirect) {
3366
+ __dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
3367
+ if (__dynCache.size > 300) {
3368
+ __dynCache.delete(__dynCache.keys().next().value as string);
3369
+ }
3370
+ }
3371
+ return page;
3372
+ }
3373
+
3374
+ // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
1866
3375
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1867
3376
 
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).
3377
+ // Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
1881
3378
  export const noJsRoutes = [
1882
3379
  ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1883
3380
  ];
@@ -1886,21 +3383,12 @@ export function isNoJs(pathname) {
1886
3383
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1887
3384
  }
1888
3385
 
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.
3386
+ // P0-2 (bug report): routes that exported "buffer = true".
1895
3387
  export function isBuffered(pathname) {
1896
- return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
3388
+ return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
1897
3389
  }
1898
3390
 
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.
3391
+
1904
3392
  export const routeHeaders = [
1905
3393
  ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1906
3394
  ];
@@ -1910,14 +3398,7 @@ export function headersFor(pathname) {
1910
3398
  return hit ? hit.headers : null;
1911
3399
  }
1912
3400
 
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.
3401
+
1921
3402
  export const cspNonceRoutes = [
1922
3403
  ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1923
3404
  ];
@@ -1926,9 +3407,7 @@ export function cspNonce(pathname) {
1926
3407
  return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1927
3408
  }
1928
3409
 
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).
3410
+ // A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
1932
3411
  function toWebRequest(raw, form) {
1933
3412
  if (raw instanceof Request) return raw;
1934
3413
  const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
@@ -1936,13 +3415,7 @@ function toWebRequest(raw, form) {
1936
3415
  return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1937
3416
  }
1938
3417
 
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.
3418
+
1946
3419
  export async function runMiddleware(rawReq, form) {
1947
3420
  resetRequestContext();
1948
3421
  if (!middleware || !rawReq) return null;
@@ -1954,10 +3427,7 @@ const routes = [
1954
3427
  ${serverRoutes}
1955
3428
  ];
1956
3429
 
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.
3430
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
1961
3431
  const apiRoutes = [
1962
3432
  ${apiRoutes.map(({ info, i }) => {
1963
3433
  const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -1965,19 +3435,40 @@ const apiRoutes = [
1965
3435
  }).join(",\n ")}
1966
3436
  ];
1967
3437
 
1968
- // pages/404.rose (with its layouts) or null -> built-in plain 404
1969
- const notFound = ${notFoundRender};
3438
+ // Not-found pages, deepest segment first: the root 404.rose ('/') and any
3439
+ // pages/<seg>/_notfound.rose, each already composed with its layout chain.
3440
+ // notFoundFor picks the nearest one up the path - an /admin miss answers
3441
+ // the admin 404, a public miss the site's - and notFoundPage is the whole
3442
+ // answer (real 404 status, or the built-in plain 404 when the app has none).
3443
+ const notFoundRoutes = ${notFoundTable};
3444
+ const notFoundFor = (pathname) => {
3445
+ for (const [prefix, render] of notFoundRoutes) {
3446
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
3447
+ }
3448
+ return null;
3449
+ };
3450
+
3451
+ const notFoundFlags = (pathname) => {
3452
+ for (const [prefix, render, flags] of notFoundRoutes) {
3453
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
3454
+ }
3455
+ return null;
3456
+ };
3457
+ const notFoundPage = async (pathname) => {
3458
+ const nf = notFoundFor(pathname);
3459
+ if (nf) {
3460
+ const page = await renderFallback(pathname, nf);
3461
+ // __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
3462
+ return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
3463
+ }
3464
+ return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
3465
+ };
3466
+
1970
3467
 
1971
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1972
3468
  // whose render throws degrades to this instead of failing the response.
1973
3469
  const errorPage = ${errorRender};
1974
3470
 
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.
3471
+
1981
3472
  export function docAttrs(pathname) {
1982
3473
  for (const route of routes) {
1983
3474
  if (!matchRoute(route.pattern, pathname)) continue;
@@ -1987,21 +3478,42 @@ export function docAttrs(pathname) {
1987
3478
  const lang = pathname.split('/')[langIdx];
1988
3479
  if (isLocale(lang)) return { lang, dir: localeDir(lang) };
1989
3480
  }
1990
- break; // matched, but not a localized route (or a bogus locale): the default
3481
+ break;
1991
3482
  }
1992
3483
  return { lang: defaultLocale, dir: localeDir(defaultLocale) };
1993
3484
  }
1994
3485
 
1995
3486
  // Paint a fallback page (404/500) and serialize its state.
1996
3487
  async function renderFallback(pathname, render) {
1997
- const { html, head } = extractHead(await render([], ''));
3488
+ // Split mode: the not-found entry's render is a loader object \u2014 resolve it through getRender (which memoizes the composed function) exactly like.
3489
+ let fn = render;
3490
+ if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
3491
+
3492
+ // { render } once the route's chunk graph is loaded
3493
+ fn = (await fn.load()).render;
3494
+ }
3495
+ const { html, head } = extractHead(await fn([], ''));
1998
3496
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1999
3497
  return { html, state, head, ...docAttrs(pathname) };
2000
3498
  }
2001
3499
 
2002
3500
  export function matchRoute(pattern, pathname) {
3501
+ // Q0 (bug report): one canonical URL per route.
3502
+ pathname = pathname.replace(/\\/+$/, '') || '/';
2003
3503
  const patternParts = pattern.split('/');
2004
3504
  const pathParts = pathname.split('/');
3505
+
3506
+ const last = patternParts[patternParts.length - 1];
3507
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
3508
+ const fixed = patternParts.slice(0, -1);
3509
+ if (pathParts.length < fixed.length) return false;
3510
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
3511
+ for (let i = 0; i < fixed.length; i++) {
3512
+ if (fixed[i].startsWith(':')) continue;
3513
+ if (fixed[i] !== pathParts[i]) return false;
3514
+ }
3515
+ return true;
3516
+ }
2005
3517
  if (patternParts.length !== pathParts.length) return false;
2006
3518
  for (let i = 0; i < patternParts.length; i++) {
2007
3519
  if (patternParts[i].startsWith(':')) continue;
@@ -2010,13 +3522,7 @@ export function matchRoute(pattern, pathname) {
2010
3522
  return true;
2011
3523
  }
2012
3524
 
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.
3525
+ // Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
2020
3526
  function extractHead(rendered) {
2021
3527
  const head = [];
2022
3528
  const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
@@ -2026,18 +3532,7 @@ function extractHead(rendered) {
2026
3532
  return { html, head };
2027
3533
  }
2028
3534
 
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.
3535
+ // Form: the submitted FormData of a progressive-enhancement POST.
2041
3536
  export async function renderPage(pathname, form) {
2042
3537
  clearRequestState();
2043
3538
  for (const route of routes) {
@@ -2045,31 +3540,21 @@ export async function renderPage(pathname, form) {
2045
3540
  const patternParts = route.pattern.split('/');
2046
3541
  const pathParts = pathname.split('/');
2047
3542
  for (let i = 0; i < patternParts.length; i++) {
2048
- if (patternParts[i].startsWith(':')) {
2049
- setState(patternParts[i].slice(1), pathParts[i]);
2050
- }
3543
+ const seg = patternParts[i];
3544
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
3545
+
3546
+
3547
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2051
3548
  }
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
3549
+ // I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
2055
3550
  const langIdx = patternParts.indexOf(':lang');
2056
3551
  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) };
3552
+ return await notFoundPage(pathname);
2059
3553
  }
2060
- // The document's <html lang>/<dir> follow this route's locale
2061
- // (the default's when the route is not localized)
3554
+
3555
+
2062
3556
  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.
3557
+ // The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
2073
3558
  let actionStatus = 0;
2074
3559
  if (form && route.actions) {
2075
3560
  const actionName = form.get('__action') || 'action';
@@ -2081,9 +3566,7 @@ export async function renderPage(pathname, form) {
2081
3566
  if (patch && typeof patch === 'object') {
2082
3567
  for (const key of Object.keys(patch)) {
2083
3568
  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.
3569
+ // An incremental patch is RECORDED, not applied: the render's own state declarations apply.
2087
3570
  if (v instanceof StateDelta) setStateDelta(key, v);
2088
3571
  else setState(key, v);
2089
3572
  }
@@ -2092,6 +3575,11 @@ export async function renderPage(pathname, form) {
2092
3575
  if (err instanceof ActionError) {
2093
3576
  setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
2094
3577
  actionStatus = err.code;
3578
+ } else if (err && err.__rosetack === 'redirect') {
3579
+
3580
+ return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
3581
+ } else if (err && err.__rosetack === 'notFound') {
3582
+ return await notFoundPage(pathname);
2095
3583
  } else {
2096
3584
  throw err;
2097
3585
  }
@@ -2102,32 +3590,46 @@ export async function renderPage(pathname, form) {
2102
3590
  try {
2103
3591
  rendered = extractHead(await route.render([], ''));
2104
3592
  } catch (err) {
3593
+ // The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
3594
+ const signal = err && err.__rosetack;
3595
+ if (signal === 'redirect') {
3596
+ return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
3597
+ }
3598
+ if (signal === 'notFound') {
3599
+ return await notFoundPage(pathname);
3600
+ }
2105
3601
  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) };
3602
+ // F10: in dev the response body carries the real error \u2014 message, file:line and the fix hint.
3603
+ let devDetail = '';
3604
+ if (process.env.rosetack_DEV === '1' && err) {
3605
+ const msg = esc(err instanceof Error ? err.message : String(err));
3606
+ const file = esc(String(err.file || ''));
3607
+ const line = err.line != null ? esc(String(err.line)) : '';
3608
+ const hint = esc(String(err.hint || ''));
3609
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
3610
+ devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
3611
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
3612
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
3613
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
3614
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
3615
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
3616
+ + '</div>';
3617
+ }
3618
+ if (errorPage) {
3619
+ const fb = await renderFallback(pathname, errorPage);
3620
+ return { ...fb, html: fb.html + devDetail, status: 500 };
3621
+ }
3622
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2108
3623
  }
2109
3624
  // __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
3625
  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) };
3626
+ // Csr ( auto since #29): false when the compiler found nothing in the route's chain that needs the client (or the route asserted csr = false) .
3627
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
2125
3628
  }
2126
3629
  }
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) };
3630
+
3631
+
3632
+ return await notFoundPage(pathname);
2131
3633
  }
2132
3634
 
2133
3635
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -2135,21 +3637,20 @@ export async function renderPage(pathname, form) {
2135
3637
  export function canStream(pathname) {
2136
3638
  return routes.some((route) => {
2137
3639
  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
3640
+ // I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
2141
3641
  const langIdx = route.pattern.split('/').indexOf(':lang');
2142
3642
  return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
2143
3643
  });
2144
3644
  }
2145
3645
 
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.
3646
+
3647
+ export function shellOff(pathname) {
3648
+ return routes.some(
3649
+ (route) => route.shell === false && matchRoute(route.pattern, pathname),
3650
+ );
3651
+ }
3652
+
3653
+ // === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
2153
3654
  export function isApi(pathname) {
2154
3655
  return pathname === '/api' || pathname.startsWith('/api/');
2155
3656
  }
@@ -2173,7 +3674,25 @@ export async function handleApi(method, pathname, request) {
2173
3674
  headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
2174
3675
  });
2175
3676
  }
2176
- return toResponse(await fn(request));
3677
+ try {
3678
+ return toResponse(await fn(request));
3679
+ } catch (err) {
3680
+
3681
+ const signal = err && err.__rosetack;
3682
+ if (signal === 'redirect') {
3683
+ return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
3684
+ status: err.status ?? 307,
3685
+ headers: { 'content-type': 'application/json', location: err.path },
3686
+ });
3687
+ }
3688
+ if (signal === 'notFound') {
3689
+ return new Response(JSON.stringify({ error: 'not found' }), {
3690
+ status: 404,
3691
+ headers: { 'content-type': 'application/json' },
3692
+ });
3693
+ }
3694
+ throw err;
3695
+ }
2177
3696
  }
2178
3697
  }
2179
3698
  return new Response(JSON.stringify({ error: 'not found' }), {
@@ -2182,18 +3701,7 @@ export async function handleApi(method, pathname, request) {
2182
3701
  });
2183
3702
  }
2184
3703
 
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).
3704
+ // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
2197
3705
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2198
3706
  clearRequestState();
2199
3707
  for (const route of routes) {
@@ -2201,9 +3709,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2201
3709
  const patternParts = route.pattern.split('/');
2202
3710
  const pathParts = pathname.split('/');
2203
3711
  for (let i = 0; i < patternParts.length; i++) {
2204
- if (patternParts[i].startsWith(':')) {
2205
- setState(patternParts[i].slice(1), pathParts[i]);
2206
- }
3712
+ const seg = patternParts[i];
3713
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
3714
+
3715
+
3716
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2207
3717
  }
2208
3718
  // i18n: an unknown locale must 404 BEFORE the shell flushes - a
2209
3719
  // streamed response cannot change its status afterwards
@@ -2214,37 +3724,103 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2214
3724
  try {
2215
3725
  html = extractHead(await route.render([], '')).html;
2216
3726
  } 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)
3727
+
2220
3728
  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>';
3729
+ // F10: dev carries the real error in the body here too \u2014 the shell
3730
+ // is out, so the detail rides after the error page body.
3731
+ let devDetail = '';
3732
+ if (process.env.rosetack_DEV === '1' && err) {
3733
+ const msg = esc(err instanceof Error ? err.message : String(err));
3734
+ const file = esc(String(err.file || ''));
3735
+ const line = err.line != null ? esc(String(err.line)) : '';
3736
+ const hint = esc(String(err.hint || ''));
3737
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
3738
+ devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
3739
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
3740
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
3741
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
3742
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
3743
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
3744
+ + '</div>';
3745
+ }
3746
+ html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
2222
3747
  }
2223
3748
  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.)
3749
+ // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
2228
3750
  if (route.csr === false) {
2229
3751
  write('</div>\\n</body>\\n</html>');
2230
3752
  return 200;
2231
3753
  }
2232
3754
  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>');
3755
+ // P1-6 (bug report): the JSON data block is embedded in the document.
3756
+ const stateSafe = state.replace(/</g, '\\\\u003c');
3757
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
2234
3758
  return 200;
2235
3759
  }
2236
3760
  }
2237
3761
  return 404;
2238
3762
  }
2239
3763
  `;
2240
- await fs.promises.writeFile(path.join(buildDir, "server-entry.js"), serverEntry);
3764
+ try {
3765
+ const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
3766
+ const uniq = [...new Set(patterns)].sort();
3767
+ const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
3768
+ const paramsOf = (pattern) => (pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
3769
+ const paramSig = uniq.map((p) => {
3770
+ const ps = paramsOf(p);
3771
+ if (!ps.length) return "";
3772
+ return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
3773
+ }).join("");
3774
+ const outDirTs = path2.join(root, "src", ".rosetack");
3775
+ await fs3.promises.mkdir(outDirTs, { recursive: true });
3776
+ const srcLines = [
3777
+ "// GENERATED by rosetack build - do not edit.",
3778
+ "export type RoutePath = " + lit + ";",
3779
+ "export const routePatterns = " + JSON.stringify(uniq) + " as const;",
3780
+ "export type RouteParams = {",
3781
+ paramSig,
3782
+ "};",
3783
+ "/** Build a URL from a route pattern and its params. */",
3784
+ "export function url(",
3785
+ " path: RoutePath,",
3786
+ " params: RouteParams[keyof RouteParams] = {} as never,",
3787
+ "): string {",
3788
+ " let out = path as string;",
3789
+ " for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
3790
+ " out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
3791
+ " }",
3792
+ " return out;",
3793
+ "}"
3794
+ ].join("\n") + "\n";
3795
+ await fs3.promises.writeFile(path2.join(outDirTs, "routes.ts"), srcLines);
3796
+ } catch {
3797
+ }
3798
+ await fs3.promises.writeFile(path2.join(buildDir, "server-entry.js"), serverEntry);
3799
+ await esbuild.build({
3800
+ entryPoints: [path2.join(buildDir, "server-entry.js")],
3801
+ bundle: true,
3802
+ outfile: path2.join(outDir, "server.js"),
3803
+ format: "esm",
3804
+ platform: "node",
3805
+ write: true,
3806
+ ...TS_LOADER
3807
+ });
2241
3808
  await esbuild.build({
2242
- entryPoints: [path.join(buildDir, "server-entry.js")],
3809
+ entryPoints: [(() => {
3810
+ const here = path2.dirname(fileURLToPath(import.meta.url));
3811
+ for (const cand of [path2.join(here, "..", "cli", "prod-server.ts"), path2.join(here, "..", "src", "cli", "prod-server.ts")]) {
3812
+ if (fs3.existsSync(cand)) return cand;
3813
+ }
3814
+ return path2.join(here, "..", "cli", "prod-server.ts");
3815
+ })()],
2243
3816
  bundle: true,
2244
- outfile: path.join(outDir, "server.js"),
3817
+ outfile: path2.join(outDir, "prod.mjs"),
2245
3818
  format: "esm",
2246
3819
  platform: "node",
2247
3820
  write: true,
3821
+ banner: {
3822
+ js: "import { createRequire } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = createRequire(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);"
3823
+ },
2248
3824
  ...TS_LOADER
2249
3825
  });
2250
3826
  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");
@@ -2254,7 +3830,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2254
3830
  const vitalsBlock = vitalsOn ? `
2255
3831
  // the app asked for web-vitals - measure once, at boot, and let the
2256
3832
  // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2257
- reportVitals;
3833
+ reportVitals();
2258
3834
  ` : "";
2259
3835
  const hasLang = infos.some((i) => i.pattern.includes(":lang"));
2260
3836
  const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
@@ -2262,26 +3838,24 @@ reportVitals;
2262
3838
  // logical properties both read it). A route with no [lang] segment
2263
3839
  // returns to the default locale, and a bogus segment falls back to it
2264
3840
  // too, exactly like the server's docAttrs.
3841
+ // Only when this container IS the document's app root. A mount
3842
+ // (dist/mount.js) renders into a foreign page, whose language and
3843
+ // direction belong to the host, not to the mounted route.
2265
3844
  const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
2266
3845
  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');
3846
+ if (container === document.getElementById('app')) {
3847
+ const docLang = known && seg ? seg : __defLocale;
3848
+ document.documentElement.lang = docLang;
3849
+ const docDir = localeDir(docLang);
3850
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
3851
+ else document.documentElement.removeAttribute('dir');
3852
+ }
2272
3853
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2273
3854
  const clientEntry = `
2274
3855
  ${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.
3856
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
3857
+
3858
+ // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
2285
3859
  setLocales(${clientLocalesJson}, '${defaultLocale}');
2286
3860
  setLocalePacks(${JSON.stringify(packed)});
2287
3861
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
@@ -2291,10 +3865,7 @@ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2291
3865
  // reportVitals alive through minification and tree-shaking; the call is one
2292
3866
  // statement at boot, before the first render.
2293
3867
  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.
3868
+ // The two pack doors, re-exported for an app that wants to warm a language before its visitor asks for it (ensureLocale) or to feed a dictionary.
2298
3869
  export { ensureLocale, loadLocale } from './runtime.js';
2299
3870
  ${vitalsBlock}
2300
3871
 
@@ -2302,14 +3873,7 @@ const routes = [
2302
3873
  ${clientRoutes}
2303
3874
  ];
2304
3875
 
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.
3876
+ // === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
2313
3877
  const loadChain = async (loaders) => {
2314
3878
  const mods = await Promise.all(loaders.map((load) => load()));
2315
3879
  let expr = (closes, children) => mods[0].render(closes, children);
@@ -2325,36 +3889,62 @@ const getRender = async (route) => {
2325
3889
  return (route.render ??= (await route.load()).render);
2326
3890
  };
2327
3891
 
2328
- // pages/404.rose (with its layouts) or null -> built-in plain 404
2329
- const notFound = ${notFoundRender};
3892
+ // Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
3893
+ const notFoundRoutes = ${notFoundTable};
3894
+ const notFoundFor = (pathname) => {
3895
+ for (const [prefix, render] of notFoundRoutes) {
3896
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
3897
+ }
3898
+ return null;
3899
+ };
2330
3900
 
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.
3901
+ // Pages/500.rose (with its layouts) or null -> built-in plain 500: a route whose render throws on the client degrades to this instead of breaking.
2334
3902
  const errorPage = ${errorRender};
2335
3903
 
2336
3904
  // Paint a fallback page (404/500) into the container, wired like any render.
2337
- async function paintFallback(container, page, builtin) {
2338
- resetEffects();
2339
- clearRequestState();
3905
+ async function paintFallback(container, page, builtin, keepState = false) {
3906
+ if (!keepState) __navReset(container);
2340
3907
  clearMounts(); // a failed render leaves stale mounts behind
2341
3908
  // inline mode passes the render itself; split mode passes a loader
2342
3909
  const render = page ? await getRender(page) : null;
2343
3910
  if (render) {
2344
3911
  const closes = [];
2345
- const html = await render(closes, '');
2346
- container.innerHTML = html;
2347
- wire(container, closes);
2348
- bindEvents(container);
2349
- flushMounts();
3912
+ await __withOwner(container, async () => {
3913
+ const html = await render(closes, '');
3914
+ container.innerHTML = html;
3915
+ wire(container, closes);
3916
+ bindEvents(container);
3917
+ flushMounts();
3918
+ });
2350
3919
  return;
2351
3920
  }
2352
3921
  container.innerHTML = builtin;
2353
3922
  }
2354
3923
 
3924
+
3925
+ export async function startNotFound(container, pathname) {
3926
+ const el = document.getElementById('__rosetack_state');
3927
+ if (el) resumeState(el.textContent);
3928
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
3929
+ }
3930
+
2355
3931
  export function matchRoute(pattern, pathname) {
3932
+ // Q0 (bug report): one canonical URL per route.
3933
+ pathname = pathname.replace(/\\/+$/, '') || '/';
2356
3934
  const patternParts = pattern.split('/');
2357
3935
  const pathParts = pathname.split('/');
3936
+
3937
+ const last = patternParts[patternParts.length - 1];
3938
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
3939
+ const fixed = patternParts.slice(0, -1);
3940
+ if (pathParts.length < fixed.length) return false;
3941
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
3942
+ for (let i = 0; i < fixed.length; i++) {
3943
+ if (fixed[i].startsWith(':')) continue;
3944
+ if (fixed[i] !== pathParts[i]) return false;
3945
+ }
3946
+ return true;
3947
+ }
2358
3948
  if (patternParts.length !== pathParts.length) return false;
2359
3949
  for (let i = 0; i < patternParts.length; i++) {
2360
3950
  if (patternParts[i].startsWith(':')) continue;
@@ -2363,85 +3953,64 @@ export function matchRoute(pattern, pathname) {
2363
3953
  return true;
2364
3954
  }
2365
3955
 
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).
3956
+ // === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
2387
3957
  let prefetchMode = ${JSON.stringify(prefetchMode)};
2388
3958
  export function setPrefetchMode(mode) { prefetchMode = mode; }
2389
3959
  const PREFETCH_BUDGET = 8;
2390
3960
  const PREFETCH_MAX_CACHED = 4;
2391
- const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
3961
+ const prefetchCache = new Map();
2392
3962
  let prefetchQueue = Promise.resolve();
2393
3963
  let prefetchPending = 0;
2394
3964
 
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.
3965
+
2401
3966
  async function applyParams(route, pathname) {
2402
3967
  const patternParts = route.pattern.split('/');
2403
3968
  const pathParts = pathname.split('/');
2404
3969
  for (let i = 0; i < patternParts.length; i++) {
2405
- if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
3970
+ const seg = patternParts[i];
3971
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
3972
+
3973
+
3974
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2406
3975
  }
2407
3976
  const langIdx = patternParts.indexOf(':lang');
2408
3977
  if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
2409
3978
  }
2410
3979
 
3980
+
3981
+ function __netOk() {
3982
+ const c = navigator.connection;
3983
+ if (!c) return true;
3984
+ if (c.saveData) return false;
3985
+ const t = c.effectiveType;
3986
+ return t !== 'slow-2g' && t !== '2g';
3987
+ }
3988
+
2411
3989
  export function prefetch(pathname, source = 'hover') {
2412
3990
  if (prefetchMode === 'off') return;
2413
3991
  if (prefetchMode === 'hover' && source !== 'hover') return;
2414
3992
  if (prefetchMode === 'viewport' && source !== 'viewport') return;
3993
+ if (!__netOk()) return; // save-data / 2g: no bytes before the click
2415
3994
  if (prefetchCache.has(pathname)) return;
2416
- if (pathname === location.pathname) return; // already here: nothing to prefetch
3995
+ if (pathname === location.pathname) return;
2417
3996
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
2418
3997
  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.
3998
+ if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
2424
3999
  const qi = pathname.indexOf('?');
2425
4000
  const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
2426
4001
  const p = prefetchQueue.then(async () => {
2427
4002
  try {
2428
4003
  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
4004
+ // The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
2434
4005
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
2435
4006
  await applyParams(route, pathname); // a packed locale's dictionary lands before the render
2436
4007
  const closes = [];
2437
- const render = await getRender(route); // split mode: loads the route's chunk here
4008
+ const render = await getRender(route);
2438
4009
  const html = await render(closes, '');
2439
4010
  return { html, closes };
2440
4011
  });
2441
4012
  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)
4013
+ prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
2445
4014
  while (prefetchCache.size > PREFETCH_MAX_CACHED) {
2446
4015
  const oldest = prefetchCache.keys().next().value;
2447
4016
  if (prefetchCache.get(oldest) instanceof Promise) break;
@@ -2449,7 +4018,7 @@ export function prefetch(pathname, source = 'hover') {
2449
4018
  }
2450
4019
  return entry;
2451
4020
  } catch {
2452
- prefetchCache.delete(pathname); // failed: the next hover retries
4021
+ prefetchCache.delete(pathname);
2453
4022
  return null;
2454
4023
  } finally {
2455
4024
  setPrefetchOverride(null);
@@ -2462,13 +4031,10 @@ export function prefetch(pathname, source = 'hover') {
2462
4031
  }
2463
4032
 
2464
4033
  export function prefetchStats() {
2465
- return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
4034
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
2466
4035
  }
2467
4036
 
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.
4037
+ // One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
2472
4038
  const DELEGATED = ['click', 'input', 'change', 'submit'];
2473
4039
  function bindEvents(container) {
2474
4040
  if (container.__rosetack_bound) return;
@@ -2485,48 +4051,76 @@ function bindEvents(container) {
2485
4051
  }
2486
4052
  }
2487
4053
 
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 });
4054
+ // === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
4055
+ async function postForm(body, container, pathname) {
4056
+
4057
+ const box = container || document.getElementById('app');
4058
+ const route = pathname || location.pathname;
4059
+ const res = await fetch(route, { method: 'POST', body });
2496
4060
  const html = await res.text();
2497
4061
  const doc = new DOMParser().parseFromString(html, 'text/html');
2498
4062
  const next = doc.getElementById('app');
2499
4063
  const st = doc.getElementById('__rosetack_state');
2500
4064
  const paint = () => {
2501
- const container = document.getElementById('app');
2502
- adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
4065
+ adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
2503
4066
  };
2504
4067
  if (document.startViewTransition) document.startViewTransition(paint);
2505
4068
  else paint();
2506
4069
  }
2507
4070
 
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.
4071
+ // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
2511
4072
  export async function $action(name, e) {
2512
4073
  if (e && e.preventDefault) e.preventDefault();
2513
4074
  const body = new FormData();
2514
4075
  body.append('__action', name);
2515
- return postForm(body);
4076
+ // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
4077
+ const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
4078
+ return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
2516
4079
  }
4080
+ // F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
4081
+ setActionDispatcher($action);
2517
4082
 
2518
4083
  export { postForm };
2519
4084
 
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.
4085
+ // The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
2525
4086
  export { serializeState };
2526
4087
 
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.
4088
+ // Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
4089
+
4090
+
4091
+ function __ownsDoc(container) {
4092
+ return container === document.getElementById('app');
4093
+ }
4094
+ function __navReset(container) {
4095
+ if (__ownsDoc(container)) {
4096
+ resetEffects();
4097
+ clearRequestState();
4098
+ } else {
4099
+ resetContainerFx(container);
4100
+ }
4101
+ }
4102
+ // Attribute everything a render creates (state keys, effects, onCleanups) to
4103
+ // its container. The document path sets no owner and keeps the global sets.
4104
+ async function __withOwner(container, fn) {
4105
+ if (__ownsDoc(container)) return fn();
4106
+ setFxOwner(container);
4107
+ try {
4108
+ return await fn();
4109
+ } finally {
4110
+ setFxOwner(null);
4111
+ }
4112
+ }
4113
+ // View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
4114
+ async function __swap(container, html) {
4115
+ const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
4116
+ if (typeof document.startViewTransition === 'function' && !reduce) {
4117
+ const vt = document.startViewTransition(() => { container.innerHTML = html; });
4118
+ await vt.updateCallbackDone.catch(() => {});
4119
+ } else {
4120
+ container.innerHTML = html;
4121
+ }
4122
+ }
4123
+
2530
4124
  export async function start(container, pathname, initial) {
2531
4125
  clearMounts(); // stale mounts from a failed render never fire
2532
4126
  if (initial) {
@@ -2535,114 +4129,123 @@ export async function start(container, pathname, initial) {
2535
4129
  }
2536
4130
  for (const route of routes) {
2537
4131
  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)
4132
+ // I18n: an unknown locale paints the 404 page, same as the server (before the prefetch check: a cached entry for a bogus locale is discarded).
2541
4133
  const langIdx = route.pattern.split('/').indexOf(':lang');
2542
4134
  ${langDirBlock}
2543
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
4135
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2544
4136
  return;
2545
4137
  }
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.
4138
+ // Prefetched on hover/focus/touch: the render already ran, so paint its HTML and adopt its signal entries - events then patch the very nodes we.
2549
4139
  let hit = initial ? undefined : prefetchCache.get(pathname);
2550
4140
  if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2551
4141
  if (hit) {
2552
- prefetchCache.delete(pathname); // single-use: the next hover refetches
2553
- resetEffects();
4142
+ prefetchCache.delete(pathname);
4143
+ __navReset(container);
2554
4144
  restoreState(hit.state);
2555
- container.innerHTML = hit.html;
2556
- wire(container, hit.closes);
4145
+ await __swap(container, hit.html);
4146
+ await __withOwner(container, () => {
4147
+ wire(container, hit.closes);
4148
+ bindEvents(container);
4149
+ hit.mounts.forEach((fn) => fn());
4150
+ adoptCleanups(hit.cleanups);
4151
+ });
4152
+ return;
4153
+ }
4154
+ if (!initial) __navReset(container);
4155
+ let broken = false;
4156
+ let signal = null;
4157
+ await __withOwner(container, async () => {
4158
+ await applyParams(route, pathname);
4159
+ const closes = [];
4160
+ let html;
4161
+ try {
4162
+ const render = await getRender(route);
4163
+ html = await render(closes, '');
4164
+ } catch (err) {
4165
+
4166
+ if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
4167
+ if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
4168
+
4169
+
4170
+ console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
4171
+ broken = true;
4172
+ return;
4173
+ }
4174
+ if (!initial) await __swap(container, html);
4175
+ wire(container, closes);
2557
4176
  bindEvents(container);
2558
- hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2559
- adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
4177
+ flushMounts();
4178
+ });
4179
+ if (signal === 'notFound') {
4180
+ // T17: a client-side render of a $data route without a prefetch entry has no data source (the server fills the context bag) - the correct.
4181
+ if (!initial) { try { location.assign(pathname); return; } catch { } }
4182
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2560
4183
  return;
2561
4184
  }
2562
- if (!initial) {
2563
- resetEffects();
2564
- clearRequestState();
4185
+ if (signal) {
4186
+ location.href = signal;
4187
+ return;
2565
4188
  }
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
4189
+ if (broken) {
2575
4190
  await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2576
- return;
2577
4191
  }
2578
- if (!initial) container.innerHTML = html;
2579
- wire(container, closes);
2580
- bindEvents(container);
2581
- flushMounts();
2582
4192
  return;
2583
4193
  }
2584
4194
  }
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>');
4195
+ // Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
4196
+ ${hasLang ? ` // the same app-root gate as above - a mount never touches the
4197
+ // host document's language or direction.
4198
+ if (container === document.getElementById('app')) {
4199
+ document.documentElement.lang = __defLocale;
4200
+ document.documentElement.removeAttribute('dir');
4201
+ }` : ""}
4202
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2591
4203
  }
2592
4204
 
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();
4205
+ // Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
4206
+ export async function adopt(container, html, stateJson, pathname) {
4207
+
4208
+
4209
+ const route0 = pathname || location.pathname;
4210
+ __navReset(container);
2602
4211
  clearMounts(); // stale mounts from a failed render never fire
2603
4212
  resumeState(stateJson);
2604
4213
  container.innerHTML = html;
2605
- // keep the embedded state in sync so a later SPA-fallback check agrees
4214
+
2606
4215
  const st = document.getElementById('__rosetack_state');
2607
4216
  if (st) st.textContent = stateJson;
2608
4217
  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();
4218
+ if (matchRoute(route.pattern, route0)) {
4219
+ await __withOwner(container, async () => {
4220
+ await applyParams(route, route0);
4221
+ const closes = [];
4222
+ try {
4223
+ const render = await getRender(route);
4224
+ await render(closes, '');
4225
+ } catch {
4226
+
4227
+
4228
+ return;
4229
+ }
4230
+ wire(container, closes);
4231
+ bindEvents(container);
4232
+ flushMounts();
4233
+ });
2623
4234
  return;
2624
4235
  }
2625
4236
  }
2626
4237
  }
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.
4238
+ // === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
2636
4239
  setRefreshHook(async () => {
2637
4240
  prefetchCache.delete(location.pathname);
2638
4241
  await start(document.getElementById('app'), location.pathname, false);
2639
4242
  });
2640
4243
  `;
2641
- await fs.promises.writeFile(path.join(buildDir, "client-entry.js"), clientEntry);
4244
+ await fs3.promises.writeFile(path2.join(buildDir, "client-entry.js"), clientEntry);
2642
4245
  if (split) {
2643
- await fs.promises.rm(path.join(outDir, "chunks"), { recursive: true, force: true });
4246
+ await fs3.promises.rm(path2.join(outDir, "chunks"), { recursive: true, force: true });
2644
4247
  await esbuild.build({
2645
- entryPoints: [path.join(buildDir, "client-entry.js")],
4248
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
2646
4249
  bundle: true,
2647
4250
  format: "esm",
2648
4251
  platform: "browser",
@@ -2656,9 +4259,9 @@ setRefreshHook(async () => {
2656
4259
  });
2657
4260
  } else {
2658
4261
  await esbuild.build({
2659
- entryPoints: [path.join(buildDir, "client-entry.js")],
4262
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
2660
4263
  bundle: true,
2661
- outfile: path.join(outDir, "client.js"),
4264
+ outfile: path2.join(outDir, "client.js"),
2662
4265
  format: "esm",
2663
4266
  platform: "browser",
2664
4267
  minify: true,
@@ -2666,36 +4269,54 @@ setRefreshHook(async () => {
2666
4269
  ...TS_LOADER
2667
4270
  });
2668
4271
  }
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
- );
4272
+ await fs3.promises.writeFile(path2.join(outDir, "mount.js"), MOUNT_ENTRY);
4273
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
4274
+ const publicDir = path2.join(root, "public");
4275
+ if (fs3.existsSync(publicDir)) {
4276
+ await fs3.promises.cp(publicDir, path2.join(outDir, "public"), { recursive: true });
4277
+ const favicon = path2.join(publicDir, "favicon.ico");
4278
+ if (fs3.existsSync(favicon)) await fs3.promises.copyFile(favicon, path2.join(outDir, "favicon.ico"));
2678
4279
  }
2679
4280
  console.log("rosetack zero-JS report:");
2680
4281
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
4282
+ const warnGroups = /* @__PURE__ */ new Map();
2681
4283
  for (const { info, i } of pages) {
2682
4284
  if (!routeShipsNoJs(infos, compiled, i)) continue;
2683
4285
  for (const ci of [i, ...layoutsOf(infos, i)]) {
2684
4286
  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}`);
4287
+ let g = warnGroups.get(w);
4288
+ if (!g) {
4289
+ g = { why: w, files: /* @__PURE__ */ new Map() };
4290
+ warnGroups.set(w, g);
4291
+ }
4292
+ const file = path2.relative(root, infos[ci].filePath).replace(/\\/g, "/");
4293
+ let routes = g.files.get(file);
4294
+ if (!routes) {
4295
+ routes = /* @__PURE__ */ new Set();
4296
+ g.files.set(file, routes);
4297
+ }
4298
+ routes.add(info.routePath);
2686
4299
  }
2687
4300
  }
2688
4301
  }
4302
+ for (const g of warnGroups.values()) {
4303
+ const allRoutes = /* @__PURE__ */ new Set();
4304
+ for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
4305
+ const parts = [...g.files.entries()].sort((a, b) => b[1].size - a[1].size).map(([file, routes]) => `${file} (${routes.size === 1 ? [...routes][0] : `${routes.size} routes`})`);
4306
+ const shown = parts.slice(0, 4).join(", ");
4307
+ const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
4308
+ console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
4309
+ }
2689
4310
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2690
4311
  }
2691
4312
  async function scanRoseFiles(root) {
2692
- const pagesDir = path.join(root, "src", "pages");
2693
- if (!fs.existsSync(pagesDir)) return [];
4313
+ const pagesDir = path2.join(root, "src", "pages");
4314
+ if (!fs3.existsSync(pagesDir)) return [];
2694
4315
  async function scan(dir) {
2695
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4316
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
2696
4317
  const files = [];
2697
4318
  for (const entry of entries) {
2698
- const full = path.join(dir, entry.name);
4319
+ const full = path2.join(dir, entry.name);
2699
4320
  if (entry.isDirectory()) files.push(...await scan(full));
2700
4321
  else if (entry.name.endsWith(".rose")) files.push(full);
2701
4322
  }
@@ -2704,13 +4325,13 @@ async function scanRoseFiles(root) {
2704
4325
  return scan(pagesDir);
2705
4326
  }
2706
4327
  async function scanComponentFiles(root) {
2707
- const compDir = path.join(root, "src", "components");
2708
- if (!fs.existsSync(compDir)) return [];
4328
+ const compDir = path2.join(root, "src", "components");
4329
+ if (!fs3.existsSync(compDir)) return [];
2709
4330
  async function scan(dir) {
2710
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4331
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
2711
4332
  const files = [];
2712
4333
  for (const entry of entries) {
2713
- const full = path.join(dir, entry.name);
4334
+ const full = path2.join(dir, entry.name);
2714
4335
  if (entry.isDirectory()) files.push(...await scan(full));
2715
4336
  else if (entry.name.endsWith(".rose")) files.push(full);
2716
4337
  }
@@ -2719,26 +4340,32 @@ async function scanComponentFiles(root) {
2719
4340
  return scan(compDir);
2720
4341
  }
2721
4342
  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);
4343
+ const layoutDir = path2.dirname(layoutPath);
4344
+ const pageDir = path2.dirname(pagePath);
4345
+ return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
2725
4346
  }
2726
4347
  function getRouteInfo(filePath, root) {
2727
- const pagesDir = path.join(root, "src", "pages");
2728
- const relative3 = path.relative(pagesDir, filePath).replace(/\\/g, "/");
4348
+ const pagesDir = path2.join(root, "src", "pages");
4349
+ const relative3 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
2729
4350
  const withoutExt = relative3.replace(/\.rose$/, "");
2730
- const base = path.posix.basename(withoutExt);
4351
+ const base = path2.posix.basename(withoutExt);
2731
4352
  const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2732
4353
  const isLayout = !isComponent && base === "_layout";
2733
- const isNotFound = !isComponent && base === "404";
4354
+ const isNotFound = !isComponent && (base === "404" || base === "_notfound");
2734
4355
  const isError = !isComponent && base === "500";
2735
4356
  const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2736
4357
  const isMiddleware = !isComponent && withoutExt === "_middleware";
2737
- let parts = withoutExt.split("/").filter((p) => p !== "_layout");
4358
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
2738
4359
  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
- );
4360
+ const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
4361
+ const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
4362
+ const routeParts = parts.map((part) => {
4363
+ const optional = OPTIONAL_CATCH_ALL.exec(part);
4364
+ if (optional) return `**${optional[1]}`;
4365
+ const catchAll = CATCH_ALL.exec(part);
4366
+ if (catchAll) return `*${catchAll[1]}`;
4367
+ return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
4368
+ });
2742
4369
  let routePath;
2743
4370
  if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2744
4371
  routePath = "/";
@@ -2749,7 +4376,13 @@ function getRouteInfo(filePath, root) {
2749
4376
  filePath,
2750
4377
  routePath,
2751
4378
  pattern: routePath,
2752
- paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
4379
+ paramNames: parts.flatMap((p) => {
4380
+ const optional = OPTIONAL_CATCH_ALL.exec(p);
4381
+ if (optional) return [optional[1]];
4382
+ const catchAll = CATCH_ALL.exec(p);
4383
+ if (catchAll) return [catchAll[1]];
4384
+ return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
4385
+ }),
2753
4386
  isLayout,
2754
4387
  isNotFound,
2755
4388
  isError,
@@ -2763,25 +4396,43 @@ function capitalize(s) {
2763
4396
  }
2764
4397
 
2765
4398
  // src/cli/shell.ts
2766
- import * as fs2 from "fs";
2767
- import * as path2 from "path";
4399
+ import * as fs4 from "fs";
4400
+ import * as path3 from "path";
2768
4401
  import * as esbuild2 from "esbuild";
2769
- var OUT_DIR = path2.join(process.cwd(), "dist");
4402
+ var OUT_DIR = path3.join(process.cwd(), "dist");
2770
4403
  var styleCache = null;
2771
4404
  function getStyles() {
2772
- const file = path2.join(OUT_DIR, "styles.css");
4405
+ const file = path3.join(OUT_DIR, "styles.css");
2773
4406
  try {
2774
- const st = fs2.statSync(file);
4407
+ const st = fs4.statSync(file);
2775
4408
  if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
2776
- styleCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
4409
+ styleCache = { mtimeMs: st.mtimeMs, source: fs4.readFileSync(file, "utf-8") };
2777
4410
  }
2778
4411
  return styleCache.source;
2779
4412
  } catch {
2780
4413
  return "";
2781
4414
  }
2782
4415
  }
2783
- var BOOTSTRAP = esbuild2.transformSync(`
2784
- const __app = document.getElementById('app');
4416
+ var BOOTSTRAP_SOURCE = `
4417
+ // shell = false: the document's SSR content sits directly in <body> - no
4418
+ // #app wrapper, no demo styles, so a real theme's CSS owns the document from
4419
+ // the first byte (and a JS-less visitor never sees either). The bundle still
4420
+ // runs, and it still needs its container: wrap the content once, here, before
4421
+ // any theme script executes (module scripts run before DOMContentLoaded). The
4422
+ // wrapper is a plain unstyled div, so the re-parent is visually inert; every
4423
+ // later path - adoption, navigation, forms - is then the ordinary one.
4424
+ let __app = document.getElementById('app');
4425
+ if (!__app) {
4426
+ __app = document.createElement('div');
4427
+ __app.id = 'app';
4428
+ // scripts stay outside the wrapper, exactly where the dressed document
4429
+ // keeps them: the state element and the running module must survive a
4430
+ // navigation's innerHTML swap (they are the document's, not the route's).
4431
+ for (const node of Array.from(document.body.children)) {
4432
+ if (node.tagName !== 'SCRIPT') __app.appendChild(node);
4433
+ }
4434
+ document.body.appendChild(__app);
4435
+ }
2785
4436
  // Native View Transitions around client-side navigation (progressive:
2786
4437
  // browsers without the API navigate normally, no polyfill, no CSS required).
2787
4438
  function __navigate(pathname) {
@@ -2844,13 +4495,15 @@ document.addEventListener('submit', (e) => {
2844
4495
  e.preventDefault();
2845
4496
  postForm(new FormData(f));
2846
4497
  });
2847
- // Dev seam: the live signal graph, readable as JSON. Two callers, one
4498
+ // Dev seam: the live signal graph, readable as JSON. Three callers, one
2848
4499
  // implementation: the dev server's reload bridge snapshots it before a
2849
4500
  // 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() };
4501
+ // and the devtools extension (devtools/) reads it the same way - the signal
4502
+ // graph plus the prefetch counters, which is the whole observable state of a
4503
+ // running page. Both are DIRECT references (no wrapper arrow): the names take
4504
+ // no arguments, so the call is identical and every document that carries the
4505
+ // bundle pays eleven bytes for the pair instead of forty.
4506
+ window.__rosetack = { state: serializeState, prefetch: prefetchStats };
2854
4507
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
2855
4508
  // If the document was rendered for a DIFFERENT route (a static-file server's
2856
4509
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
@@ -2869,21 +4522,59 @@ if (__resumed) {
2869
4522
  __state = Object.assign(__state, __resumed);
2870
4523
  __state.__route = __route;
2871
4524
  }
2872
- if (__resumed) {
4525
+ // A NOT-FOUND document (the server stamps __notFound onto its state) boots
4526
+ // into the app's own 404 route: the URL matches no route - or a catch-all
4527
+ // whose resolver threw notFound(), whose key sits null in the resumed state
4528
+ // and whose template would dereference it into a 500. startNotFound paints
4529
+ // the not-found route from the resumed state instead (zero requests).
4530
+ if (__state.__notFound) {
4531
+ startNotFound(__app, window.location.pathname);
4532
+ } else if (__resumed) {
2873
4533
  start(__app, window.location.pathname);
2874
4534
  } else if (__state.__route === window.location.pathname) {
2875
4535
  start(__app, window.location.pathname, true);
2876
4536
  } else {
2877
4537
  start(__app, window.location.pathname);
2878
4538
  }
2879
- `, { minify: true }).code;
2880
- var EXTERNAL_BOOTSTRAP = `
2881
- import { start, prefetch, postForm } from '/client.js';
2882
- ${BOOTSTRAP}`;
4539
+ `;
4540
+ var BOOTSTRAP_CACHE = null;
4541
+ function bootstrap() {
4542
+ if (BOOTSTRAP_CACHE === null) {
4543
+ if (globalThis.__rosetack_SKIP_MINIFY) {
4544
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
4545
+ } else {
4546
+ try {
4547
+ BOOTSTRAP_CACHE = esbuild2.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
4548
+ } catch {
4549
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
4550
+ }
4551
+ }
4552
+ }
4553
+ return BOOTSTRAP_CACHE;
4554
+ }
4555
+ var EXTERNAL_BOOTSTRAP_CACHE = null;
4556
+ function externalBootstrap() {
4557
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `
4558
+ import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';
4559
+ ${bootstrap()}`;
4560
+ return EXTERNAL_BOOTSTRAP_CACHE;
4561
+ }
2883
4562
  function inlineScript(client) {
4563
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
4564
+ let body = client;
4565
+ let aliases = "";
4566
+ if (m) {
4567
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
4568
+ aliases = m[1].split(",").map((pair) => {
4569
+ const parts = pair.split(" as ").map((x) => x.trim());
4570
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
4571
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
4572
+ }).join("");
4573
+ }
2884
4574
  return `
2885
- ${client}
2886
- ${BOOTSTRAP}`;
4575
+ ${body}
4576
+ ${aliases}
4577
+ ${bootstrap()}`;
2887
4578
  }
2888
4579
  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
4580
  var STYLES = `
@@ -2942,33 +4633,43 @@ function mergeHeadBlocks(blocks) {
2942
4633
  function clientScriptTag(client, nonce = "") {
2943
4634
  const n = nonce ? ` nonce="${nonce}"` : "";
2944
4635
  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>`;
4636
+ <script type="module"${n}>${externalBootstrap()}</script>`;
2946
4637
  }
2947
- function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
4638
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
2948
4639
  const clientTag = clientScriptTag(client, nonce);
2949
4640
  const mergedHead = mergeHeadBlocks(head);
4641
+ const headStamped = nonce ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs) => /\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`) : mergedHead;
4642
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ""}`;
4643
+ let bodyAttrs = "";
4644
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag, attrs) => {
4645
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, "");
4646
+ if (tag === "html") htmlAttrs = clean;
4647
+ else bodyAttrs = clean;
4648
+ return "";
4649
+ });
2950
4650
  const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
2951
4651
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
2952
4652
  ${FAVICON}`;
2953
- const headTags = mergedHead ? `
2954
- ${mergedHead}` : "";
4653
+ const headTags = headClean ? `
4654
+ ${headClean}` : "";
2955
4655
  const styleTag = styles ? `
2956
4656
  <style>${styles}</style>` : "";
4657
+ const stateSafe = stateJson.replace(/</g, "\\u003c");
2957
4658
  const jsTail = js ? `
2958
- <script type="application/json" id="__rosetack_state">${stateJson}</script>
4659
+ <script type="application/json" id="__rosetack_state">${stateSafe}</script>
2959
4660
  ${clientTag}` : "";
2960
- const open = js ? '<div id="app">' : "";
2961
- const close = js ? "</div>" : "";
2962
- const shellStyles = js ? `
4661
+ const open = js && shell ? '<div id="app">' : "";
4662
+ const close = js && shell ? "</div>" : "";
4663
+ const shellStyles = js && shell ? `
2963
4664
  <style>${STYLES_MIN}</style>` : "";
2964
4665
  return `<!DOCTYPE html>
2965
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
4666
+ <html${htmlAttrs}>
2966
4667
  <head>
2967
4668
  <meta charset="UTF-8">
2968
4669
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
2969
4670
  ${titleTag}${shellStyles}${styleTag}
2970
4671
  </head>
2971
- <body>
4672
+ <body${bodyAttrs}>
2972
4673
  ${open}${ssrHtml}${close}${jsTail}
2973
4674
  </body>
2974
4675
  </html>`;
@@ -2977,50 +4678,50 @@ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(),
2977
4678
  // src/cli/test.ts
2978
4679
  var GRAFTED = ["document", "Node", "NodeFilter", "FormData", "DOMParser", "location", "fetch", "Event", "CustomEvent", "MutationObserver", "requestAnimationFrame"];
2979
4680
  function projectRootOf(file) {
2980
- let dir = path3.dirname(path3.resolve(file));
4681
+ let dir = path4.dirname(path4.resolve(file));
2981
4682
  for (; ; ) {
2982
- if (fs3.existsSync(path3.join(dir, "src", "pages"))) return dir;
2983
- const parent = path3.dirname(dir);
4683
+ if (fs5.existsSync(path4.join(dir, "src", "pages"))) return dir;
4684
+ const parent = path4.dirname(dir);
2984
4685
  if (parent === dir) throw new Error(`rosetack/test: ${file} is not inside a project (no src/pages found above it)`);
2985
4686
  dir = parent;
2986
4687
  }
2987
4688
  }
2988
4689
  function routeOf(file, root) {
2989
- const rel = path3.relative(path3.join(root, "src", "pages"), path3.resolve(file)).replace(/\\/g, "/").replace(/\.rose$/, "");
4690
+ const rel = path4.relative(path4.join(root, "src", "pages"), path4.resolve(file)).replace(/\\/g, "/").replace(/\.rose$/, "");
2990
4691
  if (rel === "index") return "/";
2991
4692
  const segs = rel.split("/").map((s) => s.startsWith("[") && s.endsWith("]") ? `:${s.slice(1, -1)}` : s);
2992
4693
  return "/" + segs.join("/");
2993
4694
  }
2994
4695
  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);
4696
+ fs5.mkdirSync(to, { recursive: true });
4697
+ for (const e of fs5.readdirSync(from, { withFileTypes: true })) {
4698
+ const src = path4.join(from, e.name);
4699
+ const dst = path4.join(to, e.name);
2999
4700
  if (e.isDirectory()) copyTree(src, dst);
3000
- else fs3.copyFileSync(src, dst);
4701
+ else fs5.copyFileSync(src, dst);
3001
4702
  }
3002
4703
  }
3003
4704
  function propAttrs(props) {
3004
4705
  return Object.entries(props).map(([k, v]) => `${k}={${JSON.stringify(v) ?? "undefined"}}`).join(" ");
3005
4706
  }
3006
4707
  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}`);
4708
+ const target = path4.resolve(file);
4709
+ if (!fs5.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
3009
4710
  const root = projectRootOf(target);
3010
- const rel = path3.relative(root, target).replace(/\\/g, "/");
4711
+ const rel = path4.relative(root, target).replace(/\\/g, "/");
3011
4712
  const isComponent = rel.startsWith("src/components/");
3012
- const dir = opts.dir ?? fs3.mkdtempSync(path3.join(os.tmpdir(), "rosetack-test-"));
4713
+ const dir = opts.dir ?? fs5.mkdtempSync(path4.join(os.tmpdir(), "rosetack-test-"));
3013
4714
  for (const item of ["src", "public"]) {
3014
- const from = path3.join(root, item);
3015
- if (fs3.existsSync(from)) copyTree(from, path3.join(dir, item));
4715
+ const from = path4.join(root, item);
4716
+ if (fs5.existsSync(from)) copyTree(from, path4.join(dir, item));
3016
4717
  }
3017
4718
  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));
4719
+ const from = path4.join(root, item);
4720
+ if (fs5.existsSync(from)) fs5.copyFileSync(from, path4.join(dir, item));
3020
4721
  }
3021
4722
  let route;
3022
4723
  if (isComponent) {
3023
- const specifier = path3.relative(path3.join(dir, "src", "pages"), path3.join(dir, rel)).replace(/\\/g, "/");
4724
+ const specifier = path4.relative(path4.join(dir, "src", "pages"), path4.join(dir, rel)).replace(/\\/g, "/");
3024
4725
  const attrs = propAttrs(opts.props ?? {});
3025
4726
  const page = `<script>
3026
4727
  import Target from '${specifier}';
@@ -3030,27 +4731,27 @@ async function test(file, opts = {}) {
3030
4731
  <Target ${attrs} />
3031
4732
  </template>
3032
4733
  `;
3033
- fs3.writeFileSync(path3.join(dir, "src", "pages", "__rosetack_test.rose"), page);
4734
+ fs5.writeFileSync(path4.join(dir, "src", "pages", "__rosetack_test.rose"), page);
3034
4735
  route = "/__rosetack_test";
3035
4736
  } else {
3036
4737
  route = opts.route ?? routeOf(target, root);
3037
4738
  }
3038
- const outDir = path3.join(dir, "dist");
4739
+ const outDir = path4.join(dir, "dist");
3039
4740
  await buildProject(dir, outDir);
3040
- const serverUrl = pathToFileURL2(path3.join(outDir, "server.js")).href;
3041
- const clientUrl = pathToFileURL2(path3.join(outDir, "client.js")).href;
4741
+ const serverUrl = pathToFileURL2(path4.join(outDir, "server.js")).href;
4742
+ const clientUrl = pathToFileURL2(path4.join(outDir, "client.js")).href;
3042
4743
  const mod = await import(serverUrl);
3043
- const clientSource = fs3.readFileSync(path3.join(outDir, "client.js"), "utf-8");
4744
+ const clientSource = fs5.readFileSync(path4.join(outDir, "client.js"), "utf-8");
3044
4745
  let styles = "";
3045
4746
  try {
3046
- styles = fs3.readFileSync(path3.join(outDir, "styles.css"), "utf-8");
4747
+ styles = fs5.readFileSync(path4.join(outDir, "styles.css"), "utf-8");
3047
4748
  } catch {
3048
4749
  }
3049
4750
  if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
3050
4751
  if (!opts.dir && !opts.keep) {
3051
4752
  process.once("exit", () => {
3052
4753
  try {
3053
- fs3.rmSync(dir, { recursive: true, force: true });
4754
+ fs5.rmSync(dir, { recursive: true, force: true });
3054
4755
  } catch {
3055
4756
  }
3056
4757
  });
@@ -3061,15 +4762,16 @@ async function test(file, opts = {}) {
3061
4762
  state: page.state ? JSON.parse(page.state) : {},
3062
4763
  head: page.head ?? [],
3063
4764
  csr: page.csr,
4765
+ shell: page.shell,
3064
4766
  lang: page.lang ?? "en",
3065
4767
  dir: page.dir ?? "",
3066
- document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? ""),
4768
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? "", "", page.shell !== false),
3067
4769
  redirect
3068
4770
  });
3069
4771
  const toRequest = (pathname, req = {}, body) => {
3070
4772
  const headers = new Headers(req.headers ?? {});
3071
4773
  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 });
4774
+ return new Request(`http://localhost${pathname}`, { method: req.method ?? "GET", headers, body: body ?? void 0 });
3073
4775
  };
3074
4776
  const request = async (pathname, req, body) => {
3075
4777
  if (mod.middleware) {
@@ -3106,9 +4808,9 @@ async function test(file, opts = {}) {
3106
4808
  globalThis.fetch = async (url, init) => {
3107
4809
  const pathname = String(url).startsWith("http") ? new URL(String(url)).pathname : String(url);
3108
4810
  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")) };
4811
+ const file2 = path4.join(outDir, pathname.slice(1));
4812
+ if (!fs5.existsSync(file2)) return { ok: false, json: async () => ({}) };
4813
+ return { ok: true, json: async () => JSON.parse(fs5.readFileSync(file2, "utf-8")) };
3112
4814
  }
3113
4815
  requests++;
3114
4816
  const next = await request(pathname, req, init?.body);