rosetack 0.1.2 → 0.1.3

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 (54) 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 +818 -445
  11. package/dist-cli/edge.mjs +115 -39
  12. package/dist-cli/rosetack.mjs +1078 -529
  13. package/dist-cli/runtime.mjs +115 -34
  14. package/dist-cli/test.mjs +875 -464
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/edge.ts +69 -61
  18. package/src/cli/index.ts +243 -328
  19. package/src/cli/prompt.ts +4 -1
  20. package/src/cli/shell.ts +67 -69
  21. package/src/cli/test.ts +9 -70
  22. package/src/compiler/index.ts +921 -851
  23. package/src/runtime/index.ts +155 -158
  24. package/src/types/rosetack.d.ts +16 -66
  25. package/templates/admin/package.json +14 -0
  26. package/templates/admin/rosetack.config.js +1 -0
  27. package/templates/admin/src/pages/_middleware.rose +33 -0
  28. package/templates/admin/src/pages/api/items.rose +37 -0
  29. package/templates/admin/src/pages/api/login.rose +25 -0
  30. package/templates/admin/src/pages/index.rose +79 -0
  31. package/templates/api/package.json +14 -0
  32. package/templates/api/rosetack.config.js +1 -0
  33. package/templates/api/src/pages/api/health.rose +7 -0
  34. package/templates/api/src/pages/api/items.rose +46 -0
  35. package/templates/api/src/pages/api/login.rose +24 -0
  36. package/templates/api/src/pages/index.rose +25 -0
  37. package/templates/blog/package.json +14 -0
  38. package/templates/blog/rosetack.config.js +1 -0
  39. package/templates/blog/src/pages/404.rose +2 -0
  40. package/templates/blog/src/pages/_layout.rose +42 -0
  41. package/templates/blog/src/pages/_middleware.rose +74 -0
  42. package/templates/blog/src/pages/admin.rose +85 -0
  43. package/templates/blog/src/pages/api/login.rose +46 -0
  44. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  45. package/templates/blog/src/pages/api/posts.rose +72 -0
  46. package/templates/blog/src/pages/index.rose +31 -0
  47. package/templates/blog/src/pages/post/[id].rose +36 -0
  48. package/templates/site/package.json +14 -0
  49. package/templates/site/rosetack.config.js +1 -0
  50. package/templates/site/src/pages/404.rose +2 -0
  51. package/templates/site/src/pages/_layout.rose +40 -0
  52. package/templates/site/src/pages/about.rose +6 -0
  53. package/templates/site/src/pages/index.rose +13 -0
  54. package/templates/site/src/pages/pricing.rose +8 -0
@@ -216,21 +216,50 @@ function skipTemplate(src, i) {
216
216
  }
217
217
  return j;
218
218
  }
