rosetack 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,11 @@ import * as fs from 'fs';
9
9
  import * as path from 'path';
10
10
  import { pathToFileURL, fileURLToPath } from 'url';
11
11
  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
+ import { RoseError, lineOf, lineAt } from './errors.js';
15
+ export { RoseError, lineOf, lineAt, errorInfo } from './errors.js';
16
+ export type { RoseErrorInfo } from './errors.js';
12
17
 
13
18
  const COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
14
19
  const TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
@@ -36,7 +41,7 @@ const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
36
41
  */
37
42
  function encodeSlotCall(attrs: string): string {
38
43
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
39
- if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
44
+ 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} />' });
40
45
  const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)]
41
46
  .filter((m) => m[1] !== 'name')
42
47
  .map((m) => `['${m[1]}', (${m[2].trim()})]`);
@@ -74,8 +79,21 @@ export interface CompileResult {
74
79
  revalidate?: number;
75
80
  /** the component exports `csr = false` (document ships without the client bundle) */
76
81
  csr?: boolean;
82
+ /**
83
+ * P0-2 (bug report): the component exports `buffer = true` - render it per
84
+ * request on the BUFFERED path instead of streaming. A streamed response
85
+ * commits its status and headers before the body exists, so an onResponse
86
+ * hook cannot see (let alone replace) the document and a route that fails
87
+ * mid-render still answers 200. This is the explicit opt-out: the route
88
+ * keeps the exact same features, it just refuses to trade them for TTFB.
89
+ * Implies dynamic: a baked file on disk is the one path a hook can never
90
+ * run on, so `buffer = true` routes are never prerendered.
91
+ */
92
+ buffer?: boolean;
77
93
  /** the component exports `prefetch = 'off' | 'hover' | 'viewport' | 'all'` (app-global link-prefetch strategy) */
78
94
  prefetch?: string;
95
+ /** The component exports `vitals = true` (app-global web-vitals reporting) */
96
+ vitals?: boolean;
79
97
  /** the component exports `bundle = 'inline' | 'split'` (app-global client bundle mode) */
80
98
  bundle?: string;
81
99
  /** The static analysis says this component needs the client bundle */
@@ -244,8 +262,153 @@ function callifyStateReads(script: string, names: string[]): string {
244
262
  */
245
263
  function callifyTemplateExprs(template: string, names: string[]): string {
246
264
  if (names.length === 0) return template;
247
- return template.replace(/\{([^{}]*)\}/g, (whole, expr) =>
248
- `{${callifyStateReads(expr, names)}}`);
265
+ let out = '';
266
+ let last = 0;
267
+ for (const s of templateExprSpans(template)) {
268
+ out += template.slice(last, s.start) + '{' + callifyStateReads(s.expr, names) + '}';
269
+ last = s.end + 1;
270
+ }
271
+ return out + template.slice(last);
272
+ }
273
+
274
+ /**
275
+ * The spans of a template's top-level `{ ... }` expressions, literal-aware.
276
+ *
277
+ * A flat `[^{}]+` regex cannot see that `{q() ? `a ${q()}` : 'b'}` is ONE
278
+ * expression: it matched the `{q()}` inside the template literal instead, so
279
+ * the compiler rewrote THAT and left the rest as prose - the served document
280
+ * carried `Search: $rose` where the title should have said `Search: rose`.
281
+ * A wrong page with no error anywhere is the worst failure mode a template
282
+ * compiler has, so the scan below walks the source once, skipping quoted
283
+ * strings and template literals (whose own `${ ... }` holes are balanced
284
+ * separately), and reports the expression a reader sees.
285
+ *
286
+ * Shared by every pass that must agree on where an expression ends: the
287
+ * compiler itself, the state-read rewrite, the {#each} item rename and the
288
+ * named-slot prop rewrite.
289
+ */
290
+ export function templateExprSpans(src: string): Array<{ start: number; end: number; expr: string }> {
291
+ const spans: Array<{ start: number; end: number; expr: string }> = [];
292
+ let i = 0;
293
+ while (i < src.length) {
294
+ if (src[i] === '{') {
295
+ 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
+ if (end > i + 1) {
299
+ spans.push({ start: i, end, expr: src.slice(i + 1, end) });
300
+ i = end + 1;
301
+ continue;
302
+ }
303
+ }
304
+ i++;
305
+ }
306
+ return spans;
307
+ }
308
+
309
+ /** The index of the `}` that closes the `{` at `open`, or -1 when it never does. */
310
+ function scanExprEnd(src: string, open: number): number {
311
+ let depth = 0;
312
+ let i = open;
313
+ while (i < src.length) {
314
+ const ch = src[i];
315
+ if (ch === "'" || ch === '"') {
316
+ i = skipQuoted(src, i);
317
+ continue;
318
+ }
319
+ if (ch === '`') {
320
+ i = skipTemplate(src, i);
321
+ continue;
322
+ }
323
+ if (ch === '{') depth++;
324
+ else if (ch === '}' && --depth === 0) return i;
325
+ i++;
326
+ }
327
+ return -1;
328
+ }
329
+
330
+ /** Just past the closing quote of the string literal that starts at `i`. */
331
+ function skipQuoted(src: string, i: number): number {
332
+ const q = src[i];
333
+ let j = i + 1;
334
+ while (j < src.length) {
335
+ if (src[j] === '\\') {
336
+ j += 2;
337
+ continue;
338
+ }
339
+ if (src[j] === q) return j + 1;
340
+ j++;
341
+ }
342
+ return j;
343
+ }
344
+
345
+ /** Just past the closing backtick of the template literal at `i`, `${ }` holes balanced. */
346
+ function skipTemplate(src: string, i: number): number {
347
+ let j = i + 1;
348
+ while (j < src.length) {
349
+ const ch = src[j];
350
+ if (ch === '\\') {
351
+ j += 2;
352
+ continue;
353
+ }
354
+ if (ch === '`') return j + 1;
355
+ if (ch === '$' && src[j + 1] === '{') {
356
+ const end = scanExprEnd(src, j + 1);
357
+ j = end < 0 ? src.length : end + 1;
358
+ continue;
359
+ }
360
+ j++;
361
+ }
362
+ return j;
363
+ }
364
+
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
+ */
376
+ function stripComments(src: string): string {
377
+ let out = '';
378
+ let i = 0;
379
+ 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;
391
+ continue;
392
+ }
393
+ if (src.startsWith('//', i)) {
394
+ while (i < src.length && src[i] !== '\n') i++;
395
+ continue;
396
+ }
397
+ if (src.startsWith('/*', i)) {
398
+ i += 2;
399
+ while (i < src.length && !src.startsWith('*/', i)) i++;
400
+ i = Math.min(i + 2, src.length);
401
+ continue;
402
+ }
403
+ if (src.startsWith('<!--', i)) {
404
+ i += 4;
405
+ while (i < src.length && !src.startsWith('-->', i)) i++;
406
+ i = Math.min(i + 3, src.length);
407
+ continue;
408
+ }
409
+ out += src[i++];
410
+ }
411
+ return out;
249
412
  }
