rosetack 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/deploy/k8s/rosetack.yaml +107 -0
  2. package/dist-cli/compiler.mjs +2783 -0
  3. package/dist-cli/edge.mjs +332 -0
  4. package/dist-cli/rosetack.mjs +4230 -0
  5. package/dist-cli/runtime.mjs +703 -0
  6. package/dist-cli/test.mjs +3202 -0
  7. package/pack.mjs +49 -0
  8. package/package.json +25 -7
  9. package/src/FRAMEWORK_VERSION +1 -1
  10. package/src/cli/edge.ts +67 -25
  11. package/src/cli/index.ts +858 -94
  12. package/src/cli/prompt.ts +127 -0
  13. package/src/cli/shell.ts +133 -30
  14. package/src/cli/test.ts +400 -0
  15. package/src/compiler/errors.ts +74 -0
  16. package/src/compiler/index.ts +1955 -264
  17. package/src/runtime/index.ts +465 -66
  18. package/src/types/rosetack.d.ts +151 -0
  19. package/.github/workflows/ci.yml +0 -72
  20. package/.github/workflows/release.yml +0 -122
  21. package/benchmark.ts +0 -227
  22. package/example/public/favicon.ico +0 -0
  23. package/example/public/logo.svg +0 -148
  24. package/example/public/rose-mark-black.png +0 -0
  25. package/example/public/rose-mark.png +0 -0
  26. package/example/public/rose-mono.png +0 -0
  27. package/example/rosetack.config.js +0 -10
  28. package/example/src/locales/en.json +0 -8
  29. package/example/src/locales/zh.json +0 -8
  30. package/example/src/pages/404.rose +0 -15
  31. package/example/src/pages/500.rose +0 -10
  32. package/example/src/pages/[lang]/about.rose +0 -40
  33. package/example/src/pages/_layout.rose +0 -33
  34. package/example/src/pages/_middleware.rose +0 -37
  35. package/example/src/pages/about.rose +0 -67
  36. package/example/src/pages/admin.rose +0 -27
  37. package/example/src/pages/api/hello.rose +0 -19
  38. package/example/src/pages/api/login.rose +0 -55
  39. package/example/src/pages/api/posts.rose +0 -80
  40. package/example/src/pages/api/secret.rose +0 -14
  41. package/example/src/pages/blog/[id].rose +0 -25
  42. package/example/src/pages/broken.rose +0 -16
  43. package/example/src/pages/fresh.rose +0 -22
  44. package/example/src/pages/garden.rose +0 -27
  45. package/example/src/pages/index.rose +0 -84
  46. package/example/src/pages/sign.rose +0 -45
  47. package/example/src/pages/thorn.rose +0 -23
  48. package/example/src/pages/vault.rose +0 -14
  49. package/go.mod +0 -3
  50. package/main.go +0 -470
  51. package/tools/release-notes.mjs +0 -113
  52. package/tsconfig.json +0 -17
@@ -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>/;
@@ -18,21 +23,46 @@ const HEAD_RE = /<head>([\s\S]*?)<\/head>/;
18
23
  // <style> block: component CSS, scoped by a build-time attribute on the component's
19
24
  // top-level elements and inlined into the document …
20
25
  const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
21
- const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\s*\(/g;
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
+ const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
29
+ const DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
22
30
  const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
23
31
  const EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
24
32
  const SLOT_RE = /<slot\s*\/?>/g;
33
+ /** A named slot: `<slot name="row" item={post} />` . The lookahead
34
+ * keeps the plain `<slot />` out of it - that one is the default slot. */
35
+ const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
36
+
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
+ */
42
+ function encodeSlotCall(attrs: string): string {
43
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
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} />' });
45
+ const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)]
46
+ .filter((m) => m[1] !== 'name')
47
+ .map((m) => `['${m[1]}', (${m[2].trim()})]`);
48
+ return `${JSON.stringify(name)}, [${pairs.join(', ')}]`;
49
+ }
25
50
  // {#boundary}...{/boundary}: an error boundary - its content renders into its own string; a
26
- // throw anywhere inside swaps in this fallback instead of failing the whole page.
51
+ // throw anywhere inside swaps in a fallback instead of failing the whole page.
27
52
  const BOUNDARY_FALLBACK = '<p>This section failed to render.</p>';
28
53
  // API route handlers are exported functions named by HTTP method (pages/api/*.rose).
29
54
  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
+ const TS_LOADER = { loader: { '.js': 'ts' as const } };
30
58
 
31
59
  export interface CompileResult {
32
60
  ssr: string;
33
61
  client: string;
34
62
  stateKeys: string[];
35
63
  actionNames: string[];
64
+ /** The page exports `beforeAction` (the action guard), or null */
65
+ guardName: string | null;
36
66
  /** scoped CSS from the component's <style> block ('' when it has none) */
37
67
  style: string;
38
68
  /** the component exports `params` (dynamic-route prerender enumeration) */
@@ -49,16 +79,29 @@ export interface CompileResult {
49
79
  revalidate?: number;
50
80
  /** the component exports `csr = false` (document ships without the client bundle) */
51
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;
52
93
  /** the component exports `prefetch = 'off' | 'hover' | 'viewport' | 'all'` (app-global link-prefetch strategy) */
53
94
  prefetch?: string;
54
- /** the component exports `bundle = 'inline' | 'split'` (app-global client bundle mode, P0 §1) */
95
+ /** The component exports `vitals = true` (app-global web-vitals reporting) */
96
+ vitals?: boolean;
97
+ /** the component exports `bundle = 'inline' | 'split'` (app-global client bundle mode) */
55
98
  bundle?: string;
56
- /** innovation #29: the static analysis says this component needs the client bundle */
99
+ /** The static analysis says this component needs the client bundle */
57
100
  needsClient?: boolean;
58
- /** innovation #31: WHY it needs the client - the rules that fired, for the build report */
101
+ /** WHY it needs the client - the rules that fired, for the build report */
59
102
  clientReasons?: string[];
60
103
  /**
61
- * innovation #31: shapes that MIGHT need JavaScript but the syntactic
104
+ * Shapes that MIGHT need JavaScript but the syntactic
62
105
  * predicate cannot prove, on a component that otherwise ships none (an
63
106
  * inline on* attribute, a javascript: URL, eval/new Function). Warnings,
64
107
  * never errors: the document still ships, but the build says it out loud.
@@ -66,6 +109,27 @@ export interface CompileResult {
66
109
  jsWarnings?: string[];
67
110
  /** the component exports `headers = { ... }` (per-route response headers) */
68
111
  headers?: Record<string, string>;
112
+ /**
113
+ * The component exports `csp = { nonce: true }` - its documents get a
114
+ * per-request nonce policy instead of the hashed one. Never prerendered: a
115
+ * baked file cannot carry a fresh nonce.
116
+ */
117
+ cspNonce?: boolean;
118
+ /**
119
+ * The component's props - `export let title = 'x'` in its script.
120
+ * A prop is a plain value the caller passes per invocation (never a
121
+ * signal: the parent re-renders the child when a prop changes), so it is
122
+ * read straight from the props object with its default as the fallback.
123
+ */
124
+ props?: Array<{ name: string; def: string | null }>;
125
+ /**
126
+ * `.rose` imports this component makes, resolved to module indices.
127
+ * The specifiers are rewritten per bundle (ssr/client) by the generators,
128
+ * so one source resolves against both module sets.
129
+ */
130
+ roseImports?: Array<{ name: string; specifier: string; index: number }>;
131
+ /** This file lives in src/components/ (a reusable component, not a route) */
132
+ isComponent?: boolean;
69
133
  }
70
134
 
71
135
  export interface RouteInfo {
@@ -82,6 +146,8 @@ export interface RouteInfo {
82
146
  isApi: boolean;
83
147
  /** pages/_middleware.rose: the request interceptor, not a route */
84
148
  isMiddleware: boolean;
149
+ /** src/components/*.rose: a reusable component, never a route */
150
+ isComponent?: boolean;
85
151
  }
86
152
 
87
153
  interface Decl {
@@ -186,38 +252,513 @@ function callifyStateReads(script: string, names: string[]): string {
186
252
  return scan(script);
187
253
  }
188
254
 
189
- /** A plugin transforms a component's raw source before compilation sees it. */
255
+ /**
256
+ * The template-side twin of callifyStateReads: every `{...}` expression gets
257
+ * the same bare-read rewrite, and nothing else does. A whole-template scan
258
+ * would also rewrite the word in prose - `<p>likes {likes()}</p>` would print
259
+ * "likes()" - so the pass walks expressions only. Block syntax ({#if …},
260
+ * {#each …}) rides along: callifying `rows` in `{#each rows as row}` is
261
+ * exactly what the each branch already expects (`rows()`).
262
+ */
263
+ function callifyTemplateExprs(template: string, names: string[]): string {
264
+ if (names.length === 0) return template;
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;
412
+ }
413
+
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
+ */
419
+ export function scriptOf(source: string): string | null {
420
+ return source.match(COMPONENT_RE)?.[1] ?? null;
421
+ }
422
+
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
+ */
430
+ export interface RequestHookContext {
431
+ request: Request;
432
+ url: URL;
433
+ method: string;
434
+ pathname: string;
435
+ state: Record<string, unknown>;
436
+ }
437
+
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
+ */
190
450
  export interface Plugin {
191
451
  name: string;
192
- transform(code: string, filePath: string): string | Promise<string>;
452
+ transform?(code: string, filePath: string): string | Promise<string>;
453
+ /** Before routing and middleware. Return a Response to short-circuit (auth wall, rate limit, maintenance page). */
454
+ onRequest?(ctx: RequestHookContext): Response | void | Promise<Response | void>;
455
+ /** After the response exists, before it is sent. Return a Response to replace it. */
456
+ 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>;
459
+ /** Worker drain, before exit: close the pool. */
460
+ onShutdown?(): void | Promise<void>;
461
+ }
462
+
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
+ */
477
+ export interface I18nConfig {
478
+ preload?: string[];
479
+ }
480
+
481
+ export interface rosetackConfig {
482
+ plugins: Plugin[];
483
+ i18n: I18nConfig;
193
484
  }
194
485
 
195
486
  /**
196
487
  * Plugins live in `<root>/rosetack.config.js` as the default export: an array
197
- * of `{ name, transform }`, run over each component's raw source (template +
198
- * script + style, before any parsing). ponytail: ONE hook - it covers macros,
199
- * custom syntax, includes and auto-imports; add bundler/build hooks when a
200
- * real plugin needs one. The import is cache-busted per build so a config
201
- * edit takes effect on the dev server's next rebuild, and a missing file is
202
- * simply "no plugins" (existence is checked first, so a config with a syntax
203
- * error still fails loudly).
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.
204
499
  */
205
- export async function loadPlugins(root: string): Promise<Plugin[]> {
500
+ export async function loadConfig(root: string): Promise<rosetackConfig> {
206
501
  const file = path.join(root, 'rosetack.config.js');
207
- if (!fs.existsSync(file)) return [];
502
+ if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
208
503
  const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
209
- return (mod.default as Plugin[] | undefined) ?? [];
504
+ return {
505
+ plugins: (mod.default as Plugin[] | undefined) ?? [],
506
+ i18n: (mod.i18n as I18nConfig | undefined) ?? {},
507
+ };
508
+ }
509
+
510
+ /** The plugins alone (the serve command's lifecycle hooks). */
511
+ export async function loadPlugins(root: string): Promise<Plugin[]> {
512
+ return (await loadConfig(root)).plugins;
513
+ }
514
+
515
+ /**
516
+ * The module registry the build hands every compileComponent call.
517
+ * Maps a resolved .rose file to its module index and scope key, so an
518
+ * `import Card from '../components/Card.rose'` can be rewritten to the
519
+ * compiled module in BOTH bundles (the specifier differs per bundle, the
520
+ * index does not). One map, built once per build from the full file list -
521
+ * a component may import a component, so the graph is resolved before any
522
+ * compilation starts.
523
+ *
524
+ * `slots` is the child's slot declaration (`<slot name="row" item={post}>`),
525
+ * pre-scanned from its template: the parent needs the names the child passes
526
+ * INTO a slot to resolve them in the slot content it writes, and compilation
527
+ * order cannot guarantee the child is compiled first.
528
+ */
529
+ export type RoseRegistry = Map<string, { index: number; scopeKey: string; slots: Array<{ name: string; props: string[] }> }>;
530
+
531
+ /**
532
+ * Resolve every `.rose` import in a script against the registry. Returns the
533
+ * rewritten script plus the (local name, specifier, index) triples, so the
534
+ * generators can emit the right module path per bundle. An unresolvable
535
+ * specifier fails the build naming the file and the import - a typo'd
536
+ * component path must not silently ship a broken bundle.
537
+ */
538
+ function resolveRoseImports(script: string, fromFile: string, registry: RoseRegistry): { script: string; imports: Array<{ name: string; specifier: string; index: number }> } {
539
+ const imports: Array<{ name: string; specifier: string; index: number }> = [];
540
+ const resolve = (spec: string, at: number): { index: number; scopeKey: string } => {
541
+ const abs = path.resolve(path.dirname(fromFile), spec);
542
+ const hit = registry.get(abs);
543
+ if (!hit) {
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
+ );
553
+ }
554
+ return hit;
555
+ };
556
+ // A default import becomes a named one: the compiled module exports
557
+ // `render`, and the parent's `<Card>` tag calls exactly that.
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);
560
+ imports.push({ name, specifier: spec, index: hit.index });
561
+ return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
562
+ });
563
+ // A named import (`import { render as Card }`) keeps its clause; only the
564
+ // specifier becomes the placeholder.
565
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at: number) => {
566
+ const hit = resolve(spec, at);
567
+ const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? 'render';
568
+ imports.push({ name: alias, specifier: spec, index: hit.index });
569
+ return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
570
+ });
571
+ return { script: rewritten, imports };
210
572
  }
