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,2696 @@
1
+ // src/cli/test.ts
2
+ import * as fs3 from "fs";
3
+ import * as os from "os";
4
+ import * as path3 from "path";
5
+ import { pathToFileURL as pathToFileURL2 } from "url";
6
+
7
+ // src/compiler/index.ts
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import { pathToFileURL, fileURLToPath } from "url";
11
+ import * as esbuild from "esbuild";
12
+ var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
13
+ var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
14
+ var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
15
+ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
16
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
17
+ var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
18
+ var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
19
+ var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
20
+ var SLOT_RE = /<slot\s*\/?>/g;
21
+ var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
22
+ function encodeSlotCall(attrs) {
23
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
24
+ if (!name) throw new Error('<slot> with attributes must declare a name: <slot name="row" ... />');
25
+ const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
26
+ return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
27
+ }
28
+ var BOUNDARY_FALLBACK = "<p>This section failed to render.</p>";
29
+ var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
30
+ var TS_LOADER = { loader: { ".js": "ts" } };
31
+ function callifyStateReads(script, names) {
32
+ if (names.length === 0) return script;
33
+ const scan = (src) => {
34
+ let out = "";
35
+ let i = 0;
36
+ while (i < src.length) {
37
+ const ch = src[i];
38
+ if (ch === "'" || ch === '"') {
39
+ let j = i + 1;
40
+ while (j < src.length && src[j] !== ch) {
41
+ if (src[j] === "\\") j++;
42
+ j++;
43
+ }
44
+ out += src.slice(i, Math.min(j + 1, src.length));
45
+ i = j + 1;
46
+ continue;
47
+ }
48
+ if (ch === "`") {
49
+ out += ch;
50
+ i++;
51
+ while (i < src.length && src[i] !== "`") {
52
+ if (src[i] === "\\") {
53
+ out += src.slice(i, i + 2);
54
+ i += 2;
55
+ continue;
56
+ }
57
+ if (src[i] === "$" && src[i + 1] === "{") {
58
+ let depth = 1;
59
+ let j = i + 2;
60
+ while (j < src.length && depth > 0) {
61
+ if (src[j] === "{") depth++;
62
+ else if (src[j] === "}") depth--;
63
+ if (depth === 0) break;
64
+ j++;
65
+ }
66
+ out += "${" + scan(src.slice(i + 2, j)) + "}";
67
+ i = j + 1;
68
+ continue;
69
+ }
70
+ out += src[i];
71
+ i++;
72
+ }
73
+ out += "`";
74
+ i++;
75
+ continue;
76
+ }
77
+ if (ch === "/" && src[i + 1] === "/") {
78
+ const nl = src.indexOf("\n", i);
79
+ const end = nl === -1 ? src.length : nl;
80
+ out += src.slice(i, end);
81
+ i = end;
82
+ continue;
83
+ }
84
+ if (ch === "/" && src[i + 1] === "*") {
85
+ const close = src.indexOf("*/", i + 2);
86
+ const end = close === -1 ? src.length : close + 2;
87
+ out += src.slice(i, end);
88
+ i = end;
89
+ continue;
90
+ }
91
+ if (/[A-Za-z_$]/.test(ch)) {
92
+ let j = i;
93
+ while (j < src.length && /[\w$]/.test(src[j])) j++;
94
+ const word = src.slice(i, j);
95
+ const prev = out.length ? out[out.length - 1] : "";
96
+ const next = src[j] ?? "";
97
+ const rewrite = names.includes(word) && !/[\w$.]/.test(prev) && !/[\w$:(]/.test(next);
98
+ out += rewrite ? `${word}()` : word;
99
+ i = j;
100
+ continue;
101
+ }
102
+ out += ch;
103
+ i++;
104
+ }
105
+ return out;
106
+ };
107
+ return scan(script);
108
+ }
109
+ function callifyTemplateExprs(template, names) {
110
+ if (names.length === 0) return template;
111
+ return template.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${callifyStateReads(expr, names)}}`);
112
+ }
113
+ async function loadConfig(root) {
114
+ const file = path.join(root, "rosetack.config.js");
115
+ if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
116
+ const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
117
+ return {
118
+ plugins: mod.default ?? [],
119
+ i18n: mod.i18n ?? {}
120
+ };
121
+ }
122
+ function resolveRoseImports(script, fromFile, registry) {
123
+ const imports = [];
124
+ const resolve3 = (spec) => {
125
+ const abs = path.resolve(path.dirname(fromFile), spec);
126
+ const hit = registry.get(abs);
127
+ if (!hit) {
128
+ throw new Error(`${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`);
129
+ }
130
+ return hit;
131
+ };
132
+ let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
133
+ const hit = resolve3(spec);
134
+ imports.push({ name, specifier: spec, index: hit.index });
135
+ return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
136
+ });
137
+ rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s*from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec) => {
138
+ const hit = resolve3(spec);
139
+ const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
140
+ imports.push({ name: alias, specifier: spec, index: hit.index });
141
+ return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
142
+ });
143
+ return { script: rewritten, imports };
144
+ }
145
+ function rewriteRoseImports(script, kind) {
146
+ return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
147
+ }
148
+ function scanSlotDecls(filePath) {
149
+ let src;
150
+ try {
151
+ src = fs.readFileSync(filePath, "utf-8");
152
+ } catch {
153
+ return [];
154
+ }
155
+ const noBlocks = src.replace(STYLE_RE, "");
156
+ const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").replace(COMPONENT_RE, "").trim();
157
+ const out = [];
158
+ for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
159
+ const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
160
+ if (!name) continue;
161
+ const props = [...m[1].matchAll(/\b(\w+)\s*=\s*\{/g)].map((x) => x[1]).filter((n) => n !== "name");
162
+ out.push({ name: name[1], props });
163
+ }
164
+ return out;
165
+ }
166
+ function hoistImports(script) {
167
+ const imports = [];
168
+ const rest = [];
169
+ let buf = null;
170
+ let depth = 0;
171
+ const done = (line) => depth <= 0 && /from\s*['"][^'"]+['"]\s*;?\s*$/.test(line);
172
+ for (const line of script.split("\n")) {
173
+ if (buf) {
174
+ buf.push(line);
175
+ for (const ch of line) {
176
+ if (ch === "{" || ch === "(") depth++;
177
+ else if (ch === "}" || ch === ")") depth--;
178
+ }
179
+ if (done(line)) {
180
+ imports.push(buf.join("\n"));
181
+ buf = null;
182
+ }
183
+ continue;
184
+ }
185
+ if (/^\s*import\b/.test(line)) {
186
+ buf = [line];
187
+ depth = 0;
188
+ for (const ch of line) {
189
+ if (ch === "{" || ch === "(") depth++;
190
+ else if (ch === "}" || ch === ")") depth--;
191
+ }
192
+ if (done(line)) {
193
+ imports.push(line);
194
+ buf = null;
195
+ }
196
+ continue;
197
+ }
198
+ rest.push(line);
199
+ }
200
+ if (buf) imports.push(buf.join("\n"));
201
+ return { imports: imports.join("\n"), rest: rest.join("\n") };
202
+ }
203
+ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
204
+ let source = await fs.promises.readFile(filePath, "utf-8");
205
+ for (const p of plugins) {
206
+ if (!p.transform) continue;
207
+ try {
208
+ source = await p.transform(source, filePath);
209
+ } catch (err) {
210
+ throw new Error(`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`);
211
+ }
212
+ }
213
+ if (isApi) {
214
+ const scriptMatch2 = source.match(COMPONENT_RE);
215
+ const rawScript2 = scriptMatch2?.[1] ?? "";
216
+ 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));
217
+ const usesContext2 = /getContext\s*\(/.test(rawScript2);
218
+ const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
219
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
220
+ return {
221
+ ssr: "",
222
+ client: "",
223
+ stateKeys: [],
224
+ actionNames: [],
225
+ guardName: null,
226
+ style: "",
227
+ hasParams: false,
228
+ api: `import { getContext } from './runtime.js';
229
+ ${rewriteRoseImports(`${hoisted.imports}
230
+ ${hoisted.rest}`, "ssr").trim()}`,
231
+ apiMethods,
232
+ hasPrerender,
233
+ usesContext: usesContext2
234
+ };
235
+ }
236
+ const styleMatch = source.match(STYLE_RE);
237
+ const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
238
+ const sourceNoBlocks = source.replace(STYLE_RE, "");
239
+ const scriptMatch = sourceNoBlocks.match(COMPONENT_RE);
240
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
241
+ const rawScript = roseResolved.script;
242
+ const roseImports = roseResolved.imports;
243
+ const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
244
+ const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
245
+ if (isComponent && /\$data\s*\(/.test(rawScript)) {
246
+ throw new Error(
247
+ `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`
248
+ );
249
+ }
250
+ const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
251
+ const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
252
+ const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
253
+ const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
254
+ const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
255
+ const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
256
+ if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
257
+ throw new Error(`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`);
258
+ }
259
+ const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
260
+ const bundle = bundleMatch ? bundleMatch[1] : void 0;
261
+ if (bundle && !["inline", "split"].includes(bundle)) {
262
+ throw new Error(`${filePath}: export const bundle must be 'inline' or 'split'`);
263
+ }
264
+ const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
265
+ const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
266
+ if (csr === false) {
267
+ const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
268
+ if (dead) {
269
+ throw new Error(
270
+ `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`
271
+ );
272
+ }
273
+ }
274
+ let headers;
275
+ const headersLiteral = extractObjectLiteral(rawScript, "headers");
276
+ if (headersLiteral) {
277
+ let value;
278
+ try {
279
+ value = new Function(`return ${headersLiteral}`)();
280
+ } catch {
281
+ throw new Error(`${filePath}: export const headers must be an object literal`);
282
+ }
283
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
284
+ throw new Error(`${filePath}: export const headers must be a flat map of string -> string`);
285
+ }
286
+ headers = value;
287
+ }
288
+ let cspNonce;
289
+ const cspLiteral = extractObjectLiteral(rawScript, "csp");
290
+ if (cspLiteral) {
291
+ let value;
292
+ try {
293
+ value = new Function(`return ${cspLiteral}`)();
294
+ } catch {
295
+ throw new Error(`${filePath}: export const csp must be an object literal`);
296
+ }
297
+ const nonce = value?.nonce;
298
+ if (nonce !== void 0 && typeof nonce !== "boolean") {
299
+ throw new Error(`${filePath}: csp.nonce must be a boolean`);
300
+ }
301
+ cspNonce = nonce === true;
302
+ }
303
+ const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
304
+ const script = scriptNoExports;
305
+ const actionNames = new Set(actions.map((a) => a.name));
306
+ const clientReasons = [];
307
+ if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
308
+ if (/<form[\s>]/.test(source)) clientReasons.push("a <form> (its in-place adopt is the enhancement)");
309
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
310
+ if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
311
+ if (actionNames.size > 0) {
312
+ clientReasons.push(`server action${actionNames.size > 1 ? "s" : ""} (${[...actionNames].join(", ")})`);
313
+ }
314
+ const needsClient = clientReasons.length > 0;
315
+ const jsWarnings = [];
316
+ if (!needsClient) {
317
+ if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(source)) {
318
+ jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
319
+ }
320
+ if (/javascript:/i.test(source)) {
321
+ jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
322
+ }
323
+ if (/\b(?:eval|new Function)\s*\(/.test(rawScript)) {
324
+ jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
325
+ }
326
+ if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(rawScript)) {
327
+ jsWarnings.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true");
328
+ }
329
+ }
330
+ const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
331
+ const headMatch = sourceNoBlocks.match(HEAD_RE);
332
+ const headContent = headMatch?.[1] ?? "";
333
+ const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, "");
334
+ const rawTemplate = templateMatch ? templateMatch[1] : sourceNoHead.replace(COMPONENT_RE, "").trim();
335
+ const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
336
+ const decls = extractDecls(script);
337
+ const stateDecls = decls.filter((d) => d.kind === "state");
338
+ const setterNames = /* @__PURE__ */ new Map();
339
+ stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
340
+ const eventBindings = [];
341
+ let em;
342
+ EVENT_RE.lastIndex = 0;
343
+ while (em = EVENT_RE.exec(template)) {
344
+ if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
345
+ }
346
+ let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end]));
347
+ cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
348
+ const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
349
+ const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
350
+ return `${setter}(${val})`;
351
+ });
352
+ cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
353
+ const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
354
+ const ssrTemplate = templateCalled.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}").replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) => actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
355
+ const stateDeclsCode = decls.map((d) => {
356
+ const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
357
+ if (d.kind === "state") {
358
+ return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
359
+ }
360
+ const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
361
+ const fn = isFn ? d.expr : `() => (${d.expr})`;
362
+ return `const __had_${d.name} = hasState(${JSON.stringify(key)});
363
+ const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
364
+ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
365
+ }).join("\n");
366
+ const stateKeys = decls.map((d) => d.name);
367
+ const comps = new Map(roseImports.map((r) => {
368
+ const abs = path.resolve(path.dirname(filePath), r.specifier);
369
+ const hit = registry.get(abs);
370
+ return [r.name, { index: hit.index, slots: hit.slots }];
371
+ }));
372
+ const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
373
+ const compiledHead = headContent.trim() ? compileTemplate(headContent, "__hd", "__hc", null, 0, false) : "";
374
+ const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
375
+ const ssrExports = actions.length > 0 ? `${exportStmts}
376
+ ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
377
+ const ssrGuard = guard ? `
378
+ ${guard}` : "";
379
+ const isMiddleware = path.basename(filePath) === "_middleware.rose";
380
+ const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
381
+
382
+ ${importStmts}
383
+
384
+ ${ssrExports}
385
+ ${ssrGuard}
386
+
387
+ ${cleanScript}
388
+ ` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
389
+ const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
390
+ return {
391
+ ssr: rewriteRoseImports(ssr, "ssr"),
392
+ client: rewriteRoseImports(client, "client"),
393
+ stateKeys,
394
+ actionNames: [...actionNames],
395
+ guardName: guard ? "beforeAction" : null,
396
+ style: scopedStyle,
397
+ hasParams,
398
+ usesContext,
399
+ revalidate,
400
+ csr,
401
+ prefetch,
402
+ bundle,
403
+ needsClient,
404
+ clientReasons,
405
+ jsWarnings,
406
+ headers,
407
+ cspNonce,
408
+ props,
409
+ roseImports,
410
+ isComponent
411
+ };
412
+ }
413
+ function minifyDecls(block) {
414
+ return block.replace(
415
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
416
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
417
+ ).trim();
418
+ }
419
+ function scopeCss(css, key) {
420
+ const attr = `[data-rosetack-c="${key}"]`;
421
+ const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
422
+ let out = "";
423
+ let prelude = "";
424
+ let i = 0;
425
+ while (i < clean.length) {
426
+ const ch = clean[i];
427
+ if (ch === "{") {
428
+ let depth = 1;
429
+ let j = i + 1;
430
+ while (j < clean.length && depth > 0) {
431
+ if (clean[j] === "{") depth++;
432
+ else if (clean[j] === "}") depth--;
433
+ j++;
434
+ }
435
+ const block = clean.slice(i + 1, j - 1);
436
+ const sel = prelude.trim();
437
+ if (sel.startsWith("@")) {
438
+ out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
439
+ } else if (sel) {
440
+ const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
441
+ out += `${scoped}{${minifyDecls(block)}}`;
442
+ }
443
+ prelude = "";
444
+ i = j;
445
+ continue;
446
+ }
447
+ if (ch !== "}" && ch !== "\n" && ch !== "\r") prelude += ch;
448
+ else if (ch === "}") prelude = "";
449
+ i++;
450
+ }
451
+ return out.trim();
452
+ }
453
+ function injectScopeAttr(template, key) {
454
+ const attr = ` data-rosetack-c="${key}"`;
455
+ let out = "";
456
+ let depth = 0;
457
+ let i = 0;
458
+ while (i < template.length) {
459
+ const lt = template.indexOf("<", i);
460
+ if (lt === -1) {
461
+ out += template.slice(i);
462
+ break;
463
+ }
464
+ out += template.slice(i, lt);
465
+ let j = lt + 1;
466
+ let quote = "";
467
+ while (j < template.length) {
468
+ const c = template[j];
469
+ if (quote) {
470
+ if (c === quote) quote = "";
471
+ } else if (c === '"' || c === "'") quote = c;
472
+ else if (c === ">") break;
473
+ j++;
474
+ }
475
+ const tagText = template.slice(lt, j + 1);
476
+ const closing = /^<\//.test(tagText);
477
+ const nameMatch = tagText.match(/^<\/?([a-zA-Z][\w-]*)/);
478
+ const selfClosing = /\/>$/.test(tagText) || nameMatch && VOID_TAGS.has(nameMatch[1].toLowerCase());
479
+ if (nameMatch && !closing && depth === 0 && !selfClosing) {
480
+ const injectAt = tagText.endsWith("/>") ? tagText.length - 2 : tagText.length - 1;
481
+ out += tagText.slice(0, injectAt) + attr + tagText.slice(injectAt);
482
+ depth++;
483
+ } else {
484
+ out += tagText;
485
+ if (nameMatch) depth += closing ? -1 : selfClosing ? 0 : 1;
486
+ }
487
+ i = j + 1;
488
+ }
489
+ return out;
490
+ }
491
+ var VOID_TAGS = /* @__PURE__ */ new Set(["img", "br", "hr", "input", "meta", "link", "source", "wbr"]);
492
+ var EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
493
+ function extractObjectLiteral(script, name) {
494
+ const m = new RegExp(`(?:^|\\n)\\s*export\\s+(?:const|let|var)\\s+${name}\\s*=\\s*`).exec(script);
495
+ if (!m) return null;
496
+ let i = m.index + m[0].length;
497
+ if (script[i] !== "{") return null;
498
+ const start = i;
499
+ let depth = 0;
500
+ for (; i < script.length; i++) {
501
+ const ch = script[i];
502
+ if (ch === "{") depth++;
503
+ else if (ch === "}") {
504
+ depth--;
505
+ if (depth === 0) {
506
+ i++;
507
+ break;
508
+ }
509
+ }
510
+ }
511
+ return script.slice(start, i);
512
+ }
513
+ function extractExports(script) {
514
+ const stmts = [];
515
+ const actions = [];
516
+ const props = [];
517
+ const guards = [];
518
+ let out = "";
519
+ let pos = 0;
520
+ let m;
521
+ EXPORT_RE.lastIndex = 0;
522
+ while (m = EXPORT_RE.exec(script)) {
523
+ const kind = m[1];
524
+ const start = m.index + m[0].indexOf("export");
525
+ let i = start + m[0].length - m[0].indexOf("export");
526
+ if (kind) {
527
+ let depth = 0;
528
+ while (i < script.length) {
529
+ const ch = script[i];
530
+ if (ch === "(" || ch === "{" || ch === "[") depth++;
531
+ else if (ch === ")" || ch === "}" || ch === "]") {
532
+ depth--;
533
+ if (depth === 0) {
534
+ i++;
535
+ break;
536
+ }
537
+ } else if (depth === 0 && ch === ";") {
538
+ i++;
539
+ break;
540
+ } else if (depth === 0 && ch === "\n") {
541
+ const rest = script.slice(i + 1);
542
+ if (!/^\s*[.([{+\-*/?:,=&|]/.test(rest)) {
543
+ i++;
544
+ break;
545
+ }
546
+ }
547
+ i++;
548
+ }
549
+ if (script[i] === ";") i++;
550
+ } else {
551
+ while (i < script.length && script[i] !== "{") i++;
552
+ let depth = 0;
553
+ while (i < script.length) {
554
+ const ch = script[i];
555
+ if (ch === "{") depth++;
556
+ else if (ch === "}") {
557
+ depth--;
558
+ if (depth === 0) {
559
+ i++;
560
+ break;
561
+ }
562
+ }
563
+ i++;
564
+ }
565
+ }
566
+ out += script.slice(pos, start);
567
+ const stmt = script.slice(start, i).trim();
568
+ const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
569
+ const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
570
+ if (anyFn?.[1] === "beforeAction") {
571
+ guards.push(stmt);
572
+ } else if (asyncFn) {
573
+ actions.push({ name: asyncFn[1], stmt });
574
+ } else if (kind === "let") {
575
+ const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
576
+ if (pm) props.push({ name: pm[1], def: pm[2]?.trim() ?? null });
577
+ else stmts.push(stmt);
578
+ } else {
579
+ stmts.push(stmt);
580
+ }
581
+ pos = i;
582
+ }
583
+ out += script.slice(pos);
584
+ return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
585
+ }
586
+ function extractDecls(script) {
587
+ const decls = [];
588
+ DECL_RE.lastIndex = 0;
589
+ let m;
590
+ while (m = DECL_RE.exec(script)) {
591
+ let j = m.index + m[0].length;
592
+ const skipSpace = () => {
593
+ while (j < script.length && /\s/.test(script[j])) j++;
594
+ };
595
+ skipSpace();
596
+ if (script[j] === "<") {
597
+ let depth2 = 0;
598
+ while (j < script.length) {
599
+ const ch = script[j];
600
+ if (ch === "<") depth2++;
601
+ else if (ch === ">" && script[j - 1] !== "=") {
602
+ depth2--;
603
+ if (depth2 === 0) {
604
+ j++;
605
+ break;
606
+ }
607
+ } else if (ch === "=" && script[j + 1] === ">") j++;
608
+ j++;
609
+ }
610
+ skipSpace();
611
+ }
612
+ if (script[j] !== "(") continue;
613
+ const open = j + 1;
614
+ let depth = 1;
615
+ let i = open;
616
+ while (i < script.length && depth > 0) {
617
+ const ch = script[i];
618
+ if (ch === "(") depth++;
619
+ else if (ch === ")") depth--;
620
+ i++;
621
+ }
622
+ let end = i;
623
+ const cast = DECL_CAST_RE.exec(script.slice(i));
624
+ if (cast) end = i + cast[0].length;
625
+ if (script[end] === ";") end++;
626
+ decls.push({
627
+ name: m[1],
628
+ kind: m[2],
629
+ expr: script.slice(open, i - 1).trim(),
630
+ start: m.index,
631
+ end
632
+ });
633
+ }
634
+ return decls;
635
+ }
636
+ function removeRanges(text, ranges) {
637
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
638
+ let out = "";
639
+ let pos = 0;
640
+ for (const [start, end] of sorted) {
641
+ out += text.slice(pos, start);
642
+ pos = end;
643
+ }
644
+ out += text.slice(pos);
645
+ return out;
646
+ }
647
+ function autoCall(expr) {
648
+ const e = expr.trim();
649
+ return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
650
+ }
651
+ function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
652
+ let result = "";
653
+ let remaining = template;
654
+ let blockId = 0;
655
+ const nextId = () => `${depth}_${blockId++}`;
656
+ while (remaining.length > 0) {
657
+ const ifMatch = remaining.match(/\{#if\s+([^}]+)\}([\s\S]*?)\{\/if\}/);
658
+ const eachMatch = remaining.match(/\{#each\s+([\w.]+(?:\(\))?)\s+as\s+(\w+)\}([\s\S]*?)\{\/each\}/);
659
+ const boundaryMatch = remaining.match(/\{#boundary\}([\s\S]*?)\{\/boundary\}/);
660
+ const exprMatch = remaining.match(/\{([^{}]+)\}/);
661
+ const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
662
+ const candidates = [];
663
+ if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
664
+ if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
665
+ if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
666
+ if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
667
+ if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
668
+ const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
669
+ if (!earliest) {
670
+ result += emitChunk(remaining, acc, closes, scope);
671
+ break;
672
+ }
673
+ if (earliest.type === "if") {
674
+ const [, cond, content] = earliest.match;
675
+ const before = remaining.substring(0, earliest.index);
676
+ if (before) result += emitChunk(before, acc, closes, scope);
677
+ const call = autoCall(cond);
678
+ const id = nextId();
679
+ const innerScope = scope ?? "__s";
680
+ const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, markers, comps);
681
+ result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
682
+ `;
683
+ if (markers) {
684
+ result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
685
+ `;
686
+ } else {
687
+ result += `${acc} += (${call}) ? __b${id}(${scope ?? "undefined"}, []) : '';
688
+ `;
689
+ }
690
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
691
+ } else if (earliest.type === "each") {
692
+ const [, items, item, content] = earliest.match;
693
+ const before = remaining.substring(0, earliest.index);
694
+ if (before) result += emitChunk(before, acc, closes, scope);
695
+ const call = autoCall(items);
696
+ const id = nextId();
697
+ const itemRe = new RegExp(`\\b${item}\\b`, "g");
698
+ const scoped = content.trim().replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(itemRe, "__s")}}`);
699
+ const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
700
+ result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
701
+ `;
702
+ if (markers) {
703
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
704
+ `;
705
+ } else {
706
+ result += `${acc} += (${call}).map((${item}) => __b${id}(${item}, [])).join('');
707
+ `;
708
+ }
709
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
710
+ } else if (earliest.type === "boundary") {
711
+ const [, content] = earliest.match;
712
+ const before = remaining.substring(0, earliest.index);
713
+ if (before) result += emitChunk(before, acc, closes, scope);
714
+ const id = nextId();
715
+ const catchesAction = /\$action:|<form[\s>]/.test(content);
716
+ const inner = compileTemplate(content.trim(), "h", closes, scope, depth + 1, markers, comps);
717
+ result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
718
+ `;
719
+ result += `let __bd${id} = '';
720
+ `;
721
+ result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
722
+ ` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
723
+ `;
724
+ result += `${acc} += __bd${id};
725
+ `;
726
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
727
+ } else if (earliest.type === "comp") {
728
+ const tag = earliest.tag;
729
+ if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
730
+ const entry = comps.get(tag.name);
731
+ const id = nextId();
732
+ let childrenSrc = "";
733
+ let rest;
734
+ if (tag.selfClosing) {
735
+ rest = remaining.substring(tag.end);
736
+ } else {
737
+ const closeIdx = findClose(remaining, tag.end, tag.name);
738
+ if (closeIdx < 0) throw new Error(`unclosed <${tag.name}> - every component tag needs its matching close tag`);
739
+ childrenSrc = remaining.substring(tag.end, closeIdx);
740
+ rest = remaining.substring(closeIdx + tag.name.length + 3);
741
+ }
742
+ const { def, named } = splitSlots(childrenSrc);
743
+ const hasChildren = def.trim().length > 0;
744
+ if (hasChildren) {
745
+ result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, markers, comps)} return h; };
746
+ `;
747
+ }
748
+ const slotFns = named.map(([nm, src]) => {
749
+ const decl = entry.slots.find((s) => s.name === nm);
750
+ let content = src;
751
+ for (const p of decl?.props ?? []) {
752
+ content = content.replace(/\{([^{}]*)\}/g, (whole, expr) => `{${expr.replace(new RegExp(`\\b${p}\\b`, "g"), `__s.${p}`)}}`);
753
+ }
754
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
755
+ });
756
+ const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
757
+ const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
758
+ const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
759
+ return `${JSON.stringify(key)}: ${val}`;
760
+ }).join(", ");
761
+ const childrenArg = hasChildren ? `__ch${id}(${scope ?? "undefined"}, ${closes})` : `''`;
762
+ result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
763
+ `;
764
+ remaining = rest;
765
+ } else {
766
+ const [, expr] = earliest.match;
767
+ const trimmed = expr.trim();
768
+ const before = remaining.substring(0, earliest.index);
769
+ if (trimmed === "__slot__") {
770
+ if (before) result += emitChunk(before, acc, closes, scope);
771
+ result += compileSlot(acc);
772
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
773
+ continue;
774
+ }
775
+ const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*)\]\)$/.exec(trimmed);
776
+ if (slotCall) {
777
+ if (before) result += emitChunk(before, acc, closes, scope);
778
+ result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);
779
+ `;
780
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
781
+ continue;
782
+ }
783
+ const attrMatch = before.match(/([\w-]+)=\s*$/);
784
+ if (attrMatch) {
785
+ const lit = before.slice(0, before.length - attrMatch[0].length);
786
+ if (lit) result += emitChunk(lit, acc, closes, scope);
787
+ result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, markers);
788
+ } else {
789
+ if (before) result += emitChunk(before, acc, closes, scope);
790
+ const after = remaining.substring(earliest.index + earliest.match[0].length);
791
+ const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
792
+ result += emitText(trimmed, acc, closes, scope, markers, pair);
793
+ }
794
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
795
+ }
796
+ }
797
+ return result;
798
+ }
799
+ function scanTagEnd(src, start) {
800
+ let j = start + 1;
801
+ let quote = "";
802
+ let brace = 0;
803
+ while (j < src.length) {
804
+ const c = src[j];
805
+ if (quote) {
806
+ if (c === quote) quote = "";
807
+ } else if (c === '"' || c === "'") quote = c;
808
+ else if (c === "{") brace++;
809
+ else if (c === "}") brace = Math.max(0, brace - 1);
810
+ else if (c === ">" && brace === 0) return j + 1;
811
+ j++;
812
+ }
813
+ return -1;
814
+ }
815
+ function findCompTag(src, comps) {
816
+ let i = 0;
817
+ while (i < src.length) {
818
+ const lt = src.indexOf("<", i);
819
+ if (lt < 0) return null;
820
+ const nm = /^<([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
821
+ if (nm && comps.has(nm[1])) {
822
+ const end = scanTagEnd(src, lt);
823
+ if (end > 0) {
824
+ const raw = src.slice(lt, end);
825
+ const selfClosing = /\/>$/.test(raw);
826
+ return { start: lt, end, name: nm[1], attrs: raw.slice(1 + nm[1].length, selfClosing ? -2 : -1), selfClosing };
827
+ }
828
+ }
829
+ i = lt + 1;
830
+ }
831
+ return null;
832
+ }
833
+ function findClose(src, from, name) {
834
+ const re = new RegExp(`<(/?)${name}(?=[\\s/>])`, "g");
835
+ re.lastIndex = from;
836
+ let depth = 1;
837
+ let m;
838
+ while (m = re.exec(src)) {
839
+ const end = scanTagEnd(src, m.index);
840
+ if (end < 0) return -1;
841
+ if (m[1] === "/") {
842
+ depth--;
843
+ if (depth === 0) return m.index;
844
+ } else if (!/\/>$/.test(src.slice(m.index, end))) depth++;
845
+ }
846
+ return -1;
847
+ }
848
+ function parseCompAttrs(attrs) {
849
+ const out = [];
850
+ let i = 0;
851
+ while (i < attrs.length) {
852
+ const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
853
+ if (!nm) break;
854
+ i += nm[0].length;
855
+ const eq = /^\s*=\s*/.exec(attrs.slice(i));
856
+ if (!eq) {
857
+ out.push({ name: nm[1], kind: "bool", value: "" });
858
+ continue;
859
+ }
860
+ i += eq[0].length;
861
+ const ch = attrs[i];
862
+ if (ch === "{") {
863
+ let depth = 1;
864
+ let j = i + 1;
865
+ while (j < attrs.length && depth > 0) {
866
+ if (attrs[j] === "{") depth++;
867
+ else if (attrs[j] === "}") depth--;
868
+ j++;
869
+ }
870
+ out.push({ name: nm[1], kind: "expr", value: attrs.slice(i + 1, j - 1).trim() });
871
+ i = j;
872
+ } else if (ch === '"' || ch === "'") {
873
+ const j = attrs.indexOf(ch, i + 1);
874
+ out.push({ name: nm[1], kind: "str", value: attrs.slice(i + 1, j < 0 ? attrs.length : j) });
875
+ i = j < 0 ? attrs.length : j + 1;
876
+ } else break;
877
+ }
878
+ return out;
879
+ }
880
+ function rejectNestedSlot(src, outer) {
881
+ let i = 0;
882
+ while (i < src.length) {
883
+ const lt = src.indexOf("<", i);
884
+ if (lt < 0) return;
885
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(lt, lt + 64));
886
+ if (!nm) {
887
+ i = lt + 1;
888
+ continue;
889
+ }
890
+ const end = scanTagEnd(src, lt);
891
+ if (end < 0) return;
892
+ const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
893
+ if (hit && nm[1] !== "/") {
894
+ throw new Error(`slot="${hit[1]}" on <${nm[2]}> is nested inside slot="${outer}" - a slot must be a direct child of the component`);
895
+ }
896
+ i = end;
897
+ }
898
+ }
899
+ function splitSlots(src) {
900
+ let def = "";
901
+ const named = /* @__PURE__ */ new Map();
902
+ let i = 0;
903
+ let elemDepth = 0;
904
+ let blockDepth = 0;
905
+ while (i < src.length) {
906
+ const lt = src.indexOf("<", i);
907
+ const ob = src.indexOf("{#", i);
908
+ const cb = src.indexOf("{/", i);
909
+ const cands = [lt, ob, cb].filter((x) => x >= 0);
910
+ if (cands.length === 0) {
911
+ def += src.slice(i);
912
+ break;
913
+ }
914
+ const next = Math.min(...cands);
915
+ if (next > i) def += src.slice(i, next);
916
+ if (next === ob || next === cb) {
917
+ const close = src.indexOf("}", next);
918
+ const token = src.slice(next, close < 0 ? src.length : close + 1);
919
+ if (next === ob) blockDepth++;
920
+ else blockDepth = Math.max(0, blockDepth - 1);
921
+ def += token;
922
+ i = next + token.length;
923
+ continue;
924
+ }
925
+ const nm = /^<(\/?)([a-zA-Z][\w-]*)/.exec(src.slice(next, next + 64));
926
+ if (!nm) {
927
+ def += "<";
928
+ i = next + 1;
929
+ continue;
930
+ }
931
+ const end = scanTagEnd(src, next);
932
+ if (end < 0) {
933
+ def += src.slice(next);
934
+ break;
935
+ }
936
+ const tagText = src.slice(next, end);
937
+ const selfClosing = /\/>$/.test(tagText);
938
+ const isVoid = VOID_TAGS.has(nm[2].toLowerCase());
939
+ if (nm[1] === "/") {
940
+ elemDepth = Math.max(0, elemDepth - 1);
941
+ def += tagText;
942
+ i = end;
943
+ continue;
944
+ }
945
+ if (!selfClosing && !isVoid) elemDepth++;
946
+ const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
947
+ if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
948
+ throw new Error(`slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`);
949
+ }
950
+ if (slotName) {
951
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
952
+ if (selfClosing || isVoid) {
953
+ named.set(slotName, (named.get(slotName) ?? "") + stripped);
954
+ } else {
955
+ const closeIdx = findClose(src, end, nm[2]);
956
+ if (closeIdx < 0) throw new Error(`unclosed <${nm[2]}> inside slot="${slotName}"`);
957
+ const tail = `</${nm[2]}>`;
958
+ const inner = src.slice(end, closeIdx);
959
+ rejectNestedSlot(inner, slotName);
960
+ named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
961
+ elemDepth = Math.max(0, elemDepth - 1);
962
+ i = closeIdx + tail.length;
963
+ continue;
964
+ }
965
+ i = end;
966
+ continue;
967
+ }
968
+ def += tagText;
969
+ i = end;
970
+ }
971
+ return { def, named: [...named.entries()] };
972
+ }
973
+ function emitChunk(text, acc, closes, scope) {
974
+ if (!text) return "";
975
+ return `${acc} += ${JSON.stringify(text)};
976
+ `;
977
+ }
978
+ var IMG_RE = /<img\b(?:[^<>]|\{[^{}]*\})*>/g;
979
+ var IMG_MIME = {
980
+ ".png": "image/png",
981
+ ".jpg": "image/jpeg",
982
+ ".jpeg": "image/jpeg",
983
+ ".gif": "image/gif",
984
+ ".webp": "image/webp",
985
+ ".svg": "image/svg+xml",
986
+ ".ico": "image/x-icon"
987
+ };
988
+ var INLINE_IMG_MAX = 4096;
989
+ function inlineImages(template, publicDir) {
990
+ return template.replace(IMG_RE, (tag) => {
991
+ const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
992
+ if (!src) return tag;
993
+ const ext = path.extname(src[1]).toLowerCase();
994
+ const mime = IMG_MIME[ext];
995
+ if (!mime) return tag;
996
+ let file;
997
+ try {
998
+ file = fs.readFileSync(path.join(publicDir, src[1]));
999
+ } catch {
1000
+ return tag;
1001
+ }
1002
+ if (file.length > INLINE_IMG_MAX) return tag;
1003
+ 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")}`;
1004
+ return tag.replace(src[0], `src="${uri}"`);
1005
+ });
1006
+ }
1007
+ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
1008
+ if (!markers) {
1009
+ return `${acc} += esc(${expr});
1010
+ `;
1011
+ }
1012
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1013
+ let extra = pair ? ", 1" : scope ? ", 0" : "";
1014
+ if (scope) extra += `, ${scope}`;
1015
+ return `${acc} += textMark(${closes}, ${fn}${extra});
1016
+ `;
1017
+ }
1018
+ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
1019
+ if (!markers) {
1020
+ return `${acc} += '${attr}="' + esc(${expr}) + '"';
1021
+ `;
1022
+ }
1023
+ const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
1024
+ const arg = scope ? `, ${scope}` : "";
1025
+ return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
1026
+ `;
1027
+ }
1028
+ function compileSlot(acc) {
1029
+ return `${acc} += String(children);
1030
+ `;
1031
+ }
1032
+ var RUNTIME_IMPORTS = `import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark } from './runtime.js';`;
1033
+ function propsCode(props) {
1034
+ if (props.length === 0) return "";
1035
+ return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
1036
+ }
1037
+ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
1038
+ const fn = sl[name];
1039
+ if (typeof fn !== 'function') return null;
1040
+ const o = {};
1041
+ for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
1042
+ return { o, fn };
1043
+ };
1044
+ const __slotBlock = (closes, sl, name, pairs) => {
1045
+ const hit = __slot(sl, name, pairs);
1046
+ const idx = closes.length;
1047
+ closes.push(() => {
1048
+ if (!hit) return null;
1049
+ const c = [];
1050
+ return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
1051
+ });
1052
+ return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
1053
+ };`;
1054
+ function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "") {
1055
+ const headCode = headFn ? `
1056
+ const __head = () => { let __hd = ''; ${headFn} return __hd; };
1057
+ __html += headMark(closes, __head);` : "";
1058
+ return `
1059
+ ${RUNTIME_IMPORTS}
1060
+
1061
+ ${imports}
1062
+
1063
+ ${exports}
1064
+ ${guard}
1065
+
1066
+ ${namedSlots ? SLOT_HELPER : ""}
1067
+
1068
+ export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1069
+ ${props.length > 0 ? "const __p = __props || {};" : ""}
1070
+ ${namedSlots ? "const __sl = __slots || {};" : ""}
1071
+ ${propsCode(props)}
1072
+ ${stateDeclsCode}
1073
+ // The incremental patches of the action that produced THIS response,
1074
+ // applied to the state the declarations above just established (a no-op on
1075
+ // every path that is not a server action's re-render - see the runtime).
1076
+ ${isComponent ? "" : "applyStateDeltas();"}
1077
+ ${script}
1078
+ const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1079
+ let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1080
+ return __html;
1081
+ }
1082
+ `;
1083
+ }
1084
+ function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
1085
+ const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
1086
+ const headCode = headFn ? `
1087
+ const __head = () => { let __hd = ''; ${headFn} return __hd; };
1088
+ __html += headMark(closes, __head);` : "";
1089
+ return `
1090
+ ${RUNTIME_IMPORTS}
1091
+
1092
+ ${imports}
1093
+
1094
+ ${exports}
1095
+
1096
+ ${namedSlots ? SLOT_HELPER : ""}
1097
+
1098
+ export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
1099
+ ${props.length > 0 ? "const __p = __props || {};" : ""}
1100
+ ${namedSlots ? "const __sl = __slots || {};" : ""}
1101
+ ${propsCode(props)}
1102
+ ${stateDeclsCode}
1103
+ ${script}
1104
+ ${handlerRegistry}
1105
+ const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
1106
+ let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
1107
+ return __html;
1108
+ }
1109
+ `;
1110
+ }
1111
+ 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);
1112
+ var routeShipsNoJs = (infos, compiled, i) => {
1113
+ if (compiled[i].csr === true) return false;
1114
+ if (compiled[i].needsClient) return false;
1115
+ return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
1116
+ };
1117
+ function buildReport(infos, compiled) {
1118
+ return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
1119
+ if (routeShipsNoJs(infos, compiled, i)) {
1120
+ return `${info.routePath} zero-JS nothing in the chain needs the client`;
1121
+ }
1122
+ 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("; ");
1123
+ const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
1124
+ return `${info.routePath} client JS ${why}${forced}`;
1125
+ });
1126
+ }
1127
+ async function buildProject(root, outDir) {
1128
+ await fs.promises.mkdir(outDir, { recursive: true });
1129
+ const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
1130
+ await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
1131
+ const pageFiles = await scanRoseFiles(root);
1132
+ const compFiles = await scanComponentFiles(root);
1133
+ const files = [...pageFiles, ...compFiles];
1134
+ if (pageFiles.length === 0) {
1135
+ throw new Error(`no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`);
1136
+ }
1137
+ const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
1138
+ const config = await loadConfig(root);
1139
+ const plugins = config.plugins;
1140
+ const scopeKeys = files.map((f, i) => {
1141
+ const base = infos[i].isComponent ? path.join(root, "src") : path.join(root, "src", "pages");
1142
+ return path.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
1143
+ });
1144
+ const registry = new Map(
1145
+ files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
1146
+ );
1147
+ const compiled = await Promise.all(
1148
+ files.map((f, i) => compileComponent(f, path.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
1149
+ );
1150
+ const importsOf = /* @__PURE__ */ new Map();
1151
+ files.forEach((_, i) => {
1152
+ const list = [];
1153
+ for (const r of compiled[i].roseImports ?? []) {
1154
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1155
+ const hit = registry.get(abs);
1156
+ if (hit) list.push(hit.index);
1157
+ }
1158
+ importsOf.set(i, list);
1159
+ });
1160
+ const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
1161
+ if (compiled[i].needsClient) return path.basename(files[i]);
1162
+ if (seen.has(i)) return null;
1163
+ seen.add(i);
1164
+ for (const dep of importsOf.get(i) ?? []) {
1165
+ const hit = needyDep(dep, seen);
1166
+ if (hit) return hit;
1167
+ }
1168
+ return null;
1169
+ };
1170
+ compiled.forEach((c, i) => {
1171
+ if (c.needsClient) return;
1172
+ const who = needyDep(i);
1173
+ if (who) {
1174
+ c.needsClient = true;
1175
+ c.clientReasons = [...c.clientReasons ?? [], `imported component ${who} needs the client`];
1176
+ }
1177
+ });
1178
+ const reachable = /* @__PURE__ */ new Set();
1179
+ const visit = (i) => {
1180
+ if (reachable.has(i)) return;
1181
+ reachable.add(i);
1182
+ for (const r of compiled[i].roseImports ?? []) {
1183
+ const abs = path.resolve(path.dirname(files[i]), r.specifier);
1184
+ const hit = registry.get(abs);
1185
+ if (hit) visit(hit.index);
1186
+ }
1187
+ };
1188
+ files.forEach((_, i) => {
1189
+ if (!infos[i].isComponent) visit(i);
1190
+ });
1191
+ const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
1192
+ if (styles) await fs.promises.writeFile(path.join(outDir, "styles.css"), styles);
1193
+ else await fs.promises.rm(path.join(outDir, "styles.css"), { force: true });
1194
+ let locales = {};
1195
+ try {
1196
+ for (const f of await fs.promises.readdir(path.join(root, "src", "locales"))) {
1197
+ if (!f.endsWith(".json")) continue;
1198
+ locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, "src", "locales", f), "utf-8"));
1199
+ }
1200
+ } catch {
1201
+ locales = {};
1202
+ }
1203
+ const defaultLocale = locales.en ? "en" : Object.keys(locales).sort()[0] ?? "en";
1204
+ const localesJson = JSON.stringify(locales).replace(/</g, "\\u003c");
1205
+ const preload = config.i18n.preload ?? Object.keys(locales);
1206
+ const packed = Object.keys(locales).filter((l) => !preload.includes(l));
1207
+ for (const l of preload) {
1208
+ if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
1209
+ }
1210
+ await fs.promises.rm(path.join(outDir, "locales"), { recursive: true, force: true });
1211
+ if (packed.length > 0) {
1212
+ const packDir = path.join(outDir, "locales");
1213
+ await fs.promises.mkdir(packDir, { recursive: true });
1214
+ for (const l of packed) await fs.promises.writeFile(path.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
1215
+ }
1216
+ const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
1217
+ const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
1218
+ const buildDir = path.join(outDir, ".build");
1219
+ await fs.promises.rm(buildDir, { recursive: true, force: true });
1220
+ await fs.promises.mkdir(buildDir, { recursive: true });
1221
+ const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
1222
+ if (runtimePlugins.length > 0) {
1223
+ const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
1224
+ await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `// Generated by rosetack - the runtime half of rosetack.config.js. Do not edit.
1225
+ // Bundled into dist/server.js: these hooks run per request on every server
1226
+ // (Node, dev/preview, edge). Transform hooks already ran at build time.
1227
+ import config from ${JSON.stringify(configRel)};
1228
+
1229
+ const list = Array.isArray(config) ? config : [];
1230
+ export const hooks = list
1231
+ .filter((p) => p && (p.onRequest || p.onResponse))
1232
+ .map((p) => ({ name: p.name, onRequest: p.onRequest ? p.onRequest.bind(p) : null, onResponse: p.onResponse ? p.onResponse.bind(p) : null }));
1233
+
1234
+ export const hasRequestHooks = hooks.some((p) => p.onRequest);
1235
+ export const hasResponseHooks = hooks.some((p) => p.onResponse);
1236
+ `);
1237
+ }
1238
+ const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
1239
+ if (!runtimeEntry) throw new Error("rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler");
1240
+ await esbuild.build({
1241
+ entryPoints: [runtimeEntry],
1242
+ bundle: true,
1243
+ outfile: path.join(buildDir, "runtime.js"),
1244
+ format: "esm",
1245
+ platform: "browser",
1246
+ write: true
1247
+ });
1248
+ for (let i = 0; i < compiled.length; i++) {
1249
+ const src = compiled[i].api ?? compiled[i].ssr;
1250
+ await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
1251
+ if (!infos[i].isApi) {
1252
+ await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
1253
+ }
1254
+ }
1255
+ const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent);
1256
+ const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi);
1257
+ const compose = (idx) => {
1258
+ let expr = `render_${idx}`;
1259
+ for (const i of layoutsOf(infos, idx)) {
1260
+ expr = `(async (closes, children) => await render_${i}(closes, await (${expr})(closes, children)))`;
1261
+ }
1262
+ return expr;
1263
+ };
1264
+ const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? "inline";
1265
+ const split = bundleMode === "split";
1266
+ const chainOf = (idx) => [idx, ...layoutsOf(infos, idx)];
1267
+ const loaderInner = (idx) => `load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(", ")}])`;
1268
+ const loaderOf = (idx) => `{ ${loaderInner(idx)} }`;
1269
+ const routeNoJs = (i) => routeShipsNoJs(infos, compiled, i);
1270
+ const serverImports = compiled.map((_, i) => {
1271
+ if (!reachable.has(i)) return "";
1272
+ if (infos[i].isMiddleware) {
1273
+ return `import * as middlewareMod from './comp-${i}.ssr.js';`;
1274
+ }
1275
+ if (infos[i].isApi) {
1276
+ const names2 = compiled[i].apiMethods ?? [];
1277
+ const handlerImports = names2.map((n) => `${n} as ${n}_${i}`).join(", ");
1278
+ return handlerImports ? `import { ${handlerImports} } from './comp-${i}.ssr.js';` : `import './comp-${i}.ssr.js';`;
1279
+ }
1280
+ const isPage = !infos[i].isLayout && !infos[i].isNotFound;
1281
+ const names = isPage ? compiled[i].actionNames : [];
1282
+ const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(", ");
1283
+ const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : "";
1284
+ const named = [actionImports, guardImport].filter(Boolean).join(", ");
1285
+ return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
1286
+ }).join("\n");
1287
+ const nfIdx = infos.findIndex((info) => info.isNotFound);
1288
+ const notFoundRender = nfIdx >= 0 ? split ? loaderOf(nfIdx) : compose(nfIdx) : "null";
1289
+ const errIdx = infos.findIndex((info) => info.isError);
1290
+ const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
1291
+ const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
1292
+ const serverRoutes = pages.map(({ info, i }) => {
1293
+ const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
1294
+ if (compiled[i].csr === false && compiled[i].needsClient) {
1295
+ throw new Error(
1296
+ `${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`
1297
+ );
1298
+ }
1299
+ if (compiled[i].csr === false) {
1300
+ const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
1301
+ if (needy !== void 0) {
1302
+ throw new Error(
1303
+ `${info.filePath}: csr = false cannot ship under ${infos[needy].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`
1304
+ );
1305
+ }
1306
+ }
1307
+ const csrFlag = routeNoJs(i) ? ", csr: false" : "";
1308
+ const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
1309
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag} }`;
1310
+ }).join(",\n ");
1311
+ const serverEntry = `
1312
+ ${serverImports}
1313
+ import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
1314
+ ${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
1315
+ // module to import - the runners below stay no-ops and the servers call them
1316
+ // unconditionally (one code path, no flags to keep in sync).
1317
+ const __pluginHooks = [];
1318
+ const __hasRequestHooks = false;
1319
+ const __hasResponseHooks = false;`}
1320
+
1321
+ // The runtime plugin hooks. onRequest runs before routing and
1322
+ // middleware and may short-circuit the request with its own Response; onResponse
1323
+ // runs once the response exists and may replace it. Both are no-ops when the
1324
+ // project declares no runtime hooks. A throwing hook is logged and skipped -
1325
+ // the request continues - so a broken logging plugin can never take a site
1326
+ // down (a build-time transform, by contrast, fails loudly).
1327
+ export async function runRequestHooks(ctx) {
1328
+ for (const p of __pluginHooks) {
1329
+ if (!p.onRequest) continue;
1330
+ try {
1331
+ const r = await p.onRequest(ctx);
1332
+ if (r instanceof Response) return r;
1333
+ } catch (err) {
1334
+ console.error('rosetack: plugin', p.name, 'onRequest failed:', err instanceof Error ? err.message : err);
1335
+ }
1336
+ }
1337
+ return null;
1338
+ }
1339
+
1340
+ export async function runResponseHooks(ctx, res) {
1341
+ let out = res;
1342
+ for (const p of __pluginHooks) {
1343
+ if (!p.onResponse) continue;
1344
+ try {
1345
+ const r = await p.onResponse(ctx, out);
1346
+ if (r instanceof Response) out = r;
1347
+ } catch (err) {
1348
+ console.error('rosetack: plugin', p.name, 'onResponse failed:', err instanceof Error ? err.message : err);
1349
+ }
1350
+ }
1351
+ return out;
1352
+ }
1353
+
1354
+ // The servers read these to skip building the hook context entirely when no
1355
+ // hook exists - the hot path pays nothing for the feature.
1356
+ export const hasRequestHooks = __hasRequestHooks;
1357
+ export const hasResponseHooks = __hasResponseHooks;
1358
+
1359
+ // i18n: the dictionaries baked at build time from
1360
+ // src/locales/*.json. A route segment named [lang] is the locale: the value
1361
+ // must name one of these dictionaries, and $t resolves keys against it.
1362
+ setLocales(${localesJson}, '${defaultLocale}');
1363
+
1364
+ // The store transport. Under "rosetack serve" every worker is its
1365
+ // own process with its own dist/server.js module, so a $store write must
1366
+ // travel: this worker -> primary -> every other worker. process.send exists
1367
+ // only inside cluster workers, so a single-process runner (dev, preview,
1368
+ // the edge adapter) keeps the transport null and $store stays plain
1369
+ // per-process state - the documented boundary, not a bug.
1370
+ if (typeof process !== 'undefined' && typeof process.send === 'function') {
1371
+ setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
1372
+ process.on('message', (msg) => {
1373
+ if (msg && msg.type === 'rosetack:store') applyStorePatch(msg.name, msg.value);
1374
+ });
1375
+ }
1376
+
1377
+ export { localeList };
1378
+ export const defaultLocale = '${defaultLocale}';
1379
+
1380
+ // Route params maps, re-exported for the build's prerender step: routePath
1381
+ // -> the component's exported params (a static map or a function). Reading
1382
+ // them through the server bundle keeps the deploy dir free of component
1383
+ // modules - both bundles are self-contained, nothing else may ship. Only
1384
+ // components that actually export params appear here (a missing export
1385
+ // means the dynamic route renders on demand).
1386
+ ${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
1387
+
1388
+ export const routeParams = {
1389
+ ${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
1390
+ };
1391
+
1392
+ // Routes whose component reads the request context (getContext()), mutates a
1393
+ // shared store ($store), or opted into nonce-based CSP: the bag is
1394
+ // per-request, the store is per-process, and a nonce is per-response, so
1395
+ // these are dynamic - the build never bakes them and the servers never
1396
+ // answer them from a prerendered file. Public routes keep the static fast
1397
+ // path (file cache, ETag/304, streaming) untouched.
1398
+ export const dynamicRoutes = [
1399
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1400
+ ];
1401
+
1402
+ // Which api routes opt into build-time baking (export const prerender = true):
1403
+ // routePath -> boolean. The build calls the GET handler once and writes the
1404
+ // body to dist/, so the Go single binary serves read-only APIs without Node.
1405
+ ${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
1406
+
1407
+ export const apiPrerender = {
1408
+ ${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
1409
+ };
1410
+
1411
+ // Stale-while-revalidate windows (export const revalidate = N): the build
1412
+ // bakes these routes like any other, and the preview server serves the
1413
+ // baked file for up to N seconds - after which the next request is answered
1414
+ // STALE (instant, from disk) while a background pass re-renders and swaps
1415
+ // the file (ISR). Routes that read the request context are
1416
+ // excluded: they render per request and have no baked file to revalidate.
1417
+ // The dev server ignores the window (it rebuilds on change), the edge
1418
+ // adapter renders live (always fresh), and the Go binary serves the baked
1419
+ // file forever - the same static-half boundary as page POSTs.
1420
+ export const revalidate = [
1421
+ ${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
1422
+ ];
1423
+
1424
+ // pages/_middleware.rose: a Web-standard request handler that runs before
1425
+ // every render on the server (pages, POSTs, api calls alike). Returning a
1426
+ // Response short-circuits the whole request - a redirect, an auth wall, a
1427
+ // rewrite; returning nothing continues, and getContext() hands the
1428
+ // per-request bag to $data, server actions and api handlers. Absent -> null,
1429
+ // and the servers keep their static fast paths.
1430
+ export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
1431
+
1432
+ // Routes whose DOCUMENTS ship without the client bundle (
1433
+ // decided by the compiler since #29): HTML + CSS only - no runtime, no
1434
+ // state script, zero JavaScript for whoever lands on them. The compiler
1435
+ // picks these automatically: a route whose whole chain needs nothing from
1436
+ // the client (no event wiring, no lifecycle, no action, no form) is a
1437
+ // content route. An exported "csr = true" forces the bundle back in; an
1438
+ // exported "csr = false" is the same decision, asserted. The route's render
1439
+ // function still rides in the client bundle, so a client-side navigation
1440
+ // from an interactive page paints it normally and a static deploy's SPA
1441
+ // fallback can render it too; only the document is JS-free.
1442
+ // isNoJs() lets the servers keep these routes on the buffered path: a
1443
+ // streamed no-JS document would carry the shell's default <title> (the
1444
+ // route head is applied client-side at boot, and there is no client).
1445
+ export const noJsRoutes = [
1446
+ ${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
1447
+ ];
1448
+
1449
+ export function isNoJs(pathname) {
1450
+ return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
1451
+ }
1452
+
1453
+ // Per-route response headers: a route exporting a headers
1454
+ // map carries them into every response the servers write for it, merged
1455
+ // OVER the framework defaults (the strict CSP) - so an app can tighten or
1456
+ // relax the policy per route. Absent -> null, and the servers keep sending
1457
+ // the defaults alone.
1458
+ export const routeHeaders = [
1459
+ ${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
1460
+ ];
1461
+
1462
+ export function headersFor(pathname) {
1463
+ const hit = routeHeaders.find((r) => matchRoute(r.pattern, pathname));
1464
+ return hit ? hit.headers : null;
1465
+ }
1466
+
1467
+ // Routes that opted into nonce-based CSP (export const csp = { nonce: true },
1468
+ // ). The servers ask this BEFORE writing a document: when it is true they
1469
+ // mint one random nonce per response, put it in the CSP header ('nonce-...'
1470
+ // plus 'strict-dynamic', so the document's own code may load more code) and
1471
+ // stamp the same value on the script tag. The default policy stays a hash -
1472
+ // cspNonceRoutes is empty for an app that never asks, so the fast path is
1473
+ // unchanged. The Go binary never sees this: these routes are dynamic, so it
1474
+ // has no baked file for them to serve.
1475
+ export const cspNonceRoutes = [
1476
+ ${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
1477
+ ];
1478
+
1479
+ export function cspNonce(pathname) {
1480
+ return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
1481
+ }
1482
+
1483
+ // A Web-standard Request from whatever the host provides: the edge adapter
1484
+ // passes one already; the Node server passes its IncomingMessage (plus the
1485
+ // already-parsed FormData for POSTs, so middleware can read form fields).
1486
+ function toWebRequest(raw, form) {
1487
+ if (raw instanceof Request) return raw;
1488
+ const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
1489
+ if (form) init.body = form;
1490
+ return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
1491
+ }
1492
+
1493
+ // Runs the middleware (if the project has one) for this request and returns
1494
+ // its short-circuit Response, or null to continue. The servers call this
1495
+ // EXACTLY ONCE per request, before anything else: it resets the per-request
1496
+ // context bag and the middleware fills it via getContext(), which $data,
1497
+ // server actions and api handlers then read while rendering. rawReq: the
1498
+ // host's request (Node IncomingMessage or a Web-standard Request); form:
1499
+ // the already-parsed FormData of a POST.
1500
+ export async function runMiddleware(rawReq, form) {
1501
+ resetRequestContext();
1502
+ if (!middleware || !rawReq) return null;
1503
+ const res = await middleware(toWebRequest(rawReq, form));
1504
+ return res || null;
1505
+ }
1506
+
1507
+ const routes = [
1508
+ ${serverRoutes}
1509
+ ];
1510
+
1511
+ // API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
1512
+ // render HTML and never reach the client bundle. The middleware ran before
1513
+ // this (the servers call runMiddleware() first), so handlers can read
1514
+ // getContext() for auth without re-running anything.
1515
+ const apiRoutes = [
1516
+ ${apiRoutes.map(({ info, i }) => {
1517
+ const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
1518
+ return `{ pattern: '${info.pattern}', path: '${info.routePath}', handlers: { ${handlers} } }`;
1519
+ }).join(",\n ")}
1520
+ ];
1521
+
1522
+ // pages/404.rose (with its layouts) or null -> built-in plain 404
1523
+ const notFound = ${notFoundRender};
1524
+
1525
+ // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1526
+ // whose render throws degrades to this instead of failing the response.
1527
+ const errorPage = ${errorRender};
1528
+
1529
+ // The <html> attributes of the document for a pathname - the locale
1530
+ // of its [lang] segment (the default when there is none, or when the segment
1531
+ // names no dictionary: that request 404s in the default language) and the
1532
+ // reading direction that locale implies. The buffered render returns the same
1533
+ // pair; the streaming path needs it BEFORE the shell flushes, which is why
1534
+ // the servers ask for it by pathname.
1535
+ export function docAttrs(pathname) {
1536
+ for (const route of routes) {
1537
+ if (!matchRoute(route.pattern, pathname)) continue;
1538
+ const parts = route.pattern.split('/');
1539
+ const langIdx = parts.indexOf(':lang');
1540
+ if (langIdx >= 0) {
1541
+ const lang = pathname.split('/')[langIdx];
1542
+ if (isLocale(lang)) return { lang, dir: localeDir(lang) };
1543
+ }
1544
+ break; // matched, but not a localized route (or a bogus locale): the default
1545
+ }
1546
+ return { lang: defaultLocale, dir: localeDir(defaultLocale) };
1547
+ }
1548
+
1549
+ // Paint a fallback page (404/500) and serialize its state.
1550
+ async function renderFallback(pathname, render) {
1551
+ const { html, head } = extractHead(await render([], ''));
1552
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1553
+ return { html, state, head, ...docAttrs(pathname) };
1554
+ }
1555
+
1556
+ export function matchRoute(pattern, pathname) {
1557
+ const patternParts = pattern.split('/');
1558
+ const pathParts = pathname.split('/');
1559
+ if (patternParts.length !== pathParts.length) return false;
1560
+ for (let i = 0; i < patternParts.length; i++) {
1561
+ if (patternParts[i].startsWith(':')) continue;
1562
+ if (patternParts[i] !== pathParts[i]) return false;
1563
+ }
1564
+ return true;
1565
+ }
1566
+
1567
+ // Head blocks (one per component in the route chain) are pulled out of the
1568
+ // page html: the shell injects them into <head>, and the client re-applies
1569
+ // them on navigation. Document order is page-first, so the shell's keyed
1570
+ // merge lets a page override its layouts. The EMPTY marker pair stays in the
1571
+ // body so the client's wire() still finds the block: at boot it adopts the
1572
+ // shell-injected elements in place (marked with the same keys, so no
1573
+ // duplicates) and keeps the head reactive.
1574
+ function extractHead(rendered) {
1575
+ const head = [];
1576
+ const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
1577
+ head.push(content);
1578
+ return '<!--\u27E6h:' + id + '\u27E7--><!--\u27E6/h:' + id + '\u27E7-->';
1579
+ });
1580
+ return { html, head };
1581
+ }
1582
+
1583
+ // form: the submitted FormData of a progressive-enhancement POST. The
1584
+ // selected server action runs first and returns a state patch (e.g.
1585
+ // { guests: [...] }); seeding those keys BEFORE the render makes state()
1586
+ // adopt them, so the response is the page as it looks AFTER the action -
1587
+ // with or without JS. A __action field picks the action by name (default
1588
+ // 'action', the conventional <form method="POST"> target); a click handler
1589
+ // bound to an action ($action('like')) sends the same field.
1590
+ // A route whose render throws degrades to pages/500.rose (status 500) - or
1591
+ // the built-in plain 500 - instead of failing the whole response.
1592
+ // The middleware does NOT run here: the servers run it once per request via
1593
+ // runMiddleware() (which also seeds the request context), so a page render
1594
+ // never re-runs it.
1595
+ export async function renderPage(pathname, form) {
1596
+ clearRequestState();
1597
+ for (const route of routes) {
1598
+ if (matchRoute(route.pattern, pathname)) {
1599
+ const patternParts = route.pattern.split('/');
1600
+ const pathParts = pathname.split('/');
1601
+ for (let i = 0; i < patternParts.length; i++) {
1602
+ if (patternParts[i].startsWith(':')) {
1603
+ setState(patternParts[i].slice(1), pathParts[i]);
1604
+ }
1605
+ }
1606
+ // i18n: a [lang] segment naming no dictionary is a
1607
+ // 404 - the URL is the contract, and rendering the page with fallback
1608
+ // strings would serve duplicate content under a bogus language
1609
+ const langIdx = patternParts.indexOf(':lang');
1610
+ if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
1611
+ if (notFound) return { ...(await renderFallback(pathname, notFound)), status: 404 };
1612
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1613
+ }
1614
+ // The document's <html lang>/<dir> follow this route's locale
1615
+ // (the default's when the route is not localized)
1616
+ const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
1617
+ // The action dispatch. The page's guard (exported
1618
+ // beforeAction) runs FIRST and vetoes with an ActionError - the
1619
+ // action-level permission check. Then the selected action runs and its
1620
+ // return value seeds this render's state, per key, so an incremental
1621
+ // patch ($append and friends) grows a large list by one row instead of
1622
+ // re-sending the whole thing. An ActionError from either half is a
1623
+ // BUSINESS failure: it is seeded as the 'actionError' state, the
1624
+ // response carries its status, and the page renders with the failure
1625
+ // visible (a {#boundary} around the action's widget contains it).
1626
+ // Anything else is a bug and keeps going to the 500 page.
1627
+ let actionStatus = 0;
1628
+ if (form && route.actions) {
1629
+ const actionName = form.get('__action') || 'action';
1630
+ const fn = route.actions[actionName];
1631
+ if (fn) {
1632
+ try {
1633
+ if (route.guard) await route.guard(actionName, form);
1634
+ const patch = await fn(form);
1635
+ if (patch && typeof patch === 'object') {
1636
+ for (const key of Object.keys(patch)) {
1637
+ const v = patch[key];
1638
+ // An incremental patch is RECORDED, not applied: the render's
1639
+ // own state declarations apply it, so the delta is relative to
1640
+ // the value the page was going to render anyway.
1641
+ if (v instanceof StateDelta) setStateDelta(key, v);
1642
+ else setState(key, v);
1643
+ }
1644
+ }
1645
+ } catch (err) {
1646
+ if (err instanceof ActionError) {
1647
+ setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
1648
+ actionStatus = err.code;
1649
+ } else {
1650
+ throw err;
1651
+ }
1652
+ }
1653
+ }
1654
+ }
1655
+ let rendered;
1656
+ try {
1657
+ rendered = extractHead(await route.render([], ''));
1658
+ } catch (err) {
1659
+ console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1660
+ if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
1661
+ return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
1662
+ }
1663
+ // __route tells the bootstrap which route this document was rendered for.
1664
+ // A static-file server may serve another route's document (SPA fallback);
1665
+ // the bootstrap then client-renders instead of adopting mismatched DOM.
1666
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1667
+ // csr ( auto since #29): false when the compiler found
1668
+ // nothing in the route's chain that needs the client (or the route
1669
+ // asserted csr = false) - the document ships no runtime, no state
1670
+ // script, zero JavaScript. Every other route keeps the bundle. The
1671
+ // caller passes this straight to the shell as js.
1672
+ // Status is the failed action's code when one failed - the page
1673
+ // rendered fine, so the body is the page with the failure visible, and
1674
+ // the status says what happened (a 403 from the guard, a 422 from a
1675
+ // validation action). 200 otherwise.
1676
+ // Lang/dir are the document's <html> attributes - the locale
1677
+ // this route rendered in, and its reading direction.
1678
+ return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
1679
+ }
1680
+ }
1681
+ if (notFound) {
1682
+ return { ...(await renderFallback(pathname, notFound)), status: 404 };
1683
+ }
1684
+ return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
1685
+ }
1686
+
1687
+ // Would renderPageStream handle this path? (matched route = stream, anything
1688
+ // else = buffered 404/500). Lets the servers pick the path before headers.
1689
+ export function canStream(pathname) {
1690
+ return routes.some((route) => {
1691
+ if (!matchRoute(route.pattern, pathname)) return false;
1692
+ // i18n: an unknown locale must answer 404, and a
1693
+ // streamed response cannot change its status - so it takes the buffered
1694
+ // path (renderPage returns the real 404), never the streaming one
1695
+ const langIdx = route.pattern.split('/').indexOf(':lang');
1696
+ return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
1697
+ });
1698
+ }
1699
+
1700
+ // === API routes ===
1701
+ // The /api namespace answers JSON, never HTML: an API client that hits an
1702
+ // unknown path must not receive the SPA shell. Handlers receive a
1703
+ // Web-standard Request and return a plain object (serialized as JSON, 200),
1704
+ // a Response (passed through), or nothing (204). A method the route does
1705
+ // not export answers 405 with an Allow header. Same code path on the Node
1706
+ // server and the edge adapter - Response is a global in both.
1707
+ export function isApi(pathname) {
1708
+ return pathname === '/api' || pathname.startsWith('/api/');
1709
+ }
1710
+
1711
+ function toResponse(out) {
1712
+ if (out instanceof Response) return out;
1713
+ if (out === undefined || out === null) return new Response(null, { status: 204 });
1714
+ return new Response(JSON.stringify(out), {
1715
+ status: 200,
1716
+ headers: { 'content-type': 'application/json' },
1717
+ });
1718
+ }
1719
+
1720
+ export async function handleApi(method, pathname, request) {
1721
+ for (const route of apiRoutes) {
1722
+ if (matchRoute(route.pattern, pathname)) {
1723
+ const fn = route.handlers[method];
1724
+ if (!fn) {
1725
+ return new Response(JSON.stringify({ error: 'method not allowed' }), {
1726
+ status: 405,
1727
+ headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
1728
+ });
1729
+ }
1730
+ return toResponse(await fn(request));
1731
+ }
1732
+ }
1733
+ return new Response(JSON.stringify({ error: 'not found' }), {
1734
+ status: 404,
1735
+ headers: { 'content-type': 'application/json' },
1736
+ });
1737
+ }
1738
+
1739
+ // === Streaming SSR ===
1740
+ // The static shell (doctype, <head>, body + container open) flushes BEFORE
1741
+ // the - possibly slow - render completes: the first byte leaves in
1742
+ // microseconds instead of after every $data resolves. The route HTML, the
1743
+ // state script, and the inlined bundle follow as later chunks of one chunked
1744
+ // response - still exactly one request.
1745
+ // The route's <head> tags are NOT in the streamed document: the client
1746
+ // applies them at boot from the body's head markers, so JS users see the
1747
+ // correct head immediately; no-JS consumers of streamed responses get the
1748
+ // static shell head (prerendered files stay complete documents).
1749
+ // Returns 200 (matched; a render throw degrades to the error-page body) or
1750
+ // 404 (unmatched - nothing written, so the caller can still buffer).
1751
+ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
1752
+ clearRequestState();
1753
+ for (const route of routes) {
1754
+ if (matchRoute(route.pattern, pathname)) {
1755
+ const patternParts = route.pattern.split('/');
1756
+ const pathParts = pathname.split('/');
1757
+ for (let i = 0; i < patternParts.length; i++) {
1758
+ if (patternParts[i].startsWith(':')) {
1759
+ setState(patternParts[i].slice(1), pathParts[i]);
1760
+ }
1761
+ }
1762
+ // i18n: an unknown locale must 404 BEFORE the shell flushes - a
1763
+ // streamed response cannot change its status afterwards
1764
+ const langIdx = patternParts.indexOf(':lang');
1765
+ if (langIdx >= 0 && !isLocale(pathParts[langIdx])) return 404;
1766
+ write(shellOpen);
1767
+ let html;
1768
+ try {
1769
+ html = extractHead(await route.render([], '')).html;
1770
+ } catch (err) {
1771
+ // the shell is already on the wire: degrade to the error page BODY
1772
+ // (the status stays 200 - a real 500 needs the buffered path, which
1773
+ // the server picks for routes known-broken at build time)
1774
+ console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
1775
+ html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
1776
+ }
1777
+ write(html);
1778
+ // csr: false ( auto since #29): a no-JS route's document
1779
+ // ends here - no state script, no inlined bundle. (The servers keep
1780
+ // these routes off the streaming path so their <head> is complete;
1781
+ // this is the correctness floor if one streams anyway.)
1782
+ if (route.csr === false) {
1783
+ write('</div>\\n</body>\\n</html>');
1784
+ return 200;
1785
+ }
1786
+ const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
1787
+ write('</div>\\n <script type="application/json" id="__rosetack_state">' + state + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
1788
+ return 200;
1789
+ }
1790
+ }
1791
+ return 404;
1792
+ }
1793
+ `;
1794
+ await fs.promises.writeFile(path.join(buildDir, "server-entry.js"), serverEntry);
1795
+ await esbuild.build({
1796
+ entryPoints: [path.join(buildDir, "server-entry.js")],
1797
+ bundle: true,
1798
+ outfile: path.join(outDir, "server.js"),
1799
+ format: "esm",
1800
+ platform: "node",
1801
+ write: true,
1802
+ ...TS_LOADER
1803
+ });
1804
+ const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
1805
+ const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
1806
+ const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
1807
+ const hasLang = infos.some((i) => i.pattern.includes(":lang"));
1808
+ const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
1809
+ // client-side navigation cannot leave stale (screen readers and CSS
1810
+ // logical properties both read it). A route with no [lang] segment
1811
+ // returns to the default locale, and a bogus segment falls back to it
1812
+ // too, exactly like the server's docAttrs.
1813
+ const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
1814
+ const known = !seg || isLocale(seg);
1815
+ const docLang = known && seg ? seg : __defLocale;
1816
+ document.documentElement.lang = docLang;
1817
+ const docDir = localeDir(docLang);
1818
+ if (docDir) document.documentElement.setAttribute('dir', docDir);
1819
+ else document.documentElement.removeAttribute('dir');
1820
+ if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
1821
+ const clientEntry = `
1822
+ ${clientImports}
1823
+ import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
1824
+
1825
+ // i18n: the dictionaries baked at build time - the client
1826
+ // renders any PRELOADED locale from the bundle, so switching language costs
1827
+ // zero requests (the same bet as the inlined route table). a locale
1828
+ // the app left out of the preload (i18n.preload in rosetack.config.js) is a
1829
+ // pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
1830
+ // on first use - one request per language per session, then it renders from
1831
+ // memory like any other. The default build preloads everything and ships no
1832
+ // packs at all.
1833
+ setLocales(${clientLocalesJson}, '${defaultLocale}');
1834
+ setLocalePacks(${JSON.stringify(packed)});
1835
+ ${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
1836
+ // follow a route that carries no [lang] segment (a non-i18n page)
1837
+ const __defLocale = '${defaultLocale}';` : ""}
1838
+ // The two pack doors, re-exported for an app that wants to warm a language
1839
+ // before its visitor asks for it (ensureLocale) or to feed a dictionary it
1840
+ // fetched itself (loadLocale). Both are already in the bundle - ensureLocale
1841
+ // is what applyParams calls - so the re-export costs the statement alone.
1842
+ export { ensureLocale, loadLocale } from './runtime.js';
1843
+
1844
+ const routes = [
1845
+ ${clientRoutes}
1846
+ ];
1847
+
1848
+ // === Mode B: lazy route chunks ===
1849
+ // Split mode's registry entries arrive without a render function: loadChain
1850
+ // loads the route's module graph (the page plus its layouts, one chunk per
1851
+ // module, the shared runtime in its own vendor chunk) in parallel and
1852
+ // composes it at runtime - the exact nesting compose() built at compile
1853
+ // time for inline mode. getRender memoizes the composed function on the
1854
+ // entry, so a chunk loads once per session; inline mode's entries are the
1855
+ // render functions themselves, so the helper is a pass-through there.
1856
+ const loadChain = async (loaders) => {
1857
+ const mods = await Promise.all(loaders.map((load) => load()));
1858
+ let expr = (closes, children) => mods[0].render(closes, children);
1859
+ for (let k = 1; k < mods.length; k++) {
1860
+ const inner = expr;
1861
+ const outer = mods[k].render;
1862
+ expr = async (closes, children) => await outer(closes, await inner(closes, children));
1863
+ }
1864
+ return { render: expr };
1865
+ };
1866
+ const getRender = async (route) => {
1867
+ if (typeof route === 'function') return route; // inline mode: the render itself
1868
+ return (route.render ??= (await route.load()).render);
1869
+ };
1870
+
1871
+ // pages/404.rose (with its layouts) or null -> built-in plain 404
1872
+ const notFound = ${notFoundRender};
1873
+
1874
+ // pages/500.rose (with its layouts) or null -> built-in plain 500: a route
1875
+ // whose render throws on the client degrades to this instead of breaking
1876
+ // navigation.
1877
+ const errorPage = ${errorRender};
1878
+
1879
+ // Paint a fallback page (404/500) into the container, wired like any render.
1880
+ async function paintFallback(container, page, builtin) {
1881
+ resetEffects();
1882
+ clearRequestState();
1883
+ clearMounts(); // a failed render leaves stale mounts behind
1884
+ // inline mode passes the render itself; split mode passes a loader
1885
+ const render = page ? await getRender(page) : null;
1886
+ if (render) {
1887
+ const closes = [];
1888
+ const html = await render(closes, '');
1889
+ container.innerHTML = html;
1890
+ wire(container, closes);
1891
+ bindEvents(container);
1892
+ flushMounts();
1893
+ return;
1894
+ }
1895
+ container.innerHTML = builtin;
1896
+ }
1897
+
1898
+ export function matchRoute(pattern, pathname) {
1899
+ const patternParts = pattern.split('/');
1900
+ const pathParts = pathname.split('/');
1901
+ if (patternParts.length !== pathParts.length) return false;
1902
+ for (let i = 0; i < patternParts.length; i++) {
1903
+ if (patternParts[i].startsWith(':')) continue;
1904
+ if (patternParts[i] !== pathParts[i]) return false;
1905
+ }
1906
+ return true;
1907
+ }
1908
+
1909
+ // === Link prefetch ===
1910
+ // Hover / focus / touch an internal link and the target route renders NOW -
1911
+ // $data included - against a throwaway signal map. The click that follows
1912
+ // paints from the cached HTML: no await, no request, no spinner. Other
1913
+ // frameworks prefetch data only; rosetack prefetches the whole render because
1914
+ // the inlined bundle already contains every route.
1915
+ // Trade-off: the cache holds either a result or the in-flight promise (dedupes
1916
+ // hover storms); one isolated render runs at a time so signal-map swapping
1917
+ // stays correct without any merging logic. Entries are single-use: a consumed
1918
+ // entry disappears from the cache, which is also how tests observe a hit.
1919
+ // P1, three guards for link-heavy pages:
1920
+ // 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
1921
+ // 'viewport' | 'all'" (root layout); 'all' is the original behavior.
1922
+ // Trade-off: app-global, not per-route - per-route would carry the mode
1923
+ // in each document's shell.
1924
+ // 2. budget - renders are serialized by the queue, so "concurrency" is 1;
1925
+ // the budget caps the QUEUE: a hover storm past it drops the excess
1926
+ // instead of rendering fifty routes nobody clicks.
1927
+ // 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
1928
+ // is evicted first (Map iteration order; entries are single-use, so
1929
+ // insertion order IS the recency order).
1930
+ let prefetchMode = ${JSON.stringify(prefetchMode)};
1931
+ export function setPrefetchMode(mode) { prefetchMode = mode; }
1932
+ const PREFETCH_BUDGET = 8;
1933
+ const PREFETCH_MAX_CACHED = 4;
1934
+ const prefetchCache = new Map(); // pathname -> { html, closes, state } | Promise
1935
+ let prefetchQueue = Promise.resolve();
1936
+ let prefetchPending = 0;
1937
+
1938
+ // Applies the route's params to state. A [lang] segment whose dictionary is
1939
+ // a runtime pack (i18n.preload) is awaited HERE - the one place every client
1940
+ // render path goes through (navigation, prefetch, action adopt) - so a packed
1941
+ // locale costs one request per session and then renders from memory. A
1942
+ // preloaded locale (the default: every dictionary inline) resolves without
1943
+ // touching the network, so the common path stays synchronous in spirit.
1944
+ async function applyParams(route, pathname) {
1945
+ const patternParts = route.pattern.split('/');
1946
+ const pathParts = pathname.split('/');
1947
+ for (let i = 0; i < patternParts.length; i++) {
1948
+ if (patternParts[i].startsWith(':')) setState(patternParts[i].slice(1), pathParts[i]);
1949
+ }
1950
+ const langIdx = patternParts.indexOf(':lang');
1951
+ if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
1952
+ }
1953
+
1954
+ export function prefetch(pathname, source = 'hover') {
1955
+ if (prefetchMode === 'off') return;
1956
+ if (prefetchMode === 'hover' && source !== 'hover') return;
1957
+ if (prefetchMode === 'viewport' && source !== 'viewport') return;
1958
+ if (prefetchCache.has(pathname)) return;
1959
+ if (pathname === location.pathname) return; // already here: nothing to prefetch
1960
+ const route = routes.find((r) => matchRoute(r.pattern, pathname));
1961
+ if (!route) return;
1962
+ if (prefetchPending >= PREFETCH_BUDGET) return; // budget spent: drop it, a later hover retries
1963
+ const p = prefetchQueue.then(async () => {
1964
+ try {
1965
+ // the isolated render also captures the onMount callbacks the route
1966
+ // queued and the onCleanup disposers it registered: the paint that
1967
+ // consumes this entry replays the mounts after wiring and adopts the
1968
+ // cleanups, so the prefetched route's timers are disposed on the next
1969
+ // navigation like any live route's
1970
+ const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
1971
+ await applyParams(route, pathname); // a packed locale's dictionary lands before the render
1972
+ const closes = [];
1973
+ const render = await getRender(route); // split mode: loads the route's chunk here
1974
+ const html = await render(closes, '');
1975
+ return { html, closes };
1976
+ });
1977
+ const entry = { ...result, state, mounts, cleanups };
1978
+ prefetchCache.set(pathname, entry); // promise -> result
1979
+ // evict oldest-first; in-flight promises are never evicted (evicting
1980
+ // one would only force a duplicate render)
1981
+ while (prefetchCache.size > PREFETCH_MAX_CACHED) {
1982
+ const oldest = prefetchCache.keys().next().value;
1983
+ if (prefetchCache.get(oldest) instanceof Promise) break;
1984
+ prefetchCache.delete(oldest);
1985
+ }
1986
+ return entry;
1987
+ } catch {
1988
+ prefetchCache.delete(pathname); // failed: the next hover retries
1989
+ return null;
1990
+ } finally {
1991
+ prefetchPending--;
1992
+ }
1993
+ });
1994
+ prefetchPending++;
1995
+ prefetchCache.set(pathname, p);
1996
+ prefetchQueue = p;
1997
+ }
1998
+
1999
+ export function prefetchStats() {
2000
+ return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
2001
+ }
2002
+
2003
+ // One delegated listener per event type on the app container: survives DOM
2004
+ // swaps and cloned blocks, so handlers never need re-binding. A handler
2005
+ // compiled from a server action (data-on-*="$action:name") dispatches to
2006
+ // $action instead of the local handler registry.
2007
+ const DELEGATED = ['click', 'input', 'change', 'submit'];
2008
+ function bindEvents(container) {
2009
+ if (container.__rosetack_bound) return;
2010
+ container.__rosetack_bound = true;
2011
+ for (const ev of DELEGATED) {
2012
+ container.addEventListener(ev, (e) => {
2013
+ const el = e.target.closest('[data-on-' + ev + ']');
2014
+ if (!el || !container.contains(el)) return;
2015
+ const fn = el.getAttribute('data-on-' + ev);
2016
+ if (fn.startsWith('$action:')) return $action(fn.slice(8), e);
2017
+ const h = handlers[fn];
2018
+ if (h) h(e);
2019
+ });
2020
+ }
2021
+ }
2022
+
2023
+ // === Server actions from any event ===
2024
+ // POST the body to the current route and adopt the response in place: the
2025
+ // server runs the selected action, seeds its state patch, and re-renders, so
2026
+ // the swapped DOM is the page as it looks AFTER the action - one request, no
2027
+ // reload, and wire() patches only the marked nodes (no re-render). The
2028
+ // bootstrap's <form method="POST"> interception goes through the same door.
2029
+ async function postForm(body) {
2030
+ const res = await fetch(location.pathname, { method: 'POST', body });
2031
+ const html = await res.text();
2032
+ const doc = new DOMParser().parseFromString(html, 'text/html');
2033
+ const next = doc.getElementById('app');
2034
+ const st = doc.getElementById('__rosetack_state');
2035
+ const paint = () => {
2036
+ const container = document.getElementById('app');
2037
+ adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
2038
+ };
2039
+ if (document.startViewTransition) document.startViewTransition(paint);
2040
+ else paint();
2041
+ }
2042
+
2043
+ // Call a page's server action by name from any event handler:
2044
+ // <button on:click={like}> compiles to $action('like'). Without JS the
2045
+ // binding is inert - the progressive-enhancement story stays with forms.
2046
+ export async function $action(name, e) {
2047
+ if (e && e.preventDefault) e.preventDefault();
2048
+ const body = new FormData();
2049
+ body.append('__action', name);
2050
+ return postForm(body);
2051
+ }
2052
+
2053
+ export { postForm };
2054
+
2055
+ // initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to
2056
+ // the existing nodes and bind events. initial=false: client-side navigation -
2057
+ // re-render the route chain from scratch and wire the fresh DOM.
2058
+ export async function start(container, pathname, initial) {
2059
+ clearMounts(); // stale mounts from a failed render never fire
2060
+ if (initial) {
2061
+ const el = document.getElementById('__rosetack_state');
2062
+ if (el) resumeState(el.textContent);
2063
+ }
2064
+ for (const route of routes) {
2065
+ if (matchRoute(route.pattern, pathname)) {
2066
+ // i18n: an unknown locale paints the 404 page, same as the server
2067
+ // (before the prefetch check: a cached entry for a bogus locale is
2068
+ // discarded, never painted)
2069
+ const langIdx = route.pattern.split('/').indexOf(':lang');
2070
+ ${langDirBlock}
2071
+ await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2072
+ return;
2073
+ }
2074
+ // Prefetched on hover/focus/touch: the render already ran, so paint its
2075
+ // HTML and adopt its signal entries - events then patch the very nodes
2076
+ // we wire, and no $data re-runs on click.
2077
+ let hit = initial ? undefined : prefetchCache.get(pathname);
2078
+ if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
2079
+ if (hit) {
2080
+ prefetchCache.delete(pathname); // single-use: the next hover refetches
2081
+ resetEffects();
2082
+ restoreState(hit.state);
2083
+ container.innerHTML = hit.html;
2084
+ wire(container, hit.closes);
2085
+ bindEvents(container);
2086
+ hit.mounts.forEach((fn) => fn()); // the prefetched route's mounts
2087
+ adoptCleanups(hit.cleanups); // and its cleanups, for the next resetEffects
2088
+ return;
2089
+ }
2090
+ if (!initial) {
2091
+ resetEffects();
2092
+ clearRequestState();
2093
+ }
2094
+ await applyParams(route, pathname);
2095
+ const closes = [];
2096
+ let html;
2097
+ try {
2098
+ const render = await getRender(route); // split mode: loads the route's chunk here
2099
+ html = await render(closes, '');
2100
+ } catch {
2101
+ // the route itself is broken: degrade to pages/500.rose (or the
2102
+ // built-in plain 500) instead of leaving the container empty
2103
+ await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
2104
+ return;
2105
+ }
2106
+ if (!initial) container.innerHTML = html;
2107
+ wire(container, closes);
2108
+ bindEvents(container);
2109
+ flushMounts();
2110
+ return;
2111
+ }
2112
+ }
2113
+ // unmatched route: pages/404.rose renders (with its head + interactivity),
2114
+ // else the built-in plain 404 - and an i18n app's document returns to the
2115
+ // default locale, the same one the server stamps on its 404
2116
+ ${hasLang ? ` document.documentElement.lang = __defLocale;
2117
+ document.documentElement.removeAttribute('dir');` : ""}
2118
+ await paintFallback(container, notFound, '<h1>404</h1><p>Page not found</p>');
2119
+ }
2120
+
2121
+ // Adopt a server-rendered response in place - the JS-enabled half of
2122
+ // progressive-enhancement forms: the bootstrap POSTs a <form method="POST">
2123
+ // via fetch and hands the response here. The DOM is swapped and wired with
2124
+ // the same zero-render trick as boot: re-run the route's render to rebuild
2125
+ // the marker closures, wire them against the adopted nodes. The page never
2126
+ // re-renders visibly, no hydration payload, no second request beyond the POST.
2127
+ export async function adopt(container, html, stateJson) {
2128
+ resetEffects();
2129
+ clearRequestState();
2130
+ clearMounts(); // stale mounts from a failed render never fire
2131
+ resumeState(stateJson);
2132
+ container.innerHTML = html;
2133
+ // keep the embedded state in sync so a later SPA-fallback check agrees
2134
+ const st = document.getElementById('__rosetack_state');
2135
+ if (st) st.textContent = stateJson;
2136
+ for (const route of routes) {
2137
+ if (matchRoute(route.pattern, location.pathname)) {
2138
+ await applyParams(route, location.pathname);
2139
+ const closes = [];
2140
+ try {
2141
+ const render = await getRender(route); // split mode: loads the route's chunk here
2142
+ await render(closes, '');
2143
+ } catch {
2144
+ // the adopted response's route is broken (e.g. the action's page
2145
+ // throws): keep the swapped DOM but skip wiring it
2146
+ return;
2147
+ }
2148
+ wire(container, closes);
2149
+ bindEvents(container);
2150
+ flushMounts();
2151
+ return;
2152
+ }
2153
+ }
2154
+ }
2155
+ // === refresh() implementation ===
2156
+ // Re-render the current route in place: the client half of router.refresh()
2157
+ // (a router refresh) / (a full invalidation). Same machinery as a client-side
2158
+ // navigation to the current path - $data re-runs, state re-seeds from the
2159
+ // fresh render, wire() patches the marked nodes - but a refresh never lands
2160
+ // a prefetch entry: a hover from a minute ago is exactly what it exists to
2161
+ // bypass. Zero requests: the render (and its $data) runs in the page.
2162
+ // Trade-off: state resets like navigation (no per-key retention); add
2163
+ // retention when an app needs refresh-without-losing-input.
2164
+ setRefreshHook(async () => {
2165
+ prefetchCache.delete(location.pathname);
2166
+ await start(document.getElementById('app'), location.pathname, false);
2167
+ });
2168
+ `;
2169
+ await fs.promises.writeFile(path.join(buildDir, "client-entry.js"), clientEntry);
2170
+ if (split) {
2171
+ await fs.promises.rm(path.join(outDir, "chunks"), { recursive: true, force: true });
2172
+ await esbuild.build({
2173
+ entryPoints: [path.join(buildDir, "client-entry.js")],
2174
+ bundle: true,
2175
+ format: "esm",
2176
+ platform: "browser",
2177
+ minify: true,
2178
+ splitting: true,
2179
+ outdir: outDir,
2180
+ entryNames: "client",
2181
+ chunkNames: "chunks/[name]-[hash]",
2182
+ write: true,
2183
+ ...TS_LOADER
2184
+ });
2185
+ } else {
2186
+ await esbuild.build({
2187
+ entryPoints: [path.join(buildDir, "client-entry.js")],
2188
+ bundle: true,
2189
+ outfile: path.join(outDir, "client.js"),
2190
+ format: "esm",
2191
+ platform: "browser",
2192
+ minify: true,
2193
+ write: true,
2194
+ ...TS_LOADER
2195
+ });
2196
+ }
2197
+ await fs.promises.rm(buildDir, { recursive: true, force: true });
2198
+ const publicDir = path.join(root, "public");
2199
+ if (fs.existsSync(publicDir)) {
2200
+ const outPublic = path.join(outDir, "public");
2201
+ await fs.promises.mkdir(outPublic, { recursive: true });
2202
+ const assets = await fs.promises.readdir(publicDir);
2203
+ await Promise.all(
2204
+ assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
2205
+ );
2206
+ }
2207
+ console.log("rosetack zero-JS report:");
2208
+ for (const line of buildReport(infos, compiled)) console.log(" " + line);
2209
+ for (const { info, i } of pages) {
2210
+ if (!routeShipsNoJs(infos, compiled, i)) continue;
2211
+ for (const ci of [i, ...layoutsOf(infos, i)]) {
2212
+ for (const w of compiled[ci].jsWarnings ?? []) {
2213
+ console.warn(`rosetack warning: ${info.routePath} ships zero JavaScript but ${path.basename(infos[ci].filePath)} contains ${w}`);
2214
+ }
2215
+ }
2216
+ }
2217
+ return { routes: pages.map(({ info }) => info), bundle: bundleMode };
2218
+ }
2219
+ async function scanRoseFiles(root) {
2220
+ const pagesDir = path.join(root, "src", "pages");
2221
+ if (!fs.existsSync(pagesDir)) return [];
2222
+ async function scan(dir) {
2223
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
2224
+ const files = [];
2225
+ for (const entry of entries) {
2226
+ const full = path.join(dir, entry.name);
2227
+ if (entry.isDirectory()) files.push(...await scan(full));
2228
+ else if (entry.name.endsWith(".rose")) files.push(full);
2229
+ }
2230
+ return files;
2231
+ }
2232
+ return scan(pagesDir);
2233
+ }
2234
+ async function scanComponentFiles(root) {
2235
+ const compDir = path.join(root, "src", "components");
2236
+ if (!fs.existsSync(compDir)) return [];
2237
+ async function scan(dir) {
2238
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
2239
+ const files = [];
2240
+ for (const entry of entries) {
2241
+ const full = path.join(dir, entry.name);
2242
+ if (entry.isDirectory()) files.push(...await scan(full));
2243
+ else if (entry.name.endsWith(".rose")) files.push(full);
2244
+ }
2245
+ return files;
2246
+ }
2247
+ return scan(compDir);
2248
+ }
2249
+ function isAncestorDir(layoutPath, pagePath) {
2250
+ const layoutDir = path.dirname(layoutPath);
2251
+ const pageDir = path.dirname(pagePath);
2252
+ return pageDir === layoutDir || pageDir.startsWith(layoutDir + path.sep);
2253
+ }
2254
+ function getRouteInfo(filePath, root) {
2255
+ const pagesDir = path.join(root, "src", "pages");
2256
+ const relative3 = path.relative(pagesDir, filePath).replace(/\\/g, "/");
2257
+ const withoutExt = relative3.replace(/\.rose$/, "");
2258
+ const base = path.posix.basename(withoutExt);
2259
+ const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
2260
+ const isLayout = !isComponent && base === "_layout";
2261
+ const isNotFound = !isComponent && base === "404";
2262
+ const isError = !isComponent && base === "500";
2263
+ const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
2264
+ const isMiddleware = !isComponent && withoutExt === "_middleware";
2265
+ let parts = withoutExt.split("/").filter((p) => p !== "_layout");
2266
+ if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
2267
+ const routeParts = parts.map(
2268
+ (part) => part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part
2269
+ );
2270
+ let routePath;
2271
+ if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
2272
+ routePath = "/";
2273
+ } else {
2274
+ routePath = "/" + routeParts.join("/");
2275
+ }
2276
+ return {
2277
+ filePath,
2278
+ routePath,
2279
+ pattern: routePath,
2280
+ paramNames: parts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.slice(1, -1)),
2281
+ isLayout,
2282
+ isNotFound,
2283
+ isError,
2284
+ isApi,
2285
+ isMiddleware,
2286
+ isComponent
2287
+ };
2288
+ }
2289
+ function capitalize(s) {
2290
+ return s.charAt(0).toUpperCase() + s.slice(1);
2291
+ }
2292
+
2293
+ // src/cli/shell.ts
2294
+ import * as fs2 from "fs";
2295
+ import * as path2 from "path";
2296
+ import * as esbuild2 from "esbuild";
2297
+ var OUT_DIR = path2.join(process.cwd(), "dist");
2298
+ var styleCache = null;
2299
+ function getStyles() {
2300
+ const file = path2.join(OUT_DIR, "styles.css");
2301
+ try {
2302
+ const st = fs2.statSync(file);
2303
+ if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
2304
+ styleCache = { mtimeMs: st.mtimeMs, source: fs2.readFileSync(file, "utf-8") };
2305
+ }
2306
+ return styleCache.source;
2307
+ } catch {
2308
+ return "";
2309
+ }
2310
+ }
2311
+ var BOOTSTRAP = esbuild2.transformSync(`
2312
+ const __app = document.getElementById('app');
2313
+ // Native View Transitions around client-side navigation (progressive:
2314
+ // browsers without the API navigate normally, no polyfill, no CSS required).
2315
+ function __navigate(pathname) {
2316
+ const paint = () => start(__app, pathname);
2317
+ if (document.startViewTransition) {
2318
+ return document.startViewTransition(paint).updateCallbackDone;
2319
+ }
2320
+ return paint();
2321
+ }
2322
+ window.addEventListener('popstate', () => __navigate(window.location.pathname));
2323
+ document.addEventListener('click', (e) => {
2324
+ const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
2325
+ if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
2326
+ e.preventDefault();
2327
+ history.pushState(null, '', a.getAttribute('href'));
2328
+ __navigate(window.location.pathname);
2329
+ }
2330
+ });
2331
+ // Prefetch the target route's full render (including $data) on hover, keyboard
2332
+ // focus, or touch - the click that follows paints from cache: no await, no
2333
+ // request. Other frameworks prefetch data only; rosetack prefetches the render
2334
+ // because the inlined bundle already contains every route.
2335
+ function __prefetchHandler(e) {
2336
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
2337
+ if (a && prefetch) prefetch(a.getAttribute('href'), 'hover');
2338
+ }
2339
+ document.addEventListener('mouseover', __prefetchHandler);
2340
+ document.addEventListener('focusin', __prefetchHandler);
2341
+ document.addEventListener('touchstart', __prefetchHandler, { passive: true });
2342
+ // Viewport + idle prefetch (viewport-triggered): once a link scrolls into view and the
2343
+ // browser is idle, its route renders ahead of any interaction. trade-off: both
2344
+ // APIs are feature-detected; without them the hover/focus/touch path above
2345
+ // still covers every link.
2346
+ if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
2347
+ const io = new IntersectionObserver((entries) => {
2348
+ for (const e of entries) {
2349
+ if (!e.isIntersecting) continue;
2350
+ io.unobserve(e.target); // one-shot per element; fresh links re-observe after nav
2351
+ requestIdleCallback(() => prefetch(e.target.getAttribute('href'), 'viewport'));
2352
+ }
2353
+ });
2354
+ // observing an already-observed element is a no-op, so re-sweeping is cheap
2355
+ const observeLinks = () => {
2356
+ for (const a of document.querySelectorAll('a[href^="/"]')) io.observe(a);
2357
+ };
2358
+ observeLinks();
2359
+ // navigation swaps the container's innerHTML: re-observe the fresh links
2360
+ const __rawNav = __navigate;
2361
+ __navigate = (p) => __rawNav(p).then(observeLinks, () => {});
2362
+ }
2363
+ // Progressive-enhancement forms: <form method="POST"> backed by a server
2364
+ // action. With JS the submit is intercepted and handed to postForm (one
2365
+ // request, in-place adopt). Without JS the browser performs the native POST
2366
+ // and the server re-renders the page: the same form works with JavaScript
2367
+ // disabled, which Server Actions in other frameworks do not.
2368
+ document.addEventListener('submit', (e) => {
2369
+ const f = e.target;
2370
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
2371
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
2372
+ e.preventDefault();
2373
+ postForm(new FormData(f));
2374
+ });
2375
+ // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
2376
+ // If the document was rendered for a DIFFERENT route (a static-file server's
2377
+ // SPA fallback serves index.html for unknown paths), adopt nothing - let the
2378
+ // client router render the requested route from scratch.
2379
+ const __st = document.getElementById('__rosetack_state');
2380
+ const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
2381
+ if (__state.__route === window.location.pathname) {
2382
+ start(__app, window.location.pathname, true);
2383
+ } else {
2384
+ start(__app, window.location.pathname);
2385
+ }
2386
+ `, { minify: true }).code;
2387
+ var EXTERNAL_BOOTSTRAP = `
2388
+ import { start, prefetch, postForm } from '/client.js';
2389
+ ${BOOTSTRAP}`;
2390
+ function inlineScript(client) {
2391
+ return `
2392
+ ${client}
2393
+ ${BOOTSTRAP}`;
2394
+ }
2395
+ 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==">';
2396
+ var STYLES = `
2397
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
2398
+ button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
2399
+ a { color: #e91e63; text-decoration: none; font-weight: bold; }
2400
+ a:hover { text-decoration: underline; }
2401
+ nav a { margin-right: 1rem; }
2402
+ .rh { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; border-bottom: 2px solid #e91e63; margin-bottom: 1.5rem; padding-bottom: 0.75rem; }
2403
+ .rb { font-size: 1.6rem; }
2404
+ .rbrand { display: inline-flex; align-items: center; gap: 0.5em; }
2405
+ .rlogo { height: 1em; width: 1em; vertical-align: -0.08em; margin-right: 0.2em; }
2406
+ @media (max-width: 640px) {
2407
+ .rh { flex-direction: column; align-items: flex-start; gap: 0.75rem; }
2408
+ nav a:last-child { margin-right: 0; }
2409
+ }
2410
+ .rn { display: inline-block; margin-left: 1.5rem; }
2411
+ .rf { margin-top: 2rem; color: #888; font-size: 0.85rem; }
2412
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
2413
+ `;
2414
+ var STYLES_MIN = STYLES.replace(
2415
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
2416
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
2417
+ ).trim();
2418
+ function mergeHeadBlocks(blocks) {
2419
+ const byKey = /* @__PURE__ */ new Map();
2420
+ const order = [];
2421
+ const put = (key, html) => {
2422
+ if (!byKey.has(key)) {
2423
+ byKey.set(key, html);
2424
+ order.push(key);
2425
+ }
2426
+ };
2427
+ for (const block of blocks) {
2428
+ for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
2429
+ for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
2430
+ const tag = m[1].toLowerCase();
2431
+ const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
2432
+ const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
2433
+ const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
2434
+ put(key, marked);
2435
+ }
2436
+ }
2437
+ return order.map((k) => byKey.get(k)).join("\n ");
2438
+ }
2439
+ function clientScriptTag(client, nonce = "") {
2440
+ const n = nonce ? ` nonce="${nonce}"` : "";
2441
+ return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
2442
+ <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
2443
+ }
2444
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
2445
+ const clientTag = clientScriptTag(client, nonce);
2446
+ const mergedHead = mergeHeadBlocks(head);
2447
+ const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
2448
+ const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
2449
+ ${FAVICON}`;
2450
+ const headTags = mergedHead ? `
2451
+ ${mergedHead}` : "";
2452
+ const styleTag = styles ? `
2453
+ <style>${styles}</style>` : "";
2454
+ const jsTail = js ? `
2455
+ <script type="application/json" id="__rosetack_state">${stateJson}</script>
2456
+ ${clientTag}` : "";
2457
+ return `<!DOCTYPE html>
2458
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
2459
+ <head>
2460
+ <meta charset="UTF-8">
2461
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
2462
+ ${titleTag}
2463
+ <style>${STYLES_MIN}</style>${styleTag}
2464
+ </head>
2465
+ <body>
2466
+ <div id="app">${ssrHtml}</div>${jsTail}
2467
+ </body>
2468
+ </html>`;
2469
+ }
2470
+
2471
+ // src/cli/test.ts
2472
+ var GRAFTED = ["document", "Node", "NodeFilter", "FormData", "DOMParser", "location", "fetch", "Event", "CustomEvent", "MutationObserver", "requestAnimationFrame"];
2473
+ function projectRootOf(file) {
2474
+ let dir = path3.dirname(path3.resolve(file));
2475
+ for (; ; ) {
2476
+ if (fs3.existsSync(path3.join(dir, "src", "pages"))) return dir;
2477
+ const parent = path3.dirname(dir);
2478
+ if (parent === dir) throw new Error(`rosetack/test: ${file} is not inside a project (no src/pages found above it)`);
2479
+ dir = parent;
2480
+ }
2481
+ }
2482
+ function routeOf(file, root) {
2483
+ const rel = path3.relative(path3.join(root, "src", "pages"), path3.resolve(file)).replace(/\\/g, "/").replace(/\.rose$/, "");
2484
+ if (rel === "index") return "/";
2485
+ const segs = rel.split("/").map((s) => s.startsWith("[") && s.endsWith("]") ? `:${s.slice(1, -1)}` : s);
2486
+ return "/" + segs.join("/");
2487
+ }
2488
+ function copyTree(from, to) {
2489
+ fs3.mkdirSync(to, { recursive: true });
2490
+ for (const e of fs3.readdirSync(from, { withFileTypes: true })) {
2491
+ const src = path3.join(from, e.name);
2492
+ const dst = path3.join(to, e.name);
2493
+ if (e.isDirectory()) copyTree(src, dst);
2494
+ else fs3.copyFileSync(src, dst);
2495
+ }
2496
+ }
2497
+ function propAttrs(props) {
2498
+ return Object.entries(props).map(([k, v]) => `${k}={${JSON.stringify(v) ?? "undefined"}}`).join(" ");
2499
+ }
2500
+ async function test(file, opts = {}) {
2501
+ const target = path3.resolve(file);
2502
+ if (!fs3.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
2503
+ const root = projectRootOf(target);
2504
+ const rel = path3.relative(root, target).replace(/\\/g, "/");
2505
+ const isComponent = rel.startsWith("src/components/");
2506
+ const dir = opts.dir ?? fs3.mkdtempSync(path3.join(os.tmpdir(), "rosetack-test-"));
2507
+ for (const item of ["src", "public"]) {
2508
+ const from = path3.join(root, item);
2509
+ if (fs3.existsSync(from)) copyTree(from, path3.join(dir, item));
2510
+ }
2511
+ for (const item of ["rosetack.config.js"]) {
2512
+ const from = path3.join(root, item);
2513
+ if (fs3.existsSync(from)) fs3.copyFileSync(from, path3.join(dir, item));
2514
+ }
2515
+ let route;
2516
+ if (isComponent) {
2517
+ const specifier = path3.relative(path3.join(dir, "src", "pages"), path3.join(dir, rel)).replace(/\\/g, "/");
2518
+ const attrs = propAttrs(opts.props ?? {});
2519
+ const page = `<script>
2520
+ import Target from '${specifier}';
2521
+ </script>
2522
+
2523
+ <template>
2524
+ <Target ${attrs} />
2525
+ </template>
2526
+ `;
2527
+ fs3.writeFileSync(path3.join(dir, "src", "pages", "__rosetack_test.rose"), page);
2528
+ route = "/__rosetack_test";
2529
+ } else {
2530
+ route = opts.route ?? routeOf(target, root);
2531
+ }
2532
+ const outDir = path3.join(dir, "dist");
2533
+ await buildProject(dir, outDir);
2534
+ const serverUrl = pathToFileURL2(path3.join(outDir, "server.js")).href;
2535
+ const clientUrl = pathToFileURL2(path3.join(outDir, "client.js")).href;
2536
+ const mod = await import(serverUrl);
2537
+ const clientSource = fs3.readFileSync(path3.join(outDir, "client.js"), "utf-8");
2538
+ let styles = "";
2539
+ try {
2540
+ styles = fs3.readFileSync(path3.join(outDir, "styles.css"), "utf-8");
2541
+ } catch {
2542
+ }
2543
+ if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
2544
+ if (!opts.dir && !opts.keep) {
2545
+ process.once("exit", () => {
2546
+ try {
2547
+ fs3.rmSync(dir, { recursive: true, force: true });
2548
+ } catch {
2549
+ }
2550
+ });
2551
+ }
2552
+ const result = (page, redirect) => ({
2553
+ status: page.status ?? 200,
2554
+ html: page.html,
2555
+ state: page.state ? JSON.parse(page.state) : {},
2556
+ head: page.head ?? [],
2557
+ csr: page.csr,
2558
+ lang: page.lang ?? "en",
2559
+ dir: page.dir ?? "",
2560
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? ""),
2561
+ redirect
2562
+ });
2563
+ const toRequest = (pathname, req = {}, body) => {
2564
+ const headers = new Headers(req.headers ?? {});
2565
+ for (const [k, v] of Object.entries(req.cookies ?? {})) headers.append("cookie", `${k}=${v}`);
2566
+ return new Request(`http://localhost${pathname}`, { method: body ? "POST" : "GET", headers, body });
2567
+ };
2568
+ const request = async (pathname, req, body) => {
2569
+ if (mod.middleware) {
2570
+ const mw = await mod.runMiddleware(toRequest(pathname, req, body), body);
2571
+ if (mw) return { status: mw.status, html: await mw.text(), state: {}, head: [], lang: "en", dir: "", document: await mw.text(), redirect: mw.headers.get("location") ?? void 0 };
2572
+ }
2573
+ const page = await mod.renderPage(pathname, body);
2574
+ return result(page);
2575
+ };
2576
+ let requests = 0;
2577
+ let currentRoute = route;
2578
+ const mount = async (req = {}) => {
2579
+ const win = opts.dom?.window ?? opts.dom ?? globalThis;
2580
+ if (!win?.document || !win?.DOMParser) {
2581
+ throw new Error('rosetack/test: mount() needs a DOM. Pass one - test("src/components/Counter.rose", { dom: new JSDOM() }) - or run under a jsdom environment.');
2582
+ }
2583
+ const page = await request(route, req);
2584
+ const doc = win.document;
2585
+ const app = doc.getElementById("app") ?? doc.body;
2586
+ let stateEl = doc.getElementById("__rosetack_state");
2587
+ if (!stateEl) {
2588
+ stateEl = doc.createElement("script");
2589
+ stateEl.id = "__rosetack_state";
2590
+ doc.body.appendChild(stateEl);
2591
+ }
2592
+ stateEl.textContent = page.state;
2593
+ app.innerHTML = page.html;
2594
+ const saved = /* @__PURE__ */ new Map();
2595
+ for (const key of GRAFTED) {
2596
+ saved.set(key, globalThis[key]);
2597
+ globalThis[key] = win[key] ?? globalThis[key];
2598
+ }
2599
+ globalThis.location = { pathname: currentRoute, href: `http://localhost${currentRoute}` };
2600
+ globalThis.fetch = async (url, init) => {
2601
+ const pathname = String(url).startsWith("http") ? new URL(String(url)).pathname : String(url);
2602
+ if (pathname.startsWith("/locales/") && pathname.endsWith(".json")) {
2603
+ const file2 = path3.join(outDir, pathname.slice(1));
2604
+ if (!fs3.existsSync(file2)) return { ok: false, json: async () => ({}) };
2605
+ return { ok: true, json: async () => JSON.parse(fs3.readFileSync(file2, "utf-8")) };
2606
+ }
2607
+ requests++;
2608
+ const next = await request(pathname, req, init?.body);
2609
+ return { ok: next.status < 400, status: next.status, text: async () => next.document };
2610
+ };
2611
+ const client = await import(clientUrl);
2612
+ await client.start(app, route, true);
2613
+ const one = (sel) => sel ? doc.querySelector(sel) : app;
2614
+ const handle = {
2615
+ route,
2616
+ document: doc,
2617
+ window: win,
2618
+ text: (sel) => one(sel)?.textContent ?? "",
2619
+ html: (sel) => one(sel)?.outerHTML ?? null,
2620
+ exists: (sel) => !!doc.querySelector(sel),
2621
+ click: async (sel) => {
2622
+ const el = doc.querySelector(sel);
2623
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
2624
+ el.dispatchEvent(new win.MouseEvent("click", { bubbles: true, cancelable: true }));
2625
+ await new Promise((r) => setTimeout(r, 0));
2626
+ },
2627
+ fill: (sel, value) => {
2628
+ const el = doc.querySelector(sel);
2629
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
2630
+ el.value = value;
2631
+ },
2632
+ submit: async (formSel = "form", fields) => {
2633
+ const form = doc.querySelector(formSel);
2634
+ if (!form) throw new Error(`rosetack/test: no form matches ${formSel}`);
2635
+ const body = new win.FormData(form);
2636
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
2637
+ await client.postForm(body);
2638
+ },
2639
+ action: async (name, fields) => {
2640
+ const body = new win.FormData();
2641
+ body.append("__action", name);
2642
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
2643
+ await client.postForm(body);
2644
+ },
2645
+ navigate: async (pathname) => {
2646
+ currentRoute = pathname;
2647
+ globalThis.location = { pathname, href: `http://localhost${pathname}` };
2648
+ await client.start(app, pathname, false);
2649
+ },
2650
+ state: () => {
2651
+ const el = doc.getElementById("__rosetack_state");
2652
+ return el?.textContent ? JSON.parse(el.textContent) : {};
2653
+ },
2654
+ requestCount: () => requests
2655
+ };
2656
+ handle.restore = () => {
2657
+ for (const [k, v] of saved) globalThis[k] = v;
2658
+ };
2659
+ return handle;
2660
+ };
2661
+ return {
2662
+ route,
2663
+ dir,
2664
+ get: async (pathname = route, req) => request(pathname, req ?? {}),
2665
+ post: async (fields, req = {}) => {
2666
+ const pathname = req.route ?? route;
2667
+ const body = new FormData();
2668
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
2669
+ return request(pathname, req, body);
2670
+ },
2671
+ api: async (method, pathname, req = {}) => {
2672
+ if (mod.middleware) {
2673
+ const mw = await mod.runMiddleware(toRequest(pathname, req));
2674
+ if (mw) return { status: mw.status, body: await mw.text(), headers: { location: mw.headers.get("location") ?? "" } };
2675
+ }
2676
+ const res = await mod.handleApi(method, pathname, toRequest(pathname, req));
2677
+ const text = await res.text();
2678
+ let body = text;
2679
+ try {
2680
+ body = JSON.parse(text);
2681
+ } catch {
2682
+ }
2683
+ const headers = {};
2684
+ res.headers.forEach((v, k) => {
2685
+ headers[k] = v;
2686
+ });
2687
+ return { status: res.status, body, headers };
2688
+ },
2689
+ mount
2690
+ };
2691
+ }
2692
+ var test_default = test;
2693
+ export {
2694
+ test_default as default,
2695
+ test
2696
+ };