250
413
 
251
414
  /**
@@ -374,25 +537,33 @@ export type RoseRegistry = Map<string, { index: number; scopeKey: string; slots:
374
537
  */
375
538
  function resolveRoseImports(script: string, fromFile: string, registry: RoseRegistry): { script: string; imports: Array<{ name: string; specifier: string; index: number }> } {
376
539
  const imports: Array<{ name: string; specifier: string; index: number }> = [];
377
- const resolve = (spec: string): { index: number; scopeKey: string } => {
540
+ const resolve = (spec: string, at: number): { index: number; scopeKey: string } => {
378
541
  const abs = path.resolve(path.dirname(fromFile), spec);
379
542
  const hit = registry.get(abs);
380
543
  if (!hit) {
381
- throw new Error(`${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`);
544
+ throw new RoseError(
545
+ 'E-IMPORT',
546
+ `${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
547
+ {
548
+ file: fromFile,
549
+ line: lineOf(script, at),
550
+ hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`,
551
+ },
552
+ );
382
553
  }
383
554
  return hit;
384
555
  };
385
556
  // A default import becomes a named one: the compiled module exports
386
557
  // `render`, and the parent's `<Card>` tag calls exactly that.
387
- let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
388
- const hit = resolve(spec);
558
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at: number) => {
559
+ const hit = resolve(spec, at);
389
560
  imports.push({ name, specifier: spec, index: hit.index });
390
561
  return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
391
562
  });
392
563
  // A named import (`import { render as Card }`) keeps its clause; only the
393
564
  // specifier becomes the placeholder.
