rosetack 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,47 @@ import * as fs from "fs";
3
3
  import * as path from "path";
4
4
  import { pathToFileURL, fileURLToPath } from "url";
5
5
  import * as esbuild from "esbuild";
6
+
7
+ // src/compiler/errors.ts
8
+ var RoseError = class extends Error {
9
+ code;
10
+ file;
11
+ line;
12
+ hint;
13
+ constructor(code, message, opts = {}) {
14
+ super(message);
15
+ this.name = "RoseError";
16
+ this.code = code;
17
+ this.file = opts.file;
18
+ this.line = opts.line;
19
+ this.hint = opts.hint;
20
+ }
21
+ info() {
22
+ const info = { code: this.code };
23
+ if (this.file !== void 0) info.file = this.file;
24
+ if (this.line !== void 0) info.line = this.line;
25
+ info.message = this.message;
26
+ if (this.hint !== void 0) info.hint = this.hint;
27
+ return info;
28
+ }
29
+ };
30
+ function lineOf(src, index) {
31
+ let line = 1;
32
+ const end = Math.min(index, src.length);
33
+ for (let i = 0; i < end; i++) {
34
+ if (src[i] === "\n") line++;
35
+ }
36
+ return line;
37
+ }
38
+ function lineAt(src, match) {
39
+ return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
40
+ }
41
+ function errorInfo(err) {
42
+ if (err instanceof RoseError) return err.info();
43
+ return { code: "E-UNKNOWN", message: err instanceof Error ? err.message : String(err) };
44
+ }
45
+
46
+ // src/compiler/index.ts
6
47
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
7
48
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
8
49
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
@@ -10,12 +51,11 @@ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
10
51
  var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
11
52
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
12
53
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
13
- var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
14
54
  var SLOT_RE = /<slot\s*\/?>/g;
15
55
  var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
16
56
  function encodeSlotCall(attrs) {
17
57
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
18
- if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
58
+ 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} />' });
19
59
  const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
20
60
  return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
21
61
  }
@@ -102,7 +142,116 @@ function callifyStateReads(script, names) {
102
142
  }
103
143
  function callifyTemplateExprs(template, names) {
104
144
  if (names.length === 0) return template;
105
- return template.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${callifyStateReads(expr, names)}}`);
145
+ let out = "";
146
+ let last = 0;
147
+ for (const s of templateExprSpans(template)) {
148
+ out += template.slice(last, s.start) + "{" + callifyStateReads(s.expr, names) + "}";
149
+ last = s.end + 1;
150
+ }
151
+ return out + template.slice(last);
152
+ }
153
+ function templateExprSpans(src) {
154
+ const spans = [];
155
+ let i = 0;
156
+ while (i < src.length) {
157
+ if (src[i] === "{") {
158
+ const end = scanExprEnd(src, i);
159
+ if (end > i + 1) {
160
+ spans.push({ start: i, end, expr: src.slice(i + 1, end) });
161
+ i = end + 1;
162
+ continue;
163
+ }
164
+ }
165
+ i++;
166
+ }
167
+ return spans;
168
+ }
169
+ function scanExprEnd(src, open) {
170
+ let depth = 0;
171
+ let i = open;
172
+ while (i < src.length) {
173
+ const ch = src[i];
174
+ if (ch === "'" || ch === '"') {
175
+ i = skipQuoted(src, i);
176
+ continue;
177
+ }
178
+ if (ch === "`") {
179
+ i = skipTemplate(src, i);
180
+ continue;
181
+ }
182
+ if (ch === "{") depth++;
183
+ else if (ch === "}" && --depth === 0) return i;
184
+ i++;
185
+ }
186
+ return -1;
187
+ }
188
+ function skipQuoted(src, i) {
189
+ const q = src[i];
190
+ let j = i + 1;
191
+ while (j < src.length) {
192
+ if (src[j] === "\\") {
193
+ j += 2;
194
+ continue;
195
+ }
196
+ if (src[j] === q) return j + 1;
197
+ j++;
198
+ }
199
+ return j;
200
+ }
201
+ function skipTemplate(src, i) {
202
+ let j = i + 1;
203
+ while (j < src.length) {
204
+ const ch = src[j];
205
+ if (ch === "\\") {
206
+ j += 2;
207
+ continue;
208
+ }
209
+ if (ch === "`") return j + 1;
210
+ if (ch === "$" && src[j + 1] === "{") {
211
+ const end = scanExprEnd(src, j + 1);
212
+ j = end < 0 ? src.length : end + 1;
213
+ continue;
214
+ }
215
+ j++;
216
+ }
217
+ return j;
218
+ }
219
+ function stripComments(src) {
220
+ let out = "";
221
+ let i = 0;
222
+ while (i < src.length) {
223
+ const q = src[i];
224
+ if (q === '"' || q === "'") {
225
+ const end = skipQuoted(src, i);
226
+ out += src.slice(i, end);
227
+ i = end;
228
+ continue;
229
+ }
230
+ if (q === "`") {
231
+ const end = skipTemplate(src, i);
232
+ out += src.slice(i, end);
233
+ i = end;
234
+ continue;
235
+ }
236
+ if (src.startsWith("//", i)) {
237
+ while (i < src.length && src[i] !== "\n") i++;
238
+ continue;
239
+ }
240
+ if (src.startsWith("/*", i)) {
241
+ i += 2;
242
+ while (i < src.length && !src.startsWith("*/", i)) i++;
243
+ i = Math.min(i + 2, src.length);
244
+ continue;
245
+ }
246
+ if (src.startsWith("<!--", i)) {
247
+ i += 4;
248
+ while (i < src.length && !src.startsWith("-->", i)) i++;
249
+ i = Math.min(i + 3, src.length);
250
+ continue;
251
+ }
252
+ out += src[i++];
253
+ }
254
+ return out;
106
255
  }