219
+ function skipLiteral(src, i) {
220
+ const q = src[i];
221
+ if (q === '"' || q === "'") return skipQuoted(src, i);
222
+ if (q === "`") return skipTemplate(src, i);
223
+ if (q !== "/") return null;
224
+ if (src[i + 1] === "/" || src[i + 1] === "*") return null;
225
+ let b = i - 1;
226
+ while (b >= 0 && /\s/.test(src[b])) b--;
227
+ if (b >= 0) {
228
+ if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
229
+ const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
230
+ if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
231
+ }
232
+ }
233
+ let j = i + 1;
234
+ let inClass = false;
235
+ while (j < src.length) {
236
+ const c = src[j];
237
+ if (c === "\\") {
238
+ j += 2;
239
+ continue;
240
+ }
241
+ if (c === "\n") return null;
242
+ if (inClass) {
243
+ if (c === "]") inClass = false;
244
+ } else if (c === "[") inClass = true;
245
+ else if (c === "/") {
246
+ j++;
247
+ break;
248
+ }
249
+ j++;
250
+ }
251
+ if (j > src.length) return null;
252
+ while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
253
+ return j;
254
+ }
219
255
  function stripComments(src) {
220
256
  let out = "";
221
257
  let i = 0;
222
258
  while (i < src.length) {
223
- const q = src[i];
224
- if (q === '"' || q === "'") {
225
- const end = skipQuoted(src, i);
226
- out += src.slice(i, end);
227
- i = end;
228
- continue;
229
- }
230
- if (q === "`") {
231
- const end = skipTemplate(src, i);
232
- out += src.slice(i, end);
233
- i = end;
259
+ const lit = skipLiteral(src, i);
260
+ if (lit !== null) {
261
+ out += src.slice(i, lit);
262
+ i = lit;
234
263
  continue;
235
264
  }
236
265
  if (src.startsWith("//", i)) {
@@ -253,6 +282,167 @@ function stripComments(src) {
253
282
  }
254
283
  return out;
255
284
  }
285
+ function stripGuardedBranches(src) {
286
+ const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
287
+ const ws = (i2) => {
288
+ while (i2 < src.length && /\s/.test(src[i2])) i2++;
289
+ return i2;
290
+ };
291
+ const ternaryColon = (q) => {
292
+ let depth = 0;
293
+ let i2 = q + 1;
294
+ while (i2 < src.length) {
295
+ const c = src[i2];
296
+ const lit = skipLiteral(src, i2);
297
+ if (lit !== null) {
298
+ i2 = lit;
299
+ continue;
300
+ }
301
+ if (c === "(" || c === "[" || c === "{") depth++;
302
+ else if (c === ")" || c === "]" || c === "}") {
303
+ depth--;
304
+ if (depth < 0) return -1;
305
+ } else if (depth === 0 && c === ":") return i2;
306
+ else if (depth === 0 && c === "?") {
307
+ const inner = ternaryColon(i2);
308
+ if (inner < 0) return -1;
309
+ i2 = inner + 1;
310
+ continue;
311
+ }
312
+ i2++;
313
+ }
314
+ return -1;
315
+ };
316
+ const exprEnd = (i2) => {
317
+ let depth = 0;
318
+ while (i2 < src.length) {
319
+ const c = src[i2];
320
+ const lit = skipLiteral(src, i2);
321
+ if (lit !== null) {
322
+ i2 = lit;
323
+ continue;
324
+ }
325
+ if (c === "(" || c === "[" || c === "{") depth++;
326
+ else if (c === ")" || c === "]" || c === "}") {
327
+ if (depth === 0) return i2;
328
+ depth--;
329
+ } else if (depth === 0 && (c === "," || c === ";")) return i2;
330
+ else if (depth === 0 && c === "?") {
331
+ const inner = ternaryColon(i2);
332
+ if (inner < 0) return src.length;
333
+ i2 = inner + 1;
334
+ continue;
335
+ }
336
+ i2++;
337
+ }
338
+ return src.length;
339
+ };
340
+ const braceEnd = (b) => {
341
+ let depth = 0;
342
+ let i2 = b;
343
+ while (i2 < src.length) {
344
+ const c = src[i2];
345
+ const lit = skipLiteral(src, i2);
346
+ if (lit !== null) {
347
+ i2 = lit;
348
+ continue;
349
+ }
350
+ if (c === "{") depth++;
351
+ else if (c === "}") {
352
+ depth--;
353
+ if (depth === 0) return i2;
354
+ }
355
+ i2++;
356
+ }
357
+ return src.length;
358
+ };
359
+ const stmtEnd = (i2) => {
360
+ let depth = 0;
361
+ while (i2 < src.length) {
362
+ const c = src[i2];
363
+ const lit = skipLiteral(src, i2);
364
+ if (lit !== null) {
365
+ i2 = lit;
366
+ continue;
367
+ }
368
+ if (c === "(" || c === "[" || c === "{") depth++;
369
+ else if (c === ")" || c === "]" || c === "}") {
370
+ if (depth === 0) return i2;
371
+ depth--;
372
+ } else if (depth === 0 && (c === ";" || c === "\n")) return i2;
373
+ i2++;
374
+ }
375
+ return src.length;
376
+ };
377
+ const isIfGuard = (src2, at) => {
378
+ let b = at - 1;
379
+ while (b >= 0 && /\s/.test(src2[b])) b--;
380
+ if (b < 0 || src2[b] !== "(") return false;
381
+ b--;
382
+ while (b >= 0 && /\s/.test(src2[b])) b--;
383
+ return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
384
+ };
385
+ const blanks = [];
386
+ let i = 0;
387
+ while (i < src.length) {
388
+ const lit = skipLiteral(src, i);
389
+ if (lit !== null) {
390
+ i = lit;
391
+ continue;
392
+ }
393
+ GUARD.lastIndex = i;
394
+ const m = GUARD.exec(src);
395
+ if (!m) {
396
+ i++;
397
+ continue;
398
+ }
399
+ const browserAfter = m[1] === "!==";
400
+ const j = ws(i + m[0].length);
401
+ const two = src.slice(j, j + 2);
402
+ if (two === "&&" && browserAfter) {
403
+ blanks.push([j + 2, exprEnd(j + 2)]);
404
+ } else if (two === "||" && !browserAfter) {
405
+ blanks.push([j + 2, exprEnd(j + 2)]);
406
+ } else if (src[j] === "?") {
407
+ const colon = ternaryColon(j);
408
+ if (colon < 0) {
409
+ if (browserAfter) blanks.push([j + 1, src.length]);
410
+ } else if (browserAfter) {
411
+ blanks.push([j + 1, colon]);
412
+ } else {
413
+ blanks.push([colon + 1, exprEnd(colon + 1)]);
414
+ }
415
+ } else if (src[j] === ")" && isIfGuard(src, i)) {
416
+ let bodyEnd;
417
+ const k = ws(j + 1);
418
+ if (src[k] === "{") {
419
+ bodyEnd = braceEnd(k);
420
+ if (browserAfter) blanks.push([k + 1, bodyEnd]);
421
+ } else {
422
+ bodyEnd = stmtEnd(k);
423
+ if (browserAfter) blanks.push([k, bodyEnd]);
424
+ }
425
+ const after = ws(bodyEnd + 1);
426
+ if (src.startsWith("else", after)) {
427
+ const e = ws(after + 4);
428
+ if (src[e] === "{") {
429
+ const close = braceEnd(e);
430
+ if (!browserAfter) blanks.push([e + 1, close]);
431
+ } else {
432
+ const stop = stmtEnd(e);
433
+ if (!browserAfter) blanks.push([e, stop]);
434
+ }
435
+ }
436
+ }
437
+ i = j;
438
+ }
439
+ if (blanks.length === 0) return src;
440
+ const out = [...src];
441
+ for (const [a, b] of blanks) {
442
+ for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
443
+ }
444
+ return out.join("");
445
+ }
256
446
  function scriptOf(source) {
257
447
  return source.match(COMPONENT_RE)?.[1] ?? null;
258
448
  }
@@ -363,8 +553,9 @@ function scanSlotDecls(filePath) {
363
553
  } catch {
364
554
  return [];
365
555
  }
366
- const noBlocks = src.replace(STYLE_RE, "");
367
- const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
556
+ const noScript = src.replace(COMPONENT_RE, "");
557
+ const noBlocks = noScript.replace(STYLE_RE, "");
558
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
368
559
  const out = [];
369
560
  for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
370
561
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
@@ -432,6 +623,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
432
623
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
433
624
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
434
625
  const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
626
+ const ownRuntimeImports = new Set(
627
+ [...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))
628
+ );
629
+ const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
630
+ const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
631
+ ` : "";
435
632
  return {
436
633
  ssr: "",
437
634
  client: "",
@@ -440,19 +637,19 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
440
637
  guardName: null,
441
638
  style: "",
442
639
  hasParams: false,
443
- api: `import { getContext, $query } from './runtime.js';
444
- ${rewriteRoseImports(`${hoisted.imports}
640
+ api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
445
641
  ${hoisted.rest}`, "ssr").trim()}`,
446
642
  apiMethods,
447
643
  hasPrerender,
448
644
  usesContext: usesContext2
449
645
  };
450
646
  }
451
- const sourceNoHead = source.replace(HEAD_RE, "");
647
+ const sourceNoScript = source.replace(COMPONENT_RE, "");
648
+ const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
452
649
  const styleMatch = sourceNoHead.match(STYLE_RE);
453
650
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
454
651
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
455
- const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
652
+ const scriptMatch = source.match(COMPONENT_RE);
456
653
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
457
654
  const rawScript = roseResolved.script;
458
655
  const roseImports = roseResolved.imports;
@@ -512,8 +709,11 @@ ${hoisted.rest}`, "ssr").trim()}`,
512
709
  }
513
710
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
514
711
  const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
712
+ const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
713
+ const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
515
714
  const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
516
715
  const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
716
+ const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
517
717
  if (csr === false) {
518
718
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
519
719
  if (dead) {
@@ -589,21 +789,22 @@ ${hoisted.rest}`, "ssr").trim()}`,
589
789
  if (!needsClient) {
590
790
  const codeOnly = stripComments(source);
591
791
  const scriptCodeOnly = stripComments(rawScript);
792
+ const scriptScannable = stripGuardedBranches(scriptCodeOnly);
592
793
  if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
593
794
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
594
795
  }
595
796
  if (/javascript:/i.test(codeOnly)) {
596
797
  jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
597
798
  }
598
- if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
799
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
599
800
  jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
600
801
  }
601
- 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)) {
802
+ 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)) {
602
803
  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");
603
804
  }
604
805
  }
605
806
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
606
- const headContent = source.match(HEAD_RE)?.[1] ?? "";
807
+ const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
607
808
  const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
608
809
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
609
810
  const decls = extractDecls(script);
@@ -643,13 +844,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
643
844
  const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
644
845
  const wired = wireEventBindings(templateCalled, actionNames);
645
846
  const eventBindings = wired.bindings;
646
- const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
647
847
  const stateKeys = decls.map((d) => d.name);
648
848
  const comps = new Map(roseImports.map((r) => {
649
849
  const abs = path.resolve(path.dirname(filePath), r.specifier);
650
850
  const hit = registry.get(abs);
651
851
  return [r.name, { index: hit.index, slots: hit.slots }];
652
852
  }));
853
+ const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
854
+ assertKnownDirectives(ssrTemplate, filePath);
653
855
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
654
856
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
655
857
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -679,7 +881,9 @@ ${cleanScript}
679
881
  usesContext,
680
882
  revalidate,
681
883
  csr,
884
+ shell,
682
885
  buffer,
886
+ controlSignal,
683
887
  prefetch,
684
888
  vitals,
685
889
  bundle,
@@ -1033,6 +1237,108 @@ function compileHead(head) {
1033
1237
  flush();
1034
1238
  return out;
1035
1239
  }
1240
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
1241
+ function assertKnownDirectives(template, filePath) {
1242
+ const rawRanges = [];
1243
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
1244
+ let raw;
1245
+ while (raw = RAW_OPEN.exec(template)) {
1246
+ const tag = raw[1].toLowerCase();
1247
+ const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
1248
+ const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
1249
+ const end = gt < 0 ? template.length : gt + 1;
1250
+ rawRanges.push([raw.index, end]);
1251
+ RAW_OPEN.lastIndex = end;
1252
+ }
1253
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
1254
+ let note;
1255
+ while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
1256
+ rawRanges.sort((a, b) => a[0] - b[0]);
1257
+ const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
1258
+ const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
1259
+ let m;
1260
+ while (m = DIRECTIVE_RE.exec(template)) {
1261
+ if (inRaw(m.index)) continue;
1262
+ const [, sigil, word] = m;
1263
+ if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
1264
+ if (sigil === "/") {
1265
+ throw new RoseError(
1266
+ "E-TEMPLATE",
1267
+ `${filePath}: {/${word}} does not close anything`,
1268
+ { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
1269
+ );
1270
+ }
1271
+ if (word === "else") {
1272
+ throw new RoseError(
1273
+ "E-TEMPLATE",
1274
+ `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1275
+ { file: filePath, line: lineAt(template, m), hint: "nest a second {#if}: {#if cond}A{/if}{#if !cond}B{/if} - the negation of the first condition IS the else" }
1276
+ );
1277
+ }
1278
+ throw new RoseError(
1279
+ "E-TEMPLATE",
1280
+ `${filePath}: {:${word}} is not a rosetack directive`,
1281
+ { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary} - and there is no {:else}: nest a second {#if} with the negated condition" }
1282
+ );
1283
+ }
1284
+ const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
1285
+ while (m = OPENER_RE.exec(template)) {
1286
+ if (inRaw(m.index)) continue;
1287
+ const [, kind, head] = m;
1288
+ if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
1289
+ throw new RoseError(
1290
+ "E-TEMPLATE",
1291
+ `${filePath}: {#each ${head.trim()}} is missing its item name`,
1292
+ { 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)" }
1293
+ );
1294
+ }
1295
+ const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
1296
+ const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
1297
+ let depth = 1;
1298
+ let i = m.index + m[0].length;
1299
+ for (; ; ) {
1300
+ OPEN_RE.lastIndex = i;
1301
+ CLOSE_RE.lastIndex = i;
1302
+ const nextOpen = OPEN_RE.exec(template);
1303
+ const nextClose = CLOSE_RE.exec(template);
1304
+ if (!nextClose) break;
1305
+ if (nextOpen && nextOpen.index < nextClose.index) {
1306
+ i = nextOpen.index + nextOpen[0].length;
1307
+ continue;
1308
+ }
1309
+ i = nextClose.index + nextClose[0].length;
1310
+ if (--depth === 0) break;
1311
+ }
1312
+ if (depth !== 0) {
1313
+ throw new RoseError(
1314
+ "E-TEMPLATE",
1315
+ `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
1316
+ { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
1317
+ );
1318
+ }
1319
+ }
1320
+ }
1321
+ function rewriteQuotedExprAttrs(template, comps) {
1322
+ const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
1323
+ return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
1324
+ if (comps.has(name) || !/\{/.test(attrs)) return tag;
1325
+ const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
1326
+ if (!/\{/.test(value) || value.includes("`")) return whole;
1327
+ const spans = templateExprSpans(value);
1328
+ if (spans.length === 0) return whole;
1329
+ let expr = "";
1330
+ let last = 0;
1331
+ for (const s of spans) {
1332
+ if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
1333
+ expr += (expr ? " + " : "") + `(${s.expr})`;
1334
+ last = s.end + 1;
1335
+ }
1336
+ if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
1337
+ return `${attr}={${expr}}`;
1338
+ });
1339
+ return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
1340
+ });
1341
+ }
1036
1342
  function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
1037
1343
  let result = "";
1038
1344
  let remaining = template;
@@ -1052,6 +1358,25 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1052
1358
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
1053
1359
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
1054
1360
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
1361
+ const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
1362
+ const rawHit = rawOpenRe.exec(remaining);
1363
+ if (rawHit && earliest && rawHit.index < earliest.index) {
1364
+ const tag = rawHit[1].toLowerCase();
1365
+ const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
1366
+ const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
1367
+ const end = gt < 0 ? remaining.length : gt + 1;
1368
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1369
+ remaining = remaining.substring(end);
1370
+ continue;
1371
+ }
1372
+ const noteAt = remaining.indexOf("<!--");
1373
+ if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
1374
+ const noteEnd = remaining.indexOf("-->", noteAt + 4);
1375
+ const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
1376
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1377
+ remaining = remaining.substring(end);
1378
+ continue;
1379
+ }
1055
1380
  if (!earliest) {
1056
1381
  result += emitChunk(remaining, acc, closes, scope);
1057
1382
  break;
@@ -1443,7 +1768,8 @@ function compileSlot(acc) {
1443
1768
  return `${acc} += String(children);
1444
1769
  `;
1445
1770
  }
1446
- 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';`;
1771
+ 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, slotBlockMark, redirect, notFound } from './runtime.js';`;
1772
+ var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1447
1773
  function propsCode(props) {
1448
1774
  if (props.length === 0) return "";
1449
1775
  return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
@@ -1455,16 +1781,7 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1455
1781
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1456
1782
  return { o, fn };
1457
1783
  };
1458
- const __slotBlock = (closes, sl, name, pairs) => {
1459
- const hit = __slot(sl, name, pairs);
1460
- const idx = closes.length;
1461
- closes.push(() => {
1462
- if (!hit) return null;
1463
- const c = [];
1464
- return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
1465
- });
1466
- return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1467
- };`;
1784
+ const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
1468
1785
  function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1469