394
- rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
395
- const hit = resolve(spec);
565
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at: number) => {
566
+ const hit = resolve(spec, at);
396
567
  const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? 'render';
397
568
  imports.push({ name: alias, specifier: spec, index: hit.index });
398
569
  return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
@@ -410,6 +581,97 @@ function rewriteRoseImports(script: string, kind: 'ssr' | 'client'): string {
410
581
  return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
411
582
  }
412
583
 
584
+ /**
585
+ * The specifiers that can never reach a browser
586
+ * bundle. Node builtins by prefix, plus the database drivers the docs tell
587
+ * you to use - the packages a rosetack app reaches for on the server and
588
+ * nowhere else.
589
+ *
590
+ * Trade-off: a specifier list, not a resolver. A package that merely LOOKS
591
+ * server-side but bundles fine for the browser still builds (nothing is
592
+ * lost); the list only has to catch what esbuild's browser platform would
593
+ * refuse anyway, which is what turns a cryptic failure into a clear one.
594
+ */
595
+ const NODE_ONLY_SPEC = /^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream|child_process|worker_threads|dns|cluster|better-sqlite3|sqlite3|pg|mysql2|mongodb|redis|ioredis)$)/;
596
+
597
+ /** The node-only specifiers among a module's hoisted imports (type imports excluded: esbuild erases them). */
598
+ function nodeOnlyImports(importStmts: string): string[] {
599
+ const out: string[] = [];
600
+ 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
602
+ if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
603
+ }
604
+ return out;
605
+ }
606
+
607
+ /**
608
+ * `on:event={fn}` -> `data-on-event="fn"`, plus the handler registry entries
609
+ * the client module needs. One pass, two outputs, so the attribute and the
610
+ * registry can never disagree.
611
+ *
612
+ * Brace-aware on purpose: a flat `on:(\w+)=\{([^}]+)\}` stopped at the FIRST
613
+ * `}`, so an inline arrow (`on:click={() => $setState('n', n() + 1)}`) was
614
+ * truncated at its own closing brace - which emitted
615
+ * `Object.assign(handlers, { () => ... })` (a syntax error in the generated
616
+ * module) and left a stray `}` in the markup. The scan below balances braces
617
+ * and skips string and template literals, exactly like templateExprSpans.
618
+ *
619
+ * A handler that names a server action becomes `data-on-event="$action:name"`
620
+ * and never reaches the client registry (the body is server-only). An inline
621
+ * handler gets a synthetic name (`__hN`) and rides the registry as
622
+ * `__hN: <expr>`: the registry statement is emitted inside render(), after
623
+ * the state declarations, so the arrow closes over the same `count()`/`setN`
624
+ * the rest of the page uses.
625
+ */
626
+ function wireEventBindings(template: string, actionNames: Set<string>): {
627
+ template: string;
628
+ bindings: Array<{ event: string; fn: string }>;
629
+ } {
630
+ const bindings: Array<{ event: string; fn: string }> = [];
631
+ let out = '';
632
+ let rest = template;
633
+ for (;;) {
634
+ const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
635
+ if (!m) {
636
+ out += rest;
637
+ break;
638
+ }
639
+ out += rest.slice(0, m.index);
640
+ let i = m.index + m[0].length;
641
+ let depth = 1;
642
+ while (i < rest.length) {
643
+ const ch = rest[i];
644
+ if (ch === '"' || ch === "'") {
645
+ i = skipQuoted(rest, i);
646
+ continue;
647
+ }
648
+ if (ch === '`') {
649
+ i = skipTemplate(rest, i);
650
+ continue;
651
+ }
652
+ if (ch === '{') depth++;
653
+ else if (ch === '}') {
654
+ depth--;
655
+ if (depth === 0) break;
656
+ }
657
+ i++;
658
+ }
659
+ const expr = rest.slice(m.index + m[0].length, i).trim();
660
+ if (actionNames.has(expr)) {
661
+ out += `data-on-${m[1]}="$action:${expr}"`;
662
+ } else if (/^\w+$/.test(expr)) {
663
+ out += `data-on-${m[1]}="${expr}"`;
664
+ bindings.push({ event: m[1], fn: expr });
665
+ } else {
666
+ const name = `__h${bindings.length}`;
667
+ out += `data-on-${m[1]}="${name}"`;
668
+ bindings.push({ event: m[1], fn: `${name}: ${expr}` });
669
+ }
670
+ rest = rest.slice(i + 1);
671
+ }
672
+ return { template: out, bindings };
673
+ }
674
+
413
675
  /**
414
676
  * Pre-scan a file's template for its slot declarations -
415
677
  * `<slot name="row" item={post}>` -> { name: 'row', props: ['item'] }.
@@ -492,7 +754,11 @@ export async function compileComponent(filePath: string, publicDir: string, scop
492
754
  try {
493
755
  source = await p.transform(source, filePath);
494
756
  } catch (err) {
495
- throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
757
+ throw new RoseError(
758
+ 'E-PLUGIN',
759
+ `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
760
+ { file: filePath, hint: 'the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)' },
761
+ );
496
762
  }
497
763
  }
498
764
 
@@ -517,18 +783,19 @@ export async function compileComponent(filePath: string, publicDir: string, scop
517
783
  guardName: null,
518
784
  style: '',
519
785
  hasParams: false,
520
- api: `import { getContext } from './runtime.js';\n${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
786
+ api: `import { getContext, $query } from './runtime.js';\n${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
521
787
  apiMethods,
522
788
  hasPrerender,
523
789
  usesContext,
524
790
  };
525
791
  }
526
792
 
527
- // strip the <style> block first: its CSS is scoped and inlined into the
528
- // shell, and it must not leak into the template (or the <head> scan)
529
- const styleMatch = source.match(STYLE_RE);
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, '');
796
+ const styleMatch = sourceNoHead.match(STYLE_RE);
530
797
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : '';
531
- const sourceNoBlocks = source.replace(STYLE_RE, '');
798
+ const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, '');
532
799
 
533
800
  const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
534
801
  // Resolve `import Card from '../components/Card.rose'` against the build registry before
@@ -539,20 +806,41 @@ export async function compileComponent(filePath: string, publicDir: string, scop
539
806
  // The imports (a component import above all) belong at module scope,
540
807
  // not inside render() - hoisted here, emitted by the generators.
541
808
  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
+ if (path.basename(filePath) !== '_middleware.rose') {
812
+ for (const spec of nodeOnlyImports(importStmts)) {
813
+ const at = importStmts.indexOf(spec);
814
+ throw new RoseError(
815
+ 'E-NODE-ONLY',
816
+ `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. ` +
817
+ `This module's script ships to the client (its $data bodies included), so move the import to ` +
818
+ `src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows ` +
819
+ `travel to the page through getContext() / $data.`,
820
+ {
821
+ file: filePath,
822
+ line: at >= 0 ? lineOf(importStmts, at) : undefined,
823
+ hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`,
824
+ },
825
+ );
826
+ }
827
+ }
542
828
  // A component (src/components/*.rose) is not a route: the build marks it in the registry
543
829
  // with a `components/...` scope key …
544
830
  const isComponent = registry.get(filePath)?.scopeKey.startsWith('components/') ?? false;
545
831
  // Boundary, stated loudly at build time: a component renders INSIDE its parent's template
546
832
  // phase, which is synchronous by design (that is what keeps wire …
547
833
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
548
- throw new Error(
834
+ throw new RoseError(
835
+ 'E-EXPORT',
549
836
  `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. ` +
550
- `Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`
837
+ `Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
838
+ { file: filePath, hint: 'move the fetch to the page (or the middleware) and pass the value down as a prop' },
551
839
  );
552
840
  }
553
841
  // getContext() in the script makes the route dynamic: the request bag is per-request, so
554
842
  // the build must not bake it and the servers must not answer it from a prerendered file.
555
- const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
843
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
556
844
  // an exported `params` marks a dynamic route for prerender enumeration
557
845
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
558
846
  // an exported `revalidate = N` opts the route into stale-while-revalidate: the baked file
@@ -564,25 +852,55 @@ export async function compileComponent(filePath: string, publicDir: string, scop
564
852
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
565
853
  const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
566
854
  if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
567
- throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
855
+ throw new RoseError(
856
+ 'E-EXPORT',
857
+ `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
858
+ { 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
+ );
860
+ }
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
+ const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
864
+ const vitals = vitalsMatch ? vitalsMatch[1].trim() === 'true' : undefined;
865
+ if (vitalsMatch && !vitals) {
866
+ throw new RoseError(
867
+ 'E-EXPORT',
868
+ `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
869
+ { 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
+ );
568
871
  }
569
872
  // The bundle mode - the fix for the large-app architecture gap. 'inline' (the default) is
570
873
  // the single-document mode: the whole client bundle rides inside the HTML, one request …
571
874
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
572
875
  const bundle = bundleMatch ? bundleMatch[1] : undefined;
573
876
  if (bundle && !['inline', 'split'].includes(bundle)) {
574
- throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
877
+ throw new RoseError(
878
+ 'E-EXPORT',
879
+ `${filePath}: export const bundle must be 'inline' or 'split'`,
880
+ { 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
+ );
575
882
  }
576
883
  // The compiler decides zero-JS, not the developer. This is the same "does anything here
577
884
  // need the client bundle" predicate that Used to REFUSE `csr = false`: event wiring in the …
578
885
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
579
886
  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.
889
+ const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
890
+ const buffer: boolean | undefined = bufferMatch ? bufferMatch[1] !== 'false' : undefined;
580
891
  if (csr === false) {
581
892
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
582
893
  if (dead) {
583
- throw new Error(
894
+ const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? undefined) ? source : rawScript;
895
+ throw new RoseError(
896
+ 'E-EXPORT',
584
897
  `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. ` +
585
- `(Forms still work without JS: a native POST runs the server action.)`
898
+ `(Forms still work without JS: a native POST runs the server action.)`,
899
+ {
900
+ file: filePath,
901
+ line: lineAt(deadSrc, dead),
902
+ hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle',
903
+ },
586
904
  );
587
905
  }
588
906
  }
@@ -595,10 +913,18 @@ export async function compileComponent(filePath: string, publicDir: string, scop
595
913
  try {
596
914
  value = new Function(`return ${headersLiteral}`)();
597
915
  } catch {
598
- throw new Error(`${filePath}: export const headers must be an object literal`);
916
+ throw new RoseError(
917
+ 'E-EXPORT',
918
+ `${filePath}: export const headers must be an object literal`,
919
+ { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" },
920
+ );
599
921
  }
600
922
  if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value as object).some((v) => typeof v !== 'string')) {
601
- throw new Error(`${filePath}: export const headers must be a flat map of string -> string`);
923
+ throw new RoseError(
924
+ 'E-EXPORT',
925
+ `${filePath}: export const headers must be a flat map of string -> string`,
926
+ { file: filePath, hint: 'every value must be a string literal (a number or an array fails here instead of shipping verbatim)' },
927
+ );
602
928
  }
603
929
  headers = value as Record<string, string>;
604
930
  }
@@ -612,11 +938,19 @@ export async function compileComponent(filePath: string, publicDir: string, scop
612
938
  try {
613
939
  value = new Function(`return ${cspLiteral}`)();
614
940
  } catch {
615
- throw new Error(`${filePath}: export const csp must be an object literal`);
941
+ throw new RoseError(
942
+ 'E-EXPORT',
943
+ `${filePath}: export const csp must be an object literal`,
944
+ { file: filePath, hint: 'write it as one literal: export const csp = { nonce: true }' },
945
+ );
616
946
  }
617
947
  const nonce = (value as { nonce?: unknown } | null)?.nonce;
618
948
  if (nonce !== undefined && typeof nonce !== 'boolean') {
619
- throw new Error(`${filePath}: csp.nonce must be a boolean`);
949
+ throw new RoseError(
950
+ 'E-EXPORT',
951
+ `${filePath}: csp.nonce must be a boolean`,
952
+ { file: filePath, hint: 'csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)' },
953
+ );
620
954
  }
621
955
  cspNonce = nonce === true;
622
956
  }
@@ -630,41 +964,54 @@ export async function compileComponent(filePath: string, publicDir: string, scop
630
964
  // Does anything in this component need the client bundle?
631
965
  const clientReasons: string[] = [];
632
966
  if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)'); // event wiring in the template
633
- if (/<form[\s>]/.test(source)) clientReasons.push('a <form> (its in-place adopt is the enhancement)'); // a POST form
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.
975
+ if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
976
+ clientReasons.push('a form bound to a client dispatch ($action)');
977
+ }
634
978
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
635
979
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`); // lifecycle / client-only APIs
636
- if (actionNames.size > 0) { // a server action (form target or $action)
637
- clientReasons.push(`server action${actionNames.size > 1 ? 's' : ''} (${[...actionNames].join(', ')})`);
638
- }
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.
639
984
  const needsClient = clientReasons.length > 0;
640
985
 
641
986
  // The predicate is SYNTACTIC, so a component that ships no runtime is scanned for the
642
987
  // shapes that would silently need one …
643
988
  const jsWarnings: string[] = [];
644
989
  if (!needsClient) {
645
- if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
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
+ const codeOnly = stripComments(source);
993
+ const scriptCodeOnly = stripComments(rawScript);
994
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
646
995
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
647
996
  }
648
- if (/javascript:/i.test(source)) {
997
+ if (/javascript:/i.test(codeOnly)) {
649
998
  jsWarnings.push('a javascript: URL - it needs the bundle to run; link to a real route');
650
999
  }
651
- if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
1000
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
652
1001
  jsWarnings.push('eval()/new Function() - client code the predicate cannot see');
653
1002
  }
654
1003
  // Browser-only globals. The script block is embedded inside render() on BOTH sides …
655
- 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(rawScript)) {
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)) {
656
1005
  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');
657
1006
  }
658
1007
  }
659
1008
 
660
1009
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
661
- // strip the <head> block so it never leaks into the page template
662
- const headMatch = sourceNoBlocks.match(HEAD_RE);
663
- const headContent = headMatch?.[1] ?? '';
664
- const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, '');
1010
+ // the <head> block was already stripped above (before the scoped-style match) …
1011
+ const headContent = source.match(HEAD_RE)?.[1] ?? '';
665
1012
  const rawTemplate = templateMatch
666
1013
  ? templateMatch[1]
667
- : sourceNoHead.replace(COMPONENT_RE, '').trim();
1014
+ : sourceNoBlocks.replace(COMPONENT_RE, '').trim();
668
1015
  // a component with styles carries its scope attribute on every top-level
669
1016
  // element, so its rules match only its own subtree
670
1017
  const template = scopedStyle
@@ -679,56 +1026,70 @@ export async function compileComponent(filePath: string, publicDir: string, scop
679
1026
  const setterNames = new Map<string, string>();
680
1027
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
681
1028
 
682
- // Extract event bindings from original template. Handlers bound to a server action never
683
- // reach the client registry: they compile to data-on-*="$action:name" and dispatch …
684
- const eventBindings: Array<{ event: string; fn: string }> = [];
685
- let em: RegExpExecArray | null;
686
- EVENT_RE.lastIndex = 0;
687
- while ((em = EVENT_RE.exec(template))) {
688
- if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
689
- }
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
+ 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
+ const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
1036
+ if (d.kind === 'state') {
1037
+ return `const [${d.name}, ${setterNames.get(d.name)!}] = state(${JSON.stringify(key)}, ${d.expr});`;
1038
+ }
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
+ const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
1042
+ const fn = isFn ? d.expr : `() => (${d.expr})`;
1043
+ return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1044
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1045
+ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1046
+ };
1047
+
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
+ const nestedDecls: (typeof decls)[number][] = [];
1052
+ let spliced = '';
1053
+ let pos = 0;
1054
+ decls.forEach((d, i) => {
1055
+ // A top-level declaration is replaced by its placeholder (its generated code comes back
1056
+ // after the rewrites) …
1057
+ const top = braceDepthAt(script, d.start) === 0;
1058
+ if (!top) nestedDecls.push(d);
1059
+ spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : '');
1060
+ pos = d.end;
1061
+ });
1062
+ spliced += script.slice(pos);
690
1063
 
691
- // Remove declarations from script, rewrite $setState to setters
692
- let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end] as [number, number]));
693
- cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
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
+ let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
694
1067
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, '');
695
1068
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
696
1069
  return `${setter}(${val})`;
697
1070
  });
698
-
699
- // Replace bare state reads with getter calls (after decl removal). A plain regex would
700
- // also rewrite state names inside string literals …
701
1071
  cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1072
+ // ...and put each top-level declaration back, exactly where it was written.
1073
+ cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
1074
+
1075
+ // Only the nested declarations still ride the hoisted block (after the
1076
+ // script, before the deltas - the position they have always had).
1077
+ const stateDeclsCode = nestedDecls.filter((d) => d.kind === 'state').map(declCode).join('\n');
1078
+ const dataDeclsCode = nestedDecls.filter((d) => d.kind === 'data').map(declCode).join('\n');
702
1079
 
703
1080
  // The template gets the same treatment: the script auto-calls a bare state read, so
704
1081
  // `{liked}` must not silently render the getter's source text.
705
1082
  const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
706
-
707
- // on:event={fn} -> data-on-event="fn"; a handler that names a server action becomes
708
- // data-on-event="$action:fn" (dispatched by $action) …
709
- const ssrTemplate = templateCalled
1083
+ // Extract event bindings from the CALLED template (the same string the markup rewrite
1084
+ // below reads, so the two can never disagree).
1085
+ const wired = wireEventBindings(templateCalled, actionNames);
1086
+ const eventBindings = wired.bindings;
1087
+
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
710
1091
  .replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
711
- .replace(SLOT_RE, '{__slot__}')
712
- .replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) =>
713
- actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
714
-
715
- const stateDeclsCode = decls
716
- .map((d) => {
717
- // A component's state keys are namespaced by its file, so two components that both declare
718
- // `let open = $state(false)` no longer share one signal …
719
- const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
720
- if (d.kind === 'state') {
721
- return `const [${d.name}, ${setterNames.get(d.name)!}] = state(${JSON.stringify(key)}, ${d.expr});`;
722
- }
723
- // $data: fetch only when this key has no value yet (server: always after
724
- // clearRequestState; client: only on first visit or client-side nav)
725
- const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
726
- const fn = isFn ? d.expr : `() => (${d.expr})`;
727
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
728
- const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
729
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
730
- })
731
- .join('\n');
1092
+ .replace(SLOT_RE, '{__slot__}');
732
1093
 
733
1094
  const stateKeys = decls.map((d) => d.name);
734
1095
 
@@ -740,9 +1101,9 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
740
1101
  return [r.name, { index: hit.index, slots: hit.slots }] as const;
741
1102
  }));
742
1103
  const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0, true, comps);
743
- // head block: no markers (esc() inline) - the whole block re-renders per
744
- // call, so one reactive closure drives document title/meta on navigation.
745
- const compiledHead = headContent.trim() ? compileTemplate(headContent, '__hd', '__hc', null, 0, false) : '';
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
+ const compiledHead = headContent.trim() ? compileHead(headContent) : '';
746
1107
  // A named slot in the template needs the __slot() helper in the module.
747
1108
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
748
1109
 
@@ -755,8 +1116,8 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
755
1116
  const isMiddleware = path.basename(filePath) === '_middleware.rose';
756
1117
  const ssr = isMiddleware
757
1118
  ? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
758
- : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
759
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
1119
+ : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1120
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
760
1121
 
761
1122
  // One rewrite for both bundles and every branch above: the `__rose_N__` placeholder
762
1123
  // resolves to this bundle's own module path …
@@ -771,7 +1132,9 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
771
1132
  usesContext,
772
1133
  revalidate,
773
1134
  csr,
1135
+ buffer,
774
1136
  prefetch,
1137
+ vitals,
775
1138
  bundle,
776
1139
  needsClient,
777
1140
  clientReasons,
@@ -1065,16 +1428,54 @@ function extractDecls(script: string): Decl[] {
1065
1428
  return decls;
1066
1429
  }
1067
1430
 
1068
- function removeRanges(text: string, ranges: Array<[number, number]>): string {
1069
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
1070
- let out = '';
1071
- let pos = 0;
1072
- for (const [start, end] of sorted) {
1073
- out += text.slice(pos, start);
1074
- pos = end;
1431
+ /**
1432
+ * Brace depth at `index`, with strings, template literals and comments
1433
+ * skipped so their braces never count. A declaration at depth 0 is a
1434
+ * top-level statement of the script: it may be replaced where it stands
1435
+ * (BUG.md 2026.9.22 - the TDZ fix). Anything deeper lives inside a function
1436
+ * body (an onMount callback) and must keep its scope.
1437
+ */
1438
+ function braceDepthAt(src: string, index: number): number {
1439
+ let depth = 0;
1440
+ let i = 0;
1441
+ while (i < index) {
1442
+ const ch = src[i];
1443
+ if (ch === "'" || ch === '"' || ch === '`') {
1444
+ const quote = ch;
1445
+ i++;
1446
+ while (i < index) {
1447
+ if (src[i] === '\\') { i += 2; continue; }
1448
+ if (src[i] === quote) { i++; break; }
1449
+ // a ${...} inside a template literal is code again
1450
+ if (quote === '`' && src[i] === '$' && src[i + 1] === '{') {
1451
+ let d = 1;
1452
+ i += 2;
1453
+ while (i < index && d > 0) {
1454
+ if (src[i] === '{') d++;
1455
+ else if (src[i] === '}') d--;
1456
+ i++;
1457
+ }
1458
+ continue;
1459
+ }
1460
+ i++;
1461
+ }
1462
+ continue;
1463
+ }
1464
+ if (ch === '/' && src[i + 1] === '/') {
1465
+ const nl = src.indexOf('\n', i);
1466
+ i = nl === -1 ? src.length : nl;
1467
+ continue;
1468
+ }
1469
+ if (ch === '/' && src[i + 1] === '*') {
1470
+ const close = src.indexOf('*/', i + 2);
1471
+ i = close === -1 ? src.length : close + 2;
1472
+ continue;
1473
+ }
1474
+ if (ch === '{') depth++;
1475
+ else if (ch === '}') depth--;
1476
+ i++;
1075
1477
  }
1076
- out += text.slice(pos);
1077
- return out;
1478
+ return depth;
1078
1479
  }
