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