1786
  const headCode = headFn ? `
1470
1787
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -1489,9 +1806,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1489
1806
  ${script}
1490
1807
  ${stateDeclsCode}
1491
1808
  ${dataDeclsCode}
1492
- // The incremental patches of the action that produced THIS response,
1493
- // applied to the state the declarations above just established (a no-op on
1494
- // every path that is not a server action's re-render - see the runtime).
1809
+
1495
1810
  ${isComponent ? "" : "applyStateDeltas();"}
1496
1811
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1497
1812
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
@@ -1501,6 +1816,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1501
1816
  }
1502
1817
  function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1503
1818
  const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1819
+ const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
1504
1820
  const headCode = headFn ? `
1505
1821
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1506
1822
  __html += headMark(closes, __head);` : "";
@@ -1510,7 +1826,9 @@ ${RUNTIME_IMPORTS}
1510
1826
  ${imports}
1511
1827
 
1512
1828
  ${exports}
1513
-
1829
+ ${clientSetState ? `
1830
+ ${clientSetState}
1831
+ ` : ""}
1514
1832
  ${namedSlots ? SLOT_HELPER : ""}
1515
1833
 
1516
1834
  export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
@@ -1533,6 +1851,7 @@ var routeShipsNoJs = (infos, compiled, i) => {
1533
1851
  if (compiled[i].needsClient) return false;
1534
1852
  return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1535
1853
  };
1854
+ var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
1536
1855
  function buildReport(infos, compiled) {
1537
1856
  return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
1538
1857
  if (routeShipsNoJs(infos, compiled, i)) {
@@ -1543,6 +1862,48 @@ function buildReport(infos, compiled) {
1543
1862
  return `${info.routePath} client JS ${why}${forced}`;
1544
1863
  });
1545
1864
  }
1865
+ var MOUNT_ENTRY = `
1866
+ import { start, postForm } from '/client.js';
1867
+
1868
+ for (const el of document.querySelectorAll('[data-rosetack]')) {
1869
+ const route = el.getAttribute('data-rosetack');
1870
+ const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
1871
+ const parsed = new DOMParser().parseFromString(doc, 'text/html');
1872
+ // A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
1873
+ const app = parsed.getElementById('app');
1874
+ if (app) {
1875
+ el.innerHTML = app.innerHTML;
1876
+ } else {
1877
+ for (const node of Array.from(parsed.body.children)) {
1878
+ if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
1879
+ }
1880
+ }
1881
+ // start() resumes from #__rosetack_state (zero hydration), so the state
1882
+
1883
+ const state = parsed.getElementById('__rosetack_state');
1884
+ if (state) el.appendChild(state);
1885
+
1886
+ const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
1887
+ await start(el, route, rendered === route);
1888
+ if (state) state.remove();
1889
+
1890
+ el.addEventListener('click', (e) => {
1891
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
1892
+ if (!a || !el.contains(a)) return;
1893
+ e.preventDefault();
1894
+ el.setAttribute('data-rosetack', a.getAttribute('href'));
1895
+ start(el, a.getAttribute('href'), false);
1896
+ });
1897
+ // Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
1898
+ el.addEventListener('submit', (e) => {
1899
+ const f = e.target;
1900
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
1901
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
1902
+ e.preventDefault();
1903
+ postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
1904
+ });
1905
+ }
1906
+ `;
1546
1907
  async function buildProject(root, outDir) {
1547
1908
  await fs.promises.mkdir(outDir, { recursive: true });
1548
1909
  const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
@@ -1644,9 +2005,7 @@ async function buildProject(root, outDir) {
1644
2005
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1645
2006
  if (runtimePlugins.length > 0) {
1646
2007
  const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
1647
- await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
1648
- // Bundled into dist/server.js: these hooks run per request on every server
1649
- // (Node, dev/preview, edge). Transform hooks already ran at build time.
2008
+ await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
1650
2009
  import config from ${JSON.stringify(configRel)};
1651
2010
 
1652
2011
  const list = Array.isArray(config) ? config : [];
@@ -1675,8 +2034,34 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1675
2034
  await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1676
2035
  }
1677
2036
  }
1678
- const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1679
- const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi);
2037
+ 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) => {
2038
+ const rank = (pattern) => {
2039
+ const segs = pattern.split("/");
2040
+ return [
2041
+ segs.filter((s) => s.startsWith("**")).length,
2042
+ segs.filter((s) => s.startsWith("*")).length,
2043
+ segs.filter((s) => s.startsWith(":")).length
2044
+ ];
2045
+ };
2046
+ const ra = rank(a.info.pattern);
2047
+ const rb = rank(b.info.pattern);
2048
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2049
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2050
+ });
2051
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
2052
+ const rank = (pattern) => {
2053
+ const segs = pattern.split("/");
2054
+ return [
2055
+ segs.filter((s) => s.startsWith("**")).length,
2056
+ segs.filter((s) => s.startsWith("*")).length,
2057
+ segs.filter((s) => s.startsWith(":")).length
2058
+ ];
2059
+ };
2060
+ const ra = rank(a.info.pattern);
2061
+ const rb = rank(b.info.pattern);
2062
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2063
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2064
+ });
1680
2065
  const compose = (idx) => {
1681
2066
  let expr = `render_${idx}`;
1682
2067
  for (const i of layoutsOf(infos, idx)) {
@@ -1707,8 +2092,16 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1707
2092
  const named = [actionImports, guardImport].filter(Boolean).join(", ");
1708
2093
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1709
2094
  }).join("\n");
1710
- const nfIdx = infos.findIndex((info) => info.isNotFound);
1711
- const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
2095
+ const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
2096
+ const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
2097
+ const dir = path.posix.dirname(rel);
2098
+ const prefix = dir === "." ? "/" : "/" + dir;
2099
+ const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
2100
+ return { prefix, render: split ? loaderOf(i) : compose(i), flags };
2101
+ }).sort((a, b) => b.prefix.length - a.prefix.length);
2102
+ const notFoundTable = `[
2103
+ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
2104
+ ]`;
1712
2105
  const errIdx = infos.findIndex((info) => info.isError);
1713
2106
  const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
1714
2107
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
@@ -1732,9 +2125,11 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1732
2125
  }
1733
2126
  }
1734
2127
  const csrFlag = routeNoJs(i) ? ", csr: false" : "";
2128
+ const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
1735
2129
  const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
2130
+ const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
1736
2131
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1737
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
2132
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
1738
2133
  }).join(",\n ");
1739
2134
  const serverEntry = `
1740
2135
  ${serverImports}
@@ -1746,12 +2141,7 @@ const __pluginHooks = [];
1746
2141
  const __hasRequestHooks = false;