1079
1480
 
1080
1481
  /**
@@ -1111,6 +1512,111 @@ function autoCall(expr: string): string {
1111
1512
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1112
1513
  }
1113
1514
 
1515
+ /**
1516
+ * Find a `{#if ...}...{/if}`, `{#each ... as x}...{/each}` or
1517
+ * `{#boundary}...{/boundary}` block, NESTING-AWARE: the close tag that
1518
+ * ends the block is the one that BALANCES the opens inside it.
1519
+ *
1520
+ * A non-greedy regex cannot tell the two apart - it stops at the first
1521
+ * close tag, which is the INNER block's. The outer block then ends early,
1522
+ * its own close tag is left in the stream as prose, and the inner open
1523
+ * (now unclosed inside the truncated content) falls through to the
1524
+ * expression matcher and compiles to `(#if ...)` - the cryptic
1525
+ * "Unexpected #if" esbuild error. The scan below counts same-kind opens
1526
+ * as it walks, so an `{#if}` inside an `{#if}` (or an `{#each}` inside
1527
+ * an `{#each}`) is content, not a terminator.
1528
+ *
1529
+ * Returns a RegExpExecArray-shaped value (index + capture groups in the
1530
+ * same order the old regexes produced) so the call sites are unchanged.
1531
+ */
1532
+ function findBlock(src: string, kind: 'if' | 'each' | 'boundary'): RegExpExecArray | null {
1533
+ const head = kind === 'boundary'
1534
+ ? /\{#boundary\}/g
1535
+ : kind === 'if'
1536
+ ? /\{#if\s+([^}]+)\}/g
1537
+ : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
1538
+ const closeRe = new RegExp(`\\{/${kind}\\}`, 'g');
1539
+ let open: RegExpExecArray | null;
1540
+ while ((open = head.exec(src))) {
1541
+ const start = open.index;
1542
+ const afterOpen = start + open[0].length;
1543
+ let depth = 1;
1544
+ let i = afterOpen;
1545
+ for (;;) {
1546
+ head.lastIndex = i;
1547
+ closeRe.lastIndex = i;
1548
+ const nextOpen = head.exec(src);
1549
+ const nextClose = closeRe.exec(src);
1550
+ if (!nextClose) break; // this open never closes: not a block, look past it
1551
+ if (nextOpen && nextOpen.index < nextClose.index) {
1552
+ depth++;
1553
+ i = nextOpen.index + nextOpen[0].length;
1554
+ continue;
1555
+ }
1556
+ i = nextClose.index + nextClose[0].length;
1557
+ if (--depth === 0) {
1558
+ const content = src.slice(afterOpen, nextClose.index);
1559
+ const groups = kind === 'boundary' ? [content] : kind === 'if' ? [open[1], content] : [open[1], open[2], content];
1560
+ const arr = [src.slice(start, i), ...groups] as unknown as RegExpExecArray;
1561
+ (arr as any).index = start;
1562
+ return arr;
1563
+ }
1564
+ }
1565
+ head.lastIndex = afterOpen;
1566
+ }
1567
+ return null;
1568
+ }
1569
+
1570
+ /**
1571
+ * Compile a <head> block. Same template rules as the body - `{expr}` escapes,
1572
+ * `{#if}`/`{#each}`/`{@html}` all work - with two exceptions:
1573
+ *
1574
+ * - the interior of a `<style>`, `<script>` or `<noscript>` element is RAW
1575
+ * TEXT, not template source. CSS braces are not rosetack expressions
1576
+ * (`<style>.a { color: red }</style>` read as one giant `{...}` expression
1577
+ * and broke the build the first time a route shipped a head-level style),
1578
+ * and a `<script>`'s own syntax has the same problem.
1579
+ * - an HTML comment is a NOTE, not content: it is dropped. A note that
1580
+ * mentions `<style>` ("ship a <style> here") must not be able to move where
1581
+ * the stylesheet starts, and the server's head merge reads this output.
1582
+ *
1583
+ * Each markup segment compiles with its own depth so the block helper names
1584
+ * (`__b0_0`) can never collide inside the one head function they share.
1585
+ */
1586
+ function compileHead(head: string): string {
1587
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
1588
+ let out = '';
1589
+ let buf = '';
1590
+ let seg = 0;
1591
+ let i = 0;
1592
+ const flush = () => {
1593
+ if (buf.trim()) out += compileTemplate(buf, '__hd', '__hc', null, seg++, false);
1594
+ buf = '';
1595
+ };
1596
+ while (i < head.length) {
1597
+ if (head.startsWith('<!--', i)) {
1598
+ const end = head.indexOf('-->', i + 4);
1599
+ i = end < 0 ? head.length : end + 3;
1600
+ continue;
1601
+ }
1602
+ RAW_OPEN.lastIndex = i;
1603
+ const open = RAW_OPEN.exec(head);
1604
+ if (open) {
1605
+ const tag = open[1].toLowerCase();
1606
+ const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
1607
+ const gt = closeAt < 0 ? -1 : head.indexOf('>', closeAt);
1608
+ const end = gt < 0 ? head.length : gt + 1;
1609
+ flush();
1610
+ out += emitChunk(head.slice(i, end), '__hd', '__hc', null);
1611
+ i = end;
1612
+ continue;
1613
+ }
1614
+ buf += head[i++];
1615
+ }
1616
+ flush();
1617
+ return out;
1618
+ }
1619
+
1114
1620
  function compileTemplate(
1115
1621
  template: string,
1116
1622
  acc: string,
@@ -1127,10 +1633,18 @@ function compileTemplate(
1127
1633
  const nextId = () => `${depth}_${blockId++}`;
1128
1634
 
1129
1635
  while (remaining.length > 0) {
1130
- const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/) as RegExpExecArray | null;
1131
- const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/) as RegExpExecArray | null;
1132
- const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/) as RegExpExecArray | null;
1133
- const exprMatch = remaining.match(/\{([^{}]+)\}/) as RegExpExecArray | null;
1636
+ // nesting-aware: an inner block's close tag must not end its parent
1637
+ const ifMatch = findBlock(remaining, 'if');
1638
+ const eachMatch = findBlock(remaining, 'each');
1639
+ 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
+ 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
+ const exprMatch = firstExpr
1646
+ ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) as unknown as RegExpExecArray
1647
+ : null;
1134
1648
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
1135
1649
 
1136
1650
  const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
@@ -1176,8 +1690,13 @@ function compileTemplate(
1176
1690
  const id = nextId();
1177
1691
  // Rename the item variable to the block's scope parameter - INSIDE EXPRESSIONS ONLY.
1178
1692
  const itemRe = new RegExp(`\\b${item}\\b`, 'g');
1179
- const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) =>
1180
- `{${expr.replace(itemRe, '__s')}}`);
1693
+ let scoped = '';
1694
+ let lastSpan = 0;
1695
+ for (const s of templateExprSpans(content.trim())) {
1696
+ scoped += content.trim().slice(lastSpan, s.start) + '{' + s.expr.replace(itemRe, '__s') + '}';
1697
+ lastSpan = s.end + 1;
1698
+ }
1699
+ scoped += content.trim().slice(lastSpan);
1181
1700
  const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, markers, comps);