107
256
  function scriptOf(source) {
108
257
  return source.match(COMPONENT_RE)?.[1] ?? null;
@@ -121,21 +270,29 @@ async function loadPlugins(root) {
121
270
  }
122
271
  function resolveRoseImports(script, fromFile, registry) {
123
272
  const imports = [];
124
- const resolve2 = (spec) => {
273
+ const resolve2 = (spec, at) => {
125
274
  const abs = path.resolve(path.dirname(fromFile), spec);
126
275
  const hit = registry.get(abs);
127
276
  if (!hit) {
128
- throw new Error(`${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`);
277
+ throw new RoseError(
278
+ "E-IMPORT",
279
+ `${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.`,
280
+ {
281
+ file: fromFile,
282
+ line: lineOf(script, at),
283
+ hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`
284
+ }
285
+ );
129
286
  }
130
287
  return hit;
131
288
  };
132
- let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
133
- const hit = resolve2(spec);
289
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at) => {
290
+ const hit = resolve2(spec, at);
134
291
  imports.push({ name, specifier: spec, index: hit.index });
135
292
  return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
136
293
  });
137
- rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
138
- const hit = resolve2(spec);
294
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at) => {
295
+ const hit = resolve2(spec, at);
139
296
  const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
140
297
  imports.push({ name: alias, specifier: spec, index: hit.index });
141
298
  return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
@@ -145,6 +302,60 @@ function resolveRoseImports(script, fromFile, registry) {
145
302
  function rewriteRoseImports(script, kind) {
146
303
  return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
147
304
  }
305
+ var 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)$)/;
306
+ function nodeOnlyImports(importStmts) {
307
+ const out = [];
308
+ for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
309
+ if (m[1]) continue;
310
+ if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
311
+ }
312
+ return out;
313
+ }
314
+ function wireEventBindings(template, actionNames) {
315
+ const bindings = [];
316
+ let out = "";
317
+ let rest = template;
318
+ for (; ; ) {
319
+ const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
320
+ if (!m) {
321
+ out += rest;
322
+ break;
323
+ }
324
+ out += rest.slice(0, m.index);
325
+ let i = m.index + m[0].length;
326
+ let depth = 1;
327
+ while (i < rest.length) {
328
+ const ch = rest[i];
329
+ if (ch === '"' || ch === "'") {
330
+ i = skipQuoted(rest, i);
331
+ continue;
332
+ }
333
+ if (ch === "`") {
334
+ i = skipTemplate(rest, i);
335
+ continue;
336
+ }
337
+ if (ch === "{") depth++;
338
+ else if (ch === "}") {
339
+ depth--;
340
+ if (depth === 0) break;
341
+ }
342
+ i++;
343
+ }
344
+ const expr = rest.slice(m.index + m[0].length, i).trim();
345
+ if (actionNames.has(expr)) {
346
+ out += `data-on-${m[1]}="$action:${expr}"`;
347
+ } else if (/^\w+$/.test(expr)) {
348
+ out += `data-on-${m[1]}="${expr}"`;
349
+ bindings.push({ event: m[1], fn: expr });
350
+ } else {
351
+ const name = `__h${bindings.length}`;
352
+ out += `data-on-${m[1]}="${name}"`;
353
+ bindings.push({ event: m[1], fn: `${name}: ${expr}` });
354
+ }
355
+ rest = rest.slice(i + 1);
356
+ }
357
+ return { template: out, bindings };
358
+ }
148
359
  function scanSlotDecls(filePath) {
149
360
  let src;
150
361
  try {
@@ -207,7 +418,11 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
207
418
  try {
208
419
  source = await p.transform(source, filePath);
209
420
  } catch (err) {
210
- throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
421
+ throw new RoseError(
422
+ "E-PLUGIN",
423
+ `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
424
+ { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
425
+ );
211
426
  }
212
427
  }
213
428
  if (isApi) {
@@ -225,7 +440,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
225
440
  guardName: null,
226
441
  style: "",
227
442
  hasParams: false,
228
- api: `import { getContext } from './runtime.js';
443
+ api: `import { getContext, $query } from './runtime.js';
229
444
  ${rewriteRoseImports(`${hoisted.imports}
230
445
  ${hoisted.rest}`, "ssr").trim()}`,
231
446
  apiMethods,
@@ -233,41 +448,84 @@ ${hoisted.rest}`, "ssr").trim()}`,
233
448
  usesContext: usesContext2
234
449
  };
235
450
  }
236
- const styleMatch = source.match(STYLE_RE);
451
+ const sourceNoHead = source.replace(HEAD_RE, "");
452
+ const styleMatch = sourceNoHead.match(STYLE_RE);
237
453
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
238
- const sourceNoBlocks = source.replace(STYLE_RE, "");
454
+ const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
239
455
  const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
240
456
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
241
457
  const rawScript = roseResolved.script;
242
458
  const roseImports = roseResolved.imports;
243
459
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
460
+ if (path.basename(filePath) !== "_middleware.rose") {
461
+ for (const spec of nodeOnlyImports(importStmts)) {
462
+ const at = importStmts.indexOf(spec);
463
+ throw new RoseError(
464
+ "E-NODE-ONLY",
465
+ `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
466
+ {
467
+ file: filePath,
468
+ line: at >= 0 ? lineOf(importStmts, at) : void 0,
469
+ 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`
470
+ }
471
+ );
472
+ }
473
+ }
244
474
  const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
245
475
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
246
- throw new Error(
247
- `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`
476
+ throw new RoseError(
477
+ "E-EXPORT",
478
+ `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
479
+ { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
248
480
  );
249
481
  }
250
- const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
482
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
251
483
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
252
484
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
253
485
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
254
486
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
255
487
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
256
488
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
257
- throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
489
+ throw new RoseError(
490
+ "E-EXPORT",
491
+ `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
492
+ { 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'" }
493
+ );
494
+ }
495
+ const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
496
+ const vitals = vitalsMatch ? vitalsMatch[1].trim() === "true" : void 0;
497
+ if (vitalsMatch && !vitals) {
498
+ throw new RoseError(
499
+ "E-EXPORT",
500
+ `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
501
+ { 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" }
502
+ );
258
503
  }
259
504
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
260
505
  const bundle = bundleMatch ? bundleMatch[1] : void 0;
261
506
  if (bundle && !["inline", "split"].includes(bundle)) {
262
- throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
507
+ throw new RoseError(
508
+ "E-EXPORT",
509
+ `${filePath}: export const bundle must be 'inline' or 'split'`,
510
+ { 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" }
511
+ );
263
512
  }
264
513
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
265
514
  const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
515
+ const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
516
+ const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
266
517
  if (csr === false) {
267
518
  const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
268
519
  if (dead) {
269
- throw new Error(
270
- `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`
520
+ const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
521
+ throw new RoseError(
522
+ "E-EXPORT",
523
+ `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
524
+ {
525
+ file: filePath,
526
+ line: lineAt(deadSrc, dead),
527
+ 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'
528
+ }
271
529
  );
272
530
  }
273
531
  }
@@ -278,10 +536,18 @@ ${hoisted.rest}`, "ssr").trim()}`,
278
536
  try {
279
537
  value = new Function(`return ${headersLiteral}`)();
280
538
  } catch {
281
- throw new Error(`${filePath}: export const headers must be an object literal`);
539
+ throw new RoseError(
540
+ "E-EXPORT",
541
+ `${filePath}: export const headers must be an object literal`,
542
+ { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
543
+ );
282
544
  }
283
545
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
284
- throw new Error(`${filePath}: export const headers must be a flat map of string -> string`);
546
+ throw new RoseError(
547
+ "E-EXPORT",
548
+ `${filePath}: export const headers must be a flat map of string -> string`,
549
+ { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
550
+ );
285
551
  }
286
552
  headers = value;
287
553
  }
@@ -292,11 +558,19 @@ ${hoisted.rest}`, "ssr").trim()}`,
292
558
  try {
293
559
  value = new Function(`return ${cspLiteral}`)();
294
560
  } catch {
295
- throw new Error(`${filePath}: export const csp must be an object literal`);
561
+ throw new RoseError(
562
+ "E-EXPORT",
563
+ `${filePath}: export const csp must be an object literal`,
564
+ { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
565
+ );
296
566
  }
297
567
  const nonce = value?.nonce;
298
568
  if (nonce !== void 0 && typeof nonce !== "boolean") {
299
- throw new Error(`${filePath}: csp.nonce must be a boolean`);
569
+ throw new RoseError(
570
+ "E-EXPORT",
571
+ `${filePath}: csp.nonce must be a boolean`,
572
+ { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
573
+ );
300
574
  }
301
575
  cspNonce = nonce === true;
302
576
  }
@@ -305,54 +579,38 @@ ${hoisted.rest}`, "ssr").trim()}`,
305
579
  const actionNames = new Set(actions.map((a) => a.name));
306
580
  const clientReasons = [];
307
581
  if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
308
- if (/<form[\s>]/.test(source)) clientReasons.push("a <form> (its in-place adopt is the enhancement)");
582
+ if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
583
+ clientReasons.push("a form bound to a client dispatch ($action)");
584
+ }
309
585
  const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
310
586
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
311
- if (actionNames.size > 0) {
312
- clientReasons.push(`server action${actionNames.size > 1 ? "s" : ""} (${[...actionNames].join(", ")})`);
313
- }
314
587
  const needsClient = clientReasons.length > 0;
315
588
  const jsWarnings = [];
316
589
  if (!needsClient) {
317
- if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
590
+ const codeOnly = stripComments(source);
591
+ const scriptCodeOnly = stripComments(rawScript);
592
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
318
593
  jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
319
594
  }
320
- if (/javascript:/i.test(source)) {
595
+ if (/javascript:/i.test(codeOnly)) {
321
596
  jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
322
597
  }
323
- if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
598
+ if (/\b(?:eval|new Function)\s*\(/.test(scriptCodeOnly)) {
324
599
  jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
325
600
  }
326
- 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)) {
601
+ if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(scriptCodeOnly)) {
327
602
  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");
328
603
  }
329
604
  }
330
605
  const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
331
- const headMatch = sourceNoBlocks.match(HEAD_RE);
332
- const headContent = headMatch?.[1] ?? "";
333
- const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, "");
334
- const rawTemplate = templateMatch ? templateMatch[1] : sourceNoHead.replace(COMPONENT_RE, "").trim();
606
+ const headContent = source.match(HEAD_RE)?.[1] ?? "";
607
+ const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
335
608
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
336
609
  const decls = extractDecls(script);
337
610
  const stateDecls = decls.filter((d) => d.kind === "state");
338
611
  const setterNames = /* @__PURE__ */ new Map();
339
612
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
340
- const eventBindings = [];
341
- let em;
342
- EVENT_RE.lastIndex = 0;
343
- while (em = EVENT_RE.exec(template)) {
344
- if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
345
- }
346
- let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end]));
347
- cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
348
- const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
349
- const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
350
- return `${setter}(${val})`;
351
- });
352
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
353
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
354
- const ssrTemplate = templateCalled.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}").replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) => actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
355
- const stateDeclsCode = decls.map((d) => {
613
+ const declCode = (d) => {
356
614
  const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
357
615
  if (d.kind === "state") {
358
616
  return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
@@ -362,7 +620,30 @@ ${hoisted.rest}`, "ssr").trim()}`,
362
620
  return `const __had_${d.name} = hasState(${JSON.stringify(key)});
363
621
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
364
622
  if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
365
- }).join("\n");
623
+ };
624
+ const nestedDecls = [];
625
+ let spliced = "";
626
+ let pos = 0;
627
+ decls.forEach((d, i) => {
628
+ const top = braceDepthAt(script, d.start) === 0;
629
+ if (!top) nestedDecls.push(d);
630
+ spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
631
+ pos = d.end;
632
+ });
633
+ spliced += script.slice(pos);
634
+ let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
635
+ const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
636
+ const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
637
+ return `${setter}(${val})`;
638
+ });
639
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
640
+ cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
641
+ const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
642
+ const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
643
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
644
+ const wired = wireEventBindings(templateCalled, actionNames);
645
+ const eventBindings = wired.bindings;
646
+ const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
366
647
  const stateKeys = decls.map((d) => d.name);
367
648
  const comps = new Map(roseImports.map((r) => {
368
649
  const abs = path.resolve(path.dirname(filePath), r.specifier);
@@ -370,7 +651,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
370
651
  return [r.name, { index: hit.index, slots: hit.slots }];
371
652
  }));
372
653
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
373
- const compiledHead = headContent.trim() ? compileTemplate(headContent, "__hd", "__hc", null, 0, false) : "";
654
+ const compiledHead = headContent.trim() ? compileHead(headContent) : "";
374
655
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
375
656
  const ssrExports = actions.length > 0 ? `${exportStmts}
376
657
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
@@ -385,8 +666,8 @@ ${ssrExports}
385
666
  ${ssrGuard}
386
667
 
387
668
  ${cleanScript}
388
- ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
389
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
669
+ ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
670
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
390
671
  return {
391
672
  ssr: rewriteRoseImports(ssr, "ssr"),
392
673
  client: rewriteRoseImports(client, "client"),
@@ -398,7 +679,9 @@ ${cleanScript}
398
679
  usesContext,
399
680
  revalidate,
400
681
  csr,
682
+ buffer,
401
683
  prefetch,
684
+ vitals,
402
685
  bundle,
403
686
  needsClient,
404
687
  clientReasons,
@@ -633,31 +916,134 @@ function extractDecls(script) {
633
916
  }
634
917
  return decls;
635
918
  }
636
- function removeRanges(text, ranges) {
637
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
638
- let out = "";
639
- let pos = 0;
640
- for (const [start, end] of sorted) {
641
- out += text.slice(pos, start);
642
- pos = end;
919
+ function braceDepthAt(src, index) {
920
+ let depth = 0;
921
+ let i = 0;
922
+ while (i < index) {
923
+ const ch = src[i];
924
+ if (ch === "'" || ch === '"' || ch === "`") {
925
+ const quote = ch;
926
+ i++;
927
+ while (i < index) {
928
+ if (src[i] === "\\") {
929
+ i += 2;
930
+ continue;
931
+ }
932
+ if (src[i] === quote) {
933
+ i++;
934
+ break;
935
+ }
936
+ if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
937
+ let d = 1;
938
+ i += 2;
939
+ while (i < index && d > 0) {
940
+ if (src[i] === "{") d++;
941
+ else if (src[i] === "}") d--;
942
+ i++;
943
+ }
944
+ continue;
945
+ }
946
+ i++;
947
+ }
948
+ continue;
949
+ }
950
+ if (ch === "/" && src[i + 1] === "/") {
951
+ const nl = src.indexOf("\n", i);
952
+ i = nl === -1 ? src.length : nl;
953
+ continue;
954
+ }
955
+ if (ch === "/" && src[i + 1] === "*") {
956
+ const close = src.indexOf("*/", i + 2);
957
+ i = close === -1 ? src.length : close + 2;
958
+ continue;
959
+ }
960
+ if (ch === "{") depth++;
961
+ else if (ch === "}") depth--;
962
+ i++;
643
963
  }
644
- out += text.slice(pos);
645
- return out;
964
+ return depth;
646
965
  }
647
966
  function autoCall(expr) {
648
967
  const e = expr.trim();
649
968
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
650
969
  }
970
+ function findBlock(src, kind) {
971
+ const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
972
+ const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
973
+ let open;
974
+ while (open = head.exec(src)) {
975
+ const start = open.index;
976
+ const afterOpen = start + open[0].length;
977
+ let depth = 1;
978
+ let i = afterOpen;
979
+ for (; ; ) {
980
+ head.lastIndex = i;
981
+ closeRe.lastIndex = i;
982
+ const nextOpen = head.exec(src);
983
+ const nextClose = closeRe.exec(src);
984
+ if (!nextClose) break;
985
+ if (nextOpen && nextOpen.index < nextClose.index) {
986
+ depth++;
987
+ i = nextOpen.index + nextOpen[0].length;
988
+ continue;
989
+ }
990
+ i = nextClose.index + nextClose[0].length;
991
+ if (--depth === 0) {
992
+ const content = src.slice(afterOpen, nextClose.index);
993
+ const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
994
+ const arr = [src.slice(start, i), ...groups];
995
+ arr.index = start;
996
+ return arr;
997
+ }
998
+ }
999
+ head.lastIndex = afterOpen;
1000
+ }
1001
+ return null;
1002
+ }
1003
+ function compileHead(head) {
1004
+ const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
1005
+ let out = "";
1006
+ let buf = "";
1007
+ let seg = 0;
1008
+ let i = 0;
1009
+ const flush = () => {
1010
+ if (buf.trim()) out += compileTemplate(buf, "__hd", "__hc", null, seg++, false);
1011
+ buf = "";
1012
+ };
1013
+ while (i < head.length) {
1014
+ if (head.startsWith("<!--", i)) {
1015
+ const end = head.indexOf("-->", i + 4);
1016
+ i = end < 0 ? head.length : end + 3;
1017
+ continue;
1018
+ }
1019
+ RAW_OPEN.lastIndex = i;
1020
+ const open = RAW_OPEN.exec(head);
1021
+ if (open) {
1022
+ const tag = open[1].toLowerCase();
1023
+ const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
1024
+ const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
1025
+ const end = gt < 0 ? head.length : gt + 1;
1026
+ flush();
1027
+ out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
1028
+ i = end;
1029
+ continue;
1030
+ }
1031
+ buf += head[i++];
1032
+ }
1033
+ flush();
1034
+ return out;
1035
+ }
651
1036
  function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
652
1037
  let result = "";
653
1038
  let remaining = template;
654
1039
  let blockId = 0;
655
1040
  const nextId = () => `${depth}_${blockId++}`;
656
1041
  while (remaining.length > 0) {
657
- const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/);
658
- const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/);
659
- const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/);
660
- const exprMatch = remaining.match(/\{([^{}]+)\}/);
1042
+ const ifMatch = findBlock(remaining, "if");
1043
+ const eachMatch = findBlock(remaining, "each");
1044
+ const boundaryMatch = findBlock(remaining, "boundary");
1045
+ const firstExpr = templateExprSpans(remaining)[0];
1046
+ const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
661
1047
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
662
1048
  const candidates = [];
663
1049
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
@@ -695,7 +1081,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
695
1081
  const call = autoCall(items);
696
1082
  const id = nextId();
697
1083
  const itemRe = new RegExp(`\\b${item}\\b`, "g");
698
- const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(itemRe, "__s")}}`);
1084
+ let scoped = "";
1085
+ let lastSpan = 0;
1086
+ for (const s of templateExprSpans(content.trim())) {
1087
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
1088
+ lastSpan = s.end + 1;
1089
+ }
1090
+ scoped += content.trim().slice(lastSpan);
699
1091
  const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
700
1092
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
701
1093
  `;
@@ -735,7 +1127,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
735
1127
  rest = remaining.substring(tag.end);
736
1128
  } else {
737
1129
  const closeIdx = findClose(remaining, tag.end, tag.name);
738
- if (closeIdx < 0) throw new Error(`unclosed <${tag.name}> - every component tag needs its matching close tag`);
1130
+ 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)` });
739
1131
  childrenSrc = remaining.substring(tag.end, closeIdx);
740
1132
  rest = remaining.substring(closeIdx + tag.name.length + 3);
741
1133
  }
@@ -749,7 +1141,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
749
1141
  const decl = entry.slots.find((s) => s.name === nm);
750
1142
  let content = src;
751
1143
  for (const p of decl?.props ?? []) {
752
- content = content.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(new RegExp(`\\b${p}\\b`, "g"), `__s.${p}`)}}`);
1144
+ const pRe = new RegExp(`\\b${p}\\b`, "g");
1145
+ let out = "";
1146
+ let lastSpan = 0;
1147
+ for (const s of templateExprSpans(content)) {
1148
+ out += content.slice(lastSpan, s.start) + "{" + s.expr.replace(pRe, `__s.${p}`) + "}";
1149
+ lastSpan = s.end + 1;
1150
+ }
1151
+ content = out + content.slice(lastSpan);
753
1152
  }
