rosetack 0.0.0 → 0.1.1

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.
@@ -0,0 +1,3411 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/index.ts
4
+ import * as fs3 from "fs";
5
+ import * as path3 from "path";
6
+ import * as zlib from "zlib";
7
+ import { createRequire } from "module";
8
+ import { pathToFileURL as pathToFileURL2, fileURLToPath as fileURLToPath2 } from "url";
9
+
10
+ // src/compiler/index.ts
11
+ import * as fs from "fs";
12
+ import * as path from "path";
13
+ import { pathToFileURL, fileURLToPath } from "url";
14
+ import * as esbuild from "esbuild";
15
+ var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
16
+ var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
17
+ var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
18
+ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
19
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
20
+ var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
21
+ var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
22
+ var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
23
+ var SLOT_RE = /<slot\s*\/?>/g;
24
+ var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
25
+ function encodeSlotCall(attrs) {
26
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
27
+ if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
28
+ const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
29
+ return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
30
+ }
31
+ var BOUNDARY_FALLBACK = "<p>This section failed to render.</p>";
32
+ var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
33
+ var TS_LOADER = { loader: { ".js": "ts" } };
34
+ function callifyStateReads(script, names) {
35
+ if (names.length === 0) return script;
36
+ const scan = (src) => {
37
+ let out = "";
38
+ let i = 0;
39
+ while (i < src.length) {
40
+ const ch = src[i];
41
+ if (ch === "'" || ch === '"') {
42
+ let j = i + 1;
43
+ while (j < src.length && src[j] !== ch) {
44
+ if (src[j] === "\\") j++;
45
+ j++;
46
+ }
47
+ out += src.slice(i, Math.min(j + 1, src.length));
48
+ i = j + 1;
49
+ continue;
50
+ }
51
+ if (ch === "`") {
52
+ out += ch;
53
+ i++;
54
+ while (i < src.length && src[i] !== "`") {
55
+ if (src[i] === "\\") {
56
+ out += src.slice(i, i + 2);
57
+ i += 2;
58
+ continue;
59
+ }
60
+ if (src[i] === "$" && src[i + 1] === "{") {
61
+ let depth = 1;
62
+ let j = i + 2;
63
+ while (j < src.length && depth > 0) {
64
+ if (src[j] === "{") depth++;
65
+ else if (src[j] === "}") depth--;
66
+ if (depth === 0) break;
67
+ j++;
68
+ }
69
+ out += "${" + scan(src.slice(i + 2, j)) + "}";
70
+ i = j + 1;
71
+ continue;
72
+ }
73
+ out += src[i];
74
+ i++;
75
+ }
76
+ out += "`";
77
+ i++;
78
+ continue;
79
+ }
80
+ if (ch === "/" && src[i + 1] === "/") {
81
+ const nl = src.indexOf("\n", i);
82
+ const end = nl === -1 ? src.length : nl;
83
+ out += src.slice(i, end);
84
+ i = end;
85
+ continue;
86
+ }
87
+ if (ch === "/" && src[i + 1] === "*") {
88
+ const close = src.indexOf("*/", i + 2);
89
+ const end = close === -1 ? src.length : close + 2;
90
+ out += src.slice(i, end);
91
+ i = end;
92
+ continue;
93
+ }
94
+ if (/[A-Za-z_$]/.test(ch)) {
95
+ let j = i;
96
+ while (j < src.length && /[\w$]/.test(src[j])) j++;
97
+ const word = src.slice(i, j);
98
+ const prev = out.length ? out[out.length - 1] : "";
99
+ const next = src[j] ?? "";
100
+ const rewrite = names.includes(word) && !/[\w$.]/.test(prev) && !/[\w$:(]/.test(next);
101
+ out += rewrite ? `${word}()` : word;
102
+ i = j;
103
+ continue;
104
+ }
105
+ out += ch;
106
+ i++;
107
+ }
108
+ return out;
109
+ };
110
+ return scan(script);
111
+ }
112
+ function callifyTemplateExprs(template, names) {
113
+ if (names.length === 0) return template;
114
+ return template.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${callifyStateReads(expr, names)}}`);
115
+ }
116
+ function scriptOf(source) {
117
+ return source.match(COMPONENT_RE)?.[1] ?? null;
118
+ }
119
+ async function loadConfig(root) {
120
+ const file = path.join(root, "rosetack.config.js");
121
+ if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
122
+ const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
123
+ return {
124
+ plugins: mod.default ?? [],
125
+ i18n: mod.i18n ?? {}
126
+ };
127
+ }
128
+ async function loadPlugins(root) {
129
+ return (await loadConfig(root)).plugins;
130
+ }
131
+ function resolveRoseImports(script, fromFile, registry) {
132
+ const imports = [];
133
+ const resolve3 = (spec) => {
134
+ const abs = path.resolve(path.dirname(fromFile), spec);
135
+ const hit = registry.get(abs);
136
+ if (!hit) {
137
+ throw new Error(`${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`);
138
+ }
139
+ return hit;
140
+ };
141
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
142
+ const hit = resolve3(spec);
143
+ imports.push({ name, specifier: spec, index: hit.index });
144
+ return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
145
+ });
146
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
147
+ const hit = resolve3(spec);
148
+ const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
149
+ imports.push({ name: alias, specifier: spec, index: hit.index });
150
+ return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
151
+ });
152
+ return { script: rewritten, imports };
153
+ }
154
+ function rewriteRoseImports(script, kind) {
155
+ return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
156
+ }
157
+ function scanSlotDecls(filePath) {
158
+ let src;
159
+ try {
160
+ src = fs.readFileSync(filePath, "utf-8");
161
+ } catch {
162
+ return [];
163
+ }
164
+ const noBlocks = src.replace(STYLE_RE, "");
165
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
166
+ const out = [];
167
+ for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
168
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
169
+ if (!name) continue;
170
+ const props = [...m[1].matchAll(/\b(\w+)\s*=\s*\{/g)].map((x) => x[1]).filter((n) => n !== "name");
171
+ out.push({ name: name[1], props });
172
+ }
173
+ return out;
174
+ }
175
+ function hoistImports(script) {
176
+ const imports = [];
177
+ const rest = [];
178
+ let buf = null;
179
+ let depth = 0;
180
+ const done = (line) => depth <= 0 && /from\s*['"][^'"]+['"]\s*;?\s*$/.test(line);
181
+ for (const line of script.split("\n")) {
182
+ if (buf) {
183
+ buf.push(line);
184
+ for (const ch of line) {
185
+ if (ch === "{" || ch === "(") depth++;
186
+ else if (ch === "}" || ch === ")") depth--;
187
+ }
188
+ if (done(line)) {
189
+ imports.push(buf.join("\n"));
190
+ buf = null;
191
+ }
192
+ continue;
193
+ }
194
+ if (/^\s*import\b/.test(line)) {
195
+ buf = [line];
196
+ depth = 0;
197
+ for (const ch of line) {
198
+ if (ch === "{" || ch === "(") depth++;
199
+ else if (ch === "}" || ch === ")") depth--;
200
+ }
201
+ if (done(line)) {
202
+ imports.push(line);
203
+ buf = null;
204
+ }
205
+ continue;
206
+ }
207
+ rest.push(line);
208
+ }
209
+ if (buf) imports.push(buf.join("\n"));
210
+ return { imports: imports.join("\n"), rest: rest.join("\n") };
211
+ }
212
+ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
213
+ let source = await fs.promises.readFile(filePath, "utf-8");
214
+ for (const p of plugins) {
215
+ if (!p.transform) continue;
216
+ try {
217
+ source = await p.transform(source, filePath);
218
+ } catch (err) {
219
+ throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
220
+ }
221
+ }
222
+ if (isApi) {
223
+ const scriptMatch2 = source.match(COMPONENT_RE);
224
+ const rawScript2 = scriptMatch2?.[1] ?? "";
225
+ 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));
226
+ const usesContext2 = /getContext\s*\(/.test(rawScript2);
227
+ const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
228
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
229
+ return {
230
+ ssr: "",
231
+ client: "",
232
+ stateKeys: [],
233
+ actionNames: [],
234
+ guardName: null,
235
+ style: "",
236
+ hasParams: false,
237
+ api: `import { getContext } from './runtime.js';
238
+ ${rewriteRoseImports(`${hoisted.imports}
239
+ ${hoisted.rest}`, "ssr").trim()}`,
240
+ apiMethods,
241
+ hasPrerender,
242
+ usesContext: usesContext2
243
+ };
244
+ }
245
+ const styleMatch = source.match(STYLE_RE);
246
+ const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
247
+ const sourceNoBlocks = source.replace(STYLE_RE, "");
248
+ const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
249
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
250
+ const rawScript = roseResolved.script;
251
+ const roseImports = roseResolved.imports;
252
+ const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
253
+ const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
254
+ if (isComponent && /\$data\s*\(/.test(rawScript)) {
255
+ throw new Error(
256
+ `${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()}>.`
257
+ );
258
+ }
259
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
260
+ const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
261
+ const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
262
+ const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
263
+ const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
264
+ const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
265
+ if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
266
+ throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
267
+ }
268
+ const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
269
+ const bundle = bundleMatch ? bundleMatch[1] : void 0;
270
+ if (bundle && !["inline", "split"].includes(bundle)) {
271
+ throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
272
+ }
273
+ const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
274
+ const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
275
+ if (csr === false) {
276
+ const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
277
+ if (dead) {
278
+ throw new Error(
279
+ `${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.)`
280
+ );
281
+ }
282
+ }
283
+ let headers;
284
+ const headersLiteral = extractObjectLiteral(rawScript, "headers");
285
+ if (headersLiteral) {
286
+ let value;
287
+ try {
288
+ value = new Function(`return ${headersLiteral}`)();
289
+ } catch {
290
+ throw new Error(`${filePath}: export const headers must be an object literal`);
291
+ }
292
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
293
+ throw new Error(`${filePath}: export const headers must be a flat map of string -> string`);
294
+ }
295
+ headers = value;
296
+ }
297
+ let cspNonce;
298
+ const cspLiteral = extractObjectLiteral(rawScript, "csp");
299
+ if (cspLiteral) {
300
+ let value;
301
+ try {
302
+ value = new Function(`return ${cspLiteral}`)();
303
+ } catch {
304
+ throw new Error(`${filePath}: export const csp must be an object literal`);
305
+ }
306
+ const nonce = value?.nonce;
307
+ if (nonce !== void 0 && typeof nonce !== "boolean") {
308
+ throw new Error(`${filePath}: csp.nonce must be a boolean`);
309
+ }
310
+ cspNonce = nonce === true;
311
+ }
312
+ const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
313
+ const script = scriptNoExports;
314
+ const actionNames = new Set(actions.map((a) => a.name));
315
+ const clientReasons = [];
316
+ if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
317
+ if (/<form[\s>]/.test(source)) clientReasons.push("a <form> (its in-place adopt is the enhancement)");
318
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
319
+ if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
320
+ if (actionNames.size > 0) {
321
+ clientReasons.push(`server action${actionNames.size > 1 ? "s" : ""} (${[...actionNames].join(", ")})`);
322
+ }
323
+ const needsClient = clientReasons.length > 0;
324
+ const jsWarnings = [];
325
+ if (!needsClient) {
326
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
327
+ jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
328
+ }
329
+ if (/javascript:/i.test(source)) {
330
+ jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
331
+ }
332
+ if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
333
+ jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
334
+ }
335
+ if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(rawScript)) {
336
+ jsWarnings.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true");
337
+ }
338
+ }
339
+ const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
340
+ const headMatch = sourceNoBlocks.match(HEAD_RE);
341
+ const headContent = headMatch?.[1] ?? "";
342
+ const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, "");
343
+ const rawTemplate = templateMatch ? templateMatch[1] : sourceNoHead.replace(COMPONENT_RE, "").trim();
344
+ const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
345
+ const decls = extractDecls(script);
346
+ const stateDecls = decls.filter((d) => d.kind === "state");
347
+ const setterNames = /* @__PURE__ */ new Map();
348
+ stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
349
+ const eventBindings = [];
350
+ let em;
351
+ EVENT_RE.lastIndex = 0;
352
+ while (em = EVENT_RE.exec(template)) {
353
+ if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
354
+ }
355
+ let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end]));
356
+ cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
357
+ const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
358
+ const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
359
+ return `${setter}(${val})`;
360
+ });
361
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
362
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
363
+ const ssrTemplate = templateCalled.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}").replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) => actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
364
+ const stateDeclsCode = decls.map((d) => {
365
+ const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
366
+ if (d.kind === "state") {
367
+ return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
368
+ }
369
+ const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
370
+ const fn = isFn ? d.expr : `() => (${d.expr})`;
371
+ return `const __had_${d.name} = hasState(${JSON.stringify(key)});
372
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
373
+ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
374
+ }).join("\n");
375
+ const stateKeys = decls.map((d) => d.name);
376
+ const comps = new Map(roseImports.map((r) => {
377
+ const abs = path.resolve(path.dirname(filePath), r.specifier);
378
+ const hit = registry.get(abs);
379
+ return [r.name, { index: hit.index, slots: hit.slots }];
380
+ }));
381
+ const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
382
+ const compiledHead = headContent.trim() ? compileTemplate(headContent, "__hd", "__hc", null, 0, false) : "";
383
+ const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
384
+ const ssrExports = actions.length > 0 ? `${exportStmts}
385
+ ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
386
+ const ssrGuard = guard ? `
387
+ ${guard}` : "";
388
+ const isMiddleware = path.basename(filePath) === "_middleware.rose";
389
+ const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
390
+
391
+ ${importStmts}
392
+
393
+ ${ssrExports}
394
+ ${ssrGuard}
395
+
396
+ ${cleanScript}
397
+ ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
398
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
399
+ return {
400
+ ssr: rewriteRoseImports(ssr, "ssr"),
401
+ client: rewriteRoseImports(client, "client"),
402
+ stateKeys,
403
+ actionNames: [...actionNames],
404
+ guardName: guard ? "beforeAction" : null,
405
+ style: scopedStyle,
406
+ hasParams,
407
+ usesContext,
408
+ revalidate,
409
+ csr,
410
+ prefetch,
411
+ bundle,
412
+ needsClient,
413
+ clientReasons,
414
+ jsWarnings,
415
+ headers,
416
+ cspNonce,
417
+ props,
418
+ roseImports,
419
+ isComponent
420
+ };
421
+ }
422
+ function minifyDecls(block) {
423
+ return block.replace(
424
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
425
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
426
+ ).trim();
427
+ }
428
+ function scopeCss(css, key) {
429
+ const attr = `[data-rosetack-c="${key}"]`;
430
+ const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
431
+ let out = "";
432
+ let prelude = "";
433
+ let i = 0;
434
+ while (i < clean.length) {
435
+ const ch = clean[i];
436
+ if (ch === "{") {
437
+ let depth = 1;
438
+ let j = i + 1;
439
+ while (j < clean.length && depth > 0) {
440
+ if (clean[j] === "{") depth++;
441
+ else if (clean[j] === "}") depth--;
442
+ j++;
443
+ }
444
+ const block = clean.slice(i + 1, j - 1);
445
+ const sel = prelude.trim();
446
+ if (sel.startsWith("@")) {
447
+ out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
448
+ } else if (sel) {
449
+ const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
450
+ out += `${scoped}{${minifyDecls(block)}}`;
451
+ }
452
+ prelude = "";
453
+ i = j;
454
+ continue;
455
+ }
456
+ if (ch !== "}" && ch !== "\n" && ch !== "\r") prelude += ch;
457
+ else if (ch === "}") prelude = "";
458
+ i++;
459
+ }
460
+ return out.trim();
461
+ }
462
+ function injectScopeAttr(template, key) {
463
+ const attr = ` data-rosetack-c="${key}"`;
464
+ let out = "";
465
+ let depth = 0;
466
+ let i = 0;
467
+ while (i < template.length) {
468
+ const lt = template.indexOf("<", i);
469
+ if (lt === -1) {
470
+ out += template.slice(i);
471
+ break;
472
+ }
473
+ out += template.slice(i, lt);
474
+ let j = lt + 1;
475
+ let quote = "";
476
+ while (j < template.length) {
477
+ const c = template[j];
478
+ if (quote) {
479
+ if (c === quote) quote = "";
480
+ } else if (c === '"' || c === "'") quote = c;
481
+ else if (c === ">") break;
482
+ j++;
483
+ }
484
+ const tagText = template.slice(lt, j + 1);
485
+ const closing = /^<\//.test(tagText);
486
+ const nameMatch = tagText.match(/^<\/?([a-zA-Z][\w-]*)/);
487
+ const selfClosing = /\/>$/.test(tagText) || nameMatch && VOID_TAGS.has(nameMatch[1].toLowerCase());
488
+ if (nameMatch && !closing && depth === 0 && !selfClosing) {
489
+ const injectAt = tagText.endsWith("/>") ? tagText.length - 2 : tagText.length - 1;
490
+ out += tagText.slice(0, injectAt) + attr + tagText.slice(injectAt);
491
+ depth++;
492
+ } else {
493
+ out += tagText;
494
+ if (nameMatch) depth += closing ? -1 : selfClosing ? 0 : 1;
495
+ }
496
+ i = j + 1;
497
+ }
498
+ return out;
499
+ }
500
+ var VOID_TAGS = /* @__PURE__ */ new Set(["img", "br", "hr", "input", "meta", "link", "source", "wbr"]);
501
+ var EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
502
+ function extractObjectLiteral(script, name) {
503
+ const m = new RegExp(`(?:^|\\n)\\s*export\\s+(?:const|let|var)\\s+${name}\\s*=\\s*`).exec(script);
504
+ if (!m) return null;
505
+ let i = m.index + m[0].length;
506
+ if (script[i] !== "{") return null;
507
+ const start = i;
508
+ let depth = 0;
509
+ for (; i < script.length; i++) {
510
+ const ch = script[i];
511
+ if (ch === "{") depth++;
512
+ else if (ch === "}") {
513
+ depth--;
514
+ if (depth === 0) {
515
+ i++;
516
+ break;
517
+ }
518
+ }
519
+ }
520
+ return script.slice(start, i);
521
+ }
522
+ function extractExports(script) {
523
+ const stmts = [];
524
+ const actions = [];
525
+ const props = [];
526
+ const guards = [];
527
+ let out = "";
528
+ let pos = 0;
529
+ let m;
530
+ EXPORT_RE.lastIndex = 0;
531
+ while (m = EXPORT_RE.exec(script)) {
532
+ const kind = m[1];
533
+ const start = m.index + m[0].indexOf("export");
534
+ let i = start + m[0].length - m[0].indexOf("export");
535
+ if (kind) {
536
+ let depth = 0;
537
+ while (i < script.length) {
538
+ const ch = script[i];
539
+ if (ch === "(" || ch === "{" || ch === "[") depth++;
540
+ else if (ch === ")" || ch === "}" || ch === "]") {
541
+ depth--;
542
+ if (depth === 0) {
543
+ i++;
544
+ break;
545
+ }
546
+ } else if (depth === 0 && ch === ";") {
547
+ i++;
548
+ break;
549
+ } else if (depth === 0 && ch === "\n") {
550
+ const rest = script.slice(i + 1);
551
+ if (!/^\s*[.([{+\-*/?:,=&|]/.test(rest)) {
552
+ i++;
553
+ break;
554
+ }
555
+ }
556
+ i++;
557
+ }
558
+ if (script[i] === ";") i++;
559
+ } else {
560
+ while (i < script.length && script[i] !== "{") i++;
561
+ let depth = 0;
562
+ while (i < script.length) {
563
+ const ch = script[i];
564
+ if (ch === "{") depth++;
565
+ else if (ch === "}") {
566
+ depth--;
567
+ if (depth === 0) {
568
+ i++;
569
+ break;
570
+ }
571
+ }
572
+ i++;
573
+ }
574
+ }
575
+ out += script.slice(pos, start);
576
+ const stmt = script.slice(start, i).trim();
577
+ const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
578
+ const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
579
+ if (anyFn?.[1] === "beforeAction") {
580
+ guards.push(stmt);
581
+ } else if (asyncFn) {
582
+ actions.push({ name: asyncFn[1], stmt });
583
+ } else if (kind === "let") {
584
+ const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
585
+ if (pm) props.push({ name: pm[1], def: pm[2]?.trim() ?? null });
586
+ else stmts.push(stmt);
587
+ } else {
588
+ stmts.push(stmt);
589
+ }
590
+ pos = i;
591
+ }
592
+ out += script.slice(pos);
593
+ return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
594
+ }
595
+ function extractDecls(script) {
596
+ const decls = [];
597
+ DECL_RE.lastIndex = 0;
598
+ let m;
599
+ while (m = DECL_RE.exec(script)) {
600
+ let j = m.index + m[0].length;
601
+ const skipSpace = () => {
602
+ while (j < script.length && /\s/.test(script[j])) j++;
603
+ };
604
+ skipSpace();
605
+ if (script[j] === "<") {
606
+ let depth2 = 0;
607
+ while (j < script.length) {
608
+ const ch = script[j];
609
+ if (ch === "<") depth2++;
610
+ else if (ch === ">" && script[j - 1] !== "=") {
611
+ depth2--;
612
+ if (depth2 === 0) {
613
+ j++;
614
+ break;
615
+ }
616
+ } else if (ch === "=" && script[j + 1] === ">") j++;
617
+ j++;
618
+ }
619
+ skipSpace();
620
+ }
621
+ if (script[j] !== "(") continue;
622
+ const open = j + 1;
623
+ let depth = 1;
624
+ let i = open;
625
+ while (i < script.length && depth > 0) {
626
+ const ch = script[i];
627
+ if (ch === "(") depth++;
628
+ else if (ch === ")") depth--;
629
+ i++;
630
+ }
631
+ let end = i;
632
+ const cast = DECL_CAST_RE.exec(script.slice(i));
633
+ if (cast) end = i + cast[0].length;
634
+ if (script[end] === ";") end++;
635
+ decls.push({
636
+ name: m[1],
637
+ kind: m[2],
638
+ expr: script.slice(open, i - 1).trim(),
639
+ start: m.index,
640
+ end
641
+ });
642
+ }
643
+ return decls;
644
+ }
645
+ function removeRanges(text, ranges) {
646
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
647
+ let out = "";
648
+ let pos = 0;
649
+ for (const [start, end] of sorted) {
650
+ out += text.slice(pos, start);
651
+ pos = end;
652
+ }
653
+ out += text.slice(pos);
654
+ return out;
655
+ }
656
+ function autoCall(expr) {
657
+ const e = expr.trim();
658
+ return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
659
+ }
660
+ function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
661
+ let result = "";
662
+ let remaining = template;
663
+ let blockId = 0;
664
+ const nextId = () => `${depth}_${blockId++}`;
665
+ while (remaining.length > 0) {
666
+ const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/);
667
+ const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/);
668
+ const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/);
669
+ const exprMatch = remaining.match(/\{([^{}]+)\}/);
670
+ const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
671
+ const candidates = [];
672
+ if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
673
+ if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
674
+ if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
675
+ if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
676
+ if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
677
+ const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
678
+ if (!earliest) {
679
+ result += emitChunk(remaining, acc, closes, scope);
680
+ break;
681
+ }
682
+ if (earliest.type === "if") {
683
+ const [, cond, content] = earliest.match;
684
+ const before = remaining.substring(0, earliest.index);
685
+ if (before) result += emitChunk(before, acc, closes, scope);
686
+ const call = autoCall(cond);
687
+ const id = nextId();
688
+ const innerScope = scope ?? "__s";
689
+ const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, markers, comps);
690
+ result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
691
+ `;
692
+ if (markers) {
693
+ result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
694
+ `;
695
+ } else {
696
+ result += `${acc} += (${call}) ? __b${id}(${scope ?? "undefined"}, []) : '';
697
+ `;
698
+ }
699
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
700
+ } else if (earliest.type === "each") {
701
+ const [, items, item, content] = earliest.match;
702
+ const before = remaining.substring(0, earliest.index);
703
+ if (before) result += emitChunk(before, acc, closes, scope);
704
+ const call = autoCall(items);
705
+ const id = nextId();
706
+ const itemRe = new RegExp(`\\b${item}\\b`, "g");
707
+ const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(itemRe, "__s")}}`);
708
+ const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
709
+ result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
710
+ `;
711
+ if (markers) {
712
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
713
+ `;
714
+ } else {
715
+ result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');
716
+ `;
717
+ }
718
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
719
+ } else if (earliest.type === "boundary") {
720
+ const [, content] = earliest.match;
721
+ const before = remaining.substring(0, earliest.index);
722
+ if (before) result += emitChunk(before, acc, closes, scope);
723
+ const id = nextId();
724
+ const catchesAction = /\$action:|<form[\s>]/.test(content);
725
+ const inner = compileTemplate(content.trim(), "h", closes, scope, depth + 1, markers, comps);
726
+ result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
727
+ `;
728
+ result += `let __bd${id} = '';
729
+ `;
730
+ result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
731
+ ` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
732
+ `;
733
+ result += `${acc} += __bd${id};
734
+ `;
735
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
736
+ } else if (earliest.type === "comp") {
737
+ const tag = earliest.tag;
738
+ if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
739
+ const entry = comps.get(tag.name);
740
+ const id = nextId();
741
+ let childrenSrc = "";
742
+ let rest;
743
+ if (tag.selfClosing) {
744
+ rest = remaining.substring(tag.end);
745
+ } else {
746
+ const closeIdx = findClose(remaining, tag.end, tag.name);
747
+ if (closeIdx < 0) throw new Error(`unclosed <${tag.name}> - every component tag needs its matching close tag`);
748
+ childrenSrc = remaining.substring(tag.end, closeIdx);
749
+ rest = remaining.substring(closeIdx + tag.name.length + 3);
750
+ }
751
+ const { def, named } = splitSlots(childrenSrc);
752
+ const hasChildren = def.trim().length > 0;
753
+ if (hasChildren) {
754
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, markers, comps)} return h; };
755
+ `;
756
+ }
757
+ const slotFns = named.map(([nm, src]) => {
758
+ const decl = entry.slots.find((s) => s.name === nm);
759
+ let content = src;
760
+ for (const p of decl?.props ?? []) {
761
+ content = content.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(new RegExp(`\\b${p}\\b`, "g"), `__s.${p}`)}}`);
762
+ }
763
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
764
+ });
765
+ const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
766
+ const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
767
+ const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
768
+ return `${JSON.stringify(key)}: ${val}`;
769
+ }).join(", ");
770
+ const childrenArg = hasChildren ? `__ch${id}(${scope ?? "undefined"}, ${closes})` : `''`;
771
+ result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
772
+ `;
773
+ remaining = rest;
774
+ } else {
775
+ const [, expr] = earliest.match;
776
+ const trimmed = expr.trim();
777
+ const before = remaining.substring(0, earliest.index);
778
+ if (trimmed === "__slot__") {
779
+ if (before) result += emitChunk(before, acc, closes, scope);
780
+ result += compileSlot(acc);
781
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
782
+ continue;
783
+ }
784
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
785
+ if (slotCall) {
786
+ if (before) result += emitChunk(before, acc, closes, scope);
787
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);
788
+ `;
789
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
790
+ continue;
791
+ }
792
+ const attrMatch = before.match(/([\w-]+)=\s*$/);
793
+ if (attrMatch) {
794
+ const lit = before.slice(0, before.length - attrMatch[0].length);
795
+ if (lit) result += emitChunk(lit, acc, closes, scope);
796
+ result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
797
+ } else {
798
+ if (before) result += emitChunk(before, acc, closes, scope);
799
+ const after = remaining.substring(earliest.index + earliest.match[0].length);
800
+ const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
801
+ result += emitText(trimmed, acc, closes, scope, markers, pair);
802
+ }
803
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
804
+ }
805
+ }
806
+ return result;
807
+ }
808
+ function scanTagEnd(src, start) {
809
+ let j = start + 1;
810
+ let quote = "";
811
+ let brace = 0;
812
+ while (j < src.length) {
813
+ const c = src[j];
814
+ if (quote) {
815
+ if (c === quote) quote = "";
816
+ } else if (c === '"' || c === "'") quote = c;
817
+ else if (c === "{") brace++;
818
+ else if (c === "}") brace = Math.max(0, brace - 1);
819
+ else if (c === ">" && brace === 0) return j + 1;
820
+ j++;
821
+ }
822
+ return -1;
823
+ }
824
+ function findCompTag(src, comps) {
825
+ let i = 0;
826
+ while (i < src.length) {
827
+ const lt = src.indexOf("<", i);
828
+ if (lt < 0) return null;
829
+ const nm = /^<([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
830
+ if (nm && comps.has(nm[1])) {
831
+ const end = scanTagEnd(src, lt);
832
+ if (end > 0) {
833
+ const raw = src.slice(lt, end);
834
+ const selfClosing = /\/>$/.test(raw);
835
+ return { start: lt, end, name: nm[1], attrs: raw.slice(1 + nm[1].length, selfClosing ? -2 : -1), selfClosing };
836
+ }
837
+ }
838
+ i = lt + 1;
839
+ }
840
+ return null;
841
+ }
842
+ function findClose(src, from, name) {
843
+ const re = new RegExp(`<(/?)${name}(?=[\\s/>])`, "g");
844
+ re.lastIndex = from;
845
+ let depth = 1;
846
+ let m;
847
+ while (m = re.exec(src)) {
848
+ const end = scanTagEnd(src, m.index);
849
+ if (end < 0) return -1;
850
+ if (m[1] === "/") {
851
+ depth--;
852
+ if (depth === 0) return m.index;
853
+ } else if (!/\/>$/.test(src.slice(m.index, end))) depth++;
854
+ }
855
+ return -1;
856
+ }
857
+ function parseCompAttrs(attrs) {
858
+ const out = [];
859
+ let i = 0;
860
+ while (i < attrs.length) {
861
+ const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
862
+ if (!nm) break;
863
+ i += nm[0].length;
864
+ const eq = /^\s*=\s*/.exec(attrs.slice(i));
865
+ if (!eq) {
866
+ out.push({ name: nm[1], kind: "bool", value: "" });
867
+ continue;
868
+ }
869
+ i += eq[0].length;
870
+ const ch = attrs[i];
871
+ if (ch === "{") {
872
+ let depth = 1;
873
+ let j = i + 1;
874
+ while (j < attrs.length && depth > 0) {
875
+ if (attrs[j] === "{") depth++;
876
+ else if (attrs[j] === "}") depth--;
877
+ j++;
878
+ }
879
+ out.push({ name: nm[1], kind: "expr", value: attrs.slice(i + 1, j - 1).trim() });
880
+ i = j;
881
+ } else if (ch === '"' || ch === "'") {
882
+ const j = attrs.indexOf(ch, i + 1);
883
+ out.push({ name: nm[1], kind: "str", value: attrs.slice(i + 1, j < 0 ? attrs.length : j) });
884
+ i = j < 0 ? attrs.length : j + 1;
885
+ } else break;
886
+ }
887
+ return out;
888
+ }
889
+ function rejectNestedSlot(src, outer) {
890
+ let i = 0;
891
+ while (i < src.length) {
892
+ const lt = src.indexOf("<", i);
893
+ if (lt < 0) return;
894
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
895
+ if (!nm) {
896
+ i = lt + 1;
897
+ continue;
898
+ }
899
+ const end = scanTagEnd(src, lt);
900
+ if (end < 0) return;
901
+ const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
902
+ if (hit && nm[1] !== "/") {
903
+ throw new Error(`slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`);
904
+ }
905
+ i = end;
906
+ }
907
+ }
908
+ function splitSlots(src) {
909
+ let def = "";
910
+ const named = /* @__PURE__ */ new Map();
911
+ let i = 0;
912
+ let elemDepth = 0;
913
+ let blockDepth = 0;
914
+ while (i < src.length) {
915
+ const lt = src.indexOf("<", i);
916
+ const ob = src.indexOf("{#", i);
917
+ const cb = src.indexOf("{/", i);
918
+ const cands = [lt, ob, cb].filter((x) => x >= 0);
919
+ if (cands.length === 0) {
920
+ def += src.slice(i);
921
+ break;
922
+ }
923
+ const next = Math.min(...cands);
924
+ if (next > i) def += src.slice(i, next);
925
+ if (next === ob || next === cb) {
926
+ const close = src.indexOf("}", next);
927
+ const token = src.slice(next, close < 0 ? src.length : close + 1);
928
+ if (next === ob) blockDepth++;
929
+ else blockDepth = Math.max(0, blockDepth - 1);
930
+ def += token;
931
+ i = next + token.length;
932
+ continue;
933
+ }
934
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(next, next + 64));
935
+ if (!nm) {
936
+ def += "<";
937
+ i = next + 1;
938
+ continue;
939
+ }
940
+ const end = scanTagEnd(src, next);
941
+ if (end < 0) {
942
+ def += src.slice(next);
943
+ break;
944
+ }
945
+ const tagText = src.slice(next, end);
946
+ const selfClosing = /\/>$/.test(tagText);
947
+ const isVoid = VOID_TAGS.has(nm[2].toLowerCase());
948
+ if (nm[1] === "/") {
949
+ elemDepth = Math.max(0, elemDepth - 1);
950
+ def += tagText;
951
+ i = end;
952
+ continue;
953
+ }
954
+ if (!selfClosing && !isVoid) elemDepth++;
955
+ const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
956
+ if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
957
+ throw new Error(`slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`);
958
+ }
959
+ if (slotName) {
960
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
961
+ if (selfClosing || isVoid) {
962
+ named.set(slotName, (named.get(slotName) ?? "") + stripped);
963
+ } else {
964
+ const closeIdx = findClose(src, end, nm[2]);
965
+ if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
966
+ const tail = `</${nm[2]}>`;
967
+ const inner = src.slice(end, closeIdx);
968
+ rejectNestedSlot(inner, slotName);
969
+ named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
970
+ elemDepth = Math.max(0, elemDepth - 1);
971
+ i = closeIdx + tail.length;
972
+ continue;
973
+ }
974
+ i = end;
975
+ continue;
976
+ }
977
+ def += tagText;
978
+ i = end;
979
+ }
980
+ return { def, named: [...named.entries()] };
981
+ }
982
+ function emitChunk(text, acc, closes, scope) {
983
+ if (!text) return "";
984
+ return `${acc} += ${JSON.stringify(text)};
985
+ `;
986
+ }
987
+ var IMG_RE = /<img\b(?:[^<>]|\{[^{}]*\})*>/g;
988
+ var IMG_MIME = {
989
+ ".png": "image/png",
990
+ ".jpg": "image/jpeg",
991
+ ".jpeg": "image/jpeg",
992
+ ".gif": "image/gif",
993
+ ".webp": "image/webp",
994
+ ".svg": "image/svg+xml",
995
+ ".ico": "image/x-icon"
996
+ };
997
+ var INLINE_IMG_MAX = 4096;
998
+ function inlineImages(template, publicDir) {
999
+ return template.replace(IMG_RE, (tag) => {
1000
+ const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
1001
+ if (!src) return tag;
1002
+ const ext = path.extname(src[1]).toLowerCase();
1003
+ const mime = IMG_MIME[ext];
1004
+ if (!mime) return tag;
1005
+ let file;
1006
+ try {
1007
+ file = fs.readFileSync(path.join(publicDir, src[1]));
1008
+ } catch {
1009
+ return tag;
1010
+ }
1011
+ if (file.length > INLINE_IMG_MAX) return tag;
1012
+ 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")}`;
1013
+ return tag.replace(src[0], `src="${uri}"`);
1014
+ });
1015
+ }
1016
+ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
1017
+ if (!markers) {
1018
+ return `${acc} += esc(${expr});
1019
+ `;
1020
+ }
1021
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1022
+ let extra = pair ? ", 1" : scope ? ", 0" : "";
1023
+ if (scope) extra += `, ${scope}`;
1024
+ return `${acc} += textMark(${closes}, ${fn}${extra});
1025
+ `;
1026
+ }
1027
+ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1028
+ if (!markers) {
1029
+ return `${acc} += '${attr}="' + esc(${expr}) + '"';
1030
+ `;
1031
+ }
1032
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1033
+ const arg = scope ? `, ${scope}` : "";
1034
+ return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
1035
+ `;
1036
+ }
1037
+ function compileSlot(acc) {
1038
+ return `${acc} += String(children);
1039
+ `;
1040
+ }
1041
+ var RUNTIME_IMPORTS = `import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark } from './runtime.js';`;
1042
+ function propsCode(props) {
1043
+ if (props.length === 0) return "";
1044
+ return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
1045
+ }
1046
+ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1047
+ const fn = sl[name];
1048
+ if (typeof fn !== 'function') return null;
1049
+ const o = {};
1050
+ for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1051
+ return { o, fn };
1052
+ };
1053
+ const __slotBlock = (closes, sl, name, pairs) => {
1054
+ const hit = __slot(sl, name, pairs);
1055
+ const idx = closes.length;
1056
+ closes.push(() => {
1057
+ if (!hit) return null;
1058
+ const c = [];
1059
+ return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
1060
+ });
1061
+ return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1062
+ };`;
1063
+ function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "") {
1064
+ const headCode = headFn ? `
1065
+ const __head = () => { let __hd = ''; ${headFn} return __hd; };
1066
+ __html += headMark(closes, __head);` : "";
1067
+ return `
1068
+ ${RUNTIME_IMPORTS}
1069
+
1070
+ ${imports}
1071
+
1072
+ ${exports}
1073
+ ${guard}
1074
+
1075
+ ${namedSlots ? SLOT_HELPER : ""}
1076
+
1077
+ export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1078
+ ${props.length > 0 ? "const __p = __props || {};" : ""}
1079
+ ${namedSlots ? "const __sl = __slots || {};" : ""}
1080
+ ${propsCode(props)}
1081
+ ${stateDeclsCode}
1082
+ // The incremental patches of the action that produced THIS response,
1083
+ // applied to the state the declarations above just established (a no-op on
1084
+ // every path that is not a server action's re-render - see the runtime).
1085
+ ${isComponent ? "" : "applyStateDeltas();"}
1086
+ ${script}
1087
+ const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1088
+ let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1089
+ return __html;
1090
+ }
1091
+ `;
1092
+ }
1093
+ function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
1094
+ const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1095
+ const headCode = headFn ? `
1096
+ const __head = () => { let __hd = ''; ${headFn} return __hd; };
1097
+ __html += headMark(closes, __head);` : "";
1098
+ return `
1099
+ ${RUNTIME_IMPORTS}
1100
+
1101
+ ${imports}
1102
+
1103
+ ${exports}
1104
+
1105
+ ${namedSlots ? SLOT_HELPER : ""}
1106
+
1107
+ export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1108
+ ${props.length > 0 ? "const __p = __props || {};" : ""}
1109
+ ${namedSlots ? "const __sl = __slots || {};" : ""}
1110
+ ${propsCode(props)}
1111
+ ${stateDeclsCode}
1112
+ ${script}
1113
+ ${handlerRegistry}
1114
+ const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1115
+ let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1116
+ return __html;
1117
+ }
1118
+ `;
1119
+ }
1120
+ var layoutsOf = (infos, idx) => infos.map((li, i) => ({ li, i })).filter(({ li }) => li.isLayout && isAncestorDir(li.filePath, infos[idx].filePath)).sort((a, b) => b.li.filePath.length - a.li.filePath.length).map(({ i }) => i);
1121
+ var routeShipsNoJs = (infos, compiled, i) => {
1122
+ if (compiled[i].csr === true) return false;
1123
+ if (compiled[i].needsClient) return false;
1124
+ return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1125
+ };
1126
+ function buildReport(infos, compiled) {
1127
+ return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
1128
+ if (routeShipsNoJs(infos, compiled, i)) {
1129
+ return `${info.routePath} zero-JS nothing in the chain needs the client`;
1130
+ }
1131
+ 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("; ");
1132
+ const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
1133
+ return `${info.routePath} client JS ${why}${forced}`;
1134
+ });
1135
+ }
1136
+ async function buildProject(root, outDir) {
1137
+ await fs.promises.mkdir(outDir, { recursive: true });
1138
+ const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
1139
+ await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
1140
+ const pageFiles = await scanRoseFiles(root);
1141
+ const compFiles = await scanComponentFiles(root);
1142
+ const files = [...pageFiles, ...compFiles];
1143
+ if (pageFiles.length === 0) {
1144
+ throw new Error(`no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`);
1145
+ }
1146
+ const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1147
+ const config = await loadConfig(root);
1148
+ const plugins = config.plugins;
1149
+ const scopeKeys = files.map((f, i) => {
1150
+ const base = infos[i].isComponent ? path.join(root, "src") : path.join(root, "src", "pages");
1151
+ return path.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
1152
+ });
1153
+ const registry = new Map(
1154
+ files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1155
+ );
1156
+ const compiled = await Promise.all(
1157
+ files.map((f, i) => compileComponent(f, path.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
1158
+ );
1159
+ const importsOf = /* @__PURE__ */ new Map();
1160
+ files.forEach((_, i) => {
1161
+ const list = [];
1162
+ for (const r of compiled[i].roseImports ?? []) {
1163
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1164
+ const hit = registry.get(abs);
1165
+ if (hit) list.push(hit.index);
1166
+ }
1167
+ importsOf.set(i, list);
1168
+ });
1169
+ const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
1170
+ if (compiled[i].needsClient) return path.basename(files[i]);
1171
+ if (seen.has(i)) return null;
1172
+ seen.add(i);
1173
+ for (const dep of importsOf.get(i) ?? []) {
1174
+ const hit = needyDep(dep, seen);
1175
+ if (hit) return hit;
1176
+ }
1177
+ return null;
1178
+ };
1179
+ compiled.forEach((c, i) => {
1180
+ if (c.needsClient) return;
1181
+ const who = needyDep(i);
1182
+ if (who) {
1183
+ c.needsClient = true;
1184
+ c.clientReasons = [...c.clientReasons ?? [], `imported component ${who} needs the client`];
1185
+ }
1186
+ });
1187
+ const reachable = /* @__PURE__ */ new Set();
1188
+ const visit = (i) => {
1189
+ if (reachable.has(i)) return;
1190
+ reachable.add(i);
1191
+ for (const r of compiled[i].roseImports ?? []) {
1192
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1193
+ const hit = registry.get(abs);
1194
+ if (hit) visit(hit.index);
1195
+ }
1196
+ };
1197
+ files.forEach((_, i) => {
1198
+ if (!infos[i].isComponent) visit(i);
1199
+ });
1200
+ const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
1201
+ if (styles) await fs.promises.writeFile(path.join(outDir, "styles.css"), styles);
1202
+ else await fs.promises.rm(path.join(outDir, "styles.css"), { force: true });
1203
+ let locales = {};
1204
+ try {
1205
+ for (const f of await fs.promises.readdir(path.join(root, "src", "locales"))) {
1206
+ if (!f.endsWith(".json")) continue;
1207
+ locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, "src", "locales", f), "utf-8"));
1208
+ }
1209
+ } catch {
1210
+ locales = {};
1211
+ }
1212
+ const defaultLocale = locales.en ? "en" : Object.keys(locales).sort()[0] ?? "en";
1213
+ const localesJson = JSON.stringify(locales).replace(/</g, "\\u003c");
1214
+ const preload = config.i18n.preload ?? Object.keys(locales);
1215
+ const packed = Object.keys(locales).filter((l) => !preload.includes(l));
1216
+ for (const l of preload) {
1217
+ if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
1218
+ }
1219
+ await fs.promises.rm(path.join(outDir, "locales"), { recursive: true, force: true });
1220
+ if (packed.length > 0) {
1221
+ const packDir = path.join(outDir, "locales");
1222
+ await fs.promises.mkdir(packDir, { recursive: true });
1223
+ for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
1224
+ }
1225
+ const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
1226
+ const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
1227
+ const buildDir = path.join(outDir, ".build");
1228
+ await fs.promises.rm(buildDir, { recursive: true, force: true });
1229
+ await fs.promises.mkdir(buildDir, { recursive: true });
1230
+ const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1231
+ if (runtimePlugins.length > 0) {
1232
+ const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
1233
+ await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
1234
+ // Bundled into dist/server.js: these hooks run per request on every server
1235
+ // (Node, dev/preview, edge). Transform hooks already ran at build time.
1236
+ import config from ${JSON.stringify(configRel)};
1237
+
1238
+ const list = Array.isArray(config) ? config : [];
1239
+ export const hooks = list
1240
+ .filter((p) => p && (p.onRequest || p.onResponse))
1241
+ .map((p) => ({ name: p.name, onRequest: p.onRequest ? p.onRequest.bind(p) : null, onResponse: p.onResponse ? p.onResponse.bind(p) : null }));
1242
+
1243
+ export const hasRequestHooks = hooks.some((p) => p.onRequest);
1244
+ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1245
+ `);
1246
+ }
1247
+ const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
1248
+ if (!runtimeEntry) throw new Error("rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler");
1249
+ await esbuild.build({
1250
+ entryPoints: [runtimeEntry],
1251
+ bundle: true,
1252
+ outfile: path.join(buildDir, "runtime.js"),
1253
+ format: "esm",
1254
+ platform: "browser",
1255
+ write: true
1256
+ });
1257
+ for (let i = 0; i < compiled.length; i++) {
1258
+ const src = compiled[i].api ?? compiled[i].ssr;
1259
+ await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
1260
+ if (!infos[i].isApi) {
1261
+ await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1262
+ }
1263
+ }
1264
+ const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1265
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi);
1266
+ const compose = (idx) => {
1267
+ let expr = `render_${idx}`;
1268
+ for (const i of layoutsOf(infos, idx)) {
1269
+ expr = `(async (closes, children) => await render_${i}(closes, await (${expr})(closes, children)))`;
1270
+ }
1271
+ return expr;
1272
+ };
1273
+ const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? "inline";
1274
+ const split = bundleMode === "split";
1275
+ const chainOf = (idx) => [idx, ...layoutsOf(infos, idx)];
1276
+ const loaderInner = (idx) => `load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(", ")}])`;
1277
+ const loaderOf = (idx) => `{ ${loaderInner(idx)} }`;
1278
+ const routeNoJs = (i) => routeShipsNoJs(infos, compiled, i);
1279
+ const serverImports = compiled.map((_, i) => {
1280
+ if (!reachable.has(i)) return "";
1281
+ if (infos[i].isMiddleware) {
1282
+ return `import * as middlewareMod from './comp-${i}.ssr.js';`;
1283
+ }
1284
+ if (infos[i].isApi) {
1285
+ const names2 = compiled[i].apiMethods ?? [];
1286
+ const handlerImports = names2.map((n) => `${n} as ${n}_${i}`).join(", ");
1287
+ return handlerImports ? `import { ${handlerImports} } from './comp-${i}.ssr.js';` : `import './comp-${i}.ssr.js';`;
1288
+ }
1289
+ const isPage = !infos[i].isLayout && !infos[i].isNotFound;
1290
+ const names = isPage ? compiled[i].actionNames : [];
1291
+ const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(", ");
1292
+ const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : "";
1293
+ const named = [actionImports, guardImport].filter(Boolean).join(", ");
1294
+ return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1295
+ }).join("\n");
1296
+ const nfIdx = infos.findIndex((info) => info.isNotFound);
1297
+ const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
1298
+ const errIdx = infos.findIndex((info) => info.isError);
1299
+ const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
1300
+ const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
1301
+ const serverRoutes = pages.map(({ info, i }) => {
1302
+ const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
1303
+ if (compiled[i].csr === false && compiled[i].needsClient) {
1304
+ throw new Error(
1305
+ `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`
1306
+ );
1307
+ }
1308
+ if (compiled[i].csr === false) {
1309
+ const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1310
+ if (needy !== void 0) {
1311
+ throw new Error(
1312
+ `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`
1313
+ );
1314
+ }
1315
+ }
1316
+ const csrFlag = routeNoJs(i) ? ", csr: false" : "";
1317
+ const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1318
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag} }`;
1319
+ }).join(",\n ");
1320
+ const serverEntry = `
1321
+ ${serverImports}
1322
+ import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1323
+ ${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
1324
+ // module to import - the runners below stay no-ops and the servers call them
1325
+ // unconditionally (one code path, no flags to keep in sync).
1326
+ const __pluginHooks = [];
1327
+ const __hasRequestHooks = false;
1328
+ const __hasResponseHooks = false;`}
1329
+
1330
+ // The runtime plugin hooks. onRequest runs before routing and
1331
+ // middleware and may short-circuit the request with its own Response; onResponse
1332
+ // runs once the response exists and may replace it. Both are no-ops when the
1333
+ // project declares no runtime hooks. A throwing hook is logged and skipped -
1334
+ // the request continues - so a broken logging plugin can never take a site
1335
+ // down (a build-time transform, by contrast, fails loudly).
1336
+ export async function runRequestHooks(ctx) {
1337
+ for (const p of __pluginHooks) {
1338
+ if (!p.onRequest) continue;
1339
+ try {
1340
+ const r = await p.onRequest(ctx);
1341
+ if (r instanceof Response) return r;
1342
+ } catch (err) {
1343
+ console.error('rosetack: plugin', p.name, 'onRequest failed:', err instanceof Error ? err.message : err);
1344
+ }
1345
+ }
1346
+ return null;
1347
+ }
1348
+
1349
+ export async function runResponseHooks(ctx, res) {
1350
+ let out = res;
1351
+ for (const p of __pluginHooks) {
1352
+ if (!p.onResponse) continue;
1353
+ try {
1354
+ const r = await p.onResponse(ctx, out);
1355
+ if (r instanceof Response) out = r;
1356
+ } catch (err) {
1357
+ console.error('rosetack: plugin', p.name, 'onResponse failed:', err instanceof Error ? err.message : err);
1358
+ }
1359
+ }
1360
+ return out;
1361
+ }
1362
+
1363
+ // The servers read these to skip building the hook context entirely when no
1364
+ // hook exists - the hot path pays nothing for the feature.
1365
+ export const hasRequestHooks = __hasRequestHooks;
1366
+ export const hasResponseHooks = __hasResponseHooks;
1367
+
1368
+ // i18n: the dictionaries baked at build time from
1369
+ // src/locales/*.json. A route segment named [lang] is the locale: the value
1370
+ // must name one of these dictionaries, and $t resolves keys against it.
1371
+ setLocales(${localesJson}, '${defaultLocale}');
1372
+
1373
+ // The store transport. Under "rosetack serve" every worker is its
1374
+ // own process with its own dist/server.js module, so a $store write must
1375
+ // travel: this worker -> primary -> every other worker. process.send exists
1376
+ // only inside cluster workers, so a single-process runner (dev, preview,
1377
+ // the edge adapter) keeps the transport null and $store stays plain
1378
+ // per-process state - the documented boundary, not a bug.
1379
+ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1380
+ setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1381
+ process.on('message', (msg) => {
1382
+ if (msg && msg.type === 'rosetack:store') applyStorePatch(msg.name, msg.value);
1383
+ });
1384
+ }
1385
+
1386
+ export { localeList };
1387
+ export const defaultLocale = '${defaultLocale}';
1388
+
1389
+ // Route params maps, re-exported for the build's prerender step: routePath
1390
+ // -> the component's exported params (a static map or a function). Reading
1391
+ // them through the server bundle keeps the deploy dir free of component
1392
+ // modules - both bundles are self-contained, nothing else may ship. Only
1393
+ // components that actually export params appear here (a missing export
1394
+ // means the dynamic route renders on demand).
1395
+ ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1396
+
1397
+ export const routeParams = {
1398
+ ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1399
+ };
1400
+
1401
+ // Routes whose component reads the request context (getContext()), mutates a
1402
+ // shared store ($store), or opted into nonce-based CSP: the bag is
1403
+ // per-request, the store is per-process, and a nonce is per-response, so
1404
+ // these are dynamic - the build never bakes them and the servers never
1405
+ // answer them from a prerendered file. Public routes keep the static fast
1406
+ // path (file cache, ETag/304, streaming) untouched.
1407
+ export const dynamicRoutes = [
1408
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1409
+ ];
1410
+
1411
+ // Which api routes opt into build-time baking (export const prerender = true):
1412
+ // routePath -> boolean. The build calls the GET handler once and writes the
1413
+ // body to dist/, so the Go single binary serves read-only APIs without Node.
1414
+ ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1415
+
1416
+ export const apiPrerender = {
1417
+ ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1418
+ };
1419
+
1420
+ // Stale-while-revalidate windows (export const revalidate = N): the build
1421
+ // bakes these routes like any other, and the preview server serves the
1422
+ // baked file for up to N seconds - after which the next request is answered
1423
+ // STALE (instant, from disk) while a background pass re-renders and swaps
1424
+ // the file (ISR). Routes that read the request context are
1425
+ // excluded: they render per request and have no baked file to revalidate.
1426
+ // The dev server ignores the window (it rebuilds on change), the edge
1427
+ // adapter renders live (always fresh), and the Go binary serves the baked
1428
+ // file forever - the same static-half boundary as page POSTs.
1429
+ export const revalidate = [
1430
+ ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1431
+ ];
1432
+
1433
+ // pages/_middleware.rose: a Web-standard request handler that runs before
1434
+ // every render on the server (pages, POSTs, api calls alike). Returning a
1435
+ // Response short-circuits the whole request - a redirect, an auth wall, a
1436
+ // rewrite; returning nothing continues, and getContext() hands the
1437
+ // per-request bag to $data, server actions and api handlers. Absent -> null,
1438
+ // and the servers keep their static fast paths.
1439
+ export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1440
+
1441
+ // Routes whose DOCUMENTS ship without the client bundle (
1442
+ // decided by the compiler since #29): HTML + CSS only - no runtime, no
1443
+ // state script, zero JavaScript for whoever lands on them. The compiler
1444
+ // picks these automatically: a route whose whole chain needs nothing from
1445
+ // the client (no event wiring, no lifecycle, no action, no form) is a
1446
+ // content route. An exported "csr = true" forces the bundle back in; an
1447
+ // exported "csr = false" is the same decision, asserted. The route's render
1448
+ // function still rides in the client bundle, so a client-side navigation
1449
+ // from an interactive page paints it normally and a static deploy's SPA
1450
+ // fallback can render it too; only the document is JS-free.
1451
+ // isNoJs() lets the servers keep these routes on the buffered path: a
1452
+ // streamed no-JS document would carry the shell's default <title> (the
1453
+ // route head is applied client-side at boot, and there is no client).
1454
+ export const noJsRoutes = [
1455
+ ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1456
+ ];
1457
+
1458
+ export function isNoJs(pathname) {
1459
+ return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1460
+ }
1461
+
1462
+ // Per-route response headers: a route exporting a headers
1463
+ // map carries them into every response the servers write for it, merged
1464
+ // OVER the framework defaults (the strict CSP) - so an app can tighten or
1465
+ // relax the policy per route. Absent -> null, and the servers keep sending
1466
+ // the defaults alone.
1467
+ export const routeHeaders = [
1468
+ ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1469
+ ];
1470
+
1471
+ export function headersFor(pathname) {
1472
+ const hit = routeHeaders.find((r) => matchRoute(r.pattern, pathname));
1473
+ return hit ? hit.headers : null;
1474
+ }
1475
+
1476
+ // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
1477
+ // ). The servers ask this BEFORE writing a document: when it is true they
1478
+ // mint one random nonce per response, put it in the CSP header ('nonce-...'
1479
+ // plus 'strict-dynamic', so the document's own code may load more code) and
1480
+ // stamp the same value on the script tag. The default policy stays a hash -
1481
+ // cspNonceRoutes is empty for an app that never asks, so the fast path is
1482
+ // unchanged. The Go binary never sees this: these routes are dynamic, so it
1483
+ // has no baked file for them to serve.
1484
+ export const cspNonceRoutes = [
1485
+ ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1486
+ ];
1487
+
1488
+ export function cspNonce(pathname) {
1489
+ return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1490
+ }
1491
+
1492
+ // A Web-standard Request from whatever the host provides: the edge adapter
1493
+ // passes one already; the Node server passes its IncomingMessage (plus the
1494
+ // already-parsed FormData for POSTs, so middleware can read form fields).
1495
+ function toWebRequest(raw, form) {
1496
+ if (raw instanceof Request) return raw;
1497
+ const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
1498
+ if (form) init.body = form;
1499
+ return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1500
+ }
1501
+
1502
+ // Runs the middleware (if the project has one) for this request and returns
1503
+ // its short-circuit Response, or null to continue. The servers call this
1504
+ // EXACTLY ONCE per request, before anything else: it resets the per-request
1505
+ // context bag and the middleware fills it via getContext(), which $data,
1506
+ // server actions and api handlers then read while rendering. rawReq: the
1507
+ // host's request (Node IncomingMessage or a Web-standard Request); form:
1508
+ // the already-parsed FormData of a POST.
1509
+ export async function runMiddleware(rawReq, form) {
1510
+ resetRequestContext();
1511
+ if (!middleware || !rawReq) return null;
1512
+ const res = await middleware(toWebRequest(rawReq, form));
1513
+ return res || null;
1514
+ }
1515
+
1516
+ const routes = [
1517
+ ${serverRoutes}
1518
+ ];
1519
+
1520
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
1521
+ // render HTML and never reach the client bundle. The middleware ran before
1522
+ // this (the servers call runMiddleware() first), so handlers can read
1523
+ // getContext() for auth without re-running anything.
1524
+ const apiRoutes = [
1525
+ ${apiRoutes.map(({ info, i }) => {
1526
+ const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
1527
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', handlers: { ${handlers} } }`;
1528
+ }).join(",\n ")}
1529
+ ];
1530
+
1531
+ // pages/404.rose (with its layouts) or null -> built-in plain 404
1532
+ const notFound = ${notFoundRender};
1533
+
1534
+ // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1535
+ // whose render throws degrades to this instead of failing the response.
1536
+ const errorPage = ${errorRender};
1537
+
1538
+ // The <html> attributes of the document for a pathname - the locale
1539
+ // of its [lang] segment (the default when there is none, or when the segment
1540
+ // names no dictionary: that request 404s in the default language) and the
1541
+ // reading direction that locale implies. The buffered render returns the same
1542
+ // pair; the streaming path needs it BEFORE the shell flushes, which is why
1543
+ // the servers ask for it by pathname.
1544
+ export function docAttrs(pathname) {
1545
+ for (const route of routes) {
1546
+ if (!matchRoute(route.pattern, pathname)) continue;
1547
+ const parts = route.pattern.split('/');
1548
+ const langIdx = parts.indexOf(':lang');
1549
+ if (langIdx >= 0) {
1550
+ const lang = pathname.split('/')[langIdx];
1551
+ if (isLocale(lang)) return { lang, dir: localeDir(lang) };
1552
+ }
1553
+ break; // matched, but not a localized route (or a bogus locale): the default
1554
+ }
1555
+ return { lang: defaultLocale, dir: localeDir(defaultLocale) };
1556
+ }
1557
+
1558
+ // Paint a fallback page (404/500) and serialize its state.
1559
+ async function renderFallback(pathname, render) {
1560
+ const { html, head } = extractHead(await render([], ''));
1561
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1562
+ return { html, state, head, ...docAttrs(pathname) };
1563
+ }
1564
+
1565
+ export function matchRoute(pattern, pathname) {
1566
+ const patternParts = pattern.split('/');
1567
+ const pathParts = pathname.split('/');
1568
+ if (patternParts.length !== pathParts.length) return false;
1569
+ for (let i = 0; i < patternParts.length; i++) {
1570
+ if (patternParts[i].startsWith(':')) continue;
1571
+ if (patternParts[i] !== pathParts[i]) return false;
1572
+ }
1573
+ return true;
1574
+ }
1575
+
1576
+ // Head blocks (one per component in the route chain) are pulled out of the
1577
+ // page html: the shell injects them into <head>, and the client re-applies
1578
+ // them on navigation. Document order is page-first, so the shell's keyed
1579
+ // merge lets a page override its layouts. The EMPTY marker pair stays in the
1580
+ // body so the client's wire() still finds the block: at boot it adopts the
1581
+ // shell-injected elements in place (marked with the same keys, so no
1582
+ // duplicates) and keeps the head reactive.
1583
+ function extractHead(rendered) {
1584
+ const head = [];
1585
+ const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
1586
+ head.push(content);
1587
+ return '<!--\u27E6h:' + id + '\u27E7--><!--\u27E6/h:' + id + '\u27E7-->';
1588
+ });
1589
+ return { html, head };
1590
+ }
1591
+
1592
+ // form: the submitted FormData of a progressive-enhancement POST. The
1593
+ // selected server action runs first and returns a state patch (e.g.
1594
+ // { guests: [...] }); seeding those keys BEFORE the render makes state()
1595
+ // adopt them, so the response is the page as it looks AFTER the action -
1596
+ // with or without JS. A __action field picks the action by name (default
1597
+ // 'action', the conventional <form method="POST"> target); a click handler
1598
+ // bound to an action ($action('like')) sends the same field.
1599
+ // A route whose render throws degrades to pages/500.rose (status 500) - or
1600
+ // the built-in plain 500 - instead of failing the whole response.
1601
+ // The middleware does NOT run here: the servers run it once per request via
1602
+ // runMiddleware() (which also seeds the request context), so a page render
1603
+ // never re-runs it.
1604
+ export async function renderPage(pathname, form) {
1605
+ clearRequestState();
1606
+ for (const route of routes) {
1607
+ if (matchRoute(route.pattern, pathname)) {
1608
+ const patternParts = route.pattern.split('/');
1609
+ const pathParts = pathname.split('/');
1610
+ for (let i = 0; i < patternParts.length; i++) {
1611
+ if (patternParts[i].startsWith(':')) {
1612
+ setState(patternParts[i].slice(1), pathParts[i]);
1613
+ }
1614
+ }
1615
+ // i18n: a [lang] segment naming no dictionary is a
1616
+ // 404 - the URL is the contract, and rendering the page with fallback
1617
+ // strings would serve duplicate content under a bogus language
1618
+ const langIdx = patternParts.indexOf(':lang');
1619
+ if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
1620
+ if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
1621
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1622
+ }
1623
+ // The document's <html lang>/<dir> follow this route's locale
1624
+ // (the default's when the route is not localized)
1625
+ const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
1626
+ // The action dispatch. The page's guard (exported
1627
+ // beforeAction) runs FIRST and vetoes with an ActionError - the
1628
+ // action-level permission check. Then the selected action runs and its
1629
+ // return value seeds this render's state, per key, so an incremental
1630
+ // patch ($append and friends) grows a large list by one row instead of
1631
+ // re-sending the whole thing. An ActionError from either half is a
1632
+ // BUSINESS failure: it is seeded as the 'actionError' state, the
1633
+ // response carries its status, and the page renders with the failure
1634
+ // visible (a {#boundary} around the action's widget contains it).
1635
+ // Anything else is a bug and keeps going to the 500 page.
1636
+ let actionStatus = 0;
1637
+ if (form && route.actions) {
1638
+ const actionName = form.get('__action') || 'action';
1639
+ const fn = route.actions[actionName];
1640
+ if (fn) {
1641
+ try {
1642
+ if (route.guard) await route.guard(actionName, form);
1643
+ const patch = await fn(form);
1644
+ if (patch && typeof patch === 'object') {
1645
+ for (const key of Object.keys(patch)) {
1646
+ const v = patch[key];
1647
+ // An incremental patch is RECORDED, not applied: the render's
1648
+ // own state declarations apply it, so the delta is relative to
1649
+ // the value the page was going to render anyway.
1650
+ if (v instanceof StateDelta) setStateDelta(key, v);
1651
+ else setState(key, v);
1652
+ }
1653
+ }
1654
+ } catch (err) {
1655
+ if (err instanceof ActionError) {
1656
+ setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
1657
+ actionStatus = err.code;
1658
+ } else {
1659
+ throw err;
1660
+ }
1661
+ }
1662
+ }
1663
+ }
1664
+ let rendered;
1665
+ try {
1666
+ rendered = extractHead(await route.render([], ''));
1667
+ } catch (err) {
1668
+ console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1669
+ if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
1670
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
1671
+ }
1672
+ // __route tells the bootstrap which route this document was rendered for.
1673
+ // A static-file server may serve another route's document (SPA fallback);
1674
+ // the bootstrap then client-renders instead of adopting mismatched DOM.
1675
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1676
+ // csr ( auto since #29): false when the compiler found
1677
+ // nothing in the route's chain that needs the client (or the route
1678
+ // asserted csr = false) - the document ships no runtime, no state
1679
+ // script, zero JavaScript. Every other route keeps the bundle. The
1680
+ // caller passes this straight to the shell as js.
1681
+ // Status is the failed action's code when one failed - the page
1682
+ // rendered fine, so the body is the page with the failure visible, and
1683
+ // the status says what happened (a 403 from the guard, a 422 from a
1684
+ // validation action). 200 otherwise.
1685
+ // Lang/dir are the document's <html> attributes - the locale
1686
+ // this route rendered in, and its reading direction.
1687
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
1688
+ }
1689
+ }
1690
+ if (notFound) {
1691
+ return { ...(await renderFallback(pathname, notFound)), status: 404 };
1692
+ }
1693
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1694
+ }
1695
+
1696
+ // Would renderPageStream handle this path? (matched route = stream, anything
1697
+ // else = buffered 404/500). Lets the servers pick the path before headers.
1698
+ export function canStream(pathname) {
1699
+ return routes.some((route) => {
1700
+ if (!matchRoute(route.pattern, pathname)) return false;
1701
+ // i18n: an unknown locale must answer 404, and a
1702
+ // streamed response cannot change its status - so it takes the buffered
1703
+ // path (renderPage returns the real 404), never the streaming one
1704
+ const langIdx = route.pattern.split('/').indexOf(':lang');
1705
+ return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
1706
+ });
1707
+ }
1708
+
1709
+ // === API routes ===
1710
+ // The /api namespace answers JSON, never HTML: an API client that hits an
1711
+ // unknown path must not receive the SPA shell. Handlers receive a
1712
+ // Web-standard Request and return a plain object (serialized as JSON, 200),
1713
+ // a Response (passed through), or nothing (204). A method the route does
1714
+ // not export answers 405 with an Allow header. Same code path on the Node
1715
+ // server and the edge adapter - Response is a global in both.
1716
+ export function isApi(pathname) {
1717
+ return pathname === '/api' || pathname.startsWith('/api/');
1718
+ }
1719
+
1720
+ function toResponse(out) {
1721
+ if (out instanceof Response) return out;
1722
+ if (out === undefined || out === null) return new Response(null, { status: 204 });
1723
+ return new Response(JSON.stringify(out), {
1724
+ status: 200,
1725
+ headers: { 'content-type': 'application/json' },
1726
+ });
1727
+ }
1728
+
1729
+ export async function handleApi(method, pathname, request) {
1730
+ for (const route of apiRoutes) {
1731
+ if (matchRoute(route.pattern, pathname)) {
1732
+ const fn = route.handlers[method];
1733
+ if (!fn) {
1734
+ return new Response(JSON.stringify({ error: 'method not allowed' }), {
1735
+ status: 405,
1736
+ headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
1737
+ });
1738
+ }
1739
+ return toResponse(await fn(request));
1740
+ }
1741
+ }
1742
+ return new Response(JSON.stringify({ error: 'not found' }), {
1743
+ status: 404,
1744
+ headers: { 'content-type': 'application/json' },
1745
+ });
1746
+ }
1747
+
1748
+ // === Streaming SSR ===
1749
+ // The static shell (doctype, <head>, body + container open) flushes BEFORE
1750
+ // the - possibly slow - render completes: the first byte leaves in
1751
+ // microseconds instead of after every $data resolves. The route HTML, the
1752
+ // state script, and the inlined bundle follow as later chunks of one chunked
1753
+ // response - still exactly one request.
1754
+ // The route's <head> tags are NOT in the streamed document: the client
1755
+ // applies them at boot from the body's head markers, so JS users see the
1756
+ // correct head immediately; no-JS consumers of streamed responses get the
1757
+ // static shell head (prerendered files stay complete documents).
1758
+ // Returns 200 (matched; a render throw degrades to the error-page body) or
1759
+ // 404 (unmatched - nothing written, so the caller can still buffer).
1760
+ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1761
+ clearRequestState();
1762
+ for (const route of routes) {
1763
+ if (matchRoute(route.pattern, pathname)) {
1764
+ const patternParts = route.pattern.split('/');
1765
+ const pathParts = pathname.split('/');
1766
+ for (let i = 0; i < patternParts.length; i++) {
1767
+ if (patternParts[i].startsWith(':')) {
1768
+ setState(patternParts[i].slice(1), pathParts[i]);
1769
+ }
1770
+ }
1771
+ // i18n: an unknown locale must 404 BEFORE the shell flushes - a
1772
+ // streamed response cannot change its status afterwards
1773
+ const langIdx = patternParts.indexOf(':lang');
1774
+ if (langIdx >= 0 && !isLocale(pathParts[langIdx])) return 404;
1775
+ write(shellOpen);
1776
+ let html;
1777
+ try {
1778
+ html = extractHead(await route.render([], '')).html;
1779
+ } catch (err) {
1780
+ // the shell is already on the wire: degrade to the error page BODY
1781
+ // (the status stays 200 - a real 500 needs the buffered path, which
1782
+ // the server picks for routes known-broken at build time)
1783
+ console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1784
+ html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
1785
+ }
1786
+ write(html);
1787
+ // csr: false ( auto since #29): a no-JS route's document
1788
+ // ends here - no state script, no inlined bundle. (The servers keep
1789
+ // these routes off the streaming path so their <head> is complete;
1790
+ // this is the correctness floor if one streams anyway.)
1791
+ if (route.csr === false) {
1792
+ write('</div>\\n</body>\\n</html>');
1793
+ return 200;
1794
+ }
1795
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1796
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
1797
+ return 200;
1798
+ }
1799
+ }
1800
+ return 404;
1801
+ }
1802
+ `;
1803
+ await fs.promises.writeFile(path.join(buildDir, "server-entry.js"), serverEntry);
1804
+ await esbuild.build({
1805
+ entryPoints: [path.join(buildDir, "server-entry.js")],
1806
+ bundle: true,
1807
+ outfile: path.join(outDir, "server.js"),
1808
+ format: "esm",
1809
+ platform: "node",
1810
+ write: true,
1811
+ ...TS_LOADER
1812
+ });
1813
+ 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");
1814
+ const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
1815
+ const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
1816
+ const hasLang = infos.some((i) => i.pattern.includes(":lang"));
1817
+ const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
1818
+ // client-side navigation cannot leave stale (screen readers and CSS
1819
+ // logical properties both read it). A route with no [lang] segment
1820
+ // returns to the default locale, and a bogus segment falls back to it
1821
+ // too, exactly like the server's docAttrs.
1822
+ const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
1823
+ const known = !seg || isLocale(seg);
1824
+ const docLang = known && seg ? seg : __defLocale;
1825
+ document.documentElement.lang = docLang;
1826
+ const docDir = localeDir(docLang);
1827
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
1828
+ else document.documentElement.removeAttribute('dir');
1829
+ if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
1830
+ const clientEntry = `
1831
+ ${clientImports}
1832
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
1833
+
1834
+ // i18n: the dictionaries baked at build time - the client
1835
+ // renders any PRELOADED locale from the bundle, so switching language costs
1836
+ // zero requests (the same bet as the inlined route table). a locale
1837
+ // the app left out of the preload (i18n.preload in rosetack.config.js) is a
1838
+ // pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
1839
+ // on first use - one request per language per session, then it renders from
1840
+ // memory like any other. The default build preloads everything and ships no
1841
+ // packs at all.
1842
+ setLocales(${clientLocalesJson}, '${defaultLocale}');
1843
+ setLocalePacks(${JSON.stringify(packed)});
1844
+ ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
1845
+ // follow a route that carries no [lang] segment (a non-i18n page)
1846
+ const __defLocale = '${defaultLocale}';` : ""}
1847
+ // The two pack doors, re-exported for an app that wants to warm a language
1848
+ // before its visitor asks for it (ensureLocale) or to feed a dictionary it
1849
+ // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
1850
+ // is what applyParams calls - so the re-export costs the statement alone.
1851
+ export { ensureLocale, loadLocale } from './runtime.js';
1852
+
1853
+ const routes = [
1854
+ ${clientRoutes}
1855
+ ];
1856
+
1857
+ // === Mode B: lazy route chunks ===
1858
+ // Split mode's registry entries arrive without a render function: loadChain
1859
+ // loads the route's module graph (the page plus its layouts, one chunk per
1860
+ // module, the shared runtime in its own vendor chunk) in parallel and
1861
+ // composes it at runtime - the exact nesting compose() built at compile
1862
+ // time for inline mode. getRender memoizes the composed function on the
1863
+ // entry, so a chunk loads once per session; inline mode's entries are the
1864
+ // render functions themselves, so the helper is a pass-through there.
1865
+ const loadChain = async (loaders) => {
1866
+ const mods = await Promise.all(loaders.map((load) => load()));
1867
+ let expr = (closes, children) => mods[0].render(closes, children);
1868
+ for (let k = 1; k < mods.length; k++) {
1869
+ const inner = expr;
1870
+ const outer = mods[k].render;
1871
+ expr = async (closes, children) => await outer(closes, await inner(closes, children));
1872
+ }
1873
+ return { render: expr };
1874
+ };
1875
+ const getRender = async (route) => {
1876
+ if (typeof route === 'function') return route; // inline mode: the render itself
1877
+ return (route.render ??= (await route.load()).render);
1878
+ };
1879
+
1880
+ // pages/404.rose (with its layouts) or null -> built-in plain 404
1881
+ const notFound = ${notFoundRender};
1882
+
1883
+ // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1884
+ // whose render throws on the client degrades to this instead of breaking
1885
+ // navigation.
1886
+ const errorPage = ${errorRender};
1887
+
1888
+ // Paint a fallback page (404/500) into the container, wired like any render.
1889
+ async function paintFallback(container, page, builtin) {
1890
+ resetEffects();
1891
+ clearRequestState();
1892
+ clearMounts(); // a failed render leaves stale mounts behind
1893
+ // inline mode passes the render itself; split mode passes a loader
1894
+ const render = page ? await getRender(page) : null;
1895
+ if (render) {
1896
+ const closes = [];
1897
+ const html = await render(closes, '');
1898
+ container.innerHTML = html;
1899
+ wire(container, closes);
1900
+ bindEvents(container);
1901
+ flushMounts();
1902
+ return;
1903
+ }
1904
+ container.innerHTML = builtin;
1905
+ }
1906
+
1907
+ export function matchRoute(pattern, pathname) {
1908
+ const patternParts = pattern.split('/');
1909
+ const pathParts = pathname.split('/');
1910
+ if (patternParts.length !== pathParts.length) return false;
1911
+ for (let i = 0; i < patternParts.length; i++) {
1912
+ if (patternParts[i].startsWith(':')) continue;
1913
+ if (patternParts[i] !== pathParts[i]) return false;
1914
+ }
1915
+ return true;
1916
+ }
1917
+
1918
+ // === Link prefetch ===
1919
+ // Hover / focus / touch an internal link and the target route renders NOW -
1920
+ // $data included - against a throwaway signal map. The click that follows
1921
+ // paints from the cached HTML: no await, no request, no spinner. Other
1922
+ // frameworks prefetch data only; rosetack prefetches the whole render because
1923
+ // the inlined bundle already contains every route.
1924
+ // Trade-off: the cache holds either a result or the in-flight promise (dedupes
1925
+ // hover storms); one isolated render runs at a time so signal-map swapping
1926
+ // stays correct without any merging logic. Entries are single-use: a consumed
1927
+ // entry disappears from the cache, which is also how tests observe a hit.
1928
+ // P1, three guards for link-heavy pages:
1929
+ // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
1930
+ // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
1931
+ // Trade-off: app-global, not per-route - per-route would carry the mode
1932
+ // in each document's shell.
1933
+ // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
1934
+ // the budget caps the QUEUE: a hover storm past it drops the excess
1935
+ // instead of rendering fifty routes nobody clicks.
1936
+ // 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
1937
+ // is evicted first (Map iteration order; entries are single-use, so
1938
+ // insertion order IS the recency order).
1939
+ let prefetchMode = ${JSON.stringify(prefetchMode)};
1940
+ export function setPrefetchMode(mode) { prefetchMode = mode; }
1941
+ const PREFETCH_BUDGET = 8;
1942
+ const PREFETCH_MAX_CACHED = 4;
1943
+ const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
1944
+ let prefetchQueue = Promise.resolve();
1945
+ let prefetchPending = 0;
1946
+
1947
+ // Applies the route's params to state. A [lang] segment whose dictionary is
1948
+ // a runtime pack (i18n.preload) is awaited HERE - the one place every client
1949
+ // render path goes through (navigation, prefetch, action adopt) - so a packed
1950
+ // locale costs one request per session and then renders from memory. A
1951
+ // preloaded locale (the default: every dictionary inline) resolves without
1952
+ // touching the network, so the common path stays synchronous in spirit.
1953
+ async function applyParams(route, pathname) {
1954
+ const patternParts = route.pattern.split('/');
1955
+ const pathParts = pathname.split('/');
1956
+ for (let i = 0; i < patternParts.length; i++) {
1957
+ if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
1958
+ }
1959
+ const langIdx = patternParts.indexOf(':lang');
1960
+ if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
1961
+ }
1962
+
1963
+ export function prefetch(pathname, source = 'hover') {
1964
+ if (prefetchMode === 'off') return;
1965
+ if (prefetchMode === 'hover' && source !== 'hover') return;
1966
+ if (prefetchMode === 'viewport' && source !== 'viewport') return;
1967
+ if (prefetchCache.has(pathname)) return;
1968
+ if (pathname === location.pathname) return; // already here: nothing to prefetch
1969
+ const route = routes.find((r) => matchRoute(r.pattern, pathname));
1970
+ if (!route) return;
1971
+ if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
1972
+ const p = prefetchQueue.then(async () => {
1973
+ try {
1974
+ // the isolated render also captures the onMount callbacks the route
1975
+ // queued and the onCleanup disposers it registered: the paint that
1976
+ // consumes this entry replays the mounts after wiring and adopts the
1977
+ // cleanups, so the prefetched route's timers are disposed on the next
1978
+ // navigation like any live route's
1979
+ const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
1980
+ await applyParams(route, pathname); // a packed locale's dictionary lands before the render
1981
+ const closes = [];
1982
+ const render = await getRender(route); // split mode: loads the route's chunk here
1983
+ const html = await render(closes, '');
1984
+ return { html, closes };
1985
+ });
1986
+ const entry = { ...result, state, mounts, cleanups };
1987
+ prefetchCache.set(pathname, entry); // promise -> result
1988
+ // evict oldest-first; in-flight promises are never evicted (evicting
1989
+ // one would only force a duplicate render)
1990
+ while (prefetchCache.size > PREFETCH_MAX_CACHED) {
1991
+ const oldest = prefetchCache.keys().next().value;
1992
+ if (prefetchCache.get(oldest) instanceof Promise) break;
1993
+ prefetchCache.delete(oldest);
1994
+ }
1995
+ return entry;
1996
+ } catch {
1997
+ prefetchCache.delete(pathname); // failed: the next hover retries
1998
+ return null;
1999
+ } finally {
2000
+ prefetchPending--;
2001
+ }
2002
+ });
2003
+ prefetchPending++;
2004
+ prefetchCache.set(pathname, p);
2005
+ prefetchQueue = p;
2006
+ }
2007
+
2008
+ export function prefetchStats() {
2009
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
2010
+ }
2011
+
2012
+ // One delegated listener per event type on the app container: survives DOM
2013
+ // swaps and cloned blocks, so handlers never need re-binding. A handler
2014
+ // compiled from a server action (data-on-*="$action:name") dispatches to
2015
+ // $action instead of the local handler registry.
2016
+ const DELEGATED = ['click', 'input', 'change', 'submit'];
2017
+ function bindEvents(container) {
2018
+ if (container.__rosetack_bound) return;
2019
+ container.__rosetack_bound = true;
2020
+ for (const ev of DELEGATED) {
2021
+ container.addEventListener(ev, (e) => {
2022
+ const el = e.target.closest('[data-on-' + ev + ']');
2023
+ if (!el || !container.contains(el)) return;
2024
+ const fn = el.getAttribute('data-on-' + ev);
2025
+ if (fn.startsWith('$action:')) return $action(fn.slice(8), e);
2026
+ const h = handlers[fn];
2027
+ if (h) h(e);
2028
+ });
2029
+ }
2030
+ }
2031
+
2032
+ // === Server actions from any event ===
2033
+ // POST the body to the current route and adopt the response in place: the
2034
+ // server runs the selected action, seeds its state patch, and re-renders, so
2035
+ // the swapped DOM is the page as it looks AFTER the action - one request, no
2036
+ // reload, and wire() patches only the marked nodes (no re-render). The
2037
+ // bootstrap's <form method="POST"> interception goes through the same door.
2038
+ async function postForm(body) {
2039
+ const res = await fetch(location.pathname, { method: 'POST', body });
2040
+ const html = await res.text();
2041
+ const doc = new DOMParser().parseFromString(html, 'text/html');
2042
+ const next = doc.getElementById('app');
2043
+ const st = doc.getElementById('__rosetack_state');
2044
+ const paint = () => {
2045
+ const container = document.getElementById('app');
2046
+ adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
2047
+ };
2048
+ if (document.startViewTransition) document.startViewTransition(paint);
2049
+ else paint();
2050
+ }
2051
+
2052
+ // Call a page's server action by name from any event handler:
2053
+ // <button on:click={like}> compiles to $action('like'). Without JS the
2054
+ // binding is inert - the progressive-enhancement story stays with forms.
2055
+ export async function $action(name, e) {
2056
+ if (e && e.preventDefault) e.preventDefault();
2057
+ const body = new FormData();
2058
+ body.append('__action', name);
2059
+ return postForm(body);
2060
+ }
2061
+
2062
+ export { postForm };
2063
+
2064
+ // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2065
+ // the existing nodes and bind events. initial=false: client-side navigation -
2066
+ // re-render the route chain from scratch and wire the fresh DOM.
2067
+ export async function start(container, pathname, initial) {
2068
+ clearMounts(); // stale mounts from a failed render never fire
2069
+ if (initial) {
2070
+ const el = document.getElementById('__rosetack_state');
2071
+ if (el) resumeState(el.textContent);
2072
+ }
2073
+ for (const route of routes) {
2074
+ if (matchRoute(route.pattern, pathname)) {
2075
+ // i18n: an unknown locale paints the 404 page, same as the server
2076
+ // (before the prefetch check: a cached entry for a bogus locale is
2077
+ // discarded, never painted)
2078
+ const langIdx = route.pattern.split('/').indexOf(':lang');
2079
+ ${langDirBlock}
2080
+ await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2081
+ return;
2082
+ }
2083
+ // Prefetched on hover/focus/touch: the render already ran, so paint its
2084
+ // HTML and adopt its signal entries - events then patch the very nodes
2085
+ // we wire, and no $data re-runs on click.
2086
+ let hit = initial ? undefined : prefetchCache.get(pathname);
2087
+ if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2088
+ if (hit) {
2089
+ prefetchCache.delete(pathname); // single-use: the next hover refetches
2090
+ resetEffects();
2091
+ restoreState(hit.state);
2092
+ container.innerHTML = hit.html;
2093
+ wire(container, hit.closes);
2094
+ bindEvents(container);
2095
+ hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2096
+ adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
2097
+ return;
2098
+ }
2099
+ if (!initial) {
2100
+ resetEffects();
2101
+ clearRequestState();
2102
+ }
2103
+ await applyParams(route, pathname);
2104
+ const closes = [];
2105
+ let html;
2106
+ try {
2107
+ const render = await getRender(route); // split mode: loads the route's chunk here
2108
+ html = await render(closes, '');
2109
+ } catch {
2110
+ // the route itself is broken: degrade to pages/500.rose (or the
2111
+ // built-in plain 500) instead of leaving the container empty
2112
+ await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2113
+ return;
2114
+ }
2115
+ if (!initial) container.innerHTML = html;
2116
+ wire(container, closes);
2117
+ bindEvents(container);
2118
+ flushMounts();
2119
+ return;
2120
+ }
2121
+ }
2122
+ // unmatched route: pages/404.rose renders (with its head + interactivity),
2123
+ // else the built-in plain 404 - and an i18n app's document returns to the
2124
+ // default locale, the same one the server stamps on its 404
2125
+ ${hasLang ? ` document.documentElement.lang = __defLocale;
2126
+ document.documentElement.removeAttribute('dir');` : ""}
2127
+ await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2128
+ }
2129
+
2130
+ // Adopt a server-rendered response in place - the JS-enabled half of
2131
+ // progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
2132
+ // via fetch and hands the response here. The DOM is swapped and wired with
2133
+ // the same zero-render trick as boot: re-run the route's render to rebuild
2134
+ // the marker closures, wire them against the adopted nodes. The page never
2135
+ // re-renders visibly, no hydration payload, no second request beyond the POST.
2136
+ export async function adopt(container, html, stateJson) {
2137
+ resetEffects();
2138
+ clearRequestState();
2139
+ clearMounts(); // stale mounts from a failed render never fire
2140
+ resumeState(stateJson);
2141
+ container.innerHTML = html;
2142
+ // keep the embedded state in sync so a later SPA-fallback check agrees
2143
+ const st = document.getElementById('__rosetack_state');
2144
+ if (st) st.textContent = stateJson;
2145
+ for (const route of routes) {
2146
+ if (matchRoute(route.pattern, location.pathname)) {
2147
+ await applyParams(route, location.pathname);
2148
+ const closes = [];
2149
+ try {
2150
+ const render = await getRender(route); // split mode: loads the route's chunk here
2151
+ await render(closes, '');
2152
+ } catch {
2153
+ // the adopted response's route is broken (e.g. the action's page
2154
+ // throws): keep the swapped DOM but skip wiring it
2155
+ return;
2156
+ }
2157
+ wire(container, closes);
2158
+ bindEvents(container);
2159
+ flushMounts();
2160
+ return;
2161
+ }
2162
+ }
2163
+ }
2164
+ // === refresh() implementation ===
2165
+ // Re-render the current route in place: the client half of router.refresh()
2166
+ // (a router refresh) / (a full invalidation). Same machinery as a client-side
2167
+ // navigation to the current path - $data re-runs, state re-seeds from the
2168
+ // fresh render, wire() patches the marked nodes - but a refresh never lands
2169
+ // a prefetch entry: a hover from a minute ago is exactly what it exists to
2170
+ // bypass. Zero requests: the render (and its $data) runs in the page.
2171
+ // Trade-off: state resets like navigation (no per-key retention); add
2172
+ // retention when an app needs refresh-without-losing-input.
2173
+ setRefreshHook(async () => {
2174
+ prefetchCache.delete(location.pathname);
2175
+ await start(document.getElementById('app'), location.pathname, false);
2176
+ });
2177
+ `;
2178
+ await fs.promises.writeFile(path.join(buildDir, "client-entry.js"), clientEntry);
2179
+ if (split) {
2180
+ await fs.promises.rm(path.join(outDir, "chunks"), { recursive: true, force: true });
2181
+ await esbuild.build({
2182
+ entryPoints: [path.join(buildDir, "client-entry.js")],
2183
+ bundle: true,
2184
+ format: "esm",
2185
+ platform: "browser",
2186
+ minify: true,
2187
+ splitting: true,
2188
+ outdir: outDir,
2189
+ entryNames: "client",
2190
+ chunkNames: "chunks/[name]-[hash]",
2191
+ write: true,
2192
+ ...TS_LOADER
2193
+ });
2194
+ } else {
2195
+ await esbuild.build({
2196
+ entryPoints: [path.join(buildDir, "client-entry.js")],
2197
+ bundle: true,
2198
+ outfile: path.join(outDir, "client.js"),
2199
+ format: "esm",
2200
+ platform: "browser",
2201
+ minify: true,
2202
+ write: true,
2203
+ ...TS_LOADER
2204
+ });
2205
+ }
2206
+ await fs.promises.rm(buildDir, { recursive: true, force: true });
2207
+ const publicDir = path.join(root, "public");
2208
+ if (fs.existsSync(publicDir)) {
2209
+ const outPublic = path.join(outDir, "public");
2210
+ await fs.promises.mkdir(outPublic, { recursive: true });
2211
+ const assets = await fs.promises.readdir(publicDir);
2212
+ await Promise.all(
2213
+ assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
2214
+ );
2215
+ }
2216
+ console.log("rosetack zero-JS report:");
2217
+ for (const line of buildReport(infos, compiled)) console.log(" " + line);
2218
+ for (const { info, i } of pages) {
2219
+ if (!routeShipsNoJs(infos, compiled, i)) continue;
2220
+ for (const ci of [i, ...layoutsOf(infos, i)]) {
2221
+ for (const w of compiled[ci].jsWarnings ?? []) {
2222
+ console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
2223
+ }
2224
+ }
2225
+ }
2226
+ return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2227
+ }
2228
+ async function scanRoseFiles(root) {
2229
+ const pagesDir = path.join(root, "src", "pages");
2230
+ if (!fs.existsSync(pagesDir)) return [];
2231
+ async function scan(dir) {
2232
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
2233
+ const files = [];
2234
+ for (const entry of entries) {
2235
+ const full = path.join(dir, entry.name);
2236
+ if (entry.isDirectory()) files.push(...await scan(full));
2237
+ else if (entry.name.endsWith(".rose")) files.push(full);
2238
+ }
2239
+ return files;
2240
+ }
2241
+ return scan(pagesDir);
2242
+ }
2243
+ async function scanComponentFiles(root) {
2244
+ const compDir = path.join(root, "src", "components");
2245
+ if (!fs.existsSync(compDir)) return [];
2246
+ async function scan(dir) {
2247
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
2248
+ const files = [];
2249
+ for (const entry of entries) {
2250
+ const full = path.join(dir, entry.name);
2251
+ if (entry.isDirectory()) files.push(...await scan(full));
2252
+ else if (entry.name.endsWith(".rose")) files.push(full);
2253
+ }
2254
+ return files;
2255
+ }
2256
+ return scan(compDir);
2257
+ }
2258
+ function isAncestorDir(layoutPath, pagePath) {
2259
+ const layoutDir = path.dirname(layoutPath);
2260
+ const pageDir = path.dirname(pagePath);
2261
+ return pageDir === layoutDir || pageDir.startsWith(layoutDir + path.sep);
2262
+ }
2263
+ function getRouteInfo(filePath, root) {
2264
+ const pagesDir = path.join(root, "src", "pages");
2265
+ const relative3 = path.relative(pagesDir, filePath).replace(/\\/g, "/");
2266
+ const withoutExt = relative3.replace(/\.rose$/, "");
2267
+ const base = path.posix.basename(withoutExt);
2268
+ const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2269
+ const isLayout = !isComponent && base === "_layout";
2270
+ const isNotFound = !isComponent && base === "404";
2271
+ const isError = !isComponent && base === "500";
2272
+ const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2273
+ const isMiddleware = !isComponent && withoutExt === "_middleware";
2274
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout");
2275
+ if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
2276
+ const routeParts = parts.map(
2277
+ (part) => part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part
2278
+ );
2279
+ let routePath;
2280
+ if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2281
+ routePath = "/";
2282
+ } else {
2283
+ routePath = "/" + routeParts.join("/");
2284
+ }
2285
+ return {
2286
+ filePath,
2287
+ routePath,
2288
+ pattern: routePath,
2289
+ paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
2290
+ isLayout,
2291
+ isNotFound,
2292
+ isError,
2293
+ isApi,
2294
+ isMiddleware,
2295
+ isComponent
2296
+ };
2297
+ }
2298
+ function capitalize(s) {
2299
+ return s.charAt(0).toUpperCase() + s.slice(1);
2300
+ }
2301
+
2302
+ // src/cli/shell.ts
2303
+ import * as fs2 from "fs";
2304
+ import * as path2 from "path";
2305
+ import * as esbuild2 from "esbuild";
2306
+ import { createHash } from "crypto";
2307
+ var OUT_DIR = path2.join(process.cwd(), "dist");
2308
+ var clientCache = null;
2309
+ var splitMode = false;
2310
+ function setBundleMode(mode) {
2311
+ splitMode = mode === "split";
2312
+ }
2313
+ function getClientSource() {
2314
+ if (splitMode) return null;
2315
+ const file = path2.join(OUT_DIR, "client.js");
2316
+ try {
2317
+ const st = fs2.statSync(file);
2318
+ if (!clientCache || clientCache.mtimeMs !== st.mtimeMs) {
2319
+ clientCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
2320
+ }
2321
+ return clientCache.source;
2322
+ } catch {
2323
+ return null;
2324
+ }
2325
+ }
2326
+ var styleCache = null;
2327
+ function getStyles() {
2328
+ const file = path2.join(OUT_DIR, "styles.css");
2329
+ try {
2330
+ const st = fs2.statSync(file);
2331
+ if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
2332
+ styleCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
2333
+ }
2334
+ return styleCache.source;
2335
+ } catch {
2336
+ return "";
2337
+ }
2338
+ }
2339
+ var BOOTSTRAP = esbuild2.transformSync(`
2340
+ const __app = document.getElementById('app');
2341
+ // Native View Transitions around client-side navigation (progressive:
2342
+ // browsers without the API navigate normally, no polyfill, no CSS required).
2343
+ function __navigate(pathname) {
2344
+ const paint = () => start(__app, pathname);
2345
+ if (document.startViewTransition) {
2346
+ return document.startViewTransition(paint).updateCallbackDone;
2347
+ }
2348
+ return paint();
2349
+ }
2350
+ window.addEventListener('popstate', () => __navigate(window.location.pathname));
2351
+ document.addEventListener('click', (e) => {
2352
+ const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
2353
+ if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
2354
+ e.preventDefault();
2355
+ history.pushState(null, '', a.getAttribute('href'));
2356
+ __navigate(window.location.pathname);
2357
+ }
2358
+ });
2359
+ // Prefetch the target route's full render (including $data) on hover, keyboard
2360
+ // focus, or touch - the click that follows paints from cache: no await, no
2361
+ // request. Other frameworks prefetch data only; rosetack prefetches the render
2362
+ // because the inlined bundle already contains every route.
2363
+ function __prefetchHandler(e) {
2364
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
2365
+ if (a && prefetch) prefetch(a.getAttribute('href'), 'hover');
2366
+ }
2367
+ document.addEventListener('mouseover', __prefetchHandler);
2368
+ document.addEventListener('focusin', __prefetchHandler);
2369
+ document.addEventListener('touchstart', __prefetchHandler, { passive: true });
2370
+ // Viewport + idle prefetch (viewport-triggered): once a link scrolls into view and the
2371
+ // browser is idle, its route renders ahead of any interaction. trade-off: both
2372
+ // APIs are feature-detected; without them the hover/focus/touch path above
2373
+ // still covers every link.
2374
+ if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
2375
+ const io = new IntersectionObserver((entries) => {
2376
+ for (const e of entries) {
2377
+ if (!e.isIntersecting) continue;
2378
+ io.unobserve(e.target); // one-shot per element; fresh links re-observe after nav
2379
+ requestIdleCallback(() => prefetch(e.target.getAttribute('href'), 'viewport'));
2380
+ }
2381
+ });
2382
+ // observing an already-observed element is a no-op, so re-sweeping is cheap
2383
+ const observeLinks = () => {
2384
+ for (const a of document.querySelectorAll('a[href^="/"]')) io.observe(a);
2385
+ };
2386
+ observeLinks();
2387
+ // navigation swaps the container's innerHTML: re-observe the fresh links
2388
+ const __rawNav = __navigate;
2389
+ __navigate = (p) => __rawNav(p).then(observeLinks, () => {});
2390
+ }
2391
+ // Progressive-enhancement forms: <form method="POST"> backed by a server
2392
+ // action. With JS the submit is intercepted and handed to postForm (one
2393
+ // request, in-place adopt). Without JS the browser performs the native POST
2394
+ // and the server re-renders the page: the same form works with JavaScript
2395
+ // disabled, which Server Actions in other frameworks do not.
2396
+ document.addEventListener('submit', (e) => {
2397
+ const f = e.target;
2398
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
2399
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
2400
+ e.preventDefault();
2401
+ postForm(new FormData(f));
2402
+ });
2403
+ // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
2404
+ // If the document was rendered for a DIFFERENT route (a static-file server's
2405
+ // SPA fallback serves index.html for unknown paths), adopt nothing - let the
2406
+ // client router render the requested route from scratch.
2407
+ const __st = document.getElementById('__rosetack_state');
2408
+ const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
2409
+ if (__state.__route === window.location.pathname) {
2410
+ start(__app, window.location.pathname, true);
2411
+ } else {
2412
+ start(__app, window.location.pathname);
2413
+ }
2414
+ `, { minify: true }).code;
2415
+ var CSP_TAIL = `style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
2416
+ var cspCache = null;
2417
+ var EXTERNAL_BOOTSTRAP = `
2418
+ import { start, prefetch, postForm } from '/client.js';
2419
+ ${BOOTSTRAP}`;
2420
+ function inlineScript(client) {
2421
+ return `
2422
+ ${client}
2423
+ ${BOOTSTRAP}`;
2424
+ }
2425
+ function mintNonce() {
2426
+ const bytes = new Uint8Array(16);
2427
+ crypto.getRandomValues(bytes);
2428
+ let raw = "";
2429
+ for (const b of bytes) raw += String.fromCharCode(b);
2430
+ return btoa(raw);
2431
+ }
2432
+ function securityHeaders(client, nonce = "") {
2433
+ if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
2434
+ if (!cspCache || cspCache.for !== client) {
2435
+ const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(EXTERNAL_BOOTSTRAP, "utf-8").digest("base64")}'`;
2436
+ cspCache = {
2437
+ for: client,
2438
+ value: `script-src ${scriptSrc}; ${CSP_TAIL}`
2439
+ };
2440
+ }
2441
+ return { "Content-Security-Policy": cspCache.value };
2442
+ }
2443
+ 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==">';
2444
+ var STYLES = `
2445
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
2446
+ button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
2447
+ a { color: #e91e63; text-decoration: none; font-weight: bold; }
2448
+ a:hover { text-decoration: underline; }
2449
+ nav a { margin-right: 1rem; }
2450
+ .rh { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; border-bottom: 2px solid #e91e63; margin-bottom: 1.5rem; padding-bottom: 0.75rem; }
2451
+ .rb { font-size: 1.6rem; }
2452
+ .rbrand { display: inline-flex; align-items: center; gap: 0.5em; }
2453
+ .rlogo { height: 1em; width: 1em; vertical-align: -0.08em; margin-right: 0.2em; }
2454
+ @media (max-width: 640px) {
2455
+ .rh { flex-direction: column; align-items: flex-start; gap: 0.75rem; }
2456
+ nav a:last-child { margin-right: 0; }
2457
+ }
2458
+ .rn { display: inline-block; margin-left: 1.5rem; }
2459
+ .rf { margin-top: 2rem; color: #888; font-size: 0.85rem; }
2460
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
2461
+ `;
2462
+ var STYLES_MIN = STYLES.replace(
2463
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
2464
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
2465
+ ).trim();
2466
+ function mergeHeadBlocks(blocks) {
2467
+ const byKey = /* @__PURE__ */ new Map();
2468
+ const order = [];
2469
+ const put = (key, html) => {
2470
+ if (!byKey.has(key)) {
2471
+ byKey.set(key, html);
2472
+ order.push(key);
2473
+ }
2474
+ };
2475
+ for (const block of blocks) {
2476
+ for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
2477
+ for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
2478
+ const tag = m[1].toLowerCase();
2479
+ const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
2480
+ const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
2481
+ const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
2482
+ put(key, marked);
2483
+ }
2484
+ }
2485
+ return order.map((k) => byKey.get(k)).join("\n ");
2486
+ }
2487
+ function clientScriptTag(client, nonce = "") {
2488
+ const n = nonce ? ` nonce="${nonce}"` : "";
2489
+ return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
2490
+ <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
2491
+ }
2492
+ function shellOpen(styles = getStyles(), lang = "en", dir = "") {
2493
+ const styleTag = styles ? `
2494
+ <style>${styles}</style>` : "";
2495
+ return `<!DOCTYPE html>
2496
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
2497
+ <head>
2498
+ <meta charset="UTF-8">
2499
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
2500
+ <title>RoseTack</title>
2501
+ <style>${STYLES_MIN}</style>${styleTag}
2502
+ ${FAVICON}
2503
+ </head>
2504
+ <body>
2505
+ <div id="app">`;
2506
+ }
2507
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
2508
+ const clientTag = clientScriptTag(client, nonce);
2509
+ const mergedHead = mergeHeadBlocks(head);
2510
+ const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
2511
+ const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
2512
+ ${FAVICON}`;
2513
+ const headTags = mergedHead ? `
2514
+ ${mergedHead}` : "";
2515
+ const styleTag = styles ? `
2516
+ <style>${styles}</style>` : "";
2517
+ const jsTail = js ? `
2518
+ <script type="application/json" id="__rosetack_state">${stateJson}</script>
2519
+ ${clientTag}` : "";
2520
+ return `<!DOCTYPE html>
2521
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
2522
+ <head>
2523
+ <meta charset="UTF-8">
2524
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
2525
+ ${titleTag}
2526
+ <style>${STYLES_MIN}</style>${styleTag}
2527
+ </head>
2528
+ <body>
2529
+ <div id="app">${ssrHtml}</div>${jsTail}
2530
+ </body>
2531
+ </html>`;
2532
+ }
2533
+ function getHtmlShell(ssrHtml, stateJson, head = [], js = true, lang = "en", dir = "", nonce = "") {
2534
+ return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce);
2535
+ }
2536
+
2537
+ // src/cli/index.ts
2538
+ function pickEncoding(req) {
2539
+ const ae = req.headers["accept-encoding"] || "";
2540
+ if (ae.includes("br")) return "br";
2541
+ if (ae.includes("gzip")) return "gzip";
2542
+ if (ae.includes("deflate")) return "deflate";
2543
+ return null;
2544
+ }
2545
+ var brotliFast = { [zlib.constants.BROTLI_PARAM_QUALITY]: 5 };
2546
+ function compress(enc, data) {
2547
+ if (enc === "br") return zlib.brotliCompressSync(data, { params: brotliFast });
2548
+ if (enc === "gzip") return zlib.gzipSync(data);
2549
+ return zlib.deflateSync(data);
2550
+ }
2551
+ function createCompressor(enc) {
2552
+ if (enc === "br") return zlib.createBrotliCompress({ params: brotliFast });
2553
+ if (enc === "gzip") return zlib.createGzip();
2554
+ return zlib.createDeflate();
2555
+ }
2556
+ function sendHtml(req, res, status, html, extraHeaders) {
2557
+ res.statusCode = status;
2558
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
2559
+ res.setHeader("Vary", "Accept-Encoding");
2560
+ if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
2561
+ let hash = 2166136261;
2562
+ for (let i = 0; i < html.length; i++) {
2563
+ hash ^= html.charCodeAt(i);
2564
+ hash = hash * 16777619 >>> 0;
2565
+ }
2566
+ const etag = `W/"${html.length}-${hash.toString(16)}"`;
2567
+ if (req.headers["if-none-match"] === etag) {
2568
+ res.statusCode = 304;
2569
+ res.end();
2570
+ return;
2571
+ }
2572
+ res.setHeader("ETag", etag);
2573
+ const enc = pickEncoding(req);
2574
+ if (enc) {
2575
+ res.setHeader("Content-Encoding", enc);
2576
+ res.end(compress(enc, html));
2577
+ } else {
2578
+ res.end(html);
2579
+ }
2580
+ }
2581
+ function writeWebHeaders(web, res) {
2582
+ const cookies = web.headers.getSetCookie?.() ?? [];
2583
+ web.headers.forEach((v, k) => {
2584
+ if (cookies.length && k.toLowerCase() === "set-cookie") return;
2585
+ res.setHeader(k, v);
2586
+ });
2587
+ if (cookies.length) res.setHeader("set-cookie", cookies);
2588
+ }
2589
+ async function sendWebResponse(web, res) {
2590
+ writeWebHeaders(web, res);
2591
+ res.statusCode = web.status;
2592
+ res.end(Buffer.from(await web.arrayBuffer()));
2593
+ }
2594
+ async function sendPage(req, res, ssrModule, hookCtx, page, routePath) {
2595
+ let status = page.status ?? 200;
2596
+ const nonce = nonceFor(ssrModule, routePath);
2597
+ let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
2598
+ let headers = pageHeaders(ssrModule, routePath, nonce);
2599
+ if (hookCtx) {
2600
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, { status, headers }));
2601
+ status = out.status;
2602
+ headers = webHeadersToNode(out);
2603
+ html = await out.text();
2604
+ }
2605
+ sendHtml(req, res, status, html, headers);
2606
+ }
2607
+ var fileCache = /* @__PURE__ */ new Map();
2608
+ var SRC_DIR = process.argv[3] ? path3.resolve(process.argv[3]) : process.cwd();
2609
+ var OUT_DIR2 = path3.join(process.cwd(), "dist");
2610
+ var PORT = Number(process.env.PORT) || 3e3;
2611
+ var serverModule = null;
2612
+ var serverMtime = -1;
2613
+ var serverVersion = 0;
2614
+ async function loadServer() {
2615
+ const file = path3.join(OUT_DIR2, "server.js");
2616
+ const mtimeMs = fs3.statSync(file).mtimeMs;
2617
+ if (!serverModule || mtimeMs !== serverMtime) {
2618
+ serverMtime = mtimeMs;
2619
+ serverVersion++;
2620
+ serverModule = await import(pathToFileURL2(file).href + "?v=" + serverVersion);
2621
+ }
2622
+ return serverModule;
2623
+ }
2624
+ async function build2() {
2625
+ const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR2);
2626
+ await clearPrerendered(OUT_DIR2);
2627
+ setBundleMode(bundle);
2628
+ const skipped = await prerender(routes);
2629
+ await fs3.promises.writeFile(path3.join(OUT_DIR2, "broken.json"), JSON.stringify(skipped));
2630
+ const ssrModule = await loadServer();
2631
+ await fs3.promises.writeFile(path3.join(OUT_DIR2, "headers.json"), JSON.stringify({
2632
+ default: securityHeaders(getClientSource()),
2633
+ routes: ssrModule.routeHeaders ?? []
2634
+ }));
2635
+ await writeBrotli(OUT_DIR2);
2636
+ }
2637
+ var BROTLI_EXT = /* @__PURE__ */ new Set([".html", ".js", ".css", ".json", ".svg", ".txt"]);
2638
+ async function writeBrotli(dir) {
2639
+ for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
2640
+ const p = path3.join(dir, e.name);
2641
+ if (e.isDirectory()) {
2642
+ await writeBrotli(p);
2643
+ continue;
2644
+ }
2645
+ if (!BROTLI_EXT.has(path3.extname(e.name).toLowerCase())) continue;
2646
+ await fs3.promises.writeFile(p + ".br", zlib.brotliCompressSync(await fs3.promises.readFile(p)));
2647
+ }
2648
+ }
2649
+ async function clearPrerendered(dir, depth = 0) {
2650
+ for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
2651
+ if (depth === 0 && e.name === "locales" && e.isDirectory()) continue;
2652
+ const p = path3.join(dir, e.name);
2653
+ if (e.isDirectory()) {
2654
+ await clearPrerendered(p, depth + 1);
2655
+ continue;
2656
+ }
2657
+ if (!/\.(?:html|json)(?:\.br)?$/.test(e.name)) continue;
2658
+ for (let attempt = 0; ; attempt++) {
2659
+ try {
2660
+ await fs3.promises.rm(p, { force: true });
2661
+ break;
2662
+ } catch (err) {
2663
+ if (attempt >= 2 || !/EPERM|EBUSY|EACCES/.test(String(err))) throw err;
2664
+ await new Promise((r) => setTimeout(r, 50 * (attempt + 1)));
2665
+ }
2666
+ }
2667
+ }
2668
+ }
2669
+ async function prerender(routes) {
2670
+ const ssrModule = await loadServer();
2671
+ const skipped = [];
2672
+ const write = async (routePath) => {
2673
+ const mw = await ssrModule.runMiddleware({ method: "GET", url: routePath, headers: {} });
2674
+ if (mw) {
2675
+ console.error(`prerender skipped for ${routePath}: the middleware short-circuits at build time`);
2676
+ skipped.push(routePath);
2677
+ return;
2678
+ }
2679
+ const page = await ssrModule.renderPage(routePath);
2680
+ if (page.status === 500) {
2681
+ console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
2682
+ skipped.push(routePath);
2683
+ return;
2684
+ }
2685
+ const routeDir = routePath === "/" ? OUT_DIR2 : path3.join(OUT_DIR2, routePath.slice(1));
2686
+ await fs3.promises.mkdir(routeDir, { recursive: true });
2687
+ await fs3.promises.writeFile(path3.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
2688
+ console.log(`prerendered ${routePath} -> ${path3.relative(process.cwd(), path3.join(routeDir, "index.html"))}`);
2689
+ };
2690
+ for (const info of routes) {
2691
+ if (ssrModule.dynamicRoutes.includes(info.routePath)) {
2692
+ console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
2693
+ continue;
2694
+ }
2695
+ if (info.paramNames.length === 0) {
2696
+ try {
2697
+ await write(info.routePath);
2698
+ } catch (err) {
2699
+ console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
2700
+ skipped.push(info.routePath);
2701
+ }
2702
+ continue;
2703
+ }
2704
+ try {
2705
+ const paramsExport = ssrModule.routeParams?.[info.routePath];
2706
+ const raw = typeof paramsExport === "function" ? await paramsExport() : paramsExport;
2707
+ const paths = enumerateParams(info.pattern, info.paramNames, raw ?? {});
2708
+ for (const p of paths) await write(p);
2709
+ if (paths.length === 0) console.log(`dynamic route ${info.routePath}: no params export, rendered on demand`);
2710
+ } catch (err) {
2711
+ console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
2712
+ skipped.push(info.routePath);
2713
+ }
2714
+ }
2715
+ const apiPrerender = ssrModule.apiPrerender ?? {};
2716
+ for (const [routePath, on] of Object.entries(apiPrerender)) {
2717
+ if (!on) continue;
2718
+ try {
2719
+ const res = await ssrModule.handleApi("GET", routePath, new Request("http://localhost" + routePath));
2720
+ if (res.status !== 200) {
2721
+ console.error(`api prerender skipped for ${routePath}: GET answered ${res.status}`);
2722
+ continue;
2723
+ }
2724
+ const body = await res.text();
2725
+ const outFile = path3.join(OUT_DIR2, routePath.slice(1) + ".json");
2726
+ await fs3.promises.mkdir(path3.dirname(outFile), { recursive: true });
2727
+ await fs3.promises.writeFile(outFile, body);
2728
+ console.log(`prerendered api ${routePath} -> ${path3.relative(process.cwd(), outFile)}`);
2729
+ } catch (err) {
2730
+ console.error(`api prerender skipped for ${routePath}: ${err instanceof Error ? err.message : err}`);
2731
+ }
2732
+ }
2733
+ return skipped;
2734
+ }
2735
+ function enumerateParams(pattern, names, raw) {
2736
+ let combos = [[]];
2737
+ for (const name of names) {
2738
+ const values = (Array.isArray(raw[name]) ? raw[name] : []).map((v) => String(v));
2739
+ combos = combos.flatMap((c) => values.map((v) => [...c, v]));
2740
+ }
2741
+ return combos.map((values) => {
2742
+ let i = 0;
2743
+ return pattern.split("/").map((seg) => seg.startsWith(":") ? encodeURIComponent(values[i++]) : seg).join("/");
2744
+ });
2745
+ }
2746
+ var ASSET_EXT = /* @__PURE__ */ new Set([".js", ".css", ".json", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp", ".woff", ".woff2", ".txt", ".xml"]);
2747
+ function pageHeaders(ssrModule, pathname, nonce = "") {
2748
+ const headers = {};
2749
+ for (const [k, v] of Object.entries(securityHeaders(getClientSource(), nonce))) headers[k.toLowerCase()] = v;
2750
+ const own = ssrModule.headersFor?.(pathname);
2751
+ if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
2752
+ return headers;
2753
+ }
2754
+ function nonceFor(ssrModule, pathname) {
2755
+ return ssrModule.cspNonce?.(pathname) ? mintNonce() : "";
2756
+ }
2757
+ var isrBusy = /* @__PURE__ */ new Set();
2758
+ function revalidateInBackground(routePath, filePath) {
2759
+ if (isrBusy.has(filePath)) return;
2760
+ isrBusy.add(filePath);
2761
+ void (async () => {
2762
+ try {
2763
+ const ssrModule = await loadServer();
2764
+ const page = await ssrModule.renderPage(routePath);
2765
+ if (page.status === 200) {
2766
+ await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
2767
+ fileCache.delete(filePath);
2768
+ console.log(`rosetack: revalidated ${routePath} in the background`);
2769
+ }
2770
+ } catch (err) {
2771
+ console.error("rosetack: background revalidation failed for", routePath, err instanceof Error ? err.message : err);
2772
+ } finally {
2773
+ isrBusy.delete(filePath);
2774
+ }
2775
+ })();
2776
+ }
2777
+ var MAX_BODY = Number(process.env.rosetack_MAX_BODY) || 1024 * 1024;
2778
+ function readBody(req, res, onDone) {
2779
+ const chunks = [];
2780
+ let size = 0;
2781
+ let refused = false;
2782
+ req.on("data", (c) => {
2783
+ if (refused) return;
2784
+ size += c.length;
2785
+ if (size > MAX_BODY) {
2786
+ refused = true;
2787
+ res.statusCode = 413;
2788
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
2789
+ res.end(`Payload too large (limit ${MAX_BODY} bytes)`);
2790
+ return;
2791
+ }
2792
+ chunks.push(c);
2793
+ });
2794
+ req.on("end", () => {
2795
+ if (!refused) onDone(Buffer.concat(chunks));
2796
+ });
2797
+ req.on("error", () => {
2798
+ });
2799
+ }
2800
+ function crossSiteWrite(req) {
2801
+ const m = req.method;
2802
+ if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
2803
+ const origin = req.headers.origin;
2804
+ if (origin) {
2805
+ let host;
2806
+ try {
2807
+ host = new URL(origin).host;
2808
+ } catch {
2809
+ return { status: 403, body: "Cross-site request blocked (unparsable Origin header)" };
2810
+ }
2811
+ return host === req.headers.host ? null : { status: 403, body: "Cross-site request blocked (Origin does not match Host)" };
2812
+ }
2813
+ const site = req.headers["sec-fetch-site"];
2814
+ if (site && site !== "same-origin" && site !== "same-site" && site !== "none") {
2815
+ return { status: 403, body: `Cross-site request blocked (sec-fetch-site: ${site})` };
2816
+ }
2817
+ return null;
2818
+ }
2819
+ function withAccessLog(handler, tag) {
2820
+ return (req, res) => {
2821
+ const started = process.hrtime.bigint();
2822
+ let bytes = 0;
2823
+ const write = res.write.bind(res);
2824
+ const end = res.end.bind(res);
2825
+ res.write = (chunk, ...rest) => {
2826
+ if (chunk) bytes += Buffer.byteLength(chunk);
2827
+ return write(chunk, ...rest);
2828
+ };
2829
+ res.end = (chunk, ...rest) => {
2830
+ if (chunk) bytes += Buffer.byteLength(chunk);
2831
+ return end(chunk, ...rest);
2832
+ };
2833
+ res.on("finish", () => {
2834
+ const ms = Number(process.hrtime.bigint() - started) / 1e6;
2835
+ const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1e3).toFixed(0)}us`;
2836
+ console.log(`${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ""} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
2837
+ });
2838
+ handler(req, res);
2839
+ };
2840
+ }
2841
+ async function hookContext(req) {
2842
+ const headers = {};
2843
+ for (const [k, v] of Object.entries(req.headers)) {
2844
+ if (v !== void 0) headers[k] = Array.isArray(v) ? v.join(", ") : String(v);
2845
+ }
2846
+ const request = new Request(`http://${req.headers.host || "localhost"}${req.url}`, {
2847
+ method: req.method || "GET",
2848
+ headers
2849
+ });
2850
+ const url = new URL(request.url);
2851
+ return { request, url, method: request.method, pathname: url.pathname, state: {} };
2852
+ }
2853
+ function webHeadersToNode(web) {
2854
+ const out = {};
2855
+ const cookies = web.headers.getSetCookie?.() ?? [];
2856
+ web.headers.forEach((v, k) => {
2857
+ if (cookies.length && k.toLowerCase() === "set-cookie") return;
2858
+ out[k] = v;
2859
+ });
2860
+ if (cookies.length) out["set-cookie"] = cookies;
2861
+ return out;
2862
+ }
2863
+ function serveStatic(dir, isr = false) {
2864
+ return (req, res) => {
2865
+ const blocked = crossSiteWrite(req);
2866
+ if (blocked) {
2867
+ res.statusCode = blocked.status;
2868
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
2869
+ res.end(blocked.body);
2870
+ return;
2871
+ }
2872
+ loadServer().then(async (ssrModule) => {
2873
+ const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true ? await hookContext(req) : null;
2874
+ if (hookCtx) {
2875
+ const short = await ssrModule.runRequestHooks(hookCtx);
2876
+ if (short) {
2877
+ await sendWebResponse(await ssrModule.runResponseHooks(hookCtx, short), res);
2878
+ return;
2879
+ }
2880
+ }
2881
+ const apiPath0 = pathnameOf(req.url);
2882
+ const isPagePost = req.method === "POST" && !ssrModule.isApi(apiPath0);
2883
+ if (!isPagePost && ssrModule.middleware) {
2884
+ const mw = await ssrModule.runMiddleware(req);
2885
+ if (mw) {
2886
+ await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
2887
+ return;
2888
+ }
2889
+ }
2890
+ const apiPath = pathnameOf(req.url);
2891
+ if (ssrModule.isApi(apiPath)) {
2892
+ readBody(req, res, async (body) => {
2893
+ try {
2894
+ const headers = {};
2895
+ for (const [k, v] of Object.entries(req.headers)) {
2896
+ if (v !== void 0) headers[k] = Array.isArray(v) ? v.join(", ") : String(v);
2897
+ }
2898
+ const request = new Request(`http://${req.headers.host || "localhost"}${req.url}`, {
2899
+ method: req.method || "GET",
2900
+ headers,
2901
+ body: body.length > 0 ? body : void 0
2902
+ });
2903
+ let apiRes = await ssrModule.handleApi(req.method || "GET", apiPath, request);
2904
+ if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
2905
+ writeWebHeaders(apiRes, res);
2906
+ res.statusCode = apiRes.status;
2907
+ res.end(Buffer.from(await apiRes.arrayBuffer()));
2908
+ } catch {
2909
+ res.statusCode = 500;
2910
+ res.setHeader("Content-Type", "application/json");
2911
+ res.end('{"error":"api handler failed"}');
2912
+ }
2913
+ });
2914
+ return;
2915
+ }
2916
+ if (req.method === "POST") {
2917
+ readBody(req, res, async (body) => {
2918
+ try {
2919
+ const form = await new Response(body, {
2920
+ headers: { "content-type": req.headers["content-type"] || "application/x-www-form-urlencoded" }
2921
+ }).formData();
2922
+ if (ssrModule.middleware) {
2923
+ const mw = await ssrModule.runMiddleware(req, form);
2924
+ if (mw) {
2925
+ await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
2926
+ return;
2927
+ }
2928
+ }
2929
+ const page2 = await ssrModule.renderPage(req.url || "/", form);
2930
+ await sendPage(req, res, ssrModule, hookCtx, page2, pathnameOf(req.url || "/"));
2931
+ } catch {
2932
+ res.statusCode = 400;
2933
+ res.end("Bad request");
2934
+ }
2935
+ });
2936
+ return;
2937
+ }
2938
+ let safe = path3.normalize(req.url || "/").replace(/^(\.\.(\/)?)+/, "");
2939
+ if (safe === "\\" || safe === "/") safe = "/";
2940
+ let filePath = path3.join(dir, safe);
2941
+ if (!fs3.existsSync(filePath) && ASSET_EXT.has(path3.extname(safe).toLowerCase())) {
2942
+ const pubFile = path3.join(dir, "public", safe);
2943
+ if (fs3.existsSync(pubFile)) filePath = pubFile;
2944
+ }
2945
+ if (fs3.existsSync(filePath) && fs3.statSync(filePath).isDirectory()) {
2946
+ filePath = path3.join(filePath, "index.html");
2947
+ }
2948
+ if (/\.(?:br|gz)$/i.test(safe)) {
2949
+ const base = filePath.replace(/\.(?:br|gz)$/i, "");
2950
+ if (fs3.existsSync(base)) filePath = base;
2951
+ }
2952
+ const isAsset = ASSET_EXT.has(path3.extname(safe).toLowerCase());
2953
+ const isDynamic = !isAsset && ssrModule.dynamicRoutes?.includes(pathnameOf(req.url));
2954
+ if (!isDynamic && fs3.existsSync(filePath) && fs3.statSync(filePath).isFile()) {
2955
+ const st = fs3.statSync(filePath);
2956
+ const rev = isAsset ? void 0 : (ssrModule.revalidate || []).find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
2957
+ if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1e3) {
2958
+ revalidateInBackground(pathnameOf(req.url), filePath);
2959
+ }
2960
+ let entry = fileCache.get(filePath);
2961
+ if (!entry || entry.mtimeMs !== st.mtimeMs) {
2962
+ const raw = fs3.readFileSync(filePath);
2963
+ entry = {
2964
+ mtimeMs: st.mtimeMs,
2965
+ raw,
2966
+ // A file's compressed forms are computed ONCE and then served from this cache
2967
+ // forever …
2968
+ br: zlib.brotliCompressSync(raw),
2969
+ gzip: zlib.gzipSync(raw, { level: 9 }),
2970
+ etag: `W/"${st.size}-${st.mtimeMs}"`
2971
+ };
2972
+ fileCache.set(filePath, entry);
2973
+ }
2974
+ const ext = path3.extname(filePath);
2975
+ const types = {
2976
+ ".html": "text/html",
2977
+ ".js": "application/javascript",
2978
+ ".css": "text/css",
2979
+ ".json": "application/json",
2980
+ ".png": "image/png",
2981
+ ".svg": "image/svg+xml",
2982
+ ".ico": "image/x-icon",
2983
+ ".woff2": "font/woff2",
2984
+ ".mp4": "video/mp4",
2985
+ ".mp3": "audio/mpeg"
2986
+ };
2987
+ const fileHeaders = {
2988
+ "Content-Type": types[ext] || "application/octet-stream",
2989
+ "Cache-Control": rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : "public, max-age=3600",
2990
+ "ETag": entry.etag,
2991
+ "Vary": "Accept-Encoding"
2992
+ };
2993
+ if (ext === ".html") Object.assign(fileHeaders, pageHeaders(ssrModule, pathnameOf(req.url)));
2994
+ let status = 200;
2995
+ if (hookCtx) {
2996
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers: fileHeaders }));
2997
+ status = out.status;
2998
+ for (const [k, v] of Object.entries(webHeadersToNode(out))) res.setHeader(k, v);
2999
+ } else {
3000
+ for (const [k, v] of Object.entries(fileHeaders)) res.setHeader(k, v);
3001
+ }
3002
+ if (req.headers["if-none-match"] === entry.etag) {
3003
+ res.statusCode = 304;
3004
+ res.end();
3005
+ return;
3006
+ }
3007
+ const enc = pickEncoding(req);
3008
+ res.statusCode = status;
3009
+ if (enc) {
3010
+ res.setHeader("Content-Encoding", enc);
3011
+ res.end(enc === "br" ? entry.br : enc === "gzip" ? entry.gzip : compress("deflate", entry.raw));
3012
+ } else {
3013
+ res.end(entry.raw);
3014
+ }
3015
+ return;
3016
+ }
3017
+ let broken = /* @__PURE__ */ new Set();
3018
+ try {
3019
+ broken = new Set(JSON.parse(fs3.readFileSync(path3.join(dir, "broken.json"), "utf-8")));
3020
+ } catch {
3021
+ }
3022
+ const safe2 = req.url || "/";
3023
+ if (!broken.has(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
3024
+ const enc = pickEncoding(req);
3025
+ let status = 200;
3026
+ const nonce = nonceFor(ssrModule, pathnameOf(safe2));
3027
+ let headers = pageHeaders(ssrModule, pathnameOf(safe2), nonce);
3028
+ if (hookCtx) {
3029
+ const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers }));
3030
+ status = out.status;
3031
+ headers = webHeadersToNode(out);
3032
+ }
3033
+ res.statusCode = status;
3034
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
3035
+ res.setHeader("Vary", "Accept-Encoding");
3036
+ for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
3037
+ let write;
3038
+ let done;
3039
+ if (enc) {
3040
+ res.setHeader("Content-Encoding", enc);
3041
+ const compressor = createCompressor(enc);
3042
+ compressor.pipe(res);
3043
+ let flushed = false;
3044
+ write = (chunk) => {
3045
+ compressor.write(chunk);
3046
+ if (!flushed) {
3047
+ flushed = true;
3048
+ compressor.flush(zlib.constants.Z_FULL_FLUSH);
3049
+ }
3050
+ };
3051
+ compressor.on("error", () => res.destroy());
3052
+ done = () => compressor.end();
3053
+ } else {
3054
+ write = (chunk) => res.write(chunk);
3055
+ done = () => res.end();
3056
+ }
3057
+ const doc = ssrModule.docAttrs(safe2);
3058
+ await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
3059
+ done();
3060
+ return;
3061
+ }
3062
+ const page = await ssrModule.renderPage(safe2);
3063
+ await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(safe2));
3064
+ }).catch(() => {
3065
+ res.statusCode = 404;
3066
+ res.end("Not found");
3067
+ });
3068
+ };
3069
+ }
3070
+ function pathnameOf(url) {
3071
+ try {
3072
+ return new URL(url || "/", "http://localhost").pathname;
3073
+ } catch {
3074
+ return (url || "/").split("?")[0];
3075
+ }
3076
+ }
3077
+ function version() {
3078
+ for (const rel of ["../../package.json", "../package.json"]) {
3079
+ try {
3080
+ const v = JSON.parse(fs3.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8")).version;
3081
+ if (v) return v;
3082
+ } catch {
3083
+ }
3084
+ }
3085
+ return "0.0.0";
3086
+ }
3087
+ async function dev() {
3088
+ console.log(`\u{1F339} RoseTack v${version()} dev server starting...`);
3089
+ try {
3090
+ await build2();
3091
+ } catch (err) {
3092
+ console.error("Initial build failed (server still running):", err instanceof Error ? err.message : err);
3093
+ }
3094
+ let timeout;
3095
+ fs3.watch(SRC_DIR, { recursive: true }, () => {
3096
+ clearTimeout(timeout);
3097
+ timeout = setTimeout(async () => {
3098
+ try {
3099
+ console.log("Rebuilding...");
3100
+ await build2();
3101
+ } catch (err) {
3102
+ console.error("Build failed (server still running):", err instanceof Error ? err.message : err);
3103
+ }
3104
+ }, 200);
3105
+ });
3106
+ const http = await import("http");
3107
+ const server = http.createServer(serveStatic(OUT_DIR2));
3108
+ server.listen(PORT, () => {
3109
+ console.log("\u{1F339} http://localhost:" + PORT);
3110
+ });
3111
+ }
3112
+ async function preview() {
3113
+ await build2();
3114
+ const http = await import("http");
3115
+ const server = http.createServer(serveStatic(OUT_DIR2, true));
3116
+ server.listen(PORT, () => {
3117
+ console.log(`\u{1F339} RoseTack v${version()} preview at http://localhost:` + PORT);
3118
+ });
3119
+ }
3120
+ async function serve() {
3121
+ if (!fs3.existsSync(path3.join(OUT_DIR2, "server.js"))) {
3122
+ console.error(`rosetack: ${OUT_DIR2} has no server.js - run rosetack build first`);
3123
+ process.exit(1);
3124
+ }
3125
+ const cluster = (await import("node:cluster")).default;
3126
+ cluster.schedulingPolicy = cluster.SCHED_RR;
3127
+ const os = await import("node:os");
3128
+ const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
3129
+ const PORT2 = Number(process.env.PORT) || 3e3;
3130
+ if (cluster.isPrimary) {
3131
+ for (let i = 0; i < workers; i++) cluster.fork();
3132
+ cluster.on("message", (worker, msg) => {
3133
+ if (!msg || msg.type !== "rosetack:store") return;
3134
+ for (const w of Object.values(cluster.workers ?? {})) {
3135
+ if (w && w.id !== worker.id) w.send(msg);
3136
+ }
3137
+ });
3138
+ let live = workers;
3139
+ const stop2 = () => {
3140
+ for (const w of Object.values(cluster.workers ?? {})) w.kill();
3141
+ setTimeout(() => process.exit(0), 5e3).unref();
3142
+ };
3143
+ process.on("SIGTERM", stop2);
3144
+ process.on("SIGINT", stop2);
3145
+ cluster.on("exit", () => {
3146
+ if (--live <= 0) process.exit(0);
3147
+ });
3148
+ console.log(`\u{1F339} RoseTack v${version()} serve: ${workers} worker${workers > 1 ? "s" : ""} on http://localhost:${PORT2} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
3149
+ return;
3150
+ }
3151
+ process.on("disconnect", () => process.exit(0));
3152
+ let servicePlugins = [];
3153
+ try {
3154
+ servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
3155
+ } catch (err) {
3156
+ console.error("rosetack: rosetack.config.js failed to load for the serve hooks:", err instanceof Error ? err.message : err);
3157
+ }
3158
+ const http = await import("node:http");
3159
+ const server = http.createServer(withAccessLog(serveStatic(OUT_DIR2, true), `w${process.pid}`));
3160
+ server.requestTimeout = 3e4;
3161
+ server.headersTimeout = 65e3;
3162
+ server.keepAliveTimeout = 5e3;
3163
+ server.listen(PORT2, async () => {
3164
+ console.log(`\u{1F339} RoseTack worker ${process.pid} listening on http://localhost:${PORT2}`);
3165
+ for (const p of servicePlugins) {
3166
+ try {
3167
+ await p.onServe({ port: PORT2, workers });
3168
+ } catch (err) {
3169
+ console.error("rosetack: plugin", p.name, "onServe failed:", err instanceof Error ? err.message : err);
3170
+ }
3171
+ }
3172
+ });
3173
+ const stop = () => {
3174
+ for (const p of servicePlugins) {
3175
+ if (!p.onShutdown) continue;
3176
+ try {
3177
+ void Promise.resolve(p.onShutdown()).catch((err) => {
3178
+ console.error("rosetack: plugin", p.name, "onShutdown failed:", err instanceof Error ? err.message : err);
3179
+ });
3180
+ } catch (err) {
3181
+ console.error("rosetack: plugin", p.name, "onShutdown failed:", err instanceof Error ? err.message : err);
3182
+ }
3183
+ }
3184
+ server.close(() => process.exit(0));
3185
+ server.closeIdleConnections?.();
3186
+ setTimeout(() => process.exit(0), 5e3).unref();
3187
+ };
3188
+ process.on("SIGTERM", stop);
3189
+ process.on("SIGINT", stop);
3190
+ }
3191
+ async function scaffold() {
3192
+ const name = process.argv[3];
3193
+ if (!name || name.startsWith("-")) {
3194
+ console.log("Usage: rosetack new <name> (creates <name>/ with a page that builds)");
3195
+ return;
3196
+ }
3197
+ const dir = path3.resolve(name);
3198
+ if (fs3.existsSync(dir)) {
3199
+ console.error(`rosetack: ${dir} already exists - pick another name`);
3200
+ process.exit(1);
3201
+ }
3202
+ const pages = path3.join(dir, "src", "pages");
3203
+ fs3.mkdirSync(pages, { recursive: true });
3204
+ fs3.writeFileSync(path3.join(dir, "package.json"), JSON.stringify({
3205
+ name: path3.basename(dir),
3206
+ private: true,
3207
+ type: "module",
3208
+ scripts: {
3209
+ dev: "rosetack dev",
3210
+ build: "rosetack build",
3211
+ preview: "rosetack preview",
3212
+ serve: "rosetack serve",
3213
+ check: "rosetack check"
3214
+ },
3215
+ dependencies: { rosetack: `^${version()}` },
3216
+ // TypeScript is a first-class citizen: .rose scripts are typed, and `npm run check`
3217
+ // type-checks every one of them with THIS project's TypeScript …
3218
+ devDependencies: { typescript: "^5.6.0" }
3219
+ }, null, 2) + "\n");
3220
+ fs3.writeFileSync(path3.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
3221
+ `);
3222
+ fs3.writeFileSync(path3.join(dir, "tsconfig.json"), JSON.stringify({
3223
+ compilerOptions: {
3224
+ target: "ES2022",
3225
+ module: "ESNext",
3226
+ moduleResolution: "bundler",
3227
+ lib: ["ES2022", "DOM", "DOM.Iterable"],
3228
+ strict: true,
3229
+ noEmit: true,
3230
+ skipLibCheck: true
3231
+ },
3232
+ // the env file first (it is what makes the globals visible), then any
3233
+ // .ts the project grows - .rose scripts are checked by `npm run check`
3234
+ include: ["rosetack-env.d.ts", "src/**/*.ts"]
3235
+ }, null, 2) + "\n");
3236
+ fs3.writeFileSync(path3.join(pages, "index.rose"), `<script>
3237
+ // One file per route: markup, script and styles together.
3238
+ // The script block is TypeScript - interfaces, annotations, generics and
3239
+ // casts all compile, and \`npm run check\` type-checks them.
3240
+ interface Item { label: string }
3241
+
3242
+ let count = $state(0);
3243
+ let items = $state<string[]>(['zero hydration', 'one request', 'no build config']);
3244
+ let showList = $state(true);
3245
+
3246
+ function increment() { $setState('count', count() + 1); }
3247
+ function toggleList() { $setState('showList', !showList()); }
3248
+ // typed server data: the body runs per request on the server (and ships
3249
+ // to the client, where it re-runs on a client-side navigation)
3250
+ let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
3251
+ </script>
3252
+
3253
+ <h1>\u{1F339} RoseTack</h1>
3254
+ <p>Count: <strong>{count()}</strong> - first item: {first().label}</p>
3255
+ <button on:click={increment}>Increment</button>
3256
+ <button on:click={toggleList}>{showList() ? 'Hide' : 'Show'} the list</button>
3257
+
3258
+ {#if showList()}
3259
+ <ul>
3260
+ {#each items() as item}
3261
+ <li>{item}</li>
3262
+ {/each}
3263
+ </ul>
3264
+ {/if}
3265
+
3266
+ <style>
3267
+ body { font-family: system-ui, sans-serif; margin: 2rem; }
3268
+ button { padding: 0.5rem 1rem; margin-right: 0.5rem; }
3269
+ </style>
3270
+ `);
3271
+ fs3.writeFileSync(path3.join(dir, "README.md"), `# ${path3.basename(dir)}
3272
+
3273
+ A rosetack project. One file per route in \`src/pages/\`.
3274
+
3275
+ \`\`\`bash
3276
+ npm install # pulls the rosetack package (and typescript, for checking)
3277
+ npm run dev # dev server with hot rebuild: http://localhost:3000
3278
+ npm run build # compiles to dist/
3279
+ npm run serve # production runner (cluster, access log, graceful shutdown)
3280
+ npm run check # type-checks every .rose script
3281
+ \`\`\`
3282
+
3283
+ Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
3284
+ \`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
3285
+ runs before every request, \`src/pages/api/*.rose\` answers JSON.
3286
+ Full syntax: the README of the rosetack package.
3287
+ `);
3288
+ fs3.writeFileSync(path3.join(dir, ".gitignore"), "node_modules/\ndist/\n");
3289
+ console.log(`\u{1F339} Created ${dir}`);
3290
+ console.log(` src/pages/index.rose - a typed page that builds and runs`);
3291
+ console.log(` rosetack-env.d.ts + tsconfig.json - the script globals, typed`);
3292
+ console.log(`
3293
+ cd ${name}`);
3294
+ console.log(` npm install && npm run dev`);
3295
+ console.log(` npm run check # type-checks every .rose script`);
3296
+ }
3297
+ async function check() {
3298
+ const files = [...await scanRoseFiles(SRC_DIR), ...await scanComponentFiles(SRC_DIR)];
3299
+ if (files.length === 0) {
3300
+ 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>`);
3301
+ process.exit(1);
3302
+ }
3303
+ let tsMod;
3304
+ try {
3305
+ const req = createRequire(pathToFileURL2(path3.join(SRC_DIR, "package.json")));
3306
+ tsMod = await import(pathToFileURL2(req.resolve("typescript")).href);
3307
+ } catch {
3308
+ console.error(`rosetack: type checking needs typescript in this project - npm i -D typescript`);
3309
+ process.exit(1);
3310
+ }
3311
+ const nextTo = (rel) => rel.map((r) => fileURLToPath2(new URL(r, import.meta.url))).find((p) => fs3.existsSync(p));
3312
+ const typesFile = nextTo(["../types/rosetack.d.ts", "../src/types/rosetack.d.ts"]);
3313
+ if (!typesFile) {
3314
+ console.error("rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler");
3315
+ process.exit(1);
3316
+ }
3317
+ const runtimeSource = nextTo(["../runtime/index.ts", "../src/runtime/index.ts"]);
3318
+ const norm = (f) => path3.resolve(f).replace(/\\/g, "/");
3319
+ const virtual = /* @__PURE__ */ new Map();
3320
+ let checked = 0;
3321
+ for (const file of files) {
3322
+ const source = await fs3.promises.readFile(file, "utf-8");
3323
+ const m = /<script>/.exec(source);
3324
+ const script = scriptOf(source);
3325
+ if (!script) continue;
3326
+ const tagLine = source.slice(0, m.index + "<script>".length).split("\n").length;
3327
+ const wired = runtimeSource ? script.replace(/['"]\.\/runtime\.js['"]/g, JSON.stringify(runtimeSource.replace(/\\/g, "/"))) : script;
3328
+ virtual.set(norm(file), "\n".repeat(tagLine - 1) + wired);
3329
+ checked++;
3330
+ }
3331
+ if (checked === 0) {
3332
+ console.log("rosetack: no .rose scripts to check");
3333
+ return;
3334
+ }
3335
+ const propType = (def) => {
3336
+ if (!def) return "unknown";
3337
+ if (/^['"`]/.test(def)) return "string";
3338
+ if (/^-?\d+(\.\d+)?$/.test(def)) return "number";
3339
+ if (/^(true|false)$/.test(def)) return "boolean";
3340
+ return "unknown";
3341
+ };
3342
+ const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
3343
+ const declared = /* @__PURE__ */ new Set();
3344
+ for (const file of [...virtual.keys()]) {
3345
+ const script = scriptOf(await fs3.promises.readFile(file, "utf-8").catch(() => ""));
3346
+ if (!script) continue;
3347
+ for (const spec of script.matchAll(ROSE_IMPORT_RE)) {
3348
+ const target = norm(path3.resolve(path3.dirname(file), spec[1]));
3349
+ if (target === file || declared.has(target)) continue;
3350
+ const targetSource = await fs3.promises.readFile(target, "utf-8").catch(() => null);
3351
+ if (targetSource === null) continue;
3352
+ const props = extractExports(scriptOf(targetSource) ?? "").props;
3353
+ virtual.set(`${target}.d.ts`, [
3354
+ `declare function render(closes: unknown[], children: string, __props: { ${props.map((p) => `${p.name}?: ${propType(p.def)}`).join("; ")} }, __slots?: Record<string, unknown>): string;`,
3355
+ "export default render;",
3356
+ ""
3357
+ ].join("\n"));
3358
+ declared.add(target);
3359
+ }
3360
+ }
3361
+ const options = {
3362
+ noEmit: true,
3363
+ strict: true,
3364
+ target: tsMod.ScriptTarget.ES2022,
3365
+ module: tsMod.ModuleKind.ESNext,
3366
+ moduleResolution: tsMod.ModuleResolutionKind.Bundler,
3367
+ lib: ["lib.es2022.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"],
3368
+ // the virtual files are named after the .rose files (so a diagnostic points at the real
3369
+ // path) …
3370
+ allowNonTsExtensions: true,
3371
+ // the rewired './runtime.js' import points at a real .ts source
3372
+ allowImportingTsExtensions: true,
3373
+ // `types` is deliberately NOT set: the project's own @types packages (@types/node for
3374
+ // node:sqlite, say) load automatically, the way they do for the user's own .ts files.
3375
+ skipLibCheck: true
3376
+ };
3377
+ const host = tsMod.createCompilerHost(options);
3378
+ host.getCurrentDirectory = () => path3.resolve(SRC_DIR);
3379
+ const realRead = host.readFile.bind(host);
3380
+ const realGet = host.getSourceFile.bind(host);
3381
+ host.readFile = (f) => virtual.get(norm(f)) ?? realRead(f);
3382
+ host.fileExists = (f) => virtual.has(norm(f)) || tsMod.sys.fileExists(f);
3383
+ host.getSourceFile = (f, version2, onError, shouldCreate) => {
3384
+ const src = virtual.get(norm(f));
3385
+ return src ? tsMod.createSourceFile(f, src, version2, true) : realGet(f, version2, onError, shouldCreate);
3386
+ };
3387
+ const program = tsMod.createProgram([...virtual.keys(), typesFile], options, host);
3388
+ const diagnostics = tsMod.getPreEmitDiagnostics(program).filter((d) => d.file && virtual.has(norm(d.file.fileName)));
3389
+ if (diagnostics.length === 0) {
3390
+ console.log(`rosetack: ${checked} script${checked === 1 ? "" : "s"} type-checked, no errors`);
3391
+ return;
3392
+ }
3393
+ for (const d of diagnostics) {
3394
+ const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
3395
+ const where = d.file && at ? `${path3.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})` : "rosetack";
3396
+ const text = tsMod.flattenDiagnosticMessageText(d.messageText, "\n");
3397
+ const kind = d.category === 1 ? "error" : "warning";
3398
+ console.error(`${where}: ${kind} TS${d.code}: ${text}`);
3399
+ }
3400
+ const errors = diagnostics.filter((d) => d.category === 1).length;
3401
+ console.error(`rosetack: ${errors} type error${errors === 1 ? "" : "s"} in ${checked} script${checked === 1 ? "" : "s"}`);
3402
+ process.exit(1);
3403
+ }
3404
+ var cmd = process.argv[2];
3405
+ if (cmd === "dev") dev();
3406
+ else if (cmd === "build") build2();
3407
+ else if (cmd === "preview") preview();
3408
+ else if (cmd === "serve") serve();
3409
+ else if (cmd === "new") scaffold();
3410
+ else if (cmd === "check") check();
3411
+ else console.log("Usage: rosetack dev|build|preview|serve|new|check [dir] (dir defaults to the current directory; dist/ is written there)");