1182
1701
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
1183
1702
  if (markers) {
@@ -1214,7 +1733,7 @@ function compileTemplate(
1214
1733
  rest = remaining.substring(tag.end);
1215
1734
  } else {
1216
1735
  const closeIdx = findClose(remaining, tag.end, tag.name);
1217
- if (closeIdx < 0) throw new Error(`unclosed <${tag.name}> - every component tag needs its matching close tag`);
1736
+ if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${tag.name}> - every component tag needs its matching close tag`, { hint: `add the matching </${tag.name}> (or close the tag with /> when it takes no children)` });
1218
1737
  childrenSrc = remaining.substring(tag.end, closeIdx);
1219
1738
  rest = remaining.substring(closeIdx + tag.name.length + 3);
1220
1739
  }
@@ -1231,8 +1750,14 @@ function compileTemplate(
1231
1750
  const decl = entry.slots.find((s) => s.name === nm);
1232
1751
  let content = src;
1233
1752
  for (const p of decl?.props ?? []) {
1234
- content = content.replace(/\{([^{}]*)\}/g, (whole, expr) =>
1235
- `{${expr.replace(new RegExp(`\\b${p}\\b`, 'g'), `__s.${p}`)}}`);
1753
+ const pRe = new RegExp(`\\b${p}\\b`, 'g');
1754
+ let out = '';
1755
+ let lastSpan = 0;
1756
+ for (const s of templateExprSpans(content)) {
1757
+ out += content.slice(lastSpan, s.start) + '{' + s.expr.replace(pRe, `__s.${p}`) + '}';
1758
+ lastSpan = s.end + 1;
1759
+ }
1760
+ content = out + content.slice(lastSpan);
1236
1761
  }
1237
1762
  return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1, markers, comps)} return h; }`;
1238
1763
  });