211
573
 
212
- export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = []): Promise<CompileResult> {
574
+ /**
575
+ * Rewrite the `__rose_N__` placeholders to this bundle's module paths. Both
576
+ * bundles are generated from the same resolved script, so one placeholder
577
+ * resolves to two different files - the only per-bundle difference in the
578
+ * whole component pipeline.
579
+ */
580
+ function rewriteRoseImports(script: string, kind: 'ssr' | 'client'): string {
581
+ return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
582
+ }
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
+
675
+ /**
676
+ * Pre-scan a file's template for its slot declarations -
677
+ * `<slot name="row" item={post}>` -> { name: 'row', props: ['item'] }.
678
+ * Cheap regex on purpose: the parent's compiler needs the names the child
679
+ * passes INTO a slot, before (and independently of) compiling the child.
680
+ */
681
+ function scanSlotDecls(filePath: string): Array<{ name: string; props: string[] }> {
682
+ let src: string;
683
+ try {
684
+ src = fs.readFileSync(filePath, 'utf-8');
685
+ } catch {
686
+ return [];
687
+ }
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();
692
+ const out: Array<{ name: string; props: string[] }> = [];
693
+ for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
694
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
695
+ if (!name) continue;
696
+ const props = [...m[1].matchAll(/\b(\w+)\s*=\s*\{/g)].map((x) => x[1]).filter((n) => n !== 'name');
697
+ out.push({ name: name[1], props });
698
+ }
699
+ return out;
700
+ }
701
+
702
+ /**
703
+ * Lift `import` statements out of a script block to module scope. The
704
+ * script body is embedded inside render(), where an import declaration is a
705
+ * syntax error - and a component import is exactly what a page/component
706
+ * script now carries. Line-based on purpose: multi-line imports are tracked
707
+ * by brace/paren depth and end at their `from '...'` clause.
708
+ */
709
+ function hoistImports(script: string): { imports: string; rest: string } {
710
+ const imports: string[] = [];
711
+ const rest: string[] = [];
712
+ let buf: string[] | null = null;
713
+ let depth = 0;
714
+ const done = (line: string) => depth <= 0 && /from\s*['"][^'"]+['"]\s*;?\s*$/.test(line);
715
+ for (const line of script.split('\n')) {
716
+ if (buf) {
717
+ buf.push(line);
718
+ for (const ch of line) {
719
+ if (ch === '{' || ch === '(') depth++;
720
+ else if (ch === '}' || ch === ')') depth--;
721
+ }
722
+ if (done(line)) {
723
+ imports.push(buf.join('\n'));
724
+ buf = null;
725
+ }
726
+ continue;
727
+ }
728
+ if (/^\s*import\b/.test(line)) {
729
+ buf = [line];
730
+ depth = 0;
731
+ for (const ch of line) {
732
+ if (ch === '{' || ch === '(') depth++;
733
+ else if (ch === '}' || ch === ')') depth--;
734
+ }
735
+ if (done(line)) {
736
+ imports.push(line);
737
+ buf = null;
738
+ }
739
+ continue;
740
+ }
741
+ rest.push(line);
742
+ }
743
+ if (buf) imports.push(buf.join('\n')); // unterminated import: keep it whole
744
+ return { imports: imports.join('\n'), rest: rest.join('\n') };
745
+ }
746
+
747
+ export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = [], registry: RoseRegistry = new Map()): Promise<CompileResult> {
213
748
  let source = await fs.promises.readFile(filePath, 'utf-8');
214
- // Plugins (innovation #30) see the raw source first: whatever they return is what the
215
- // compiler parses.
749
+ // Plugins see the raw source first: whatever they return is what the compiler parses.
216
750
  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
+ if (!p.transform) continue;
217
754
  try {
218
755
  source = await p.transform(source, filePath);
219
756
  } catch (err) {
220
- 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
+ );
221
762
  }
222
763
  }
223
764
 
@@ -233,67 +774,138 @@ export async function compileComponent(filePath: string, publicDir: string, scop
233
774
  // per-request, a baked body would freeze one request's answer
234
775
  const usesContext = /getContext\s*\(/.test(rawScript);
235
776
  const hasPrerender = !usesContext && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript);
777
+ const hoisted = hoistImports(resolveRoseImports(rawScript, filePath, registry).script);
236
778
  return {
237
779
  ssr: '',
238
780
  client: '',
239
781
  stateKeys: [],
240
782
  actionNames: [],
783
+ guardName: null,
241
784
  style: '',
242
785
  hasParams: false,
243
- api: `import { getContext } from './runtime.js';\n${rawScript.trim()}`,
786
+ api: `import { getContext, $query } from './runtime.js';\n${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
244
787
  apiMethods,
245
788
  hasPrerender,
246
789
  usesContext,
247
790
  };
248
791
  }
249
792
 
250
- // strip the <style> block first: its CSS is scoped and inlined into the
251
- // shell, and it must not leak into the template (or the <head> scan)
252
- 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);
253
797
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : '';
254
- const sourceNoBlocks = source.replace(STYLE_RE, '');
798
+ const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, '');
255
799
 
256
800
  const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
257
- const rawScript = scriptMatch?.[1] ?? '';
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) …
803
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? '', filePath, registry);
804
+ const rawScript = roseResolved.script;
805
+ 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
+ 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
+ }
828
+ // A component (src/components/*.rose) is not a route: the build marks it in the registry
829
+ // with a `components/...` scope key …
830
+ 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
+ if (isComponent && /\$data\s*\(/.test(rawScript)) {
834
+ throw new RoseError(
835
+ 'E-EXPORT',
836
+ `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. ` +
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' },
839
+ );
840
+ }
258
841
  // getContext() in the script makes the route dynamic: the request bag is per-request, so
259
842
  // the build must not bake it and the servers must not answer it from a prerendered file.
260
- 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);
261
844
  // an exported `params` marks a dynamic route for prerender enumeration
262
845
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
263
846
  // an exported `revalidate = N` opts the route into stale-while-revalidate: the baked file
264
847
  // is served for up to N seconds …
265
848
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
266
849
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
267
- // P1 (consultant report): an exported `prefetch = '...'` sets the app-global
268
- // link-prefetch strategy - 'off', 'hover' …
850
+ // P1: an exported `prefetch = '...'` sets the app-global link-prefetch strategy - 'off',
851
+ // 'hover' …
269
852
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
270
853
  const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
271
854
  if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
272
- 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
+ );
273
871
  }
274
- // P0 §1 (consultant report): the bundle mode - the fix for the large-app architecture
275
- // gap.
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 …
276
874
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
277
875
  const bundle = bundleMatch ? bundleMatch[1] : undefined;
278
876
  if (bundle && !['inline', 'split'].includes(bundle)) {
279
- 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
+ );
280
882
  }
281
- // Innovation #29: the compiler decides zero-JS, not the developer. This is the same "does
282
- // anything here need the client bundle" predicate that innovation #25 used to REFUSE …
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 …
283
885
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
284
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;
285
891
  if (csr === false) {
286
892
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
287
893
  if (dead) {
288
- throw new Error(
894
+ const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? undefined) ? source : rawScript;
895
+ throw new RoseError(
896
+ 'E-EXPORT',
289
897
  `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. ` +
290
- `(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
+ },
291
904
  );
292
905
  }
293
906
  }
294
907
 
295
- // An exported `headers = { ... }` sets this route's response headers (innovation #26) -
296
- // the servers merge them OVER the framework defaults (the strict CSP) …
908
+ // An exported `headers = { ... }` sets this route's response headers
297
909
  let headers: Record<string, string> | undefined;
298
910
  const headersLiteral = extractObjectLiteral(rawScript, 'headers');
299
911
  if (headersLiteral) {
@@ -301,58 +913,105 @@ export async function compileComponent(filePath: string, publicDir: string, scop
301
913
  try {
302
914
  value = new Function(`return ${headersLiteral}`)();
303
915
  } catch {
304
- 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
+ );
305
921
  }
306
922
  if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value as object).some((v) => typeof v !== 'string')) {
307
- 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
+ );
308
928
  }
309
929
  headers = value as Record<string, string>;
310
930
  }
311
931
 
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
+ let cspNonce: boolean | undefined;
935
+ const cspLiteral = extractObjectLiteral(rawScript, 'csp');
936
+ if (cspLiteral) {
937
+ let value: unknown;
938
+ try {
939
+ value = new Function(`return ${cspLiteral}`)();
940
+ } catch {
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
+ );
946
+ }
947
+ const nonce = (value as { nonce?: unknown } | null)?.nonce;
948
+ if (nonce !== undefined && typeof nonce !== '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
+ );
954
+ }
955
+ cspNonce = nonce === true;
956
+ }
957
+
312
958
  // Top-level `export` statements (e.g. `export const params = {...}` for dynamic-route
313
959
  // prerendering) are hoisted to module scope: the script body itself is embedded inside …
314
- const { clean: scriptNoExports, exports: exportStmts, actions } = extractExports(rawScript);
960
+ const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
315
961
  const script = scriptNoExports;
316
962
  const actionNames = new Set(actions.map((a) => a.name));
317
963
 
318
- // Innovation #29: does anything in this component need the client bundle?
964
+ // Does anything in this component need the client bundle?
319
965
  const clientReasons: string[] = [];
320
966
  if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)'); // event wiring in the template
321
- 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
+ }
322
978
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
323
979
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`); // lifecycle / client-only APIs
324
- if (actionNames.size > 0) { // a server action (form target or $action)
325
- clientReasons.push(`server action${actionNames.size > 1 ? 's' : ''} (${[...actionNames].join(', ')})`);
326
- }
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.
327
984
  const needsClient = clientReasons.length > 0;
328
985
 
329
- // Innovation #31: the predicate is SYNTACTIC, so a component that ships no runtime is
330
- // scanned for the shapes that would silently need one …
986
+ // The predicate is SYNTACTIC, so a component that ships no runtime is scanned for the
987
+ // shapes that would silently need one …
331
988
  const jsWarnings: string[] = [];
332
989
  if (!needsClient) {
333
- 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)) {
334
995
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
335
996
  }
336
- if (/javascript:/i.test(source)) {
997
+ if (/javascript:/i.test(codeOnly)) {
337
998
  jsWarnings.push('a javascript: URL - it needs the bundle to run; link to a real route');
338
999
  }
339
- if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
1000
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
340
1001
  jsWarnings.push('eval()/new Function() - client code the predicate cannot see');
341
1002
  }
342
1003
  // Browser-only globals. The script block is embedded inside render() on BOTH sides …
343
- 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)) {
344
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');
345
1006
  }
346
1007
  }
347
1008
 
348
1009
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
349
- // strip the <head> block so it never leaks into the page template
350
- const headMatch = sourceNoBlocks.match(HEAD_RE);
351
- const headContent = headMatch?.[1] ?? '';
352
- 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] ?? '';
353
1012
  const rawTemplate = templateMatch
354
1013
  ? templateMatch[1]
355
- : sourceNoHead.replace(COMPONENT_RE, '').trim();
1014
+ : sourceNoBlocks.replace(COMPONENT_RE, '').trim();
356
1015
  // a component with styles carries its scope attribute on every top-level
357
1016
  // element, so its rules match only its own subtree
358
1017
  const template = scopedStyle
@@ -367,69 +1026,146 @@ export async function compileComponent(filePath: string, publicDir: string, scop
367
1026
  const setterNames = new Map<string, string>();
368
1027
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
369
1028
 
370
- // Extract event bindings from original template. Handlers bound to a server action never
371
- // reach the client registry: they compile to data-on-*="$action:name" and dispatch …
372
- const eventBindings: Array<{ event: string; fn: string }> = [];
373
- let em: RegExpExecArray | null;
374
- EVENT_RE.lastIndex = 0;
375
- while ((em = EVENT_RE.exec(template))) {
376
- if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
377
- }
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);
378
1063
 
379
- // Remove declarations from script, rewrite $setState to setters
380
- let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end] as [number, number]));
381
- 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) => {
382
1067
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, '');
383
1068
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
384
1069
  return `${setter}(${val})`;
385
1070
  });
386
-
387
- // on:event={fn} -> data-on-event="fn"; a handler that names a server action becomes
388
- // data-on-event="$action:fn" (dispatched by $action); <slot /> -> block marker
389
- const ssrTemplate = template
390
- .replace(SLOT_RE, '{__slot__}')
391
- .replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) =>
392
- actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
393
-
394
- // Replace bare state reads with getter calls (after decl removal). A plain regex would
395
- // also rewrite state names inside string literals …
396
1071
  cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
397
-
398
- const stateDeclsCode = decls
399
- .map((d) => {
400
- if (d.kind === 'state') {
401
- return `const [${d.name}, ${setterNames.get(d.name)!}] = state("${d.name}", ${d.expr});`;
402
- }
403
- // $data: fetch only when this key has no value yet (server: always after
404
- // clearRequestState; client: only on first visit or client-side nav)
405
- const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
406
- const fn = isFn ? d.expr : `() => (${d.expr})`;
407
- return `const __had_${d.name} = hasState("${d.name}");
408
- const [${d.name}, set${capitalize(d.name)}] = state("${d.name}", null);
409
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
410
- })
411
- .join('\n');
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');
1079
+
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
+ 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
+ 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
1091
+ .replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
1092
+ .replace(SLOT_RE, '{__slot__}');
412
1093
 
