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