@@ -1272,6 +1797,22 @@ function compileTemplate(
1272
1797
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1273
1798
  continue;
1274
1799
  }
1800
+ // P1-2 (bug report): {@html expr} is the explicit reverse of esc() - trusted HTML,
1801
+ // emitted verbatim.
1802
+ const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
1803
+ if (rawMatch) {
1804
+ if (before) result += emitChunk(before, acc, closes, scope);
1805
+ const expr = rawMatch[1].trim();
1806
+ if (!markers) {
1807
+ // head block: the value is markup, so it is concatenated raw
1808
+ result += `${acc} += String(${expr} ?? '');\n`;
1809
+ } else {
1810
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1811
+ result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ''});\n`;
1812
+ }
1813
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1814
+ continue;
1815
+ }
1275
1816
  // attr={expr} -> reactive attribute; otherwise a text marker
1276
1817
  const attrMatch = before.match(/([\w-]+)=\s*$/);
1277
1818
  if (attrMatch) {
@@ -1418,7 +1959,7 @@ function rejectNestedSlot(src: string, outer: string): void {
1418
1959
  if (end < 0) return;
1419
1960
  const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
1420
1961
  if (hit && nm[1] !== '/') {
1421
- throw new Error(`slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`);
1962
+ throw new RoseError('E-TEMPLATE', `slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`, { hint: 'move the inner <slot> out of the outer one - a slot is a direct child of the component tag, never nested in another slot' });
1422
1963
  }
1423
1964
  i = end;
1424
1965
  }
@@ -1480,7 +2021,7 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
1480
2021
  if (!selfClosing && !isVoid) elemDepth++;
1481
2022
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
1482
2023
  if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
1483
- throw new Error(`slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`);
2024
+ throw new RoseError('E-TEMPLATE', `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
1484
2025
  }