413
1094
  const stateKeys = decls.map((d) => d.name);
414
1095
 
415
- const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0);
416
- // head block: no markers (esc() inline) - the whole block re-renders per
417
- // call, so one reactive closure drives document title/meta on navigation.
418
- const compiledHead = headContent.trim() ? compileTemplate(headContent, '__hd', '__hc', null, 0, false) : '';
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
+ const comps = new Map(roseImports.map((r) => {
1099
+ const abs = path.resolve(path.dirname(filePath), r.specifier);
1100
+ const hit = registry.get(abs)!;
1101
+ return [r.name, { index: hit.index, slots: hit.slots }] as const;
1102
+ }));
1103
+ 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
+ const compiledHead = headContent.trim() ? compileHead(headContent) : '';
1107
+ // A named slot in the template needs the __slot() helper in the module.
1108
+ const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
419
1109
 
420
1110
  // Actions ship in the SSR module only; the client bundle gets every other
421
1111
  // export (params, sync helpers) but never an action body.
422
1112
  const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
423
- const ssr = generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead);
424
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead);
1113
+ // The guard is emitted at the SSR module's scope, beside the actions it fronts …
1114
+ const ssrGuard = guard ? `\n${guard}` : '';
1115
+ // pages/_middleware.rose is a hook module, not a route: no template, no state, no head.
1116
+ const isMiddleware = path.basename(filePath) === '_middleware.rose';
1117
+ const ssr = isMiddleware
1118
+ ? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
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);
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
+ return {
1125
+ ssr: rewriteRoseImports(ssr, 'ssr'),
1126
+ client: rewriteRoseImports(client, 'client'),
1127
+ stateKeys,
1128
+ actionNames: [...actionNames],
1129
+ guardName: guard ? 'beforeAction' : null,
1130
+ style: scopedStyle,
1131
+ hasParams,
1132
+ usesContext,
1133
+ revalidate,
1134
+ csr,
1135
+ buffer,
1136
+ prefetch,
1137
+ vitals,
1138
+ bundle,
1139
+ needsClient,
1140
+ clientReasons,
1141
+ jsWarnings,
1142
+ headers,
1143
+ cspNonce,
1144
+ props,
1145
+ roseImports,
1146
+ isComponent,
1147
+ };
1148
+ }
425
1149
 
426
- return { ssr, client, stateKeys, actionNames: [...actionNames], style: scopedStyle, hasParams, usesContext, revalidate, csr, prefetch, bundle, needsClient, clientReasons, jsWarnings, headers };
1150
+ /**
1151
+ * Collapse a declaration block's whitespace outside strings. Every byte of
1152
+ * component CSS ships inside every document, so the source's formatting is a
1153
+ * tax paid on every route; collapsing it is free - declarations are not
1154
+ * whitespace-sensitive, and quoted strings (content: "a b") are left
1155
+ * untouched by the alternation.
1156
+ */
1157
+ function minifyDecls(block: string): string {
1158
+ return block
1159
+ .replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g, (m) =>
1160
+ m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, ' ').replace(/\s*([:;{},])\s*/g, '$1').trim()
1161
+ )
1162
+ .trim();
427
1163
  }
428
1164
 
429
1165
  /**
430
1166
  * Scope a component's CSS to its own subtree: every selector is prefixed
431
1167
  * with the component's scope attribute, recursing into @media/@supports.
432
- * ponytail: no full CSS parser - comma lists only, and @keyframes blocks
1168
+ * Trade-off: no full CSS parser - comma lists only, and @keyframes blocks
433
1169
  * pass through unscoped (their from/to/to selectors are not selectors).
434
1170
  * Global element rules (:root/html/body) belong in the shell's STYLES.
435
1171
  */
@@ -454,10 +1190,10 @@ function scopeCss(css: string, key: string): string {
454
1190
  if (sel.startsWith('@')) {
455
1191
  // at-rule: keep the prelude, scope the inner rules (keyframes pass
456
1192
  // through: their 0%/from/to "selectors" are not selectors)
457
- out += `${sel} { ${/^@(?:-[\w]+-)?keyframes/.test(sel) ? block : scopeCss(block, key)} }`;
1193
+ out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
458
1194
  } else if (sel) {
459
- const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(', ');
460
- out += `${scoped} { ${block} }`;
1195
+ const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(',');
1196
+ out += `${scoped}{${minifyDecls(block)}}`;
461
1197
  }
462
1198
  prelude = '';
463
1199
  i = j;
@@ -518,7 +1254,7 @@ function injectScopeAttr(template: string, key: string): string {
518
1254
 
519
1255
  const VOID_TAGS = new Set(['img', 'br', 'hr', 'input', 'meta', 'link', 'source', 'wbr']);
520
1256
 
521
- // ponytail: tolerate leading indentation - .rose script blocks are indented
1257
+ // Trade-off: tolerate leading indentation - .rose script blocks are indented
522
1258
  const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
523
1259
 
524
1260
  /**
@@ -526,7 +1262,7 @@ const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(
526
1262
  * body. They must be self-contained (no references to state or template
527
1263
  * scope) - they exist for build-time consumers like dynamic-route `params`.
528
1264
  *
529
- * Every exported ASYNC function is a SERVER-ONLY action (Next.js semantics:
1265
+ * Every exported ASYNC function is a SERVER-ONLY action (server-action semantics:
530
1266
  * `export const params` and sync helpers stay shared, async exports are
531
1267
  * server code). `action` is the conventional name a <form method="POST">
532
1268
  * posts to; any other name is reachable from an event handler
@@ -559,9 +1295,17 @@ function extractObjectLiteral(script: string, name: string): string | null {
559
1295
  return script.slice(start, i);
560
1296
  }
561
1297
 
562
- function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }> } {
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
+ export function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }>; props: Array<{ name: string; def: string | null }>; guard: string } {
563
1301
  const stmts: string[] = [];
564
1302
  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
+ 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
+ const guards: string[] = [];
565
1309
  let out = '';
566
1310
  let pos = 0;
567
1311
  let m: RegExpExecArray | null;
@@ -616,15 +1360,24 @@ function extractExports(script: string): { clean: string; exports: string; actio
616
1360
  out += script.slice(pos, start);
617
1361
  const stmt = script.slice(start, i).trim();
618
1362
  const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
619
- if (asyncFn) {
1363
+ const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
1364
+ if (anyFn?.[1] === 'beforeAction') {
1365
+ guards.push(stmt); // the guard: server-only, never an action target
1366
+ } else if (asyncFn) {
620
1367
  actions.push({ name: asyncFn[1], stmt }); // server-only: kept out of the client bundle
1368
+ } 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
+ const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
1372
+ 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
621
1374
  } else {
622
1375
  stmts.push(stmt);
623
1376
  }
624
1377
  pos = i;
625
1378
  }
626
1379
  out += script.slice(pos);
627
- return { clean: out, exports: stmts.join('\n'), actions };
1380
+ return { clean: out, exports: stmts.join('\n'), actions, props, guard: guards.join('\n') };
628
1381
  }
629
1382
 
630
1383
  function extractDecls(script: string): Decl[] {
@@ -632,7 +1385,26 @@ function extractDecls(script: string): Decl[] {
632
1385
  DECL_RE.lastIndex = 0;
633
1386
  let m: RegExpExecArray | null;
634
1387
  while ((m = DECL_RE.exec(script))) {
635
- const open = m.index + m[0].length;
1388
+ // The regex matched up to `$state`/`$data`; what follows is an optional type-argument
1389
+ // list and then the call.
1390
+ let j = m.index + m[0].length;
1391
+ const skipSpace = () => { while (j < script.length && /\s/.test(script[j])) j++; };
1392
+ skipSpace();
1393
+ if (script[j] === '<') {
1394
+ let depth = 0;
1395
+ while (j < script.length) {
1396
+ const ch = script[j];
1397
+ if (ch === '<') depth++;
1398
+ else if (ch === '>' && script[j - 1] !== '=') {
1399
+ depth--;
1400
+ if (depth === 0) { j++; break; }
1401
+ } else if (ch === '=' && script[j + 1] === '>') j++; // `=>`: both chars are one token
1402
+ j++;
1403
+ }
1404
+ skipSpace();
1405
+ }
1406
+ if (script[j] !== '(') continue; // `$state` used as a value, not a call
1407
+ const open = j + 1;
636
1408
  let depth = 1;
637
1409
  let i = open;
638
1410
  while (i < script.length && depth > 0) {
@@ -642,6 +1414,8 @@ function extractDecls(script: string): Decl[] {
642
1414
  i++;
643
1415
  }
644
1416
  let end = i;
1417
+ const cast = DECL_CAST_RE.exec(script.slice(i));
1418
+ if (cast) end = i + cast[0].length;
645
1419
  if (script[end] === ';') end++;
646
1420
  decls.push({
647
1421
  name: m[1],
@@ -654,16 +1428,54 @@ function extractDecls(script: string): Decl[] {
654
1428
  return decls;
655
1429
  }
656
1430
 
657
- function removeRanges(text: string, ranges: Array<[number, number]>): string {
658
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
659
- let out = '';
660
- let pos = 0;
661
- for (const [start, end] of sorted) {
662
- out += text.slice(pos, start);
663
- 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++;
664
1477
  }
665
- out += text.slice(pos);
666
- return out;
1478
+ return depth;
667
1479
  }
668
1480
 
669
1481
  /**
@@ -679,14 +1491,140 @@ function removeRanges(text: string, ranges: Array<[number, number]>): string {
679
1491
  *
680
1492
  * Text/attr values are HTML-escaped on the server; wire() writes raw values
681
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
+ */
1501
+
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
+ function autoCall(expr: string): string {
1511
+ const e = expr.trim();
1512
+ return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1513
+ }
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.
682
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
+
683
1620
  function compileTemplate(
684
1621
  template: string,
685
1622
  acc: string,
686
1623
  closes: string,
687
1624
  scope: string | null,
688
1625
  depth: number,
689
- markers = true
1626
+ markers = true,
1627
+ comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map()
690
1628
  ): string {
691
1629
  let result = '';
692
1630
  let remaining = template;
@@ -695,16 +1633,26 @@ function compileTemplate(
695
1633
  const nextId = () => `${depth}_${blockId++}`;
696
1634
 
697
1635
  while (remaining.length > 0) {
698
- const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/) as RegExpExecArray | null;
699
- const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/) as RegExpExecArray | null;
700
- const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/) as RegExpExecArray | null;
701
- 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;
1648
+ const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
702
1649
 
703
- const candidates: Array<{ type: string; match: RegExpExecArray; index: number }> = [];
1650
+ const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
704
1651
  if (ifMatch?.index !== undefined) candidates.push({ type: 'if', match: ifMatch, index: ifMatch.index });
705
1652
  if (eachMatch?.index !== undefined) candidates.push({ type: 'each', match: eachMatch, index: eachMatch.index });
706
1653
  if (boundaryMatch?.index !== undefined) candidates.push({ type: 'boundary', match: boundaryMatch, index: boundaryMatch.index });
707
1654
  if (exprMatch?.index !== undefined) candidates.push({ type: 'expr', match: exprMatch, index: exprMatch.index });
1655
+ if (compTag) candidates.push({ type: 'comp', match: exprMatch!, index: compTag.start, tag: compTag });
708
1656
  const earliest = candidates.length > 0
709
1657
  ? candidates.reduce((a, b) => (a.index <= b.index ? a : b))
710
1658
  : null;
@@ -718,21 +1666,18 @@ function compileTemplate(
718
1666
  const [, cond, content] = earliest.match;
719
1667
  const before = remaining.substring(0, earliest.index);
720
1668
  if (before) result += emitChunk(before, acc, closes, scope);
721
- const call = cond.trim().endsWith('()') ? cond.trim() : `${cond.trim()}()`;
1669
+ const call = autoCall(cond);
722
1670
  const id = nextId();
723
1671
  const innerScope = scope ?? '__s';
724
1672
  // Inner markers live in the block's OWN closes array, so wiring an
725
1673
  // adopted/cloned block never re-touches the parent's markers.
726
- const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers);
1674
+ const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers, comps);
727
1675
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
728
1676
  if (markers) {
729
- result += `const __c${id} = [];\n`;
730
- result += `const __bh${id} = __b${id}(${scope ?? 'undefined'}, __c${id});\n`;
731
- result += `const __i${id} = ${closes}.length;\n`;
732
- result += `${closes}.push(() => (${call}) ? { html: __bh${id}, closes: __c${id} } : null);\n`;
733
- result += `${acc} += "<!--\u27e6i:" + __i${id} + "\u27e7-->";\n`;
734
- result += `{ const __r = ${closes}[__i${id}](); if (__r) ${acc} += __r.html; }\n`;
735
- result += `${acc} += "<!--\u27e6/i:" + __i${id} + "\u27e7-->";\n`;
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
+ result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ''});\n`;
736
1681
  } else {
737
1682
  result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
738
1683
  }
@@ -741,18 +1686,21 @@ function compileTemplate(
741
1686
  const [, items, item, content] = earliest.match;
742
1687
  const before = remaining.substring(0, earliest.index);
743
1688
  if (before) result += emitChunk(before, acc, closes, scope);
744
- const call = items.trim().endsWith('()') ? items.trim() : `${items.trim()}()`;
1689
+ const call = autoCall(items);
745
1690
  const id = nextId();
746
- // Rename the item variable to the block's scope parameter
747
- const scoped = content.trim().replace(new RegExp(`\\b${item}\\b`, 'g'), '__s');
748
- const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, markers);
1691
+ // Rename the item variable to the block's scope parameter - INSIDE EXPRESSIONS ONLY.
1692
+ const itemRe = new RegExp(`\\b${item}\\b`, 'g');
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);
1700
+ const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, markers, comps);
749
1701
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
750
1702
  if (markers) {
751
- result += `const __i${id} = ${closes}.length;\n`;
752
- result += `${closes}.push(() => (${call}).map((${item}) => { const __c = []; return { html: __b${id}(${item}, __c), closes: __c, scope: ${item} }; }));\n`;
753
- result += `${acc} += "<!--\u27e6l:" + __i${id} + "\u27e7-->";\n`;
754
- result += `${closes}[__i${id}]().forEach((__r) => { ${acc} += __r.html; });\n`;
755
- result += `${acc} += "<!--\u27e6/l:" + __i${id} + "\u27e7-->";\n`;
1703
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});\n`;
756
1704
  } else {
757
1705
  result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');\n`;
758
1706
  }
