rosetack 0.1.3 → 0.1.5

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.
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli/index.ts
4
- import * as fs3 from "fs";
5
- import * as path3 from "path";
4
+ import * as fs5 from "fs";
5
+ import * as path4 from "path";
6
6
  import * as zlib from "zlib";
7
+ import { createHash as createHash2 } from "crypto";
7
8
  import { createRequire } from "module";
8
- import { pathToFileURL as pathToFileURL2, fileURLToPath as fileURLToPath2 } from "url";
9
+ import { pathToFileURL as pathToFileURL3, fileURLToPath as fileURLToPath2 } from "url";
9
10
 
10
11
  // src/compiler/index.ts
11
- import * as fs from "fs";
12
- import * as path from "path";
12
+ import * as fs3 from "fs";
13
+ import * as path2 from "path";
14
+ import * as os from "os";
13
15
  import { pathToFileURL, fileURLToPath } from "url";
14
16
  import * as esbuild from "esbuild";
15
17
 
@@ -52,16 +54,209 @@ function errorInfo(err) {
52
54
  return { code: "E-UNKNOWN", message: err instanceof Error ? err.message : String(err) };
53
55
  }
54
56
 
57
+ // src/cli/image-size.ts
58
+ import fs from "node:fs";
59
+ function readImageSize(filePath2) {
60
+ try {
61
+ const fd = fs.openSync(filePath2, "r");
62
+ const buf = Buffer.alloc(64);
63
+ const read = fs.readSync(fd, buf, 0, 64, 0);
64
+ fs.closeSync(fd);
65
+ if (read < 24) return null;
66
+ if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
67
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
68
+ }
69
+ if (buf.slice(0, 3).toString("latin1") === "GIF") {
70
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
71
+ }
72
+ if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP") {
73
+ return parseWebP(buf);
74
+ }
75
+ if (buf[0] === 255 && buf[1] === 216) {
76
+ return parseJpeg(filePath2);
77
+ }
78
+ return null;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ function parseWebP(buf) {
84
+ const format = buf.slice(12, 16).toString("latin1");
85
+ if (format === "VP8 ") {
86
+ return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
87
+ }
88
+ if (format === "VP8L") {
89
+ const b = buf.readUInt32LE(21);
90
+ return { width: (b & 16383) + 1, height: (b >> 14 & 16383) + 1 };
91
+ }
92
+ if (format === "VP8X") {
93
+ const w = buf.readUIntLE(24, 3) + 1;
94
+ const h = buf.readUIntLE(27, 3) + 1;
95
+ return { width: w, height: h };
96
+ }
97
+ return null;
98
+ }
99
+ function parseJpeg(filePath2) {
100
+ const fd = fs.openSync(filePath2, "r");
101
+ try {
102
+ const buf = Buffer.alloc(4);
103
+ let pos = 2;
104
+ for (let guard = 0; guard < 64; guard++) {
105
+ if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
106
+ if (buf[0] !== 255) {
107
+ pos += 1;
108
+ continue;
109
+ }
110
+ const marker = buf[1];
111
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
112
+ pos += 2;
113
+ continue;
114
+ }
115
+ const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
116
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
117
+ const seg = Buffer.alloc(8);
118
+ fs.readSync(fd, seg, 0, 8, pos + 4);
119
+ return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
120
+ }
121
+ pos += 2 + len;
122
+ }
123
+ return null;
124
+ } finally {
125
+ fs.closeSync(fd);
126
+ }
127
+ }
128
+
129
+ // src/cli/content.ts
130
+ import fs2 from "node:fs";
131
+ import path from "node:path";
132
+ function parseFrontmatter(raw) {
133
+ if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
134
+ const end = raw.indexOf("\n---", 3);
135
+ if (end < 0) return { frontmatter: {}, body: raw };
136
+ const head = raw.slice(4, end);
137
+ const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
138
+ const frontmatter = {};
139
+ for (const line of head.split("\n")) {
140
+ const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
141
+ if (!m) continue;
142
+ const [, k, v] = m;
143
+ const arr = /^\[(.+)\]$/.exec(v.trim());
144
+ frontmatter[k] = arr ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")) : v.trim().replace(/^["']|["']$/g, "");
145
+ }
146
+ return { frontmatter, body };
147
+ }
148
+ function interpolate(md, vars) {
149
+ return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
150
+ const v = k.split(".").reduce((o, p) => o == null ? o : o[p], vars);
151
+ return v === void 0 || v === null ? "" : String(v);
152
+ });
153
+ }
154
+ function renderMarkdown(md, vars) {
155
+ if (vars) md = interpolate(md, vars);
156
+ const blocks = [];
157
+ let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
158
+ blocks.push(
159
+ `<pre data-lang="${lang}"><code>${code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</code></pre>`
160
+ );
161
+ return `\0CODE${blocks.length - 1}\0`;
162
+ });
163
+ const inline = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
164
+ /\[([^\]]+)\]\(([^)]+)\)/g,
165
+ '<a href="$2" rel="noopener">$1</a>'
166
+ );
167
+ const out = [];
168
+ let listOpen = null;
169
+ const closeList = () => {
170
+ if (listOpen) {
171
+ out.push(`</${listOpen}>`);
172
+ listOpen = null;
173
+ }
174
+ };
175
+ for (const line of src.split("\n")) {
176
+ const h = /^(#{1,4})\s+(.*)$/.exec(line);
177
+ const li = /^\s*[-*]\s+(.*)$/.exec(line);
178
+ const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
179
+ if (h) {
180
+ closeList();
181
+ out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
182
+ } else if (li) {
183
+ if (listOpen !== "ul") {
184
+ closeList();
185
+ out.push("<ul>");
186
+ listOpen = "ul";
187
+ }
188
+ out.push(`<li>${inline(li[1])}</li>`);
189
+ } else if (oli) {
190
+ if (listOpen !== "ol") {
191
+ closeList();
192
+ out.push("<ol>");
193
+ listOpen = "ol";
194
+ }
195
+ out.push(`<li>${inline(oli[1])}</li>`);
196
+ } else if (line.trim() === "") {
197
+ closeList();
198
+ } else if (line.startsWith("\0CODE")) {
199
+ closeList();
200
+ out.push(line);
201
+ } else {
202
+ closeList();
203
+ out.push(`<p>${inline(line)}</p>`);
204
+ }
205
+ }
206
+ closeList();
207
+ return out.join("\n").replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
208
+ }
209
+ function scanContentDir(contentDir) {
210
+ const collections = {};
211
+ if (!fs2.existsSync(contentDir)) return collections;
212
+ for (const coll of fs2.readdirSync(contentDir, { withFileTypes: true })) {
213
+ if (!coll.isDirectory()) continue;
214
+ const entries = [];
215
+ const dir = path.join(contentDir, coll.name);
216
+ for (const f of fs2.readdirSync(dir)) {
217
+ if (!f.endsWith(".md")) continue;
218
+ const raw = fs2.readFileSync(path.join(dir, f), "utf-8");
219
+ const { frontmatter, body } = parseFrontmatter(raw);
220
+ if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
221
+ const slug = f.replace(/\.md$/, "");
222
+ const html = renderMarkdown(body);
223
+ const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
224
+ const headings = [];
225
+ const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl, txt) => {
226
+ const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
227
+ headings.push({ level: Number(lvl), text: txt, id });
228
+ return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
229
+ });
230
+ entries.push({
231
+ slug,
232
+ frontmatter,
233
+ body,
234
+ html: tocHtml,
235
+ readingTime: Math.max(1, Math.round(words / 200)),
236
+ wordCount: words,
237
+ toc: headings,
238
+ excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160)
239
+ });
240
+ }
241
+ entries.sort(
242
+ (a, b) => String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? ""))
243
+ );
244
+ collections[coll.name] = entries;
245
+ }
246
+ return collections;
247
+ }
248
+ globalThis.__rosetackContentMk = renderMarkdown;
249
+
55
250
  // src/compiler/index.ts
56
251
  var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
57
252
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
58
253
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
59
254
  var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
60
- var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
255
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist|derived)\b/g;
61
256
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
62
257
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
63
- var SLOT_RE = /<slot\s*\/?>/g;
64
- var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
258
+ var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
259
+ var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
65
260
  function encodeSlotCall(attrs) {
66
261
  const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
67
262
  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} />' });
@@ -456,8 +651,8 @@ function scriptOf(source) {
456
651
  return source.match(COMPONENT_RE)?.[1] ?? null;
457
652
  }