1485
2026
  if (slotName) {
1486
2027
  const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '');
@@ -1488,7 +2029,7 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
1488
2029
  named.set(slotName, (named.get(slotName) ?? '') + stripped);
1489
2030
  } else {
1490
2031
  const closeIdx = findClose(src, end, nm[2]);
1491
- if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
2032
+ if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
1492
2033
  const tail = `</${nm[2]}>`;
1493
2034
  const inner = src.slice(end, closeIdx);
1494
2035
  // The same rule one level down: a slot= INSIDE a named slot's
@@ -1589,7 +2130,7 @@ function compileSlot(acc: string): string {
1589
2130
 
1590
2131
  // The runtime's public surface, as one import line. Three generators emit it (page SSR,
1591
2132
  // page client, the middleware module) …
1592
- const RUNTIME_IMPORTS = `import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark } from './runtime.js';`;
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';`;
1593
2134
 
1594
2135
  /**
1595
2136
  * `export let title = 'x'` -> a per-invocation const read from the
@@ -1624,7 +2165,7 @@ const __slotBlock = (closes, sl, name, pairs) => {
1624
2165
  return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1625
2166
  };`;
1626
2167
 
1627
- function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = '', props: Array<{ name: string; def: string | null }> = [], namedSlots = false, imports = '', isComponent = false, guard = ''): string {
2168
+ 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 {
1628
2169
  // The head block renders to a clean html string (no markers) and is wrapped in an h
1629
2170
  // marker pair: renderPage extracts it for <head> injection …
1630
2171
  const headCode = headFn
@@ -1632,6 +2173,10 @@ function generateSSR(script: string, templateFn: string, stateDeclsCode: string,
1632
2173
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1633
2174
  __html += headMark(closes, __head);`
1634
2175
  : '';
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
+ const actionState = hasActions ? `
2179
+ const $setState = (key, value) => setState(key, value);` : '';
1635
2180
  // A page's render is async ($data awaits); a component's is not - its parent calls it
1636
2181
  // inside a string concatenation (`h += Card(...)`) …
1637
2182
  return `
@@ -1641,6 +2186,7 @@ ${imports}
1641
2186
 
1642
2187
  ${exports}
1643
2188
  ${guard}
2189
+ ${actionState}
1644
2190
 
1645
2191
  ${namedSlots ? SLOT_HELPER : ''}
1646
2192
 
@@ -1648,12 +2194,13 @@ export ${isComponent ? 'function' : 'async function'} render(closes, children, _
1648
2194
  ${props.length > 0 ? 'const __p = __props || {};' : ''}
1649
2195
  ${namedSlots ? 'const __sl = __slots || {};' : ''}
1650
2196
  ${propsCode(props)}
2197
+ ${script}
1651
2198
  ${stateDeclsCode}
2199
+ ${dataDeclsCode}
1652
2200
  // The incremental patches of the action that produced THIS response,
1653
2201
  // applied to the state the declarations above just established (a no-op on
1654
2202
  // every path that is not a server action's re-render - see the runtime).
1655
2203
  ${isComponent ? '' : 'applyStateDeltas();'}
1656
- ${script}
1657
2204
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1658
2205
  let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
1659
2206
  return __html;
@@ -1671,7 +2218,8 @@ function generateClient(
1671
2218
  props: Array<{ name: string; def: string | null }> = [],
1672
2219
  namedSlots = false,
1673
2220
  imports = '',
1674
- isComponent = false
2221
+ isComponent = false,
2222
+ dataDeclsCode = ''
1675
2223
  ): string {
1676
2224
  // Handlers live on a shared global (the runtime's `handlers` registry) so one delegated
1677
2225
  // listener per event type can dispatch for any component, including freshly cloned nodes.
@@ -1697,8 +2245,9 @@ export ${isComponent ? 'function' : 'async function'} render(closes, children, _
1697
2245
  ${props.length > 0 ? 'const __p = __props || {};' : ''}
1698
2246
  ${namedSlots ? 'const __sl = __slots || {};' : ''}
1699
2247
  ${propsCode(props)}
1700
- ${stateDeclsCode}
1701
2248
  ${script}
2249
+ ${stateDeclsCode}
2250
+ ${dataDeclsCode}
1702
2251
  ${handlerRegistry}
1703
2252
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1704
2253
  let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
@@ -1768,7 +2317,11 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1768
2317
  // A build that silently produces nothing is the worst possible failure mode (an empty
1769
2318
  // dist/ deploys as a blank site).
1770
2319
  if (pageFiles.length === 0) {
1771
- throw new Error(`no .rose pages found under ${path.join(root, 'src', 'pages')} - run rosetack from a project root, or pass one: rosetack build <dir>`);
2320
+ throw new RoseError(
2321
+ 'E-ROUTE',
2322
+ `no .rose pages found under ${path.join(root, 'src', 'pages')} - run rosetack from a project root, or pass one: rosetack build <dir>`,
2323
+ { file: path.join(root, 'src', 'pages'), hint: 'create src/pages/index.rose in that directory (or run the command from the project root)' },
2324
+ );
1772
2325
  }
1773
2326
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1774
2327
  // rosetack.config.js: the plugins and the i18n options , loaded fresh per build so the dev
@@ -1909,7 +2462,7 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1909
2462
  const runtimeEntry = ['../runtime/index.ts', '../src/runtime/index.ts']
1910
2463
  .map((rel) => fileURLToPath(new URL(rel, import.meta.url)))
1911
2464
  .find((p) => fs.existsSync(p));
1912
- if (!runtimeEntry) throw new Error('rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler');
2465
+ if (!runtimeEntry) throw new RoseError('E-INTERNAL', 'rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler', { hint: 'the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout' });
1913
2466
  await esbuild.build({
1914
2467
  entryPoints: [runtimeEntry],
1915
2468
  bundle: true,
@@ -2015,31 +2568,38 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2015
2568
  // csr: false rides on the route so renderPage/renderPageStream can drop the state
2016
2569
  // script + bundle from the document (; the decision is the compiler's since #29).
2017
2570
  if (compiled[i].csr === false && compiled[i].needsClient) {
2018
- throw new Error(
2571
+ throw new RoseError(
2572
+ 'E-EXPORT',
2019
2573
  `${info.filePath}: csr = false but this route needs the client bundle ` +
2020
- `(${(compiled[i].clientReasons ?? ['needs the client']).join(' + ')}).`
2574
+ `(${(compiled[i].clientReasons ?? ['needs the client']).join(' + ')}).`,
2575
+ { file: info.filePath, hint: 'remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above' },
2021
2576
  );
2022
2577
  }
2023
2578
  if (compiled[i].csr === false) {
2024
2579
  const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
2025
2580
  if (needy !== undefined) {
2026
- throw new Error(
2581
+ throw new RoseError(
2582
+ 'E-EXPORT',
2027
2583
  `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle ` +
2028
- `(event wiring, onMount/onCleanup, refresh() or a server action).`
2584
+ `(event wiring, onMount/onCleanup, refresh() or a server action).`,
2585
+ { file: info.filePath, hint: 'a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only' },
2029
2586
  );
2030
2587
  }
2031
2588
  }
2032
2589
  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 …
2592
+ const bufferFlag = compiled[i].buffer ? ', buffer: true' : '';
2033
2593
  // Guard - runs before every action of this route (null when the
2034
2594
  // page exports no beforeAction)
2035
2595
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : '';
2036
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag} }`;
2596
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag}${bufferFlag} }`;
2037
2597
  })
2038
2598
  .join(',\n ');
2039
2599
 
2040
2600
  const serverEntry = `
2041
2601
  ${serverImports}
2042
- import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
2602
+ import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
2043
2603
  ${runtimePlugins.length > 0
2044
2604
  ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
2045
2605
  : `// no plugin declares a runtime hook, so there is no plugins
@@ -2087,6 +2647,16 @@ export async function runResponseHooks(ctx, res) {
2087
2647
  export const hasRequestHooks = __hasRequestHooks;
2088
2648
  export const hasResponseHooks = __hasResponseHooks;
2089
2649
 
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.
2656
+ export function setQuery(query) {
2657
+ setRequestQuery(query || {});
2658
+ }
2659
+
2090
2660
  // i18n: the dictionaries baked at build time from
2091
2661
  // src/locales/*.json. A route segment named [lang] is the locale: the value
2092
2662
  // must name one of these dictionaries, and $t resolves keys against it.
@@ -2121,13 +2691,15 @@ export const routeParams = {
2121
2691
  };
2122
2692
 
2123
2693
  // Routes whose component reads the request context (getContext()), mutates a
2124
- // shared store ($store), or opted into nonce-based CSP: the bag is
2125
- // per-request, the store is per-process, and a nonce is per-response, so
2126
- // these are dynamic - the build never bakes them and the servers never
2127
- // answer them from a prerendered file. Public routes keep the static fast
2128
- // path (file cache, ETag/304, streaming) untouched.
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.
2129
2701
  export const dynamicRoutes = [
2130
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2702
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2131
2703
  ];
2132
2704
 
2133
2705
  // Which api routes opt into build-time baking (export const prerender = true):
@@ -2181,6 +2753,16 @@ export function isNoJs(pathname) {
2181
2753
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
2182
2754
  }
2183
2755
 
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.
2762
+ export function isBuffered(pathname) {
2763
+ return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
2764
+ }
2765
+
2184
2766
  // Per-route response headers: a route exporting a headers
2185
2767
  // map carries them into every response the servers write for it, merged
2186
2768
  // OVER the framework defaults (the strict CSP) - so an app can tighten or
@@ -2550,6 +3132,12 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2550
3132
  // P1: the app-global prefetch strategy, declared once (the root layout) as `export const
2551
3133
  // prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
2552
3134
  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
+ 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`
3140
+ : '';
2553
3141
 
2554
3142
  // The <html lang dir> tracker only exists when the app actually has a [lang] route - an
2555
3143
  // app without i18n pays nothing for it …
@@ -2572,7 +3160,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2572
3160
 
2573
3161
  const clientEntry = `
2574
3162
  ${clientImports}
2575
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
3163
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
2576
3164
 
2577
3165
  // i18n: the dictionaries baked at build time - the client
2578
3166
  // renders any PRELOADED locale from the bundle, so switching language costs
@@ -2587,11 +3175,13 @@ setLocalePacks(${JSON.stringify(packed)});
2587
3175
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
2588
3176
  // follow a route that carries no [lang] segment (a non-i18n page)
2589
3177
  const __defLocale = '${defaultLocale}';` : ''}
3178
+ ${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';`: ''}
2590
3179
  // The two pack doors, re-exported for an app that wants to warm a language
2591
3180
  // before its visitor asks for it (ensureLocale) or to feed a dictionary it
2592
3181
  // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
2593
3182
  // is what applyParams calls - so the re-export costs the statement alone.
2594
3183
  export { ensureLocale, loadLocale } from './runtime.js';
3184
+ ${vitalsBlock}
2595
3185
 
2596
3186
  const routes = [
2597
3187
  ${clientRoutes}
@@ -2712,8 +3302,15 @@ export function prefetch(pathname, source = 'hover') {
2712
3302
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
2713
3303
  if (!route) return;
2714
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.
3309
+ const qi = pathname.indexOf('?');
3310
+ const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
2715
3311
  const p = prefetchQueue.then(async () => {
2716
3312
  try {
3313
+ setPrefetchOverride(qOverride);
2717
3314
  // the isolated render also captures the onMount callbacks the route
2718
3315
  // queued and the onCleanup disposers it registered: the paint that
2719
3316
  // consumes this entry replays the mounts after wiring and adopts the
@@ -2740,6 +3337,7 @@ export function prefetch(pathname, source = 'hover') {
2740
3337
  prefetchCache.delete(pathname); // failed: the next hover retries
2741
3338
  return null;
2742
3339
  } finally {
3340
+ setPrefetchOverride(null);
2743
3341
  prefetchPending--;
2744
3342
  }
2745
3343
  });
@@ -2804,6 +3402,13 @@ export async function $action(name, e) {
2804
3402
 
2805
3403
  export { postForm };
2806
3404
 
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.
3410
+ export { serializeState };
3411
+
2807
3412
  // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2808
3413
  // the existing nodes and bind events. initial=false: client-side navigation -
2809
3414
  // re-render the route chain from scratch and wire the fresh DOM.