@@ -764,12 +1712,70 @@ function compileTemplate(
764
1712
  const id = nextId();
765
1713
  // Error boundary: the content renders into its OWN string and is only appended on
766
1714
  // success - a throw anywhere inside swaps in the fallback …
767
- const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers);
1715
+ const catchesAction = /\$action:|<form[\s>]/.test(content);
1716
+ const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers, comps);
768
1717
  result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
769
1718
  result += `let __bd${id} = '';\n`;
770
- result += `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
1719
+ result += catchesAction
1720
+ ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }\n`
1721
+ : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
771
1722
  result += `${acc} += __bd${id};\n`;
772
1723
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1724
+ } else if (earliest.type === 'comp') {
1725
+ // <Card prop={x}>...</Card> -> Card(closes, children, props, slots).
1726
+ const tag = earliest.tag!;
1727
+ if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
1728
+ const entry = comps.get(tag.name)!;
1729
+ const id = nextId();
1730
+ let childrenSrc = '';
1731
+ let rest: string;
1732
+ if (tag.selfClosing) {
1733
+ rest = remaining.substring(tag.end);
1734
+ } else {
1735
+ const closeIdx = findClose(remaining, tag.end, tag.name);
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)` });
1737
+ childrenSrc = remaining.substring(tag.end, closeIdx);
1738
+ rest = remaining.substring(closeIdx + tag.name.length + 3);
1739
+ }
1740
+ 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
+ const hasChildren = def.trim().length > 0;
1744
+ if (hasChildren) {
1745
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1, markers, comps)} return h; };\n`;
1746
+ }
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
+ const slotFns = named.map(([nm, src]) => {
1750
+ const decl = entry.slots.find((s) => s.name === nm);
1751
+ let content = src;
1752
+ for (const p of decl?.props ?? []) {
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);
1761
+ }
1762
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1, markers, comps)} return h; }`;
1763
+ });
1764
+ const propsObj = parseCompAttrs(tag.attrs)
1765
+ .filter((a) => a.name !== 'slot')
1766
+ .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
+ const key = a.name.startsWith('on:') ? `on${capitalize(a.name.slice(3))}` : a.name;
1770
+ const val = a.kind === 'expr' ? `(${a.value})` : a.kind === 'str' ? JSON.stringify(a.value) : 'true';
1771
+ return `${JSON.stringify(key)}: ${val}`;
1772
+ })
1773
+ .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
+ const childrenArg = hasChildren ? `__ch${id}(${scope ?? 'undefined'}, ${closes})` : `''`;
1777
+ result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(', ')} });\n`;
1778
+ remaining = rest;
773
1779
  } else {
774
1780
  const [, expr] = earliest.match;
775
1781
  const trimmed = expr.trim();
@@ -780,6 +1786,33 @@ function compileTemplate(
780
1786
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
781
1787
  continue;
782
1788
  }
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
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
1792
+ if (slotCall) {
1793
+ 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
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);\n`;
1797
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1798
+ continue;
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
+ }
783
1816
  // attr={expr} -> reactive attribute; otherwise a text marker
784
1817
  const attrMatch = before.match(/([\w-]+)=\s*$/);
785
1818
  if (attrMatch) {
@@ -788,7 +1821,11 @@ function compileTemplate(
788
1821
  result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
789
1822
  } else {
790
1823
  if (before) result += emitChunk(before, acc, closes, scope);
791
- result += emitText(trimmed, acc, closes, scope, markers);
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
+ const after = remaining.substring(earliest.index + earliest.match[0].length);
1827
+ const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith('{');
1828
+ result += emitText(trimmed, acc, closes, scope, markers, pair);
792
1829
  }
793
1830
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
794
1831
  }
@@ -797,6 +1834,221 @@ function compileTemplate(
797
1834
  return result;
798
1835
  }
799
1836
 
1837
+ /** One component tag found in a template . */
1838
+ interface CompTag {
1839
+ /** index of `<` in the searched string */
1840
+ start: number;
1841
+ /** index just past `>` */
1842
+ end: number;
1843
+ name: string;
1844
+ /** the raw attribute text between the tag name and `>` */
1845
+ attrs: string;
1846
+ selfClosing: boolean;
1847
+ }
1848
+
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
+ */
1854
+ function scanTagEnd(src: string, start: number): number {
1855
+ let j = start + 1;
1856
+ let quote = '';
1857
+ let brace = 0;
1858
+ while (j < src.length) {
1859
+ const c = src[j];
1860
+ if (quote) {
1861
+ if (c === quote) quote = '';
1862
+ } else if (c === '"' || c === "'") quote = c;
1863
+ else if (c === '{') brace++;
1864
+ else if (c === '}') brace = Math.max(0, brace - 1);
1865
+ else if (c === '>' && brace === 0) return j + 1;
1866
+ j++;
1867
+ }
1868
+ return -1;
1869
+ }
1870
+
1871
+ /** The earliest open tag whose name is an imported component . */
1872
+ function findCompTag(src: string, comps: Map<string, unknown>): CompTag | null {
1873
+ let i = 0;
1874
+ while (i < src.length) {
1875
+ const lt = src.indexOf('<', i);
1876
+ if (lt < 0) return null;
1877
+ const nm = /^<([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
1878
+ if (nm && comps.has(nm[1])) {
1879
+ const end = scanTagEnd(src, lt);
1880
+ if (end > 0) {
1881
+ const raw = src.slice(lt, end);
1882
+ const selfClosing = /\/>$/.test(raw);
1883
+ return { start: lt, end, name: nm[1], attrs: raw.slice(1 + nm[1].length, selfClosing ? -2 : -1), selfClosing };
1884
+ }
1885
+ }
1886
+ i = lt + 1;
1887
+ }
1888
+ return null;
1889
+ }
1890
+
1891
+ /** Index of the `</name>` that closes the tag opened before `from` (-1: none). */
1892
+ function findClose(src: string, from: number, name: string): number {
1893
+ const re = new RegExp(`<(/?)${name}(?=[\\s/>])`, 'g');
1894
+ re.lastIndex = from;
1895
+ let depth = 1;
1896
+ let m: RegExpExecArray | null;
1897
+ while ((m = re.exec(src))) {
1898
+ const end = scanTagEnd(src, m.index);
1899
+ if (end < 0) return -1;
1900
+ if (m[1] === '/') {
1901
+ depth--;
1902
+ if (depth === 0) return m.index;
1903
+ } else if (!/\/>$/.test(src.slice(m.index, end))) depth++;
1904
+ }
1905
+ return -1;
1906
+ }
1907
+
1908
+ interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool'; value: string }
1909
+
1910
+ /** Parse a component tag's attributes into prop={expr} / prop="lit" / bool. */
1911
+ function parseCompAttrs(attrs: string): CompAttr[] {
1912
+ const out: CompAttr[] = [];
1913
+ let i = 0;
1914
+ while (i < attrs.length) {
1915
+ const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
1916
+ if (!nm) break;
1917
+ i += nm[0].length;
1918
+ const eq = /^\s*=\s*/.exec(attrs.slice(i));
1919
+ if (!eq) {
1920
+ out.push({ name: nm[1], kind: 'bool', value: '' });
1921
+ continue;
1922
+ }
1923
+ i += eq[0].length;
1924
+ const ch = attrs[i];
1925
+ if (ch === '{') {
1926
+ let depth = 1;
1927
+ let j = i + 1;
1928
+ while (j < attrs.length && depth > 0) {
1929
+ if (attrs[j] === '{') depth++;
1930
+ else if (attrs[j] === '}') depth--;
1931
+ j++;
1932
+ }
1933
+ out.push({ name: nm[1], kind: 'expr', value: attrs.slice(i + 1, j - 1).trim() });
1934
+ i = j;
1935
+ } else if (ch === '"' || ch === "'") {
1936
+ const j = attrs.indexOf(ch, i + 1);
1937
+ out.push({ name: nm[1], kind: 'str', value: attrs.slice(i + 1, j < 0 ? attrs.length : j) });
1938
+ i = j < 0 ? attrs.length : j + 1;
1939
+ } else break;
1940
+ }
1941
+ return out;
1942
+ }
1943
+
1944
+ /**
1945
+ * Reject a slot= that hides inside a named slot's content. The child only
1946
+ * ever looks at its DIRECT named children, so `<span slot="a"><b slot="a">`
1947
+ * would silently drop the inner one - say it at build time instead. The walk
1948
+ * is quote-aware (scanTagEnd), so an attribute value containing '>' cannot
1949
+ * fake a tag.
1950
+ */
1951
+ function rejectNestedSlot(src: string, outer: string): void {
1952
+ let i = 0;
1953
+ while (i < src.length) {
1954
+ const lt = src.indexOf('<', i);
1955
+ if (lt < 0) return;
1956
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
1957
+ if (!nm) { i = lt + 1; continue; }
1958
+ const end = scanTagEnd(src, lt);
1959
+ if (end < 0) return;
1960
+ const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
1961
+ if (hit && nm[1] !== '/') {
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' });
1963
+ }
1964
+ i = end;
1965
+ }
1966
+ }
1967
+
1968
+ /**
1969
+ * Split a component's children into the default slot and the named slots
1970
+ * (`<li slot="row">`). Only DIRECT children may be slot content: lifting an
1971
+ * element out of another element, or out of an {#if}/{#each} block, would
1972
+ * break the template around it - so that is a build error, not a silent
1973
+ * mis-render.
1974
+ */
1975
+ function splitSlots(src: string): { def: string; named: Array<[string, string]> } {
1976
+ let def = '';
1977
+ const named = new Map<string, string>();
1978
+ let i = 0;
1979
+ let elemDepth = 0;
1980
+ let blockDepth = 0;
1981
+ while (i < src.length) {
1982
+ const lt = src.indexOf('<', i);
1983
+ const ob = src.indexOf('{#', i);
1984
+ const cb = src.indexOf('{/', i);
1985
+ const cands = [lt, ob, cb].filter((x) => x >= 0);
1986
+ if (cands.length === 0) {
1987
+ def += src.slice(i);
1988
+ break;
1989
+ }
1990
+ const next = Math.min(...cands);
1991
+ if (next > i) def += src.slice(i, next);
1992
+ if (next === ob || next === cb) {
1993
+ const close = src.indexOf('}', next);
1994
+ const token = src.slice(next, close < 0 ? src.length : close + 1);
1995
+ if (next === ob) blockDepth++;
1996
+ else blockDepth = Math.max(0, blockDepth - 1);
1997
+ def += token;
1998
+ i = next + token.length;
1999
+ continue;
2000
+ }
2001
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(next, next + 64));
2002
+ if (!nm) {
2003
+ def += '<';
2004
+ i = next + 1;
2005
+ continue;
2006
+ }
2007
+ const end = scanTagEnd(src, next);
2008
+ if (end < 0) {
2009
+ def += src.slice(next);
2010
+ break;
2011
+ }
2012
+ const tagText = src.slice(next, end);
2013
+ const selfClosing = /\/>$/.test(tagText);
2014
+ const isVoid = VOID_TAGS.has(nm[2].toLowerCase());
2015
+ if (nm[1] === '/') {
2016
+ elemDepth = Math.max(0, elemDepth - 1);
2017
+ def += tagText;
2018
+ i = end;
2019
+ continue;
2020
+ }
2021
+ if (!selfClosing && !isVoid) elemDepth++;
2022
+ const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
2023
+ if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
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' });
2025
+ }
2026
+ if (slotName) {
2027
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '');
2028
+ if (selfClosing || isVoid) {
2029
+ named.set(slotName, (named.get(slotName) ?? '') + stripped);
2030
+ } else {
2031
+ const closeIdx = findClose(src, end, nm[2]);
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` });
2033
+ const tail = `</${nm[2]}>`;
2034
+ 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
+ rejectNestedSlot(inner, slotName);
2038
+ named.set(slotName, (named.get(slotName) ?? '') + stripped + inner + tail);
2039
+ elemDepth = Math.max(0, elemDepth - 1);
2040
+ i = closeIdx + tail.length;
2041
+ continue;
2042
+ }
2043
+ i = end;
2044
+ continue;
2045
+ }
2046
+ def += tagText;
2047
+ i = end;
2048
+ }
2049
+ return { def, named: [...named.entries()] };
2050
+ }
2051
+
800
2052
  /** Emit a static chunk (attributes are handled by the expr branch). */