1747
2142
  const __hasResponseHooks = false;`}
1748
2143
 
1749
- // The runtime plugin hooks. onRequest runs before routing and
1750
- // middleware and may short-circuit the request with its own Response; onResponse
1751
- // runs once the response exists and may replace it. Both are no-ops when the
1752
- // project declares no runtime hooks. A throwing hook is logged and skipped -
1753
- // the request continues - so a broken logging plugin can never take a site
1754
- // down (a build-time transform, by contrast, fails loudly).
2144
+
1755
2145
  export async function runRequestHooks(ctx) {
1756
2146
  for (const p of __pluginHooks) {
1757
2147
  if (!p.onRequest) continue;
@@ -1779,32 +2169,20 @@ export async function runResponseHooks(ctx, res) {
1779
2169
  return out;
1780
2170
  }
1781
2171
 
1782
- // The servers read these to skip building the hook context entirely when no
1783
- // hook exists - the hot path pays nothing for the feature.
2172
+
2173
+
1784
2174
  export const hasRequestHooks = __hasRequestHooks;
1785
2175
  export const hasResponseHooks = __hasResponseHooks;
1786
2176
 
1787
- // P0-1: the query of the request being rendered, for $query(). The servers
1788
- // call this before every render (stream, buffered, POST, api) with the parsed
1789
- // query string; routing itself matches the pathname, which is what fixed the
1790
- // query-404. A render with no query (the build's prerender, the ISR
1791
- // background pass) passes {} explicitly - the bag is per request, so a stale
1792
- // one must never leak into the next.
2177
+ // P0-1: the query of the request being rendered, for $query().
1793
2178
  export function setQuery(query) {
1794
2179
  setRequestQuery(query || {});
1795
2180
  }
1796
2181
 
1797
- // i18n: the dictionaries baked at build time from
1798
- // src/locales/*.json. A route segment named [lang] is the locale: the value
1799
- // must name one of these dictionaries, and $t resolves keys against it.
2182
+
1800
2183
  setLocales(${localesJson}, '${defaultLocale}');
1801
2184
 
1802
- // The store transport. Under "rosetack serve" every worker is its
1803
- // own process with its own dist/server.js module, so a $store write must
1804
- // travel: this worker -> primary -> every other worker. process.send exists
1805
- // only inside cluster workers, so a single-process runner (dev, preview,
1806
- // the edge adapter) keeps the transport null and $store stays plain
1807
- // per-process state - the documented boundary, not a bug.
2185
+
1808
2186
  if (typeof process !== 'undefined' && typeof process.send === 'function') {
1809
2187
  setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1810
2188
  process.on('message', (msg) => {
@@ -1812,76 +2190,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1812
2190
  });
1813
2191
  }
1814
2192
 
2193
+ // (the cross-machine seam): the cluster relay above covers ONE machine.
2194
+ export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
2195
+ setStoreTransport(send);
2196
+ }
2197
+ export function __deliverStorePatch(name: string, value: unknown): void {
2198
+ applyStorePatch(name, value);
2199
+ }
2200
+
1815
2201
  export { localeList };
1816
2202
  export const defaultLocale = '${defaultLocale}';
1817
2203
 
1818
- // Route params maps, re-exported for the build's prerender step: routePath
1819
- // -> the component's exported params (a static map or a function). Reading
1820
- // them through the server bundle keeps the deploy dir free of component
1821
- // modules - both bundles are self-contained, nothing else may ship. Only
1822
- // components that actually export params appear here (a missing export
1823
- // means the dynamic route renders on demand).
2204
+ // Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
1824
2205
  ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1825
2206
 
1826
2207
  export const routeParams = {
1827
2208
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1828
2209
  };
1829
2210
 
1830
- // Routes whose component reads the request context (getContext()), mutates a
1831
- // shared store ($store()), reads the query ($query(), P0-1), opted into
1832
- // nonce-based CSP or into the buffered path (buffer = true, P0-2):
1833
- // the bag is per-request, the store is per-process, a nonce is per-response,
1834
- // and a buffered route's hooks must run per request - so these are dynamic.
1835
- // The build never bakes them and the servers never answer them from a
1836
- // prerendered file. Public routes keep the static fast path (file cache,
1837
- // ETag/304, streaming) untouched.
2211
+ // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
1838
2212
  export const dynamicRoutes = [
1839
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
2213
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1840
2214
  ];
1841
2215
 
1842
- // Which api routes opt into build-time baking (export const prerender = true):
1843
- // routePath -> boolean. The build calls the GET handler once and writes the
1844
- // body to dist/, so the Go single binary serves read-only APIs without Node.
2216
+ // Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
1845
2217
  ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1846
2218
 
1847
2219
  export const apiPrerender = {
1848
2220
  ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1849
2221
  };
1850
2222
 
1851
- // Stale-while-revalidate windows (export const revalidate = N): the build
1852
- // bakes these routes like any other, and the preview server serves the
1853
- // baked file for up to N seconds - after which the next request is answered
1854
- // STALE (instant, from disk) while a background pass re-renders and swaps
1855
- // the file (ISR). Routes that read the request context are
1856
- // excluded: they render per request and have no baked file to revalidate.
1857
- // The dev server ignores the window (it rebuilds on change), the edge
1858
- // adapter renders live (always fresh), and the Go binary serves the baked
1859
- // file forever - the same static-half boundary as page POSTs.
2223
+
1860
2224
  export const revalidate = [
1861
2225
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1862
2226
  ];
1863
2227
 
1864
- // pages/_middleware.rose: a Web-standard request handler that runs before
1865
- // every render on the server (pages, POSTs, api calls alike). Returning a
1866
- // Response short-circuits the whole request - a redirect, an auth wall, a
1867
- // rewrite; returning nothing continues, and getContext() hands the
1868
- // per-request bag to $data, server actions and api handlers. Absent -> null,
1869
- // and the servers keep their static fast paths.
2228
+ // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
1870
2229
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1871
2230
 
1872
- // Routes whose DOCUMENTS ship without the client bundle (
1873
- // decided by the compiler since #29): HTML + CSS only - no runtime, no
1874
- // state script, zero JavaScript for whoever lands on them. The compiler
1875
- // picks these automatically: a route whose whole chain needs nothing from
1876
- // the client (no event wiring, no lifecycle, no action, no form) is a
1877
- // content route. An exported "csr = true" forces the bundle back in; an
1878
- // exported "csr = false" is the same decision, asserted. The route's render
1879
- // function still rides in the client bundle, so a client-side navigation
1880
- // from an interactive page paints it normally and a static deploy's SPA
1881
- // fallback can render it too; only the document is JS-free.
1882
- // isNoJs() lets the servers keep these routes on the buffered path: a
1883
- // streamed no-JS document would carry the shell's default <title> (the
1884
- // route head is applied client-side at boot, and there is no client).
2231
+ // Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
1885
2232
  export const noJsRoutes = [
1886
2233
  ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1887
2234
  ];
@@ -1890,21 +2237,12 @@ export function isNoJs(pathname) {
1890
2237
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1891
2238
  }
1892
2239
 
1893
- // P0-2 (bug report): routes that exported "buffer = true". The servers ask
1894
- // this BEFORE choosing a path: a streamed response commits its status and
1895
- // headers before the body exists, so its onResponse hooks cannot see the
1896
- // document and a render that throws mid-flight still answers 200. A buffered
1897
- // route keeps every capability and gives up the early flush - the trade is
1898
- // the route's to make, per route, not the framework's.
2240
+ // P0-2 (bug report): routes that exported "buffer = true".
1899
2241
  export function isBuffered(pathname) {
1900
- return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
2242
+ return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
1901
2243
  }
1902
2244
 
1903
- // Per-route response headers: a route exporting a headers
1904
- // map carries them into every response the servers write for it, merged
1905
- // OVER the framework defaults (the strict CSP) - so an app can tighten or
1906
- // relax the policy per route. Absent -> null, and the servers keep sending
1907
- // the defaults alone.
2245
+
1908
2246
  export const routeHeaders = [
1909
2247
  ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1910
2248
  ];
@@ -1914,14 +2252,7 @@ export function headersFor(pathname) {
1914
2252
  return hit ? hit.headers : null;
1915
2253
  }
1916
2254
 
1917
- // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
1918
- // ). The servers ask this BEFORE writing a document: when it is true they
1919
- // mint one random nonce per response, put it in the CSP header ('nonce-...'
1920
- // plus 'strict-dynamic', so the document's own code may load more code) and
1921
- // stamp the same value on the script tag. The default policy stays a hash -
1922
- // cspNonceRoutes is empty for an app that never asks, so the fast path is
1923
- // unchanged. The Go binary never sees this: these routes are dynamic, so it
1924
- // has no baked file for them to serve.
2255
+
1925
2256
  export const cspNonceRoutes = [
1926
2257
  ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1927
2258
  ];
@@ -1930,9 +2261,7 @@ export function cspNonce(pathname) {
1930
2261
  return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1931
2262
  }
1932
2263
 
1933
- // A Web-standard Request from whatever the host provides: the edge adapter
1934
- // passes one already; the Node server passes its IncomingMessage (plus the
1935
- // already-parsed FormData for POSTs, so middleware can read form fields).
2264
+ // A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
1936
2265
  function toWebRequest(raw, form) {
1937
2266
  if (raw instanceof Request) return raw;
1938
2267
  const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
@@ -1940,13 +2269,7 @@ function toWebRequest(raw, form) {
1940
2269
  return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1941
2270
  }
1942
2271
 
1943
- // Runs the middleware (if the project has one) for this request and returns
1944
- // its short-circuit Response, or null to continue. The servers call this
1945
- // EXACTLY ONCE per request, before anything else: it resets the per-request
1946
- // context bag and the middleware fills it via getContext(), which $data,
1947
- // server actions and api handlers then read while rendering. rawReq: the
1948
- // host's request (Node IncomingMessage or a Web-standard Request); form:
1949
- // the already-parsed FormData of a POST.
2272
+
1950
2273
  export async function runMiddleware(rawReq, form) {
1951
2274
  resetRequestContext();
1952
2275
  if (!middleware || !rawReq) return null;
@@ -1958,10 +2281,7 @@ const routes = [
1958
2281
  ${serverRoutes}
1959
2282
  ];
1960
2283
 
1961
- // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
1962
- // render HTML and never reach the client bundle. The middleware ran before
1963
- // this (the servers call runMiddleware() first), so handlers can read
1964
- // getContext() for auth without re-running anything.
2284
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
1965
2285
  const apiRoutes = [
1966
2286
  ${apiRoutes.map(({ info, i }) => {
1967
2287
  const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -1969,19 +2289,40 @@ const apiRoutes = [
1969
2289
  }).join(",\n ")}
1970
2290
  ];
1971
2291
 
1972
- // pages/404.rose (with its layouts) or null -> built-in plain 404
1973
- const notFound = ${notFoundRender};
2292
+ // Not-found pages, deepest segment first: the root 404.rose ('/') and any
2293
+ // pages/<seg>/_notfound.rose, each already composed with its layout chain.
2294
+ // notFoundFor picks the nearest one up the path - an /admin miss answers
2295
+ // the admin 404, a public miss the site's - and notFoundPage is the whole
2296
+ // answer (real 404 status, or the built-in plain 404 when the app has none).
2297
+ const notFoundRoutes = ${notFoundTable};
2298
+ const notFoundFor = (pathname) => {
2299
+ for (const [prefix, render] of notFoundRoutes) {
2300
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2301
+ }
2302
+ return null;
2303
+ };
2304
+
2305
+ const notFoundFlags = (pathname) => {
2306
+ for (const [prefix, render, flags] of notFoundRoutes) {
2307
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
2308
+ }
2309
+ return null;
2310
+ };
2311
+ const notFoundPage = async (pathname) => {
2312
+ const nf = notFoundFor(pathname);
2313
+ if (nf) {
2314
+ const page = await renderFallback(pathname, nf);
2315
+ // __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
2316
+ return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
2317
+ }
2318
+ return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
2319
+ };
2320
+
1974
2321
 
1975
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1976
2322
  // whose render throws degrades to this instead of failing the response.
1977
2323
  const errorPage = ${errorRender};
1978
2324
 
1979
- // The <html> attributes of the document for a pathname - the locale
1980
- // of its [lang] segment (the default when there is none, or when the segment
1981
- // names no dictionary: that request 404s in the default language) and the
1982
- // reading direction that locale implies. The buffered render returns the same
1983
- // pair; the streaming path needs it BEFORE the shell flushes, which is why
1984
- // the servers ask for it by pathname.
2325
+
1985
2326
  export function docAttrs(pathname) {
1986
2327
  for (const route of routes) {
1987
2328
  if (!matchRoute(route.pattern, pathname)) continue;
@@ -1991,7 +2332,7 @@ export function docAttrs(pathname) {
1991
2332
  const lang = pathname.split('/')[langIdx];
1992
2333
  if (isLocale(lang)) return { lang, dir: localeDir(lang) };
1993
2334
  }
1994
- break; // matched, but not a localized route (or a bogus locale): the default
2335
+ break;
1995
2336
  }
1996
2337
  return { lang: defaultLocale, dir: localeDir(defaultLocale) };
1997
2338
  }
@@ -2004,8 +2345,22 @@ async function renderFallback(pathname, render) {
2004
2345
  }
2005
2346
 
2006
2347
  export function matchRoute(pattern, pathname) {
2348
+ // Q0 (bug report): one canonical URL per route.
2349
+ pathname = pathname.replace(/\\/+$/, '') || '/';
2007
2350
  const patternParts = pattern.split('/');
2008
2351
  const pathParts = pathname.split('/');
2352
+
2353
+ const last = patternParts[patternParts.length - 1];
2354
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2355
+ const fixed = patternParts.slice(0, -1);
2356
+ if (pathParts.length < fixed.length) return false;
2357
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2358
+ for (let i = 0; i < fixed.length; i++) {
2359
+ if (fixed[i].startsWith(':')) continue;
2360
+ if (fixed[i] !== pathParts[i]) return false;
2361
+ }
2362
+ return true;
2363
+ }
2009
2364
  if (patternParts.length !== pathParts.length) return false;
2010
2365
  for (let i = 0; i < patternParts.length; i++) {
2011
2366
  if (patternParts[i].startsWith(':')) continue;
@@ -2014,13 +2369,7 @@ export function matchRoute(pattern, pathname) {
2014
2369
  return true;
2015
2370
  }
2016
2371
 
2017
- // Head blocks (one per component in the route chain) are pulled out of the
2018
- // page html: the shell injects them into <head>, and the client re-applies
2019
- // them on navigation. Document order is page-first, so the shell's keyed
2020
- // merge lets a page override its layouts. The EMPTY marker pair stays in the
2021
- // body so the client's wire() still finds the block: at boot it adopts the
2022
- // shell-injected elements in place (marked with the same keys, so no
2023
- // duplicates) and keeps the head reactive.
2372
+ // Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
2024
2373
  function extractHead(rendered) {
2025
2374
  const head = [];
2026
2375
  const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
@@ -2030,18 +2379,7 @@ function extractHead(rendered) {
2030
2379
  return { html, head };
2031
2380
  }
2032
2381
 
2033
- // form: the submitted FormData of a progressive-enhancement POST. The
2034
- // selected server action runs first and returns a state patch (e.g.
2035
- // { guests: [...] }); seeding those keys BEFORE the render makes state()
2036
- // adopt them, so the response is the page as it looks AFTER the action -
2037
- // with or without JS. A __action field picks the action by name (default
2038
- // 'action', the conventional <form method="POST"> target); a click handler
2039
- // bound to an action ($action('like')) sends the same field.
2040
- // A route whose render throws degrades to pages/500.rose (status 500) - or
2041
- // the built-in plain 500 - instead of failing the whole response.
2042
- // The middleware does NOT run here: the servers run it once per request via
2043
- // runMiddleware() (which also seeds the request context), so a page render
2044
- // never re-runs it.
2382
+ // Form: the submitted FormData of a progressive-enhancement POST.
2045
2383
  export async function renderPage(pathname, form) {
2046
2384
  clearRequestState();
2047
2385
  for (const route of routes) {
@@ -2049,31 +2387,21 @@ export async function renderPage(pathname, form) {
2049
2387
  const patternParts = route.pattern.split('/');
2050
2388
  const pathParts = pathname.split('/');
2051
2389
  for (let i = 0; i < patternParts.length; i++) {
2052
- if (patternParts[i].startsWith(':')) {
2053
- setState(patternParts[i].slice(1), pathParts[i]);
2054
- }
2390
+ const seg = patternParts[i];
2391
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2392
+
2393
+
2394
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2055
2395
  }
2056
- // i18n: a [lang] segment naming no dictionary is a
2057
- // 404 - the URL is the contract, and rendering the page with fallback
2058
- // strings would serve duplicate content under a bogus language
2396
+ // I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
2059
2397
  const langIdx = patternParts.indexOf(':lang');
2060
2398
  if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
2061
- if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
2062
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2399
+ return await notFoundPage(pathname);
2063
2400
  }
2064
- // The document's <html lang>/<dir> follow this route's locale
2065
- // (the default's when the route is not localized)
2401
+
2402
+
2066
2403
  const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
2067
- // The action dispatch. The page's guard (exported
2068
- // beforeAction) runs FIRST and vetoes with an ActionError - the
2069
- // action-level permission check. Then the selected action runs and its
2070
- // return value seeds this render's state, per key, so an incremental
2071
- // patch ($append and friends) grows a large list by one row instead of
2072
- // re-sending the whole thing. An ActionError from either half is a
2073
- // BUSINESS failure: it is seeded as the 'actionError' state, the
2074
- // response carries its status, and the page renders with the failure
2075
- // visible (a {#boundary} around the action's widget contains it).
2076
- // Anything else is a bug and keeps going to the 500 page.
2404
+ // The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
2077
2405
  let actionStatus = 0;
2078
2406
  if (form && route.actions) {
2079
2407
  const actionName = form.get('__action') || 'action';
@@ -2085,9 +2413,7 @@ export async function renderPage(pathname, form) {
2085
2413
  if (patch && typeof patch === 'object') {
2086
2414
  for (const key of Object.keys(patch)) {
2087
2415
  const v = patch[key];
2088
- // An incremental patch is RECORDED, not applied: the render's
2089
- // own state declarations apply it, so the delta is relative to
2090
- // the value the page was going to render anyway.
2416
+ // An incremental patch is RECORDED, not applied: the render's own state declarations apply.
2091
2417
  if (v instanceof StateDelta) setStateDelta(key, v);
2092
2418
  else setState(key, v);
2093
2419
  }
@@ -2096,6 +2422,11 @@ export async function renderPage(pathname, form) {
2096
2422
  if (err instanceof ActionError) {
2097
2423
  setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
2098
2424
  actionStatus = err.code;
2425
+ } else if (err && err.__rosetack === 'redirect') {
2426
+
2427
+ return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
2428
+ } else if (err && err.__rosetack === 'notFound') {
2429
+ return await notFoundPage(pathname);
2099
2430
  } else {
2100
2431
  throw err;
2101
2432
  }
@@ -2106,32 +2437,27 @@ export async function renderPage(pathname, form) {
2106
2437
  try {
2107
2438
  rendered = extractHead(await route.render([], ''));
2108
2439
  } catch (err) {
2440
+ // The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
2441
+ const signal = err && err.__rosetack;
2442
+ if (signal === 'redirect') {
2443
+ return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
2444
+ }
2445
+ if (signal === 'notFound') {
2446
+ return await notFoundPage(pathname);
2447
+ }
2109
2448
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2110
2449
  if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
2111
2450
  return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2112
2451
  }
2113
2452
  // __route tells the bootstrap which route this document was rendered for.
2114
- // A static-file server may serve another route's document (SPA fallback);
2115
- // the bootstrap then client-renders instead of adopting mismatched DOM.
2116
2453
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2117
- // csr ( auto since #29): false when the compiler found
2118
- // nothing in the route's chain that needs the client (or the route
2119
- // asserted csr = false) - the document ships no runtime, no state
2120
- // script, zero JavaScript. Every other route keeps the bundle. The
2121
- // caller passes this straight to the shell as js.
2122
- // Status is the failed action's code when one failed - the page
2123
- // rendered fine, so the body is the page with the failure visible, and
2124
- // the status says what happened (a 403 from the guard, a 422 from a
2125
- // validation action). 200 otherwise.
2126
- // Lang/dir are the document's <html> attributes - the locale
2127
- // this route rendered in, and its reading direction.
2128
- return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
2454
+ // 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) .
2455
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
2129
2456
  }
2130
2457
  }
2131
- if (notFound) {
2132
- return { ...(await renderFallback(pathname, notFound)), status: 404 };
2133
- }
2134
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2458
+
2459
+
2460
+ return await notFoundPage(pathname);
2135
2461
  }
2136
2462
 
2137
2463
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -2139,21 +2465,20 @@ export async function renderPage(pathname, form) {
2139
2465
  export function canStream(pathname) {
2140
2466
  return routes.some((route) => {
2141
2467
  if (!matchRoute(route.pattern, pathname)) return false;
2142
- // i18n: an unknown locale must answer 404, and a
2143
- // streamed response cannot change its status - so it takes the buffered
2144
- // path (renderPage returns the real 404), never the streaming one
2468
+ // I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
2145
2469
  const langIdx = route.pattern.split('/').indexOf(':lang');
2146
2470
  return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
2147
2471
  });
2148
2472
  }
2149
2473
 
2150
- // === API routes ===
2151
- // The /api namespace answers JSON, never HTML: an API client that hits an
2152
- // unknown path must not receive the SPA shell. Handlers receive a
2153
- // Web-standard Request and return a plain object (serialized as JSON, 200),
2154
- // a Response (passed through), or nothing (204). A method the route does
2155
- // not export answers 405 with an Allow header. Same code path on the Node
2156
- // server and the edge adapter - Response is a global in both.
2474
+
2475
+ export function shellOff(pathname) {
2476
+ return routes.some(
2477
+ (route) => route.shell === false && matchRoute(route.pattern, pathname),
2478
+ );
2479
+ }
2480
+
2481
+ // === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
2157
2482
  export function isApi(pathname) {
2158
2483
  return pathname === '/api' || pathname.startsWith('/api/');
2159
2484
  }
@@ -2177,7 +2502,25 @@ export async function handleApi(method, pathname, request) {
2177
2502
  headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
2178
2503
  });
2179
2504
  }
2180
- return toResponse(await fn(request));
2505
+ try {
2506
+ return toResponse(await fn(request));
2507
+ } catch (err) {
2508
+
2509
+ const signal = err && err.__rosetack;
2510
+ if (signal === 'redirect') {
2511
+ return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
2512
+ status: err.status ?? 307,
2513
+ headers: { 'content-type': 'application/json', location: err.path },
2514
+ });
2515
+ }
2516
+ if (signal === 'notFound') {
2517
+ return new Response(JSON.stringify({ error: 'not found' }), {
2518
+ status: 404,
2519
+ headers: { 'content-type': 'application/json' },
2520
+ });
2521
+ }
2522
+ throw err;
2523
+ }
2181
2524
  }
2182
2525
  }
2183
2526
  return new Response(JSON.stringify({ error: 'not found' }), {
@@ -2186,18 +2529,7 @@ export async function handleApi(method, pathname, request) {
2186
2529
  });
2187
2530
  }
2188
2531
 
2189
- // === Streaming SSR ===
2190
- // The static shell (doctype, <head>, body + container open) flushes BEFORE
2191
- // the - possibly slow - render completes: the first byte leaves in
2192
- // microseconds instead of after every $data resolves. The route HTML, the
2193
- // state script, and the inlined bundle follow as later chunks of one chunked
2194
- // response - still exactly one request.
2195
- // The route's <head> tags are NOT in the streamed document: the client
2196
- // applies them at boot from the body's head markers, so JS users see the
2197
- // correct head immediately; no-JS consumers of streamed responses get the
2198
- // static shell head (prerendered files stay complete documents).
2199
- // Returns 200 (matched; a render throw degrades to the error-page body) or
2200
- // 404 (unmatched - nothing written, so the caller can still buffer).
2532
+ // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
2201
2533
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2202
2534
  clearRequestState();
2203
2535
  for (const route of routes) {
@@ -2205,9 +2537,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2205
2537
  const patternParts = route.pattern.split('/');
2206
2538
  const pathParts = pathname.split('/');
2207
2539
  for (let i = 0; i < patternParts.length; i++) {
2208
- if (patternParts[i].startsWith(':')) {
2209
- setState(patternParts[i].slice(1), pathParts[i]);
2210
- }
2540
+ const seg = patternParts[i];
2541
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2542
+
2543
+
2544
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2211
2545
  }
2212
2546
  // i18n: an unknown locale must 404 BEFORE the shell flushes - a
2213
2547
  // streamed response cannot change its status afterwards
@@ -2218,23 +2552,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2218
2552
  try {
2219
2553
  html = extractHead(await route.render([], '')).html;
2220
2554
  } catch (err) {
2221
- // the shell is already on the wire: degrade to the error page BODY
2222
- // (the status stays 200 - a real 500 needs the buffered path, which
2223
- // the server picks for routes known-broken at build time)
2555
+
2224
2556
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2225
2557
  html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
2226
2558
  }
2227
2559
  write(html);
2228
- // csr: false ( auto since #29): a no-JS route's document
2229
- // ends here - no state script, no inlined bundle. (The servers keep
2230
- // these routes off the streaming path so their <head> is complete;
2231
- // this is the correctness floor if one streams anyway.)
2560
+ // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
2232
2561
  if (route.csr === false) {
2233
2562
  write('</div>\\n</body>\\n</html>');
2234
2563
  return 200;
2235
2564
  }
2236
2565
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2237
- write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
2566
+ // P1-6 (bug report): the JSON data block is embedded in the document.
2567
+ const stateSafe = state.replace(/</g, '\\\\u003c');
2568
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
2238
2569
  return 200;
2239
2570
  }
2240
2571
  }
@@ -2258,7 +2589,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2258
2589
  const vitalsBlock = vitalsOn ? `