754
1153
  return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
755
1154
  });
@@ -780,6 +1179,21 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
780
1179
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
781
1180
  continue;
782
1181
  }
1182
+ const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
1183
+ if (rawMatch) {
1184
+ if (before) result += emitChunk(before, acc, closes, scope);
1185
+ const expr2 = rawMatch[1].trim();
1186
+ if (!markers) {
1187
+ result += `${acc} += String(${expr2} ?? '');
1188
+ `;
1189
+ } else {
1190
+ const fn = scope ? `(${scope}) => (${expr2})` : `() => (${expr2})`;
1191
+ result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ""});
1192
+ `;
1193
+ }
1194
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1195
+ continue;
1196
+ }
783
1197
  const attrMatch = before.match(/([\w-]+)=\s*$/);
784
1198
  if (attrMatch) {
785
1199
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -891,7 +1305,7 @@ function rejectNestedSlot(src, outer) {
891
1305
  if (end < 0) return;
892
1306
  const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
893
1307
  if (hit && nm[1] !== "/") {
894
- throw new Error(`slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`);
1308
+ 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" });
895
1309
  }
896
1310
  i = end;
897
1311
  }
@@ -945,7 +1359,7 @@ function splitSlots(src) {
945
1359
  if (!selfClosing && !isVoid) elemDepth++;
946
1360
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
947
1361
  if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
948
- throw new Error(`slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`);
1362
+ 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' });
949
1363
  }
950
1364
  if (slotName) {
951
1365
  const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
@@ -953,7 +1367,7 @@ function splitSlots(src) {
953
1367
  named.set(slotName, (named.get(slotName) ?? "") + stripped);
954
1368
  } else {
955
1369
  const closeIdx = findClose(src, end, nm[2]);
956
- if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
1370
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
957
1371
  const tail = `</${nm[2]}>`;
958
1372
  const inner = src.slice(end, closeIdx);
959
1373
  rejectNestedSlot(inner, slotName);
@@ -1029,7 +1443,7 @@ function compileSlot(acc) {
1029
1443
  return `${acc} += String(children);