801
2053
  function emitChunk(text: string, acc: string, closes: string, scope: string | null): string {
802
2054
  if (!text) return '';
@@ -816,7 +2068,7 @@ const IMG_MIME: Record<string, string> = {
816
2068
  '.svg': 'image/svg+xml',
817
2069
  '.ico': 'image/x-icon',
818
2070
  };
819
- // ponytail: fixed 4 KB cap; make it configurable when a real app cares
2071
+ // Trade-off: fixed 4 KB cap; make it configurable when a real app cares
820
2072
  const INLINE_IMG_MAX = 4096;
821
2073
 
822
2074
  function inlineImages(template: string, publicDir: string): string {
@@ -841,23 +2093,31 @@ function inlineImages(template: string, publicDir: string): string {
841
2093
  });
842
2094
  }
843
2095
 
844
- /** Emit a reactive text marker: <!--⟦m:K⟧-->escaped value. */
845
- function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
846
- const arg = scope ? `${scope}` : '';
2096
+ /**
2097
+ * Emit a reactive text marker through the runtime's textMark(): the helper
2098
+ * pushes the closure and returns the marker pair around the escaped value.
2099
+ * A marker whose value is followed by literal text passes pair, so the wire
2100
+ * can bound exactly the value and leave the prose alone.
2101
+ */
2102
+ function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true, pair = false): string {
847
2103
  if (!markers) {
848
2104
  // head block: inline escaped value, no marker comment (clean SSR html)
849
2105
  return `${acc} += esc(${expr});\n`;
850
2106
  }
851
- return `${acc} += "<!--\u27e6m:" + (${closes}.push(${scope ? `(${scope})` : '()'} => (${expr})) - 1) + "\u27e7-->" + esc(${closes}[${closes}.length - 1](${arg}));\n`;
2107
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
2108
+ let extra = pair ? ', 1' : scope ? ', 0' : '';
2109
+ if (scope) extra += `, ${scope}`;
2110
+ return `${acc} += textMark(${closes}, ${fn}${extra});\n`;
852
2111
  }
853
2112
 
854
- /** Emit a reactive attribute: name="value" data-b="K:name". */
2113
+ /** Emit a reactive attribute through the runtime's attrMark(). */
855
2114
  function emitAttr(attr: string, expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
856
2115
  if (!markers) {
857
2116
  return `${acc} += '${attr}="' + esc(${expr}) + '"';\n`;
858
2117
  }
859
- const arg = scope ? `${scope}` : '';
860
- return `${acc} += '${attr}="' + esc(${closes}[${closes}.push(${scope ? `(${scope})` : '()'} => (${expr})) - 1](${arg})) + '" data-b="' + (${closes}.length - 1) + ':${attr}"';\n`;
2118
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
2119
+ const arg = scope ? `, ${scope}` : '';
2120
+ return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
861
2121
  }
862
2122
 
863
2123
  /**
@@ -868,26 +2128,81 @@ function compileSlot(acc: string): string {
868
2128
  return `${acc} += String(children);\n`;
869
2129
  }
870
2130
 
871
- function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = ''): string {
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';`;
2134
+
2135
+ /**
2136
+ * `export let title = 'x'` -> a per-invocation const read from the
2137
+ * caller's props object, defaulting to the declared value. Emitted at the top
2138
+ * of render(), BEFORE the state declarations: a prop may seed one
2139
+ * (`let open = $state(collapsed)`).
2140
+ */
2141
+ function propsCode(props: Array<{ name: string; def: string | null }>): string {
2142
+ if (props.length === 0) return '';
2143
+ return props
2144
+ .map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ''};`)
2145
+ .join('\n');
2146
+ }
2147
+
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
+ const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
2151
+ const fn = sl[name];
2152
+ if (typeof fn !== 'function') return null;
2153
+ const o = {};
2154
+ for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
2155
+ return { o, fn };
2156
+ };
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
+ };`;
2167
+
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 {
872
2169
  // The head block renders to a clean html string (no markers) and is wrapped in an h
873
2170
  // marker pair: renderPage extracts it for <head> injection …
874
2171
  const headCode = headFn
875
2172
  ? `
876
2173
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
877
- const __hi = closes.length;
878
- closes.push(__head);
879
- __html += "<!--\u27e6h:" + __hi + "\u27e7-->" + __head() + "<!--\u27e6/h:" + __hi + "\u27e7-->";`
2174
+ __html += headMark(closes, __head);`
880
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);` : '';
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(...)`) …
881
2182
  return `
882
- import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, $cookies, $sessionCookie, $store } from './runtime.js';
2183
+ ${RUNTIME_IMPORTS}
2184
+
2185
+ ${imports}
883
2186
 
884
2187
  ${exports}
2188
+ ${guard}
2189
+ ${actionState}
885
2190
 
886
- export async function render(closes, children) {
887
- ${stateDeclsCode}
2191
+ ${namedSlots ? SLOT_HELPER : ''}
2192
+
2193
+ export ${isComponent ? 'function' : 'async function'} render(closes, children, __props, __slots) {
2194
+ ${props.length > 0 ? 'const __p = __props || {};' : ''}
2195
+ ${namedSlots ? 'const __sl = __slots || {};' : ''}
2196
+ ${propsCode(props)}
888
2197
  ${script}
2198
+ ${stateDeclsCode}
2199
+ ${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).
2203
+ ${isComponent ? '' : 'applyStateDeltas();'}
889
2204
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
890
- let __html = await __root(closes, children);${headCode}
2205
+ let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
891
2206
  return __html;
892
2207
  }
893
2208
  `;
@@ -899,34 +2214,43 @@ function generateClient(
899
2214
  stateDeclsCode: string,
900
2215
  eventBindings: Array<{ event: string; fn: string }>,
901
2216
  exports = '',
902
- headFn = ''
2217
+ headFn = '',
2218
+ props: Array<{ name: string; def: string | null }> = [],
2219
+ namedSlots = false,
2220
+ imports = '',
2221
+ isComponent = false,
2222
+ dataDeclsCode = ''
903
2223
  ): string {
904
- // Handlers live on a shared global so one delegated listener per event
905
- // type can dispatch for any component, including freshly cloned nodes.
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.
906
2226
  const handlerRegistry = eventBindings.length > 0
907
- ? `Object.assign(__handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
2227
+ ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
908
2228
  : '';
909
2229
  const headCode = headFn
910
2230
  ? `
911
2231
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
912
- const __hi = closes.length;
913
- closes.push(__head);
914
- __html += "<!--\u27e6h:" + __hi + "\u27e7-->" + __head() + "<!--\u27e6/h:" + __hi + "\u27e7-->";`
2232
+ __html += headMark(closes, __head);`
915
2233
  : '';
916
2234
 
917
2235
  return `
918
- import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, $cookies, $sessionCookie, $store } from './runtime.js';
2236
+ ${RUNTIME_IMPORTS}
2237
+
2238
+ ${imports}
919
2239
 
920
2240
  ${exports}
921
2241
 
922
- const __handlers = globalThis.__rosetack_handlers ?? (globalThis.__rosetack_handlers = {});
2242
+ ${namedSlots ? SLOT_HELPER : ''}
923
2243
 
924
- export async function render(closes, children) {
925
- ${stateDeclsCode}
2244
+ export ${isComponent ? 'function' : 'async function'} render(closes, children, __props, __slots) {
2245
+ ${props.length > 0 ? 'const __p = __props || {};' : ''}
2246
+ ${namedSlots ? 'const __sl = __slots || {};' : ''}
2247
+ ${propsCode(props)}
926
2248
  ${script}
2249
+ ${stateDeclsCode}
2250
+ ${dataDeclsCode}
927
2251
  ${handlerRegistry}
928
2252
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
929
- let __html = await __root(closes, children);${headCode}
2253
+ let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
930
2254
  return __html;
931
2255
  }
932
2256
  `;
@@ -943,7 +2267,7 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
943
2267
  .map(({ i }) => i);
944
2268
 
945
2269
  /**
946
- * Innovation #29's decision as a pure function: does this route's document
2270
+ * 's decision as a pure function: does this route's document
947
2271
  * ship without the client bundle? Shared by the route table (csr: false) and
948
2272
  * the build report (#31), so the report can never disagree with the build.
949
2273
  */
@@ -956,7 +2280,7 @@ const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number
956
2280
  };
957
2281
 
958
2282
  /**
959
- * The build's zero-JS lint report (innovation #31): one line per route with
2283
+ * The build's zero-JS lint report: one line per route with
960
2284
  * its verdict and the exact reason - which component in the chain needs the
961
2285
  * client bundle and why, or that nothing does. Pure: the same inputs the
962
2286
  * route table is built from.
@@ -964,8 +2288,8 @@ const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number
964
2288
  export function buildReport(infos: RouteInfo[], compiled: CompileResult[]): string[] {
965
2289
  return infos
966
2290
  .map((info, i) => ({ info, i }))
967
- .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware)
968
- .map(({ info, i }) => {
2291
+ .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
2292
+ .map(({ info, i }) => {
969
2293
  if (routeShipsNoJs(infos, compiled, i)) {
970
2294
  return `${info.routePath} zero-JS nothing in the chain needs the client`;
971
2295
  }
@@ -987,31 +2311,96 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
987
2311
  /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
988
2312
  await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
989
2313
 
990
- const files = await scanRoseFiles(root);
991
- // Phase 0: a build that silently produces nothing is the worst possible failure mode (an
992
- // empty dist/ deploys as a blank site).
993
- if (files.length === 0) {
994
- 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>`);
2314
+ const pageFiles = await scanRoseFiles(root);
2315
+ const compFiles = await scanComponentFiles(root);
2316
+ 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
+ if (pageFiles.length === 0) {
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
+ );
995
2325
  }
