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
@@ -1,30 +1,17 @@
1
- /**
2
- * rosetack Compiler - Compile .rose components to SSR + client-resume JS
3
- *
4
- * Features: compile-time reactivity, zero-hydration resume, file-system
5
- * routing, nested layouts, server data fetching ($data) with request cache.
6
- */
1
+ // rosetack Compiler - Compile .rose components to SSR + client-resume JS
7
2
 
8
3
  import * as fs from 'fs';
9
4
  import * as path from 'path';
10
5
  import { pathToFileURL, fileURLToPath } from 'url';
11
6
  import * as esbuild from 'esbuild';
12
- // The error contract every compiler failure speaks: a stable code, the file, the line when
13
- // known, and the fix …
14
7
  import { RoseError, lineOf, lineAt } from './errors.js';
15
8
  export { RoseError, lineOf, lineAt, errorInfo } from './errors.js';
16
9
  export type { RoseErrorInfo } from './errors.js';
17
10
 
18
11
  const COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
19
12
  const TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
20
- // <head> block: per-route document metadata (title/meta/link), compiled
21
- // without markers so the SSR output stays clean for <head> injection.
22
13
  const HEAD_RE = /<head>([\s\S]*?)<\/head>/;
23
- // <style> block: component CSS, scoped by a build-time attribute on the component's
24
- // top-level elements and inlined into the document …
25
14
  const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
26
- // A declaration's initializer may carry TypeScript: a type argument (`$state<Record<string,
27
- // Post>>(...)`) and/or a cast (`$state(0) as Counter`).
28
15
  const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
29
16
  const DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
30
17
  const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
@@ -34,11 +21,7 @@ const SLOT_RE = /<slot\s*\/?>/g;
34
21
  * keeps the plain `<slot />` out of it - that one is the default slot. */
35
22
  const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
36
23
 