1030
1444
  `;
1031
1445
  }
1032
- var RUNTIME_IMPORTS = `import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark } from './runtime.js';`;
1446
+ var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark } from './runtime.js';`;
1033
1447
  function propsCode(props) {
1034
1448
  if (props.length === 0) return "";
1035
1449
  return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
@@ -1051,10 +1465,12 @@ const __slotBlock = (closes, sl, name, pairs) => {
1051
1465
  });
1052
1466
  return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1053
1467
  };`;
1054
- function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "") {
1468
+ function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1055
1469
  const headCode = headFn ? `
1056
1470
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
1057
1471
  __html += headMark(closes, __head);` : "";
1472
+ const actionState = hasActions ? `
1473
+ const $setState = (key, value) => setState(key, value);` : "";
1058
1474
  return `
1059
1475
  ${RUNTIME_IMPORTS}
1060
1476
 
@@ -1062,6 +1478,7 @@ ${imports}
1062
1478
 
1063
1479
  ${exports}
1064
1480
  ${guard}
1481
+ ${actionState}
1065
1482
 
1066
1483
  ${namedSlots ? SLOT_HELPER : ""}
1067
1484
 
@@ -1069,19 +1486,20 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1069
1486
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1070
1487
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1071
1488
  ${propsCode(props)}