996
2326
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
997
- // Plugins (innovation #30): rosetack.config.js at the project root, loaded
998
- // fresh per build so the dev server's hot rebuild picks up config edits.
999
- const plugins = await loadPlugins(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
+ const config = await loadConfig(root);
2330
+ const plugins = config.plugins;
1000
2331
  // scope key: the component's path under pages/ (index, _layout, blog/[id])
1001
- const scopeKeys = files.map((f) =>
1002
- path.relative(path.join(root, 'src', 'pages'), f).replace(/\\/g, '/').replace(/\.rose$/, ''));
2332
+ const scopeKeys = files.map((f, i) => {
2333
+ const base = infos[i].isComponent ? path.join(root, 'src') : path.join(root, 'src', 'pages');
2334
+ return path.relative(base, f).replace(/\\/g, '/').replace(/\.rose$/, '');
2335
+ });
2336
+ // The build-wide import registry: absolute path -> module index, scope key, and the named
2337
+ // slots the component declares.
2338
+ const registry: RoseRegistry = new Map(
2339
+ files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
2340
+ );
1003
2341
  const compiled = await Promise.all(
1004
- files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins))
2342
+ files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
1005
2343
  );
1006
2344
 
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
+ const importsOf = new Map<number, number[]>();
2348
+ files.forEach((_, i) => {
2349
+ const list: number[] = [];
2350
+ for (const r of compiled[i].roseImports ?? []) {
2351
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
2352
+ const hit = registry.get(abs);
2353
+ if (hit) list.push(hit.index);
2354
+ }
2355
+ importsOf.set(i, list);
2356
+ });
2357
+ // The walk reports WHICH dependency needs the client, so the build's lint
2358
+ // line names the component instead of the page.
2359
+ const needyDep = (i: number, seen = new Set<number>()): string | null => {
2360
+ if (compiled[i].needsClient) return path.basename(files[i]);
2361
+ if (seen.has(i)) return null;
2362
+ seen.add(i);
2363
+ for (const dep of importsOf.get(i) ?? []) {
2364
+ const hit = needyDep(dep, seen);
2365
+ if (hit) return hit;
2366
+ }
2367
+ return null;
2368
+ };
2369
+ compiled.forEach((c, i) => {
2370
+ if (c.needsClient) return;
2371
+ const who = needyDep(i);
2372
+ if (who) {
2373
+ c.needsClient = true;
2374
+ c.clientReasons = [...(c.clientReasons ?? []), `imported component ${who} needs the client`];
2375
+ }
2376
+ });
2377
+
2378
+ // Reachability: a component no page (transitively) imports ships in neither
2379
+ // bundle - not the server's, not the client's.
2380
+ const reachable = new Set<number>();
2381
+ const visit = (i: number) => {
2382
+ if (reachable.has(i)) return;
2383
+ reachable.add(i);
2384
+ for (const r of compiled[i].roseImports ?? []) {
2385
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
2386
+ const hit = registry.get(abs);
2387
+ if (hit) visit(hit.index);
2388
+ }
2389
+ };
2390
+ files.forEach((_, i) => {
2391
+ if (!infos[i].isComponent) visit(i);
2392
+ });
2393
+
1007
2394
  // Every component's scoped CSS in one stylesheet, inlined into the shell:
1008
2395
  // styles ship inside the document like the JS bundle - zero requests.
1009
- const styles = compiled.map((c) => c.style).filter(Boolean).join('\n');
2396
+ const styles = compiled
2397
+ .map((c, i) => (reachable.has(i) ? c.style : ''))
2398
+ .filter(Boolean).join('\n');
1010
2399
  if (styles) await fs.promises.writeFile(path.join(outDir, 'styles.css'), styles);
1011
2400
  else await fs.promises.rm(path.join(outDir, 'styles.css'), { force: true });
1012
2401
 
1013
- // i18n (innovation #27): every JSON file in src/locales/ is a language. The dictionaries
1014
- // are baked into BOTH bundles at build time …
2402
+ // i18n: every JSON file in src/locales/ is a language. The dictionaries are baked into
2403
+ // BOTH bundles at build time …
1015
2404
  let locales: Record<string, Record<string, string>> = {};
1016
2405
  try {
1017
2406
  for (const f of await fs.promises.readdir(path.join(root, 'src', 'locales'))) {
@@ -1024,15 +2413,56 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1024
2413
  const defaultLocale = locales.en ? 'en' : Object.keys(locales).sort()[0] ?? 'en';
1025
2414
  const localesJson = JSON.stringify(locales).replace(/</g, '\\u003c');
1026
2415
 
2416
+ // Which dictionaries ride in the CLIENT bundle. Default: all of them, so a locale switch
2417
+ // stays a zero-request navigation.
2418
+ const preload: string[] = config.i18n.preload ?? Object.keys(locales);
2419
+ const packed = Object.keys(locales).filter((l) => !preload.includes(l));
2420
+ for (const l of preload) {
2421
+ if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
2422
+ }
2423
+ await fs.promises.rm(path.join(outDir, 'locales'), { recursive: true, force: true });
2424
+ if (packed.length > 0) {
2425
+ const packDir = path.join(outDir, 'locales');
2426
+ await fs.promises.mkdir(packDir, { recursive: true });
2427
+ for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
2428
+ }
2429
+ const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
2430
+ const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, '\\u003c');
2431
+
1027
2432
  // Intermediates (component modules, shared runtime, bundle entries) live in a build dir
1028
2433
  // that is removed before returning: both bundles are fully self-contained …
1029
2434
  const buildDir = path.join(outDir, '.build');
1030
2435
  await fs.promises.rm(buildDir, { recursive: true, force: true });
1031
2436
  await fs.promises.mkdir(buildDir, { recursive: true });
1032
2437
 
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
+ const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
2441
+ if (runtimePlugins.length > 0) {
2442
+ // Relative from .build/, so the build works from any cwd (`rosetack build <dir>` from
2443
+ // elsewhere).
2444
+ 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.
2448
+ import config from ${JSON.stringify(configRel)};
2449
+
2450
+ const list = Array.isArray(config) ? config : [];
2451
+ export const hooks = list
2452
+ .filter((p) => p && (p.onRequest || p.onResponse))
2453
+ .map((p) => ({ name: p.name, onRequest: p.onRequest ? p.onRequest.bind(p) : null, onResponse: p.onResponse ? p.onResponse.bind(p) : null }));
2454
+
2455
+ export const hasRequestHooks = hooks.some((p) => p.onRequest);
2456
+ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2457
+ `);
2458
+ }
2459
+
1033
2460
  // Shared runtime module, bundled once into client and server output. The runtime ships
1034
2461
  // WITH THE COMPILER …
1035
- const runtimeEntry = fileURLToPath(new URL('../runtime/index.ts', import.meta.url));
2462
+ const runtimeEntry = ['../runtime/index.ts', '../src/runtime/index.ts']
2463
+ .map((rel) => fileURLToPath(new URL(rel, import.meta.url)))
2464
+ .find((p) => fs.existsSync(p));
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' });
1036
2466
  await esbuild.build({
1037
2467
  entryPoints: [runtimeEntry],
1038
2468
  bundle: true,
@@ -1054,7 +2484,7 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1054
2484
 
1055
2485
  const pages = infos
1056
2486
  .map((info, i) => ({ info, i }))
1057
- .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware);
2487
+ .filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1058
2488
 
1059
2489
  // API routes (pages/api/*.rose) dispatch handlers, never render HTML: they live in the
1060
2490
  // server bundle only and are excluded from the client route table entirely.
@@ -1071,7 +2501,8 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1071
2501
  return expr;
1072
2502
  };
1073
2503
 
1074
- // P0 §1 (consultant report): mode B. `export const bundle = 'split'` …
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 …
1075
2506
  const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? 'inline';
1076
2507
  const split = bundleMode === 'split';
1077
2508
  // The chain a route's chunk graph must load: the page first, then its layouts
@@ -1083,12 +2514,13 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1083
2514
  `load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(', ')}])`;
1084
2515
  const loaderOf = (idx: number): string => `{ ${loaderInner(idx)} }`;
1085
2516
 
1086
- // Innovation #29: the compiler decides zero-JS, not the developer. A route ships no
1087
- // client bundle - no runtime, no state script, zero JavaScript …
2517
+ // The compiler decides zero-JS, not the developer. A route ships no client bundle - no
2518
+ // runtime, no state script, zero JavaScript …
1088
2519
  const routeNoJs = (i: number): boolean => routeShipsNoJs(infos, compiled, i);
1089
2520
 
1090
2521
  const serverImports = compiled
1091
2522
  .map((_, i) => {
2523
+ if (!reachable.has(i)) return ''; // an unimported component ships nowhere
1092
2524
  if (infos[i].isMiddleware) {
1093
2525
  // pages/_middleware.rose: server-only, imported as a namespace so a missing
1094
2526
  // `handle` export is simply "no middleware" (null), never a build error
@@ -1107,8 +2539,11 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1107
2539
  const isPage = !infos[i].isLayout && !infos[i].isNotFound;
1108
2540
  const names = isPage ? compiled[i].actionNames : [];
1109
2541
  const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
1110
- return names.length > 0
1111
- ? `import { render as render_${i}, ${actionImports} } from './comp-${i}.ssr.js';`
2542
+ // The action guard rides the same import, server-only like the actions it fronts
2543
+ const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : '';
2544
+ const named = [actionImports, guardImport].filter(Boolean).join(', ');
2545
+ return named
2546
+ ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';`
1112
2547
  : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1113
2548
  })
1114
2549
  .join('\n');
@@ -1131,31 +2566,103 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
1131
2566
  // actions: name -> imported fn, so a POST's __action field …
1132
2567
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(', ');
1133
2568
  // csr: false rides on the route so renderPage/renderPageStream can drop the state
1134
- // script + bundle from the document …
2569
+ // script + bundle from the document (; the decision is the compiler's since #29).
2570
+ if (compiled[i].csr === false && compiled[i].needsClient) {
2571
+ throw new RoseError(
2572
+ 'E-EXPORT',
2573
+ `${info.filePath}: csr = false but this route needs the client bundle ` +
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' },
2576
+ );
2577
+ }
1135
2578
  if (compiled[i].csr === false) {
1136
2579
  const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1137
2580
  if (needy !== undefined) {
1138
- throw new Error(
2581
+ throw new RoseError(
2582
+ 'E-EXPORT',
1139
2583
  `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle ` +
1140
- `(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' },
1141
2586
  );
1142
2587
  }
1143
2588
  }
1144
2589
  const csrFlag = routeNoJs(i) ? ', csr: false' : '';
1145
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${csrFlag} }`;
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' : '';
2593
+ // Guard - runs before every action of this route (null when the
2594
+ // page exports no beforeAction)
2595
+ 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} }`;
1146
2597
  })
1147
2598
  .join(',\n ');
1148
2599
 
1149
2600
  const serverEntry = `
1150
2601
  ${serverImports}
1151
- import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, setStoreTransport, applyStorePatch } from './runtime.js';
2602
+ import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
2603
+ ${runtimePlugins.length > 0
2604
+ ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
2605
+ : `// no plugin declares a runtime hook, so there is no plugins
2606
+ // module to import - the runners below stay no-ops and the servers call them
2607
+ // unconditionally (one code path, no flags to keep in sync).
2608
+ const __pluginHooks = [];
2609
+ const __hasRequestHooks = false;
2610
+ const __hasResponseHooks = false;`}
2611
+
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).
2618
+ export async function runRequestHooks(ctx) {
2619
+ for (const p of __pluginHooks) {
2620
+ if (!p.onRequest) continue;
2621
+ try {
2622
+ const r = await p.onRequest(ctx);
2623
+ if (r instanceof Response) return r;
2624
+ } catch (err) {
2625
+ console.error('rosetack: plugin', p.name, 'onRequest failed:', err instanceof Error ? err.message : err);
2626
+ }
2627
+ }
2628
+ return null;
2629
+ }
1152
2630
 