458
653
  async function loadConfig(root) {
459
- const file = path.join(root, "rosetack.config.js");
460
- if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
654
+ const file = path2.join(root, "rosetack.config.js");
655
+ if (!fs3.existsSync(file)) return { plugins: [], i18n: {} };
461
656
  const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
462
657
  return {
463
658
  plugins: mod.default ?? [],
@@ -470,12 +665,12 @@ async function loadPlugins(root) {
470
665
  function resolveRoseImports(script, fromFile, registry) {
471
666
  const imports = [];
472
667
  const resolve3 = (spec, at) => {
473
- const abs = path.resolve(path.dirname(fromFile), spec);
668
+ const abs = path2.resolve(path2.dirname(fromFile), spec);
474
669
  const hit = registry.get(abs);
475
670
  if (!hit) {
476
671
  throw new RoseError(
477
672
  "E-IMPORT",
478
- `${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.`,
673
+ `${path2.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.`,
479
674
  {
480
675
  file: fromFile,
481
676
  line: lineOf(script, at),
@@ -510,16 +705,45 @@ function nodeOnlyImports(importStmts) {
510
705
  }
511
706
  return out;
512
707
  }
513
- function wireEventBindings(template, actionNames) {
708
+ function wireEventBindings(template, actionNames, filePath2 = "<template>") {
514
709
  const bindings = [];
515
710
  let out = "";
516
711
  let rest = template;
712
+ const TARGET_MODS = { window: "w", document: "d" };
713
+ const MOD_PRE = {
714
+ preventDefault: () => "e.preventDefault()",
715
+ stopPropagation: () => "e.stopPropagation()",
716
+ self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`
717
+ };
718
+ const MOD_POST = {
719
+ once: (p) => `const __o = e.target && e.target.closest ? e.target.closest('[data-${p}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${p}-' + e.type);`
720
+ };
721
+ const KNOWN_MODS = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
517
722
  for (; ; ) {
518
- const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
723
+ const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
519
724
  if (!m) {
520
725
  out += rest;
521
726
  break;
522
727
  }
728
+ const mods = m[2] ? m[2].slice(1).split("|") : [];
729
+ const targets = mods.filter((mod) => TARGET_MODS[mod]);
730
+ if (targets.length > 1) {
731
+ throw new RoseError(
732
+ "E-TEMPLATE",
733
+ `${filePath2}: on:${m[1]} carries both |${targets.join(" and |")}`,
734
+ { hint: "a handler binds to one target - the element (default), |window or |document" }
735
+ );
736
+ }
737
+ const prefix = targets.length ? "on" + TARGET_MODS[targets[0]] : "on";
738
+ for (const mod of mods) {
739
+ if (!KNOWN_MODS.includes(mod)) {
740
+ throw new RoseError(
741
+ "E-TEMPLATE",
742
+ `${filePath2}: unknown event modifier |${mod}`,
743
+ { hint: `the supported modifiers are ${KNOWN_MODS.map((k) => "|" + k).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` }
744
+ );
745
+ }
746
+ }
523
747
  out += rest.slice(0, m.index);
524
748
  let i = m.index + m[0].length;
525
749
  let depth = 1;
@@ -541,7 +765,24 @@ function wireEventBindings(template, actionNames) {
541
765
  i++;
542
766
  }
543
767
  const expr = rest.slice(m.index + m[0].length, i).trim();
544
- if (actionNames.has(expr)) {
768
+ const wrap = (body) => {
769
+ if (!mods.length) return body;
770
+ const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
771
+ const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
772
+ return `(e) => {${pre.length ? " " + pre.join("; ") + ";" : ""} (${body})(e);${post.length ? " " + post.join("; ") + ";" : ""} }`;
773
+ };
774
+ if (mods.length && actionNames.has(expr)) {
775
+ throw new RoseError(
776
+ "E-TEMPLATE",
777
+ `${filePath2}: event modifiers are not supported on the server action ${expr}`,
778
+ { hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
779
+ );
780
+ }
781
+ if (mods.length) {
782
+ const name = `__h${bindings.length}`;
783
+ out += `data-${prefix}-${m[1]}="${name}"`;
784
+ bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
785
+ } else if (actionNames.has(expr)) {
545
786
  out += `data-on-${m[1]}="$action:${expr}"`;
546
787
  } else if (/^\w+$/.test(expr)) {
547
788
  out += `data-on-${m[1]}="${expr}"`;
@@ -555,10 +796,10 @@ function wireEventBindings(template, actionNames) {
555
796
  }
556
797
  return { template: out, bindings };
557
798
  }
558
- function scanSlotDecls(filePath) {
799
+ function scanSlotDecls(filePath2) {
559
800
  let src;
560
801
  try {
561
- src = fs.readFileSync(filePath, "utf-8");
802
+ src = fs3.readFileSync(filePath2, "utf-8");
562
803
  } catch {
563
804
  return [];
564
805
  }
@@ -611,17 +852,104 @@ function hoistImports(script) {
611
852
  if (buf) imports.push(buf.join("\n"));
612
853
  return { imports: imports.join("\n"), rest: rest.join("\n") };
613
854
  }
614
- async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
615
- let source = await fs.promises.readFile(filePath, "utf-8");
855
+ var __compileMemo = /* @__PURE__ */ new Map();
856
+ function compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry) {
857
+ let st;
858
+ try {
859
+ st = fs3.statSync(filePath2);
860
+ } catch {
861
+ return null;
862
+ }
863
+ const reg = [];
864
+ for (const [p, e] of registry) reg.push(`${p}#${e.index}:${e.scopeKey}:${e.slots.join("|")}`);
865
+ return [filePath2, String(st.mtimeMs), String(st.size), scopeKey, isApi ? "1" : "0", reg.join(";")].join("\0");
866
+ }
867
+ var __compilerStamp = (() => {
868
+ try {
869
+ return String(fs3.statSync(fileURLToPath(import.meta.url)).mtimeMs);
870
+ } catch {
871
+ return "noid";
872
+ }
873
+ })();
874
+ var __diskCacheDir = (() => {
875
+ try {
876
+ const dir = path2.join(os.tmpdir(), "rosetack-compile-cache");
877
+ fs3.mkdirSync(dir, { recursive: true });
878
+ return dir;
879
+ } catch {
880
+ return null;
881
+ }
882
+ })();
883
+ var __diskWrites = 0;
884
+ function __fnv1a(str) {
885
+ let h = 2166136261;
886
+ for (let i = 0; i < str.length; i++) {
887
+ h ^= str.charCodeAt(i);
888
+ h = Math.imul(h, 16777619);
889
+ }
890
+ return (h >>> 0).toString(16).padStart(8, "0");
891
+ }
892
+ function __diskFile(key) {
893
+ return path2.join(__diskCacheDir, __fnv1a(key + "|" + __compilerStamp) + ".json");
894
+ }
895
+ function __diskGet(key) {
896
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return null;
897
+ try {
898
+ const obj = JSON.parse(fs3.readFileSync(__diskFile(key), "utf-8"));
899
+ if (obj && typeof obj === "object" && typeof obj.ssr === "string") return obj;
900
+ } catch {
901
+ }
902
+ return null;
903
+ }
904
+ function __diskSet(key, result) {
905
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return;
906
+ try {
907
+ fs3.writeFileSync(__diskFile(key), JSON.stringify(result));
908
+ if ((__diskWrites++ & 511) === 0) {
909
+ try {
910
+ const entries = fs3.readdirSync(__diskCacheDir);
911
+ if (entries.length > 5e3) {
912
+ for (const e of entries) {
913
+ try {
914
+ fs3.unlinkSync(path2.join(__diskCacheDir, e));
915
+ } catch {
916
+ }
917
+ }
918
+ }
919
+ } catch {
920
+ }
921
+ }
922
+ } catch {
923
+ }
924
+ }
925
+ async function compileComponentMemo(filePath2, publicDir, scopeKey, isApi, plugins, registry) {
926
+ if (plugins.length > 0) return compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
927
+ const key = compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry);
928
+ if (key) {
929
+ const hit = __compileMemo.get(key);
930
+ if (hit) return { ...hit };
931
+ const disk = __diskGet(key);
932
+ if (disk) return disk;
933
+ }
934
+ const result = await compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
935
+ if (key) {
936
+ if (__compileMemo.size > 500) __compileMemo.clear();
937
+ __compileMemo.set(key, result);
938
+ __diskSet(key, result);
939
+ }
940
+ return result;
941
+ }
942
+ async function compileComponent(filePath2, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
943
+ let source = await fs3.promises.readFile(filePath2, "utf-8");
616
944
  for (const p of plugins) {
617
945
  if (!p.transform) continue;
618
946
  try {
619
- source = await p.transform(source, filePath);
947
+ source = await p.transform(source, filePath2);
620
948
  } catch (err) {
621
949
  throw new RoseError(
622
950
  "E-PLUGIN",
623
- `plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
624
- { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
951
+ `plugin ${p.name} failed on ${path2.basename(filePath2)}: ${err instanceof Error ? err.message : String(err)}`,
952
+ { file: filePath2, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
625
953
  );
626
954
  }
627
955
  }
@@ -631,7 +959,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
631
959
  const apiMethods = [...rawScript2.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)].map((m) => m[1]).filter((name) => HTTP_METHODS.has(name));
632
960
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
633
961
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
634
- const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
962
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath2, registry).script);
635
963
  const ownRuntimeImports = new Set(
636
964
  [...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
637
965
  );
@@ -659,43 +987,46 @@ ${hoisted.rest}`, "ssr").trim()}`,
659
987
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
660
988
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
661
989
  const scriptMatch = source.match(COMPONENT_RE);
662
- const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
990
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath2, registry);
663
991
  const rawScript = roseResolved.script;
992
+ const usesrosetackAuth = rawScript.includes("__rosetackAuth");
664
993
  const roseImports = roseResolved.imports;
665
994
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
666
- if (path.basename(filePath) !== "_middleware.rose") {
995
+ if (path2.basename(filePath2) !== "_middleware.rose") {
667
996
  for (const spec of nodeOnlyImports(importStmts)) {
668
997
  const at = importStmts.indexOf(spec);
669
998
  throw new RoseError(
670
999
  "E-NODE-ONLY",
671
- `${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.`,
1000
+ `${filePath2}: 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.`,
672
1001
  {
673
- file: filePath,
1002
+ file: filePath2,
674
1003
  line: at >= 0 ? lineOf(importStmts, at) : void 0,
675
1004
  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`
676
1005
  }
677
1006
  );
678
1007
  }
679
1008
  }
680
- const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
1009
+ const isComponent = registry.get(filePath2)?.scopeKey.startsWith("components/") ?? false;
681
1010
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
682
1011
  throw new RoseError(
683
1012
  "E-EXPORT",
684
- `${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()}>.`,
685
- { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
1013
+ `${filePath2}: $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()}>.`,
1014
+ { file: filePath2, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
686
1015
  );
687
1016
  }
688
1017
  const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
689
1018
  const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
690
1019
  const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
691
1020
  const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
1021
+ const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
1022
+ const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : void 0;
692
1023
  const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
693
1024
  const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
694
1025
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
695
1026
  throw new RoseError(
696
1027
  "E-EXPORT",
697
- `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
698
- { 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'" }
1028
+ `${filePath2}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
1029
+ { file: filePath2, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
699
1030
  );
700
1031
  }
701
1032
  const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
@@ -703,8 +1034,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
703
1034
  if (vitalsMatch && !vitals) {
704
1035
  throw new RoseError(
705
1036
  "E-EXPORT",
706
- `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
707
- { 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" }
1037
+ `${filePath2}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
1038
+ { file: filePath2, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
708
1039
  );
709
1040
  }
710
1041
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
@@ -712,8 +1043,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
712
1043
  if (bundle && !["inline", "split"].includes(bundle)) {
713
1044
  throw new RoseError(
714
1045
  "E-EXPORT",
715
- `${filePath}: export const bundle must be 'inline' or 'split'`,
716
- { 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" }
1046
+ `${filePath2}: export const bundle must be 'inline' or 'split'`,
1047
+ { file: filePath2, 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" }
717
1048
  );
718
1049
  }
719
1050
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
@@ -729,9 +1060,9 @@ ${hoisted.rest}`, "ssr").trim()}`,
729
1060
  const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
730
1061
  throw new RoseError(
731
1062
  "E-EXPORT",
732
- `${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.)`,
1063
+ `${filePath2}: 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.)`,
733
1064
  {
734
- file: filePath,
1065
+ file: filePath2,
735
1066
  line: lineAt(deadSrc, dead),
736
1067
  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'
737
1068
  }
@@ -747,15 +1078,15 @@ ${hoisted.rest}`, "ssr").trim()}`,
747
1078
  } catch {
748
1079
  throw new RoseError(
749
1080
  "E-EXPORT",
750
- `${filePath}: export const headers must be an object literal`,
751
- { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
1081
+ `${filePath2}: export const headers must be an object literal`,
1082
+ { file: filePath2, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
752
1083
  );
753
1084
  }
754
1085
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
755
1086
  throw new RoseError(
756
1087
  "E-EXPORT",
757
- `${filePath}: export const headers must be a flat map of string -> string`,
758
- { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
1088
+ `${filePath2}: export const headers must be a flat map of string -> string`,
1089
+ { file: filePath2, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
759
1090
  );
760
1091
  }
761
1092
  headers = value;
@@ -769,16 +1100,16 @@ ${hoisted.rest}`, "ssr").trim()}`,
769
1100
  } catch {
770
1101
  throw new RoseError(
771
1102
  "E-EXPORT",
772
- `${filePath}: export const csp must be an object literal`,
773
- { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
1103
+ `${filePath2}: export const csp must be an object literal`,
1104
+ { file: filePath2, hint: "write it as one literal: export const csp = { nonce: true }" }
774
1105
  );
775
1106
  }
776
1107
  const nonce = value?.nonce;
777
1108
  if (nonce !== void 0 && typeof nonce !== "boolean") {
778
1109
  throw new RoseError(
779
1110
  "E-EXPORT",
780
- `${filePath}: csp.nonce must be a boolean`,
781
- { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1111
+ `${filePath2}: csp.nonce must be a boolean`,
1112
+ { file: filePath2, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
782
1113
  );
783
1114
  }
784
1115
  cspNonce = nonce === true;
@@ -791,8 +1122,10 @@ ${hoisted.rest}`, "ssr").trim()}`,
791
1122
  if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
792
1123
  clientReasons.push("a form bound to a client dispatch ($action)");
793
1124
  }
794
- const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
1125
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);
795
1126
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
1127
+ if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
1128
+ if (source.includes("{#await")) clientReasons.push("{#await} async block");
796
1129
  const needsClient = clientReasons.length > 0;
797
1130
  const jsWarnings = [];
798
1131
  if (!needsClient) {
@@ -817,7 +1150,9 @@ ${hoisted.rest}`, "ssr").trim()}`,
817
1150
  const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
818
1151
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
819
1152
  const decls = extractDecls(script);
820
- const stateDecls = decls.filter((d) => d.kind === "state");
1153
+ const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
1154
+ const derivedNames = decls.filter((d) => d.kind === "derived").map((d) => d.name);
1155
+ const callifyNames = [...stateDecls.map((s) => s.name), ...derivedNames];
821
1156
  const setterNames = /* @__PURE__ */ new Map();
822
1157
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
823
1158
  const declCode = (d) => {
@@ -827,40 +1162,191 @@ ${hoisted.rest}`, "ssr").trim()}`,
827
1162
  }
828
1163
  const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
829
1164
  const fn = isFn ? d.expr : `() => (${d.expr})`;
830
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1165
+ if (d.kind === "persist") {
1166
+ return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1167
+ }
1168
+ if (d.kind === "derived") {
1169
+ return `const ${d.name} = () => (${callifyStateReads(d.expr, callifyNames)});`;
1170
+ }
1171
+ if (d.kind === "kv") {
1172
+ const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1173
+ const fnExpr = mTtl ? mTtl[1] : d.expr;
1174
+ const ttl = mTtl ? mTtl[2] : "300";
1175
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1176
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1177
+ if (!__seeded_${d.name}) { const __v_${d.name} = await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1178
+ }
1179
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
831
1180
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
832
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1181
+ if (!__seeded_${d.name}) { const __v_${d.name} = await $data(${fn}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
833
1182
  };
834
1183
  const nestedDecls = [];
835
1184
  let spliced = "";
836
1185
  let pos = 0;
837
1186
  decls.forEach((d, i) => {
838
1187
  const top = braceDepthAt(script, d.start) === 0;
839
- if (!top) nestedDecls.push(d);
1188
+ if (!top) {
1189
+ if (d.kind === "derived") {
1190
+ throw new Error(
1191
+ `${filePath2}: $derived must be a top-level declaration - inside a function body a plain const arrow already does this natively`
1192
+ );
1193
+ }
1194
+ nestedDecls.push(d);
1195
+ }
840
1196
  spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
841
1197
  pos = d.end;
842
1198
  });
843
1199
  spliced += script.slice(pos);
844
1200
  let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
845
1201
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
1202
+ if (derivedNames.includes(trimmedKey)) {
1203
+ throw new Error(
1204
+ `${filePath2}: $setState('${trimmedKey}', ...) - a $derived value is read-only; make it $state or derive a different expression`
1205
+ );
1206
+ }
846
1207
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
847
1208
  return `${setter}(${val})`;
848
1209
  });
849
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1210
+ cleanScript = callifyStateReads(cleanScript, callifyNames);
850
1211
  cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
851
1212
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
852
1213
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
853
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
854
- const wired = wireEventBindings(templateCalled, actionNames);
855
- const eventBindings = wired.bindings;
856
- const stateKeys = decls.map((d) => d.name);
1214
+ const templateCalled = callifyTemplateExprs(template, callifyNames);
1215
+ const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
1216
+ const wired = wireEventBindings(imgDefaulted, actionNames, filePath2);
1217
+ const stateKeys = decls.filter((d) => d.kind !== "derived").map((d) => d.name);
1218
+ const bindBindings = [];
1219
+ let bindCounter = 0;
1220
+ const bindExpanded = wired.template.replace(
1221
+ /\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1222
+ (whole, kind, name, offset, str) => {
1223
+ if (!stateKeys.includes(name)) {
1224
+ throw new Error(
1225
+ `${filePath2}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1226
+ );
1227
+ }
1228
+ if (kind === "this") return ` data-bind-this="${name}"`;
1229
+ const tagStart = str.lastIndexOf("<", offset);
1230
+ const tagText = tagStart >= 0 ? str.slice(tagStart, offset) : "";
1231
+ if (kind === "value" && /^<select[\s>]/i.test(tagText) && /\smultiple\b/i.test(tagText)) {
1232
+ const setterM = setterNames.get(name);
1233
+ const hnameM = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1234
+ bindBindings.push({
1235
+ event: "change",
1236
+ fn: `${hnameM}: (e) => ${setterM}(Array.from(e.target.selectedOptions, (o) => o.value))`
1237
+ });
1238
+ return ` data-selmulti={${name}().join(',')} data-on-change="${hnameM}"`;
1239
+ }
1240
+ if (kind === "open") {
1241
+ const setterO = setterNames.get(name);
1242
+ const hnameO = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1243
+ bindBindings.push({ event: "toggle", fn: `${hnameO}: (e) => ${setterO}(e.target.open)` });
1244
+ return ` open={${name}()} data-on-toggle="${hnameO}"`;
1245
+ }
1246
+ const setter = setterNames.get(name);
1247
+ const evt = kind === "checked" ? "change" : "input";
1248
+ const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1249
+ bindBindings.push({
1250
+ event: evt,
1251
+ fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; ${setter}(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`
1252
+ });
1253
+ const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
1254
+ return ` ${kind}={${name}()}${evtAttr}`;
1255
+ }
1256
+ );
857
1257
  const comps = new Map(roseImports.map((r) => {
858
- const abs = path.resolve(path.dirname(filePath), r.specifier);
1258
+ const abs = path2.resolve(path2.dirname(filePath2), r.specifier);
859
1259
  const hit = registry.get(abs);
860
1260
  return [r.name, { index: hit.index, slots: hit.slots }];
861
1261
  }));
862
- const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
863
- assertKnownDirectives(ssrTemplate, filePath);
1262
+ const groupBindings = [];
1263
+ let groupCounter = 0;
1264
+ const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1265
+ const groupExpanded = (() => {
1266
+ if (!bindExpanded.includes("bind:group")) return bindExpanded;
1267
+ let out = "";
1268
+ let pos2 = 0;
1269
+ let m;
1270
+ TAG_SCAN_RE.lastIndex = 0;
1271
+ while (m = TAG_SCAN_RE.exec(bindExpanded)) {
1272
+ const [whole, tag, attrs, selfClose] = m;
1273
+ const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
1274
+ if (!gm) continue;
1275
+ const name = gm[1];
1276
+ if (!stateKeys.includes(name)) {
1277
+ throw new RoseError(
1278
+ "E-TEMPLATE",
1279
+ `${filePath2}: bind:group={${name}} must name a $state declaration`,
1280
+ { hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
1281
+ );
1282
+ }
1283
+ if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
1284
+ throw new RoseError(
1285
+ "E-TEMPLATE",
1286
+ `${filePath2}: bind:group is for radio and checkbox inputs`,
1287
+ { hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' }
1288
+ );
1289
+ }
1290
+ const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
1291
+ const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
1292
+ if (!vm || /\{/.test(vm[0])) {
1293
+ throw new RoseError(
1294
+ "E-TEMPLATE",
1295
+ `${filePath2}: a bind:group input needs a static value attribute`,
1296
+ { hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
1297
+ );
1298
+ }
1299
+ if (/\schecked\s*=/.test(attrs)) {
1300
+ throw new RoseError(
1301
+ "E-TEMPLATE",
1302
+ `${filePath2}: a bind:group input cannot also carry checked=`,
1303
+ { hint: "the group state alone decides which inputs are checked" }
1304
+ );
1305
+ }
1306
+ const setter = setterNames.get(name);
1307
+ const hname = `__rvbg_${scopeKey.replace(/\W/g, "_")}_${groupCounter++}`;
1308
+ const groupValue = JSON.stringify(vm[1] ?? vm[2]);
1309
+ const checkedExpr = isArrayGroup ? `${name}().includes(${groupValue})` : `${name}() === ${groupValue}`;
1310
+ const handlerBody = isArrayGroup ? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))` : `${setter}(e.target.value)`;
1311
+ groupBindings.push({ event: "change", fn: `${hname}: (e) => { ${handlerBody}; }` });
1312
+ const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
1313
+ out += bindExpanded.slice(pos2, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1314
+ pos2 = m.index + whole.length;
1315
+ }
1316
+ if (pos2 === 0) return bindExpanded;
1317
+ out += bindExpanded.slice(pos2);
1318
+ return out;
1319
+ })();
1320
+ const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
1321
+ const useExpanded = groupExpanded.replace(
1322
+ /\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
1323
+ (_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
1324
+ );
1325
+ const classExpanded = expandClassDirectives(useExpanded, filePath2);
1326
+ const classMerged = mergeStaticClass(classExpanded);
1327
+ const styleExpanded = expandStyleDirectives(classMerged, filePath2);
1328
+ const transExpanded = expandTransitionDirectives(styleExpanded, filePath2);
1329
+ const animExpanded = expandAnimateDirectives(transExpanded, filePath2);
1330
+ const keyExpanded = expandKeyBlocks(animExpanded, filePath2);
1331
+ const elseExpanded = expandIfElse(keyExpanded);
1332
+ const deferExpanded = expandDeferBlocks(elseExpanded);
1333
+ const awaitExpanded = expandAwaitBlocks(deferExpanded.template, filePath2);
1334
+ const fbExpanded = expandBoundaryFallbacks(awaitExpanded.template, filePath2);
1335
+ const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
1336
+ const call = `{__slot(${encodeSlotCall(attrs)})}`;
1337
+ if (fallback) {
1338
+ if (/\{[^{}]*\}/.test(fallback)) {
1339
+ throw new RoseError(
1340
+ "E-TEMPLATE",
1341
+ `${filePath2}: slot fallback content must be static markup`,
1342
+ { hint: "a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content" }
1343
+ );
1344
+ }
1345
+ return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
1346
+ }
1347
+ return call;
1348
+ }).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
1349
+ assertKnownDirectives(ssrTemplate, filePath2);
864
1350
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
865
1351
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
866
1352
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -868,7 +1354,8 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
868
1354
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
869
1355
  const ssrGuard = guard ? `
870
1356
  ${guard}` : "";
871
- const isMiddleware = path.basename(filePath) === "_middleware.rose";
1357
+ const isMiddleware = path2.basename(filePath2) === "_middleware.rose";
1358
+ const bootCode = deferBootCode(deferExpanded.count, deferExpanded.holds) + (awaitExpanded.blocks.length ? "\n" + awaitBootCode(awaitExpanded.blocks) : "");
872
1359
  const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
873
1360
 
874
1361
  ${importStmts}
@@ -877,8 +1364,8 @@ ${ssrExports}
877
1364
  ${ssrGuard}
878
1365
 
879
1366
  ${cleanScript}
880
- ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
881
- const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1367
+ ` : generateSSR(cleanScript + bootCode, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1368
+ const client = generateClient(cleanScript + bootCode, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
882
1369
  return {
883
1370
  ssr: rewriteRoseImports(ssr, "ssr"),
884
1371
  client: rewriteRoseImports(client, "client"),
@@ -889,6 +1376,7 @@ ${cleanScript}
889
1376
  hasParams,
890
1377
  usesContext,
891
1378
  revalidate,
1379
+ cache: cacheSeconds,
892
1380
  csr,
893
1381
  shell,
894
1382
  buffer,
@@ -901,6 +1389,7 @@ ${cleanScript}
901
1389
  jsWarnings,
902
1390
  headers,
903
1391
  cspNonce,
1392
+ usesrosetackAuth,
904
1393
  props,
905
1394
  roseImports,
906
1395
  isComponent
@@ -914,6 +1403,13 @@ function minifyDecls(block) {
914
1403
  }
915
1404
  function scopeCss(css, key) {
916
1405
  const attr = `[data-rosetack-c="${key}"]`;
1406
+ const scopeOneSelector = (s) => {
1407
+ const t = s.trim();
1408
+ if (!t.includes(":global")) return `${attr} ${t}`;
1409
+ const stripped = t.replace(/:global\([^()]*\)/g, (m) => m.slice(8, -1)).trim();
1410
+ const outside = t.replace(/:global\([^()]*\)/g, "").trim();
1411
+ return outside ? `${attr} ${stripped}` : stripped;
1412
+ };
917
1413
  const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
918
1414
  let out = "";
919
1415
  let prelude = "";
@@ -933,7 +1429,7 @@ function scopeCss(css, key) {
933
1429
  if (sel.startsWith("@")) {
934
1430
  out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
935
1431
  } else if (sel) {
936
- const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
1432
+ const scoped = sel.split(",").map((s) => scopeOneSelector(s)).join(",");
937
1433
  out += `${scoped}{${minifyDecls(block)}}`;
938
1434
  }
939
1435
  prelude = "";
@@ -1079,6 +1575,20 @@ function extractExports(script) {
1079
1575
  out += script.slice(pos);
1080
1576
  return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
1081
1577
  }
1578
+ var REGEX_PRECEDERS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
1579
+ function isRegexStart(src, i) {
1580
+ let j = i - 1;
1581
+ while (j >= 0 && /\s/.test(src[j])) j--;
1582
+ if (j < 0) return true;
1583
+ const p = src[j];
1584
+ if (REGEX_PRECEDERS.has(p)) return true;
1585
+ if (/[A-Za-z0-9_$]/.test(p)) {
1586
+ const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
1587
+ if (!w) return false;
1588
+ return ["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else"].includes(w[1]);
1589
+ }
1590
+ return false;
1591
+ }
1082
1592
  function extractDecls(script) {
1083
1593
  const decls = [];
1084
1594
  DECL_RE.lastIndex = 0;
@@ -1170,6 +1680,35 @@ function braceDepthAt(src, index) {
1170
1680
  i = close === -1 ? src.length : close + 2;
1171
1681
  continue;
1172
1682
  }
1683
+ if (ch === "/" && isRegexStart(src, i)) {
1684
+ i++;
1685
+ let inClass = false;
1686
+ while (i < index) {
1687
+ const c2 = src[i];
1688
+ if (c2 === "\\") {
1689
+ i += 2;
1690
+ continue;
1691
+ }
1692
+ if (inClass) {
1693
+ if (c2 === "]") inClass = false;
1694
+ i++;
1695
+ continue;
1696
+ }
1697
+ if (c2 === "[") {
1698
+ inClass = true;
1699
+ i++;
1700
+ continue;
1701
+ }
1702
+ if (c2 === "/") {
1703
+ i++;
1704
+ break;
1705
+ }
1706
+ if (c2 === "\n") break;
1707
+ i++;
1708
+ }
1709
+ while (i < index && /[a-z]/.test(src[i])) i++;
1710
+ continue;
1711
+ }
1173
1712
  if (ch === "{") depth++;
1174
1713
  else if (ch === "}") depth--;
1175
1714
  i++;
@@ -1180,8 +1719,701 @@ function autoCall(expr) {
1180
1719
  const e = expr.trim();
1181
1720
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1182
1721
  }
1722
+ var DEFER_ENABLED = true;
1723
+ function expandKeyBlocks(template, filePath2) {
1724
+ if (!template.includes("{#key")) return template;
1725
+ for (let pass = 0; pass < 10; pass++) {
1726
+ const OPEN_RE = /\{#key\s+([^}]+)\}/g;
1727
+ OPEN_RE.lastIndex = 0;
1728
+ const openM = OPEN_RE.exec(template);
1729
+ if (!openM) return template;
1730
+ const expr = openM[1].trim();
1731
+ const bodyStart = openM.index + openM[0].length;
1732
+ const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
1733
+ TOK_RE.lastIndex = bodyStart;
1734
+ let depth = 1;
1735
+ let closeAt = -1;
1736
+ let tm;
1737
+ while (tm = TOK_RE.exec(template)) {
1738
+ if (tm[0].startsWith("{#")) {
1739
+ depth++;
1740
+ continue;
1741
+ }
1742
+ depth--;
1743
+ if (depth === 0) {
1744
+ closeAt = tm.index;
1745
+ break;
1746
+ }
1747
+ }
1748
+ if (closeAt < 0) {
1749
+ throw new RoseError(
1750
+ "E-TEMPLATE",
1751
+ `${filePath2}: {#key ${expr}} is never closed`,
1752
+ { hint: "every {#key} needs its {/key}" }
1753
+ );
1754
+ }
1755
+ template = template.slice(0, openM.index) + `{#each [${expr}] as __rvkv}` + template.slice(bodyStart, closeAt) + "{/each}" + template.slice(closeAt + "{/key}".length);
1756
+ }
1757
+ return template;
1758
+ }
1759
+ function expandIfElseOnce(template) {
1760
+ const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
1761
+ let out = "";
1762
+ let pos = 0;
1763
+ let changed = false;
1764
+ for (; ; ) {
1765
+ const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
1766
+ if (!openM) {
1767
+ out += template.slice(pos);
1768
+ break;
1769
+ }
1770
+ const kind = openM[1];
1771
+ const head = openM[2];
1772
+ const start = pos + openM.index;
1773
+ const cond = kind === "if" ? head.trim() : "";
1774
+ const bodyStart = start + openM[0].length;
1775
+ out += template.slice(pos, start);
1776
+ TOK_RE.lastIndex = bodyStart;
1777
+ let depth = 1;
1778
+ let closeAt = -1;
1779
+ let closeLen = 0;
1780
+ const elses = [];
1781
+ let tm;
1782
+ while (tm = TOK_RE.exec(template)) {
1783
+ const tok = tm[0];
1784
+ if (tok.startsWith("{:else")) {
1785
+ if (depth === 1) {
1786
+ const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
1787
+ elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
1788
+ }
1789
+ continue;
1790
+ }
1791
+ if (tok.startsWith("{#")) {
1792
+ depth++;
1793
+ continue;
1794
+ }
1795
+ depth--;
1796
+ if (depth === 0) {
1797
+ closeAt = tm.index;
1798
+ closeLen = tok.length;
1799
+ break;
1800
+ }
1801
+ }
1802
+ if (closeAt < 0 || elses.length === 0) {
1803
+ out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
1804
+ if (closeAt < 0) break;
1805
+ pos = closeAt + closeLen;
1806
+ continue;
1807
+ }
1808
+ const body = template.slice(bodyStart, closeAt);
1809
+ if (kind === "each") {
1810
+ const lastBare = [...elses].reverse().find((e) => e.cond === null);
1811
+ if (!lastBare) {
1812
+ out += template.slice(start, closeAt + closeLen);
1813
+ pos = closeAt + closeLen;
1814
+ continue;
1815
+ }
1816
+ const relLast = lastBare.at - bodyStart;
1817
+ const eachBody = body.slice(0, relLast);
1818
+ const elseBody = body.slice(relLast + lastBare.len);
1819
+ const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, "").trim();
1820
+ out += template.slice(start, bodyStart) + eachBody + `{/each}{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
1821
+ pos = closeAt + closeLen;
1822
+ changed = true;
1823
+ continue;
1824
+ }
1825
+ const branches = [];
1826
+ let cursor = 0;
1827
+ for (let i = 0; i < elses.length; i++) {
1828
+ const e = elses[i];
1829
+ const rel = e.at - bodyStart;
1830
+ branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
1831
+ cursor = rel + e.len;
1832
+ }
1833
+ branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
1834
+ const first = branches.shift();
1835
+ const build3 = (bs) => {
1836
+ if (!bs.length) return "";
1837
+ const head2 = bs[0];
1838
+ const rest = bs.slice(1);
1839
+ if (head2.cond == null) return head2.body;
1840
+ let s = `{#if ${head2.cond}}${head2.body}{/if}`;
1841
+ if (rest.length) s += `{#if !(${head2.cond})}` + build3(rest) + `{/if}`;
1842
+ return s;
1843
+ };
1844
+ let emitted = `{#if ${cond}}${first.body}{/if}`;
1845
+ if (branches.length) emitted += `{#if !(${cond})}` + build3(branches) + `{/if}`;
1846
+ out += emitted;
1847
+ pos = closeAt + closeLen;
1848
+ changed = true;
1849
+ }
1850
+ return { template: out, changed };
1851
+ }
1852
+ function mergeStaticClass(template) {
1853
+ if (!/\sclass\s*=\s*"/.test(template) || !/\sclass\s*=\s*\{/.test(template)) return template;
1854
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1855
+ let out = "";
1856
+ let pos = 0;
1857
+ let m;
1858
+ TAG_RE.lastIndex = 0;
1859
+ while (m = TAG_RE.exec(template)) {
1860
+ const [whole, tag, attrs, selfClose] = m;
1861
+ const sm = /\sclass\s*=\s*"([^"]*)"/.exec(attrs);
1862
+ if (!sm) continue;
1863
+ const rm = /\sclass\s*=\s*\{/.exec(attrs);
1864
+ if (!rm || rm.index === sm.index) continue;
1865
+ const open = attrs.indexOf("{", rm.index);
1866
+ let depth = 1;
1867
+ let j = open + 1;
1868
+ while (j < attrs.length && depth > 0) {
1869
+ const ch = attrs[j];
1870
+ if (ch === '"' || ch === "'") {
1871
+ j = skipQuoted(attrs, j);
1872
+ continue;
1873
+ }
1874
+ if (ch === "{") depth++;
1875
+ else if (ch === "}") depth--;
1876
+ j++;
1877
+ }
1878
+ if (depth !== 0) continue;
1879
+ const expr = attrs.slice(open + 1, j - 1);
1880
+ const base = JSON.stringify(sm[1]);
1881
+ const merged = ` class={((v) => v == null ? ${base} : typeof v === 'object' ? ({ ${base}: true, ...v }) : (${base} + ' ' + v))(${expr})}`;
1882
+ const lo = Math.min(sm.index, rm.index);
1883
+ const hiEnd = Math.max(sm.index + sm[0].length, j);
1884
+ const newAttrs = attrs.slice(0, lo) + merged + attrs.slice(hiEnd);
1885
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1886
+ pos = m.index + whole.length;
1887
+ }
1888
+ out += template.slice(pos);
1889
+ return out;
1890
+ }
1891
+ function expandClassDirectives(template, filePath2) {
1892
+ if (!template.includes("class:")) return template;
1893
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1894
+ let out = "";
1895
+ let pos = 0;
1896
+ let m;
1897
+ TAG_RE.lastIndex = 0;
1898
+ while (m = TAG_RE.exec(template)) {
1899
+ const [whole, tag, attrs, selfClose] = m;
1900
+ if (!attrs.includes("class:")) continue;
1901
+ const pairs = [];
1902
+ const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
1903
+ let nm;
1904
+ while (nm = NAME_RE.exec(attrs)) {
1905
+ let i = nm.index + nm[0].length;
1906
+ let depth = 1;
1907
+ while (i < attrs.length && depth > 0) {
1908
+ const ch = attrs[i];
1909
+ if (ch === '"' || ch === "'") {
1910
+ i = skipQuoted(attrs, i);
1911
+ continue;
1912
+ }
1913
+ if (ch === "{") depth++;
1914
+ else if (ch === "}") depth--;
1915
+ i++;
1916
+ }
1917
+ if (depth !== 0) {
1918
+ throw new RoseError("E-TEMPLATE", `${filePath2}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
1919
+ }
1920
+ pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1921
+ }
1922
+ const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1923
+ const clsM = clsRe.exec(attrs);
1924
+ if (clsM && clsM[2].startsWith("{")) {
1925
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both class={...} and class: directives`, { file: filePath2, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
1926
+ }
1927
+ const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
1928
+ let closure = `(${JSON.stringify(staticCls)}`;
1929
+ for (const p of pairs) {
1930
+ closure += `+((${p.expr})?${JSON.stringify(" " + p.name)}:'')`;
1931
+ }
1932
+ closure += `)`;
1933
+ let newAttrs = attrs;
1934
+ for (let k = pairs.length - 1; k >= 0; k--) {
1935
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1936
+ }
1937
+ if (clsM) {
1938
+ newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
1939
+ } else {
1940
+ newAttrs = ` class={${closure}}` + newAttrs;
1941
+ }
1942
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1943
+ pos = m.index + whole.length;
1944
+ }
1945
+ if (pos === 0) return template;
1946
+ out += template.slice(pos);
1947
+ return out;
1948
+ }
1949
+ function expandTransitionDirectives(template, filePath2) {
1950
+ if (!/\s(?:transition|in|out):/.test(template)) return template;
1951
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1952
+ let out = "";
1953
+ let pos = 0;
1954
+ let m;
1955
+ TAG_RE.lastIndex = 0;
1956
+ while (m = TAG_RE.exec(template)) {
1957
+ const [whole, tag, attrs, selfClose] = m;
1958
+ if (!attrs.includes("transition:") && !/\s(?:in|out):/.test(attrs)) continue;
1959
+ const pairs = [];
1960
+ const NAME_RE = /\s(transition|in|out):([\w-]+)(?:\s*=\s*\{)?/g;
1961
+ let nm;
1962
+ while (nm = NAME_RE.exec(attrs)) {
1963
+ let start = nm.index;
1964
+ let end = nm.index + nm[0].length;
1965
+ let params = "";
1966
+ if (nm[0].endsWith("{")) {
1967
+ let depth = 1;
1968
+ let i = end;
1969
+ while (i < attrs.length && depth > 0) {
1970
+ const ch = attrs[i];
1971
+ if (ch === '"' || ch === "'") {
1972
+ i = skipQuoted(attrs, i);
1973
+ continue;
1974
+ }
1975
+ if (ch === "{") depth++;
1976
+ else if (ch === "}") depth--;
1977
+ i++;
1978
+ }
1979
+ if (depth !== 0) {
1980
+ throw new RoseError("E-TEMPLATE", `${filePath2}: transition:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the transition params expression needs a matching } before the tag ends" });
1981
+ }
1982
+ params = attrs.slice(end, i - 1);
1983
+ end = i;
1984
+ }
1985
+ pairs.push({ dir: nm[1] === "transition" ? "" : nm[1], name: nm[2], params, start, end });
1986
+ }
1987
+ if (pairs.length === 0) continue;
1988
+ let transitionValue = "";
1989
+ for (const p of pairs) {
1990
+ if (transitionValue) transitionValue += "|";
1991
+ transitionValue += (p.dir ? p.dir + ":" : "") + p.name + (p.params ? ":" + p.params : "");
1992
+ }
1993
+ let newAttrs = attrs;
1994
+ for (let k = pairs.length - 1; k >= 0; k--) {
1995
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1996
+ }
1997
+ const transRe = /\sdata-transition\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1998
+ const tm = transRe.exec(newAttrs);
1999
+ if (tm) {
2000
+ const existing = tm[2] ?? tm[3] ?? "";
2001
+ newAttrs = newAttrs.replace(transRe, ` data-transition="${existing}${transitionValue ? (existing ? "|" : "") + transitionValue : ""}"`);
2002
+ } else {
2003
+ newAttrs = ` data-transition="${transitionValue}"` + newAttrs;
2004
+ }
2005
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2006
+ pos = m.index + whole.length;
2007
+ }
2008
+ out += template.slice(pos);
2009
+ return out;
2010
+ }
2011
+ function expandAnimateDirectives(template, filePath2) {
2012
+ if (!template.includes("animate:")) return template;
2013
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2014
+ let out = "";
2015
+ let pos = 0;
2016
+ let m;
2017
+ TAG_RE.lastIndex = 0;
2018
+ while (m = TAG_RE.exec(template)) {
2019
+ const [whole, tag, attrs, selfClose] = m;
2020
+ if (!attrs.includes("animate:")) continue;
2021
+ const pairs = [];
2022
+ const NAME_RE = /\sanimate:([\w-]+)(?:\s*=\s*\{)?/g;
2023
+ let nm;
2024
+ while (nm = NAME_RE.exec(attrs)) {
2025
+ let start = nm.index;
2026
+ let end = nm.index + nm[0].length;
2027
+ let params = "";
2028
+ if (nm[0].endsWith("{")) {
2029
+ let depth = 1;
2030
+ let i = end;
2031
+ while (i < attrs.length && depth > 0) {
2032
+ const ch = attrs[i];
2033
+ if (ch === '"' || ch === "'") {
2034
+ i = skipQuoted(attrs, i);
2035
+ continue;
2036
+ }
2037
+ if (ch === "{") depth++;
2038
+ else if (ch === "}") depth--;
2039
+ i++;
2040
+ }
2041
+ if (depth !== 0) {
2042
+ throw new RoseError("E-TEMPLATE", `${filePath2}: animate:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the animate params expression needs a matching } before the tag ends" });
2043
+ }
2044
+ params = attrs.slice(end, i - 1);
2045
+ end = i;
2046
+ }
2047
+ pairs.push({ name: nm[1], params, start, end });
2048
+ }
2049
+ let animateValue = "";
2050
+ for (const p of pairs) {
2051
+ if (animateValue) animateValue += "|";
2052
+ animateValue += p.name + (p.params ? ":" + p.params : "");
2053
+ }
2054
+ let newAttrs = attrs;
2055
+ for (let k = pairs.length - 1; k >= 0; k--) {
2056
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2057
+ }
2058
+ const animRe = /\sdata-animate\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2059
+ const am = animRe.exec(newAttrs);
2060
+ if (am) {
2061
+ const existing = am[2] ?? am[3] ?? "";
2062
+ newAttrs = newAttrs.replace(animRe, ` data-animate="${existing}${animateValue ? (existing ? "|" : "") + animateValue : ""}"`);
2063
+ } else {
2064
+ newAttrs = ` data-animate="${animateValue}"` + newAttrs;
2065
+ }
2066
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2067
+ pos = m.index + whole.length;
2068
+ }
2069
+ out += template.slice(pos);
2070
+ return out;
2071
+ }
2072
+ function expandStyleDirectives(template, filePath2) {
2073
+ if (!template.includes("style:")) return template;
2074
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2075
+ let out = "";
2076
+ let pos = 0;
2077
+ let m;
2078
+ TAG_RE.lastIndex = 0;
2079
+ while (m = TAG_RE.exec(template)) {
2080
+ const [whole, tag, attrs, selfClose] = m;
2081
+ if (!attrs.includes("style:")) continue;
2082
+ const pairs = [];
2083
+ const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
2084
+ let nm;
2085
+ while (nm = NAME_RE.exec(attrs)) {
2086
+ let i = nm.index + nm[0].length;
2087
+ let depth = 1;
2088
+ while (i < attrs.length && depth > 0) {
2089
+ const ch = attrs[i];
2090
+ if (ch === '"' || ch === "'") {
2091
+ i = skipQuoted(attrs, i);
2092
+ continue;
2093
+ }
2094
+ if (ch === "{") depth++;
2095
+ else if (ch === "}") depth--;
2096
+ i++;
2097
+ }
2098
+ if (depth !== 0) {
2099
+ throw new RoseError("E-TEMPLATE", `${filePath2}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
2100
+ }
2101
+ pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
2102
+ }
2103
+ const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2104
+ const stM = styleRe.exec(attrs);
2105
+ if (stM && stM[2].startsWith("{")) {
2106
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both style={...} and style: directives`, { file: filePath2, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
2107
+ }
2108
+ const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
2109
+ let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
2110
+ for (const p of pairs) {
2111
+ closure += `+${JSON.stringify(p.prop + ":")}+(${p.expr})+';'`;
2112
+ }
2113
+ let newAttrs = attrs;
2114
+ for (let k = pairs.length - 1; k >= 0; k--) {
2115
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2116
+ }
2117
+ if (stM) {
2118
+ newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
2119
+ } else {
2120
+ newAttrs = ` style={${closure}}` + newAttrs;
2121
+ }
2122
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2123
+ pos = m.index + whole.length;
2124
+ }
2125
+ if (pos === 0) return template;
2126
+ out += template.slice(pos);
2127
+ return out;
2128
+ }
2129
+ function expandBoundaryFallbacks(template, filePath2) {
2130
+ if (!template.includes("{:fallback")) return template;
2131
+ for (let pass = 0; pass < 10; pass++) {
2132
+ const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
2133
+ let out = "";
2134
+ let pos = 0;
2135
+ let changed = false;
2136
+ let tm;
2137
+ while (tm = TOK_RE.exec(template)) {
2138
+ if (tm[0] !== "{#boundary}") continue;
2139
+ const start = tm.index;
2140
+ const bodyStart = start + tm[0].length;
2141
+ let depth = 1;
2142
+ let closeAt = -1;
2143
+ let tm2;
2144
+ while (tm2 = TOK_RE.exec(template)) {
2145
+ if (tm2[0] === "{#boundary}") {
2146
+ depth++;
2147
+ continue;
2148
+ }
2149
+ if (tm2[0] === "{/boundary}") {
2150
+ depth--;
2151
+ if (depth === 0) {
2152
+ closeAt = tm2.index;
2153
+ break;
2154
+ }
2155
+ }
2156
+ }
2157
+ if (closeAt < 0) break;
2158
+ const body = template.slice(bodyStart, closeAt);
2159
+ const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
2160
+ const kindStack = ["boundary"];
2161
+ let d = 1;
2162
+ let fbAt = -1;
2163
+ let fbLen = 0;
2164
+ let tm3;
2165
+ BTOK2.lastIndex = 0;
2166
+ while (tm3 = BTOK2.exec(body)) {
2167
+ const tok = tm3[0];
2168
+ if (tok === "{:fallback}") {
2169
+ const top = kindStack[kindStack.length - 1];
2170
+ if (top !== "boundary") {
2171
+ throw new RoseError(
2172
+ "E-TEMPLATE",
2173
+ `${filePath2}: {:fallback} must sit directly inside a {#boundary} block`,
2174
+ { hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
2175
+ );
2176
+ }
2177
+ if (fbAt >= 0) {
2178
+ throw new RoseError("E-TEMPLATE", `${filePath2}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
2179
+ }
2180
+ fbAt = tm3.index;
2181
+ fbLen = tok.length;
2182
+ continue;
2183
+ }
2184
+ if (tok.startsWith("{#")) {
2185
+ d++;
2186
+ kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]);
2187
+ continue;
2188
+ }
2189
+ d--;
2190
+ kindStack.pop();
2191
+ }
2192
+ if (fbAt < 0) continue;
2193
+ const custom = body.slice(0, fbAt);
2194
+ const fbMarkup = body.slice(fbAt + fbLen);
2195
+ const b64 = Buffer.from(fbMarkup, "utf-8").toString("base64");
2196
+ out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + "{/boundary}";
2197
+ pos = closeAt + "{/boundary}".length;
2198
+ changed = true;
2199
+ }
2200
+ if (!changed) break;
2201
+ template = out + template.slice(pos);
2202
+ }
2203
+ return template;
2204
+ }
2205
+ function expandIfElse(template) {
2206
+ for (let pass = 0; pass < 10; pass++) {
2207
+ if (!/\{:else\b/.test(template)) return template;
2208
+ const r = expandIfElseOnce(template);
2209
+ template = r.template;
2210
+ if (!r.changed) return template;
2211
+ }
2212
+ return template;
2213
+ }
2214
+ function expandDeferBlocks(template) {
2215
+ if (!DEFER_ENABLED) {
2216
+ const openRe2 = /\{#defer(?:\s+hold=\\d+)?\}/g;
2217
+ let out2 = "";
2218
+ let dpos = 0;
2219
+ for (; ; ) {
2220
+ openRe2.lastIndex = dpos;
2221
+ const openM = openRe2.exec(template);
2222
+ if (!openM) break;
2223
+ const openAt = openM.index;
2224
+ const openLen = openM[0].length;
2225
+ const closeAt = template.indexOf("{/defer}", openAt + openLen);
2226
+ if (closeAt < 0) break;
2227
+ out2 += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
2228
+ dpos = closeAt + 8;
2229
+ }
2230
+ return { template: dpos === 0 ? template : out2, count: 0, holds: [] };
2231
+ }
2232
+ let count = 0;
2233
+ const holds = [];
2234
+ let out = "";
2235
+ let pos = 0;
2236
+ const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
2237
+ for (; ; ) {
2238
+ openRe.lastIndex = pos;
2239
+ const openM = openRe.exec(template);
2240
+ if (!openM) break;
2241
+ const openAt = openM.index;
2242
+ const openLen = openM[0].length;
2243
+ const hold = openM[1] ? Number(openM[1]) : 0;
2244
+ let depth = 1;
2245
+ let i = openAt + openLen;
2246
+ let closeAt = -1;
2247
+ while (i < template.length) {
2248
+ openRe.lastIndex = i;
2249
+ const nextOpenM = openRe.exec(template);
2250
+ const nextOpen = nextOpenM ? nextOpenM.index : -1;
2251
+ const nextClose = template.indexOf("{/defer}", i);
2252
+ if (nextClose < 0) break;
2253
+ if (nextOpen >= 0 && nextOpen < nextClose) {
2254
+ depth++;
2255
+ i = nextOpen + nextOpenM[0].length;
2256
+ continue;
2257
+ }
2258
+ depth--;
2259
+ if (depth === 0) {
2260
+ closeAt = nextClose;
2261
+ break;
2262
+ }
2263
+ i = nextClose + 8;
2264
+ }
2265
+ if (closeAt < 0) break;
2266
+ const content = template.slice(openAt + openLen, closeAt);
2267
+ holds.push(hold);
2268
+ const n = ++count;
2269
+ out += template.slice(pos, openAt);
2270
+ out += "{#if __rvDefer" + n + "()}" + content + "{/if}\n{#if !__rvDefer" + n + '()}<div class="rv-defer-loading"></div>{/if}';
2271
+ pos = closeAt + 8;
2272
+ }
2273
+ if (count === 0) return { template, count: 0, holds: [] };
2274
+ out += template.slice(pos);
2275
+ return { template: out, count, holds };
2276
+ }
2277
+ function deferBootCode(count, holds = []) {
2278
+ let code = "";
2279
+ for (let n = 1; n <= count; n++) {
2280
+ code += "const [__rvDefer" + n + ", set__rvDefer" + n + '] = state("__rvdefer' + n + '", false);\n';
2281
+ const hold = holds[n - 1] || 0;
2282
+ code += hold > 0 ? "onMount(function () { setTimeout(function () { set__rvDefer" + n + "(true); }, " + hold + "); });\n" : "onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer" + n + "(true); }); }); });\n";
2283
+ }
2284
+ return code;
2285
+ }
2286
+ function expandAwaitBlocks(template, filePath2) {
2287
+ let out = "";
2288
+ let pos = 0;
2289
+ let n = 0;
2290
+ const blocks = [];
2291
+ for (; ; ) {
2292
+ const openAt = template.indexOf("{#await", pos);
2293
+ if (openAt < 0) break;
2294
+ let i = openAt + 7;
2295
+ let brace = 1;
2296
+ while (i < template.length && brace > 0) {
2297
+ const c = template[i];
2298
+ if (c === "{") brace++;
2299
+ else if (c === "}") brace--;
2300
+ i++;
2301
+ }
2302
+ if (brace !== 0) break;
2303
+ const openLen = i - openAt;
2304
+ const expr = template.slice(openAt + 7, i - 1).trim();
2305
+ if (!expr) {
2306
+ throw new RoseError("E-TEMPLATE", `${filePath2}: {#await} needs a promise expression`, {
2307
+ file: filePath2,
2308
+ hint: "write {#await fetchUsers()}...{:then users}...{/await}"
2309
+ });
2310
+ }
2311
+ const blockOpenRe = /\{\#(if|each|boundary|island|await)\b/g;
2312
+ const blockCloseRe = /\{\/(if|each|boundary|island|await)\}/g;
2313
+ const thenRe = /\{:then\b([^}]*)\}/g;
2314
+ const catchRe = /\{:catch\b([^}]*)\}/g;
2315
+ let d = 1;
2316
+ let j = i;
2317
+ let thenAt = -1, catchAt = -1, closeAt = -1;
2318
+ let thenRaw = "", catchRaw = "";
2319
+ for (; ; ) {
2320
+ blockOpenRe.lastIndex = j;
2321
+ blockCloseRe.lastIndex = j;
2322
+ thenRe.lastIndex = j;
2323
+ catchRe.lastIndex = j;
2324
+ const nextOpen = blockOpenRe.exec(template);
2325
+ const nextClose = blockCloseRe.exec(template);
2326
+ const nextThen = thenRe.exec(template);
2327
+ const nextCatch = catchRe.exec(template);
2328
+ let nearestPos = Infinity, kind = "", m = null;
2329
+ const consider = (mm, k) => {
2330
+ if (mm && mm.index < nearestPos) {
2331
+ nearestPos = mm.index;
2332
+ kind = k;
2333
+ m = mm;
2334
+ }
2335
+ };
2336
+ consider(nextOpen, "open");
2337
+ consider(nextClose, "close");
2338
+ consider(nextThen, "then");
2339
+ consider(nextCatch, "catch");
2340
+ if (!m) break;
2341
+ if (kind === "open") {
2342
+ d++;
2343
+ j = m.index + m[0].length;
2344
+ continue;
2345
+ }
2346
+ if (kind === "close") {
2347
+ if (d === 1 && m[1] === "await") {
2348
+ closeAt = m.index;
2349
+ break;
2350
+ }
2351
+ d--;
2352
+ j = m.index + m[0].length;
2353
+ continue;
2354
+ }
2355
+ if (d === 1) {
2356
+ if (kind === "then" && thenAt < 0) {
2357
+ thenAt = m.index;
2358
+ thenRaw = m[1];
2359
+ } else if (kind === "catch" && catchAt < 0) {
2360
+ catchAt = m.index;
2361
+ catchRaw = m[1];
2362
+ }
2363
+ }
2364
+ j = m.index + m[0].length;
2365
+ }
2366
+ if (closeAt < 0 || thenAt < 0) break;
2367
+ const thenTokenEnd = thenAt + 7 + thenRaw.length;
2368
+ const catchTokenEnd = catchAt >= 0 ? catchAt + 7 + catchRaw.length : -1;
2369
+ const pending = template.slice(i, thenAt);
2370
+ const thenBody = template.slice(thenTokenEnd, catchAt >= 0 ? catchAt : closeAt);
2371
+ const catchBody = catchAt >= 0 ? template.slice(catchTokenEnd, closeAt) : "";
2372
+ const thenVarRaw = thenRaw.trim();
2373
+ const catchVarRaw = catchRaw.trim();
2374
+ const thenVar = /^\w+$/.test(thenVarRaw) ? thenVarRaw : `__rvAwaitThen${n + 1}`;
2375
+ const catchVar = catchAt >= 0 ? /^\w+$/.test(catchVarRaw) ? catchVarRaw : `__rvAwaitCatch${n + 1}` : "";
2376
+ n++;
2377
+ const nn = n;
2378
+ const stateName = `__rvAwait${nn}`;
2379
+ blocks.push({ n: nn, expr, thenVar, catchVar });
2380
+ out += template.slice(pos, openAt);
2381
+ out += `{#if ${stateName}().status === 'pending'}` + pending + "{/if}\n";
2382
+ out += `{#each (${stateName}().status === 'resolved' ? [${stateName}().value] : []) as ${thenVar}}` + thenBody + "{/each}\n";
2383
+ if (catchAt >= 0) {
2384
+ out += `{#each (${stateName}().status === 'rejected' ? [${stateName}().error] : []) as ${catchVar}}` + catchBody + "{/each}\n";
2385
+ }
2386
+ pos = closeAt + 8;
2387
+ }
2388
+ if (n === 0) return { template, blocks };
2389
+ out += template.slice(pos);
2390
+ return { template: out, blocks };
2391
+ }
2392
+ function awaitBootCode(blocks) {
2393
+ let code = "";
2394
+ for (const b of blocks) {
2395
+ const stateName = `__rvAwait${b.n}`;
2396
+ code += `const [${stateName}, set${stateName}] = state("__rvawait${b.n}", { status: 'pending', value: null, error: null });
2397
+ `;
2398
+ code += `onMount(function () {
2399
+ `;
2400
+ code += ` Promise.resolve(${b.expr}).then(function (__rvAwaitVal) {
2401
+ `;
2402
+ code += ` set${stateName}({ status: 'resolved', value: __rvAwaitVal });
2403
+ `;
2404
+ code += ` }).catch(function (__rvAwaitErr) {
2405
+ `;
2406
+ code += ` set${stateName}({ status: 'rejected', error: __rvAwaitErr });
2407
+ `;
2408
+ code += ` });
2409
+ `;
2410
+ code += `});
2411
+ `;
2412
+ }
2413
+ return code;
2414
+ }
1183
2415
  function findBlock(src, kind) {
1184
- const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
2416
+ const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : kind === "snippet" ? /\{#snippet\s+(\w+)(?:\s*\(([^)]+)\))?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([^)]+)\))?\}/g;
1185
2417
  const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1186
2418
  let open;
1187
2419
  while (open = head.exec(src)) {
@@ -1203,7 +2435,7 @@ function findBlock(src, kind) {
1203
2435
  i = nextClose.index + nextClose[0].length;
1204
2436
  if (--depth === 0) {
1205
2437
  const content = src.slice(afterOpen, nextClose.index);
1206
- const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
2438
+ const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "snippet" ? [open[1], open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", open[4] ?? "", content];
1207
2439
  const arr = [src.slice(start, i), ...groups];
1208
2440
  arr.index = start;
1209
2441
  return arr;
@@ -1246,8 +2478,20 @@ function compileHead(head) {
1246
2478
  flush();
1247
2479
  return out;
1248
2480
  }
1249
- var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
1250
- function assertKnownDirectives(template, filePath) {
2481
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island", "await", "snippet"]);
2482
+ var __blockResCache = /* @__PURE__ */ new Map();
2483
+ function blockCloseRes(kind) {
2484
+ let hit = __blockResCache.get(kind);
2485
+ if (!hit) {
2486
+ hit = {
2487
+ open: new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g"),
2488
+ close: new RegExp(`\\{/${kind}\\}`, "g")
2489
+ };
2490
+ __blockResCache.set(kind, hit);
2491
+ }
2492
+ return hit;
2493
+ }
2494
+ function assertKnownDirectives(template, filePath2) {
1251
2495
  const rawRanges = [];
1252
2496
  const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
1253
2497
  let raw;
@@ -1273,36 +2517,83 @@ function assertKnownDirectives(template, filePath) {
1273
2517
  if (sigil === "/") {
1274
2518
  throw new RoseError(
1275
2519
  "E-TEMPLATE",
1276
- `${filePath}: {/${word}} does not close anything`,
1277
- { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2520
+ `${filePath2}: {/${word}} does not close anything`,
2521
+ { file: filePath2, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
1278
2522
  );
1279
2523
  }
1280
2524
  if (word === "else") {
2525
+ const netOpens = (re, closer, at) => {
2526
+ let n = 0, mm;
2527
+ re.lastIndex = 0;
2528
+ while (mm = re.exec(template)) {
2529
+ if (mm.index >= at) break;
2530
+ if (!inRaw(mm.index)) n++;
2531
+ }
2532
+ const cr = new RegExp(closer, "g");
2533
+ let c = 0;
2534
+ while (mm = cr.exec(template)) {
2535
+ if (mm.index >= at) break;
2536
+ if (!inRaw(mm.index)) c++;
2537
+ }
2538
+ return n - c;
2539
+ };
2540
+ const ifNet = netOpens(/\{#if\b/g, "\\{/if\\b", m.index);
2541
+ const eachNet = netOpens(/\{#each\b/g, "\\{/each\\b", m.index);
2542
+ if (ifNet <= 0 && eachNet <= 0) {
2543
+ throw new RoseError(
2544
+ "E-TEMPLATE",
2545
+ `${filePath2}: a stray {:else} with no {#if} or {#each} above it`,
2546
+ { file: filePath2, line: lineAt(template, m), hint: "{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block" }
2547
+ );
2548
+ }
2549
+ continue;
2550
+ }
2551
+ if (word === "fallback") {
1281
2552
  throw new RoseError(
1282
2553
  "E-TEMPLATE",
1283
- `${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
1284
- { file: filePath, line: lineAt(template, m), hint: "nest a second {#if}: {#if cond}A{/if}{#if !cond}B{/if} - the negation of the first condition IS the else" }
2554
+ `${filePath2}: a stray {:fallback} with no {#boundary} above it`,
2555
+ { file: filePath2, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
1285
2556
  );
1286
2557
  }
2558
+ if (word === "then" || word === "catch") {
2559
+ const opensBefore = (re, at) => {
2560
+ re.lastIndex = 0;
2561
+ let n = 0, mm;
2562
+ while (mm = re.exec(template)) {
2563
+ if (mm.index >= at) break;
2564
+ if (!inRaw(mm.index)) n++;
2565
+ }
2566
+ return n;
2567
+ };
2568
+ const open = opensBefore(/\{#await\b/g, m.index);
2569
+ const close = opensBefore(/\{\/await\b/g, m.index);
2570
+ if (open <= close) {
2571
+ throw new RoseError(
2572
+ "E-TEMPLATE",
2573
+ `${filePath2}: a stray {:${word}} with no {#await} above it`,
2574
+ { file: filePath2, line: lineAt(template, m), hint: "{:then} / {:catch} belong inside an {#await} ... {/await} block" }
2575
+ );
2576
+ }
2577
+ continue;
2578
+ }
1287
2579
  throw new RoseError(
1288
2580
  "E-TEMPLATE",
1289
- `${filePath}: {:${word}} is not a rosetack directive`,
1290
- { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary} - and there is no {:else}: nest a second {#if} with the negated condition" }
2581
+ `${filePath2}: {:${word}} is not a rosetack directive`,
2582
+ { file: filePath2, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
1291
2583
  );
1292
2584
  }
1293
- const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
2585
+ const OPENER_RE = /\{#(if|each|boundary|island|await)\b([^}]*)\}/g;
1294
2586
  while (m = OPENER_RE.exec(template)) {
1295
2587
  if (inRaw(m.index)) continue;
1296
2588
  const [, kind, head] = m;
1297
- if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
2589
+ if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?(?:\s*\([^)]*\))?\s*$/.test(head)) {
1298
2590
  throw new RoseError(
1299
2591
  "E-TEMPLATE",
1300
- `${filePath}: {#each ${head.trim()}} is missing its item name`,
1301
- { file: filePath, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
2592
+ `${filePath2}: {#each ${head.trim()}} is missing its item name`,
2593
+ { file: filePath2, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
1302
2594
  );
1303
2595
  }
1304
- const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
1305
- const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
2596
+ const { open: OPEN_RE, close: CLOSE_RE } = blockCloseRes(kind);
1306
2597
  let depth = 1;
1307
2598
  let i = m.index + m[0].length;
1308
2599
  for (; ; ) {
@@ -1321,8 +2612,8 @@ function assertKnownDirectives(template, filePath) {
1321
2612
  if (depth !== 0) {
1322
2613
  throw new RoseError(
1323
2614
  "E-TEMPLATE",
1324
- `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
1325
- { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2615
+ `${filePath2}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2616
+ { file: filePath2, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
1326
2617
  );
1327
2618
  }
1328
2619
  }
@@ -1348,11 +2639,14 @@ function rewriteQuotedExprAttrs(template, comps) {
1348
2639
  return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
1349
2640
  });
1350
2641
  }
1351
- function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
2642
+ function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map(), islandDepth = 0) {
1352
2643
  let result = "";
1353
2644
  let remaining = template;
1354
2645
  let blockId = 0;
2646
+ const islandsMode = /\{#island\b/.test(template);
2647
+ const effMarkers = markers && (!islandsMode || islandDepth > 0);
1355
2648
  const nextId = () => `${depth}_${blockId++}`;
2649
+ if (depth === 0) result += "const __snip = {};\n";
1356
2650
  while (remaining.length > 0) {
1357
2651
  const ifMatch = findBlock(remaining, "if");
1358
2652
  const eachMatch = findBlock(remaining, "each");
@@ -1360,10 +2654,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1360
2654
  const firstExpr = templateExprSpans(remaining)[0];
1361
2655
  const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
1362
2656
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2657
+ const islandMatch = findBlock(remaining, "island");
2658
+ const snippetMatch = findBlock(remaining, "snippet");
1363
2659
  const candidates = [];
1364
2660
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
1365
2661
  if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
1366
2662
  if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
2663
+ if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
2664
+ if (snippetMatch?.index !== void 0) candidates.push({ type: "snippet", match: snippetMatch, index: snippetMatch.index });
1367
2665
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
1368
2666
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
1369
2667
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
@@ -1397,10 +2695,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1397
2695
  const call = autoCall(cond);
1398
2696
  const id = nextId();
1399
2697
  const innerScope = scope ?? "__s";
1400
- const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, markers, comps);
2698
+ const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, effMarkers, comps, islandDepth);
1401
2699
  result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
1402
2700
  `;
1403
- if (markers) {
2701
+ if (effMarkers) {
1404
2702
  result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
1405
2703
  `;
1406
2704
  } else {
@@ -1409,45 +2707,88 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1409
2707
  }
1410
2708
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1411
2709
  } else if (earliest.type === "each") {
1412
- const [, items, item, content] = earliest.match;
2710
+ const [, items, item, index, key, content] = earliest.match;
1413
2711
  const before = remaining.substring(0, earliest.index);
1414
2712
  if (before) result += emitChunk(before, acc, closes, scope);
1415
2713
  const call = autoCall(items);
1416
2714
  const id = nextId();
1417
- const itemRe = new RegExp(`\\b${item}\\b`, "g");
2715
+ const isDestructure = /^[{[]/.test(item);
2716
+ const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, "g");
2717
+ const indexRe = index ? new RegExp(`\\b${index}\\b`, "g") : null;
1418
2718
  let scoped = "";
1419
2719
  let lastSpan = 0;
1420
2720
  for (const s of templateExprSpans(content.trim())) {
1421
- scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
2721
+ let expr = itemRe ? s.expr.replace(itemRe, "__s") : s.expr;
2722
+ if (indexRe) expr = expr.replace(indexRe, "__i");
2723
+ scoped += content.trim().slice(lastSpan, s.start) + "{" + expr + "}";
1422
2724
  lastSpan = s.end + 1;
1423
2725
  }
1424
2726
  scoped += content.trim().slice(lastSpan);
1425
- const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
1426
- result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
2727
+ const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2728
+ const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2729
+ let keyFn = "";
2730
+ if (key) {
2731
+ if (isDestructure) {
2732
+ throw new RoseError(
2733
+ "E-TEMPLATE",
2734
+ `${filePath}: a keyed {#each} keys on a named item's property - write {#each xs as x (x.id)}, not a destructuring pattern`,
2735
+ { file: filePath, hint: "name the item first, then key on one of its properties" }
2736
+ );
2737
+ }
2738
+ let k = key.trim();
2739
+ if (itemRe) k = k.replace(itemRe, "__s");
2740
+ if (indexRe) k = k.replace(indexRe, "__i");
2741
+ keyFn = `, (__s, __i) => (${k})`;
2742
+ }
2743
+ result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
1427
2744
  `;
1428
- if (markers) {
1429
- result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
2745
+ if (effMarkers) {
2746
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id}${keyFn});
1430
2747
  `;
1431
2748
  } else {
1432
- result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');
2749
+ const param = isDestructure ? "__s" : item;
2750
+ result += `${acc} += (${call}).map((${param}${index ? ", __i" : ""}) => __b${id}(${param}, []${index ? ", __i" : ""}))).join('');
1433
2751
  `;
1434
2752
  }
1435
2753
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1436
2754
  } else if (earliest.type === "boundary") {
1437
- const [, content] = earliest.match;
2755
+ const [, fbAttr, content] = earliest.match;
2756
+ let fallbackSrc = "";
2757
+ if (fbAttr) {
2758
+ const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
2759
+ if (fbM) fallbackSrc = Buffer.from(fbM[1], "base64").toString("utf-8");
2760
+ }
2761
+ const custom = content;
1438
2762
  const before = remaining.substring(0, earliest.index);
1439
2763
  if (before) result += emitChunk(before, acc, closes, scope);
1440
2764
  const id = nextId();
1441
- const catchesAction = /\$action:|<form[\s>]/.test(content);
1442
- const inner = compileTemplate(content.trim(), "h", closes, scope, depth + 1, markers, comps);
2765
+ const catchesAction = /\$action:|<form[\s>]/.test(custom);
2766
+ const inner = compileTemplate(custom.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
1443
2767
  result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
1444
2768
  `;
2769
+ let fbBlock = "";
2770
+ if (fallbackSrc.trim()) {
2771
+ const fbInner = compileTemplate(fallbackSrc.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
2772
+ fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };
2773
+ `;
2774
+ }
2775
+ result += fbBlock;
1445
2776
  result += `let __bd${id} = '';
1446
2777
  `;
1447
- result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
1448
- ` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
2778
+ result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : "$boundaryFallback(e)"}; }
2779
+ ` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
1449
2780
  `;
1450
2781
  result += `${acc} += __bd${id};
2782
+ `;
2783
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2784
+ } else if (earliest.type === "snippet") {
2785
+ const [, name, params, content] = earliest.match;
2786
+ const before = remaining.substring(0, earliest.index);
2787
+ if (before) result += emitChunk(before, acc, closes, scope);
2788
+ const id = nextId();
2789
+ const paramList = params ? params.split(",").map((p) => p.trim()).filter(Boolean).join(",") : "";
2790
+ const inner = compileTemplate(content.trim(), "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2791
+ result += `__snip.${name} = (__s, __c${paramList ? "," + paramList : ""}) => { let h = ''; ${inner} return h; };
1451
2792
  `;
1452
2793
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1453
2794
  } else if (earliest.type === "comp") {
@@ -1468,7 +2809,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1468
2809
  const { def, named } = splitSlots(childrenSrc);
1469
2810
  const hasChildren = def.trim().length > 0;
1470
2811
  if (hasChildren) {
1471
- result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, markers, comps)} return h; };
2812
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; };
1472
2813
  `;
1473
2814
  }
1474
2815
  const slotFns = named.map(([nm, src]) => {
@@ -1484,9 +2825,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1484
2825
  }
1485
2826
  content = out + content.slice(lastSpan);
1486
2827
  }
1487
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
2828
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; }`;
1488
2829
  });
1489
2830
  const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
2831
+ if (a.kind === "spread") return `...(${a.value})`;
1490
2832
  const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
1491
2833
  const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
1492
2834
  return `${JSON.stringify(key)}: ${val}`;
@@ -1495,20 +2837,49 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1495
2837
  result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
1496
2838
  `;
1497
2839
  remaining = rest;
2840
+ } else if (earliest.type === "island") {
2841
+ const [, name, hydrate, content] = earliest.match;
2842
+ const before = remaining.substring(0, earliest.index);
2843
+ if (before) result += emitChunk(before, acc, closes, scope);
2844
+ const hydrateAttr = hydrate === "visible" || hydrate === "idle" ? ` data-rv-island-hydrate="${hydrate}"` : "";
2845
+ result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ""}"${hydrateAttr}>`)};
2846
+ `;
2847
+ const inner = compileTemplate(content.trim(), "h", "__c", scope, depth + 1, markers, comps, islandDepth + 1);
2848
+ result += inner;
2849
+ result += `${acc} += '</div>';
2850
+ `;
2851
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
1498
2852
  } else {
1499
2853
  const [, expr] = earliest.match;
1500
2854
  const trimmed = expr.trim();
1501
2855
  const before = remaining.substring(0, earliest.index);
2856
+ const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
2857
+ if (constMatch) {
2858
+ if (before) result += emitChunk(before, acc, closes, scope);
2859
+ result += `const ${constMatch[1]} = (${constMatch[2].trim()});
2860
+ `;
2861
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2862
+ continue;
2863
+ }
1502
2864
  if (trimmed === "__slot__") {
1503
2865
  if (before) result += emitChunk(before, acc, closes, scope);
1504
- result += compileSlot(acc);
2866
+ result += compileSlot(acc);
2867
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2868
+ continue;
2869
+ }
2870
+ const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
2871
+ if (slotDefault) {
2872
+ if (before) result += emitChunk(before, acc, closes, scope);
2873
+ result += `${acc} += __slotDefault(children, ${slotDefault[1]});
2874
+ `;
1505
2875
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1506
2876
  continue;
1507
2877
  }
1508
- const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
2878
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
1509
2879
  if (slotCall) {
1510
2880
  if (before) result += emitChunk(before, acc, closes, scope);
1511
- result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);
2881
+ const fb = slotCall[4] ? `, ${slotCall[4]}` : "";
2882
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});
1512
2883
  `;
1513
2884
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1514
2885
  continue;
@@ -1517,7 +2888,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1517
2888
  if (rawMatch) {
1518
2889
  if (before) result += emitChunk(before, acc, closes, scope);
1519
2890
  const expr2 = rawMatch[1].trim();
1520
- if (!markers) {
2891
+ if (!effMarkers) {
1521
2892
  result += `${acc} += String(${expr2} ?? '');
1522
2893
  `;
1523
2894
  } else {
@@ -1528,16 +2899,43 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
1528
2899
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1529
2900
  continue;
1530
2901
  }
2902
+ const dbgMatch = /^@debug\b([\s\S]*)$/.exec(trimmed);
2903
+ if (dbgMatch) {
2904
+ if (before) result += emitChunk(before, acc, closes, scope);
2905
+ const names = dbgMatch[1].trim().replace(/,$/, "");
2906
+ result += names ? `console.log('[rosetack:debug]', { ${names} });
2907
+ ` : `console.log('[rosetack:debug]'); debugger;
2908
+ `;
2909
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2910
+ continue;
2911
+ }
2912
+ const renderMatch = /^@render\s+([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(trimmed);
2913
+ if (renderMatch) {
2914
+ const ahead = new RegExp(`\\{#snippet\\s+${renderMatch[1]}\\b`).test(remaining.substring(earliest.index + earliest.match[0].length));
2915
+ if (ahead) {
2916
+ throw new RoseError(
2917
+ "E-TEMPLATE",
2918
+ `${filePath}: {@render ${renderMatch[1]}} runs before its {#snippet ${renderMatch[1]}} is defined`,
2919
+ { file: filePath, hint: "move the {#snippet} definition above the {@render} call - definitions register as the statement stream reaches them" }
2920
+ );
2921
+ }
2922
+ if (before) result += emitChunk(before, acc, closes, scope);
2923
+ const renderArgs = renderMatch[2].trim();
2924
+ result += `${acc} += ((__snip && __snip.${renderMatch[1]}) ? __snip.${renderMatch[1]}(${scope ?? "null"}, ${closes}${renderArgs ? ", " + renderArgs : ""}) : '');
2925
+ `;
2926
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2927
+ continue;
2928
+ }
1531
2929
  const attrMatch = before.match(/([\w-]+)=\s*$/);
1532
2930
  if (attrMatch) {
1533
2931
  const lit = before.slice(0, before.length - attrMatch[0].length);
1534
2932
  if (lit) result += emitChunk(lit, acc, closes, scope);
1535
- result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
2933
+ result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
1536
2934
  } else {
1537
2935
  if (before) result += emitChunk(before, acc, closes, scope);
1538
2936
  const after = remaining.substring(earliest.index + earliest.match[0].length);
1539
2937
  const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
1540
- result += emitText(trimmed, acc, closes, scope, markers, pair);
2938
+ result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
1541
2939
  }
1542
2940
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
1543
2941
  }
@@ -1597,6 +2995,12 @@ function parseCompAttrs(attrs) {
1597
2995
  const out = [];
1598
2996
  let i = 0;
1599
2997
  while (i < attrs.length) {
2998
+ const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
2999
+ if (spread) {
3000
+ out.push({ name: "...", kind: "spread", value: spread[1].trim() });
3001
+ i += spread[0].length;
3002
+ continue;
3003
+ }
1600
3004
  const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
1601
3005
  if (!nm) break;
1602
3006
  i += nm[0].length;
@@ -1650,6 +3054,7 @@ function splitSlots(src) {
1650
3054
  let i = 0;
1651
3055
  let elemDepth = 0;
1652
3056
  let blockDepth = 0;
3057
+ const blockStack = [];
1653
3058
  while (i < src.length) {
1654
3059
  const lt = src.indexOf("<", i);
1655
3060
  const ob = src.indexOf("{#", i);
@@ -1664,8 +3069,14 @@ function splitSlots(src) {
1664
3069
  if (next === ob || next === cb) {
1665
3070
  const close = src.indexOf("}", next);
1666
3071
  const token = src.slice(next, close < 0 ? src.length : close + 1);
1667
- if (next === ob) blockDepth++;
1668
- else blockDepth = Math.max(0, blockDepth - 1);
3072
+ if (next === ob) {
3073
+ const m = /^\{#(\w+)/.exec(token);
3074
+ blockStack.push({ header: token, type: m ? m[1] : "" });
3075
+ blockDepth++;
3076
+ } else {
3077
+ blockDepth = Math.max(0, blockDepth - 1);
3078
+ if (blockStack.length) blockStack.pop();
3079
+ }
1669
3080
  def += token;
1670
3081
  i = next + token.length;
1671
3082
  continue;
@@ -1692,20 +3103,16 @@ function splitSlots(src) {
1692
3103
  }
1693
3104
  if (!selfClosing && !isVoid) elemDepth++;
1694
3105
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
1695
- if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
1696
- 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' });
1697
- }
1698
- if (slotName) {
1699
- const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3106
+ if (slotName && elemDepth === 1 && blockDepth === 0) {
1700
3107
  if (selfClosing || isVoid) {
1701
- named.set(slotName, (named.get(slotName) ?? "") + stripped);
3108
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, ""));
1702
3109
  } else {
1703
3110
  const closeIdx = findClose(src, end, nm[2]);
1704
- if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
3111
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
1705
3112
  const tail = `</${nm[2]}>`;
1706
3113
  const inner = src.slice(end, closeIdx);
1707
3114
  rejectNestedSlot(inner, slotName);
1708
- named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
3115
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "") + inner + tail);
1709
3116
  elemDepth = Math.max(0, elemDepth - 1);
1710
3117
  i = closeIdx + tail.length;
1711
3118
  continue;
@@ -1713,6 +3120,32 @@ function splitSlots(src) {
1713
3120
  i = end;
1714
3121
  continue;
1715
3122
  }
3123
+ if (slotName && blockDepth > 0) {
3124
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3125
+ let lifted = "";
3126
+ for (const b of blockStack) lifted += b.header;
3127
+ lifted += stripped;
3128
+ if (selfClosing || isVoid) {
3129
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3130
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3131
+ i = end;
3132
+ continue;
3133
+ }
3134
+ const closeIdx = findClose(src, end, nm[2]);
3135
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
3136
+ const tail = `</${nm[2]}>`;
3137
+ lifted += src.slice(end, closeIdx) + tail;
3138
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3139
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3140
+ elemDepth = Math.max(0, elemDepth - 1);
3141
+ i = closeIdx + tail.length;
3142
+ continue;
3143
+ }
3144
+ if (slotName) {
3145
+ throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component, or wrapped only by an {#if}/{#each}/{#boundary} block - it is nested inside another element`, {
3146
+ hint: 'place the element with slot="..." directly inside the component tag, or inside a single {#if}/{#each} block - wrapping it in another element is not yet supported'
3147
+ });
3148
+ }
1716
3149
  def += tagText;
1717
3150
  i = end;
1718
3151
  }
@@ -1733,23 +3166,76 @@ var IMG_MIME = {
1733
3166
  ".svg": "image/svg+xml",
1734
3167
  ".ico": "image/x-icon"
1735
3168
  };
1736
- var INLINE_IMG_MAX = 4096;
3169
+ var INLINE_IMG_MAX = 8192;
3170
+ var INLINE_SVG_MAX = 16384;
3171
+ function listImageVariants(publicDir, url) {
3172
+ const ext = path2.extname(url);
3173
+ const base = path2.basename(url, ext);
3174
+ const dirUrl = url.slice(0, url.length - (base + ext).length);
3175
+ let entries;
3176
+ try {
3177
+ entries = fs3.readdirSync(path2.join(publicDir, path2.dirname(url)));
3178
+ } catch {
3179
+ return [];
3180
+ }
3181
+ const re = new RegExp(
3182
+ "^" + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.w(\\d+)" + ext.replace(".", "\\.") + "$",
3183
+ "i"
3184
+ );
3185
+ const out = [];
3186
+ for (const e of entries) {
3187
+ const m = re.exec(e);
3188
+ const width = m ? Number(m[1]) : 0;
3189
+ if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
3190
+ }
3191
+ return out.sort((a, b) => a.width - b.width);
3192
+ }
3193
+ var __imgReadCache = /* @__PURE__ */ new Map();
3194
+ function cachedImageRead(filePath2) {
3195
+ let st;
3196
+ try {
3197
+ st = fs3.statSync(filePath2);
3198
+ } catch {
3199
+ return null;
3200
+ }
3201
+ const hit = __imgReadCache.get(filePath2);
3202
+ if (hit && hit.mtime === st.mtimeMs) return { buffer: hit.buffer, dims: hit.dims };
3203
+ let buffer;
3204
+ try {
3205
+ buffer = fs3.readFileSync(filePath2);
3206
+ } catch {
3207
+ return null;
3208
+ }
3209
+ const dims = readImageSize(filePath2);
3210
+ const entry = { mtime: st.mtimeMs, buffer, dims };
3211
+ __imgReadCache.set(filePath2, entry);
3212
+ return { buffer, dims: entry.dims };
3213
+ }
1737
3214
  function inlineImages(template, publicDir) {
1738
3215
  return template.replace(IMG_RE, (tag) => {
1739
3216
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
1740
3217
  if (!src) return tag;
1741
- const ext = path.extname(src[1]).toLowerCase();
3218
+ const ext = path2.extname(src[1]).toLowerCase();
1742
3219
  const mime = IMG_MIME[ext];
1743
3220
  if (!mime) return tag;
1744
- let file;
1745
- try {
1746
- file = fs.readFileSync(path.join(publicDir, src[1]));
1747
- } catch {
1748
- return tag;
3221
+ const rel = src[1].replace(/^\/public(?=\/)/, "");
3222
+ const filePath2 = path2.join(publicDir, rel);
3223
+ const read = cachedImageRead(filePath2);
3224
+ if (!read) return tag;
3225
+ const file = read.buffer;
3226
+ const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
3227
+ const dims = authorDims ? null : read.dims;
3228
+ const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
3229
+ const inlineMax = ext === ".svg" ? INLINE_SVG_MAX : INLINE_IMG_MAX;
3230
+ if (file.length > inlineMax) {
3231
+ const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
3232
+ const variants = hasSS ? [] : listImageVariants(publicDir, rel);
3233
+ if (!variants.length) return withDims(tag);
3234
+ const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(", ");
3235
+ return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
1749
3236
  }
1750
- if (file.length > INLINE_IMG_MAX) return tag;
1751
3237
  const uri = ext === ".svg" ? `data:image/svg+xml,${file.toString("utf-8").replace(/%/g, "%25").replace(/#/g, "%23").replace(/\{/g, "%7B").replace(/\}/g, "%7D").replace(/"/g, "%22")}` : `data:${mime};base64,${file.toString("base64")}`;
1752
- return tag.replace(src[0], `src="${uri}"`);
3238
+ return withDims(tag.replace(src[0], `src="${uri}"`));
1753
3239
  });
1754
3240
  }
1755
3241
  function emitText(expr, acc, closes, scope, markers = true, pair = false) {
@@ -1763,6 +3249,7 @@ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
1763
3249
  return `${acc} += textMark(${closes}, ${fn}${extra});
1764
3250
  `;
1765
3251
  }
3252
+ var BOOLEAN_ATTRS = /* @__PURE__ */ new Set(["checked", "disabled", "readonly", "required", "selected", "multiple", "autofocus", "open"]);
1766
3253
  function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1767
3254
  if (!markers) {
1768
3255
  return `${acc} += '${attr}="' + esc(${expr}) + '"';
@@ -1770,6 +3257,10 @@ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1770
3257
  }
1771
3258
  const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1772
3259
  const arg = scope ? `, ${scope}` : "";
3260
+ if (BOOLEAN_ATTRS.has(attr)) {
3261
+ return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});
3262
+ `;
3263
+ }
1773
3264
  return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
1774
3265
  `;
1775
3266
  }
@@ -1777,7 +3268,7 @@ function compileSlot(acc) {
1777
3268
  return `${acc} += String(children);
1778
3269
  `;
1779
3270
  }
1780
- var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
3271
+ var RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, isSeeded, markSeeded, esc, refresh, onMount, onCleanup, $effect, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $actionPending, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
1781
3272
  var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
1782
3273
  function propsCode(props) {
1783
3274
  if (props.length === 0) return "";
@@ -1790,7 +3281,16 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1790
3281
  for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1791
3282
  return { o, fn };
1792
3283
  };
1793
- const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
3284
+ const __slotBlock = (closes, sl, name, pairs, fallback) => {
3285
+ const hit = __slot(sl, name, pairs);
3286
+ if (hit) return slotBlockMark(closes, hit);
3287
+ return fallback || '';
3288
+ };
3289
+ const __slotDefault = (children, fallback) => {
3290
+ const c = children == null ? '' : String(children);
3291
+ if (c.trim()) return c;
3292
+ return fallback || '';
3293
+ };`;
1794
3294
  function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
1795
3295
  const headCode = headFn ? `
1796
3296
  const __head = () => { let __hd = ''; ${headFn} return __hd; };
@@ -1866,7 +3366,7 @@ function buildReport(infos, compiled) {
1866
3366
  if (routeShipsNoJs(infos, compiled, i)) {
1867
3367
  return `${info.routePath} zero-JS nothing in the chain needs the client`;
1868
3368
  }
1869
- const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path.basename(infos[ci].filePath)}`).join("; ");
3369
+ const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path2.basename(infos[ci].filePath)}`).join("; ");
1870
3370
  const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
1871
3371
  return `${info.routePath} client JS ${why}${forced}`;
1872
3372
  });
@@ -1914,44 +3414,44 @@ for (const el of document.querySelectorAll('[data-rosetack]')) {
1914
3414
  }
1915
3415
  `;
1916
3416
  async function buildProject(root, outDir) {
1917
- await fs.promises.mkdir(outDir, { recursive: true });
1918
- const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
1919
- await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
3417
+ await fs3.promises.mkdir(outDir, { recursive: true });
3418
+ const stale = (await fs3.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
3419
+ await Promise.all(stale.map((f) => fs3.promises.rm(path2.join(outDir, f), { force: true })));
1920
3420
  const pageFiles = await scanRoseFiles(root);
1921
3421
  const compFiles = await scanComponentFiles(root);
1922
3422
  const files = [...pageFiles, ...compFiles];
1923
3423
  if (pageFiles.length === 0) {
1924
3424
  throw new RoseError(
1925
3425
  "E-ROUTE",
1926
- `no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
1927
- { file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
3426
+ `no .rose pages found under ${path2.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
3427
+ { file: path2.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
1928
3428
  );
1929
3429
  }
1930
3430
  const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1931
3431
  const config = await loadConfig(root);
1932
3432
  const plugins = config.plugins;
1933
3433
  const scopeKeys = files.map((f, i) => {
1934
- const base = infos[i].isComponent ? path.join(root, "src") : path.join(root, "src", "pages");
1935
- return path.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
3434
+ const base = infos[i].isComponent ? path2.join(root, "src") : path2.join(root, "src", "pages");
3435
+ return path2.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
1936
3436
  });
1937
3437
  const registry = new Map(
1938
3438
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1939
3439
  );
1940
3440
  const compiled = await Promise.all(
1941
- files.map((f, i) => compileComponent(f, path.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
3441
+ files.map((f, i) => compileComponentMemo(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
1942
3442
  );
1943
3443
  const importsOf = /* @__PURE__ */ new Map();
1944
3444
  files.forEach((_, i) => {
1945
3445
  const list = [];
1946
3446
  for (const r of compiled[i].roseImports ?? []) {
1947
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
3447
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1948
3448
  const hit = registry.get(abs);
1949
3449
  if (hit) list.push(hit.index);
1950
3450
  }
1951
3451
  importsOf.set(i, list);
1952
3452
  });
1953
3453
  const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
1954
- if (compiled[i].needsClient) return path.basename(files[i]);
3454
+ if (compiled[i].needsClient) return path2.basename(files[i]);
1955
3455
  if (seen.has(i)) return null;
1956
3456
  seen.add(i);
1957
3457
  for (const dep of importsOf.get(i) ?? []) {
@@ -1973,7 +3473,7 @@ async function buildProject(root, outDir) {
1973
3473
  if (reachable.has(i)) return;
1974
3474
  reachable.add(i);
1975
3475
  for (const r of compiled[i].roseImports ?? []) {
1976
- const abs = path.resolve(path.dirname(files[i]), r.specifier);
3476
+ const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
1977
3477
  const hit = registry.get(abs);
1978
3478
  if (hit) visit(hit.index);
1979
3479
  }
@@ -1982,13 +3482,13 @@ async function buildProject(root, outDir) {
1982
3482
  if (!infos[i].isComponent) visit(i);
1983
3483
  });
1984
3484
  const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
1985
- if (styles) await fs.promises.writeFile(path.join(outDir, "styles.css"), styles);
1986
- else await fs.promises.rm(path.join(outDir, "styles.css"), { force: true });
3485
+ if (styles) await fs3.promises.writeFile(path2.join(outDir, "styles.css"), styles);
3486
+ else await fs3.promises.rm(path2.join(outDir, "styles.css"), { force: true });
1987
3487
  let locales = {};
1988
3488
  try {
1989
- for (const f of await fs.promises.readdir(path.join(root, "src", "locales"))) {
3489
+ for (const f of await fs3.promises.readdir(path2.join(root, "src", "locales"))) {
1990
3490
  if (!f.endsWith(".json")) continue;
1991
- locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, "src", "locales", f), "utf-8"));
3491
+ locales[f.slice(0, -5)] = JSON.parse(await fs3.promises.readFile(path2.join(root, "src", "locales", f), "utf-8"));
1992
3492
  }
1993
3493
  } catch {
1994
3494
  locales = {};
@@ -2000,21 +3500,24 @@ async function buildProject(root, outDir) {
2000
3500
  for (const l of preload) {
2001
3501
  if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
2002
3502
  }
2003
- await fs.promises.rm(path.join(outDir, "locales"), { recursive: true, force: true });
3503
+ await fs3.promises.rm(path2.join(outDir, "locales"), { recursive: true, force: true });
2004
3504
  if (packed.length > 0) {
2005
- const packDir = path.join(outDir, "locales");
2006
- await fs.promises.mkdir(packDir, { recursive: true });
2007
- for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
3505
+ const packDir = path2.join(outDir, "locales");
3506
+ await fs3.promises.mkdir(packDir, { recursive: true });
3507
+ for (const l of packed) await fs3.promises.writeFile(path2.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
2008
3508
  }
2009
3509
  const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
2010
3510
  const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
2011
- const buildDir = path.join(outDir, ".build");
2012
- await fs.promises.rm(buildDir, { recursive: true, force: true });
2013
- await fs.promises.mkdir(buildDir, { recursive: true });
3511
+ const buildDir = path2.join(outDir, ".build");
3512
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
3513
+ await fs3.promises.mkdir(buildDir, { recursive: true });
3514
+ const contentSrcCands = [path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "cli", "content.ts"), path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "src", "cli", "content.ts")];
3515
+ const contentSrc = contentSrcCands.find((c) => fs3.existsSync(c)) ?? contentSrcCands[0];
3516
+ fs3.copyFileSync(contentSrc, path2.join(buildDir, "content-md.ts"));
2014
3517
  const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
2015
3518
  if (runtimePlugins.length > 0) {
2016
- const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
2017
- await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
3519
+ const configRel = path2.relative(buildDir, path2.join(root, "rosetack.config.js")).replace(/\\/g, "/");
3520
+ await fs3.promises.writeFile(path2.join(buildDir, "plugins.js"), `
2018
3521
  import config from ${JSON.stringify(configRel)};
2019
3522
 
2020
3523
  const list = Array.isArray(config) ? config : [];
@@ -2026,21 +3529,21 @@ export const hasRequestHooks = hooks.some((p) => p.onRequest);
2026
3529
  export const hasResponseHooks = hooks.some((p) => p.onResponse);
2027
3530
  `);
2028
3531
  }
2029
- const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
3532
+ const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs3.existsSync(p));
2030
3533
  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" });
2031
3534
  await esbuild.build({
2032
3535
  entryPoints: [runtimeEntry],
2033
3536
  bundle: true,
2034
- outfile: path.join(buildDir, "runtime.js"),
3537
+ outfile: path2.join(buildDir, "runtime.js"),
2035
3538
  format: "esm",
2036
3539
  platform: "browser",
2037
3540
  write: true
2038
3541
  });
2039
3542
  for (let i = 0; i < compiled.length; i++) {
2040
3543
  const src = compiled[i].api ?? compiled[i].ssr;
2041
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
3544
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.ssr.js`), src);
2042
3545
  if (!infos[i].isApi) {
2043
- await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
3546
+ await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
2044
3547
  }
2045
3548
  }
2046
3549
  const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).sort((a, b) => {
@@ -2102,17 +3605,17 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
2102
3605
  return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
2103
3606
  }).join("\n");
2104
3607
  const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
2105
- const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
2106
- const dir = path.posix.dirname(rel);
3608
+ const rel = path2.relative(path2.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
3609
+ const dir = path2.posix.dirname(rel);
2107
3610
  const prefix = dir === "." ? "/" : "/" + dir;
2108
3611
  const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
2109
- return { prefix, render: split ? loaderOf(i) : compose(i), flags };
3612
+ return { prefix, render: compose(i), flags };
2110
3613
  }).sort((a, b) => b.prefix.length - a.prefix.length);
2111
3614
  const notFoundTable = `[
2112
3615
  ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
2113
3616
  ]`;
2114
3617
  const errIdx = infos.findIndex((info) => info.isError);
2115
- const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
3618
+ const errorRender = errIdx >= 0 ? compose(errIdx) : "null";
2116
3619
  const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
2117
3620
  const serverRoutes = pages.map(({ info, i }) => {
2118
3621
  const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
@@ -2140,9 +3643,12 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
2140
3643
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
2141
3644
  return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
2142
3645
  }).join(",\n ");
3646
+ const appUsesAuth = compiled.some((c) => c.usesrosetackAuth);
2143
3647
  const serverEntry = `
2144
3648
  ${serverImports}
2145
- import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
3649
+ import { renderMarkdown } from './content-md.ts';
3650
+ ${appUsesAuth ? "import crypto from 'node:crypto';" : "// no route references __rosetackAuth: the node:crypto auth helpers are omitted, keeping the bundle edge-loadable"}
3651
+ import { setState, persistState, clearRequestState, isolateRender, serializeState, resetRequestContext, installContextStore, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
2146
3652
  ${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
2147
3653
  // module to import - the runners below stay no-ops and the servers call them
2148
3654
  // unconditionally (one code path, no flags to keep in sync).
@@ -2199,6 +3705,7 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
2199
3705
  });
2200
3706
  }
2201
3707
 
3708
+
2202
3709
  // (the cross-machine seam): the cluster relay above covers ONE machine.
2203
3710
  export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
2204
3711
  setStoreTransport(send);
@@ -2219,6 +3726,11 @@ export const routeParams = {
2219
3726
 
2220
3727
  // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
2221
3728
  export const dynamicRoutes = [
3729
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal || compiled[i].needsClient).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3730
+ ];
3731
+
3732
+ // Routes that the prerender function should skip (not bake into static files).
3733
+ export const prerenderSkipRoutes = [
2222
3734
  ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
2223
3735
  ];
2224
3736
 
@@ -2234,6 +3746,239 @@ export const revalidate = [
2234
3746
  ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
2235
3747
  ];
2236
3748
 
3749
+ // Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
3750
+ export const routeCaches = [
3751
+ ${pages.filter(({ i }) => compiled[i].cache !== void 0).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(",\n ")}
3752
+ ];
3753
+ const __dynCache = new Map();
3754
+ export function invalidateRenderCache(): void {
3755
+ __dynCache.clear();
3756
+ }
3757
+
3758
+
3759
+ // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3760
+ const __kvStore = new Map<string, { v: unknown; exp: number }>();
3761
+ // Content collections: src/content/<coll>/*.md scanned once at build time,
3762
+
3763
+ const contentCollections = ${JSON.stringify(scanContentDir(path2.join(root, "src", "content")))};
3764
+ export const kv = {
3765
+ get(key: string): unknown {
3766
+ const e = __kvStore.get(key);
3767
+ if (!e) return undefined;
3768
+ if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
3769
+ return e.v;
3770
+ },
3771
+ set(key: string, value: unknown, ttlSeconds = 300): void {
3772
+ if (__kvStore.size > 1000) {
3773
+ const cutoff = Date.now();
3774
+ for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
3775
+ if (__kvStore.size > 2000) __kvStore.clear();
3776
+ }
3777
+ __kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
3778
+ },
3779
+ del(key: string): void { __kvStore.delete(key); },
3780
+ has(key: string): boolean {
3781
+ const e = __kvStore.get(key);
3782
+ return !!e && e.exp >= Date.now();
3783
+ },
3784
+ };
3785
+ globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
3786
+ globalThis.__rosetackContent = {
3787
+ list: (coll: string, filter?: { tag: string }) => {
3788
+ let items = contentCollections[coll] ?? [];
3789
+ if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
3790
+ return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
3791
+ },
3792
+ rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
3793
+ return buildRss(contentCollections[coll] ?? [], opts);
3794
+ },
3795
+ get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
3796
+ const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
3797
+ if (!e) return null;
3798
+ return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
3799
+ },
3800
+ };
3801
+
3802
+ const v = {
3803
+ validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
3804
+ const errors: Record<string, string> = {};
3805
+ const values: Record<string, unknown> = {};
3806
+ for (const [field, ruleList] of Object.entries(rules)) {
3807
+ let val = body[field];
3808
+ for (const rule of ruleList) {
3809
+ if (val === undefined || val === null || val === "") {
3810
+ if (rule === "required") errors[field] = field + " is required";
3811
+ else if (rule.startsWith("default:")) val = rule.slice(8);
3812
+ continue;
3813
+ }
3814
+ if (rule === "string") val = String(val);
3815
+ else if (rule === "trim") val = String(val).trim();
3816
+ else if (rule === "number") {
3817
+ const num = Number(val);
3818
+ if (Number.isNaN(num)) errors[field] = field + " must be a number";
3819
+ else val = num;
3820
+ } else if (rule === "email") {
3821
+ if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
3822
+ } else if (rule.startsWith("min:")) {
3823
+ const min = Number(rule.slice(4));
3824
+ if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
3825
+ } else if (rule.startsWith("max:")) {
3826
+ const max = Number(rule.slice(4));
3827
+ if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
3828
+ }
3829
+ }
3830
+ values[field] = val;
3831
+ }
3832
+ return { ok: Object.keys(errors).length === 0, errors, values };
3833
+ },
3834
+ };
3835
+
3836
+ const jobs = {
3837
+ _timers: new Map<string, ReturnType<typeof setInterval>>(),
3838
+ every(name: string, seconds: number, fn: () => void | Promise<void>): void {
3839
+ if (this._timers.has(name)) return;
3840
+ const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
3841
+ this._timers.set(name, t as any);
3842
+ },
3843
+ cancel(name: string): void {
3844
+ const t = this._timers.get(name);
3845
+ if (t) { clearInterval(t); this._timers.delete(name); }
3846
+ },
3847
+ cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
3848
+ };
3849
+
3850
+ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
3851
+ const encoder = new TextEncoder();
3852
+ const stream = new ReadableStream({
3853
+ async start(controller) {
3854
+ let closed = false;
3855
+ const send = (event: string, data: unknown) => {
3856
+ if (closed) return;
3857
+ controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
3858
+ };
3859
+ try {
3860
+ await handler(send);
3861
+ } finally {
3862
+ closed = true;
3863
+ try { controller.close(); } catch { }
3864
+ }
3865
+ },
3866
+ });
3867
+ return new Response(stream, {
3868
+ headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
3869
+ });
3870
+ }
3871
+ globalThis.__rosetackExtras = { v, jobs, sse };
3872
+ ${appUsesAuth ? `
3873
+ const auth = {
3874
+ hashPassword(password: string): string {
3875
+ const salt = crypto.randomBytes(16).toString("hex");
3876
+ const hash = crypto.scryptSync(password, salt, 32).toString("hex");
3877
+ return salt + ":" + hash;
3878
+ },
3879
+ verifyPassword(password: string, stored: string): boolean {
3880
+ const [salt, hash] = stored.split(":");
3881
+ if (!salt || !hash) return false;
3882
+ return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
3883
+ },
3884
+ signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
3885
+ const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
3886
+ const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3887
+ return payload + "." + sig;
3888
+ },
3889
+ verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
3890
+ const dot = token.lastIndexOf(".");
3891
+ if (dot < 0) return null;
3892
+ const payload = token.slice(0, dot);
3893
+ const sig = token.slice(dot + 1);
3894
+ const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
3895
+ try {
3896
+ if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
3897
+ } catch { return null; }
3898
+ try {
3899
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString());
3900
+ if (data.exp < Date.now()) return null;
3901
+ return data as T;
3902
+ } catch { return null; }
3903
+ },
3904
+ csrfToken(secret: string, sessionId: string): string {
3905
+ return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
3906
+ },
3907
+ verifyCsrf(token: string, secret: string, sessionId: string): boolean {
3908
+ try {
3909
+ return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
3910
+ } catch { return false; }
3911
+ },
3912
+ };
3913
+ globalThis.__rosetackAuth = auth;
3914
+ ` : "// __rosetackAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
3915
+
3916
+ export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3917
+ const hit = kv.get(key);
3918
+ if (hit !== undefined) return hit;
3919
+ const v = await compute();
3920
+ if (v !== undefined) kv.set(key, v, ttlSeconds);
3921
+ return v;
3922
+ }
3923
+ export function isCachedRoute(pathname: string): boolean {
3924
+ return routeCaches.some((r) => matchRoute(r.pattern, pathname));
3925
+ }
3926
+ export function invalidatePath(pathname: string): number {
3927
+ let n = 0;
3928
+ for (const key of [...__dynCache.keys()]) {
3929
+ if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
3930
+ }
3931
+ return n;
3932
+ }
3933
+ export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
3934
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3935
+ if (!cfg) return null;
3936
+ let h = 0x811c9dc5;
3937
+ const c = cookieHeader || '';
3938
+ for (let i = 0; i < c.length; i++) {
3939
+ h ^= c.charCodeAt(i);
3940
+ h = (h * 0x01000193) >>> 0;
3941
+ }
3942
+ const hit = __dynCache.get(pathname + '|' + h.toString(16));
3943
+ return hit && hit.expires > Date.now() ? hit.page : null;
3944
+ }
3945
+ export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
3946
+ const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
3947
+ if (!cfg) return renderPage(pathname);
3948
+ let h = 0x811c9dc5;
3949
+ for (let i = 0; i < cookieHeader.length; i++) {
3950
+ h ^= cookieHeader.charCodeAt(i);
3951
+ h = (h * 0x01000193) >>> 0;
3952
+ }
3953
+ const key = pathname + '|' + h.toString(16);
3954
+ const hit = __dynCache.get(key);
3955
+ if (hit && hit.expires > Date.now()) {
3956
+ __dynCache.delete(key);
3957
+ __dynCache.set(key, hit);
3958
+ return hit.page;
3959
+ }
3960
+ // Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
3961
+ if (hit && !hit.refreshing) {
3962
+ hit.refreshing = true;
3963
+ renderPage(pathname).then((fresh: any) => {
3964
+ if (fresh.status === 200 && !fresh.redirect) {
3965
+ __dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
3966
+ } else {
3967
+ __dynCache.delete(key);
3968
+ }
3969
+ }).catch(() => { __dynCache.delete(key); });
3970
+ return hit.page;
3971
+ }
3972
+ const page = await renderPage(pathname);
3973
+ if (page.status === 200 && !page.redirect) {
3974
+ __dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
3975
+ if (__dynCache.size > 300) {
3976
+ __dynCache.delete(__dynCache.keys().next().value as string);
3977
+ }
3978
+ }
3979
+ return page;
3980
+ }
3981
+
2237
3982
  // Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
2238
3983
  export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
2239
3984
 
@@ -2348,7 +4093,14 @@ export function docAttrs(pathname) {
2348
4093
 
2349
4094
  // Paint a fallback page (404/500) and serialize its state.
2350
4095
  async function renderFallback(pathname, render) {
2351
- const { html, head } = extractHead(await render([], ''));
4096
+ // Split mode: the not-found entry's render is a loader object \u2014 resolve it through getRender (which memoizes the composed function) exactly like.
4097
+ let fn = render;
4098
+ if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
4099
+
4100
+ // { render } once the route's chunk graph is loaded
4101
+ fn = (await fn.load()).render;
4102
+ }
4103
+ const { html, head } = extractHead(await fn([], ''));
2352
4104
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
2353
4105
  return { html, state, head, ...docAttrs(pathname) };
2354
4106
  }
@@ -2390,7 +4142,15 @@ function extractHead(rendered) {
2390
4142
 
2391
4143
  // Form: the submitted FormData of a progressive-enhancement POST.
2392
4144
  export async function renderPage(pathname, form) {
4145
+ // Renders DO overlap in one process: prod-server warms every route in the background at startup.
4146
+ return isolateRender(() => renderPageIsolated(pathname, form));
4147
+ }
4148
+
4149
+ async function renderPageIsolated(pathname, form) {
2393
4150
  clearRequestState();
4151
+ // Cold-start readiness gate (oboext #8): await the app's published DB-ready promise before any $data() read.
4152
+ const appReady = globalThis.__rosetackAppReady;
4153
+ if (appReady) await appReady;
2394
4154
  for (const route of routes) {
2395
4155
  if (matchRoute(route.pattern, pathname)) {
2396
4156
  const patternParts = route.pattern.split('/');
@@ -2455,8 +4215,27 @@ export async function renderPage(pathname, form) {
2455
4215
  return await notFoundPage(pathname);
2456
4216
  }
2457
4217
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2458
- if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
2459
- return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
4218
+ // F10: in dev the response body carries the real error \u2014 message, file:line and the fix hint.
4219
+ let devDetail = '';
4220
+ if (process.env.rosetack_DEV === '1' && err) {
4221
+ const msg = esc(err instanceof Error ? err.message : String(err));
4222
+ const file = esc(String(err.file || ''));
4223
+ const line = err.line != null ? esc(String(err.line)) : '';
4224
+ const hint = esc(String(err.hint || ''));
4225
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
4226
+ devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
4227
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
4228
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
4229
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
4230
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
4231
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
4232
+ + '</div>';
4233
+ }
4234
+ if (errorPage) {
4235
+ const fb = await renderFallback(pathname, errorPage);
4236
+ return { ...fb, html: fb.html + devDetail, status: 500 };
4237
+ }
4238
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
2460
4239
  }
2461
4240
  // __route tells the bootstrap which route this document was rendered for.
2462
4241
  const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
@@ -2540,7 +4319,15 @@ export async function handleApi(method, pathname, request) {
2540
4319
 
2541
4320
  // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
2542
4321
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4322
+ // Isolated for the same reason as renderPage: a streaming render awaits inside route.render()
4323
+ return isolateRender(() => renderPageStreamIsolated(pathname, write, shellOpen, clientTag));
4324
+ }
4325
+
4326
+ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
2543
4327
  clearRequestState();
4328
+ // Cold-start readiness gate (oboext #8): same contract as renderPage \u2014 await the app's published DB-ready promise before streaming the shell.
4329
+ const appReady = globalThis.__rosetackAppReady;
4330
+ if (appReady) await appReady;
2544
4331
  for (const route of routes) {
2545
4332
  if (matchRoute(route.pattern, pathname)) {
2546
4333
  const patternParts = route.pattern.split('/');
@@ -2563,7 +4350,24 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2563
4350
  } catch (err) {
2564
4351
 
2565
4352
  console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
2566
- html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
4353
+ // F10: dev carries the real error in the body here too \u2014 the shell
4354
+ // is out, so the detail rides after the error page body.
4355
+ let devDetail = '';
4356
+ if (process.env.rosetack_DEV === '1' && err) {
4357
+ const msg = esc(err instanceof Error ? err.message : String(err));
4358
+ const file = esc(String(err.file || ''));
4359
+ const line = err.line != null ? esc(String(err.line)) : '';
4360
+ const hint = esc(String(err.hint || ''));
4361
+ const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
4362
+ devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
4363
+ + '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
4364
+ + '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
4365
+ + (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
4366
+ + (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
4367
+ + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
4368
+ + '</div>';
4369
+ }
4370
+ html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
2567
4371
  }
2568
4372
  write(html);
2569
4373
  // Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
@@ -2580,15 +4384,72 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
2580
4384
  }
2581
4385
  return 404;
2582
4386
  }
4387
+ // Prevent tree-shaking of invalidateRenderCache (called from prod-server.ts / edge.ts on non-GET writes).
4388
+ void invalidateRenderCache;
4389
+
4390
+ // Same reason, for the per-request context store: prod-server.ts installs an AsyncLocalStorage adapter.
4391
+ export { installContextStore };
2583
4392
  `;
2584
- await fs.promises.writeFile(path.join(buildDir, "server-entry.js"), serverEntry);
4393
+ try {
4394
+ const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
4395
+ const uniq = [...new Set(patterns)].sort();
4396
+ const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
4397
+ const paramsOf = (pattern) => (pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
4398
+ const paramSig = uniq.map((p) => {
4399
+ const ps = paramsOf(p);
4400
+ if (!ps.length) return "";
4401
+ return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
4402
+ }).join("");
4403
+ const outDirTs = path2.join(root, "src", ".rosetack");
4404
+ await fs3.promises.mkdir(outDirTs, { recursive: true });
4405
+ const srcLines = [
4406
+ "// GENERATED by rosetack build - do not edit.",
4407
+ "export type RoutePath = " + lit + ";",
4408
+ "export const routePatterns = " + JSON.stringify(uniq) + " as const;",
4409
+ "export type RouteParams = {",
4410
+ paramSig,
4411
+ "};",
4412
+ "/** Build a URL from a route pattern and its params. */",
4413
+ "export function url(",
4414
+ " path: RoutePath,",
4415
+ " params: RouteParams[keyof RouteParams] = {} as never,",
4416
+ "): string {",
4417
+ " let out = path as string;",
4418
+ " for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
4419
+ " out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
4420
+ " }",
4421
+ " return out;",
4422
+ "}"
4423
+ ].join("\n") + "\n";
4424
+ await fs3.promises.writeFile(path2.join(outDirTs, "routes.ts"), srcLines);
4425
+ } catch {
4426
+ }
4427
+ await fs3.promises.writeFile(path2.join(buildDir, "server-entry.js"), serverEntry);
4428
+ await esbuild.build({
4429
+ entryPoints: [path2.join(buildDir, "server-entry.js")],
4430
+ bundle: true,
4431
+ outfile: path2.join(outDir, "server.js"),
4432
+ format: "esm",
4433
+ platform: "node",
4434
+ write: true,
4435
+ ...TS_LOADER
4436
+ });
2585
4437
  await esbuild.build({
2586
- entryPoints: [path.join(buildDir, "server-entry.js")],
4438
+ entryPoints: [(() => {
4439
+ const here = path2.dirname(fileURLToPath(import.meta.url));
4440
+ for (const cand of [path2.join(here, "..", "cli", "prod-server.ts"), path2.join(here, "..", "src", "cli", "prod-server.ts")]) {
4441
+ if (fs3.existsSync(cand)) return cand;
4442
+ }
4443
+ return path2.join(here, "..", "cli", "prod-server.ts");
4444
+ })()],
2587
4445
  bundle: true,
2588
- outfile: path.join(outDir, "server.js"),
4446
+ outfile: path2.join(outDir, "prod.mjs"),
2589
4447
  format: "esm",
2590
4448
  platform: "node",
2591
4449
  write: true,
4450
+ banner: {
4451
+ js: "import { createRequire } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = createRequire(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);"
4452
+ },
2592
4453
  ...TS_LOADER
2593
4454
  });
2594
4455
  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");
@@ -2621,7 +4482,7 @@ reportVitals();
2621
4482
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
2622
4483
  const clientEntry = `
2623
4484
  ${clientImports}
2624
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
4485
+ import { state, setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
2625
4486
 
2626
4487
  // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
2627
4488
  setLocales(${clientLocalesJson}, '${defaultLocale}');
@@ -2839,12 +4700,22 @@ async function postForm(body, container, pathname) {
2839
4700
  // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
2840
4701
  export async function $action(name, e) {
2841
4702
  if (e && e.preventDefault) e.preventDefault();
4703
+ // F34: the pending flag is ordinary signal state - {#if $actionPending()}
4704
+ // disables a submit button while the action is in flight, reactively.
4705
+ const [__rvPending, __rvSetPending] = state('actionPending', false);
4706
+ __rvSetPending(true);
2842
4707
  const body = new FormData();
2843
4708
  body.append('__action', name);
2844
4709
  // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
2845
4710
  const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
2846
- return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4711
+ try {
4712
+ return await postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4713
+ } finally {
4714
+ __rvSetPending(false);
4715
+ }
2847
4716
  }
4717
+ // F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
4718
+ setActionDispatcher($action);
2848
4719
 
2849
4720
  export { postForm };
2850
4721
 
@@ -2876,6 +4747,16 @@ async function __withOwner(container, fn) {
2876
4747
  setFxOwner(null);
2877
4748
  }
2878
4749
  }
4750
+ // View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
4751
+ async function __swap(container, html) {
4752
+ const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
4753
+ if (typeof document.startViewTransition === 'function' && !reduce) {
4754
+ const vt = document.startViewTransition(() => { container.innerHTML = html; });
4755
+ await vt.updateCallbackDone.catch(() => {});
4756
+ } else {
4757
+ container.innerHTML = html;
4758
+ }
4759
+ }
2879
4760
 
2880
4761
  export async function start(container, pathname, initial) {
2881
4762
  clearMounts(); // stale mounts from a failed render never fire
@@ -2898,7 +4779,7 @@ ${langDirBlock}
2898
4779
  prefetchCache.delete(pathname);
2899
4780
  __navReset(container);
2900
4781
  restoreState(hit.state);
2901
- container.innerHTML = hit.html;
4782
+ await __swap(container, hit.html);
2902
4783
  await __withOwner(container, () => {
2903
4784
  wire(container, hit.closes);
2904
4785
  bindEvents(container);
@@ -2923,15 +4804,18 @@ ${langDirBlock}
2923
4804
  if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
2924
4805
 
2925
4806
 
4807
+ console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
2926
4808
  broken = true;
2927
4809
  return;
2928
4810
  }
2929
- if (!initial) container.innerHTML = html;
4811
+ if (!initial) await __swap(container, html);
2930
4812
  wire(container, closes);
2931
4813
  bindEvents(container);
2932
4814
  flushMounts();
2933
4815
  });
2934
4816
  if (signal === 'notFound') {
4817
+ // T17: a client-side render of a $data route without a prefetch entry has no data source (the server fills the context bag) - the correct.
4818
+ if (!initial) { try { location.assign(pathname); return; } catch { } }
2935
4819
  await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
2936
4820
  return;
2937
4821
  }
@@ -2994,11 +4878,11 @@ setRefreshHook(async () => {
2994
4878
  await start(document.getElementById('app'), location.pathname, false);
2995
4879
  });
2996
4880
  `;
2997
- await fs.promises.writeFile(path.join(buildDir, "client-entry.js"), clientEntry);
4881
+ await fs3.promises.writeFile(path2.join(buildDir, "client-entry.js"), clientEntry);
2998
4882
  if (split) {
2999
- await fs.promises.rm(path.join(outDir, "chunks"), { recursive: true, force: true });
4883
+ await fs3.promises.rm(path2.join(outDir, "chunks"), { recursive: true, force: true });
3000
4884
  await esbuild.build({
3001
- entryPoints: [path.join(buildDir, "client-entry.js")],
4885
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
3002
4886
  bundle: true,
3003
4887
  format: "esm",
3004
4888
  platform: "browser",
@@ -3012,9 +4896,9 @@ setRefreshHook(async () => {
3012
4896
  });
3013
4897
  } else {
3014
4898
  await esbuild.build({
3015
- entryPoints: [path.join(buildDir, "client-entry.js")],
4899
+ entryPoints: [path2.join(buildDir, "client-entry.js")],
3016
4900
  bundle: true,
3017
- outfile: path.join(outDir, "client.js"),
4901
+ outfile: path2.join(outDir, "client.js"),
3018
4902
  format: "esm",
3019
4903
  platform: "browser",
3020
4904
  minify: true,
@@ -3022,13 +4906,13 @@ setRefreshHook(async () => {
3022
4906
  ...TS_LOADER
3023
4907
  });
3024
4908
  }
3025
- await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
3026
- await fs.promises.rm(buildDir, { recursive: true, force: true });
3027
- const publicDir = path.join(root, "public");
3028
- if (fs.existsSync(publicDir)) {
3029
- await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
3030
- const favicon = path.join(publicDir, "favicon.ico");
3031
- if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
4909
+ await fs3.promises.writeFile(path2.join(outDir, "mount.js"), MOUNT_ENTRY);
4910
+ await fs3.promises.rm(buildDir, { recursive: true, force: true });
4911
+ const publicDir = path2.join(root, "public");
4912
+ if (fs3.existsSync(publicDir)) {
4913
+ await fs3.promises.cp(publicDir, path2.join(outDir, "public"), { recursive: true });
4914
+ const favicon = path2.join(publicDir, "favicon.ico");
4915
+ if (fs3.existsSync(favicon)) await fs3.promises.copyFile(favicon, path2.join(outDir, "favicon.ico"));
3032
4916
  }
3033
4917
  console.log("rosetack zero-JS report:");
3034
4918
  for (const line of buildReport(infos, compiled)) console.log(" " + line);
@@ -3042,7 +4926,7 @@ setRefreshHook(async () => {
3042
4926
  g = { why: w, files: /* @__PURE__ */ new Map() };
3043
4927
  warnGroups.set(w, g);
3044
4928
  }
3045
- const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
4929
+ const file = path2.relative(root, infos[ci].filePath).replace(/\\/g, "/");
3046
4930
  let routes = g.files.get(file);
3047
4931
  if (!routes) {
3048
4932
  routes = /* @__PURE__ */ new Set();
@@ -3063,13 +4947,13 @@ setRefreshHook(async () => {
3063
4947
  return { routes: pages.map(({ info }) => info), bundle: bundleMode };
3064
4948
  }
3065
4949
  async function scanRoseFiles(root) {
3066
- const pagesDir = path.join(root, "src", "pages");
3067
- if (!fs.existsSync(pagesDir)) return [];
4950
+ const pagesDir = path2.join(root, "src", "pages");
4951
+ if (!fs3.existsSync(pagesDir)) return [];
3068
4952
  async function scan(dir) {
3069
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4953
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
3070
4954
  const files = [];
3071
4955
  for (const entry of entries) {
3072
- const full = path.join(dir, entry.name);
4956
+ const full = path2.join(dir, entry.name);
3073
4957
  if (entry.isDirectory()) files.push(...await scan(full));
3074
4958
  else if (entry.name.endsWith(".rose")) files.push(full);
3075
4959
  }
@@ -3078,13 +4962,13 @@ async function scanRoseFiles(root) {
3078
4962
  return scan(pagesDir);
3079
4963
  }
3080
4964
  async function scanComponentFiles(root) {
3081
- const compDir = path.join(root, "src", "components");
3082
- if (!fs.existsSync(compDir)) return [];
4965
+ const compDir = path2.join(root, "src", "components");
4966
+ if (!fs3.existsSync(compDir)) return [];
3083
4967
  async function scan(dir) {
3084
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
4968
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
3085
4969
  const files = [];
3086
4970
  for (const entry of entries) {
3087
- const full = path.join(dir, entry.name);
4971
+ const full = path2.join(dir, entry.name);
3088
4972
  if (entry.isDirectory()) files.push(...await scan(full));
3089
4973
  else if (entry.name.endsWith(".rose")) files.push(full);
3090
4974
  }
@@ -3093,16 +4977,16 @@ async function scanComponentFiles(root) {
3093
4977
  return scan(compDir);
3094
4978
  }
3095
4979
  function isAncestorDir(layoutPath, pagePath) {
3096
- const layoutDir = path.dirname(layoutPath);
3097
- const pageDir = path.dirname(pagePath);
3098
- return pageDir === layoutDir || pageDir.startsWith(layoutDir + path.sep);
4980
+ const layoutDir = path2.dirname(layoutPath);
4981
+ const pageDir = path2.dirname(pagePath);
4982
+ return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
3099
4983
  }
3100
- function getRouteInfo(filePath, root) {
3101
- const pagesDir = path.join(root, "src", "pages");
3102
- const relative3 = path.relative(pagesDir, filePath).replace(/\\/g, "/");
4984
+ function getRouteInfo(filePath2, root) {
4985
+ const pagesDir = path2.join(root, "src", "pages");
4986
+ const relative3 = path2.relative(pagesDir, filePath2).replace(/\\/g, "/");
3103
4987
  const withoutExt = relative3.replace(/\.rose$/, "");
3104
- const base = path.posix.basename(withoutExt);
3105
- const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
4988
+ const base = path2.posix.basename(withoutExt);
4989
+ const isComponent = filePath2.replace(/\\/g, "/").includes("/src/components/");
3106
4990
  const isLayout = !isComponent && base === "_layout";
3107
4991
  const isNotFound = !isComponent && (base === "404" || base === "_notfound");
3108
4992
  const isError = !isComponent && base === "500";
@@ -3126,7 +5010,7 @@ function getRouteInfo(filePath, root) {
3126
5010
  routePath = "/" + routeParts.join("/");
3127
5011
  }
3128
5012
  return {
3129
- filePath,
5013
+ filePath: filePath2,
3130
5014
  routePath,
3131
5015
  pattern: routePath,
3132
5016
  paramNames: parts.flatMap((p) => {
@@ -3149,11 +5033,11 @@ function capitalize(s) {
3149
5033
  }
3150
5034
 
3151
5035
  // src/cli/shell.ts
3152
- import * as fs2 from "fs";
3153
- import * as path2 from "path";
5036
+ import * as fs4 from "fs";
5037
+ import * as path3 from "path";
3154
5038
  import * as esbuild2 from "esbuild";
3155
5039
  import { createHash } from "crypto";
3156
- var OUT_DIR = path2.join(process.cwd(), "dist");
5040
+ var OUT_DIR = path3.join(process.cwd(), "dist");
3157
5041
  var clientCache = null;
3158
5042
  var splitMode = false;
3159
5043
  function setBundleMode(mode) {
@@ -3161,11 +5045,11 @@ function setBundleMode(mode) {
3161
5045
  }
3162
5046
  function getClientSource() {
3163
5047
  if (splitMode) return null;
3164
- const file = path2.join(OUT_DIR, "client.js");
5048
+ const file = path3.join(OUT_DIR, "client.js");
3165
5049
  try {
3166
- const st = fs2.statSync(file);
5050
+ const st = fs4.statSync(file);
3167
5051
  if (!clientCache || clientCache.mtimeMs !== st.mtimeMs) {
3168
- clientCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
5052
+ clientCache = { mtimeMs: st.mtimeMs, source: fs4.readFileSync(file, "utf-8") };
3169
5053
  }
3170
5054
  return clientCache.source;
3171
5055
  } catch {
@@ -3174,18 +5058,18 @@ function getClientSource() {
3174
5058
  }
3175
5059
  var styleCache = null;
3176
5060
  function getStyles() {
3177
- const file = path2.join(OUT_DIR, "styles.css");
5061
+ const file = path3.join(OUT_DIR, "styles.css");
3178
5062
  try {
3179
- const st = fs2.statSync(file);
5063
+ const st = fs4.statSync(file);
3180
5064
  if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
3181
- styleCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
5065
+ styleCache = { mtimeMs: st.mtimeMs, source: fs4.readFileSync(file, "utf-8") };
3182
5066
  }
3183
5067
  return styleCache.source;
3184
5068
  } catch {
3185
5069
  return "";
3186
5070
  }
3187
5071
  }
3188
- var BOOTSTRAP = esbuild2.transformSync(`
5072
+ var BOOTSTRAP_SOURCE = `
3189
5073
  // shell = false: the document's SSR content sits directly in <body> - no
3190
5074
  // #app wrapper, no demo styles, so a real theme's CSS owns the document from
3191
5075
  // the first byte (and a JS-less visitor never sees either). The bundle still
@@ -3207,18 +5091,39 @@ if (!__app) {
3207
5091
  }
3208
5092
  // Native View Transitions around client-side navigation (progressive:
3209
5093
  // browsers without the API navigate normally, no polyfill, no CSS required).
3210
- function __navigate(pathname) {
3211
- const paint = () => start(__app, pathname);
5094
+ // F35: stash the CURRENT entry's scroll position into its history state
5095
+ // before a new push - the browser only restores scroll on full page loads; a
5096
+ // pjax swap would land wherever the swap left it.
5097
+ function __saveScroll() {
5098
+ try {
5099
+ const s = history.state || {};
5100
+ history.replaceState(Object.assign({}, s, { __rosetackScroll: window.scrollY }), '');
5101
+ } catch (e) { /* history state unavailable (file:// edge): best effort */ }
5102
+ }
5103
+ function __navigate(pathname, restore) {
5104
+ const paint = () => {
5105
+ const p = start(__app, pathname);
5106
+ if (restore) {
5107
+ // back/forward: restore the entry's scroll (top when it has none)
5108
+ const s = history.state || {};
5109
+ const y = typeof s.__rosetackScroll === 'number' ? s.__rosetackScroll : 0;
5110
+ return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
5111
+ }
5112
+ // a fresh navigation starts at the top, like a full page load
5113
+ window.scrollTo(0, 0);
5114
+ return p;
5115
+ };
3212
5116
  if (document.startViewTransition) {
3213
5117
  return document.startViewTransition(paint).updateCallbackDone;
3214
5118
  }
3215
5119
  return paint();
3216
5120
  }
3217
- window.addEventListener('popstate', () => __navigate(window.location.pathname));
5121
+ window.addEventListener('popstate', () => __navigate(window.location.pathname, true));
3218
5122
  document.addEventListener('click', (e) => {
3219
5123
  const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
3220
5124
  if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
3221
5125
  e.preventDefault();
5126
+ __saveScroll();
3222
5127
  history.pushState(null, '', a.getAttribute('href'));
3223
5128
  __navigate(window.location.pathname);
3224
5129
  }
@@ -3308,16 +5213,53 @@ if (__state.__notFound) {
3308
5213
  } else {
3309
5214
  start(__app, window.location.pathname);
3310
5215
  }
3311
- `, { minify: true }).code;
5216
+ `;
5217
+ var BOOTSTRAP_CACHE = null;
5218
+ function bootstrap() {
5219
+ if (BOOTSTRAP_CACHE === null) {
5220
+ if (globalThis.__rosetack_SKIP_MINIFY) {
5221
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
5222
+ } else {
5223
+ try {
5224
+ BOOTSTRAP_CACHE = esbuild2.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
5225
+ } catch {
5226
+ BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
5227
+ }
5228
+ }
5229
+ }
5230
+ return BOOTSTRAP_CACHE;
5231
+ }
3312
5232
  var CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
5233
+ var BASELINE_SECURITY_HEADERS = {
5234
+ "x-content-type-options": "nosniff",
5235
+ "x-frame-options": "DENY",
5236
+ "referrer-policy": "strict-origin-when-cross-origin",
5237
+ "permissions-policy": "accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), fullscreen=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), serial=(), usb=(), xr-spatial-tracking=()"
5238
+ };
3313
5239
  var cspCache = null;
3314
- var EXTERNAL_BOOTSTRAP = `
3315
- import { start, prefetch, postForm, prefetchStats } from '/client.js';
3316
- ${BOOTSTRAP}`;
5240
+ var EXTERNAL_BOOTSTRAP_CACHE = null;
5241
+ function externalBootstrap() {
5242
+ if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `
5243
+ import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';
5244
+ ${bootstrap()}`;
5245
+ return EXTERNAL_BOOTSTRAP_CACHE;
5246
+ }
3317
5247
  function inlineScript(client) {
5248
+ const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
5249
+ let body = client;
5250
+ let aliases = "";
5251
+ if (m) {
5252
+ body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
5253
+ aliases = m[1].split(",").map((pair) => {
5254
+ const parts = pair.split(" as ").map((x) => x.trim());
5255
+ if (parts.length === 1 || parts[0] === parts[1]) return "";
5256
+ return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
5257
+ }).join("");
5258
+ }
3318
5259
  return `
3319
- ${client}
3320
- ${BOOTSTRAP}`;
5260
+ ${body}
5261
+ ${aliases}
5262
+ ${bootstrap()}`;
3321
5263
  }
3322
5264
  function mintNonce() {
3323
5265
  const bytes = new Uint8Array(16);
@@ -3327,15 +5269,20 @@ function mintNonce() {
3327
5269
  return btoa(raw);
3328
5270
  }
3329
5271
  function securityHeaders(client, nonce = "") {
3330
- if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
5272
+ const headers = { ...BASELINE_SECURITY_HEADERS };
5273
+ if (nonce) {
5274
+ headers["Content-Security-Policy"] = `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}`;
5275
+ return headers;
5276
+ }
3331
5277
  if (!cspCache || cspCache.for !== client) {
3332
- const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(EXTERNAL_BOOTSTRAP, "utf-8").digest("base64")}'`;
5278
+ const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(externalBootstrap(), "utf-8").digest("base64")}'`;
3333
5279
  cspCache = {
3334
5280
  for: client,
3335
5281
  value: `script-src ${scriptSrc}; ${CSP_TAIL}`
3336
5282
  };
3337
5283
  }
3338
- return { "Content-Security-Policy": cspCache.value };
5284
+ headers["Content-Security-Policy"] = cspCache.value;
5285
+ return headers;
3339
5286
  }
3340
5287
  var FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
3341
5288
  var STYLES = `
@@ -3394,7 +5341,7 @@ function mergeHeadBlocks(blocks) {
3394
5341
  function clientScriptTag(client, nonce = "") {
3395
5342
  const n = nonce ? ` nonce="${nonce}"` : "";
3396
5343
  return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
3397
- <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
5344
+ <script type="module"${n}>${externalBootstrap()}</script>`;
3398
5345
  }
3399
5346
  function shellOpen(styles = getStyles(), lang = "en", dir = "", shell = true) {
3400
5347
  const styleTag = styles ? `
@@ -3501,6 +5448,12 @@ Rules the compiler enforces (breaking one fails the build):
3501
5448
  type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
3502
5449
  - $state / $data declarations are top-level statements. The declared name IS the
3503
5450
  getter: write count() in the template and the script, never bare count.
5451
+ $persist is $state backed by localStorage: let theme = $persist('light') \u2014
5452
+ the value survives reloads (SSR renders the initial; the client re-seeds
5453
+ from storage at boot).
5454
+ $derived is computed state: let sq = $derived(n * n) \u2014 a read-only getter
5455
+ that recomputes from the signals its expression reads; $setState on it is a
5456
+ build error. Top-level only (in a function body, use a plain const arrow).
3504
5457
  - A route param (pages/blog/[id].rose) is read as state too: declare it
3505
5458
  (\`let id = $state('1')\`) and read id() - the server overwrites the default
3506
5459
  with the URL's value, and export const params = { id: [...] } bakes those
@@ -3510,11 +5463,84 @@ Rules the compiler enforces (breaking one fails the build):
3510
5463
  the value down as a prop.
3511
5464
  - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
3512
5465
  trusted-HTML escape hatch - use it only for content you control.
3513
- - Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
3514
- {#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
5466
+ {@debug a, b} logs those values (as they are AT that point in the render);
5467
+ bare {@debug} also breaks into the debugger. Neither emits HTML. {@const name
5468
+ = expr} is a template-level binding: it evaluates once and is visible to every
5469
+ expression that follows in the same scope (use it to name a computed value
5470
+ inside {#each} without re-evaluating, or to shorten a long expression).
5471
+ - Blocks: {#if cond}...{:else if cond2}...{:else}...{/if},
5472
+ {#each items as item, i}...{:else}...{/each} (i is the zero-based index, the
5473
+ {:else} renders when the list is empty, and the item may be a DESTRUCTURING
5474
+ pattern - {#each items as {name, price}} or {#each entries as [k, v]} - the
5475
+ body then reads the properties/elements directly),
5476
+ {#key expr}...{/key} (re-creates the
5477
+ body whenever expr changes), {#boundary}...{:fallback}...{/boundary} (the
5478
+ fallback renders on a throw; {$boundaryError()?.message} reads the caught
5479
+ error), {#island name="x"}...{/island} (partial hydration) and
5480
+ {#defer}...{/defer} (progressive render; hold=N keeps the skeleton up at
5481
+ least N ms), and {#await promise}...{:then value}...{:catch error}...{/await}
5482
+ (the server renders the pending branch, the client flips to the resolved
5483
+ value once the promise settles, or to the caught error if it rejects; the
5484
+ {:then} / {:catch} names are in scope only inside their branch, and {:catch}
5485
+ is optional). There is NO {:else} branch of its own: a bare {:else} with no
5486
+ block around it is a build error - inside {#each} it means "the list is
5487
+ empty", inside {#if} it is the final else.
5488
+ - Keyed each: {#each todos() as t (t.id)} \u2014 the key makes wire() reconcile:
5489
+ rows whose key and rendered html are unchanged KEEP their DOM nodes (focus,
5490
+ unbound input text, loaded images survive; reorders become moves). Rows
5491
+ with handlers/actions/refs/transitions/components rebuild fresh. The key
5492
+ needs a named item \u2014 {#each xs as x (x.id)}, not a destructuring pattern.
5493
+ - Snippets: {#snippet name(a, b)}...{/snippet} defines a parameterized
5494
+ fragment; {@render name(x, y)} calls it and inlines the markup. Define the
5495
+ snippet BEFORE the render call (top-down execution order \u2014 the compiler
5496
+ rejects the reverse). Reactive content inside works per call.
5497
+ - Transitions: transition:fade (both directions), in:fade (enter only),
5498
+ out:fade (mounts at rest, leave only). Built-ins: fade, slide, fly, zoom,
5499
+ slide-up/down/left/right, scale, spin, blur, stagger; params via
5500
+ transition:fade={300} or transition:fade={duration: 300} (the trailing
5501
+ number wins), or the bare name (300 ms default). Custom: register
5502
+ globalThis.__rosetackTransitions.NAME = (el, duration, phase) => cleanup? \u2014
5503
+ a transition:NAME that is not a built-in falls through to it (phase
5504
+ 'both'/'in'/'out'; built-ins always win).
5505
+ - $actionPending() is true while a server action is in flight: use it to
5506
+ disable the submit button reactively ({#if $actionPending()}).
5507
+ - $setState('k', (x) => x + 1) supports a FUNCTIONAL UPDATER: when the new
5508
+ value is a function it receives the current value and returns the next one.
5509
+ (State that must literally store a function cannot use this form.)
5510
+ - <input type="number" bind:value={n}>: clearing the field stores 'null'
5511
+ (NOT 'NaN') so bound math (n() + 1) stays clean instead of going NaN. The
5512
+ empty field renders as '' on write-back.
5513
+ - Scroll listeners are passive by default (they cannot preventDefault), which
5514
+ keeps the constant scroll event off the main-thread critical path.
5515
+ - Scoped CSS: component <style> rules scope under the component. Use
5516
+ :global(X) to unscope one compound (.card :global(.md)); a selector made
5517
+ only of :global(...) groups emits fully unscoped (:global(body){...}).
5518
+ - animate:flip={duration: 300} (or animate:flip={300}) passes a DURATION
5519
+ param to the FLIP animation; the trailing number is parsed even though object
5520
+ params carry their own colons. Registered animation names work the same way.
5521
+ - <select multiple bind:value={arr}> binds an ARRAY of selected values
5522
+ (declare $state([])); state changes drive option.selected properties.
5523
+ - Two-way binding: <input bind:value={q}> / <input type="checkbox"
5524
+ bind:checked={on}> / <select bind:value={s}>. Numeric inputs coerce through
5525
+ valueAsNumber. Radio groups: <input type="radio" value="free"
5526
+ bind:group={plan}> - the group state holds the selected value and every
5527
+ radio's checked state follows it. bind:this={ref} captures the ELEMENT into
5528
+ a $state slot (declare it: let ref = $state(null)) - call ref().focus() or
5529
+ measure it after mount. A bind:* name must be a $state declaration.
5530
+ - Conditional attributes: class:NAME={expr} and style:PROP={expr} merge with
5531
+ the tag's static class/style into one reactive attribute.
5532
+ - Boolean attributes (checked/disabled/...) are presence-correct: a false
5533
+ expression omits the attribute entirely.
5534
+ - use:NAME attaches a registered element action: directives.NAME = (el, param)
5535
+ => { ...; return { update: (p) => ..., destroy: () => ... } } (or return a
5536
+ cleanup function). A reactive param: use:tooltip={text} - the action's
5537
+ update half re-runs when text changes; the param arrives JSON-parsed.
3515
5538
  - A <slot> with attributes is a named slot and must declare its name:
3516
5539
  <slot name="row" item={post} />. A named slot must be a DIRECT child of the
3517
- component tag - never inside another element or an {#if}/{#each} block.
5540
+ component tag, OR wrapped by a single {#if}/{#each}/{#boundary} block (F21:
5541
+ the block is reconstructed around the slot and the lifted content reads the
5542
+ parent scope, so a gated slot still projects). A named slot inside a plain
5543
+ wrapper element (a <div>, not a block) is still a build error.
3518
5544
  - Every component tag needs its matching close tag (or self-closes with />).
3519
5545
  - In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
3520
5546
  through. A <style> inside <head> is document CSS; a <style> in the body is
@@ -3526,8 +5552,19 @@ Rules the compiler enforces (breaking one fails the build):
3526
5552
 
3527
5553
  ## Events and server actions
3528
5554
 
3529
- - on:click={handler} wires a client event. The handler is a named function from
3530
- the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
5555
+ - on:EVENT={handler} wires a client event - ANY event, not just click. The
5556
+ handler is a named function from the script or an inline arrow:
5557
+ on:click={() => $setState('n', n() + 1)}, on:keydown={noteKey}.
5558
+ click/input/change/submit ride one delegated listener per event type; every
5559
+ other event (keydown, focus, scroll, mouseenter, ...) is bound directly on
5560
+ the element by wire(), so no handler is ever silently dead. |window /
5561
+ |document move the binding onto the global instead (Escape closes the modal,
5562
+ scroll, resize) - one target per handler.
5563
+ Modifiers ride the event: on:submit|preventDefault={save} (supported:
5564
+ |preventDefault, |stopPropagation, |self - only when the event target IS the
5565
+ bound element, |once - unbind after the first run). capture/passive are NOT
5566
+ supported: they are listener options and one delegated listener per event
5567
+ type cannot carry per-element options.
3531
5568
  - A server action is an exported async function. Call it from a native form
3532
5569
  (method="POST", no JS needed - progressive enhancement) or from any event
3533
5570
  (on:click={like} - one POST, in-place adopt). Its return value is an
@@ -3574,6 +5611,181 @@ window., timers) belongs in onMount, and anything the predicate cannot see
3574
5611
  (inline on* attributes, javascript: URLs, eval) is reported by the build.
3575
5612
  `;
3576
5613
 
5614
+ // src/cli/edge.ts
5615
+ import { pathToFileURL as pathToFileURL2 } from "url";
5616
+ import { join as join3 } from "path";
5617
+
5618
+ // src/cli/shutdown.ts
5619
+ var shutdownHooks = [];
5620
+ var draining = null;
5621
+ globalThis.__rosetackOnShutdown = onShutdown;
5622
+ globalThis.__rosetackRunShutdownHooks = runShutdownHooks;
5623
+ function onShutdown(name, fn) {
5624
+ const hook = { name, fn };
5625
+ shutdownHooks.push(hook);
5626
+ return () => {
5627
+ const at = shutdownHooks.indexOf(hook);
5628
+ if (at !== -1) shutdownHooks.splice(at, 1);
5629
+ };
5630
+ }
5631
+ function runShutdownHooks(reason) {
5632
+ if (draining) return draining;
5633
+ draining = (async () => {
5634
+ const results = [];
5635
+ for (const hook of shutdownHooks.slice()) {
5636
+ try {
5637
+ await hook.fn();
5638
+ results.push({ name: hook.name, ok: true });
5639
+ } catch (err) {
5640
+ const message = err instanceof Error ? err.message : String(err);
5641
+ results.push({ name: hook.name, ok: false, error: message });
5642
+ console.error(`[rosetack] shutdown hook ${hook.name} failed (${reason}):`, message);
5643
+ }
5644
+ }
5645
+ return results;
5646
+ })().finally(() => {
5647
+ draining = null;
5648
+ });
5649
+ return draining;
5650
+ }
5651
+
5652
+ // src/cli/edge.ts
5653
+ function crossSiteWrite(request) {
5654
+ const m = request.method;
5655
+ if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
5656
+ const origin = request.headers.get("origin");
5657
+ if (origin) {
5658
+ let host;
5659
+ try {
5660
+ host = new URL(origin).host;
5661
+ } catch {
5662
+ return new Response("Cross-site request blocked (unparsable Origin header)", { status: 403 });
5663
+ }
5664
+ return host === new URL(request.url).host ? null : new Response("Cross-site request blocked (Origin does not match Host)", { status: 403 });
5665
+ }
5666
+ const site = request.headers.get("sec-fetch-site");
5667
+ if (site && site !== "same-origin" && site !== "same-site" && site !== "none") {
5668
+ return new Response(`Cross-site request blocked (sec-fetch-site: ${site})`, { status: 403 });
5669
+ }
5670
+ return null;
5671
+ }
5672
+ async function createEdgeHandler(outDir, preloaded) {
5673
+ const mod = preloaded?.server ?? await import(pathToFileURL2(join3(outDir, "server.js")).href);
5674
+ let client = null;
5675
+ let styles = "";
5676
+ if (preloaded && "client" in preloaded) {
5677
+ client = preloaded.client ?? null;
5678
+ } else {
5679
+ try {
5680
+ client = await (await import("fs/promises")).readFile(join3(outDir, "client.js"), "utf-8");
5681
+ } catch {
5682
+ client = null;
5683
+ }
5684
+ }
5685
+ if (client && client.includes("chunks/")) client = null;
5686
+ if (preloaded && "styles" in preloaded) {
5687
+ styles = preloaded.styles ?? "";
5688
+ } else {
5689
+ try {
5690
+ styles = await (await import("fs/promises")).readFile(join3(outDir, "styles.css"), "utf-8");
5691
+ } catch {
5692
+ styles = "";
5693
+ }
5694
+ }
5695
+ let broken = /* @__PURE__ */ new Set();
5696
+ if (preloaded && "broken" in preloaded) {
5697
+ broken = new Set(preloaded.broken);
5698
+ } else {
5699
+ try {
5700
+ broken = new Set(JSON.parse(await (await import("fs/promises")).readFile(join3(outDir, "broken.json"), "utf-8")));
5701
+ } catch {
5702
+ broken = /* @__PURE__ */ new Set();
5703
+ }
5704
+ }
5705
+ const pageHeaders2 = (pathname, nonce = "") => {
5706
+ const headers = {};
5707
+ for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
5708
+ if (!headers["cache-control"]) headers["cache-control"] = "no-cache";
5709
+ const own = mod.headersFor?.(pathname);
5710
+ if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
5711
+ return headers;
5712
+ };
5713
+ return async function handle(request) {
5714
+ const refused = crossSiteWrite(request);
5715
+ if (refused) return refused;
5716
+ const { pathname, searchParams } = new URL(request.url);
5717
+ const canonical = pathname.replace(/\/+$/, "") || "/";
5718
+ if (canonical !== pathname) {
5719
+ return new Response(null, { status: 308, headers: { location: canonical + new URL(request.url).search } });
5720
+ }
5721
+ mod.setQuery?.(Object.fromEntries(searchParams));
5722
+ const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks ? { request, url: new URL(request.url), method: request.method, pathname, state: {} } : null;
5723
+ if (hookCtx) {
5724
+ const short = await mod.runRequestHooks(hookCtx);
5725
+ if (short) return mod.runResponseHooks(hookCtx, short);
5726
+ }
5727
+ if (mod.middleware) {
5728
+ const mw = await mod.runMiddleware(request);
5729
+ if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
5730
+ }
5731
+ if (mod.isApi(pathname)) {
5732
+ if (request.method !== "GET") {
5733
+ const fn = mod.invalidateRenderCache;
5734
+ if (typeof fn === "function") fn();
5735
+ }
5736
+ const apiRes = await mod.handleApi(request.method, pathname, request);
5737
+ return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
5738
+ }
5739
+ const form = request.method === "POST" ? await request.formData() : void 0;
5740
+ if (form) {
5741
+ const fn = mod.invalidateRenderCache;
5742
+ if (typeof fn === "function") fn();
5743
+ }
5744
+ if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
5745
+ const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
5746
+ const streamed = new Response(null, {
5747
+ status: 200,
5748
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders2(pathname, nonce2) }
5749
+ });
5750
+ const head = hookCtx ? await mod.runResponseHooks(hookCtx, streamed) : streamed;
5751
+ const encoder = new TextEncoder();
5752
+ const stream = new ReadableStream({
5753
+ async start(controller) {
5754
+ const doc = mod.docAttrs(pathname);
5755
+ await mod.renderPageStream(
5756
+ pathname,
5757
+ (chunk) => controller.enqueue(encoder.encode(chunk)),
5758
+ shellOpen(styles, doc.lang, doc.dir, !mod.shellOff?.(pathname)),
5759
+ clientScriptTag(client, nonce2)
5760
+ );
5761
+ controller.close();
5762
+ }
5763
+ });
5764
+ return new Response(stream, { status: head.status, headers: head.headers });
5765
+ }
5766
+ const cookieHeader = request.headers.get("cookie") || "";
5767
+ const memoHit = !form && mod.isCachedRoute?.(pathname) ? mod.peekRenderCache?.(pathname, cookieHeader) : null;
5768
+ const page = memoHit ?? (mod.renderPageCached && !form ? await mod.renderPageCached(pathname, cookieHeader) : await mod.renderPage(pathname, form));
5769
+ const nonce = mod.cspNonce?.(pathname) ? mintNonce() : "";
5770
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
5771
+ const buffered = new Response(html, {
5772
+ status: page.status ?? 200,
5773
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders2(pathname, nonce) }
5774
+ });
5775
+ return hookCtx ? mod.runResponseHooks(hookCtx, buffered) : buffered;
5776
+ };
5777
+ }
5778
+
5779
+ // src/cli/origin.ts
5780
+ function requestOrigin(req, fallbackPort) {
5781
+ const rawProto = String(req.headers?.["x-forwarded-proto"] || "");
5782
+ const proto = rawProto.split(",")[0].trim();
5783
+ const scheme = proto === "https" || proto === "http" ? proto : "http";
5784
+ const rawHost = String(req.headers?.["x-forwarded-host"] || "");
5785
+ const host = rawHost.split(",")[0].trim() || req.headers?.host || `localhost:${fallbackPort}`;
5786
+ return `${scheme}://${host}`;
5787
+ }
5788
+
3577
5789
  // src/cli/index.ts
3578
5790
  function pickEncoding(req) {
3579
5791
  const ae = req.headers["accept-encoding"] || "";
@@ -3597,6 +5809,9 @@ function sendHtml(req, res, status, html, extraHeaders) {
3597
5809
  res.statusCode = status;
3598
5810
  res.setHeader("Content-Type", "text/html; charset=utf-8");
3599
5811
  res.setHeader("Vary", "Accept-Encoding");
5812
+ if (!Object.keys(extraHeaders || {}).some((k) => k.toLowerCase() === "cache-control")) {
5813
+ res.setHeader("Cache-Control", "no-cache");
5814
+ }
3600
5815
  if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
3601
5816
  let hash = 2166136261;
3602
5817
  for (let i = 0; i < html.length; i++) {
@@ -3672,25 +5887,42 @@ if (__portArg) {
3672
5887
  const __v = __portArg.includes("=") ? __portArg.slice("--port=".length) : process.argv[process.argv.indexOf(__portArg) + 1];
3673
5888
  if (__v && Number(__v) > 0) process.env.PORT = __v;
3674
5889
  }
3675
- var SRC_DIR = process.argv[3] && !process.argv[3].startsWith("-") ? path3.resolve(process.argv[3]) : process.cwd();
3676
- var OUT_DIR2 = path3.join(process.cwd(), "dist");
5890
+ var SRC_DIR = process.argv[3] && !process.argv[3].startsWith("-") ? path4.resolve(process.argv[3]) : process.cwd();
5891
+ var OUT_DIR2 = path4.join(process.cwd(), "dist");
3677
5892
  var PORT = Number(process.env.PORT) || 3e3;
3678
5893
  var serverModule = null;
3679
5894
  var serverMtime = -1;
3680
5895
  var serverVersion = 0;
5896
+ function loadDotEnv(dir) {
5897
+ try {
5898
+ const raw = fs5.readFileSync(path4.join(dir, ".env"), "utf-8");
5899
+ for (const line of raw.split(/\r?\n/)) {
5900
+ const t = line.trim();
5901
+ if (!t || t.startsWith("#")) continue;
5902
+ const eq = t.indexOf("=");
5903
+ if (eq <= 0) continue;
5904
+ const k = t.slice(0, eq).trim();
5905
+ let v = t.slice(eq + 1).trim();
5906
+ if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) v = v.slice(1, -1);
5907
+ if (!(k in process.env)) process.env[k] = v;
5908
+ }
5909
+ } catch {
5910
+ }
5911
+ }
5912
+ loadDotEnv(process.cwd());
3681
5913
  async function loadServer() {
3682
- const file = path3.join(OUT_DIR2, "server.js");
3683
- const mtimeMs = fs3.statSync(file).mtimeMs;
5914
+ const file = path4.join(OUT_DIR2, "server.js");
5915
+ const mtimeMs = fs5.statSync(file).mtimeMs;
3684
5916
  if (!serverModule || mtimeMs !== serverMtime) {
3685
5917
  serverMtime = mtimeMs;
3686
5918
  serverVersion++;
3687
5919
  let target = file;
3688
5920
  if (devMode) {
3689
- target = path3.join(OUT_DIR2, ".build", `server-${serverVersion}.mjs`);
3690
- await fs3.promises.mkdir(path3.dirname(target), { recursive: true });
3691
- await fs3.promises.copyFile(file, target);
5921
+ target = path4.join(OUT_DIR2, ".build", `server-${serverVersion}.mjs`);
5922
+ await fs5.promises.mkdir(path4.dirname(target), { recursive: true });
5923
+ await fs5.promises.copyFile(file, target);
3692
5924
  }
3693
- serverModule = await import(pathToFileURL2(target).href);
5925
+ serverModule = await import(pathToFileURL3(target).href);
3694
5926
  }
3695
5927
  return serverModule;
3696
5928
  }
@@ -3699,9 +5931,9 @@ async function build2() {
3699
5931
  await clearPrerendered(OUT_DIR2);
3700
5932
  setBundleMode(bundle);
3701
5933
  const skipped = await prerender(routes);
3702
- await fs3.promises.writeFile(path3.join(OUT_DIR2, "broken.json"), JSON.stringify(skipped));
5934
+ await fs5.promises.writeFile(path4.join(OUT_DIR2, "broken.json"), JSON.stringify(skipped));
3703
5935
  const ssrModule = await loadServer();
3704
- await fs3.promises.writeFile(path3.join(OUT_DIR2, "headers.json"), JSON.stringify({
5936
+ await fs5.promises.writeFile(path4.join(OUT_DIR2, "headers.json"), JSON.stringify({
3705
5937
  default: securityHeaders(getClientSource()),
3706
5938
  routes: ssrModule.routeHeaders ?? []
3707
5939
  }));
@@ -3724,33 +5956,33 @@ async function build2() {
3724
5956
  }
3725
5957
  var BROTLI_EXT = /* @__PURE__ */ new Set([".html", ".js", ".css", ".json", ".svg", ".txt"]);
3726
5958
  async function writeBrotli(dir) {
3727
- for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
3728
- const p = path3.join(dir, e.name);
5959
+ for (const e of await fs5.promises.readdir(dir, { withFileTypes: true })) {
5960
+ const p = path4.join(dir, e.name);
3729
5961
  if (e.isDirectory()) {
3730
5962
  await writeBrotli(p);
3731
5963
  continue;
3732
5964
  }
3733
- if (!BROTLI_EXT.has(path3.extname(e.name).toLowerCase())) continue;
3734
- await fs3.promises.writeFile(p + ".br", zlib.brotliCompressSync(await fs3.promises.readFile(p)));
5965
+ if (!BROTLI_EXT.has(path4.extname(e.name).toLowerCase())) continue;
5966
+ await fs5.promises.writeFile(p + ".br", zlib.brotliCompressSync(await fs5.promises.readFile(p)));
3735
5967
  }
3736
5968
  }
3737
5969
  async function analyze(outDir, dynamic) {
3738
5970
  const rows = [];
3739
5971
  const walk = async (dir, prefix) => {
3740
- for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
5972
+ for (const e of await fs5.promises.readdir(dir, { withFileTypes: true })) {
3741
5973
  if (e.isDirectory()) {
3742
- await walk(path3.join(dir, e.name), `${prefix}/${e.name}`);
5974
+ await walk(path4.join(dir, e.name), `${prefix}/${e.name}`);
3743
5975
  continue;
3744
5976
  }
3745
5977
  if (!e.name.endsWith(".html")) continue;
3746
- const file = path3.join(dir, e.name);
3747
- const raw = await fs3.promises.readFile(file);
5978
+ const file = path4.join(dir, e.name);
5979
+ const raw = await fs5.promises.readFile(file);
3748
5980
  const brFile = `${file}.br`;
3749
5981
  rows.push({
3750
5982
  route: prefix || "/",
3751
5983
  raw: raw.length,
3752
5984
  gzip: zlib.gzipSync(raw, { level: 9 }).length,
3753
- br: fs3.existsSync(brFile) ? (await fs3.promises.stat(brFile)).size : 0,
5985
+ br: fs5.existsSync(brFile) ? (await fs5.promises.stat(brFile)).size : 0,
3754
5986
  js: /<script type="module"/.test(raw.toString("utf8"))
3755
5987
  });
3756
5988
  }
@@ -3761,10 +5993,10 @@ async function analyze(outDir, dynamic) {
3761
5993
  for (const r of rows.sort((a, b) => a.route < b.route ? -1 : 1)) {
3762
5994
  lines.push(` ${r.route.padEnd(16)}${kb(r.raw).padStart(9)} raw ${kb(r.gzip).padStart(8)} gzip ${kb(r.br).padStart(8)} br ${r.js ? "bundle inlined" : "zero-JS"}`);
3763
5995
  }
3764
- const client = path3.join(outDir, "client.js");
3765
- if (fs3.existsSync(client)) {
3766
- const raw = await fs3.promises.readFile(client);
3767
- lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs3.existsSync(`${client}.br`) ? (await fs3.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
5996
+ const client = path4.join(outDir, "client.js");
5997
+ if (fs5.existsSync(client)) {
5998
+ const raw = await fs5.promises.readFile(client);
5999
+ lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs5.existsSync(`${client}.br`) ? (await fs5.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
3768
6000
  }
3769
6001
  if (dynamic.length > 0) {
3770
6002
  lines.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${dynamic.join(" ")}`);
@@ -3772,9 +6004,9 @@ async function analyze(outDir, dynamic) {
3772
6004
  for (const l of lines) console.log(l);
3773
6005
  }
3774
6006
  async function clearPrerendered(dir, depth = 0) {
3775
- for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
6007
+ for (const e of await fs5.promises.readdir(dir, { withFileTypes: true })) {
3776
6008
  if (depth === 0 && e.name === "locales" && e.isDirectory()) continue;
3777
- const p = path3.join(dir, e.name);
6009
+ const p = path4.join(dir, e.name);
3778
6010
  if (e.isDirectory()) {
3779
6011
  await clearPrerendered(p, depth + 1);
3780
6012
  continue;
@@ -3782,7 +6014,7 @@ async function clearPrerendered(dir, depth = 0) {
3782
6014
  if (!/\.(?:html|json)(?:\.br)?$/.test(e.name)) continue;
3783
6015
  for (let attempt = 0; ; attempt++) {
3784
6016
  try {
3785
- await fs3.promises.rm(p, { force: true });
6017
+ await fs5.promises.rm(p, { force: true });
3786
6018
  break;
3787
6019
  } catch (err) {
3788
6020
  if (attempt >= 2 || !/EPERM|EBUSY|EACCES/.test(String(err))) throw err;
@@ -3808,13 +6040,13 @@ async function prerender(routes) {
3808
6040
  skipped.push(routePath);
3809
6041
  return;
3810
6042
  }
3811
- const routeDir = routePath === "/" ? OUT_DIR2 : path3.join(OUT_DIR2, routePath.slice(1));
3812
- await fs3.promises.mkdir(routeDir, { recursive: true });
3813
- await fs3.promises.writeFile(path3.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
3814
- console.log(`prerendered ${routePath} -> ${path3.relative(process.cwd(), path3.join(routeDir, "index.html"))}`);
6043
+ const routeDir = routePath === "/" ? OUT_DIR2 : path4.join(OUT_DIR2, routePath.slice(1));
6044
+ await fs5.promises.mkdir(routeDir, { recursive: true });
6045
+ await fs5.promises.writeFile(path4.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
6046
+ console.log(`prerendered ${routePath} -> ${path4.relative(process.cwd(), path4.join(routeDir, "index.html"))}`);
3815
6047
  };
3816
6048
  for (const info of routes) {
3817
- if (ssrModule.dynamicRoutes.includes(info.routePath)) {
6049
+ if ((ssrModule.prerenderSkipRoutes ?? []).includes(info.routePath)) {
3818
6050
  console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
3819
6051
  continue;
3820
6052
  }
@@ -3848,10 +6080,10 @@ async function prerender(routes) {
3848
6080
  continue;
3849
6081
  }
3850
6082
  const body = await res.text();
3851
- const outFile = path3.join(OUT_DIR2, routePath.slice(1) + ".json");
3852
- await fs3.promises.mkdir(path3.dirname(outFile), { recursive: true });
3853
- await fs3.promises.writeFile(outFile, body);
3854
- console.log(`prerendered api ${routePath} -> ${path3.relative(process.cwd(), outFile)}`);
6083
+ const outFile = path4.join(OUT_DIR2, routePath.slice(1) + ".json");
6084
+ await fs5.promises.mkdir(path4.dirname(outFile), { recursive: true });
6085
+ await fs5.promises.writeFile(outFile, body);
6086
+ console.log(`prerendered api ${routePath} -> ${path4.relative(process.cwd(), outFile)}`);
3855
6087
  } catch (err) {
3856
6088
  console.error(`api prerender skipped for ${routePath}: ${err instanceof Error ? err.message : err}`);
3857
6089
  }
@@ -3885,23 +6117,23 @@ function nonceFor(ssrModule, pathname) {
3885
6117
  return ssrModule.cspNonce?.(pathname) ? mintNonce() : "";
3886
6118
  }
3887
6119
  var isrBusy = /* @__PURE__ */ new Set();
3888
- function revalidateInBackground(routePath, filePath) {
3889
- if (isrBusy.has(filePath)) return;
3890
- isrBusy.add(filePath);
6120
+ function revalidateInBackground(routePath, filePath2) {
6121
+ if (isrBusy.has(filePath2)) return;
6122
+ isrBusy.add(filePath2);
3891
6123
  void (async () => {
3892
6124
  try {
3893
6125
  const ssrModule = await loadServer();
3894
6126
  ssrModule.setQuery?.({});
3895
6127
  const page = await ssrModule.renderPage(routePath);
3896
6128
  if (page.status === 200) {
3897
- await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
3898
- fileCache.delete(filePath);
6129
+ await fs5.promises.writeFile(filePath2, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
6130
+ fileCache.delete(filePath2);
3899
6131
  console.log(`rosetack: revalidated ${routePath} in the background`);
3900
6132
  }
3901
6133
  } catch (err) {
3902
6134
  console.error("rosetack: background revalidation failed for", routePath, err instanceof Error ? err.message : err);
3903
6135
  } finally {
3904
- isrBusy.delete(filePath);
6136
+ isrBusy.delete(filePath2);
3905
6137
  }
3906
6138
  })();
3907
6139
  }
@@ -3928,7 +6160,7 @@ function readBody(req, res, onDone) {
3928
6160
  req.on("error", () => {
3929
6161
  });
3930
6162
  }
3931
- function crossSiteWrite(req) {
6163
+ function crossSiteWrite2(req) {
3932
6164
  const m = req.method;
3933
6165
  if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
3934
6166
  const origin = req.headers.origin;
@@ -3947,6 +6179,11 @@ function crossSiteWrite(req) {
3947
6179
  }
3948
6180
  return null;
3949
6181
  }
6182
+ function writeAccessLine(req, res, bytes, tag, startedNs) {
6183
+ const ms = Number(process.hrtime.bigint() - (startedNs ?? process.hrtime.bigint())) / 1e6;
6184
+ const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1e3).toFixed(0)}us`;
6185
+ console.log(`${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ""} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
6186
+ }
3950
6187
  function withAccessLog(handler, tag) {
3951
6188
  return (req, res) => {
3952
6189
  const started = process.hrtime.bigint();
@@ -3961,11 +6198,7 @@ function withAccessLog(handler, tag) {
3961
6198
  if (chunk) bytes += Buffer.byteLength(chunk);
3962
6199
  return end(chunk, ...rest);
3963
6200
  };
3964
- res.on("finish", () => {
3965
- const ms = Number(process.hrtime.bigint() - started) / 1e6;
3966
- const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1e3).toFixed(0)}us`;
3967
- console.log(`${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ""} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
3968
- });
6201
+ res.on("finish", () => writeAccessLine(req, res, bytes, tag, started));
3969
6202
  handler(req, res);
3970
6203
  };
3971
6204
  }
@@ -4052,6 +6285,7 @@ function settleDevBuild() {
4052
6285
  if (!devMode || !devBuild && !devBuildPending) return null;
4053
6286
  return startDevBuild();
4054
6287
  }
6288
+ var invalidateHook = null;
4055
6289
  function devWrap(inner) {
4056
6290
  devMode = true;
4057
6291
  return (req, res) => {
@@ -4084,13 +6318,44 @@ function devWrap(inner) {
4084
6318
  }
4085
6319
  function serveStatic(dir, isr = false, dev2 = false) {
4086
6320
  return (req, res) => {
4087
- const blocked = crossSiteWrite(req);
6321
+ const blocked = crossSiteWrite2(req);
4088
6322
  if (blocked) {
4089
6323
  res.statusCode = blocked.status;
4090
6324
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
4091
6325
  res.end(blocked.body);
4092
6326
  return;
4093
6327
  }
6328
+ if (req.method === "POST" && (req.url || "").startsWith("/__rosetack/revalidate")) {
6329
+ const token = process.env.rosetack_REVALIDATE_TOKEN || "";
6330
+ if (!token) {
6331
+ res.statusCode = 404;
6332
+ res.end();
6333
+ return;
6334
+ }
6335
+ if (req.headers["x-rosetack-token"] !== token) {
6336
+ res.statusCode = 403;
6337
+ res.setHeader("content-type", "application/json");
6338
+ res.end(JSON.stringify({ error: "invalid token" }));
6339
+ return;
6340
+ }
6341
+ let body = "";
6342
+ req.on("data", (c) => {
6343
+ body += c;
6344
+ if (body.length > 1e6) req.destroy();
6345
+ });
6346
+ req.on("end", () => {
6347
+ try {
6348
+ const payload = JSON.parse(body || "{}");
6349
+ if (invalidateHook) invalidateHook();
6350
+ res.setHeader("content-type", "application/json");
6351
+ res.end(JSON.stringify({ revalidated: true, scope: payload.all ? "all" : "paths" }));
6352
+ } catch (e) {
6353
+ res.statusCode = 400;
6354
+ res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
6355
+ }
6356
+ });
6357
+ return;
6358
+ }
4094
6359
  const want = pathnameOf(req.url || "/");
4095
6360
  const canonical = want.replace(/\/+$/, "") || "/";
4096
6361
  if (canonical !== want) {
@@ -4107,8 +6372,8 @@ function serveStatic(dir, isr = false, dev2 = false) {
4107
6372
  return;
4108
6373
  }
4109
6374
  const settled = settleDevBuild();
4110
- const ready = settled ? settled.then(() => loadServer()) : loadServer();
4111
- ready.then(async (ssrModule) => {
6375
+ const ready2 = settled ? settled.then(() => loadServer()) : loadServer();
6376
+ ready2.then(async (ssrModule) => {
4112
6377
  const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true ? await hookContext(req) : null;
4113
6378
  if (hookCtx) {
4114
6379
  const short = await ssrModule.runRequestHooks(hookCtx);
@@ -4140,6 +6405,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4140
6405
  body: body.length > 0 ? body : void 0
4141
6406
  });
4142
6407
  ssrModule.setQuery?.(queryOf(req.url));
6408
+ if ((req.method || "GET") !== "GET") ssrModule.invalidateRenderCache?.();
4143
6409
  let apiRes = await ssrModule.handleApi(req.method || "GET", apiPath, request);
4144
6410
  if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
4145
6411
  writeWebHeaders(apiRes, res);
@@ -4168,6 +6434,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4168
6434
  }
4169
6435
  }
4170
6436
  ssrModule.setQuery?.(queryOf(req.url));
6437
+ ssrModule.invalidateRenderCache?.();
4171
6438
  const page2 = await ssrModule.renderPage(pathnameOf(req.url || "/"), form);
4172
6439
  await sendPage(req, res, ssrModule, hookCtx, page2, pathnameOf(req.url || "/"));
4173
6440
  } catch (err) {
@@ -4180,31 +6447,31 @@ function serveStatic(dir, isr = false, dev2 = false) {
4180
6447
  });
4181
6448
  return;
4182
6449
  }
4183
- let safe = path3.normalize(pathnameOf(req.url || "/")).replace(/^(\.\.(\/)?)+/, "");
6450
+ let safe = path4.normalize(pathnameOf(req.url || "/")).replace(/^(\.\.(\/)?)+/, "");
4184
6451
  if (safe === "\\" || safe === "/") safe = "/";
4185
- let filePath = path3.join(dir, safe);
4186
- if (!fs3.existsSync(filePath) && ASSET_EXT.has(path3.extname(safe).toLowerCase())) {
4187
- const pubFile = path3.join(dir, "public", safe);
4188
- if (fs3.existsSync(pubFile)) filePath = pubFile;
6452
+ let filePath2 = path4.join(dir, safe);
6453
+ if (!fs5.existsSync(filePath2) && ASSET_EXT.has(path4.extname(safe).toLowerCase())) {
6454
+ const pubFile = path4.join(dir, "public", safe);
6455
+ if (fs5.existsSync(pubFile)) filePath2 = pubFile;
4189
6456
  }
4190
- if (fs3.existsSync(filePath) && fs3.statSync(filePath).isDirectory()) {
4191
- filePath = path3.join(filePath, "index.html");
6457
+ if (fs5.existsSync(filePath2) && fs5.statSync(filePath2).isDirectory()) {
6458
+ filePath2 = path4.join(filePath2, "index.html");
4192
6459
  }
4193
6460
  if (/\.(?:br|gz)$/i.test(safe)) {
4194
- const base = filePath.replace(/\.(?:br|gz)$/i, "");
4195
- if (fs3.existsSync(base)) filePath = base;
6461
+ const base = filePath2.replace(/\.(?:br|gz)$/i, "");
6462
+ if (fs5.existsSync(base)) filePath2 = base;
4196
6463
  }
4197
- const isAsset = ASSET_EXT.has(path3.extname(safe).toLowerCase());
6464
+ const isAsset = ASSET_EXT.has(path4.extname(safe).toLowerCase());
4198
6465
  const isDynamic = !isAsset && ssrModule.dynamicRoutes?.includes(pathnameOf(req.url));
4199
- if (!isDynamic && fs3.existsSync(filePath) && fs3.statSync(filePath).isFile()) {
4200
- const st = fs3.statSync(filePath);
6466
+ if (!isDynamic && fs5.existsSync(filePath2) && fs5.statSync(filePath2).isFile()) {
6467
+ const st = fs5.statSync(filePath2);
4201
6468
  const rev = isAsset ? void 0 : (ssrModule.revalidate || []).find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
4202
6469
  if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1e3) {
4203
- revalidateInBackground(pathnameOf(req.url), filePath);
6470
+ revalidateInBackground(pathnameOf(req.url), filePath2);
4204
6471
  }
4205
- let entry = fileCache.get(filePath);
6472
+ let entry = fileCache.get(filePath2);
4206
6473
  if (!entry || entry.mtimeMs !== st.mtimeMs) {
4207
- const raw = fs3.readFileSync(filePath);
6474
+ const raw = fs5.readFileSync(filePath2);
4208
6475
  entry = {
4209
6476
  mtimeMs: st.mtimeMs,
4210
6477
  raw,
@@ -4212,9 +6479,9 @@ function serveStatic(dir, isr = false, dev2 = false) {
4212
6479
  gzip: zlib.gzipSync(raw, { level: 9 }),
4213
6480
  etag: `W/"${st.size}-${st.mtimeMs}"`
4214
6481
  };
4215
- fileCache.set(filePath, entry);
6482
+ fileCache.set(filePath2, entry);
4216
6483
  }
4217
- const ext = path3.extname(filePath);
6484
+ const ext = path4.extname(filePath2);
4218
6485
  const types = {
4219
6486
  ".html": "text/html",
4220
6487
  ".js": "application/javascript",
@@ -4229,7 +6496,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4229
6496
  };
4230
6497
  const fileHeaders = {
4231
6498
  "Content-Type": types[ext] || "application/octet-stream",
4232
- "Cache-Control": rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : "public, max-age=3600",
6499
+ "Cache-Control": devMode ? "no-cache" : rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : "public, max-age=3600",
4233
6500
  "ETag": entry.etag,
4234
6501
  "Vary": "Accept-Encoding"
4235
6502
  };
@@ -4259,7 +6526,7 @@ function serveStatic(dir, isr = false, dev2 = false) {
4259
6526
  }
4260
6527
  let broken = /* @__PURE__ */ new Set();
4261
6528
  try {
4262
- broken = new Set(JSON.parse(fs3.readFileSync(path3.join(dir, "broken.json"), "utf-8")));
6529
+ broken = new Set(JSON.parse(fs5.readFileSync(path4.join(dir, "broken.json"), "utf-8")));
4263
6530
  } catch {
4264
6531
  }
4265
6532
  const safe2 = pathnameOf(req.url || "/");
@@ -4303,7 +6570,8 @@ function serveStatic(dir, isr = false, dev2 = false) {
4303
6570
  done();
4304
6571
  return;
4305
6572
  }
4306
- const page = await ssrModule.renderPage(safe2);
6573
+ const hasQuery = (req.url || "").includes("?");
6574
+ const page = req.method === "GET" && !hasQuery && ssrModule.renderPageCached ? await ssrModule.renderPageCached(safe2, String(req.headers.cookie || "")) : await ssrModule.renderPage(safe2);
4307
6575
  await sendPage(req, res, ssrModule, hookCtx, page, safe2);
4308
6576
  }).catch((err) => {
4309
6577
  console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
@@ -4313,10 +6581,19 @@ function serveStatic(dir, isr = false, dev2 = false) {
4313
6581
  }
4314
6582
  res.statusCode = 500;
4315
6583
  res.setHeader("Content-Type", "text/html; charset=utf-8");
4316
- res.end("<h1>500</h1><p>Something went wrong rendering this page.</p>");
6584
+ const devErr = err;
6585
+ let devDetail = "";
6586
+ if (process.env.rosetack_DEV === "1" && err) {
6587
+ const stack = err instanceof Error ? (err.stack || "").split("\n").slice(1, 7).join("\n") : "";
6588
+ devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word"><div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + escapeHtml(req.url || "") + '</div><div style="margin:10px 0 0;color:#ffd479">' + escapeHtml(err instanceof Error ? err.message : err) + "</div>" + (devErr.file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + escapeHtml(devErr.file) + (devErr.line != null ? ":" + devErr.line : "") + "</div>" : "") + (devErr.hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + escapeHtml(devErr.hint) + "</div>" : "") + (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + escapeHtml(stack) + "</pre>" : "") + "</div>";
6589
+ }
6590
+ res.end("<h1>500</h1><p>Something went wrong rendering this page.</p>" + devDetail);
4317
6591
  });
4318
6592
  };
4319
6593
  }
6594
+ function escapeHtml(v) {
6595
+ return String(v ?? "").replace(/[<>&"]/g, (ch) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;" })[ch]);
6596
+ }
4320
6597
  function pathnameOf(url) {
4321
6598
  try {
4322
6599
  return new URL(url || "/", "http://localhost").pathname;
@@ -4336,21 +6613,26 @@ function queryOf(url) {
4336
6613
  }
4337
6614
  function listenFree(server, port, onReady) {
4338
6615
  const attempt = (p) => {
4339
- const onError = (err) => {
6616
+ const cleanup = () => {
4340
6617
  server.removeListener("error", onError);
6618
+ server.removeListener("listening", onListening);
6619
+ };
6620
+ const onError = (err) => {
6621
+ cleanup();
4341
6622
  if (err && err.code === "EADDRINUSE" && p - port < 20) {
4342
- console.log(`\u{1F339} port ${p} is in use - trying ${p + 1}`);
4343
6623
  attempt(p + 1);
4344
6624
  return;
4345
6625
  }
4346
6626
  console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
4347
6627
  process.exit(1);
4348
6628
  };
4349
- server.once("error", onError);
4350
- server.listen(p, () => {
4351
- server.removeListener("error", onError);
6629
+ const onListening = () => {
6630
+ cleanup();
4352
6631
  onReady(p);
4353
- });
6632
+ };
6633
+ server.once("error", onError);
6634
+ server.once("listening", onListening);
6635
+ server.listen(p);
4354
6636
  };
4355
6637
  attempt(port);
4356
6638
  }
@@ -4369,7 +6651,7 @@ async function freePort(from) {
4369
6651
  function version() {
4370
6652
  for (const rel of ["../FRAMEWORK_VERSION", "../../FRAMEWORK_VERSION", "../../package.json", "../package.json"]) {
4371
6653
  try {
4372
- const raw = fs3.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8");
6654
+ const raw = fs5.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8");
4373
6655
  const v = rel.endsWith("FRAMEWORK_VERSION") ? raw.trim() : JSON.parse(raw).version;
4374
6656
  if (v) return v;
4375
6657
  } catch {
@@ -4379,7 +6661,7 @@ function version() {
4379
6661
  }
4380
6662
  function projectTag() {
4381
6663
  try {
4382
- const pkg = JSON.parse(fs3.readFileSync(path3.join(process.cwd(), "package.json"), "utf-8"));
6664
+ const pkg = JSON.parse(fs5.readFileSync(path4.join(process.cwd(), "package.json"), "utf-8"));
4383
6665
  if (!pkg.version || pkg.name === "rosetack") return "";
4384
6666
  return ` - project: ${pkg.name} v${pkg.version}`;
4385
6667
  } catch {
@@ -4387,6 +6669,8 @@ function projectTag() {
4387
6669
  }
4388
6670
  }
4389
6671
  async function dev() {
6672
+ devMode = true;
6673
+ process.env.rosetack_DEV = "1";
4390
6674
  console.log(`\u{1F339} RoseTack v${version()}${projectTag()} dev server starting...`);
4391
6675
  try {
4392
6676
  await build2();
@@ -4394,7 +6678,7 @@ async function dev() {
4394
6678
  console.error("Initial build failed (server still running):", err instanceof Error ? err.message : err);
4395
6679
  }
4396
6680
  let timeout;
4397
- fs3.watch(SRC_DIR, { recursive: true }, () => {
6681
+ fs5.watch(SRC_DIR, { recursive: true }, () => {
4398
6682
  devBuildPending = true;
4399
6683
  clearTimeout(timeout);
4400
6684
  timeout = setTimeout(() => {
@@ -4416,14 +6700,14 @@ async function preview() {
4416
6700
  });
4417
6701
  }
4418
6702
  async function serve() {
4419
- if (!fs3.existsSync(path3.join(OUT_DIR2, "server.js"))) {
6703
+ if (!fs5.existsSync(path4.join(OUT_DIR2, "server.js"))) {
4420
6704
  console.error(`rosetack: ${OUT_DIR2} has no server.js - run rosetack build first`);
4421
6705
  process.exit(1);
4422
6706
  }
4423
6707
  const cluster = (await import("node:cluster")).default;
4424
6708
  cluster.schedulingPolicy = cluster.SCHED_RR;
4425
- const os = await import("node:os");
4426
- const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
6709
+ const os2 = await import("node:os");
6710
+ const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os2.cpus().length);
4427
6711
  if (cluster.isPrimary) {
4428
6712
  const port = await freePort(Number(process.env.PORT) || 3e3);
4429
6713
  for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
@@ -4468,12 +6752,115 @@ async function serve() {
4468
6752
  }
4469
6753
  };
4470
6754
  try {
4471
- await loadServer();
6755
+ const hooksMod = await loadServer();
6756
+ invalidateHook = () => {
6757
+ try {
6758
+ hooksMod.invalidateRenderCache();
6759
+ } catch {
6760
+ }
6761
+ };
4472
6762
  } catch (err) {
4473
6763
  console.error("rosetack: dist/server.js failed to load for the serve hooks:", err instanceof Error ? err.message : String(err));
4474
6764
  }
4475
6765
  const http = await import("node:http");
4476
- const server = http.createServer(withAccessLog(serveStatic(OUT_DIR2, true), `w${process.pid}`));
6766
+ const edgeReady = createEdgeHandler(OUT_DIR2);
6767
+ edgeReady.then(async (handle) => {
6768
+ await ready;
6769
+ for (const r of serverModule?.dynamicRoutes || []) {
6770
+ if (r.includes(":")) continue;
6771
+ try {
6772
+ const res = await handle(new Request("http://localhost" + r));
6773
+ await res.arrayBuffer();
6774
+ } catch {
6775
+ }
6776
+ }
6777
+ }).catch(() => {
6778
+ });
6779
+ const baseHandler = withAccessLog(serveStatic(OUT_DIR2, true), `w${process.pid}`);
6780
+ const earlyHintLinks = (() => {
6781
+ try {
6782
+ const html = fs5.readFileSync(path4.join(OUT_DIR2, "index.html"), "utf8");
6783
+ const links = [];
6784
+ for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
6785
+ const v = `<${m[1]}>; rel=preload; as=script`;
6786
+ if (!links.includes(v)) links.push(v);
6787
+ }
6788
+ for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
6789
+ const href = /href="([^"]+)"/.exec(m[0])?.[1];
6790
+ if (href) {
6791
+ const v = `<${href}>; rel=preload; as=style`;
6792
+ if (!links.includes(v)) links.push(v);
6793
+ }
6794
+ }
6795
+ for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
6796
+ const v = `<${m[1]}>; rel=preload; as=style`;
6797
+ if (!links.includes(v)) links.push(v);
6798
+ }
6799
+ return links;
6800
+ } catch {
6801
+ return [];
6802
+ }
6803
+ })();
6804
+ let dynRouteSet = null;
6805
+ const dynRoutesOf = () => {
6806
+ const list = serverModule?.dynamicRoutes || [];
6807
+ if (!dynRouteSet || dynRouteSet.size !== list.length) dynRouteSet = new Set(list);
6808
+ return dynRouteSet;
6809
+ };
6810
+ const server = http.createServer(async (req, res) => {
6811
+ let bytesWritten = 0;
6812
+ const started = process.hrtime.bigint();
6813
+ try {
6814
+ if ((req.method === "GET" || req.method === "HEAD") && dynRoutesOf().has(pathnameOf(req.url || "/"))) {
6815
+ const handle = await edgeReady;
6816
+ if (earlyHintLinks.length && req.method === "GET" && String(req.headers.accept ?? "").includes("text/html")) {
6817
+ try {
6818
+ res.writeEarlyHints({ link: earlyHintLinks });
6819
+ } catch {
6820
+ }
6821
+ }
6822
+ const url = requestOrigin(req, PORT) + (req.url || "/");
6823
+ const response = await handle(new Request(url, { method: req.method, headers: req.headers }));
6824
+ const access = () => writeAccessLine(req, res, bytesWritten, `w${process.pid}`, started);
6825
+ res.statusCode = response.status;
6826
+ response.headers.forEach((v, k) => res.setHeader(k, v));
6827
+ const htmlDoc = (response.headers.get("content-type") ?? "").startsWith("text/html");
6828
+ const enc = htmlDoc && req.method === "GET" ? pickEncoding(req) : null;
6829
+ if (response.body && enc) {
6830
+ const raw = Buffer.from(await response.arrayBuffer());
6831
+ const etag = 'W/"' + createHash2("sha1").update(raw).digest("base64url").slice(0, 24) + '"';
6832
+ if (req.headers["if-none-match"] === etag) {
6833
+ res.statusCode = 304;
6834
+ bytesWritten = 0;
6835
+ res.end();
6836
+ access();
6837
+ return;
6838
+ }
6839
+ const body = compress(enc, raw);
6840
+ res.setHeader("ETag", etag);
6841
+ res.setHeader("Content-Encoding", enc);
6842
+ res.setHeader("Content-Length", String(body.length));
6843
+ res.end(body);
6844
+ bytesWritten = body.length;
6845
+ access();
6846
+ return;
6847
+ }
6848
+ if (response.body) {
6849
+ const raw = Buffer.from(await response.arrayBuffer());
6850
+ bytesWritten = raw.length;
6851
+ res.end(raw);
6852
+ access();
6853
+ } else {
6854
+ res.end();
6855
+ bytesWritten = 0;
6856
+ access();
6857
+ }
6858
+ return;
6859
+ }
6860
+ } catch {
6861
+ }
6862
+ baseHandler(req, res);
6863
+ });
4477
6864
  server.requestTimeout = 3e4;
4478
6865
  server.headersTimeout = 65e3;
4479
6866
  server.keepAliveTimeout = 5e3;
@@ -4498,7 +6885,9 @@ async function serve() {
4498
6885
  console.error("rosetack: plugin", p.name, "onShutdown failed:", err instanceof Error ? err.message : err);
4499
6886
  }
4500
6887
  }
4501
- server.close(() => process.exit(0));
6888
+ server.close(() => {
6889
+ void runShutdownHooks("worker signal").finally(() => process.exit(0));
6890
+ });
4502
6891
  server.closeIdleConnections?.();
4503
6892
  setTimeout(() => process.exit(0), 5e3).unref();
4504
6893
  };
@@ -4508,14 +6897,14 @@ async function serve() {
4508
6897
  function templatesDir() {
4509
6898
  for (const rel of ["../../templates", "../templates"]) {
4510
6899
  const p = fileURLToPath2(new URL(rel, import.meta.url));
4511
- if (fs3.existsSync(p)) return p;
6900
+ if (fs5.existsSync(p)) return p;
4512
6901
  }
4513
6902
  return null;
4514
6903
  }
4515
6904
  function writeTypeScriptReady(dir) {
4516
- fs3.writeFileSync(path3.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
6905
+ fs5.writeFileSync(path4.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
4517
6906
  `);
4518
- fs3.writeFileSync(path3.join(dir, "tsconfig.json"), JSON.stringify({
6907
+ fs5.writeFileSync(path4.join(dir, "tsconfig.json"), JSON.stringify({
4519
6908
  compilerOptions: {
4520
6909
  target: "ES2022",
4521
6910
  module: "ESNext",
@@ -4530,27 +6919,27 @@ function writeTypeScriptReady(dir) {
4530
6919
  }
4531
6920
  function copyTemplate(dir, name, display) {
4532
6921
  const base = templatesDir();
4533
- const shipped = base ? path3.resolve(base, name) : "";
4534
- const src = fs3.existsSync(shipped) ? shipped : path3.resolve(name);
4535
- if (!fs3.existsSync(src) || !fs3.statSync(src).isDirectory()) {
4536
- const available = base ? fs3.readdirSync(base).join(", ") : "(none found)";
6922
+ const shipped = base ? path4.resolve(base, name) : "";
6923
+ const src = fs5.existsSync(shipped) ? shipped : path4.resolve(name);
6924
+ if (!fs5.existsSync(src) || !fs5.statSync(src).isDirectory()) {
6925
+ const available = base ? fs5.readdirSync(base).join(", ") : "(none found)";
4537
6926
  console.error(`rosetack: no template '${name}' - available: ${available} (or pass a path to any project directory)`);
4538
6927
  process.exit(1);
4539
6928
  }
4540
- fs3.cpSync(src, dir, {
6929
+ fs5.cpSync(src, dir, {
4541
6930
  recursive: true,
4542
6931
  filter: (s) => !/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(s)
4543
6932
  });
4544
- const pkgFile = path3.join(dir, "package.json");
4545
- if (fs3.existsSync(pkgFile)) {
4546
- const pkg = JSON.parse(fs3.readFileSync(pkgFile, "utf8"));
4547
- pkg.name = path3.basename(dir);
6933
+ const pkgFile = path4.join(dir, "package.json");
6934
+ if (fs5.existsSync(pkgFile)) {
6935
+ const pkg = JSON.parse(fs5.readFileSync(pkgFile, "utf8"));
6936
+ pkg.name = path4.basename(dir);
4548
6937
  if (pkg.dependencies?.rosetack) pkg.dependencies.rosetack = `^${version()}`;
4549
6938
  pkg.devDependencies = { ...pkg.devDependencies, typescript: "^5.6.0" };
4550
- fs3.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
6939
+ fs5.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
4551
6940
  }
4552
6941
  writeTypeScriptReady(dir);
4553
- console.log(`\u{1F339} RoseTack new: ${display}/ from the '${path3.basename(src)}' template`);
6942
+ console.log(`\u{1F339} RoseTack new: ${display}/ from the '${path4.basename(src)}' template`);
4554
6943
  console.log(`
4555
6944
  cd ${display}`);
4556
6945
  console.log(` npm install && npm run dev`);
@@ -4562,12 +6951,12 @@ async function scaffold() {
4562
6951
  const template = tplIdx >= 0 ? args[tplIdx + 1] : null;
4563
6952
  const name = args.find((a, i) => !a.startsWith("-") && i !== (tplIdx >= 0 ? tplIdx + 1 : -1));
4564
6953
  if (!name || tplIdx >= 0 && !template) {
4565
- const available = templatesDir() ? fs3.readdirSync(templatesDir()).join(", ") : "blog, api, admin, site";
6954
+ const available = templatesDir() ? fs5.readdirSync(templatesDir()).join(", ") : "blog, api, admin, site";
4566
6955
  console.log(`Usage: rosetack new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${available} - or any project directory)`);
4567
6956
  return;
4568
6957
  }
4569
- const dir = path3.resolve(name);
4570
- if (fs3.existsSync(dir)) {
6958
+ const dir = path4.resolve(name);
6959
+ if (fs5.existsSync(dir)) {
4571
6960
  console.error(`rosetack: ${dir} already exists - pick another name`);
4572
6961
  process.exit(1);
4573
6962
  }
@@ -4575,10 +6964,10 @@ async function scaffold() {
4575
6964
  copyTemplate(dir, template, name);
4576
6965
  return;
4577
6966
  }
4578
- const pages = path3.join(dir, "src", "pages");
4579
- fs3.mkdirSync(pages, { recursive: true });
4580
- fs3.writeFileSync(path3.join(dir, "package.json"), JSON.stringify({
4581
- name: path3.basename(dir),
6967
+ const pages = path4.join(dir, "src", "pages");
6968
+ fs5.mkdirSync(pages, { recursive: true });
6969
+ fs5.writeFileSync(path4.join(dir, "package.json"), JSON.stringify({
6970
+ name: path4.basename(dir),
4582
6971
  private: true,
4583
6972
  type: "module",
4584
6973
  scripts: {
@@ -4592,7 +6981,7 @@ async function scaffold() {
4592
6981
  devDependencies: { typescript: "^5.6.0" }
4593
6982
  }, null, 2) + "\n");
4594
6983
  writeTypeScriptReady(dir);
4595
- fs3.writeFileSync(path3.join(pages, "index.rose"), `<script>
6984
+ fs5.writeFileSync(path4.join(pages, "index.rose"), `<script>
4596
6985
 
4597
6986
  interface Item { label: string }
4598
6987
 
@@ -4625,7 +7014,7 @@ async function scaffold() {
4625
7014
  button { padding: 0.5rem 1rem; margin-right: 0.5rem; }
4626
7015
  </style>
4627
7016
  `);
4628
- fs3.writeFileSync(path3.join(dir, "README.md"), `# ${path3.basename(dir)}
7017
+ fs5.writeFileSync(path4.join(dir, "README.md"), `# ${path4.basename(dir)}
4629
7018
 
4630
7019
  A rosetack project. One file per route in \`src/pages/\`.
4631
7020
 
@@ -4641,7 +7030,7 @@ Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
4641
7030
  \`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
4642
7031
  runs before every request, \`src/pages/api/*.rose\` answers JSON.
4643
7032
  `);
4644
- fs3.writeFileSync(path3.join(dir, ".gitignore"), "node_modules/\ndist/\n");
7033
+ fs5.writeFileSync(path4.join(dir, ".gitignore"), "node_modules/\ndist/\n");
4645
7034
  console.log(`\u{1F339} Created ${dir}`);
4646
7035
  console.log(` src/pages/index.rose - a typed page that builds and runs`);
4647
7036
  console.log(` rosetack-env.d.ts + tsconfig.json - the script globals, typed`);
@@ -4653,29 +7042,29 @@ runs before every request, \`src/pages/api/*.rose\` answers JSON.
4653
7042
  async function check() {
4654
7043
  const files = [...await scanRoseFiles(SRC_DIR), ...await scanComponentFiles(SRC_DIR)];
4655
7044
  if (files.length === 0) {
4656
- console.error(`rosetack: no .rose pages found under ${path3.join(SRC_DIR, "src", "pages")} - run rosetack check from a project root, or pass one: rosetack check <dir>`);
7045
+ console.error(`rosetack: no .rose pages found under ${path4.join(SRC_DIR, "src", "pages")} - run rosetack check from a project root, or pass one: rosetack check <dir>`);
4657
7046
  process.exit(1);
4658
7047
  }
4659
7048
  let tsMod;
4660
7049
  try {
4661
- const req = createRequire(pathToFileURL2(path3.join(SRC_DIR, "package.json")));
4662
- tsMod = await import(pathToFileURL2(req.resolve("typescript")).href);
7050
+ const req = createRequire(pathToFileURL3(path4.join(SRC_DIR, "package.json")));
7051
+ tsMod = await import(pathToFileURL3(req.resolve("typescript")).href);
4663
7052
  } catch {
4664
7053
  console.error(`rosetack: type checking needs typescript in this project - npm i -D typescript`);
4665
7054
  process.exit(1);
4666
7055
  }
4667
- const nextTo = (rel) => rel.map((r) => fileURLToPath2(new URL(r, import.meta.url))).find((p) => fs3.existsSync(p));
7056
+ const nextTo = (rel) => rel.map((r) => fileURLToPath2(new URL(r, import.meta.url))).find((p) => fs5.existsSync(p));
4668
7057
  const typesFile = nextTo(["../types/rosetack.d.ts", "../src/types/rosetack.d.ts"]);
4669
7058
  if (!typesFile) {
4670
7059
  console.error("rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler");
4671
7060
  process.exit(1);
4672
7061
  }
4673
7062
  const runtimeSource = nextTo(["../runtime/index.ts", "../src/runtime/index.ts"]);
4674
- const norm = (f) => path3.resolve(f).replace(/\\/g, "/");
7063
+ const norm = (f) => path4.resolve(f).replace(/\\/g, "/");
4675
7064
  const virtual = /* @__PURE__ */ new Map();
4676
7065
  let checked = 0;
4677
7066
  for (const file of files) {
4678
- const source = await fs3.promises.readFile(file, "utf-8");
7067
+ const source = await fs5.promises.readFile(file, "utf-8");
4679
7068
  const m = /<script>/.exec(source);
4680
7069
  const script = scriptOf(source);
4681
7070
  if (!script) continue;
@@ -4698,12 +7087,12 @@ async function check() {
4698
7087
  const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
4699
7088
  const declared = /* @__PURE__ */ new Set();
4700
7089
  for (const file of [...virtual.keys()]) {
4701
- const script = scriptOf(await fs3.promises.readFile(file, "utf-8").catch(() => ""));
7090
+ const script = scriptOf(await fs5.promises.readFile(file, "utf-8").catch(() => ""));
4702
7091
  if (!script) continue;
4703
7092
  for (const spec of script.matchAll(ROSE_IMPORT_RE)) {
4704
- const target = norm(path3.resolve(path3.dirname(file), spec[1]));
7093
+ const target = norm(path4.resolve(path4.dirname(file), spec[1]));
4705
7094
  if (target === file || declared.has(target)) continue;
4706
- const targetSource = await fs3.promises.readFile(target, "utf-8").catch(() => null);
7095
+ const targetSource = await fs5.promises.readFile(target, "utf-8").catch(() => null);
4707
7096
  if (targetSource === null) continue;
4708
7097
  const props = extractExports(scriptOf(targetSource) ?? "").props;
4709
7098
  virtual.set(`${target}.d.ts`, [
@@ -4726,7 +7115,7 @@ async function check() {
4726
7115
  skipLibCheck: true
4727
7116
  };
4728
7117
  const host = tsMod.createCompilerHost(options);
4729
- host.getCurrentDirectory = () => path3.resolve(SRC_DIR);
7118
+ host.getCurrentDirectory = () => path4.resolve(SRC_DIR);
4730
7119
  const realRead = host.readFile.bind(host);
4731
7120
  const realGet = host.getSourceFile.bind(host);
4732
7121
  host.readFile = (f) => virtual.get(norm(f)) ?? realRead(f);
@@ -4743,7 +7132,7 @@ async function check() {
4743
7132
  }
4744
7133
  for (const d of diagnostics) {
4745
7134
  const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
4746
- const where = d.file && at ? `${path3.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})` : "rosetack";
7135
+ const where = d.file && at ? `${path4.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})` : "rosetack";
4747
7136
  const text = tsMod.flattenDiagnosticMessageText(d.messageText, "\n");
4748
7137
  const kind = d.category === 1 ? "error" : "warning";
4749
7138
  console.error(`${where}: ${kind} TS${d.code}: ${text}`);