1489
+ ${script}
1072
1490
  ${stateDeclsCode}
1491
+ ${dataDeclsCode}
1073
1492
  // The incremental patches of the action that produced THIS response,
1074
1493
  // applied to the state the declarations above just established (a no-op on
1075
1494
  // every path that is not a server action's re-render - see the runtime).
1076
1495
  ${isComponent ? "" : "applyStateDeltas();"}
1077
- ${script}
1078
1496
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1079
1497
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1080
1498
  return __html;
1081
1499
  }
1082
1500
  `;
1083
1501
  }
1084
- function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
1502
+ function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
1085
1503
  const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1086
1504
  const headCode = headFn ? `
1087
1505
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -1099,8 +1517,9 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
1099
1517
  ${props.length > 0 ? "const __p = __props || {};" : ""}
1100
1518
  ${namedSlots ? "const __sl = __slots || {};" : ""}
1101
1519
  ${propsCode(props)}
1102
- ${stateDeclsCode}
1103
1520
  ${script}
1521
+ ${stateDeclsCode}
1522
+ ${dataDeclsCode}
1104
1523
  ${handlerRegistry}
1105
1524
  const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1106
1525
  let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
@@ -1132,7 +1551,11 @@ async function buildProject(root, outDir) {
1132
1551
  const compFiles = await scanComponentFiles(root);
1133
1552
  const files = [...pageFiles, ...compFiles];
1134
1553
  if (pageFiles.length === 0) {
1135
- 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>`);
1554
+ throw new RoseError(
1555
+ "E-ROUTE",
1556
+ `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1557
+ { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1558
+ );
1136
1559
  }
1137
1560
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1138
1561
  const config = await loadConfig(root);
@@ -1236,7 +1659,7 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1236
1659
  `);
1237
1660
  }
1238
1661
  const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
1239
- if (!runtimeEntry) throw new Error("rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler");
1662
+ 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" });
1240
1663
  await esbuild.build({
1241
1664
  entryPoints: [runtimeEntry],
1242
1665
  bundle: true,
@@ -1292,25 +1715,30 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1292
1715
  const serverRoutes = pages.map(({ info, i }) => {
1293
1716
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
1294
1717
  if (compiled[i].csr === false && compiled[i].needsClient) {
1295
- throw new Error(
1296
- `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`
1718
+ throw new RoseError(
1719
+ "E-EXPORT",
1720
+ `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`,
1721
+ { file: info.filePath, hint: "remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above" }
1297
1722
  );
1298
1723
  }
1299
1724
  if (compiled[i].csr === false) {
1300
1725
  const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1301
1726
  if (needy !== void 0) {
1302
- throw new Error(
1303
- `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`
1727
+ throw new RoseError(
1728
+ "E-EXPORT",
1729
+ `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`,
1730
+ { file: info.filePath, hint: "a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only" }
1304
1731
  );
1305
1732
  }
1306
1733
  }
1307
1734
  const csrFlag = routeNoJs(i) ? ", csr: false" : "";
1735
+ const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
1308
1736
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1309
- return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag} }`;
1737
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
1310
1738
  }).join(",\n ");