1153
- // i18n (innovation #27): the dictionaries baked at build time from
2631
+ export async function runResponseHooks(ctx, res) {
2632
+ let out = res;
2633
+ for (const p of __pluginHooks) {
2634
+ if (!p.onResponse) continue;
2635
+ try {
2636
+ const r = await p.onResponse(ctx, out);
2637
+ if (r instanceof Response) out = r;
2638
+ } catch (err) {
2639
+ console.error('rosetack: plugin', p.name, 'onResponse failed:', err instanceof Error ? err.message : err);
2640
+ }
2641
+ }
2642
+ return out;
2643
+ }
2644
+
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.
2647
+ export const hasRequestHooks = __hasRequestHooks;
2648
+ export const hasResponseHooks = __hasResponseHooks;
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
+
2660
+ // i18n: the dictionaries baked at build time from
1154
2661
  // src/locales/*.json. A route segment named [lang] is the locale: the value
1155
2662
  // must name one of these dictionaries, and $t resolves keys against it.
1156
2663
  setLocales(${localesJson}, '${defaultLocale}');
1157
2664
 
1158
- // Phase 2: the store transport. Under "rosetack serve" every worker is its
2665
+ // The store transport. Under "rosetack serve" every worker is its
1159
2666
  // own process with its own dist/server.js module, so a $store write must
1160
2667
  // travel: this worker -> primary -> every other worker. process.send exists
1161
2668
  // only inside cluster workers, so a single-process runner (dev, preview,
@@ -1183,12 +2690,16 @@ export const routeParams = {
1183
2690
  ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(',\n ')}
1184
2691
  };
1185
2692
 
1186
- // Routes whose component reads the request context (getContext()): the bag
1187
- // is per-request, so these are dynamic - the build never bakes them and the
1188
- // servers never answer them from a prerendered file. Public routes keep the
1189
- // static fast path (file cache, ETag/304, streaming) untouched.
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.
1190
2701
  export const dynamicRoutes = [
1191
- ${pages.filter(({ i }) => compiled[i].usesContext).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 ')}
1192
2703
  ];
1193
2704
 
1194
2705
  // Which api routes opt into build-time baking (export const prerender = true):
@@ -1204,7 +2715,7 @@ export const apiPrerender = {
1204
2715
  // bakes these routes like any other, and the preview server serves the
1205
2716
  // baked file for up to N seconds - after which the next request is answered
1206
2717
  // STALE (instant, from disk) while a background pass re-renders and swaps
1207
- // the file (ISR, innovation #24). Routes that read the request context are
2718
+ // the file (ISR). Routes that read the request context are
1208
2719
  // excluded: they render per request and have no baked file to revalidate.
1209
2720
  // The dev server ignores the window (it rebuilds on change), the edge
1210
2721
  // adapter renders live (always fresh), and the Go binary serves the baked
@@ -1221,7 +2732,7 @@ export const revalidate = [
1221
2732
  // and the servers keep their static fast paths.
1222
2733
  export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
1223
2734
 
1224
- // Routes whose DOCUMENTS ship without the client bundle (innovation #25,
2735
+ // Routes whose DOCUMENTS ship without the client bundle (
1225
2736
  // decided by the compiler since #29): HTML + CSS only - no runtime, no
1226
2737
  // state script, zero JavaScript for whoever lands on them. The compiler
1227
2738
  // picks these automatically: a route whose whole chain needs nothing from
@@ -1242,7 +2753,17 @@ export function isNoJs(pathname) {
1242
2753
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1243
2754
  }
1244
2755
 
1245
- // Per-route response headers (innovation #26): a route exporting a headers
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
+
2766
+ // Per-route response headers: a route exporting a headers
1246
2767
  // map carries them into every response the servers write for it, merged
1247
2768
  // OVER the framework defaults (the strict CSP) - so an app can tighten or
1248
2769
  // relax the policy per route. Absent -> null, and the servers keep sending
@@ -1256,6 +2777,22 @@ export function headersFor(pathname) {
1256
2777
  return hit ? hit.headers : null;
1257
2778
  }
1258
2779
 
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.
2788
+ export const cspNonceRoutes = [
2789
+ ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
2790
+ ];
2791
+
2792
+ export function cspNonce(pathname) {
2793
+ return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
2794
+ }
2795
+
1259
2796
  // A Web-standard Request from whatever the host provides: the edge adapter
1260
2797
  // passes one already; the Node server passes its IncomingMessage (plus the
1261
2798
  // already-parsed FormData for POSTs, so middleware can read form fields).
@@ -1302,11 +2839,31 @@ const notFound = ${notFoundRender};
1302
2839
  // whose render throws degrades to this instead of failing the response.
1303
2840
  const errorPage = ${errorRender};
1304
2841
 
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.
2848
+ export function docAttrs(pathname) {
2849
+ for (const route of routes) {
2850
+ if (!matchRoute(route.pattern, pathname)) continue;
2851
+ const parts = route.pattern.split('/');
2852
+ const langIdx = parts.indexOf(':lang');
2853
+ if (langIdx >= 0) {
2854
+ const lang = pathname.split('/')[langIdx];
2855
+ if (isLocale(lang)) return { lang, dir: localeDir(lang) };
2856
+ }
2857
+ break; // matched, but not a localized route (or a bogus locale): the default
2858
+ }
2859
+ return { lang: defaultLocale, dir: localeDir(defaultLocale) };
2860
+ }
2861
+
1305
2862
  // Paint a fallback page (404/500) and serialize its state.
1306
2863
  async function renderFallback(pathname, render) {
1307
2864
  const { html, head } = extractHead(await render([], ''));
1308
2865
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1309
- return { html, state, head };
2866
+ return { html, state, head, ...docAttrs(pathname) };
1310
2867
  }
1311
2868
 
1312
2869
  export function matchRoute(pattern, pathname) {
@@ -1359,20 +2916,52 @@ export async function renderPage(pathname, form) {
1359
2916
  setState(patternParts[i].slice(1), pathParts[i]);
1360
2917
  }
1361
2918
  }
1362
- // i18n (innovation #27): a [lang] segment naming no dictionary is a
2919
+ // i18n: a [lang] segment naming no dictionary is a
1363
2920
  // 404 - the URL is the contract, and rendering the page with fallback
1364
2921
  // strings would serve duplicate content under a bogus language
1365
2922
  const langIdx = patternParts.indexOf(':lang');
1366
2923
  if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
1367
2924
  if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
1368
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404 };
2925
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1369
2926
  }
2927
+ // The document's <html lang>/<dir> follow this route's locale
2928
+ // (the default's when the route is not localized)
2929
+ 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.
2940
+ let actionStatus = 0;
1370
2941
  if (form && route.actions) {
1371
- const fn = route.actions[form.get('__action') || 'action'];
2942
+ const actionName = form.get('__action') || 'action';
2943
+ const fn = route.actions[actionName];
1372
2944
  if (fn) {
1373
- const patch = await fn(form);
1374
- if (patch && typeof patch === 'object') {
1375
- for (const key of Object.keys(patch)) setState(key, patch[key]);
2945
+ try {
2946
+ if (route.guard) await route.guard(actionName, form);
2947
+ const patch = await fn(form);
2948
+ if (patch && typeof patch === 'object') {
2949
+ for (const key of Object.keys(patch)) {
2950
+ 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.
2954
+ if (v instanceof StateDelta) setStateDelta(key, v);
2955
+ else setState(key, v);
2956
+ }
2957
+ }
2958
+ } catch (err) {
2959
+ if (err instanceof ActionError) {
2960
+ setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
2961
+ actionStatus = err.code;
2962
+ } else {
2963
+ throw err;
2964
+ }
1376
2965
  }
1377
2966
  }
1378
2967
  }
@@ -1382,24 +2971,30 @@ export async function renderPage(pathname, form) {
1382
2971
  } catch (err) {
1383
2972
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1384
2973
  if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
1385
- return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500 };
2974
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
1386
2975
  }
1387
2976
  // __route tells the bootstrap which route this document was rendered for.
1388
2977
  // A static-file server may serve another route's document (SPA fallback);
1389
2978
  // the bootstrap then client-renders instead of adopting mismatched DOM.
1390
2979
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1391
- // csr (innovation #25, auto since #29): false when the compiler found
2980
+ // csr ( auto since #29): false when the compiler found
1392
2981
  // nothing in the route's chain that needs the client (or the route
1393
2982
  // asserted csr = false) - the document ships no runtime, no state
1394
2983
  // script, zero JavaScript. Every other route keeps the bundle. The
1395
2984
  // caller passes this straight to the shell as js.
1396
- return { html: rendered.html, state, head: rendered.head, status: 200, csr: route.csr !== false };
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) };
1397
2992
  }
1398
2993
  }
1399
2994
  if (notFound) {
1400
2995
  return { ...(await renderFallback(pathname, notFound)), status: 404 };
1401
2996
  }
1402
- return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404 };
2997
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1403
2998
  }
1404
2999
 
1405
3000
  // Would renderPageStream handle this path? (matched route = stream, anything
@@ -1407,7 +3002,7 @@ export async function renderPage(pathname, form) {
1407
3002
  export function canStream(pathname) {
1408
3003
  return routes.some((route) => {
1409
3004
  if (!matchRoute(route.pattern, pathname)) return false;
1410
- // i18n (innovation #27): an unknown locale must answer 404, and a
3005
+ // i18n: an unknown locale must answer 404, and a
1411
3006
  // streamed response cannot change its status - so it takes the buffered
1412
3007
  // path (renderPage returns the real 404), never the streaming one
1413
3008
  const langIdx = route.pattern.split('/').indexOf(':lang');
@@ -1493,7 +3088,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1493
3088
  html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
1494
3089
  }
1495
3090
  write(html);
1496
- // csr: false (innovation #25, auto since #29): a no-JS route's document
3091
+ // csr: false ( auto since #29): a no-JS route's document
1497
3092
  // ends here - no state script, no inlined bundle. (The servers keep
1498
3093
  // these routes off the streaming path so their <head> is complete;
1499
3094
  // this is the correctness floor if one streams anyway.)
@@ -1517,13 +3112,14 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1517
3112
  format: 'esm',
1518
3113
  platform: 'node',
1519
3114
  write: true,
3115
+ ...TS_LOADER,
1520
3116
  });
1521
3117
 
1522
3118
  // api routes and the middleware have no client module: they are server-only handlers /
1523
3119
  // interceptors.
1524
3120
  const clientImports = split ? '' : compiled
1525
3121
  .map((_, i) => ({ i }))
1526
- .filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware)
3122
+ .filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i))
1527
3123
  .map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`)
1528
3124
  .join('\n');
1529
3125
 
@@ -1533,24 +3129,65 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1533
3129
  : `{ pattern: '${info.pattern}', render: ${compose(i)} }`))
1534
3130
  .join(',\n ');
1535
3131
 
1536
- // P1 (consultant report): the app-global prefetch strategy, declared once (the root
1537
- // layout) as `export const prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
3132
+ // P1: the app-global prefetch strategy, declared once (the root layout) as `export const
3133
+ // prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
1538
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
+ : '';
3141
+
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
+ const hasLang = infos.some((i) => i.pattern.includes(':lang'));
3145
+ const langDirBlock = hasLang
3146
+ ? ` // <html lang dir> follows the route - the one part of the document
3147
+ // client-side navigation cannot leave stale (screen readers and CSS
3148
+ // logical properties both read it). A route with no [lang] segment
3149
+ // returns to the default locale, and a bogus segment falls back to it
3150
+ // too, exactly like the server's docAttrs.
3151
+ const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
3152
+ 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');
3158
+ if (!known) {`
3159
+ : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
1539
3160
 
1540
3161
  const clientEntry = `
1541
3162
  ${clientImports}
1542
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, setLocales, isLocale } from './runtime.js';
1543
-
1544
- // i18n (innovation #27): the dictionaries baked at build time - the client
1545
- // renders any locale from the bundle, so switching language costs zero
1546
- // requests (the same bet as the inlined route table).
1547
- setLocales(${localesJson}, '${defaultLocale}');
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.
3173
+ setLocales(${clientLocalesJson}, '${defaultLocale}');
3174
+ setLocalePacks(${JSON.stringify(packed)});
3175
+ ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
3176
+ // follow a route that carries no [lang] segment (a non-i18n page)
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';`: ''}
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.
3183
+ export { ensureLocale, loadLocale } from './runtime.js';
3184
+ ${vitalsBlock}
1548
3185
 
1549
3186
  const routes = [
1550
3187
  ${clientRoutes}
1551
3188
  ];
1552
3189
 