37
- /**
38
- * Encode a named slot tag as the template expression
39
- * `__slot('row', [['item', (post)]])` - array pairs, because the template
40
- * scanner matches `{...}` without nested braces.
41
- */
24
+ // Encode a named slot tag as the template expression `__slot('row', [['item', (post)]])` - array pairs.
42
25
  function encodeSlotCall(attrs: string): string {
43
26
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
44
27
  if (!name) throw new RoseError('E-TEMPLATE', '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
@@ -47,13 +30,8 @@ function encodeSlotCall(attrs: string): string {
47
30
  .map((m) => `['${m[1]}', (${m[2].trim()})]`);
48
31
  return `${JSON.stringify(name)}, [${pairs.join(', ')}]`;
49
32
  }
50
- // {#boundary}...{/boundary}: an error boundary - its content renders into its own string; a
51
- // throw anywhere inside swaps in a fallback instead of failing the whole page.
52
33
  const BOUNDARY_FALLBACK = '<p>This section failed to render.</p>';
53
- // API route handlers are exported functions named by HTTP method (pages/api/*.rose).
54
34
  const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
55
- // A .rose <script> block is TypeScript: interfaces, annotations, `as`, generics. The
56
- // compiler's intermediates therefore hold TypeScript, and esbuild must STRIP the types …
57
35
  const TS_LOADER = { loader: { '.js': 'ts' as const } };
58
36
 
59
37
  export interface CompileResult {
@@ -79,6 +57,15 @@ export interface CompileResult {
79
57
  revalidate?: number;
80
58
  /** the component exports `csr = false` (document ships without the client bundle) */
81
59
  csr?: boolean;
60
+ /**
61
+ * The component exports `shell = false`: keep the client bundle (this route
62
+ * still needs it - comments widgets, third-party scripts) but drop the
63
+ * shell's demo dressing - the #app wrapper and STYLES_MIN. A real app ships
64
+ * its own theme CSS; the scaffold's `body{padding:2rem}` / pink links then
65
+ * outrank it on equal specificity. Same escape the zero-JS branch has, for
66
+ * routes that cannot go JS-free.
67
+ */
68
+ shell?: boolean;
82
69
  /**
83
70
  * P0-2 (bug report): the component exports `buffer = true` - render it per
84
71
  * request on the BUFFERED path instead of streaming. A streamed response
@@ -90,6 +77,14 @@ export interface CompileResult {
90
77
  * run on, so `buffer = true` routes are never prerendered.
91
78
  */
92
79
  buffer?: boolean;
80
+ /**
81
+ * The script calls `redirect()` or `notFound()` (the control-flow pair).
82
+ * Both are thrown signals whose answer is the RESPONSE's status - a 30x
83
+ * with a Location, or a real 404 - and a streamed response has committed
84
+ * its status before the render runs. Such a route is therefore buffered
85
+ * by construction, exactly like `buffer = true`, and never prerendered.
86
+ */
87
+ controlSignal?: boolean;
93
88
  /** the component exports `prefetch = 'off' | 'hover' | 'viewport' | 'all'` (app-global link-prefetch strategy) */
94
89
  prefetch?: string;
95
90
  /** The component exports `vitals = true` (app-global web-vitals reporting) */
@@ -174,7 +169,6 @@ function callifyStateReads(script: string, names: string[]): string {
174
169
  let i = 0;
175
170
  while (i < src.length) {
176
171
  const ch = src[i];
177
- // string literal: copy verbatim
178
172
  if (ch === "'" || ch === '"') {
179
173
  let j = i + 1;
180
174
  while (j < src.length && src[j] !== ch) {
@@ -185,7 +179,6 @@ function callifyStateReads(script: string, names: string[]): string {
185
179
  i = j + 1;
186
180
  continue;
187
181
  }
188
- // template literal: copy text verbatim, scan ${...} as code
189
182
  if (ch === '`') {
190
183
  out += ch;
191
184
  i++;
@@ -215,7 +208,6 @@ function callifyStateReads(script: string, names: string[]): string {
215
208
  i++;
216
209
  continue;
217
210
  }
218
- // comments: copy verbatim
219
211
  if (ch === '/' && src[i + 1] === '/') {
220
212
  const nl = src.indexOf('\n', i);
221
213
  const end = nl === -1 ? src.length : nl;
@@ -230,7 +222,6 @@ function callifyStateReads(script: string, names: string[]): string {
230
222
  i = end;
231
223
  continue;
232
224
  }
233
- // identifier: rewrite bare state reads only
234
225
  if (/[A-Za-z_$]/.test(ch)) {
235
226
  let j = i;
236
227
  while (j < src.length && /[\w$]/.test(src[j])) j++;
@@ -293,8 +284,6 @@ export function templateExprSpans(src: string): Array<{ start: number; end: numb
293
284
  while (i < src.length) {
294
285
  if (src[i] === '{') {
295
286
  const end = scanExprEnd(src, i);
296
- // An empty `{}` is prose, not an expression (the old regex's `+` said
297
- // the same thing): skipping it leaves the braces for emitChunk.
298
287
  if (end > i + 1) {
299
288
  spans.push({ start: i, end, expr: src.slice(i + 1, end) });
300
289
  i = end + 1;
@@ -362,32 +351,46 @@ function skipTemplate(src: string, i: number): number {
362
351
  return j;
363
352
  }
364
353
 
365
- /**
366
- * 's scanners are syntactic, and prose is not code: the demo's
367
- * own "the same zero-JS document." (a sentence ending, not a member access)
368
- * tripped the browser-only warning on a route that touches no browser API.
369
- * Drop both comment syntaxes - JS line and block comments, HTML comments -
370
- * outside string and template literals, so a URL inside a string can never
371
- * eat the rest of its line and a real member access can never hide inside a
372
- * comment. Only the advisory warnings read the result: the needsClient
373
- * predicate keeps scanning the raw source, because missing a real `on:`
374
- * wiring is a broken page while a stray warning is only noise.
375
- */
354
+ // The literal that starts at `i`, if any: a quoted string, a template literal, or - the one that keeps derailing scanners - a REGEX literal.
355
+ function skipLiteral(src: string, i: number): number | null {
356
+ const q = src[i];
357
+ if (q === '"' || q === "'") return skipQuoted(src, i);
358
+ if (q === '`') return skipTemplate(src, i);
359
+ if (q !== '/') return null;
360
+ if (src[i + 1] === '/' || src[i + 1] === '*') return null;
361
+ let b = i - 1;
362
+ while (b >= 0 && /\s/.test(src[b])) b--;
363
+ if (b >= 0) {
364
+ if (!'(,=:[!&|?{};+-*%~^'.includes(src[b])) {
365
+ const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? '';
366
+ if (!['return', 'typeof', 'case', 'in', 'of', 'new', 'delete', 'void', 'do', 'else', 'instanceof', 'yield', 'await'].includes(word)) return null;
367
+ }
368
+ }
369
+ let j = i + 1;
370
+ let inClass = false;
371
+ while (j < src.length) {
372
+ const c = src[j];
373
+ if (c === '\\') { j += 2; continue; }
374
+ if (c === '\n') return null;
375
+ if (inClass) { if (c === ']') inClass = false; }
376
+ else if (c === '[') inClass = true;
377
+ else if (c === '/') { j++; break; }
378
+ j++;
379
+ }
380
+ if (j > src.length) return null;
381
+ while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
382
+ return j;
383
+ }
384
+
385
+ // 's scanners are syntactic, and prose is not code: the demo's own "the same zero-JS document." (a sentence ending).
376
386
  function stripComments(src: string): string {
377
387
  let out = '';
378
388
  let i = 0;
379
389
  while (i < src.length) {
380
- const q = src[i];
381
- if (q === '"' || q === "'") {
382
- const end = skipQuoted(src, i);
383
- out += src.slice(i, end);
384
- i = end;
385
- continue;
386
- }
387
- if (q === '`') {
388
- const end = skipTemplate(src, i);
389
- out += src.slice(i, end);
390
- i = end;
390
+ const lit = skipLiteral(src, i);
391
+ if (lit !== null) {
392
+ out += src.slice(i, lit);
393
+ i = lit;
391
394
  continue;
392
395
  }
393
396
  if (src.startsWith('//', i)) {
@@ -411,22 +414,136 @@ function stripComments(src: string): string {
411
414
  return out;
412
415
  }
413
416
 
414
- /**
415
- * The <script> block of a .rose source, verbatim. `rosetack check` must
416
- * type-check exactly what the compiler will embed, so the extraction lives
417
- * here and both consumers share it - one regex, one truth.
418
- */
417
+ // Q1 (bug report): the zero-JS scanner cried wolf on the standard isomorphic guard.
418
+ function stripGuardedBranches(src: string): string {
419
+ const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
420
+ const ws = (i: number): number => { while (i < src.length && /\s/.test(src[i])) i++; return i; };
421
+ const ternaryColon = (q: number): number => {
422
+ let depth = 0;
423
+ let i = q + 1;
424
+ while (i < src.length) {
425
+ const c = src[i];
426
+ const lit = skipLiteral(src, i);
427
+ if (lit !== null) { i = lit; continue; }
428
+ if (c === '(' || c === '[' || c === '{') depth++;
429
+ else if (c === ')' || c === ']' || c === '}') { depth--; if (depth < 0) return -1; }
430
+ else if (depth === 0 && c === ':') return i;
431
+ else if (depth === 0 && c === '?') { const inner = ternaryColon(i); if (inner < 0) return -1; i = inner + 1; continue; }
432
+ i++;
433
+ }
434
+ return -1;
435
+ };
436
+ const exprEnd = (i: number): number => {
437
+ let depth = 0;
438
+ while (i < src.length) {
439
+ const c = src[i];
440
+ const lit = skipLiteral(src, i);
441
+ if (lit !== null) { i = lit; continue; }
442
+ if (c === '(' || c === '[' || c === '{') depth++;
443
+ else if (c === ')' || c === ']' || c === '}') { if (depth === 0) return i; depth--; }
444
+ else if (depth === 0 && (c === ',' || c === ';')) return i;
445
+ else if (depth === 0 && c === '?') { const inner = ternaryColon(i); if (inner < 0) return src.length; i = inner + 1; continue; }
446
+ i++;
447
+ }
448
+ return src.length;
449
+ };
450
+ const braceEnd = (b: number): number => {
451
+ let depth = 0;
452
+ let i = b;
453
+ while (i < src.length) {
454
+ const c = src[i];
455
+ const lit = skipLiteral(src, i);
456
+ if (lit !== null) { i = lit; continue; }
457
+ if (c === '{') depth++;
458
+ else if (c === '}') { depth--; if (depth === 0) return i; }
459
+ i++;
460
+ }
461
+ return src.length;
462
+ };
463
+ const stmtEnd = (i: number): number => {
464
+ let depth = 0;
465
+ while (i < src.length) {
466
+ const c = src[i];
467
+ const lit = skipLiteral(src, i);
468
+ if (lit !== null) { i = lit; continue; }
469
+ if (c === '(' || c === '[' || c === '{') depth++;
470
+ else if (c === ')' || c === ']' || c === '}') { if (depth === 0) return i; depth--; }
471
+ else if (depth === 0 && (c === ';' || c === '\n')) return i;
472
+ i++;
473
+ }
474
+ return src.length;
475
+ };
476
+ const isIfGuard = (src: string, at: number): boolean => {
477
+ let b = at - 1;
478
+ while (b >= 0 && /\s/.test(src[b])) b--;
479
+ if (b < 0 || src[b] !== '(') return false;
480
+ b--;
481
+ while (b >= 0 && /\s/.test(src[b])) b--;
482
+ return b >= 1 && src[b] === 'f' && src[b - 1] === 'i' && (b < 2 || !/[\w$]/.test(src[b - 2]));
483
+ };
484
+
485
+ const blanks: Array<[number, number]> = [];
486
+ let i = 0;
487
+ while (i < src.length) {
488
+ const lit = skipLiteral(src, i);
489
+ if (lit !== null) { i = lit; continue; }
490
+ GUARD.lastIndex = i;
491
+ const m = GUARD.exec(src);
492
+ if (!m) { i++; continue; }
493
+ const browserAfter = m[1] === '!==';
494
+ const j = ws(i + m[0].length);
495
+ const two = src.slice(j, j + 2);
496
+ if (two === '&&' && browserAfter) {
497
+ blanks.push([j + 2, exprEnd(j + 2)]);
498
+ } else if (two === '||' && !browserAfter) {
499
+ blanks.push([j + 2, exprEnd(j + 2)]);
500
+ } else if (src[j] === '?') {
501
+ const colon = ternaryColon(j);
502
+ if (colon < 0) {
503
+ if (browserAfter) blanks.push([j + 1, src.length]);
504
+ } else if (browserAfter) {
505
+ blanks.push([j + 1, colon]);
506
+ } else {
507
+ blanks.push([colon + 1, exprEnd(colon + 1)]);
508
+ }
509
+ } else if (src[j] === ')' && isIfGuard(src, i)) {
510
+ let bodyEnd: number;
511
+ const k = ws(j + 1);
512
+ if (src[k] === '{') {
513
+ bodyEnd = braceEnd(k);
514
+ if (browserAfter) blanks.push([k + 1, bodyEnd]);
515
+ } else {
516
+ bodyEnd = stmtEnd(k);
517
+ if (browserAfter) blanks.push([k, bodyEnd]);
518
+ }
519
+ const after = ws(bodyEnd + 1);
520
+ if (src.startsWith('else', after)) {
521
+ const e = ws(after + 4);
522
+ if (src[e] === '{') {
523
+ const close = braceEnd(e);
524
+ if (!browserAfter) blanks.push([e + 1, close]);
525
+ } else {
526
+ const stop = stmtEnd(e);
527
+ if (!browserAfter) blanks.push([e, stop]);
528
+ }
529
+ }
530
+ }
531
+ i = j;
532
+ }
533
+ if (blanks.length === 0) return src;
534
+ const out = [...src];
535
+ for (const [a, b] of blanks) {
536
+ for (let k = a; k < b && k < out.length; k++) if (out[k] !== '\n') out[k] = ' ';
537
+ }
538
+ return out.join('');
539
+ }
540
+
541
+ // The <script> block of a .rose source, verbatim.
419
542
  export function scriptOf(source: string): string | null {
420
543
  return source.match(COMPONENT_RE)?.[1] ?? null;
421
544
  }
422
545
 
423
- /**
424
- * The per-request bag the runtime hooks receive. Web-standard on purpose:
425
- * the same object reaches a hook on the Node server, the preview server and
426
- * the edge adapter, so hook code is written once and runs everywhere.
427
- * `state` is scratch space - one hook writes, a later hook (or the page,
428
- * through getContext()) reads.
429
- */
546
+ // The per-request bag the runtime hooks receive.
430
547
  export interface RequestHookContext {
431
548
  request: Request;
432
549
  url: URL;
@@ -435,18 +552,15 @@ export interface RequestHookContext {
435
552
  state: Record<string, unknown>;
436
553
  }
437
554
 
438
- /**
439
- * A plugin, in two halves. `transform` runs at BUILD time over each
440
- * component's raw source. The rest run at RUNTIME: `onRequest`/`onResponse`
441
- * once per request (Node server, dev/preview and edge adapter alike),
442
- * `onServe`/`onShutdown` once per worker process under `rosetack serve`
443
- * (Node only - an edge runtime owns the lifecycle, there is no worker start
444
- * to hook).
445
- *
446
- * A runtime hook is bundled into dist/server.js together with the config
447
- * module that declares it, so its imports must load in the target runtime
448
- * (Node and edge both): keep node-only code out of rosetack.config.js.
449
- */
555
+
556
+ export interface StoreBridge {
557
+ /** Install the sender: every $store write in this worker calls it. Pass null to detach. */
558
+ install(send: ((name: string, value: unknown) => void) | null): void;
559
+ /** Apply a patch that arrived from another process or machine. */
560
+ deliver(name: string, value: unknown): void;
561
+ }
562
+
563
+
450
564
  export interface Plugin {
451
565
  name: string;
452
566
  transform?(code: string, filePath: string): string | Promise<string>;
@@ -454,26 +568,13 @@ export interface Plugin {
454
568
  onRequest?(ctx: RequestHookContext): Response | void | Promise<Response | void>;
455
569
  /** After the response exists, before it is sent. Return a Response to replace it. */
456
570
  onResponse?(ctx: RequestHookContext, res: Response): Response | void | Promise<Response | void>;
457
- /** Worker start: open a connection pool, warm a cache. */
458
- onServe?(meta: { port: number; workers: number }): void | Promise<void>;
571
+ /** Worker start: open a connection pool, warm a cache, install a cross-machine store driver. */
572
+ onServe?(meta: { port: number; workers: number; store: StoreBridge }): void | Promise<void>;
459
573
  /** Worker drain, before exit: close the pool. */
460
574
  onShutdown?(): void | Promise<void>;
461
575
  }
462
576
 
463
- /**
464
- * The i18n half of rosetack.config.js - a named export beside the
465
- * plugins:
466
- *
467
- * export const i18n = { preload: ['en', 'zh'] };
468
- *
469
- * `preload` lists the locales baked into the CLIENT bundle. The default is
470
- * every locale: a language switch then costs zero requests, which is the
471
- * one-request bet taken to its conclusion. An app with many languages lists
472
- * the ones it wants inline; the rest are written to dist/locales/<lang>.json
473
- * and fetched on first use (ensureLocale in the runtime). The SERVER bundle
474
- * always carries every locale - it renders any language on demand, and its
475
- * size is nobody's hot path.
476
- */
577
+
477
578
  export interface I18nConfig {
478
579
  preload?: string[];
479
580
  }
@@ -483,20 +584,7 @@ export interface rosetackConfig {
483
584
  i18n: I18nConfig;
484
585
  }
485
586
 
486
- /**
487
- * Plugins live in `<root>/rosetack.config.js` as the default export: an array
488
- * of `{ name, transform, onRequest, onResponse, onServe, onShutdown }`.
489
- * `transform` runs over each component's raw source (template + script +
490
- * style, before any parsing) at build time; the runtime hooks are bundled
491
- * into dist/server.js by build() below. trade-off: transform alone covers
492
- * macros, custom syntax, includes and auto-imports - a transform can rewrite
493
- * anything, including the script block; the request/serve hooks cover auth,
494
- * logging and lifecycle, which no source rewrite can express. The import is
495
- * cache-busted per build so a config edit takes effect on the dev server's
496
- * next rebuild, and a missing file is simply "no config" (existence is
497
- * checked first, so a config with a syntax error still fails loudly).
498
- * One import, one evaluation: the i18n options ride in the same module.
499
- */
587
+
500
588
  export async function loadConfig(root: string): Promise<rosetackConfig> {
501
589
  const file = path.join(root, 'rosetack.config.js');
502
590
  if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
@@ -553,15 +641,11 @@ function resolveRoseImports(script: string, fromFile: string, registry: RoseRegi
553
641
  }
554
642
  return hit;
555
643
  };
556
- // A default import becomes a named one: the compiled module exports
557
- // `render`, and the parent's `<Card>` tag calls exactly that.
558
644
  let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at: number) => {
559
645
  const hit = resolve(spec, at);
560
646
  imports.push({ name, specifier: spec, index: hit.index });
561
647
  return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
562
648
  });
563
- // A named import (`import { render as Card }`) keeps its clause; only the
564
- // specifier becomes the placeholder.
565
649
  rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at: number) => {
566
650
  const hit = resolve(spec, at);
567
651
  const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? 'render';
@@ -598,7 +682,7 @@ const NODE_ONLY_SPEC = /^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream
598
682
  function nodeOnlyImports(importStmts: string): string[] {
599
683
  const out: string[] = [];
600
684
  for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
601
- if (m[1]) continue; // `import type` never ships, so it cannot break the client bundle
685
+ if (m[1]) continue;
602
686
  if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
603
687
  }
604
688
  return out;
@@ -685,10 +769,9 @@ function scanSlotDecls(filePath: string): Array<{ name: string; props: string[]
685
769
  } catch {
686
770
  return [];
687
771
  }
688
- // Same template extraction compileComponent does: a <template> block when
689
- // the file has one, otherwise everything that is not script/style/head.
690
- const noBlocks = src.replace(STYLE_RE, '');
691
- const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, '').replace(COMPONENT_RE, '').trim();
772
+ const noScript = src.replace(COMPONENT_RE, '');
773
+ const noBlocks = noScript.replace(STYLE_RE, '');
774
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, '').trim();
692
775
  const out: Array<{ name: string; props: string[] }> = [];
693
776
  for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
694
777
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
@@ -740,16 +823,13 @@ function hoistImports(script: string): { imports: string; rest: string } {
740
823
  }
741
824
  rest.push(line);
742
825
  }
743
- if (buf) imports.push(buf.join('\n')); // unterminated import: keep it whole
826
+ if (buf) imports.push(buf.join('\n'));
744
827
  return { imports: imports.join('\n'), rest: rest.join('\n') };
745
828
  }
746
829
 
747
830
  export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = [], registry: RoseRegistry = new Map()): Promise<CompileResult> {
748
831
  let source = await fs.promises.readFile(filePath, 'utf-8');
749
- // Plugins see the raw source first: whatever they return is what the compiler parses.
750
832
  for (const p of plugins) {
751
- // a runtime-only plugin (onRequest/onServe, no transform) has nothing to
752
- // rewrite - it must not break the build for lacking a build-time hook
753
833
  if (!p.transform) continue;
754
834
  try {
755
835
  source = await p.transform(source, filePath);
@@ -762,19 +842,21 @@ export async function compileComponent(filePath: string, publicDir: string, scop
762
842
  }
763
843
  }
764
844
 
765
- // API route (pages/api/*.rose): no template, no state, no markers - the script's exported
766
- // functions ARE the handlers …
767
845
  if (isApi) {
768
846
  const scriptMatch = source.match(COMPONENT_RE);
769
847
  const rawScript = scriptMatch?.[1] ?? '';
770
848
  const apiMethods = [...rawScript.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)]
771
849
  .map((m) => m[1])
772
850
  .filter((name) => HTTP_METHODS.has(name));
773
- // a handler that reads the request context cannot be baked: the bag is
774
- // per-request, a baked body would freeze one request's answer
775
851
  const usesContext = /getContext\s*\(/.test(rawScript);
776
852
  const hasPrerender = !usesContext && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript);
777
853
  const hoisted = hoistImports(resolveRoseImports(rawScript, filePath, registry).script);
854
+ const ownRuntimeImports = new Set(
855
+ [...rawScript.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)]
856
+ .flatMap((m) => m[1].split(',').map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
857
+ );
858
+ const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
859
+ const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(', ')} } from './runtime.js';\n` : '';
778
860
  return {
779
861
  ssr: '',
780
862
  client: '',
@@ -783,31 +865,24 @@ export async function compileComponent(filePath: string, publicDir: string, scop
783
865
  guardName: null,
784
866
  style: '',
785
867
  hasParams: false,
786
- api: `import { getContext, $query } from './runtime.js';\n${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
868
+ api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
787
869
  apiMethods,
788
870
  hasPrerender,
789
871
  usesContext,
790
872
  };
791
873
  }
792
874
 
793
- // strip the <head> block first, THEN the <style> block: a <style> written INSIDE <head>
794
- // is head content (a route-level stylesheet - bug report 2026.9.22 11:46) …
795
- const sourceNoHead = source.replace(HEAD_RE, '');
875
+ const sourceNoScript = source.replace(COMPONENT_RE, '');
876
+ const sourceNoHead = sourceNoScript.replace(HEAD_RE, '');
796
877
  const styleMatch = sourceNoHead.match(STYLE_RE);
797
878
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : '';
798
879
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, '');
799
880
 
800
- const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
801
- // Resolve `import Card from '../components/Card.rose'` against the build registry before
802
- // anything else looks at the script: the rewritten specifier (a `__rose_N__` placeholder) …
881
+ const scriptMatch = source.match(COMPONENT_RE);
803
882
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? '', filePath, registry);
804
883
  const rawScript = roseResolved.script;
805
884
  const roseImports = roseResolved.imports;
806
- // The imports (a component import above all) belong at module scope,
807
- // not inside render() - hoisted here, emitted by the generators.
808
885
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
809
- // The npm interop boundary, enforced instead of documented and hoped for. A page's or a
810
- // component's script ships to the browser - the $data bodies included …
811
886
  if (path.basename(filePath) !== '_middleware.rose') {
812
887
  for (const spec of nodeOnlyImports(importStmts)) {
813
888
  const at = importStmts.indexOf(spec);
@@ -825,11 +900,7 @@ export async function compileComponent(filePath: string, publicDir: string, scop
825
900
  );
826
901
  }
827
902
  }
828
- // A component (src/components/*.rose) is not a route: the build marks it in the registry
829
- // with a `components/...` scope key …
830
903
  const isComponent = registry.get(filePath)?.scopeKey.startsWith('components/') ?? false;
831
- // Boundary, stated loudly at build time: a component renders INSIDE its parent's template
832
- // phase, which is synchronous by design (that is what keeps wire …
833
904
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
834
905
  throw new RoseError(
835
906
  'E-EXPORT',
@@ -838,17 +909,10 @@ export async function compileComponent(filePath: string, publicDir: string, scop
838
909
  { file: filePath, hint: 'move the fetch to the page (or the middleware) and pass the value down as a prop' },
839
910
  );
840
911
  }
841
- // getContext() in the script makes the route dynamic: the request bag is per-request, so
842
- // the build must not bake it and the servers must not answer it from a prerendered file.
843
912
  const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
844
- // an exported `params` marks a dynamic route for prerender enumeration
845
913
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
846
- // an exported `revalidate = N` opts the route into stale-while-revalidate: the baked file
847
- // is served for up to N seconds …
848
914
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
849
915
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
850
- // P1: an exported `prefetch = '...'` sets the app-global link-prefetch strategy - 'off',
851
- // 'hover' …
852
916
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
853
917
  const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
854
918
  if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
@@ -858,8 +922,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
858
922
  { file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" },
859
923
  );
860
924
  }
861
- // `export const vitals = true` turns on the client-side web-vitals hook (runtime
862
- // reportVitals). App-global like prefetch, declared once (the root layout).
863
925
  const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
864
926
  const vitals = vitalsMatch ? vitalsMatch[1].trim() === 'true' : undefined;
865
927
  if (vitalsMatch && !vitals) {
@@ -869,8 +931,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
869
931
  { file: filePath, line: lineAt(rawScript, vitalsMatch), hint: 'omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app' },
870
932
  );
871
933
  }
872
- // The bundle mode - the fix for the large-app architecture gap. 'inline' (the default) is
873
- // the single-document mode: the whole client bundle rides inside the HTML, one request …
874
934
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
875
935
  const bundle = bundleMatch ? bundleMatch[1] : undefined;
876
936
  if (bundle && !['inline', 'split'].includes(bundle)) {
@@ -880,14 +940,13 @@ export async function compileComponent(filePath: string, publicDir: string, scop
880
940
  { file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" },
881
941
  );
882
942
  }
883
- // The compiler decides zero-JS, not the developer. This is the same "does anything here
884
- // need the client bundle" predicate that Used to REFUSE `csr = false`: event wiring in the …
885
943
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
886
944
  const csr: boolean | undefined = csrMatch ? csrMatch[1] !== 'false' : undefined;
887
- // P0-2 (bug report): `export const buffer = true` keeps this route off the streaming path
888
- // - see the Compiled flag.
945
+ const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
946
+ const shell: boolean | undefined = shellMatch ? shellMatch[1] !== 'false' : undefined;
889
947
  const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
890
948
  const buffer: boolean | undefined = bufferMatch ? bufferMatch[1] !== 'false' : undefined;
949
+ const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || undefined;
891
950
  if (csr === false) {
892
951
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
893
952
  if (dead) {
@@ -905,7 +964,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
905
964
  }
906
965
  }
907
966
 
908
- // An exported `headers = { ... }` sets this route's response headers
909
967
  let headers: Record<string, string> | undefined;
910
968
  const headersLiteral = extractObjectLiteral(rawScript, 'headers');
911
969
  if (headersLiteral) {
@@ -929,8 +987,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
929
987
  headers = value as Record<string, string>;
930
988
  }
931
989
 
932
- // An exported `csp = { nonce: true }` switches this route from the hashed policy to a
933
- // per-request nonce . The hash is the stronger default
934
990
  let cspNonce: boolean | undefined;
935
991
  const cspLiteral = extractObjectLiteral(rawScript, 'csp');
936
992
  if (cspLiteral) {
@@ -955,89 +1011,58 @@ export async function compileComponent(filePath: string, publicDir: string, scop
955
1011
  cspNonce = nonce === true;
956
1012
  }
957
1013
 
958
- // Top-level `export` statements (e.g. `export const params = {...}` for dynamic-route
959
- // prerendering) are hoisted to module scope: the script body itself is embedded inside …
960
1014
  const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
961
1015
  const script = scriptNoExports;
962
1016
  const actionNames = new Set(actions.map((a) => a.name));
963
1017
 
964
- // Does anything in this component need the client bundle?
965
1018
  const clientReasons: string[] = [];
966
- if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)'); // event wiring in the template
967
- // P1-3 (bug report): a bare <form method="POST"> is the progressive-
968
- // enhancement path, not a reason to ship JavaScript. With the bundle the
969
- // bootstrap intercepts the submit and adopts the response in place; without
970
- // it the browser performs the native POST and the server re-renders the
971
- // page - the action runs either way. Only a form WIRED to the client (an
972
- // on: handler, a $action dispatch) needs the runtime, and that wiring is
973
- // already a reason above, so a native form must not force the bundle onto
974
- // its page. This is what lets a CMS ship a real search form at zero JS.
1019
+ if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)');
975
1020
  if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
976
1021
  clientReasons.push('a form bound to a client dispatch ($action)');
977
1022
  }
978
1023
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
979
- if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`); // lifecycle / client-only APIs
980
- // A server action alone is NOT a reason either (P1-3): the native POST runs
981
- // it on the server and re-renders, which is the whole progressive-
982
- // enhancement story. The in-place adopt is the enhancement a page opts into
983
- // with on: wiring, not a tax every action page pays.
1024
+ if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`);
984
1025
  const needsClient = clientReasons.length > 0;
985
1026
 
986
- // The predicate is SYNTACTIC, so a component that ships no runtime is scanned for the
987
- // shapes that would silently need one …
988
1027
  const jsWarnings: string[] = [];
989
1028
  if (!needsClient) {
990
- // comments are prose, not code (see stripComments) - a sentence that happens to end in
991
- // "document." must not warn, and a commented-out handler must not either.
992
1029
  const codeOnly = stripComments(source);
993
1030
  const scriptCodeOnly = stripComments(rawScript);
1031
+ const scriptScannable = stripGuardedBranches(scriptCodeOnly);
994
1032
  if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
995
1033
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
996
1034
  }
997
1035
  if (/javascript:/i.test(codeOnly)) {
998
1036
  jsWarnings.push('a javascript: URL - it needs the bundle to run; link to a real route');
999
1037
  }
1000
- if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
1038
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
1001
1039
  jsWarnings.push('eval()/new Function() - client code the predicate cannot see');
1002
1040
  }
1003
- // Browser-only globals. The script block is embedded inside render() on BOTH sides …
1004
- 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)) {
1041
+ 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)) {
1005
1042
  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');
1006
1043
  }
1007
1044
  }
1008
1045
 
1009
1046
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
1010
- // the <head> block was already stripped above (before the scoped-style match) …
1011
- const headContent = source.match(HEAD_RE)?.[1] ?? '';
1047
+ const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? '';
1012
1048
  const rawTemplate = templateMatch
1013
1049
  ? templateMatch[1]
1014
1050
  : sourceNoBlocks.replace(COMPONENT_RE, '').trim();
1015
- // a component with styles carries its scope attribute on every top-level
1016
- // element, so its rules match only its own subtree
1017
1051
  const template = scopedStyle
1018
1052
  ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey)
1019
1053
  : inlineImages(rawTemplate, publicDir);
1020
1054
 
1021
- // Extract state / data declarations with balanced-paren scanning
1022
1055
  const decls = extractDecls(script);
1023
1056
  const stateDecls = decls.filter((d) => d.kind === 'state');
1024
1057
 
1025
- // setter name per state: setCount
1026
1058
  const setterNames = new Map<string, string>();
1027
1059
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
1028
1060
 
1029
- // The render body's emission order, and why it is what it is: props -> script (every
1030
- // top-level declaration left where the developer wrote it) -> hoisted nested declarations
1031
- // -> …
1032
1061
  const declCode = (d: (typeof decls)[number]): string => {
1033
- // A component's state keys are namespaced by its file, so two components that both declare
1034
- // `let open = $state(false)` no longer share one signal …
1035
1062
  const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
1036
1063
  if (d.kind === 'state') {
1037
1064
  return `const [${d.name}, ${setterNames.get(d.name)!}] = state(${JSON.stringify(key)}, ${d.expr});`;
1038
1065
  }
1039
- // $data: fetch only when this key has no value yet (server: always after
1040
- // clearRequestState; client: only on first visit or client-side nav)
1041
1066
  const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
1042
1067
  const fn = isFn ? d.expr : `() => (${d.expr})`;
1043
1068
  return `const __had_${d.name} = hasState(${JSON.stringify(key)});
@@ -1045,15 +1070,10 @@ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null
1045
1070
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1046
1071
  };
1047
1072
 
1048
- // Splice every top-level declaration back where it was written. The placeholder is a
1049
- // string literal: both rewrites below (the $setState rewrite and the bare-read callify)
1050
- // copy …
1051
1073
  const nestedDecls: (typeof decls)[number][] = [];
1052
1074
  let spliced = '';
1053
1075
  let pos = 0;
1054
1076
  decls.forEach((d, i) => {
1055
- // A top-level declaration is replaced by its placeholder (its generated code comes back
1056
- // after the rewrites) …
1057
1077
  const top = braceDepthAt(script, d.start) === 0;
1058
1078
  if (!top) nestedDecls.push(d);
1059
1079
  spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : '');
@@ -1061,66 +1081,44 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1061
1081
  });
1062
1082
  spliced += script.slice(pos);
1063
1083
 
1064
- // Rewrite $setState to setters, then replace bare state reads with getter calls. A plain
1065
- // regex would also rewrite state names inside string literals …
1066
1084
  let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
1067
1085
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, '');
1068
1086
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
1069
1087
  return `${setter}(${val})`;
1070
1088
  });
1071
1089
  cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1072
- // ...and put each top-level declaration back, exactly where it was written.
1073
1090
  cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
1074
1091
 
1075
- // Only the nested declarations still ride the hoisted block (after the
1076
- // script, before the deltas - the position they have always had).
1077
1092
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === 'state').map(declCode).join('\n');
1078
1093
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === 'data').map(declCode).join('\n');
1079
1094
 
1080
- // The template gets the same treatment: the script auto-calls a bare state read, so
1081
- // `{liked}` must not silently render the getter's source text.
1082
1095
  const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
1083
- // Extract event bindings from the CALLED template (the same string the markup rewrite
1084
- // below reads, so the two can never disagree).
1085
1096
  const wired = wireEventBindings(templateCalled, actionNames);
1086
1097
  const eventBindings = wired.bindings;
1087
1098
 
1088
- // on:event={fn} -> data-on-event="fn" (wireEventBindings: brace-aware, so an inline
1089
- // arrow's own braces are part of the expression) …
1090
- const ssrTemplate = wired.template
1091
- .replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
1092
- .replace(SLOT_RE, '{__slot__}');
1093
-
1094
1099
  const stateKeys = decls.map((d) => d.name);
1095
1100
 
1096
- // The local name -> module map for the components this file imports, handed to the
1097
- // template compiler so `<Card title={x}>` becomes a call to the imported module's render() …
1098
1101
  const comps = new Map(roseImports.map((r) => {
1099
1102
  const abs = path.resolve(path.dirname(filePath), r.specifier);
1100
1103
  const hit = registry.get(abs)!;
1101
1104
  return [r.name, { index: hit.index, slots: hit.slots }] as const;
1102
1105
  }));
1106
+ const ssrTemplate = rewriteQuotedExprAttrs(wired.template
1107
+ .replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
1108
+ .replace(SLOT_RE, '{__slot__}'), comps);
1109
+ assertKnownDirectives(ssrTemplate, filePath);
1103
1110
  const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0, true, comps);
1104
- // head block: no markers (esc() inline) - the whole block re-renders per call, so one
1105
- // reactive closure drives document title/meta on navigation.
1106
1111
  const compiledHead = headContent.trim() ? compileHead(headContent) : '';
1107
- // A named slot in the template needs the __slot() helper in the module.
1108
1112
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
1109
1113
 
1110
- // Actions ship in the SSR module only; the client bundle gets every other
1111
- // export (params, sync helpers) but never an action body.
1112
1114
  const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
1113
- // The guard is emitted at the SSR module's scope, beside the actions it fronts …
1114
1115
  const ssrGuard = guard ? `\n${guard}` : '';
1115
- // pages/_middleware.rose is a hook module, not a route: no template, no state, no head.
1116
1116
  const isMiddleware = path.basename(filePath) === '_middleware.rose';
1117
1117
  const ssr = isMiddleware
1118
1118
  ? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
1119
1119
  : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1120
1120
  const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1121
1121
 
1122
- // One rewrite for both bundles and every branch above: the `__rose_N__` placeholder
1123
- // resolves to this bundle's own module path …
1124
1122
  return {
1125
1123
  ssr: rewriteRoseImports(ssr, 'ssr'),
1126
1124
  client: rewriteRoseImports(client, 'client'),
@@ -1132,7 +1130,9 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1132
1130
  usesContext,
1133
1131
  revalidate,
1134
1132
  csr,
1133
+ shell,
1135
1134
  buffer,
1135
+ controlSignal,
1136
1136
  prefetch,
1137
1137
  vitals,
1138
1138
  bundle,
@@ -1188,8 +1188,6 @@ function scopeCss(css: string, key: string): string {
1188
1188
  const block = clean.slice(i + 1, j - 1);
1189
1189
  const sel = prelude.trim();
1190
1190
  if (sel.startsWith('@')) {
1191
- // at-rule: keep the prelude, scope the inner rules (keyframes pass
1192
- // through: their 0%/from/to "selectors" are not selectors)
1193
1191
  out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
1194
1192
  } else if (sel) {
1195
1193
  const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(',');
@@ -1223,7 +1221,6 @@ function injectScopeAttr(template: string, key: string): string {
1223
1221
  break;
1224
1222
  }
1225
1223
  out += template.slice(i, lt);
1226
- // scan one tag, respecting quoted attribute values
1227
1224
  let j = lt + 1;
1228
1225
  let quote = '';
1229
1226
  while (j < template.length) {
@@ -1234,12 +1231,11 @@ function injectScopeAttr(template: string, key: string): string {
1234
1231
  else if (c === '>') break;
1235
1232
  j++;
1236
1233
  }
1237
- const tagText = template.slice(lt, j + 1); // includes < and >
1234
+ const tagText = template.slice(lt, j + 1);
1238
1235
  const closing = /^<\//.test(tagText);
1239
1236
  const nameMatch = tagText.match(/^<\/?([a-zA-Z][\w-]*)/);
1240
1237
  const selfClosing = /\/>$/.test(tagText) || (nameMatch && VOID_TAGS.has(nameMatch[1].toLowerCase()));
1241
1238
  if (nameMatch && !closing && depth === 0 && !selfClosing) {
1242
- // inject before the closing > (or before a trailing />)
1243
1239
  const injectAt = tagText.endsWith('/>') ? tagText.length - 2 : tagText.length - 1;
1244
1240
  out += tagText.slice(0, injectAt) + attr + tagText.slice(injectAt);
1245
1241
  depth++;
@@ -1254,7 +1250,6 @@ function injectScopeAttr(template: string, key: string): string {
1254
1250
 
1255
1251
  const VOID_TAGS = new Set(['img', 'br', 'hr', 'input', 'meta', 'link', 'source', 'wbr']);
1256
1252
 
1257
- // Trade-off: tolerate leading indentation - .rose script blocks are indented
1258
1253
  const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
1259
1254
 
1260
1255
  /**
@@ -1295,28 +1290,20 @@ function extractObjectLiteral(script: string, name: string): string | null {
1295
1290
  return script.slice(start, i);
1296
1291
  }
1297
1292
 
1298
- // Exported for `rosetack check`: it synthesizes a module declaration for every imported
1299
- // .rose component from the SAME prop parse the compiler uses …
1300
1293
  export function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }>; props: Array<{ name: string; def: string | null }>; guard: string } {
1301
1294
  const stmts: string[] = [];
1302
1295
  const actions: Array<{ name: string; stmt: string }> = [];
1303
- // `export let` is a PROP, not a module-scope value - it is read from the caller's props
1304
- // object per invocation.
1305
1296
  const props: Array<{ name: string; def: string | null }> = [];
1306
- // `export async function beforeAction(name, form)` is the page's action GUARD - it runs
1307
- // before every action and vetoes with an ActionError.
1308
1297
  const guards: string[] = [];
1309
1298
  let out = '';
1310
1299
  let pos = 0;
1311
1300
  let m: RegExpExecArray | null;
1312
1301
  EXPORT_RE.lastIndex = 0;
1313
1302
  while ((m = EXPORT_RE.exec(script))) {
1314
- const kind = m[1]; // const/let/var, or undefined for function
1315
- const start = m.index + m[0].indexOf('export'); // skip leading indentation
1303
+ const kind = m[1];
1304
+ const start = m.index + m[0].indexOf('export');
1316
1305
  let i = start + m[0].length - m[0].indexOf('export');
1317
1306
  if (kind) {
1318
- // balanced scan: object/array literals, calls, arrows end at their
1319
- // matching close; primitive literals end at `;` or a plain newline.
1320
1307
  let depth = 0;
1321
1308
  while (i < script.length) {
1322
1309
  const ch = script[i];
@@ -1341,7 +1328,6 @@ export function extractExports(script: string): { clean: string; exports: string
1341
1328
  }
1342
1329
  if (script[i] === ';') i++;
1343
1330
  } else {
1344
- // function declaration: skip the parameter list, balance the body
1345
1331
  while (i < script.length && script[i] !== '{') i++;
1346
1332
  let depth = 0;
1347
1333
  while (i < script.length) {
@@ -1362,15 +1348,13 @@ export function extractExports(script: string): { clean: string; exports: string
1362
1348
  const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
1363
1349
  const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
1364
1350
  if (anyFn?.[1] === 'beforeAction') {
1365
- guards.push(stmt); // the guard: server-only, never an action target
1351
+ guards.push(stmt);
1366
1352
  } else if (asyncFn) {
1367
- actions.push({ name: asyncFn[1], stmt }); // server-only: kept out of the client bundle
1353
+ actions.push({ name: asyncFn[1], stmt });
1368
1354
  } else if (kind === 'let') {
1369
- // A prop. The declaration never reaches module scope - the generated render reads it from
1370
- // the props object (with this default) …
1371
1355
  const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
1372
1356
  if (pm) props.push({ name: pm[1], def: pm[2]?.trim() ?? null });
1373
- else stmts.push(stmt); // a destructuring pattern: not a prop, keep it shared
1357
+ else stmts.push(stmt);
1374
1358
  } else {
1375
1359
  stmts.push(stmt);
1376
1360
  }
@@ -1385,8 +1369,6 @@ function extractDecls(script: string): Decl[] {
1385
1369
  DECL_RE.lastIndex = 0;
1386
1370
  let m: RegExpExecArray | null;
1387
1371
  while ((m = DECL_RE.exec(script))) {
1388
- // The regex matched up to `$state`/`$data`; what follows is an optional type-argument
1389
- // list and then the call.
1390
1372
  let j = m.index + m[0].length;
1391
1373
  const skipSpace = () => { while (j < script.length && /\s/.test(script[j])) j++; };
1392
1374
  skipSpace();
@@ -1398,12 +1380,12 @@ function extractDecls(script: string): Decl[] {
1398
1380
  else if (ch === '>' && script[j - 1] !== '=') {
1399
1381
  depth--;
1400
1382
  if (depth === 0) { j++; break; }
1401
- } else if (ch === '=' && script[j + 1] === '>') j++; // `=>`: both chars are one token
1383
+ } else if (ch === '=' && script[j + 1] === '>') j++;
1402
1384
  j++;
1403
1385
  }
1404
1386
  skipSpace();
1405
1387
  }
1406
- if (script[j] !== '(') continue; // `$state` used as a value, not a call
1388
+ if (script[j] !== '(') continue;
1407
1389
  const open = j + 1;
1408
1390
  let depth = 1;
1409
1391
  let i = open;
@@ -1446,7 +1428,6 @@ function braceDepthAt(src: string, index: number): number {
1446
1428
  while (i < index) {
1447
1429
  if (src[i] === '\\') { i += 2; continue; }
1448
1430
  if (src[i] === quote) { i++; break; }
1449
- // a ${...} inside a template literal is code again
1450
1431
  if (quote === '`' && src[i] === '$' && src[i + 1] === '{') {
1451
1432
  let d = 1;
1452
1433
  i += 2;
@@ -1478,35 +1459,9 @@ function braceDepthAt(src: string, index: number): number {
1478
1459
  return depth;
1479
1460
  }
1480
1461
 
1481
- /**
1482
- * Compile a .rose template to statements that build an HTML string with
1483
- * reactive markers, and push update closures into the shared `closes` array.
1484
- *
1485
- * Marker protocol (identical on server and client, so the client can adopt
1486
- * the SSR DOM instead of re-rendering it):
1487
- * text: <!--⟦m:K⟧-->value wire() updates the following text node
1488
- * if block: <!--⟦i:K⟧-->html<!--⟦/i:K⟧--> wire() inserts/removes the block
1489
- * each list: <!--⟦l:K⟧-->items<!--⟦/l:K⟧--> wire() rebuilds the list
1490
- * attr: name="value" data-b="K:name" wire() re-sets the attribute
1491
- *
1492
- * Text/attr values are HTML-escaped on the server; wire() writes raw values
1493
- * because DOM text nodes and attributes are not HTML-parsed.
1494
- *
1495
- * `comps` maps an imported component's local name to its module index
1496
- * and slot declarations. A `<Card title={x}>` tag compiles to a call of that
1497
- * module's render() - the child pushes its markers into the SAME closes array
1498
- * the parent is using, so one wire() pass covers the whole tree (the same
1499
- * trick the layout chain already uses with children html).
1500
- */
1462
+ // Compile a .rose template to statements that build an HTML string with reactive markers, and push update closures into the shared `closes` array.
1463
+
1501
1464
 
1502
- /**
1503
- * Auto-call a BARE state read and nothing else. The callify pass has already
1504
- * rewritten a bare name to `name()`, so what reaches here is that - or an
1505
- * expression the developer wrote (a comparison, a member read, a call with
1506
- * arguments). Appending () to THOSE is a crash the developer reads as a
1507
- * framework bug: `{#if flash().name}` must not become `flash().name()`, and
1508
- * `{#each rows.filter(ok) as row}` must not become `rows.filter(ok)()`.
1509
- */
1510
1465
  function autoCall(expr: string): string {
1511
1466
  const e = expr.trim();
1512
1467
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
@@ -1547,7 +1502,7 @@ function findBlock(src: string, kind: 'if' | 'each' | 'boundary'): RegExpExecArr
1547
1502
  closeRe.lastIndex = i;
1548
1503
  const nextOpen = head.exec(src);
1549
1504
  const nextClose = closeRe.exec(src);
1550
- if (!nextClose) break; // this open never closes: not a block, look past it
1505
+ if (!nextClose) break;
1551
1506
  if (nextOpen && nextOpen.index < nextClose.index) {
1552
1507
  depth++;
1553
1508
  i = nextOpen.index + nextOpen[0].length;
@@ -1617,6 +1572,147 @@ function compileHead(head: string): string {
1617
1572
  return out;
1618
1573
  }
1619
1574
 
1575
+ /**
1576
+ * - "errors an agent can fix" - closed on a real
1577
+ * failure from the field. A template directive rosetack does not implement
1578
+ * used to reach esbuild as generated code and die THERE: the oboext port
1579
+ * wrote `{:else}` (the branch syntax every other template language has and
1580
+ * rosetack deliberately does not - `prompt.ts` says so in one line) and got
1581
+ * `dist/.build/comp-12.ssr.js:87: ERROR: Unexpected ":"` - a file the author
1582
+ * never wrote, a construct never named, a fix never suggested. An unknown
1583
+ * directive is now a build error at the .rose file, with the line, the
1584
+ * construct and the rosetack shape that replaces it.
1585
+ *
1586
+ * The known set is exactly what findBlock matches: `{#if}`, `{#each}`,
1587
+ * `{#boundary}` and their closers. There is no `{:...}` directive at all.
1588
+ * The same gate catches the two shapes findBlock cannot match at all - an
1589
+ * `{#each}` with no `as <name>` and an opener with no closer - which used to
1590
+ * reach esbuild the same way (`Unexpected "#each"`, `Unexpected "#if"`).
1591
+ * Adversarial probing found all three in one afternoon; a template compiler
1592
+ * that emits broken code silently is the worst failure mode it has.
1593
+ */
1594
+ const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary']);
1595
+ function assertKnownDirectives(template: string, filePath: string): void {
1596
+ const rawRanges: Array<[number, number]> = [];
1597
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
1598
+ let raw: RegExpExecArray | null;
1599
+ while ((raw = RAW_OPEN.exec(template))) {
1600
+ const tag = raw[1].toLowerCase();
1601
+ const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
1602
+ const gt = closeAt < 0 ? -1 : template.indexOf('>', closeAt);
1603
+ const end = gt < 0 ? template.length : gt + 1;
1604
+ rawRanges.push([raw.index, end]);
1605
+ RAW_OPEN.lastIndex = end;
1606
+ }
1607
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
1608
+ let note: RegExpExecArray | null;
1609
+ while ((note = COMMENT_RE.exec(template))) rawRanges.push([note.index, note.index + note[0].length]);
1610
+ rawRanges.sort((a, b) => a[0] - b[0]);
1611
+ const inRaw = (idx: number): boolean => rawRanges.some(([s, e]) => idx >= s && idx < e);
1612
+ const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
1613
+ let m: RegExpExecArray | null;
1614
+ while ((m = DIRECTIVE_RE.exec(template))) {
1615
+ if (inRaw(m.index)) continue;
1616
+ const [, sigil, word] = m;
1617
+ if (sigil === '/' && KNOWN_CLOSERS.has(word)) continue;
1618
+ if (sigil === '/') {
1619
+ throw new RoseError(
1620
+ 'E-TEMPLATE',
1621
+ `${filePath}: {/${word}} does not close anything`,
1622
+ { file: filePath, line: lineAt(template, m), hint: 'the closers are {/if}, {/each} and {/boundary} - one per block you opened' },
1623
+ );
1624
+ }
1625
+ if (word === 'else') {
1626
+ throw new RoseError(
1627
+ 'E-TEMPLATE',
1628
+ `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1629
+ { 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' },
1630
+ );
1631
+ }
1632
+ throw new RoseError(
1633
+ 'E-TEMPLATE',
1634
+ `${filePath}: {:${word}} is not a rosetack directive`,
1635
+ { 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" },
1636
+ );
1637
+ }
1638
+ const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
1639
+ while ((m = OPENER_RE.exec(template))) {
1640
+ if (inRaw(m.index)) continue;
1641
+ const [, kind, head] = m;
1642
+ if (kind === 'each' && !/\bas\s+(\w+)\s*$/.test(head)) {
1643
+ throw new RoseError(
1644
+ 'E-TEMPLATE',
1645
+ `${filePath}: {#each ${head.trim()}} is missing its item name`,
1646
+ { 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)' },
1647
+ );
1648
+ }
1649
+ const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, 'g');
1650
+ const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, 'g');
1651
+ let depth = 1;
1652
+ let i = m.index + m[0].length;
1653
+ for (;;) {
1654
+ OPEN_RE.lastIndex = i;
1655
+ CLOSE_RE.lastIndex = i;
1656
+ const nextOpen = OPEN_RE.exec(template);
1657
+ const nextClose = CLOSE_RE.exec(template);
1658
+ if (!nextClose) break;
1659
+ if (nextOpen && nextOpen.index < nextClose.index) {
1660
+ i = nextOpen.index + nextOpen[0].length;
1661
+ continue;
1662
+ }
1663
+ i = nextClose.index + nextClose[0].length;
1664
+ if (--depth === 0) break;
1665
+ }
1666
+ if (depth !== 0) {
1667
+ throw new RoseError(
1668
+ 'E-TEMPLATE',
1669
+ `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
1670
+ { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` },
1671
+ );
1672
+ }
1673
+ }
1674
+ }
1675
+
1676
+ /**
1677
+ * A QUOTED attribute whose value carries an expression - `class="{x}"`,
1678
+ * `style="color:{c};"`, `href="/p{id}"` - used to be compiled as if the value
1679
+ * were body text: the reactive markers landed INSIDE the attribute
1680
+ * (`class="<!--⟦m:0⟧-->yes<!--⟦/m:0⟧-->"`), a class list no selector matches,
1681
+ * and no wire pass can repair it (markers inside an attribute value are not
1682
+ * nodes). The real CMS writes `style="background:{p.enabled ? ...};"` on
1683
+ * every row, so this was not exotic. The unquoted form (`class={x}`) has
1684
+ * always compiled correctly through attrMark(); this pass rewrites the quoted
1685
+ * form into a single equivalent expression - `class={('yes')}`,
1686
+ * `style={('background:' + (p.enabled ? …) + ';')}` - so there is ONE
1687
+ * attribute path in the compiler instead of two, one of them broken.
1688
+ *
1689
+ * Component tags keep their own attribute parser (a quoted value is a string
1690
+ * prop there, by design), and a value holding a template literal is left
1691
+ * alone: rewriting it would need the literal-aware scanner the value does not
1692
+ * have, and the old path was no better.
1693
+ */
1694
+ function rewriteQuotedExprAttrs(template: string, comps: Map<string, unknown>): string {
1695
+ const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
1696
+ return template.replace(TAG_RE, (tag: string, name: string, attrs: string, selfClose: string) => {
1697
+ if (comps.has(name) || !/\{/.test(attrs)) return tag;
1698
+ const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole: string, attr: string, value: string) => {
1699
+ if (!/\{/.test(value) || value.includes('`')) return whole;
1700
+ const spans = templateExprSpans(value);
1701
+ if (spans.length === 0) return whole;
1702
+ let expr = '';
1703
+ let last = 0;
1704
+ for (const s of spans) {
1705
+ if (last < s.start) expr += (expr ? ' + ' : '') + JSON.stringify(value.slice(last, s.start));
1706
+ expr += (expr ? ' + ' : '') + `(${s.expr})`;
1707
+ last = s.end + 1;
1708
+ }
1709
+ if (last < value.length) expr += (expr ? ' + ' : '') + JSON.stringify(value.slice(last));
1710
+ return `${attr}={${expr}}`;
1711
+ });
1712
+ return `<${name}${rewritten}${selfClose ? ' /' : ''}>`;
1713
+ });
1714
+ }
1715
+
1620
1716
  function compileTemplate(
1621
1717
  template: string,
1622
1718
  acc: string,
@@ -1633,15 +1729,10 @@ function compileTemplate(
1633
1729
  const nextId = () => `${depth}_${blockId++}`;
1634
1730
 
1635
1731
  while (remaining.length > 0) {
1636
- // nesting-aware: an inner block's close tag must not end its parent
1637
1732
  const ifMatch = findBlock(remaining, 'if');
1638
1733
  const eachMatch = findBlock(remaining, 'each');
1639
1734
  const boundaryMatch = findBlock(remaining, 'boundary');
1640
- // The first top-level expression, found with the literal-aware scanner
1641
- // (templateExprSpans) rather than a flat `[^{}]+` regex …
1642
1735
  const firstExpr = templateExprSpans(remaining)[0];
1643
- // The same RegExpExecArray shape findBlock returns (an array plus `index`),
1644
- // so every call site below reads it exactly as it read the old regex match.
1645
1736
  const exprMatch = firstExpr
1646
1737
  ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) as unknown as RegExpExecArray
1647
1738
  : null;
@@ -1657,6 +1748,27 @@ function compileTemplate(
1657
1748
  ? candidates.reduce((a, b) => (a.index <= b.index ? a : b))
1658
1749
  : null;
1659
1750
 
1751
+ const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
1752
+ const rawHit = rawOpenRe.exec(remaining);
1753
+ if (rawHit && earliest && rawHit.index < earliest.index) {
1754
+ const tag = rawHit[1].toLowerCase();
1755
+ const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
1756
+ const gt = closeAt < 0 ? -1 : remaining.indexOf('>', closeAt);
1757
+ const end = gt < 0 ? remaining.length : gt + 1;
1758
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1759
+ remaining = remaining.substring(end);
1760
+ continue;
1761
+ }
1762
+
1763
+ const noteAt = remaining.indexOf('<!--');
1764
+ if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
1765
+ const noteEnd = remaining.indexOf('-->', noteAt + 4);
1766
+ const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
1767
+ result += emitChunk(remaining.slice(0, end), acc, closes, scope);
1768
+ remaining = remaining.substring(end);
1769
+ continue;
1770
+ }
1771
+
1660
1772
  if (!earliest) {
1661
1773
  result += emitChunk(remaining, acc, closes, scope);
1662
1774
  break;
@@ -1669,14 +1781,9 @@ function compileTemplate(
1669
1781
  const call = autoCall(cond);
1670
1782
  const id = nextId();
1671
1783
  const innerScope = scope ?? '__s';
1672
- // Inner markers live in the block's OWN closes array, so wiring an
1673
- // adopted/cloned block never re-touches the parent's markers.
1674
1784
  const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers, comps);
1675
1785
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
1676
1786
  if (markers) {
1677
- // The content renders the FIRST time the block shows, never before - see the
1678
- // runtime's ifMark for why the eager version crashed `{#if
1679
- // user()}{user().name}{/if}`.
1680
1787
  result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ''});\n`;
1681
1788
  } else {
1682
1789
  result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
@@ -1688,7 +1795,6 @@ function compileTemplate(
1688
1795
  if (before) result += emitChunk(before, acc, closes, scope);
1689
1796
  const call = autoCall(items);
1690
1797
  const id = nextId();
1691
- // Rename the item variable to the block's scope parameter - INSIDE EXPRESSIONS ONLY.
1692
1798
  const itemRe = new RegExp(`\\b${item}\\b`, 'g');
1693
1799
  let scoped = '';
1694
1800
  let lastSpan = 0;
@@ -1710,8 +1816,6 @@ function compileTemplate(
1710
1816
  const before = remaining.substring(0, earliest.index);
1711
1817
  if (before) result += emitChunk(before, acc, closes, scope);
1712
1818
  const id = nextId();
1713
- // Error boundary: the content renders into its OWN string and is only appended on
1714
- // success - a throw anywhere inside swaps in the fallback …
1715
1819
  const catchesAction = /\$action:|<form[\s>]/.test(content);
1716
1820
  const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers, comps);
1717
1821
  result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
@@ -1722,7 +1826,6 @@ function compileTemplate(
1722
1826
  result += `${acc} += __bd${id};\n`;
1723
1827
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1724
1828
  } else if (earliest.type === 'comp') {
1725
- // <Card prop={x}>...</Card> -> Card(closes, children, props, slots).
1726
1829
  const tag = earliest.tag!;
1727
1830
  if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
1728
1831
  const entry = comps.get(tag.name)!;
@@ -1738,14 +1841,10 @@ function compileTemplate(
1738
1841
  rest = remaining.substring(closeIdx + tag.name.length + 3);
1739
1842
  }
1740
1843
  const { def, named } = splitSlots(childrenSrc);
1741
- // Default children render at CALL time with the enclosing scope (inside an {#each}
1742
- // that scope is the item), exactly like a layout's children.
1743
1844
  const hasChildren = def.trim().length > 0;
1744
1845
  if (hasChildren) {
1745
1846
  result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1, markers, comps)} return h; };\n`;
1746
1847
  }
1747
- // Named slots are functions of the object the child passes in AND of a marker array
1748
- // of their own: their content is a block scoped to that object (see SLOT_HELPER) …
1749
1848
  const slotFns = named.map(([nm, src]) => {
1750
1849
  const decl = entry.slots.find((s) => s.name === nm);
1751
1850
  let content = src;
@@ -1764,15 +1863,11 @@ function compileTemplate(
1764
1863
  const propsObj = parseCompAttrs(tag.attrs)
1765
1864
  .filter((a) => a.name !== 'slot')
1766
1865
  .map((a) => {
1767
- // on:click={fn} is an event outward: the child receives it as the `onClick` prop
1768
- // and calls it - no extra machinery, a prop is a function like any other value.
1769
1866
  const key = a.name.startsWith('on:') ? `on${capitalize(a.name.slice(3))}` : a.name;
1770
1867
  const val = a.kind === 'expr' ? `(${a.value})` : a.kind === 'str' ? JSON.stringify(a.value) : 'true';
1771
1868
  return `${JSON.stringify(key)}: ${val}`;
1772
1869
  })
1773
1870
  .join(', ');
1774
- // The imported binding IS the child's render function (a default `import Card from
1775
- // '...rose'` compiles to `import { render as Card }`), so the call is direct …
1776
1871
  const childrenArg = hasChildren ? `__ch${id}(${scope ?? 'undefined'}, ${closes})` : `''`;
1777
1872
  result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(', ')} });\n`;
1778
1873
  remaining = rest;
@@ -1786,25 +1881,18 @@ function compileTemplate(
1786
1881
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1787
1882
  continue;
1788
1883
  }
1789
- // <slot name="x" item={post}> -> the child's named slot, rendered from the parent's
1790
- // content with the object the child passes in.
1791
1884
  const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
1792
1885
  if (slotCall) {
1793
1886
  if (before) result += emitChunk(before, acc, closes, scope);
1794
- // The slot renders markup, so it is concatenated raw - esc() would turn the
1795
- // parent's own elements into text.
1796
1887
  result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);\n`;
1797
1888
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1798
1889
  continue;
1799
1890
  }
1800
- // P1-2 (bug report): {@html expr} is the explicit reverse of esc() - trusted HTML,
1801
- // emitted verbatim.
1802
1891
  const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
1803
1892
  if (rawMatch) {
1804
1893
  if (before) result += emitChunk(before, acc, closes, scope);
1805
1894
  const expr = rawMatch[1].trim();
1806
1895
  if (!markers) {
1807
- // head block: the value is markup, so it is concatenated raw
1808
1896
  result += `${acc} += String(${expr} ?? '');\n`;
1809
1897
  } else {
1810
1898
  const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
@@ -1813,7 +1901,6 @@ function compileTemplate(
1813
1901
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1814
1902
  continue;
1815
1903
  }
1816
- // attr={expr} -> reactive attribute; otherwise a text marker
1817
1904
  const attrMatch = before.match(/([\w-]+)=\s*$/);
1818
1905
  if (attrMatch) {
1819
1906
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -1821,8 +1908,6 @@ function compileTemplate(
1821
1908
  result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
1822
1909
  } else {
1823
1910
  if (before) result += emitChunk(before, acc, closes, scope);
1824
- // A marker whose value is followed by LITERAL TEXT needs an end marker: the wire
1825
- // patches the text node after the start marker …
1826
1911
  const after = remaining.substring(earliest.index + earliest.match[0].length);
1827
1912
  const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith('{');
1828
1913
  result += emitText(trimmed, acc, closes, scope, markers, pair);
@@ -1846,11 +1931,7 @@ interface CompTag {
1846
1931
  selfClosing: boolean;
1847
1932
  }
1848
1933
 
1849
- /**
1850
- * Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside
1851
- * an attribute expression (`title={a > b}`) does not end the tag. Returns the
1852
- * index just past `>`, or -1 when the tag is never closed.
1853
- */
1934
+ // Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside an attribute expression (`title={a > b}`) does not end the tag.
1854
1935
  function scanTagEnd(src: string, start: number): number {
1855
1936
  let j = start + 1;
1856
1937
  let quote = '';
@@ -2032,8 +2113,6 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
2032
2113
  if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
2033
2114
  const tail = `</${nm[2]}>`;
2034
2115
  const inner = src.slice(end, closeIdx);
2035
- // The same rule one level down: a slot= INSIDE a named slot's
2036
- // content is nested too, and the child would silently never call it.
2037
2116
  rejectNestedSlot(inner, slotName);
2038
2117
  named.set(slotName, (named.get(slotName) ?? '') + stripped + inner + tail);
2039
2118
  elemDepth = Math.max(0, elemDepth - 1);
@@ -2055,9 +2134,6 @@ function emitChunk(text: string, acc: string, closes: string, scope: string | nu
2055
2134
  return `${acc} += ${JSON.stringify(text)};\n`;
2056
2135
  }
2057
2136
 
2058
- // --- Build-time image inlining ------------------------------------------- One fewer
2059
- // request per small local image: <img src="/logo.svg"> ships as a data URI inside the …
2060
-
2061
2137
  const IMG_RE = /<img\b(?:[^<>]|\{[^{}]*\})*>/g;
2062
2138
  const IMG_MIME: Record<string, string> = {
2063
2139
  '.png': 'image/png',
@@ -2068,13 +2144,12 @@ const IMG_MIME: Record<string, string> = {
2068
2144
  '.svg': 'image/svg+xml',
2069
2145
  '.ico': 'image/x-icon',
2070
2146
  };
2071
- // Trade-off: fixed 4 KB cap; make it configurable when a real app cares
2072
2147
  const INLINE_IMG_MAX = 4096;
2073
2148
 
2074
2149
  function inlineImages(template: string, publicDir: string): string {
2075
2150
  return template.replace(IMG_RE, (tag) => {
2076
- const src = tag.match(/\bsrc="(\/[^"{}]+)"/); // static, site-root-relative only
2077
- if (!src) return tag; // reactive/remote/missing src: leave it alone
2151
+ const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
2152
+ if (!src) return tag;
2078
2153
  const ext = path.extname(src[1]).toLowerCase();
2079
2154
  const mime = IMG_MIME[ext];
2080
2155
  if (!mime) return tag;
@@ -2082,10 +2157,9 @@ function inlineImages(template: string, publicDir: string): string {
2082
2157
  try {
2083
2158
  file = fs.readFileSync(path.join(publicDir, src[1]));
2084
2159
  } catch {
2085
- return tag; // not in public/ at build time: keep the URL, server 404s honestly
2160
+ return tag;
2086
2161
  }
2087
2162
  if (file.length > INLINE_IMG_MAX) return tag;
2088
- // SVG inlines as text (percent-encoded for #, ", %); binaries as base64
2089
2163
  const uri = ext === '.svg'
2090
2164
  ? `data:image/svg+xml,${file.toString('utf-8').replace(/%/g, '%25').replace(/#/g, '%23').replace(/\{/g, '%7B').replace(/\}/g, '%7D').replace(/"/g, '%22')}`
2091
2165
  : `data:${mime};base64,${file.toString('base64')}`;
@@ -2101,7 +2175,6 @@ function inlineImages(template: string, publicDir: string): string {
2101
2175
  */
2102
2176
  function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true, pair = false): string {
2103
2177
  if (!markers) {
2104
- // head block: inline escaped value, no marker comment (clean SSR html)
2105
2178
  return `${acc} += esc(${expr});\n`;
2106
2179
  }
2107
2180
  const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
@@ -2128,9 +2201,14 @@ function compileSlot(acc: string): string {
2128
2201
  return `${acc} += String(children);\n`;
2129
2202
  }
2130
2203
 
2131
- // The runtime's public surface, as one import line. Three generators emit it (page SSR,
2132
- // page client, the middleware module) …
2133
- const 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';`;
2204
+ const 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';`;
2205
+
2206
+ const API_RUNTIME_HELPERS = RUNTIME_IMPORTS
2207
+ .replace(/^import\s*\{/, '')
2208
+ .replace(/\}\s*from[\s\S]*$/, '')
2209
+ .split(',')
2210
+ .map((s) => s.trim())
2211
+ .filter(Boolean);
2134
2212
 
2135
2213
  /**
2136
2214
  * `export let title = 'x'` -> a per-invocation const read from the
@@ -2145,8 +2223,6 @@ function propsCode(props: Array<{ name: string; def: string | null }>): string {
2145
2223
  .join('\n');
2146
2224
  }
2147
2225
 
2148
- // The named-slot helpers, identical in both bundles . __slot resolves the parent's slot
2149
- // function and builds the object its <slot name item={...}> declared …
2150
2226
  const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
2151
2227
  const fn = sl[name];
2152
2228
  if (typeof fn !== 'function') return null;
@@ -2154,31 +2230,16 @@ const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
2154
2230
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
2155
2231
  return { o, fn };
2156
2232
  };
2157
- const __slotBlock = (closes, sl, name, pairs) => {
2158
- const hit = __slot(sl, name, pairs);
2159
- const idx = closes.length;
2160
- closes.push(() => {
2161
- if (!hit) return null;
2162
- const c = [];
2163
- return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
2164
- });
2165
- return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
2166
- };`;
2233
+ const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
2167
2234
 
2168
2235
  function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = '', props: Array<{ name: string; def: string | null }> = [], namedSlots = false, imports = '', isComponent = false, guard = '', hasActions = false, dataDeclsCode = ''): string {
2169
- // The head block renders to a clean html string (no markers) and is wrapped in an h
2170
- // marker pair: renderPage extracts it for <head> injection …
2171
2236
  const headCode = headFn
2172
2237
  ? `
2173
2238
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
2174
2239
  __html += headMark(closes, __head);`
2175
2240
  : '';
2176
- // A page's actions live at MODULE scope (the server entry imports them and dispatches by
2177
- // name), where render()'s per-state setters do not exist …
2178
2241
  const actionState = hasActions ? `
2179
2242
  const $setState = (key, value) => setState(key, value);` : '';
2180
- // A page's render is async ($data awaits); a component's is not - its parent calls it
2181
- // inside a string concatenation (`h += Card(...)`) …
2182
2243
  return `
2183
2244
  ${RUNTIME_IMPORTS}
2184
2245
 
@@ -2197,9 +2258,7 @@ export ${isComponent ? 'function' : 'async function'} render(closes, children, _
2197
2258
  ${script}
2198
2259
  ${stateDeclsCode}
2199
2260
  ${dataDeclsCode}
2200
- // The incremental patches of the action that produced THIS response,
2201
- // applied to the state the declarations above just established (a no-op on
2202
- // every path that is not a server action's re-render - see the runtime).
2261
+
2203
2262
  ${isComponent ? '' : 'applyStateDeltas();'}
2204
2263
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
2205
2264
  let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
@@ -2221,11 +2280,12 @@ function generateClient(
2221
2280
  isComponent = false,
2222
2281
  dataDeclsCode = ''
2223
2282
  ): string {
2224
- // Handlers live on a shared global (the runtime's `handlers` registry) so one delegated
2225
- // listener per event type can dispatch for any component, including freshly cloned nodes.
2226
2283
  const handlerRegistry = eventBindings.length > 0
2227
2284
  ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
2228
2285
  : '';
2286
+ const clientSetState = eventBindings.length > 0
2287
+ ? `const $setState = (key, value) => setState(key, value);`
2288
+ : '';
2229
2289
  const headCode = headFn
2230
2290
  ? `
2231
2291
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -2238,7 +2298,7 @@ ${RUNTIME_IMPORTS}
2238
2298
  ${imports}
2239
2299
 
2240
2300
  ${exports}
2241
-
2301
+ ${clientSetState ? `\n${clientSetState}\n` : ''}
2242
2302
  ${namedSlots ? SLOT_HELPER : ''}
2243
2303
 
2244
2304
  export ${isComponent ? 'function' : 'async function'} render(closes, children, __props, __slots) {
@@ -2263,7 +2323,7 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
2263
2323
  infos
2264
2324
  .map((li, i) => ({ li, i }))
2265
2325
  .filter(({ li }) => li.isLayout && isAncestorDir(li.filePath, infos[idx].filePath))
2266
- .sort((a, b) => b.li.filePath.length - a.li.filePath.length) // deepest first
2326
+ .sort((a, b) => b.li.filePath.length - a.li.filePath.length)
2267
2327
  .map(({ i }) => i);
2268
2328
 
2269
2329
  /**
@@ -2274,11 +2334,12 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
2274
2334
  const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number): boolean => {
2275
2335
  if (compiled[i].csr === true) return false;
2276
2336
  if (compiled[i].needsClient) return false;
2277
- // a layout needing the client bundles every document under it: its
2278
- // handlers would be dead code in a runtime-less document
2279
2337
  return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
2280
2338
  };
2281
2339
 
2340
+ const routeShellOff = (infos: RouteInfo[], compiled: CompileResult[], i: number): boolean =>
2341
+ compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
2342
+
2282
2343
  /**
2283
2344
  * The build's zero-JS lint report: one line per route with
2284
2345
  * its verdict and the exact reason - which component in the chain needs the
@@ -2302,11 +2363,72 @@ export function buildReport(infos: RouteInfo[], compiled: CompileResult[]): stri
2302
2363
  });
2303
2364
  }
2304
2365
 
2366
+ /**
2367
+ * The mount entry - the migration door. A foreign
2368
+ * page (the legacy half of a micro-frontend, or an old app adopting rosetack
2369
+ * one route at a time) marks containers and includes this one file:
2370
+ *
2371
+ * <div data-rosetack="/checkout"></div>
2372
+ * <script type="module" src="/mount.js"></script>
2373
+ *
2374
+ * Each container fetches its route's own document - the same one-request,
2375
+ * zero-hydration shape a standalone page gets - adopts the server's DOM in
2376
+ * place, and navigates inside itself: the host page keeps its URL, its
2377
+ * history, its <head> and every node outside the container. It imports the
2378
+ * same /client.js the documents use (mode B's entry, or the inline build's
2379
+ * bundle), so there is no second runtime and no hydration.
2380
+ *
2381
+ * Written verbatim, not minified: it ships once per app (not once per
2382
+ * document) and the servers compress it like any other asset. The cost to a
2383
+ * normal rosetack document is zero bytes - nothing references it unless the
2384
+ * host page does.
2385
+ */
2386
+ const MOUNT_ENTRY = `
2387
+ import { start, postForm } from '/client.js';
2388
+
2389
+ for (const el of document.querySelectorAll('[data-rosetack]')) {
2390
+ const route = el.getAttribute('data-rosetack');
2391
+ const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
2392
+ const parsed = new DOMParser().parseFromString(doc, 'text/html');
2393
+ // A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
2394
+ const app = parsed.getElementById('app');
2395
+ if (app) {
2396
+ el.innerHTML = app.innerHTML;
2397
+ } else {
2398
+ for (const node of Array.from(parsed.body.children)) {
2399
+ if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
2400
+ }
2401
+ }
2402
+ // start() resumes from #__rosetack_state (zero hydration), so the state
2403
+
2404
+ const state = parsed.getElementById('__rosetack_state');
2405
+ if (state) el.appendChild(state);
2406
+
2407
+ const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
2408
+ await start(el, route, rendered === route);
2409
+ if (state) state.remove();
2410
+
2411
+ el.addEventListener('click', (e) => {
2412
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
2413
+ if (!a || !el.contains(a)) return;
2414
+ e.preventDefault();
2415
+ el.setAttribute('data-rosetack', a.getAttribute('href'));
2416
+ start(el, a.getAttribute('href'), false);
2417
+ });
2418
+ // Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
2419
+ el.addEventListener('submit', (e) => {
2420
+ const f = e.target;
2421
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
2422
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
2423
+ e.preventDefault();
2424
+ postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
2425
+ });
2426
+ }
2427
+ `;
2428
+
2305
2429
  export async function buildProject(root: string, outDir: string): Promise<{ routes: RouteInfo[]; bundle: string }> {
2306
2430
  await fs.promises.mkdir(outDir, { recursive: true });
2307
2431
 
2308
- // stale intermediates from an older build layout must not survive into the
2309
- // deploy dir (they used to live directly in outDir)
2310
2432
  const stale = (await fs.promises.readdir(outDir)).filter((f) =>
2311
2433
  /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
2312
2434
  await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
@@ -2314,8 +2436,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2314
2436
  const pageFiles = await scanRoseFiles(root);
2315
2437
  const compFiles = await scanComponentFiles(root);
2316
2438
  const files = [...pageFiles, ...compFiles];
2317
- // A build that silently produces nothing is the worst possible failure mode (an empty
2318
- // dist/ deploys as a blank site).
2319
2439
  if (pageFiles.length === 0) {
2320
2440
  throw new RoseError(
2321
2441
  'E-ROUTE',
@@ -2324,17 +2444,12 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2324
2444
  );
2325
2445
  }
2326
2446
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
2327
- // rosetack.config.js: the plugins and the i18n options , loaded fresh per build so the dev
2328
- // server's hot rebuild picks up config edits.
2329
2447
  const config = await loadConfig(root);
2330
2448
  const plugins = config.plugins;
2331
- // scope key: the component's path under pages/ (index, _layout, blog/[id])
2332
2449
  const scopeKeys = files.map((f, i) => {
2333
2450
  const base = infos[i].isComponent ? path.join(root, 'src') : path.join(root, 'src', 'pages');
2334
2451
  return path.relative(base, f).replace(/\\/g, '/').replace(/\.rose$/, '');
2335
2452
  });
2336
- // The build-wide import registry: absolute path -> module index, scope key, and the named
2337
- // slots the component declares.
2338
2453
  const registry: RoseRegistry = new Map(
2339
2454
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
2340
2455
  );
@@ -2342,8 +2457,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2342
2457
  files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
2343
2458
  );
2344
2459
 
2345
- // A component that needs the client drags every page that imports it into the client
2346
- // bundle - the page renders it, so it must be able to resume it.
2347
2460
  const importsOf = new Map<number, number[]>();
2348
2461
  files.forEach((_, i) => {
2349
2462
  const list: number[] = [];
@@ -2354,8 +2467,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2354
2467
  }
2355
2468
  importsOf.set(i, list);
2356
2469
  });
2357
- // The walk reports WHICH dependency needs the client, so the build's lint
2358
- // line names the component instead of the page.
2359
2470
  const needyDep = (i: number, seen = new Set<number>()): string | null => {
2360
2471
  if (compiled[i].needsClient) return path.basename(files[i]);
2361
2472
  if (seen.has(i)) return null;
@@ -2375,8 +2486,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2375
2486
  }
2376
2487
  });
2377
2488
 
2378
- // Reachability: a component no page (transitively) imports ships in neither
2379
- // bundle - not the server's, not the client's.
2380
2489
  const reachable = new Set<number>();
2381
2490
  const visit = (i: number) => {
2382
2491
  if (reachable.has(i)) return;
@@ -2391,16 +2500,12 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2391
2500
  if (!infos[i].isComponent) visit(i);
2392
2501
  });
2393
2502
 
2394
- // Every component's scoped CSS in one stylesheet, inlined into the shell:
2395
- // styles ship inside the document like the JS bundle - zero requests.
2396
2503
  const styles = compiled
2397
2504
  .map((c, i) => (reachable.has(i) ? c.style : ''))
2398
2505
  .filter(Boolean).join('\n');
2399
2506
  if (styles) await fs.promises.writeFile(path.join(outDir, 'styles.css'), styles);
2400
2507
  else await fs.promises.rm(path.join(outDir, 'styles.css'), { force: true });
2401
2508
 
2402
- // i18n: every JSON file in src/locales/ is a language. The dictionaries are baked into
2403
- // BOTH bundles at build time …
2404
2509
  let locales: Record<string, Record<string, string>> = {};
2405
2510
  try {
2406
2511
  for (const f of await fs.promises.readdir(path.join(root, 'src', 'locales'))) {
@@ -2408,13 +2513,11 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2408
2513
  locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, 'src', 'locales', f), 'utf-8'));
2409
2514
  }
2410
2515
  } catch {
2411
- locales = {}; // no src/locales/: the app ships no translations
2516
+ locales = {};
2412
2517
  }
2413
2518
  const defaultLocale = locales.en ? 'en' : Object.keys(locales).sort()[0] ?? 'en';
2414
2519
  const localesJson = JSON.stringify(locales).replace(/</g, '\\u003c');
2415
2520
 
2416
- // Which dictionaries ride in the CLIENT bundle. Default: all of them, so a locale switch
2417
- // stays a zero-request navigation.
2418
2521
  const preload: string[] = config.i18n.preload ?? Object.keys(locales);
2419
2522
  const packed = Object.keys(locales).filter((l) => !preload.includes(l));
2420
2523
  for (const l of preload) {
@@ -2429,22 +2532,14 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
2429
2532
  const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
2430
2533
  const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, '\\u003c');
2431
2534
 
2432
- // Intermediates (component modules, shared runtime, bundle entries) live in a build dir
2433
- // that is removed before returning: both bundles are fully self-contained …
2434
2535
  const buildDir = path.join(outDir, '.build');
2435
2536
  await fs.promises.rm(buildDir, { recursive: true, force: true });
2436
2537
  await fs.promises.mkdir(buildDir, { recursive: true });
2437
2538
 
2438
- // The runtime half of the plugins. A transform already ran at build time (in
2439
- // compileComponent); onRequest/onResponse must run per request INSIDE the server bundle …
2440
2539
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
2441
2540
  if (runtimePlugins.length > 0) {
2442
- // Relative from .build/, so the build works from any cwd (`rosetack build <dir>` from
2443
- // elsewhere).
2444
2541
  const configRel = path.relative(buildDir, path.join(root, 'rosetack.config.js')).replace(/\\/g, '/');
2445
- await fs.promises.writeFile(path.join(buildDir, 'plugins.js'), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
2446
- // Bundled into dist/server.js: these hooks run per request on every server
2447
- // (Node, dev/preview, edge). Transform hooks already ran at build time.
2542
+ await fs.promises.writeFile(path.join(buildDir, 'plugins.js'), `
2448
2543
  import config from ${JSON.stringify(configRel)};
2449
2544
 
2450
2545
  const list = Array.isArray(config) ? config : [];
@@ -2457,8 +2552,6 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2457
2552
  `);
2458
2553
  }
2459
2554
 
2460
- // Shared runtime module, bundled once into client and server output. The runtime ships
2461
- // WITH THE COMPILER …
2462
2555
  const runtimeEntry = ['../runtime/index.ts', '../src/runtime/index.ts']
2463
2556
  .map((rel) => fileURLToPath(new URL(rel, import.meta.url)))
2464
2557
  .find((p) => fs.existsSync(p));
@@ -2473,8 +2566,6 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2473
2566
  });
2474
2567
 
2475
2568
  for (let i = 0; i < compiled.length; i++) {
2476
- // api routes compile to a handler module (no render): still an
2477
- // intermediate, still removed with the rest of the build dir
2478
2569
  const src = compiled[i].api ?? compiled[i].ssr;
2479
2570
  await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
2480
2571
  if (!infos[i].isApi) {
@@ -2484,15 +2575,46 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2484
2575
 
2485
2576
  const pages = infos
2486
2577
  .map((info, i) => ({ info, i }))
2487
- .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
2578
+ .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
2579
+ // Specificity order, by route specificity: a literal segment
2580
+ // beats a param, a param beats a catch-all, and an optional catch-all
2581
+ // (which also matches the parent path) goes last. Without this a root
2582
+ // `[[...slug]]` - the shape a CMS's public site is written as - would
2583
+ // match EVERY pathname first and shadow every real route. The order is
2584
+ // stable within a class, so an app without catch-alls is unchanged.
2585
+ .sort((a, b) => {
2586
+ const rank = (pattern: string): number[] => {
2587
+ const segs = pattern.split('/');
2588
+ return [
2589
+ segs.filter((s) => s.startsWith('**')).length,
2590
+ segs.filter((s) => s.startsWith('*')).length,
2591
+ segs.filter((s) => s.startsWith(':')).length,
2592
+ ];
2593
+ };
2594
+ const ra = rank(a.info.pattern);
2595
+ const rb = rank(b.info.pattern);
2596
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2597
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2598
+ });
2488
2599
 
2489
- // API routes (pages/api/*.rose) dispatch handlers, never render HTML: they live in the
2490
- // server bundle only and are excluded from the client route table entirely.
2491
2600
  const apiRoutes = infos
2492
2601
  .map((info, i) => ({ info, i }))
2493
- .filter(({ info }) => info.isApi);
2602
+ .filter(({ info }) => info.isApi)
2603
+ .sort((a, b) => {
2604
+ const rank = (pattern: string): number[] => {
2605
+ const segs = pattern.split('/');
2606
+ return [
2607
+ segs.filter((s) => s.startsWith('**')).length,
2608
+ segs.filter((s) => s.startsWith('*')).length,
2609
+ segs.filter((s) => s.startsWith(':')).length,
2610
+ ];
2611
+ };
2612
+ const ra = rank(a.info.pattern);
2613
+ const rb = rank(b.info.pattern);
2614
+ for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
2615
+ return a.info.filePath < b.info.filePath ? -1 : 1;
2616
+ });
2494
2617
 
2495
- // Compose render chains: page wrapped by its layouts (deepest first)
2496
2618
  const compose = (idx: number): string => {
2497
2619
  let expr = `render_${idx}`;
2498
2620
  for (const i of layoutsOf(infos, idx)) {
@@ -2501,45 +2623,31 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2501
2623
  return expr;
2502
2624
  };
2503
2625
 
2504
- // Mode B. `export const bundle = 'split'` (declared once, the root layout) turns every
2505
- // route's client module into its own chunk: the document references /client.js externally …
2506
2626
  const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? 'inline';
2507
2627
  const split = bundleMode === 'split';
2508
- // The chain a route's chunk graph must load: the page first, then its layouts
2509
- // deepest-first - exactly compose()'s nesting order …
2510
2628
  const chainOf = (idx: number): number[] => [idx, ...layoutsOf(infos, idx)];
2511
- // Mode B's loader expression: literal dynamic imports (esbuild needs the paths statically
2512
- // analyzable to emit one chunk per module) …
2513
2629
  const loaderInner = (idx: number): string =>
2514
2630
  `load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(', ')}])`;
2515
2631
  const loaderOf = (idx: number): string => `{ ${loaderInner(idx)} }`;
2516
2632
 
2517
- // The compiler decides zero-JS, not the developer. A route ships no client bundle - no
2518
- // runtime, no state script, zero JavaScript …
2519
2633
  const routeNoJs = (i: number): boolean => routeShipsNoJs(infos, compiled, i);
2520
2634
 
2521
2635
  const serverImports = compiled
2522
2636
  .map((_, i) => {
2523
- if (!reachable.has(i)) return ''; // an unimported component ships nowhere
2637
+ if (!reachable.has(i)) return '';
2524
2638
  if (infos[i].isMiddleware) {
2525
- // pages/_middleware.rose: server-only, imported as a namespace so a missing
2526
- // `handle` export is simply "no middleware" (null), never a build error
2527
2639
  return `import * as middlewareMod from './comp-${i}.ssr.js';`;
2528
2640
  }
2529
2641
  if (infos[i].isApi) {
2530
- // api route: import its HTTP-method handlers (aliased per component)
2531
2642
  const names = compiled[i].apiMethods ?? [];
2532
2643
  const handlerImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
2533
2644
  return handlerImports
2534
2645
  ? `import { ${handlerImports} } from './comp-${i}.ssr.js';`
2535
2646
  : `import './comp-${i}.ssr.js';`;
2536
2647
  }
2537
- // a page's server actions are imported alongside its render; layouts
2538
- // and the 404 page never receive POSTs, so they never need one
2539
2648
  const isPage = !infos[i].isLayout && !infos[i].isNotFound;
2540
2649
  const names = isPage ? compiled[i].actionNames : [];
2541
2650
  const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
2542
- // The action guard rides the same import, server-only like the actions it fronts
2543
2651
  const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : '';
2544
2652
  const named = [actionImports, guardImport].filter(Boolean).join(', ');
2545
2653
  return named
@@ -2548,25 +2656,27 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2548
2656
  })
2549
2657
  .join('\n');
2550
2658
 
2551
- // pages/404.rose renders for unmatched routes (SSR + client), wrapped in
2552
- // its layouts like any other page; absent -> the built-in plain 404.
2553
- const nfIdx = infos.findIndex((info) => info.isNotFound);
2554
- const notFoundRender = nfIdx >= 0 ? (split ? loaderOf(nfIdx) : compose(nfIdx)) : 'null';
2659
+ const notFoundEntries = infos
2660
+ .map((info, i) => ({ info, i }))
2661
+ .filter(({ info }) => info.isNotFound)
2662
+ .map(({ info, i }) => {
2663
+ const rel = path.relative(path.join(root, 'src', 'pages'), info.filePath).replace(/\\/g, '/');
2664
+ const dir = path.posix.dirname(rel);
2665
+ const prefix = dir === '.' ? '/' : '/' + dir;
2666
+ const flags = routeShellOff(infos, compiled, i) ? ', { shell: false }' : '';
2667
+ return { prefix, render: split ? loaderOf(i) : compose(i), flags };
2668
+ })
2669
+ .sort((a, b) => b.prefix.length - a.prefix.length);
2670
+ const notFoundTable = `[\n${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join('\n')}\n]`;
2555
2671
 
2556
- // pages/500.rose renders for routes whose render throws (a dead $data source, a bad
2557
- // expression): the page degrades instead of crashing the response …
2558
2672
  const errIdx = infos.findIndex((info) => info.isError);
2559
2673
  const errorRender = errIdx >= 0 ? (split ? loaderOf(errIdx) : compose(errIdx)) : 'null';
2560
2674
 
2561
- // pages/_middleware.rose: the request interceptor (absent -> null).
2562
2675
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
2563
2676
 
2564
2677
  const serverRoutes = pages
2565
2678
  .map(({ info, i }) => {
2566
- // actions: name -> imported fn, so a POST's __action field …
2567
2679
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(', ');
2568
- // csr: false rides on the route so renderPage/renderPageStream can drop the state
2569
- // script + bundle from the document (; the decision is the compiler's since #29).
2570
2680
  if (compiled[i].csr === false && compiled[i].needsClient) {
2571
2681
  throw new RoseError(
2572
2682
  'E-EXPORT',
@@ -2587,13 +2697,11 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2587
2697
  }
2588
2698
  }
2589
2699
  const csrFlag = routeNoJs(i) ? ', csr: false' : '';
2590
- // P0-2 (bug report): `buffer = true` rides on the route so the servers can keep it
2591
- // off the streaming path …
2700
+ const shellFlag = routeShellOff(infos, compiled, i) ? ', shell: false' : '';
2592
2701
  const bufferFlag = compiled[i].buffer ? ', buffer: true' : '';
2593
- // Guard - runs before every action of this route (null when the
2594
- // page exports no beforeAction)
2702
+ const signalFlag = compiled[i].controlSignal ? ', signal: true' : '';
2595
2703
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : '';
2596
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag}${bufferFlag} }`;
2704
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
2597
2705
  })
2598
2706
  .join(',\n ');
2599
2707
 
@@ -2609,12 +2717,7 @@ const __pluginHooks = [];
2609
2717
  const __hasRequestHooks = false;
2610
2718
  const __hasResponseHooks = false;`}
2611
2719
 
2612
- // The runtime plugin hooks. onRequest runs before routing and
2613
- // middleware and may short-circuit the request with its own Response; onResponse
2614
- // runs once the response exists and may replace it. Both are no-ops when the
2615
- // project declares no runtime hooks. A throwing hook is logged and skipped -
2616
- // the request continues - so a broken logging plugin can never take a site
2617
- // down (a build-time transform, by contrast, fails loudly).
2720
+
2618
2721
  export async function runRequestHooks(ctx) {
2619
2722
  for (const p of __pluginHooks) {
2620
2723
  if (!p.onRequest) continue;
@@ -2642,32 +2745,20 @@ export async function runResponseHooks(ctx, res) {
2642
2745
  return out;
2643
2746
  }
2644
2747
 
2645
- // The servers read these to skip building the hook context entirely when no
2646
- // hook exists - the hot path pays nothing for the feature.
2748
+
2749
+
2647
2750
  export const hasRequestHooks = __hasRequestHooks;
2648
2751
  export const hasResponseHooks = __hasResponseHooks;
2649
2752
 
2650
- // P0-1: the query of the request being rendered, for $query(). The servers
2651
- // call this before every render (stream, buffered, POST, api) with the parsed
2652
- // query string; routing itself matches the pathname, which is what fixed the
2653
- // query-404. A render with no query (the build's prerender, the ISR
2654
- // background pass) passes {} explicitly - the bag is per request, so a stale
2655
- // one must never leak into the next.
2753
+ // P0-1: the query of the request being rendered, for $query().
2656
2754
  export function setQuery(query) {
2657
2755
  setRequestQuery(query || {});
2658
2756
  }
2659
2757
 
2660
- // i18n: the dictionaries baked at build time from
2661
- // src/locales/*.json. A route segment named [lang] is the locale: the value
2662
- // must name one of these dictionaries, and $t resolves keys against it.
2758
+
2663
2759
  setLocales(${localesJson}, '${defaultLocale}');
2664
2760
 
2665
- // The store transport. Under "rosetack serve" every worker is its
2666
- // own process with its own dist/server.js module, so a $store write must
2667
- // travel: this worker -> primary -> every other worker. process.send exists
2668
- // only inside cluster workers, so a single-process runner (dev, preview,
2669
- // the edge adapter) keeps the transport null and $store stays plain
2670
- // per-process state - the documented boundary, not a bug.
2761
+
2671
2762
  if (typeof process !== 'undefined' && typeof process.send === 'function') {
2672
2763
  setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
2673
2764
  process.on('message', (msg) => {
@@ -2675,76 +2766,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
2675
2766
  });
2676
2767
  }
2677
2768
 
2769
+ // (the cross-machine seam): the cluster relay above covers ONE machine.
2770
+ export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
2771
+ setStoreTransport(send);
2772
+ }
2773
+ export function __deliverStorePatch(name: string, value: unknown): void {
2774
+ applyStorePatch(name, value);
2775
+ }
2776
+
2678
2777
  export { localeList };
2679
2778
  export const defaultLocale = '${defaultLocale}';
2680
2779
 
2681
- // Route params maps, re-exported for the build's prerender step: routePath
2682
- // -> the component's exported params (a static map or a function). Reading
2683
- // them through the server bundle keeps the deploy dir free of component
2684
- // modules - both bundles are self-contained, nothing else may ship. Only
2685
- // components that actually export params appear here (a missing export
2686
- // means the dynamic route renders on demand).
2780
+ // Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
2687
2781
  ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join('\n')}
2688
2782
 
2689
2783
  export const routeParams = {
2690
2784
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(',\n ')}
2691
2785
  };
2692
2786
 
2693
- // Routes whose component reads the request context (getContext()), mutates a
2694
- // shared store ($store()), reads the query ($query(), P0-1), opted into
2695
- // nonce-based CSP or into the buffered path (buffer = true, P0-2):
2696
- // the bag is per-request, the store is per-process, a nonce is per-response,
2697
- // and a buffered route's hooks must run per request - so these are dynamic.
2698
- // The build never bakes them and the servers never answer them from a
2699
- // prerendered file. Public routes keep the static fast path (file cache,
2700
- // ETag/304, streaming) untouched.
2787
+ // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
2701
2788
  export const dynamicRoutes = [
2702
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2789
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2703
2790
  ];
2704
2791
 
2705
- // Which api routes opt into build-time baking (export const prerender = true):
2706
- // routePath -> boolean. The build calls the GET handler once and writes the
2707
- // body to dist/, so the Go single binary serves read-only APIs without Node.
2792
+ // Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
2708
2793
  ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join('\n')}
2709
2794
 
2710
2795
  export const apiPrerender = {
2711
2796
  ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : 'false'}`).join(',\n ')}
2712
2797
  };
2713
2798
 
2714
- // Stale-while-revalidate windows (export const revalidate = N): the build
2715
- // bakes these routes like any other, and the preview server serves the
2716
- // baked file for up to N seconds - after which the next request is answered
2717
- // STALE (instant, from disk) while a background pass re-renders and swaps
2718
- // the file (ISR). Routes that read the request context are
2719
- // excluded: they render per request and have no baked file to revalidate.
2720
- // The dev server ignores the window (it rebuilds on change), the edge
2721
- // adapter renders live (always fresh), and the Go binary serves the baked
2722
- // file forever - the same static-half boundary as page POSTs.
2799
+
2723
2800
  export const revalidate = [
2724
2801
  ${pages.filter(({ i }) => compiled[i].revalidate !== undefined && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(',\n ')}
2725
2802
  ];
2726
2803
 
2727
- // pages/_middleware.rose: a Web-standard request handler that runs before
2728
- // every render on the server (pages, POSTs, api calls alike). Returning a
2729
- // Response short-circuits the whole request - a redirect, an auth wall, a
2730
- // rewrite; returning nothing continues, and getContext() hands the
2731
- // per-request bag to $data, server actions and api handlers. Absent -> null,
2732
- // and the servers keep their static fast paths.
2804
+ // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
2733
2805
  export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
2734
2806
 
2735
- // Routes whose DOCUMENTS ship without the client bundle (
2736
- // decided by the compiler since #29): HTML + CSS only - no runtime, no
2737
- // state script, zero JavaScript for whoever lands on them. The compiler
2738
- // picks these automatically: a route whose whole chain needs nothing from
2739
- // the client (no event wiring, no lifecycle, no action, no form) is a
2740
- // content route. An exported "csr = true" forces the bundle back in; an
2741
- // exported "csr = false" is the same decision, asserted. The route's render
2742
- // function still rides in the client bundle, so a client-side navigation
2743
- // from an interactive page paints it normally and a static deploy's SPA
2744
- // fallback can render it too; only the document is JS-free.
2745
- // isNoJs() lets the servers keep these routes on the buffered path: a
2746
- // streamed no-JS document would carry the shell's default <title> (the
2747
- // route head is applied client-side at boot, and there is no client).
2807
+ // Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
2748
2808
  export const noJsRoutes = [
2749
2809
  ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(',\n ')}
2750
2810
  ];
@@ -2753,21 +2813,12 @@ export function isNoJs(pathname) {
2753
2813
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
2754
2814
  }
2755
2815
 
2756
- // P0-2 (bug report): routes that exported "buffer = true". The servers ask
2757
- // this BEFORE choosing a path: a streamed response commits its status and
2758
- // headers before the body exists, so its onResponse hooks cannot see the
2759
- // document and a render that throws mid-flight still answers 200. A buffered
2760
- // route keeps every capability and gives up the early flush - the trade is
2761
- // the route's to make, per route, not the framework's.
2816
+ // P0-2 (bug report): routes that exported "buffer = true".
2762
2817
  export function isBuffered(pathname) {
2763
- return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
2818
+ return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
2764
2819
  }
2765
2820
 
2766
- // Per-route response headers: a route exporting a headers
2767
- // map carries them into every response the servers write for it, merged
2768
- // OVER the framework defaults (the strict CSP) - so an app can tighten or
2769
- // relax the policy per route. Absent -> null, and the servers keep sending
2770
- // the defaults alone.
2821
+
2771
2822
  export const routeHeaders = [
2772
2823
  ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(',\n ')}
2773
2824
  ];
@@ -2777,14 +2828,7 @@ export function headersFor(pathname) {
2777
2828
  return hit ? hit.headers : null;
2778
2829
  }
2779
2830
 
2780
- // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
2781
- // ). The servers ask this BEFORE writing a document: when it is true they
2782
- // mint one random nonce per response, put it in the CSP header ('nonce-...'
2783
- // plus 'strict-dynamic', so the document's own code may load more code) and
2784
- // stamp the same value on the script tag. The default policy stays a hash -
2785
- // cspNonceRoutes is empty for an app that never asks, so the fast path is
2786
- // unchanged. The Go binary never sees this: these routes are dynamic, so it
2787
- // has no baked file for them to serve.
2831
+
2788
2832
  export const cspNonceRoutes = [
2789
2833
  ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2790
2834
  ];
@@ -2793,9 +2837,7 @@ export function cspNonce(pathname) {
2793
2837
  return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
2794
2838
  }
2795
2839
 
2796
- // A Web-standard Request from whatever the host provides: the edge adapter
2797
- // passes one already; the Node server passes its IncomingMessage (plus the
2798
- // already-parsed FormData for POSTs, so middleware can read form fields).
2840
+ // A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
2799
2841
  function toWebRequest(raw, form) {
2800
2842
  if (raw instanceof Request) return raw;
2801
2843
  const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
@@ -2803,13 +2845,7 @@ function toWebRequest(raw, form) {
2803
2845
  return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
2804
2846
  }
2805
2847
 
2806
- // Runs the middleware (if the project has one) for this request and returns
2807
- // its short-circuit Response, or null to continue. The servers call this
2808
- // EXACTLY ONCE per request, before anything else: it resets the per-request
2809
- // context bag and the middleware fills it via getContext(), which $data,
2810
- // server actions and api handlers then read while rendering. rawReq: the
2811
- // host's request (Node IncomingMessage or a Web-standard Request); form:
2812
- // the already-parsed FormData of a POST.
2848
+
2813
2849
  export async function runMiddleware(rawReq, form) {
2814
2850
  resetRequestContext();
2815
2851
  if (!middleware || !rawReq) return null;
@@ -2821,10 +2857,7 @@ const routes = [
2821
2857
  ${serverRoutes}
2822
2858
  ];
2823
2859
 
2824
- // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
2825
- // render HTML and never reach the client bundle. The middleware ran before
2826
- // this (the servers call runMiddleware() first), so handlers can read
2827
- // getContext() for auth without re-running anything.
2860
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
2828
2861
  const apiRoutes = [
2829
2862
  ${apiRoutes.map(({ info, i }) => {
2830
2863
  const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(', ');
@@ -2832,19 +2865,40 @@ const apiRoutes = [
2832
2865
  }).join(',\n ')}
2833
2866
  ];
2834
2867
 
2835
- // pages/404.rose (with its layouts) or null -> built-in plain 404
2836
- const notFound = ${notFoundRender};
2868
+ // Not-found pages, deepest segment first: the root 404.rose ('/') and any
2869
+ // pages/<seg>/_notfound.rose, each already composed with its layout chain.
2870
+ // notFoundFor picks the nearest one up the path - an /admin miss answers
2871
+ // the admin 404, a public miss the site's - and notFoundPage is the whole
2872
+ // answer (real 404 status, or the built-in plain 404 when the app has none).
2873
+ const notFoundRoutes = ${notFoundTable};
2874
+ const notFoundFor = (pathname) => {
2875
+ for (const [prefix, render] of notFoundRoutes) {
2876
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
2877
+ }
2878
+ return null;
2879
+ };
2880
+
2881
+ const notFoundFlags = (pathname) => {
2882
+ for (const [prefix, render, flags] of notFoundRoutes) {
2883
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
2884
+ }
2885
+ return null;
2886
+ };
2887
+ const notFoundPage = async (pathname) => {
2888
+ const nf = notFoundFor(pathname);
2889
+ if (nf) {
2890
+ const page = await renderFallback(pathname, nf);
2891
+ // __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
2892
+ return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
2893
+ }
2894
+ return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
2895
+ };
2896
+
2837
2897
 
2838
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
2839
2898
  // whose render throws degrades to this instead of failing the response.
2840
2899
  const errorPage = ${errorRender};
2841
2900
 
2842
- // The <html> attributes of the document for a pathname - the locale
2843
- // of its [lang] segment (the default when there is none, or when the segment
2844
- // names no dictionary: that request 404s in the default language) and the
2845
- // reading direction that locale implies. The buffered render returns the same
2846
- // pair; the streaming path needs it BEFORE the shell flushes, which is why
2847
- // the servers ask for it by pathname.
2901
+
2848
2902
  export function docAttrs(pathname) {
2849
2903
  for (const route of routes) {
2850
2904
  if (!matchRoute(route.pattern, pathname)) continue;
@@ -2854,7 +2908,7 @@ export function docAttrs(pathname) {
2854
2908
  const lang = pathname.split('/')[langIdx];
2855
2909
  if (isLocale(lang)) return { lang, dir: localeDir(lang) };
2856
2910
  }
2857
- break; // matched, but not a localized route (or a bogus locale): the default
2911
+ break;
2858
2912
  }
2859
2913
  return { lang: defaultLocale, dir: localeDir(defaultLocale) };
2860
2914
  }
@@ -2867,8 +2921,22 @@ async function renderFallback(pathname, render) {
2867
2921
  }
2868
2922
 
2869
2923
  export function matchRoute(pattern, pathname) {
2924
+ // Q0 (bug report): one canonical URL per route.
2925
+ pathname = pathname.replace(/\\/+$/, '') || '/';
2870
2926
  const patternParts = pattern.split('/');
2871
2927
  const pathParts = pathname.split('/');
2928
+
2929
+ const last = patternParts[patternParts.length - 1];
2930
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
2931
+ const fixed = patternParts.slice(0, -1);
2932
+ if (pathParts.length < fixed.length) return false;
2933
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
2934
+ for (let i = 0; i < fixed.length; i++) {
2935
+ if (fixed[i].startsWith(':')) continue;
2936
+ if (fixed[i] !== pathParts[i]) return false;
2937
+ }
2938
+ return true;
2939
+ }
2872
2940
  if (patternParts.length !== pathParts.length) return false;
2873
2941
  for (let i = 0; i < patternParts.length; i++) {
2874
2942
  if (patternParts[i].startsWith(':')) continue;
@@ -2877,13 +2945,7 @@ export function matchRoute(pattern, pathname) {
2877
2945
  return true;
2878
2946
  }
2879
2947
 
2880
- // Head blocks (one per component in the route chain) are pulled out of the
2881
- // page html: the shell injects them into <head>, and the client re-applies
2882
- // them on navigation. Document order is page-first, so the shell's keyed
2883
- // merge lets a page override its layouts. The EMPTY marker pair stays in the
2884
- // body so the client's wire() still finds the block: at boot it adopts the
2885
- // shell-injected elements in place (marked with the same keys, so no
2886
- // duplicates) and keeps the head reactive.
2948
+ // Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
2887
2949
  function extractHead(rendered) {
2888
2950
  const head = [];
2889
2951
  const html = rendered.replace(/<!--\u27e6h:(\\d+)\u27e7-->([\\s\\S]*?)<!--\u27e6\\/h:\\1\u27e7-->/g, (_, id, content) => {
@@ -2893,18 +2955,7 @@ function extractHead(rendered) {
2893
2955
  return { html, head };
2894
2956
  }
2895
2957
 
2896
- // form: the submitted FormData of a progressive-enhancement POST. The
2897
- // selected server action runs first and returns a state patch (e.g.
2898
- // { guests: [...] }); seeding those keys BEFORE the render makes state()
2899
- // adopt them, so the response is the page as it looks AFTER the action -
2900
- // with or without JS. A __action field picks the action by name (default
2901
- // 'action', the conventional <form method="POST"> target); a click handler
2902
- // bound to an action ($action('like')) sends the same field.
2903
- // A route whose render throws degrades to pages/500.rose (status 500) - or
2904
- // the built-in plain 500 - instead of failing the whole response.
2905
- // The middleware does NOT run here: the servers run it once per request via
2906
- // runMiddleware() (which also seeds the request context), so a page render
2907
- // never re-runs it.
2958
+ // Form: the submitted FormData of a progressive-enhancement POST.
2908
2959
  export async function renderPage(pathname, form) {
2909
2960
  clearRequestState();
2910
2961
  for (const route of routes) {
@@ -2912,31 +2963,21 @@ export async function renderPage(pathname, form) {
2912
2963
  const patternParts = route.pattern.split('/');
2913
2964
  const pathParts = pathname.split('/');
2914
2965
  for (let i = 0; i < patternParts.length; i++) {
2915
- if (patternParts[i].startsWith(':')) {
2916
- setState(patternParts[i].slice(1), pathParts[i]);
2917
- }
2966
+ const seg = patternParts[i];
2967
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
2968
+
2969
+
2970
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
2918
2971
  }
2919
- // i18n: a [lang] segment naming no dictionary is a
2920
- // 404 - the URL is the contract, and rendering the page with fallback
2921
- // strings would serve duplicate content under a bogus language
2972
+ // I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
2922
2973
  const langIdx = patternParts.indexOf(':lang');
2923
2974
  if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
2924
- if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
2925
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
2975
+ return await notFoundPage(pathname);
2926
2976
  }
2927
- // The document's <html lang>/<dir> follow this route's locale
2928
- // (the default's when the route is not localized)
2977
+
2978
+
2929
2979
  const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
2930
- // The action dispatch. The page's guard (exported
2931
- // beforeAction) runs FIRST and vetoes with an ActionError - the
2932
- // action-level permission check. Then the selected action runs and its
2933
- // return value seeds this render's state, per key, so an incremental
2934
- // patch ($append and friends) grows a large list by one row instead of
2935
- // re-sending the whole thing. An ActionError from either half is a
2936
- // BUSINESS failure: it is seeded as the 'actionError' state, the
2937
- // response carries its status, and the page renders with the failure
2938
- // visible (a {#boundary} around the action's widget contains it).
2939
- // Anything else is a bug and keeps going to the 500 page.
2980
+ // The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
2940
2981
  let actionStatus = 0;
2941
2982
  if (form && route.actions) {
2942
2983
  const actionName = form.get('__action') || 'action';
@@ -2948,9 +2989,7 @@ export async function renderPage(pathname, form) {
2948
2989
  if (patch && typeof patch === 'object') {
2949
2990
  for (const key of Object.keys(patch)) {
2950
2991
  const v = patch[key];
2951
- // An incremental patch is RECORDED, not applied: the render's
2952
- // own state declarations apply it, so the delta is relative to
2953
- // the value the page was going to render anyway.
2992
+ // An incremental patch is RECORDED, not applied: the render's own state declarations apply.
2954
2993
  if (v instanceof StateDelta) setStateDelta(key, v);
2955
2994
  else setState(key, v);
2956
2995
  }
@@ -2959,6 +2998,11 @@ export async function renderPage(pathname, form) {
2959
2998
  if (err instanceof ActionError) {
2960
2999
  setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
2961
3000
  actionStatus = err.code;
3001
+ } else if (err && err.__rosetack === 'redirect') {
3002
+
3003
+ return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
3004
+ } else if (err && err.__rosetack === 'notFound') {
3005
+ return await notFoundPage(pathname);
2962
3006
  } else {
2963
3007
  throw err;
2964
3008
  }
@@ -2969,32 +3013,27 @@ export async function renderPage(pathname, form) {
2969
3013
  try {
2970
3014
  rendered = extractHead(await route.render([], ''));
2971
3015
  } catch (err) {
3016
+ // The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
3017
+ const signal = err && err.__rosetack;
3018
+ if (signal === 'redirect') {
3019
+ return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
3020
+ }
3021
+ if (signal === 'notFound') {
3022
+ return await notFoundPage(pathname);
3023
+ }
2972
3024
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2973
3025
  if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
2974
3026
  return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2975
3027
  }
2976
3028
  // __route tells the bootstrap which route this document was rendered for.
2977
- // A static-file server may serve another route's document (SPA fallback);
2978
- // the bootstrap then client-renders instead of adopting mismatched DOM.
2979
3029
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2980
- // csr ( auto since #29): false when the compiler found
2981
- // nothing in the route's chain that needs the client (or the route
2982
- // asserted csr = false) - the document ships no runtime, no state
2983
- // script, zero JavaScript. Every other route keeps the bundle. The
2984
- // caller passes this straight to the shell as js.
2985
- // Status is the failed action's code when one failed - the page
2986
- // rendered fine, so the body is the page with the failure visible, and
2987
- // the status says what happened (a 403 from the guard, a 422 from a
2988
- // validation action). 200 otherwise.
2989
- // Lang/dir are the document's <html> attributes - the locale
2990
- // this route rendered in, and its reading direction.
2991
- return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
3030
+ // 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) .
3031
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
2992
3032
  }
2993
3033
  }
2994
- if (notFound) {
2995
- return { ...(await renderFallback(pathname, notFound)), status: 404 };
2996
- }
2997
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
3034
+
3035
+
3036
+ return await notFoundPage(pathname);
2998
3037
  }
2999
3038
 
3000
3039
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -3002,21 +3041,20 @@ export async function renderPage(pathname, form) {
3002
3041
  export function canStream(pathname) {
3003
3042
  return routes.some((route) => {
3004
3043
  if (!matchRoute(route.pattern, pathname)) return false;
3005
- // i18n: an unknown locale must answer 404, and a
3006
- // streamed response cannot change its status - so it takes the buffered
3007
- // path (renderPage returns the real 404), never the streaming one
3044
+ // I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
3008
3045
  const langIdx = route.pattern.split('/').indexOf(':lang');
3009
3046
  return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
3010
3047
  });
3011
3048
  }
3012
3049
 
3013
- // === API routes ===
3014
- // The /api namespace answers JSON, never HTML: an API client that hits an
3015
- // unknown path must not receive the SPA shell. Handlers receive a
3016
- // Web-standard Request and return a plain object (serialized as JSON, 200),
3017
- // a Response (passed through), or nothing (204). A method the route does
3018
- // not export answers 405 with an Allow header. Same code path on the Node
3019
- // server and the edge adapter - Response is a global in both.
3050
+
3051
+ export function shellOff(pathname) {
3052
+ return routes.some(
3053
+ (route) => route.shell === false && matchRoute(route.pattern, pathname),
3054
+ );
3055
+ }
3056
+
3057
+ // === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
3020
3058
  export function isApi(pathname) {
3021
3059
  return pathname === '/api' || pathname.startsWith('/api/');
3022
3060
  }
@@ -3040,7 +3078,25 @@ export async function handleApi(method, pathname, request) {
3040
3078
  headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
3041
3079
  });
3042
3080
  }
3043
- return toResponse(await fn(request));
3081
+ try {
3082
+ return toResponse(await fn(request));
3083
+ } catch (err) {
3084
+
3085
+ const signal = err && err.__rosetack;
3086
+ if (signal === 'redirect') {
3087
+ return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
3088
+ status: err.status ?? 307,
3089
+ headers: { 'content-type': 'application/json', location: err.path },
3090
+ });
3091
+ }
3092
+ if (signal === 'notFound') {
3093
+ return new Response(JSON.stringify({ error: 'not found' }), {
3094
+ status: 404,
3095
+ headers: { 'content-type': 'application/json' },
3096
+ });
3097
+ }
3098
+ throw err;
3099
+ }
3044
3100
  }
3045
3101
  }
3046
3102
  return new Response(JSON.stringify({ error: 'not found' }), {
@@ -3049,18 +3105,7 @@ export async function handleApi(method, pathname, request) {
3049
3105
  });
3050
3106
  }
3051
3107
 
3052
- // === Streaming SSR ===
3053
- // The static shell (doctype, <head>, body + container open) flushes BEFORE
3054
- // the - possibly slow - render completes: the first byte leaves in
3055
- // microseconds instead of after every $data resolves. The route HTML, the
3056
- // state script, and the inlined bundle follow as later chunks of one chunked
3057
- // response - still exactly one request.
3058
- // The route's <head> tags are NOT in the streamed document: the client
3059
- // applies them at boot from the body's head markers, so JS users see the
3060
- // correct head immediately; no-JS consumers of streamed responses get the
3061
- // static shell head (prerendered files stay complete documents).
3062
- // Returns 200 (matched; a render throw degrades to the error-page body) or
3063
- // 404 (unmatched - nothing written, so the caller can still buffer).
3108
+ // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
3064
3109
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3065
3110
  clearRequestState();
3066
3111
  for (const route of routes) {
@@ -3068,9 +3113,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3068
3113
  const patternParts = route.pattern.split('/');
3069
3114
  const pathParts = pathname.split('/');
3070
3115
  for (let i = 0; i < patternParts.length; i++) {
3071
- if (patternParts[i].startsWith(':')) {
3072
- setState(patternParts[i].slice(1), pathParts[i]);
3073
- }
3116
+ const seg = patternParts[i];
3117
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
3118
+
3119
+
3120
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
3074
3121
  }
3075
3122
  // i18n: an unknown locale must 404 BEFORE the shell flushes - a
3076
3123
  // streamed response cannot change its status afterwards
@@ -3081,23 +3128,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3081
3128
  try {
3082
3129
  html = extractHead(await route.render([], '')).html;
3083
3130
  } catch (err) {
3084
- // the shell is already on the wire: degrade to the error page BODY
3085
- // (the status stays 200 - a real 500 needs the buffered path, which
3086
- // the server picks for routes known-broken at build time)
3131
+
3087
3132
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
3088
3133
  html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
3089
3134
  }
3090
3135
  write(html);
3091
- // csr: false ( auto since #29): a no-JS route's document
3092
- // ends here - no state script, no inlined bundle. (The servers keep
3093
- // these routes off the streaming path so their <head> is complete;
3094
- // this is the correctness floor if one streams anyway.)
3136
+ // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
3095
3137
  if (route.csr === false) {
3096
3138
  write('</div>\\n</body>\\n</html>');
3097
3139
  return 200;
3098
3140
  }
3099
3141
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
3100
- write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
3142
+ // P1-6 (bug report): the JSON data block is embedded in the document.
3143
+ const stateSafe = state.replace(/</g, '\\\\u003c');
3144
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
3101
3145
  return 200;
3102
3146
  }
3103
3147
  }
@@ -3115,8 +3159,6 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3115
3159
  ...TS_LOADER,
3116
3160
  });
3117
3161
 
3118
- // api routes and the middleware have no client module: they are server-only handlers /
3119
- // interceptors.
3120
3162
  const clientImports = split ? '' : compiled
3121
3163
  .map((_, i) => ({ i }))
3122
3164
  .filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i))
@@ -3129,18 +3171,12 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3129
3171
  : `{ pattern: '${info.pattern}', render: ${compose(i)} }`))
3130
3172
  .join(',\n ');
3131
3173
 
3132
- // P1: the app-global prefetch strategy, declared once (the root layout) as `export const
3133
- // prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
3134
3174
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? 'all';
3135
- // The client-side web-vitals hook, declared once (the root layout) as `export const vitals
3136
- // = true`. First declaration wins, app-global like prefetch.
3137
3175
  const vitalsOn = compiled.some((c) => c.vitals === true);
3138
- const vitalsBlock = vitalsOn
3139
- ? `\n// the app asked for web-vitals - measure once, at boot, and let the\n// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).\nreportVitals;\n`
3176
+ const vitalsBlock = vitalsOn
3177
+ ? `\n// the app asked for web-vitals - measure once, at boot, and let the\n// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).\nreportVitals();\n`
3140
3178
  : '';
3141
3179
 
3142
- // The <html lang dir> tracker only exists when the app actually has a [lang] route - an
3143
- // app without i18n pays nothing for it …
3144
3180
  const hasLang = infos.some((i) => i.pattern.includes(':lang'));
3145
3181
  const langDirBlock = hasLang
3146
3182
  ? ` // <html lang dir> follows the route - the one part of the document
@@ -3148,38 +3184,33 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3148
3184
  // logical properties both read it). A route with no [lang] segment
3149
3185
  // returns to the default locale, and a bogus segment falls back to it
3150
3186
  // too, exactly like the server's docAttrs.
3187
+ // Only when this container IS the document's app root. A mount
3188
+ // (dist/mount.js) renders into a foreign page, whose language and
3189
+ // direction belong to the host, not to the mounted route.
3151
3190
  const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
3152
3191
  const known = !seg || isLocale(seg);
3153
- const docLang = known && seg ? seg : __defLocale;
3154
- document.documentElement.lang = docLang;
3155
- const docDir = localeDir(docLang);
3156
- if (docDir) document.documentElement.setAttribute('dir', docDir);
3157
- else document.documentElement.removeAttribute('dir');
3192
+ if (container === document.getElementById('app')) {
3193
+ const docLang = known && seg ? seg : __defLocale;
3194
+ document.documentElement.lang = docLang;
3195
+ const docDir = localeDir(docLang);
3196
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
3197
+ else document.documentElement.removeAttribute('dir');
3198
+ }
3158
3199
  if (!known) {`
3159
3200
  : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
3160
3201
 
3161
3202
  const clientEntry = `
3162
3203
  ${clientImports}
3163
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
3164
-
3165
- // i18n: the dictionaries baked at build time - the client
3166
- // renders any PRELOADED locale from the bundle, so switching language costs
3167
- // zero requests (the same bet as the inlined route table). a locale
3168
- // the app left out of the preload (i18n.preload in rosetack.config.js) is a
3169
- // pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
3170
- // on first use - one request per language per session, then it renders from
3171
- // memory like any other. The default build preloads everything and ships no
3172
- // packs at all.
3204
+ 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';
3205
+
3206
+ // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
3173
3207
  setLocales(${clientLocalesJson}, '${defaultLocale}');
3174
3208
  setLocalePacks(${JSON.stringify(packed)});
3175
3209
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
3176
3210
  // follow a route that carries no [lang] segment (a non-i18n page)
3177
3211
  const __defLocale = '${defaultLocale}';` : ''}
3178
3212
  ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps\n// reportVitals alive through minification and tree-shaking; the call is one\n// statement at boot, before the first render.\nimport { reportVitals } from './runtime.js';`: ''}
3179
- // The two pack doors, re-exported for an app that wants to warm a language
3180
- // before its visitor asks for it (ensureLocale) or to feed a dictionary it
3181
- // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
3182
- // is what applyParams calls - so the re-export costs the statement alone.
3213
+ // 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.
3183
3214
  export { ensureLocale, loadLocale } from './runtime.js';
3184
3215
  ${vitalsBlock}
3185
3216
 
@@ -3187,14 +3218,7 @@ const routes = [
3187
3218
  ${clientRoutes}
3188
3219
  ];
3189
3220
 
3190
- // === Mode B: lazy route chunks ===
3191
- // Split mode's registry entries arrive without a render function: loadChain
3192
- // loads the route's module graph (the page plus its layouts, one chunk per
3193
- // module, the shared runtime in its own vendor chunk) in parallel and
3194
- // composes it at runtime - the exact nesting compose() built at compile
3195
- // time for inline mode. getRender memoizes the composed function on the
3196
- // entry, so a chunk loads once per session; inline mode's entries are the
3197
- // render functions themselves, so the helper is a pass-through there.
3221
+ // === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
3198
3222
  const loadChain = async (loaders) => {
3199
3223
  const mods = await Promise.all(loaders.map((load) => load()));
3200
3224
  let expr = (closes, children) => mods[0].render(closes, children);
@@ -3210,36 +3234,62 @@ const getRender = async (route) => {
3210
3234
  return (route.render ??= (await route.load()).render);
3211
3235
  };
3212
3236
 
3213
- // pages/404.rose (with its layouts) or null -> built-in plain 404
3214
- const notFound = ${notFoundRender};
3237
+ // Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
3238
+ const notFoundRoutes = ${notFoundTable};
3239
+ const notFoundFor = (pathname) => {
3240
+ for (const [prefix, render] of notFoundRoutes) {
3241
+ if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
3242
+ }
3243
+ return null;
3244
+ };
3215
3245
 
3216
- // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
3217
- // whose render throws on the client degrades to this instead of breaking
3218
- // navigation.
3246
+ // 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.
3219
3247
  const errorPage = ${errorRender};
3220
3248
 
3221
3249
  // Paint a fallback page (404/500) into the container, wired like any render.
3222
- async function paintFallback(container, page, builtin) {
3223
- resetEffects();
3224
- clearRequestState();
3250
+ async function paintFallback(container, page, builtin, keepState = false) {
3251
+ if (!keepState) __navReset(container);
3225
3252
  clearMounts(); // a failed render leaves stale mounts behind
3226
3253
  // inline mode passes the render itself; split mode passes a loader
3227
3254
  const render = page ? await getRender(page) : null;
3228
3255
  if (render) {
3229
3256
  const closes = [];
3230
- const html = await render(closes, '');
3231
- container.innerHTML = html;
3232
- wire(container, closes);
3233
- bindEvents(container);
3234
- flushMounts();
3257
+ await __withOwner(container, async () => {
3258
+ const html = await render(closes, '');
3259
+ container.innerHTML = html;
3260
+ wire(container, closes);
3261
+ bindEvents(container);
3262
+ flushMounts();
3263
+ });
3235
3264
  return;
3236
3265
  }
3237
3266
  container.innerHTML = builtin;
3238
3267
  }
3239
3268
 
3269
+
3270
+ export async function startNotFound(container, pathname) {
3271
+ const el = document.getElementById('__rosetack_state');
3272
+ if (el) resumeState(el.textContent);
3273
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
3274
+ }
3275
+
3240
3276
  export function matchRoute(pattern, pathname) {
3277
+ // Q0 (bug report): one canonical URL per route.
3278
+ pathname = pathname.replace(/\\/+$/, '') || '/';
3241
3279
  const patternParts = pattern.split('/');
3242
3280
  const pathParts = pathname.split('/');
3281
+
3282
+ const last = patternParts[patternParts.length - 1];
3283
+ if (last && (last.startsWith('*') || last.startsWith('**'))) {
3284
+ const fixed = patternParts.slice(0, -1);
3285
+ if (pathParts.length < fixed.length) return false;
3286
+ if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
3287
+ for (let i = 0; i < fixed.length; i++) {
3288
+ if (fixed[i].startsWith(':')) continue;
3289
+ if (fixed[i] !== pathParts[i]) return false;
3290
+ }
3291
+ return true;
3292
+ }
3243
3293
  if (patternParts.length !== pathParts.length) return false;
3244
3294
  for (let i = 0; i < patternParts.length; i++) {
3245
3295
  if (patternParts[i].startsWith(':')) continue;
@@ -3248,85 +3298,64 @@ export function matchRoute(pattern, pathname) {
3248
3298
  return true;
3249
3299
  }
3250
3300
 
3251
- // === Link prefetch ===
3252
- // Hover / focus / touch an internal link and the target route renders NOW -
3253
- // $data included - against a throwaway signal map. The click that follows
3254
- // paints from the cached HTML: no await, no request, no spinner. Other
3255
- // frameworks prefetch data only; rosetack prefetches the whole render because
3256
- // the inlined bundle already contains every route.
3257
- // Trade-off: the cache holds either a result or the in-flight promise (dedupes
3258
- // hover storms); one isolated render runs at a time so signal-map swapping
3259
- // stays correct without any merging logic. Entries are single-use: a consumed
3260
- // entry disappears from the cache, which is also how tests observe a hit.
3261
- // P1, three guards for link-heavy pages:
3262
- // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
3263
- // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
3264
- // Trade-off: app-global, not per-route - per-route would carry the mode
3265
- // in each document's shell.
3266
- // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
3267
- // the budget caps the QUEUE: a hover storm past it drops the excess
3268
- // instead of rendering fifty routes nobody clicks.
3269
- // 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
3270
- // is evicted first (Map iteration order; entries are single-use, so
3271
- // insertion order IS the recency order).
3301
+ // === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
3272
3302
  let prefetchMode = ${JSON.stringify(prefetchMode)};
3273
3303
  export function setPrefetchMode(mode) { prefetchMode = mode; }
3274
3304
  const PREFETCH_BUDGET = 8;
3275
3305
  const PREFETCH_MAX_CACHED = 4;
3276
- const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
3306
+ const prefetchCache = new Map();
3277
3307
  let prefetchQueue = Promise.resolve();
3278
3308
  let prefetchPending = 0;
3279
3309
 
3280
- // Applies the route's params to state. A [lang] segment whose dictionary is
3281
- // a runtime pack (i18n.preload) is awaited HERE - the one place every client
3282
- // render path goes through (navigation, prefetch, action adopt) - so a packed
3283
- // locale costs one request per session and then renders from memory. A
3284
- // preloaded locale (the default: every dictionary inline) resolves without
3285
- // touching the network, so the common path stays synchronous in spirit.
3310
+
3286
3311
  async function applyParams(route, pathname) {
3287
3312
  const patternParts = route.pattern.split('/');
3288
3313
  const pathParts = pathname.split('/');
3289
3314
  for (let i = 0; i < patternParts.length; i++) {
3290
- if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
3315
+ const seg = patternParts[i];
3316
+ if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
3317
+
3318
+
3319
+ else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
3291
3320
  }
3292
3321
  const langIdx = patternParts.indexOf(':lang');
3293
3322
  if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
3294
3323
  }
3295
3324
 
3325
+
3326
+ function __netOk() {
3327
+ const c = navigator.connection;
3328
+ if (!c) return true;
3329
+ if (c.saveData) return false;
3330
+ const t = c.effectiveType;
3331
+ return t !== 'slow-2g' && t !== '2g';
3332
+ }
3333
+
3296
3334
  export function prefetch(pathname, source = 'hover') {
3297
3335
  if (prefetchMode === 'off') return;
3298
3336
  if (prefetchMode === 'hover' && source !== 'hover') return;
3299
3337
  if (prefetchMode === 'viewport' && source !== 'viewport') return;
3338
+ if (!__netOk()) return; // save-data / 2g: no bytes before the click
3300
3339
  if (prefetchCache.has(pathname)) return;
3301
- if (pathname === location.pathname) return; // already here: nothing to prefetch
3340
+ if (pathname === location.pathname) return;
3302
3341
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
3303
3342
  if (!route) return;
3304
- if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
3305
- // P0-1: the link may carry a query (/search?q=cats). $query() reads the
3306
- // browser's own URL, which is the page being LEFT - so the prefetched
3307
- // render would see the wrong one. Override it for the duration and clear
3308
- // it after; the queue below serializes renders, so one slot is enough.
3343
+ if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
3309
3344
  const qi = pathname.indexOf('?');
3310
3345
  const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
3311
3346
  const p = prefetchQueue.then(async () => {
3312
3347
  try {
3313
3348
  setPrefetchOverride(qOverride);
3314
- // the isolated render also captures the onMount callbacks the route
3315
- // queued and the onCleanup disposers it registered: the paint that
3316
- // consumes this entry replays the mounts after wiring and adopts the
3317
- // cleanups, so the prefetched route's timers are disposed on the next
3318
- // navigation like any live route's
3349
+ // The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
3319
3350
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
3320
3351
  await applyParams(route, pathname); // a packed locale's dictionary lands before the render
3321
3352
  const closes = [];
3322
- const render = await getRender(route); // split mode: loads the route's chunk here
3353
+ const render = await getRender(route);
3323
3354
  const html = await render(closes, '');
3324
3355
  return { html, closes };
3325
3356
  });
3326
3357
  const entry = { ...result, state, mounts, cleanups };
3327
- prefetchCache.set(pathname, entry); // promise -> result
3328
- // evict oldest-first; in-flight promises are never evicted (evicting
3329
- // one would only force a duplicate render)
3358
+ prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
3330
3359
  while (prefetchCache.size > PREFETCH_MAX_CACHED) {
3331
3360
  const oldest = prefetchCache.keys().next().value;
3332
3361
  if (prefetchCache.get(oldest) instanceof Promise) break;
@@ -3334,7 +3363,7 @@ export function prefetch(pathname, source = 'hover') {
3334
3363
  }
3335
3364
  return entry;
3336
3365
  } catch {
3337
- prefetchCache.delete(pathname); // failed: the next hover retries
3366
+ prefetchCache.delete(pathname);
3338
3367
  return null;
3339
3368
  } finally {
3340
3369
  setPrefetchOverride(null);
@@ -3347,13 +3376,10 @@ export function prefetch(pathname, source = 'hover') {
3347
3376
  }
3348
3377
 
3349
3378
  export function prefetchStats() {
3350
- return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
3379
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
3351
3380
  }
3352
3381
 
3353
- // One delegated listener per event type on the app container: survives DOM
3354
- // swaps and cloned blocks, so handlers never need re-binding. A handler
3355
- // compiled from a server action (data-on-*="$action:name") dispatches to
3356
- // $action instead of the local handler registry.
3382
+ // One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
3357
3383
  const DELEGATED = ['click', 'input', 'change', 'submit'];
3358
3384
  function bindEvents(container) {
3359
3385
  if (container.__rosetack_bound) return;
@@ -3370,48 +3396,64 @@ function bindEvents(container) {
3370
3396
  }
3371
3397
  }
3372
3398
 
3373
- // === Server actions from any event ===
3374
- // POST the body to the current route and adopt the response in place: the
3375
- // server runs the selected action, seeds its state patch, and re-renders, so
3376
- // the swapped DOM is the page as it looks AFTER the action - one request, no
3377
- // reload, and wire() patches only the marked nodes (no re-render). The
3378
- // bootstrap's <form method="POST"> interception goes through the same door.
3379
- async function postForm(body) {
3380
- const res = await fetch(location.pathname, { method: 'POST', body });
3399
+ // === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
3400
+ async function postForm(body, container, pathname) {
3401
+
3402
+ const box = container || document.getElementById('app');
3403
+ const route = pathname || location.pathname;
3404
+ const res = await fetch(route, { method: 'POST', body });
3381
3405
  const html = await res.text();
3382
3406
  const doc = new DOMParser().parseFromString(html, 'text/html');
3383
3407
  const next = doc.getElementById('app');
3384
3408
  const st = doc.getElementById('__rosetack_state');
3385
3409
  const paint = () => {
3386
- const container = document.getElementById('app');
3387
- adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
3410
+ adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
3388
3411
  };
3389
3412
  if (document.startViewTransition) document.startViewTransition(paint);
3390
3413
  else paint();
3391
3414
  }
3392
3415
 
3393
- // Call a page's server action by name from any event handler:
3394
- // <button on:click={like}> compiles to $action('like'). Without JS the
3395
- // binding is inert - the progressive-enhancement story stays with forms.
3416
+ // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
3396
3417
  export async function $action(name, e) {
3397
3418
  if (e && e.preventDefault) e.preventDefault();
3398
3419
  const body = new FormData();
3399
3420
  body.append('__action', name);
3400
- return postForm(body);
3421
+ // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
3422
+ const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
3423
+ return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
3401
3424
  }
3402
3425
 
3403
3426
  export { postForm };
3404
3427
 
3405
- // The live signal graph as JSON - the same serializeState the zero-hydration
3406
- // resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
3407
- // can hand it to the dev server's reload bridge and to a devtools extension.
3408
- // A local re-export on purpose: it keeps the binding alive through minification
3409
- // for the bootstrap text appended after the bundle.
3428
+ // The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
3410
3429
  export { serializeState };
3411
3430
 
3412
- // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
3413
- // the existing nodes and bind events. initial=false: client-side navigation -
3414
- // re-render the route chain from scratch and wire the fresh DOM.
3431
+ // Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
3432
+
3433
+
3434
+ function __ownsDoc(container) {
3435
+ return container === document.getElementById('app');
3436
+ }
3437
+ function __navReset(container) {
3438
+ if (__ownsDoc(container)) {
3439
+ resetEffects();
3440
+ clearRequestState();
3441
+ } else {
3442
+ resetContainerFx(container);
3443
+ }
3444
+ }
3445
+ // Attribute everything a render creates (state keys, effects, onCleanups) to
3446
+ // its container. The document path sets no owner and keeps the global sets.
3447
+ async function __withOwner(container, fn) {
3448
+ if (__ownsDoc(container)) return fn();
3449
+ setFxOwner(container);
3450
+ try {
3451
+ return await fn();
3452
+ } finally {
3453
+ setFxOwner(null);
3454
+ }
3455
+ }
3456
+
3415
3457
  export async function start(container, pathname, initial) {
3416
3458
  clearMounts(); // stale mounts from a failed render never fire
3417
3459
  if (initial) {
@@ -3420,104 +3462,110 @@ export async function start(container, pathname, initial) {
3420
3462
  }
3421
3463
  for (const route of routes) {
3422
3464
  if (matchRoute(route.pattern, pathname)) {
3423
- // i18n: an unknown locale paints the 404 page, same as the server
3424
- // (before the prefetch check: a cached entry for a bogus locale is
3425
- // discarded, never painted)
3465
+ // 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).
3426
3466
  const langIdx = route.pattern.split('/').indexOf(':lang');
3427
3467
  ${langDirBlock}
3428
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
3468
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
3429
3469
  return;
3430
3470
  }
3431
- // Prefetched on hover/focus/touch: the render already ran, so paint its
3432
- // HTML and adopt its signal entries - events then patch the very nodes
3433
- // we wire, and no $data re-runs on click.
3471
+ // 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.
3434
3472
  let hit = initial ? undefined : prefetchCache.get(pathname);
3435
3473
  if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
3436
3474
  if (hit) {
3437
- prefetchCache.delete(pathname); // single-use: the next hover refetches
3438
- resetEffects();
3475
+ prefetchCache.delete(pathname);
3476
+ __navReset(container);
3439
3477
  restoreState(hit.state);
3440
3478
  container.innerHTML = hit.html;
3441
- wire(container, hit.closes);
3479
+ await __withOwner(container, () => {
3480
+ wire(container, hit.closes);
3481
+ bindEvents(container);
3482
+ hit.mounts.forEach((fn) => fn());
3483
+ adoptCleanups(hit.cleanups);
3484
+ });
3485
+ return;
3486
+ }
3487
+ if (!initial) __navReset(container);
3488
+ let broken = false;
3489
+ let signal = null;
3490
+ await __withOwner(container, async () => {
3491
+ await applyParams(route, pathname);
3492
+ const closes = [];
3493
+ let html;
3494
+ try {
3495
+ const render = await getRender(route);
3496
+ html = await render(closes, '');
3497
+ } catch (err) {
3498
+
3499
+ if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
3500
+ if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
3501
+
3502
+
3503
+ broken = true;
3504
+ return;
3505
+ }
3506
+ if (!initial) container.innerHTML = html;
3507
+ wire(container, closes);
3442
3508
  bindEvents(container);
3443
- hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
3444
- adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
3509
+ flushMounts();
3510
+ });
3511
+ if (signal === 'notFound') {
3512
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
3445
3513
  return;
3446
3514
  }
3447
- if (!initial) {
3448
- resetEffects();
3449
- clearRequestState();
3515
+ if (signal) {
3516
+ location.href = signal;
3517
+ return;
3450
3518
  }
3451
- await applyParams(route, pathname);
3452
- const closes = [];
3453
- let html;
3454
- try {
3455
- const render = await getRender(route); // split mode: loads the route's chunk here
3456
- html = await render(closes, '');
3457
- } catch {
3458
- // the route itself is broken: degrade to pages/500.rose (or the
3459
- // built-in plain 500) instead of leaving the container empty
3519
+ if (broken) {
3460
3520
  await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
3461
- return;
3462
3521
  }
3463
- if (!initial) container.innerHTML = html;
3464
- wire(container, closes);
3465
- bindEvents(container);
3466
- flushMounts();
3467
3522
  return;
3468
3523
  }
3469
3524
  }
3470
- // unmatched route: pages/404.rose renders (with its head + interactivity),
3471
- // else the built-in plain 404 - and an i18n app's document returns to the
3472
- // default locale, the same one the server stamps on its 404
3473
- ${hasLang ? ` document.documentElement.lang = __defLocale;
3474
- document.documentElement.removeAttribute('dir');` : ''}
3475
- await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
3525
+ // Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
3526
+ ${hasLang ? ` // the same app-root gate as above - a mount never touches the
3527
+ // host document's language or direction.
3528
+ if (container === document.getElementById('app')) {
3529
+ document.documentElement.lang = __defLocale;
3530
+ document.documentElement.removeAttribute('dir');
3531
+ }` : ''}
3532
+ await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
3476
3533
  }
3477
3534
 
3478
- // Adopt a server-rendered response in place - the JS-enabled half of
3479
- // progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
3480
- // via fetch and hands the response here. The DOM is swapped and wired with
3481
- // the same zero-render trick as boot: re-run the route's render to rebuild
3482
- // the marker closures, wire them against the adopted nodes. The page never
3483
- // re-renders visibly, no hydration payload, no second request beyond the POST.
3484
- export async function adopt(container, html, stateJson) {
3485
- resetEffects();
3486
- clearRequestState();
3535
+ // Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
3536
+ export async function adopt(container, html, stateJson, pathname) {
3537
+
3538
+
3539
+ const route0 = pathname || location.pathname;
3540
+ __navReset(container);
3487
3541
  clearMounts(); // stale mounts from a failed render never fire
3488
3542
  resumeState(stateJson);
3489
3543
  container.innerHTML = html;
3490
- // keep the embedded state in sync so a later SPA-fallback check agrees
3544
+
3491
3545
  const st = document.getElementById('__rosetack_state');
3492
3546
  if (st) st.textContent = stateJson;
3493
3547
  for (const route of routes) {
3494
- if (matchRoute(route.pattern, location.pathname)) {
3495
- await applyParams(route, location.pathname);
3496
- const closes = [];
3497
- try {
3498
- const render = await getRender(route); // split mode: loads the route's chunk here
3499
- await render(closes, '');
3500
- } catch {
3501
- // the adopted response's route is broken (e.g. the action's page
3502
- // throws): keep the swapped DOM but skip wiring it
3503
- return;
3504
- }
3505
- wire(container, closes);
3506
- bindEvents(container);
3507
- flushMounts();
3548
+ if (matchRoute(route.pattern, route0)) {
3549
+ await __withOwner(container, async () => {
3550
+ await applyParams(route, route0);
3551
+ const closes = [];
3552
+ try {
3553
+ const render = await getRender(route);
3554
+ await render(closes, '');
3555
+ } catch {
3556
+
3557
+
3558
+ return;
3559
+ }
3560
+ wire(container, closes);
3561
+ bindEvents(container);
3562
+ flushMounts();
3563
+ });
3508
3564
  return;
3509
3565
  }
3510
3566
  }
3511
3567
  }
3512
- // === refresh() implementation ===
3513
- // Re-render the current route in place: the client half of router.refresh()
3514
- // (a router refresh) / (a full invalidation). Same machinery as a client-side
3515
- // navigation to the current path - $data re-runs, state re-seeds from the
3516
- // fresh render, wire() patches the marked nodes - but a refresh never lands
3517
- // a prefetch entry: a hover from a minute ago is exactly what it exists to
3518
- // bypass. Zero requests: the render (and its $data) runs in the page.
3519
- // Trade-off: state resets like navigation (no per-key retention); add
3520
- // retention when an app needs refresh-without-losing-input.
3568
+ // === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
3521
3569
  setRefreshHook(async () => {
3522
3570
  prefetchCache.delete(location.pathname);
3523
3571
  await start(document.getElementById('app'), location.pathname, false);
@@ -3525,8 +3573,6 @@ setRefreshHook(async () => {
3525
3573
  `;
3526
3574
  await fs.promises.writeFile(path.join(buildDir, 'client-entry.js'), clientEntry);
3527
3575
  if (split) {
3528
- // Mode B: esbuild code splitting. One chunk per route module, the shared runtime in its
3529
- // own vendor chunk …
3530
3576
  await fs.promises.rm(path.join(outDir, 'chunks'), { recursive: true, force: true });
3531
3577
  await esbuild.build({
3532
3578
  entryPoints: [path.join(buildDir, 'client-entry.js')],
@@ -3554,31 +3600,51 @@ setRefreshHook(async () => {
3554
3600
  });
3555
3601
  }
3556
3602
 
3557
- // the deploy dir now holds only real artifacts
3603
+ await fs.promises.writeFile(path.join(outDir, 'mount.js'), MOUNT_ENTRY);
3604
+
3558
3605
  await fs.promises.rm(buildDir, { recursive: true, force: true });
3559
3606
 
3560
3607
  const publicDir = path.join(root, 'public');
3561
3608
  if (fs.existsSync(publicDir)) {
3562
- const outPublic = path.join(outDir, 'public');
3563
- await fs.promises.mkdir(outPublic, { recursive: true });
3564
- const assets = await fs.promises.readdir(publicDir);
3565
- await Promise.all(
3566
- assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
3567
- );
3609
+ await fs.promises.cp(publicDir, path.join(outDir, 'public'), { recursive: true });
3610
+ // Browsers ask for /favicon.ico without being told to: an app that ships one in public/
3611
+ // gets it at the root of the build too, so every server …
3612
+ const favicon = path.join(publicDir, 'favicon.ico');
3613
+ if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, 'favicon.ico'));
3568
3614
  }
3569
3615
 
3570
- // The build's zero-JS lint report - every route, its verdict, and the reason. Printed on
3571
- // every build (dev rebuilds included) so the decision is auditable instead of silent.
3572
3616
  console.log('rosetack zero-JS report:');
3573
3617
  for (const line of buildReport(infos, compiled)) console.log(' ' + line);
3618
+ const warnGroups = new Map<string, { why: string; files: Map<string, Set<string>> }>();
3574
3619
  for (const { info, i } of pages) {
3575
3620
  if (!routeShipsNoJs(infos, compiled, i)) continue;
3576
3621
  for (const ci of [i, ...layoutsOf(infos, i)]) {
3577
3622
  for (const w of compiled[ci].jsWarnings ?? []) {
3578
- console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
3623
+ let g = warnGroups.get(w);
3624
+ if (!g) {
3625
+ g = { why: w, files: new Map() };
3626
+ warnGroups.set(w, g);
3627
+ }
3628
+ const file = path.relative(root, infos[ci].filePath).replace(/\\/g, '/');
3629
+ let routes = g.files.get(file);
3630
+ if (!routes) {
3631
+ routes = new Set();
3632
+ g.files.set(file, routes);
3633
+ }
3634
+ routes.add(info.routePath);
3579
3635
  }
3580
3636
  }
3581
3637
  }
3638
+ for (const g of warnGroups.values()) {
3639
+ const allRoutes = new Set<string>();
3640
+ for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
3641
+ const parts = [...g.files.entries()]
3642
+ .sort((a, b) => b[1].size - a[1].size)
3643
+ .map(([file, routes]) => `${file} (${routes.size === 1 ? [...routes][0] : `${routes.size} routes`})`);
3644
+ const shown = parts.slice(0, 4).join(', ');
3645
+ const more = parts.length > 4 ? `, +${parts.length - 4} more files` : '';
3646
+ console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
3647
+ }
3582
3648
 
3583
3649
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
3584
3650
  }
@@ -3634,26 +3700,24 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
3634
3700
  const relative = path.relative(pagesDir, filePath).replace(/\\/g, '/');
3635
3701
  const withoutExt = relative.replace(/\.rose$/, '');
3636
3702
  const base = path.posix.basename(withoutExt);
3637
- // A component (src/components/**) is not a route at all - it is imported by one.
3638
- // Everything below still runs so a broken file reports a sane routePath in build errors …
3639
3703
  const isComponent = filePath.replace(/\\/g, '/').includes('/src/components/');
3640
3704
  const isLayout = !isComponent && base === '_layout';
3641
- const isNotFound = !isComponent && base === '404';
3705
+ const isNotFound = !isComponent && (base === '404' || base === '_notfound');
3642
3706
  const isError = !isComponent && base === '500';
3643
- // pages/api/*.rose: Web-standard handler routes (JSON in, JSON out), never
3644
- // HTML pages - they dispatch by method and never reach the client bundle.
3645
3707
  const isApi = !isComponent && (withoutExt === 'api' || withoutExt.startsWith('api/'));
3646
- // pages/_middleware.rose: the request interceptor. It runs before every render and is not
3647
- // a route: it matches nothing and never reaches the client bundle.
3648
3708
  const isMiddleware = !isComponent && withoutExt === '_middleware';
3649
3709
 
3650
- let parts = withoutExt.split('/').filter((p) => p !== '_layout');
3651
- // a trailing `index` segment names its directory (blog/index -> /blog,
3652
- // api/index -> /api); only the root index collapses to '/'
3710
+ let parts = withoutExt.split('/').filter((p) => p !== '_layout' && p !== '_notfound');
3653
3711
  if (parts.length > 1 && parts[parts.length - 1] === 'index') parts = parts.slice(0, -1);
3654
- const routeParts = parts.map((part) =>
3655
- part.startsWith('[') && part.endsWith(']') ? `:${part.slice(1, -1)}` : part
3656
- );
3712
+ const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
3713
+ const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
3714
+ const routeParts = parts.map((part) => {
3715
+ const optional = OPTIONAL_CATCH_ALL.exec(part);
3716
+ if (optional) return `**${optional[1]}`;
3717
+ const catchAll = CATCH_ALL.exec(part);
3718
+ if (catchAll) return `*${catchAll[1]}`;
3719
+ return part.startsWith('[') && part.endsWith(']') ? `:${part.slice(1, -1)}` : part;
3720
+ });
3657
3721
 
3658
3722
  let routePath: string;
3659
3723
  if (routeParts.length === 0 || (routeParts.length === 1 && routeParts[0] === 'index')) {
@@ -3666,7 +3730,13 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
3666
3730
  filePath,
3667
3731
  routePath,
3668
3732
  pattern: routePath,
3669
- paramNames: parts.filter((p) => p.startsWith('[') && p.endsWith(']')).map((p) => p.slice(1, -1)),
3733
+ paramNames: parts.flatMap((p) => {
3734
+ const optional = OPTIONAL_CATCH_ALL.exec(p);
3735
+ if (optional) return [optional[1]];
3736
+ const catchAll = CATCH_ALL.exec(p);
3737
+ if (catchAll) return [catchAll[1]];
3738
+ return p.startsWith('[') && p.endsWith(']') ? [p.slice(1, -1)] : [];
3739
+ }),
3670
3740
  isLayout,
3671
3741
  isNotFound,
3672
3742
  isError,