1311
1739
  const serverEntry = `
1312
1740
  ${serverImports}
1313
- import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1741
+ import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1314
1742
  ${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
1315
1743
  // module to import - the runners below stay no-ops and the servers call them
1316
1744
  // unconditionally (one code path, no flags to keep in sync).
@@ -1356,6 +1784,16 @@ export async function runResponseHooks(ctx, res) {
1356
1784
  export const hasRequestHooks = __hasRequestHooks;
1357
1785
  export const hasResponseHooks = __hasResponseHooks;
1358
1786
 
1787
+ // P0-1: the query of the request being rendered, for $query(). The servers
1788
+ // call this before every render (stream, buffered, POST, api) with the parsed
1789
+ // query string; routing itself matches the pathname, which is what fixed the
1790
+ // query-404. A render with no query (the build's prerender, the ISR
1791
+ // background pass) passes {} explicitly - the bag is per request, so a stale
1792
+ // one must never leak into the next.
1793
+ export function setQuery(query) {
1794
+ setRequestQuery(query || {});
1795
+ }
1796
+
1359
1797
  // i18n: the dictionaries baked at build time from
1360
1798
  // src/locales/*.json. A route segment named [lang] is the locale: the value
1361
1799
  // must name one of these dictionaries, and $t resolves keys against it.
@@ -1390,13 +1828,15 @@ export const routeParams = {
1390
1828
  };
1391
1829
 
1392
1830
  // Routes whose component reads the request context (getContext()), mutates a
1393
- // shared store ($store), or opted into nonce-based CSP: the bag is
1394
- // per-request, the store is per-process, and a nonce is per-response, so
1395
- // these are dynamic - the build never bakes them and the servers never
1396
- // answer them from a prerendered file. Public routes keep the static fast
1397
- // path (file cache, ETag/304, streaming) untouched.
1831
+ // shared store ($store()), reads the query ($query(), P0-1), opted into
1832
+ // nonce-based CSP or into the buffered path (buffer = true, P0-2):
1833
+ // the bag is per-request, the store is per-process, a nonce is per-response,
1834
+ // and a buffered route's hooks must run per request - so these are dynamic.
1835
+ // The build never bakes them and the servers never answer them from a
1836
+ // prerendered file. Public routes keep the static fast path (file cache,
1837
+ // ETag/304, streaming) untouched.
1398
1838
  export const dynamicRoutes = [
1399
- ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1839
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1400
1840
  ];
1401
1841
 
1402
1842
  // Which api routes opt into build-time baking (export const prerender = true):
@@ -1450,6 +1890,16 @@ export function isNoJs(pathname) {
1450
1890
  return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1451
1891
  }
1452
1892
 
1893
+ // P0-2 (bug report): routes that exported "buffer = true". The servers ask
1894
+ // this BEFORE choosing a path: a streamed response commits its status and
1895
+ // headers before the body exists, so its onResponse hooks cannot see the
1896
+ // document and a render that throws mid-flight still answers 200. A buffered
1897
+ // route keeps every capability and gives up the early flush - the trade is
1898
+ // the route's to make, per route, not the framework's.
1899
+ export function isBuffered(pathname) {
1900
+ return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
1901
+ }
1902
+
1453
1903
  // Per-route response headers: a route exporting a headers
1454
1904
  // map carries them into every response the servers write for it, merged
1455
1905
  // OVER the framework defaults (the strict CSP) - so an app can tighten or
@@ -1804,6 +2254,12 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1804
2254
  const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
1805
2255
  const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
1806
2256
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
2257
+ const vitalsOn = compiled.some((c) => c.vitals === true);
2258
+ const vitalsBlock = vitalsOn ? `
2259
+ // the app asked for web-vitals - measure once, at boot, and let the
2260
+ // app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
2261
+ reportVitals;
2262
+ ` : "";
1807
2263
  const hasLang = infos.some((i) => i.pattern.includes(":lang"));
1808
2264
  const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
1809
2265
  // client-side navigation cannot leave stale (screen readers and CSS
@@ -1820,7 +2276,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1820
2276
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
1821
2277
  const clientEntry = `