1553
- // === Mode B (P0 §1): lazy route chunks ===
3190
+ // === Mode B: lazy route chunks ===
1554
3191
  // Split mode's registry entries arrive without a render function: loadChain
1555
3192
  // loads the route's module graph (the page plus its layouts, one chunk per
1556
3193
  // module, the shared runtime in its own vendor chunk) in parallel and
@@ -1614,17 +3251,17 @@ export function matchRoute(pattern, pathname) {
1614
3251
  // === Link prefetch ===
1615
3252
  // Hover / focus / touch an internal link and the target route renders NOW -
1616
3253
  // $data included - against a throwaway signal map. The click that follows
1617
- // paints from the cached HTML: no await, no request, no spinner. SvelteKit
1618
- // and Qwik prefetch data only; rosetack prefetches the whole render because
3254
+ // paints from the cached HTML: no await, no request, no spinner. Other
3255
+ // frameworks prefetch data only; rosetack prefetches the whole render because
1619
3256
  // the inlined bundle already contains every route.
1620
- // ponytail: the cache holds either a result or the in-flight promise (dedupes
3257
+ // Trade-off: the cache holds either a result or the in-flight promise (dedupes
1621
3258
  // hover storms); one isolated render runs at a time so signal-map swapping
1622
3259
  // stays correct without any merging logic. Entries are single-use: a consumed
1623
3260
  // entry disappears from the cache, which is also how tests observe a hit.
1624
- // P1 (consultant report), three guards for link-heavy pages:
3261
+ // P1, three guards for link-heavy pages:
1625
3262
  // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
1626
3263
  // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
1627
- // ponytail: app-global, not per-route - per-route would carry the mode
3264
+ // Trade-off: app-global, not per-route - per-route would carry the mode
1628
3265
  // in each document's shell.
1629
3266
  // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
1630
3267
  // the budget caps the QUEUE: a hover storm past it drops the excess
@@ -1640,12 +3277,20 @@ const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promis
1640
3277
  let prefetchQueue = Promise.resolve();
1641
3278
  let prefetchPending = 0;
1642
3279
 
1643
- function applyParams(route, pathname) {
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.
3286
+ async function applyParams(route, pathname) {
1644
3287
  const patternParts = route.pattern.split('/');
1645
3288
  const pathParts = pathname.split('/');
1646
3289
  for (let i = 0; i < patternParts.length; i++) {
1647
3290
  if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
1648
3291
  }
3292
+ const langIdx = patternParts.indexOf(':lang');
3293
+ if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
1649
3294
  }
1650
3295
 
1651
3296
  export function prefetch(pathname, source = 'hover') {
@@ -1657,15 +3302,22 @@ export function prefetch(pathname, source = 'hover') {
1657
3302
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
1658
3303
  if (!route) return;
1659
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;
1660
3311
  const p = prefetchQueue.then(async () => {
1661
3312
  try {
3313
+ setPrefetchOverride(qOverride);
1662
3314
  // the isolated render also captures the onMount callbacks the route
1663
3315
  // queued and the onCleanup disposers it registered: the paint that
1664
3316
  // consumes this entry replays the mounts after wiring and adopts the
1665
3317
  // cleanups, so the prefetched route's timers are disposed on the next
1666
3318
  // navigation like any live route's
1667
3319
  const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
1668
- applyParams(route, pathname);
3320
+ await applyParams(route, pathname); // a packed locale's dictionary lands before the render
1669
3321
  const closes = [];
1670
3322
  const render = await getRender(route); // split mode: loads the route's chunk here
1671
3323
  const html = await render(closes, '');
@@ -1685,6 +3337,7 @@ export function prefetch(pathname, source = 'hover') {
1685
3337
  prefetchCache.delete(pathname); // failed: the next hover retries
1686
3338
  return null;
1687
3339
  } finally {
3340
+ setPrefetchOverride(null);
1688
3341
  prefetchPending--;
1689
3342
  }
1690
3343
  });
@@ -1711,7 +3364,7 @@ function bindEvents(container) {
1711
3364
  if (!el || !container.contains(el)) return;
1712
3365
  const fn = el.getAttribute('data-on-' + ev);
1713
3366
  if (fn.startsWith('$action:')) return $action(fn.slice(8), e);
1714
- const h = globalThis.__rosetack_handlers[fn];
3367
+ const h = handlers[fn];
1715
3368
  if (h) h(e);
1716
3369
  });
1717
3370
  }
@@ -1749,6 +3402,13 @@ export async function $action(name, e) {
1749
3402
 
1750
3403
  export { postForm };
1751
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
+
1752
3412
  // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
1753
3413
  // the existing nodes and bind events. initial=false: client-side navigation -
1754
3414
  // re-render the route chain from scratch and wire the fresh DOM.
@@ -1764,7 +3424,7 @@ export async function start(container, pathname, initial) {
1764
3424
  // (before the prefetch check: a cached entry for a bogus locale is
1765
3425
  // discarded, never painted)
1766
3426
  const langIdx = route.pattern.split('/').indexOf(':lang');
1767
- if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {
3427
+ ${langDirBlock}
1768
3428
  await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
1769
3429
  return;
1770
3430
  }
@@ -1788,7 +3448,7 @@ export async function start(container, pathname, initial) {
1788
3448
  resetEffects();
1789
3449
  clearRequestState();
1790
3450
  }
1791
- applyParams(route, pathname);
3451
+ await applyParams(route, pathname);
1792
3452
  const closes = [];
1793
3453
  let html;
1794
3454
  try {
@@ -1808,7 +3468,10 @@ export async function start(container, pathname, initial) {
1808
3468
  }
1809
3469
  }
1810
3470
  // unmatched route: pages/404.rose renders (with its head + interactivity),
1811
- // else the built-in plain 404
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');` : ''}
1812
3475
  await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
1813
3476
  }
1814
3477
 
@@ -1829,7 +3492,7 @@ export async function adopt(container, html, stateJson) {
1829
3492
  if (st) st.textContent = stateJson;
1830
3493
  for (const route of routes) {
1831
3494
  if (matchRoute(route.pattern, location.pathname)) {
1832
- applyParams(route, location.pathname);
3495
+ await applyParams(route, location.pathname);
1833
3496
  const closes = [];
1834
3497
  try {
1835
3498
  const render = await getRender(route); // split mode: loads the route's chunk here
@@ -1848,12 +3511,12 @@ export async function adopt(container, html, stateJson) {
1848
3511
  }
1849
3512
  // === refresh() implementation ===
1850
3513
  // Re-render the current route in place: the client half of router.refresh()
1851
- // (Next.js) / invalidateAll() (SvelteKit). Same machinery as a client-side
3514
+ // (a router refresh) / (a full invalidation). Same machinery as a client-side
1852
3515
  // navigation to the current path - $data re-runs, state re-seeds from the
1853
3516
  // fresh render, wire() patches the marked nodes - but a refresh never lands
1854
3517
  // a prefetch entry: a hover from a minute ago is exactly what it exists to
1855
3518
  // bypass. Zero requests: the render (and its $data) runs in the page.
1856
- // ponytail: state resets like navigation (no per-key retention); add
3519
+ // Trade-off: state resets like navigation (no per-key retention); add
1857
3520
  // retention when an app needs refresh-without-losing-input.
1858
3521
  setRefreshHook(async () => {
1859
3522
  prefetchCache.delete(location.pathname);
@@ -1862,8 +3525,8 @@ setRefreshHook(async () => {
1862
3525
  `;
1863
3526
  await fs.promises.writeFile(path.join(buildDir, 'client-entry.js'), clientEntry);
1864
3527
  if (split) {
1865
- // Mode B (P0 §1): esbuild code splitting. One chunk per route module, the shared
1866
- // runtime in its own vendor chunk …
3528
+ // Mode B: esbuild code splitting. One chunk per route module, the shared runtime in its
3529
+ // own vendor chunk …
1867
3530
  await fs.promises.rm(path.join(outDir, 'chunks'), { recursive: true, force: true });
1868
3531
  await esbuild.build({
1869
3532
  entryPoints: [path.join(buildDir, 'client-entry.js')],
@@ -1876,6 +3539,7 @@ setRefreshHook(async () => {
1876
3539
  entryNames: 'client',
1877
3540
  chunkNames: 'chunks/[name]-[hash]',
1878
3541
  write: true,
3542
+ ...TS_LOADER,
1879
3543
  });
1880
3544
  } else {
1881
3545
  await esbuild.build({
@@ -1886,6 +3550,7 @@ setRefreshHook(async () => {
1886
3550
  platform: 'browser',
1887
3551
  minify: true,
1888
3552
  write: true,
3553
+ ...TS_LOADER,
1889
3554
  });
1890
3555
  }
1891
3556
 
@@ -1902,8 +3567,8 @@ setRefreshHook(async () => {
1902
3567
  );
1903
3568
  }
1904
3569
 
1905
- // Innovation #31: the build's zero-JS lint report - every route, its verdict, and the
1906
- // reason.
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.
1907
3572
  console.log('rosetack zero-JS report:');
1908
3573
  for (const line of buildReport(infos, compiled)) console.log(' ' + line);
1909
3574
  for (const { info, i } of pages) {
@@ -1918,7 +3583,8 @@ setRefreshHook(async () => {
1918
3583
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
1919
3584
  }
1920
3585
 
1921
- async function scanRoseFiles(root: string): Promise<string[]> {
3586
+ /** Every .rose file under <root>/src/pages, recursively (layouts and api included). */
3587
+ export async function scanRoseFiles(root: string): Promise<string[]> {
1922
3588
  const pagesDir = path.join(root, 'src', 'pages');
1923
3589
  if (!fs.existsSync(pagesDir)) return [];
1924
3590
 
@@ -1936,6 +3602,27 @@ async function scanRoseFiles(root: string): Promise<string[]> {
1936
3602
  return scan(pagesDir);
1937
3603
  }
1938
3604
 
3605
+ /** Every .rose file under <root>/src/components, recursively . These
3606
+ * are not routes: they are compiled into the same module index space as the
3607
+ * pages so a page can `import Card from '../components/Card.rose'`. */
3608
+ export async function scanComponentFiles(root: string): Promise<string[]> {
3609
+ const compDir = path.join(root, 'src', 'components');
3610
+ if (!fs.existsSync(compDir)) return [];
3611
+
3612
+ async function scan(dir: string): Promise<string[]> {
3613
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
3614
+ const files: string[] = [];
3615
+ for (const entry of entries) {
3616
+ const full = path.join(dir, entry.name);
3617
+ if (entry.isDirectory()) files.push(...(await scan(full)));
3618
+ else if (entry.name.endsWith('.rose')) files.push(full);
3619
+ }
3620
+ return files;
3621
+ }
3622
+
3623
+ return scan(compDir);
3624
+ }
3625
+
1939
3626
  function isAncestorDir(layoutPath: string, pagePath: string): boolean {
1940
3627
  const layoutDir = path.dirname(layoutPath);
1941
3628
  const pageDir = path.dirname(pagePath);
@@ -1947,15 +3634,18 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
1947
3634
  const relative = path.relative(pagesDir, filePath).replace(/\\/g, '/');
1948
3635
  const withoutExt = relative.replace(/\.rose$/, '');
1949
3636
  const base = path.posix.basename(withoutExt);
1950
- const isLayout = base === '_layout';
1951
- const isNotFound = base === '404';
1952
- const isError = base === '500';
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
+ const isComponent = filePath.replace(/\\/g, '/').includes('/src/components/');
3640
+ const isLayout = !isComponent && base === '_layout';
3641
+ const isNotFound = !isComponent && base === '404';
3642
+ const isError = !isComponent && base === '500';
1953
3643
  // pages/api/*.rose: Web-standard handler routes (JSON in, JSON out), never
1954
3644
  // HTML pages - they dispatch by method and never reach the client bundle.
1955
- const isApi = withoutExt === 'api' || withoutExt.startsWith('api/');
3645
+ const isApi = !isComponent && (withoutExt === 'api' || withoutExt.startsWith('api/'));
1956
3646
  // pages/_middleware.rose: the request interceptor. It runs before every render and is not
1957
3647
  // a route: it matches nothing and never reaches the client bundle.
1958
- const isMiddleware = withoutExt === '_middleware';
3648
+ const isMiddleware = !isComponent && withoutExt === '_middleware';
1959
3649
 
1960
3650
  let parts = withoutExt.split('/').filter((p) => p !== '_layout');
1961
3651
  // a trailing `index` segment names its directory (blog/index -> /blog,
@@ -1982,6 +3672,7 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
1982
3672
  isError,
1983
3673
  isApi,
1984
3674
  isMiddleware,
3675
+ isComponent,
1985
3676
  };
1986
3677
  }
1987
3678