2259
2590
  // the app asked for web-vitals - measure once, at boot, and let the
2260
2591
  // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2261
- reportVitals;
2592
+ reportVitals();
2262
2593
  ` : "";
2263
2594
  const hasLang = infos.some((i) => i.pattern.includes(":lang"));
2264
2595
  const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
@@ -2266,26 +2597,24 @@ reportVitals;
2266
2597
  // logical properties both read it). A route with no [lang] segment
2267
2598
  // returns to the default locale, and a bogus segment falls back to it
2268
2599
  // too, exactly like the server's docAttrs.
2600
+ // Only when this container IS the document's app root. A mount
2601
+ // (dist/mount.js) renders into a foreign page, whose language and
2602
+ // direction belong to the host, not to the mounted route.
2269
2603
  const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
2270
2604
  const known = !seg || isLocale(seg);
2271
- const docLang = known && seg ? seg : __defLocale;
2272
- document.documentElement.lang = docLang;
2273
- const docDir = localeDir(docLang);
2274
- if (docDir) document.documentElement.setAttribute('dir', docDir);
2275
- else document.documentElement.removeAttribute('dir');
2605
+ if (container === document.getElementById('app')) {
2606
+ const docLang = known && seg ? seg : __defLocale;
2607
+ document.documentElement.lang = docLang;
2608
+ const docDir = localeDir(docLang);
2609
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
2610
+ else document.documentElement.removeAttribute('dir');
2611
+ }
2276
2612
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2277
2613
  const clientEntry = `