1822
2278
  ${clientImports}
1823
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
2279
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
1824
2280
 
1825
2281
  // i18n: the dictionaries baked at build time - the client
1826
2282
  // renders any PRELOADED locale from the bundle, so switching language costs
@@ -1835,11 +2291,16 @@ setLocalePacks(${JSON.stringify(packed)});
1835
2291
  ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
1836
2292
  // follow a route that carries no [lang] segment (a non-i18n page)
1837
2293
  const __defLocale = '${defaultLocale}';` : ""}
2294
+ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
2295
+ // reportVitals alive through minification and tree-shaking; the call is one
2296
+ // statement at boot, before the first render.
2297
+ import { reportVitals } from './runtime.js';` : ""}
1838
2298
  // The two pack doors, re-exported for an app that wants to warm a language
1839
2299
  // before its visitor asks for it (ensureLocale) or to feed a dictionary it
1840
2300
  // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
1841
2301
  // is what applyParams calls - so the re-export costs the statement alone.
1842
2302
  export { ensureLocale, loadLocale } from './runtime.js';
2303
+ ${vitalsBlock}
1843
2304
 
1844
2305
  const routes = [
1845
2306
  ${clientRoutes}
@@ -1960,8 +2421,15 @@ export function prefetch(pathname, source = 'hover') {
1960
2421
  const route = routes.find((r) => matchRoute(r.pattern, pathname));
1961
2422
  if (!route) return;
1962
2423
  if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
2424
+ // P0-1: the link may carry a query (/search?q=cats). $query() reads the
2425
+ // browser's own URL, which is the page being LEFT - so the prefetched
2426
+ // render would see the wrong one. Override it for the duration and clear
2427
+ // it after; the queue below serializes renders, so one slot is enough.
2428
+ const qi = pathname.indexOf('?');
2429
+ const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
1963
2430
  const p = prefetchQueue.then(async () => {
1964
2431
  try {
2432
+ setPrefetchOverride(qOverride);
1965
2433
  // the isolated render also captures the onMount callbacks the route
1966
2434
  // queued and the onCleanup disposers it registered: the paint that
1967
2435
  // consumes this entry replays the mounts after wiring and adopts the
@@ -1988,6 +2456,7 @@ export function prefetch(pathname, source = 'hover') {
1988
2456
  prefetchCache.delete(pathname); // failed: the next hover retries
1989
2457
  return null;
1990
2458
  } finally {
2459
+ setPrefetchOverride(null);
1991
2460
  prefetchPending--;
1992
2461
  }
1993
2462
  });
@@ -2052,6 +2521,13 @@ export async function $action(name, e) {
2052
2521
 
2053
2522
  export { postForm };
2054
2523
 
2524
+ // The live signal graph as JSON - the same serializeState the zero-hydration
2525
+ // resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
2526
+ // can hand it to the dev server's reload bridge and to a devtools extension.
2527
+ // A local re-export on purpose: it keeps the binding alive through minification
2528
+ // for the bootstrap text appended after the bundle.
2529
+ export { serializeState };
2530
+
2055
2531
  // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2056
2532
  // the existing nodes and bind events. initial=false: client-side navigation -
2057
2533
  // re-render the route chain from scratch and wire the fresh DOM.
@@ -2290,13 +2766,18 @@ function capitalize(s) {
2290
2766
  return s.charAt(0).toUpperCase() + s.slice(1);
2291
2767
  }
2292
2768
  export {
2769
+ RoseError,
2293
2770
  buildProject,
2294
2771
  buildReport,
2295
2772
  compileComponent,
2773
+ errorInfo,
2296
2774
  extractExports,
2775
+ lineAt,
2776
+ lineOf,
2297
2777
  loadConfig,
2298
2778
  loadPlugins,
2299
2779
  scanComponentFiles,
2300
2780
  scanRoseFiles,
2301
- scriptOf
2781
+ scriptOf,
2782
+ templateExprSpans
2302
2783
  };