2278
2614
  ${clientImports}
2279
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
2280
-
2281
- // i18n: the dictionaries baked at build time - the client
2282
- // renders any PRELOADED locale from the bundle, so switching language costs
2283
- // zero requests (the same bet as the inlined route table). a locale
2284
- // the app left out of the preload (i18n.preload in rosetack.config.js) is a
2285
- // pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
2286
- // on first use - one request per language per session, then it renders from
2287
- // memory like any other. The default build preloads everything and ships no
2288
- // packs at all.
2615
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
2616
+
2617
+ // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
2289
2618
  setLocales(${clientLocalesJson}, '${defaultLocale}');
2290
2619
  setLocalePacks(${JSON.stringify(packed)});
2291
2620
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
@@ -2295,10 +2624,7 @@ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2295
2624
  // reportVitals alive through minification and tree-shaking; the call is one
2296
2625
  // statement at boot, before the first render.
2297
2626
  import { reportVitals } from './runtime.js';` : ""}
2298
- // The two pack doors, re-exported for an app that wants to warm a language
2299
- // before its visitor asks for it (ensureLocale) or to feed a dictionary it
2300
- // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
2301
- // is what applyParams calls - so the re-export costs the statement alone.
2627
+ // 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.
2302
2628
  export { ensureLocale, loadLocale } from './runtime.js';
2303
2629
  ${vitalsBlock}
2304
2630
 
@@ -2306,14 +2632,7 @@ const routes = [
2306
2632
  ${clientRoutes}
2307
2633
  ];
2308
2634
 
2309
- // === Mode B: lazy route chunks ===
2310
- // Split mode's registry entries arrive without a render function: loadChain
2311
- // loads the route's module graph (the page plus its layouts, one chunk per
2312
- // module, the shared runtime in its own vendor chunk) in parallel and
2313
- // composes it at runtime - the exact nesting compose() built at compile
2314
- // time for inline mode. getRender memoizes the composed function on the
2315
- // entry, so a chunk loads once per session; inline mode's entries are the
2316
- // render functions themselves, so the helper is a pass-through there.
2635
+ // === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
2317
2636
  const loadChain = async (loaders) => {
2318
2637
  const mods = await Promise.all(loaders.map((load) => load()));
2319
2638
  let expr = (closes, children) => mods[0].render(closes, children);
@@ -2329,36 +2648,62 @@ const getRender = async (route) => {
2329
2648
  return (route.render ??= (await route.load()).render);
2330
2649
  };
2331
2650
 
2332
- // pages/404.rose (with its layouts) or null -> built-in plain 404
2333
- const notFound = ${notFoundRender};
2651
+ // Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
2652
+ const notFoundRoutes = ${notFoundTable};
2653
+ const notFoundFor = (pathname) => {
2654
+ for (const [prefix, render] of notFoundRoutes) {
2655
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2656
+ }
2657
+ return null;
2658
+ };
2334
2659
 
2335
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
2336
- // whose render throws on the client degrades to this instead of breaking
2337
- // navigation.
2660
+ // 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.
2338
2661
  const errorPage = ${errorRender};
2339
2662
 
2340
2663
  // Paint a fallback page (404/500) into the container, wired like any render.
2341
- async function paintFallback(container, page, builtin) {
2342
- resetEffects();
2343
- clearRequestState();
2664
+ async function paintFallback(container, page, builtin, keepState = false) {
2665
+ if (!keepState) __navReset(container);
2344
2666
  clearMounts(); // a failed render leaves stale mounts behind
2345
2667
  // inline mode passes the render itself; split mode passes a loader
2346
2668
  const render = page ? await getRender(page) : null;
2347
2669
  if (render) {
2348
2670
  const closes = [];
2349
- const html = await render(closes, '');
2350
- container.innerHTML = html;
2351
- wire(container, closes);
2352
- bindEvents(container);
2353
- flushMounts();
2671
+ await __withOwner(container, async () => {
2672
+ const html = await render(closes, '');
2673
+ container.innerHTML = html;
2674
+ wire(container, closes);
2675
+ bindEvents(container);
2676
+ flushMounts();
2677
+ });
2354
2678
  return;
2355
2679
  }
2356
2680
  container.innerHTML = builtin;
2357
2681
  }
2358
2682
 
2683
+
2684
+ export async function startNotFound(container, pathname) {
2685
+ const el = document.getElementById('__rosetack_state');
2686
+ if (el) resumeState(el.textContent);
2687
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
2688
+ }
2689
+
2359
2690
  export function matchRoute(pattern, pathname) {
2691
+ // Q0 (bug report): one canonical URL per route.
2692
+ pathname = pathname.replace(/\\/+$/, '') || '/';
2360
2693
  const patternParts = pattern.split('/');
2361
2694
  const pathParts = pathname.split('/');
2695
+
2696
+ const last = patternParts[patternParts.length - 1];
2697
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2698
+ const fixed = patternParts.slice(0, -1);
2699
+ if (pathParts.length < fixed.length) return false;
2700
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2701
+ for (let i = 0; i < fixed.length; i++) {
2702
+ if (fixed[i].startsWith(':')) continue;
2703
+ if (fixed[i] !== pathParts[i]) return false;
2704
+ }
2705
+ return true;
2706
+ }
2362
2707
  if (patternParts.length !== pathParts.length) return false;
2363
2708
  for (let i = 0; i < patternParts.length; i++) {
2364
2709
  if (patternParts[i].startsWith(':')) continue;
@@ -2367,85 +2712,64 @@ export function matchRoute(pattern, pathname) {
2367
2712
  return true;
2368
2713
  }
2369
2714
 
2370
- // === Link prefetch ===
2371
- // Hover / focus / touch an internal link and the target route renders NOW -
2372
- // $data included - against a throwaway signal map. The click that follows
2373
- // paints from the cached HTML: no await, no request, no spinner. Other
2374
- // frameworks prefetch data only; rosetack prefetches the whole render because
2375
- // the inlined bundle already contains every route.
2376
- // Trade-off: the cache holds either a result or the in-flight promise (dedupes
2377
- // hover storms); one isolated render runs at a time so signal-map swapping
2378
- // stays correct without any merging logic. Entries are single-use: a consumed
2379
- // entry disappears from the cache, which is also how tests observe a hit.
2380
- // P1, three guards for link-heavy pages:
2381
- // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
2382
- // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
2383
- // Trade-off: app-global, not per-route - per-route would carry the mode
2384
- // in each document's shell.
2385
- // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
2386
- // the budget caps the QUEUE: a hover storm past it drops the excess
2387
- // instead of rendering fifty routes nobody clicks.
2388
- // 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
2389
- // is evicted first (Map iteration order; entries are single-use, so
2390
- // insertion order IS the recency order).
2715
+ // === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
2391
2716
  let prefetchMode = ${JSON.stringify(prefetchMode)};
2392
2717
  export function setPrefetchMode(mode) { prefetchMode = mode; }
2393
2718
  const PREFETCH_BUDGET = 8;
2394
2719
  const PREFETCH_MAX_CACHED = 4;
2395
- const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
2720
+ const prefetchCache = new Map();
2396
2721
  let prefetchQueue = Promise.resolve();
2397
2722
  let prefetchPending = 0;
2398
2723
 
2399
- // Applies the route's params to state. A [lang] segment whose dictionary is
2400
- // a runtime pack (i18n.preload) is awaited HERE - the one place every client
2401
- // render path goes through (navigation, prefetch, action adopt) - so a packed
2402
- // locale costs one request per session and then renders from memory. A
2403
- // preloaded locale (the default: every dictionary inline) resolves without
2404
- // touching the network, so the common path stays synchronous in spirit.
2724
+
2405
2725
  async function applyParams(route, pathname) {
2406
2726
  const patternParts = route.pattern.split('/');
2407
2727
  const pathParts = pathname.split('/');
2408
2728
  for (let i = 0; i < patternParts.length; i++) {
2409
- if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
2729
+ const seg = patternParts[i];
2730
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2731
+
2732
+
2733
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2410
2734
  }
2411
2735
  const langIdx = patternParts.indexOf(':lang');
2412
2736
  if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
2413
2737
  }
2414
2738
 
2739
+
2740
+ function __netOk() {
2741
+ const c = navigator.connection;
2742
+ if (!c) return true;
2743
+ if (c.saveData) return false;
2744
+ const t = c.effectiveType;
2745
+ return t !== 'slow-2g' && t !== '2g';
2746
+ }
2747
+
2415
2748
  export function prefetch(pathname, source = 'hover') {
2416
2749
  if (prefetchMode === 'off') return;
2417
2750
  if (prefetchMode === 'hover' && source !== 'hover') return;
2418
2751
  if (prefetchMode === 'viewport' && source !== 'viewport') return;
2752
+ if (!__netOk()) return; // save-data / 2g: no bytes before the click
2419
2753
  if (prefetchCache.has(pathname)) return;
2420
- if (pathname === location.pathname) return; // already here: nothing to prefetch
2754
+ if (pathname === location.pathname) return;
2421
2755
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
2422
2756
  if (!route) return;
2423
- if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
2424
- // P0-1: the link may carry a query (/search?q=cats). $query() reads the
2425
- // browser's own URL, which is the page being LEFT - so the prefetched
2426
- // render would see the wrong one. Override it for the duration and clear
2427
- // it after; the queue below serializes renders, so one slot is enough.
2757
+ if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
2428
2758
  const qi = pathname.indexOf('?');
2429
2759
  const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
2430
2760
  const p = prefetchQueue.then(async () => {
2431
2761
  try {
2432
2762
  setPrefetchOverride(qOverride);
2433
- // the isolated render also captures the onMount callbacks the route
2434
- // queued and the onCleanup disposers it registered: the paint that
2435
- // consumes this entry replays the mounts after wiring and adopts the
2436
- // cleanups, so the prefetched route's timers are disposed on the next
2437
- // navigation like any live route's
2763
+ // The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
2438
2764
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
2439
2765
  await applyParams(route, pathname); // a packed locale's dictionary lands before the render
2440
2766
  const closes = [];
2441
- const render = await getRender(route); // split mode: loads the route's chunk here
2767
+ const render = await getRender(route);
2442
2768
  const html = await render(closes, '');
2443
2769
  return { html, closes };
2444
2770
  });
2445
2771
  const entry = { ...result, state, mounts, cleanups };
2446
- prefetchCache.set(pathname, entry); // promise -> result
2447
- // evict oldest-first; in-flight promises are never evicted (evicting
2448
- // one would only force a duplicate render)
2772
+ prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
2449
2773
  while (prefetchCache.size > PREFETCH_MAX_CACHED) {
2450
2774
  const oldest = prefetchCache.keys().next().value;
2451
2775
  if (prefetchCache.get(oldest) instanceof Promise) break;
@@ -2453,7 +2777,7 @@ export function prefetch(pathname, source = 'hover') {
2453
2777
  }
2454
2778
  return entry;
2455
2779
  } catch {
2456
- prefetchCache.delete(pathname); // failed: the next hover retries
2780
+ prefetchCache.delete(pathname);
2457
2781
  return null;
2458
2782
  } finally {
2459
2783
  setPrefetchOverride(null);
@@ -2466,13 +2790,10 @@ export function prefetch(pathname, source = 'hover') {
2466
2790
  }
2467
2791
 
2468
2792
  export function prefetchStats() {
2469
- return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
2793
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
2470
2794
  }
2471
2795
 
2472
- // One delegated listener per event type on the app container: survives DOM
2473
- // swaps and cloned blocks, so handlers never need re-binding. A handler
2474
- // compiled from a server action (data-on-*="$action:name") dispatches to
2475
- // $action instead of the local handler registry.
2796
+ // One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
2476
2797
  const DELEGATED = ['click', 'input', 'change', 'submit'];
2477
2798
  function bindEvents(container) {
2478
2799
  if (container.__rosetack_bound) return;
@@ -2489,48 +2810,64 @@ function bindEvents(container) {
2489
2810
  }
2490
2811
  }
2491
2812
 
2492
- // === Server actions from any event ===
2493
- // POST the body to the current route and adopt the response in place: the
2494
- // server runs the selected action, seeds its state patch, and re-renders, so
2495
- // the swapped DOM is the page as it looks AFTER the action - one request, no
2496
- // reload, and wire() patches only the marked nodes (no re-render). The
2497
- // bootstrap's <form method="POST"> interception goes through the same door.
2498
- async function postForm(body) {
2499
- const res = await fetch(location.pathname, { method: 'POST', body });
2813
+ // === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
2814
+ async function postForm(body, container, pathname) {
2815
+
2816
+ const box = container || document.getElementById('app');
2817
+ const route = pathname || location.pathname;
2818
+ const res = await fetch(route, { method: 'POST', body });
2500
2819
  const html = await res.text();
2501
2820
  const doc = new DOMParser().parseFromString(html, 'text/html');
2502
2821
  const next = doc.getElementById('app');
2503
2822
  const st = doc.getElementById('__rosetack_state');
2504
2823
  const paint = () => {
2505
- const container = document.getElementById('app');
2506
- adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
2824
+ adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
2507
2825
  };
2508
2826
  if (document.startViewTransition) document.startViewTransition(paint);
2509
2827
  else paint();
2510
2828
  }
2511
2829
 
2512
- // Call a page's server action by name from any event handler:
2513
- // <button on:click={like}> compiles to $action('like'). Without JS the
2514
- // binding is inert - the progressive-enhancement story stays with forms.
2830
+ // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
2515
2831
  export async function $action(name, e) {
2516
2832
  if (e && e.preventDefault) e.preventDefault();
2517
2833
  const body = new FormData();
2518
2834
  body.append('__action', name);
2519
- return postForm(body);
2835
+ // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
2836
+ const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
2837
+ return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
2520
2838
  }
2521
2839
 
2522
2840
  export { postForm };
2523
2841
 
2524
- // The live signal graph as JSON - the same serializeState the zero-hydration
2525
- // resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
2526
- // can hand it to the dev server's reload bridge and to a devtools extension.
2527
- // A local re-export on purpose: it keeps the binding alive through minification
2528
- // for the bootstrap text appended after the bundle.
2842
+ // The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
2529
2843
  export { serializeState };
2530
2844
 
2531
- // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2532
- // the existing nodes and bind events. initial=false: client-side navigation -
2533
- // re-render the route chain from scratch and wire the fresh DOM.
2845
+ // Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
2846
+
2847
+
2848
+ function __ownsDoc(container) {
2849
+ return container === document.getElementById('app');
2850
+ }
2851
+ function __navReset(container) {
2852
+ if (__ownsDoc(container)) {
2853
+ resetEffects();
2854
+ clearRequestState();
2855
+ } else {
2856
+ resetContainerFx(container);
2857
+ }
2858
+ }
2859
+ // Attribute everything a render creates (state keys, effects, onCleanups) to
2860
+ // its container. The document path sets no owner and keeps the global sets.
2861
+ async function __withOwner(container, fn) {
2862
+ if (__ownsDoc(container)) return fn();
2863
+ setFxOwner(container);
2864
+ try {
2865
+ return await fn();
2866
+ } finally {
2867
+ setFxOwner(null);
2868
+ }
2869
+ }
2870
+
2534
2871
  export async function start(container, pathname, initial) {
2535
2872
  clearMounts(); // stale mounts from a failed render never fire
2536
2873
  if (initial) {
@@ -2539,104 +2876,110 @@ export async function start(container, pathname, initial) {
2539
2876
  }
2540
2877
  for (const route of routes) {
2541
2878
  if (matchRoute(route.pattern, pathname)) {
2542
- // i18n: an unknown locale paints the 404 page, same as the server
2543
- // (before the prefetch check: a cached entry for a bogus locale is
2544
- // discarded, never painted)
2879
+ // 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).
2545
2880
  const langIdx = route.pattern.split('/').indexOf(':lang');
2546
2881
  ${langDirBlock}
2547
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2882
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2548
2883
  return;
2549
2884
  }
2550
- // Prefetched on hover/focus/touch: the render already ran, so paint its
2551
- // HTML and adopt its signal entries - events then patch the very nodes
2552
- // we wire, and no $data re-runs on click.
2885
+ // 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.
2553
2886
  let hit = initial ? undefined : prefetchCache.get(pathname);
2554
2887
  if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2555
2888
  if (hit) {
2556
- prefetchCache.delete(pathname); // single-use: the next hover refetches
2557
- resetEffects();
2889
+ prefetchCache.delete(pathname);
2890
+ __navReset(container);
2558
2891
  restoreState(hit.state);
2559
2892
  container.innerHTML = hit.html;
2560
- wire(container, hit.closes);
2893
+ await __withOwner(container, () => {
2894
+ wire(container, hit.closes);
2895
+ bindEvents(container);
2896
+ hit.mounts.forEach((fn) => fn());
2897
+ adoptCleanups(hit.cleanups);
2898
+ });
2899
+ return;
2900
+ }
2901
+ if (!initial) __navReset(container);
2902
+ let broken = false;
2903
+ let signal = null;
2904
+ await __withOwner(container, async () => {
2905
+ await applyParams(route, pathname);
2906
+ const closes = [];
2907
+ let html;
2908
+ try {
2909
+ const render = await getRender(route);
2910
+ html = await render(closes, '');
2911
+ } catch (err) {
2912
+
2913
+ if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
2914
+ if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
2915
+
2916
+
2917
+ broken = true;
2918
+ return;
2919
+ }
2920
+ if (!initial) container.innerHTML = html;
2921
+ wire(container, closes);
2561
2922
  bindEvents(container);
2562
- hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2563
- adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
2923
+ flushMounts();
2924
+ });
2925
+ if (signal === 'notFound') {
2926
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2564
2927
  return;
2565
2928
  }
2566
- if (!initial) {
2567
- resetEffects();
2568
- clearRequestState();
2929
+ if (signal) {
2930
+ location.href = signal;
2931
+ return;
2569
2932
  }
2570
- await applyParams(route, pathname);
2571
- const closes = [];
2572
- let html;
2573
- try {
2574
- const render = await getRender(route); // split mode: loads the route's chunk here
2575
- html = await render(closes, '');
2576
- } catch {
2577
- // the route itself is broken: degrade to pages/500.rose (or the
2578
- // built-in plain 500) instead of leaving the container empty
2933
+ if (broken) {
2579
2934
  await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2580
- return;
2581
2935
  }
2582
- if (!initial) container.innerHTML = html;
2583
- wire(container, closes);
2584
- bindEvents(container);
2585
- flushMounts();
2586
2936
  return;
2587
2937
  }
2588
2938
  }
2589
- // unmatched route: pages/404.rose renders (with its head + interactivity),
2590
- // else the built-in plain 404 - and an i18n app's document returns to the
2591
- // default locale, the same one the server stamps on its 404
2592
- ${hasLang ? ` document.documentElement.lang = __defLocale;
2593
- document.documentElement.removeAttribute('dir');` : ""}
2594
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2939
+ // Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
2940
+ ${hasLang ? ` // the same app-root gate as above - a mount never touches the
2941
+ // host document's language or direction.
2942
+ if (container === document.getElementById('app')) {
2943
+ document.documentElement.lang = __defLocale;
2944
+ document.documentElement.removeAttribute('dir');
2945
+ }` : ""}
2946
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2595
2947
  }
2596
2948
 
2597
- // Adopt a server-rendered response in place - the JS-enabled half of
2598
- // progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
2599
- // via fetch and hands the response here. The DOM is swapped and wired with
2600
- // the same zero-render trick as boot: re-run the route's render to rebuild
2601
- // the marker closures, wire them against the adopted nodes. The page never
2602
- // re-renders visibly, no hydration payload, no second request beyond the POST.
2603
- export async function adopt(container, html, stateJson) {
2604
- resetEffects();
2605
- clearRequestState();
2949
+ // Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
2950
+ export async function adopt(container, html, stateJson, pathname) {
2951
+
2952
+
2953
+ const route0 = pathname || location.pathname;
2954
+ __navReset(container);
2606
2955
  clearMounts(); // stale mounts from a failed render never fire
2607
2956
  resumeState(stateJson);
2608
2957
  container.innerHTML = html;
2609
- // keep the embedded state in sync so a later SPA-fallback check agrees
2958
+
2610
2959
  const st = document.getElementById('__rosetack_state');
2611
2960
  if (st) st.textContent = stateJson;
2612
2961
  for (const route of routes) {
2613
- if (matchRoute(route.pattern, location.pathname)) {
2614
- await applyParams(route, location.pathname);
2615
- const closes = [];
2616
- try {
2617
- const render = await getRender(route); // split mode: loads the route's chunk here
2618
- await render(closes, '');
2619
- } catch {
2620
- // the adopted response's route is broken (e.g. the action's page
2621
- // throws): keep the swapped DOM but skip wiring it
2622
- return;
2623
- }
2624
- wire(container, closes);
2625
- bindEvents(container);
2626
- flushMounts();
2962
+ if (matchRoute(route.pattern, route0)) {
2963
+ await __withOwner(container, async () => {
2964
+ await applyParams(route, route0);
2965
+ const closes = [];
2966
+ try {
2967
+ const render = await getRender(route);
2968
+ await render(closes, '');
2969
+ } catch {
2970
+
2971
+
2972
+ return;
2973
+ }
2974
+ wire(container, closes);
2975
+ bindEvents(container);
2976
+ flushMounts();
2977
+ });
2627
2978
  return;
2628
2979
  }
2629
2980
  }
2630
2981
  }
2631
- // === refresh() implementation ===
2632
- // Re-render the current route in place: the client half of router.refresh()
2633
- // (a router refresh) / (a full invalidation). Same machinery as a client-side
2634
- // navigation to the current path - $data re-runs, state re-seeds from the
2635
- // fresh render, wire() patches the marked nodes - but a refresh never lands
2636
- // a prefetch entry: a hover from a minute ago is exactly what it exists to
2637
- // bypass. Zero requests: the render (and its $data) runs in the page.
2638
- // Trade-off: state resets like navigation (no per-key retention); add
2639
- // retention when an app needs refresh-without-losing-input.
2982
+ // === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
2640
2983
  setRefreshHook(async () => {
2641
2984
  prefetchCache.delete(location.pathname);
2642
2985
  await start(document.getElementById('app'), location.pathname, false);
@@ -2670,26 +3013,44 @@ setRefreshHook(async () => {
2670
3013
  ...TS_LOADER
2671
3014
  });
2672
3015
  }
3016
+ await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
2673
3017
  await fs.promises.rm(buildDir, { recursive: true, force: true });
2674
3018
  const publicDir = path.join(root, "public");
2675
3019
  if (fs.existsSync(publicDir)) {
2676
- const outPublic = path.join(outDir, "public");
2677
- await fs.promises.mkdir(outPublic, { recursive: true });
2678
- const assets = await fs.promises.readdir(publicDir);
2679
- await Promise.all(
2680
- assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
2681
- );
3020
+ await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
3021
+ const favicon = path.join(publicDir, "favicon.ico");
3022
+ if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
2682
3023
  }
2683
3024
  console.log("rosetack zero-JS report:");
2684
3025
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
3026
+ const warnGroups = /* @__PURE__ */ new Map();
2685
3027
  for (const { info, i } of pages) {
2686
3028
  if (!routeShipsNoJs(infos, compiled, i)) continue;
2687
3029
  for (const ci of [i, ...layoutsOf(infos, i)]) {
2688
3030
  for (const w of compiled[ci].jsWarnings ?? []) {
2689
- console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
3031
+ let g = warnGroups.get(w);
3032
+ if (!g) {
3033
+ g = { why: w, files: /* @__PURE__ */ new Map() };
3034
+ warnGroups.set(w, g);
3035
+ }
3036
+ const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
3037
+ let routes = g.files.get(file);
3038
+ if (!routes) {
3039
+ routes = /* @__PURE__ */ new Set();
3040
+ g.files.set(file, routes);
3041
+ }
3042
+ routes.add(info.routePath);
2690
3043
  }
2691
3044
  }
2692
3045
  }
3046
+ for (const g of warnGroups.values()) {
3047
+ const allRoutes = /* @__PURE__ */ new Set();
3048
+ for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
3049
+ 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`})`);
3050
+ const shown = parts.slice(0, 4).join(", ");
3051
+ const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
3052
+ console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
3053
+ }
2693
3054
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2694
3055
  }
2695
3056
  async function scanRoseFiles(root) {
@@ -2734,15 +3095,21 @@ function getRouteInfo(filePath, root) {
2734
3095
  const base = path.posix.basename(withoutExt);
2735
3096
  const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2736
3097
  const isLayout = !isComponent && base === "_layout";
2737
- const isNotFound = !isComponent && base === "404";
3098
+ const isNotFound = !isComponent && (base === "404" || base === "_notfound");
2738
3099
  const isError = !isComponent && base === "500";
2739
3100
  const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2740
3101
  const isMiddleware = !isComponent && withoutExt === "_middleware";
2741
- let parts = withoutExt.split("/").filter((p) => p !== "_layout");
3102
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
2742
3103
  if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
2743
- const routeParts = parts.map(
2744
- (part) => part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part
2745
- );
3104
+ const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
3105
+ const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
3106
+ const routeParts = parts.map((part) => {
3107
+ const optional = OPTIONAL_CATCH_ALL.exec(part);
3108
+ if (optional) return `**${optional[1]}`;
3109
+ const catchAll = CATCH_ALL.exec(part);
3110
+ if (catchAll) return `*${catchAll[1]}`;
3111
+ return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
3112
+ });
2746
3113
  let routePath;
2747
3114
  if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2748
3115
  routePath = "/";
@@ -2753,7 +3120,13 @@ function getRouteInfo(filePath, root) {
2753
3120
  filePath,
2754
3121
  routePath,
2755
3122
  pattern: routePath,
2756
- paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
3123
+ paramNames: parts.flatMap((p) => {
3124
+ const optional = OPTIONAL_CATCH_ALL.exec(p);
3125
+ if (optional) return [optional[1]];
3126
+ const catchAll = CATCH_ALL.exec(p);
3127
+ if (catchAll) return [catchAll[1]];
3128
+ return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
3129
+ }),
2757
3130
  isLayout,
2758
3131
  isNotFound,
2759
3132
  isError,