rosetack 0.1.1 → 0.1.3
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/cloudflare/functions/[[path]].ts +61 -0
- package/deploy/cloudflare/wrangler.toml +14 -0
- package/deploy/k8s/rosetack.yaml +107 -0
- package/deploy/netlify/functions/rosetack.ts +38 -0
- package/deploy/netlify.toml +17 -0
- package/devtools/devtools.html +7 -0
- package/devtools/devtools.js +1 -0
- package/devtools/manifest.json +8 -0
- package/devtools/panel.html +28 -0
- package/devtools/panel.js +54 -0
- package/dist-cli/compiler.mjs +1346 -492
- package/dist-cli/edge.mjs +152 -41
- package/dist-cli/rosetack.mjs +1974 -606
- package/dist-cli/runtime.mjs +205 -40
- package/dist-cli/test.mjs +1425 -508
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/edge.ts +76 -61
- package/src/cli/index.ts +516 -293
- package/src/cli/prompt.ts +130 -0
- package/src/cli/shell.ts +113 -65
- package/src/cli/test.ts +9 -70
- package/src/compiler/errors.ts +74 -0
- package/src/compiler/index.ts +1514 -839
- package/src/runtime/index.ts +255 -150
- package/src/types/rosetack.d.ts +18 -59
- package/templates/admin/package.json +14 -0
- package/templates/admin/rosetack.config.js +1 -0
- package/templates/admin/src/pages/_middleware.rose +33 -0
- package/templates/admin/src/pages/api/items.rose +37 -0
- package/templates/admin/src/pages/api/login.rose +25 -0
- package/templates/admin/src/pages/index.rose +79 -0
- package/templates/api/package.json +14 -0
- package/templates/api/rosetack.config.js +1 -0
- package/templates/api/src/pages/api/health.rose +7 -0
- package/templates/api/src/pages/api/items.rose +46 -0
- package/templates/api/src/pages/api/login.rose +24 -0
- package/templates/api/src/pages/index.rose +25 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/rosetack.config.js +1 -0
- package/templates/blog/src/pages/404.rose +2 -0
- package/templates/blog/src/pages/_layout.rose +42 -0
- package/templates/blog/src/pages/_middleware.rose +74 -0
- package/templates/blog/src/pages/admin.rose +85 -0
- package/templates/blog/src/pages/api/login.rose +46 -0
- package/templates/blog/src/pages/api/posts/[id].rose +37 -0
- package/templates/blog/src/pages/api/posts.rose +72 -0
- package/templates/blog/src/pages/index.rose +31 -0
- package/templates/blog/src/pages/post/[id].rose +36 -0
- package/templates/site/package.json +14 -0
- package/templates/site/rosetack.config.js +1 -0
- package/templates/site/src/pages/404.rose +2 -0
- package/templates/site/src/pages/_layout.rose +40 -0
- package/templates/site/src/pages/about.rose +6 -0
- package/templates/site/src/pages/index.rose +13 -0
- package/templates/site/src/pages/pricing.rose +8 -0
package/dist-cli/rosetack.mjs
CHANGED
|
@@ -12,6 +12,47 @@ import * as fs from "fs";
|
|
|
12
12
|
import * as path from "path";
|
|
13
13
|
import { pathToFileURL, fileURLToPath } from "url";
|
|
14
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
|
|
15
56
|
var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
16
57
|
var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
17
58
|
var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
@@ -19,12 +60,11 @@ var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
|
19
60
|
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
20
61
|
var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
21
62
|
var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
22
|
-
var EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
|
|
23
63
|
var SLOT_RE = /<slot\s*\/?>/g;
|
|
24
64
|
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)\/?>/g;
|
|
25
65
|
function encodeSlotCall(attrs) {
|
|
26
66
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
|
|
27
|
-
if (!name) throw new
|
|
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} />' });
|
|
28
68
|
const pairs = [...attrs.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter((m) => m[1] !== "name").map((m) => `['${m[1]}', (${m[2].trim()})]`);
|
|
29
69
|
return `${JSON.stringify(name)}, [${pairs.join(", ")}]`;
|
|
30
70
|
}
|
|
@@ -111,7 +151,306 @@ function callifyStateReads(script, names) {
|
|
|
111
151
|
}
|
|
112
152
|
function callifyTemplateExprs(template, names) {
|
|
113
153
|
if (names.length === 0) return template;
|
|
114
|
-
|
|
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 skipLiteral(src, i) {
|
|
229
|
+
const q = src[i];
|
|
230
|
+
if (q === '"' || q === "'") return skipQuoted(src, i);
|
|
231
|
+
if (q === "`") return skipTemplate(src, i);
|
|
232
|
+
if (q !== "/") return null;
|
|
233
|
+
if (src[i + 1] === "/" || src[i + 1] === "*") return null;
|
|
234
|
+
let b = i - 1;
|
|
235
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
236
|
+
if (b >= 0) {
|
|
237
|
+
if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
|
|
238
|
+
const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
|
|
239
|
+
if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
let j = i + 1;
|
|
243
|
+
let inClass = false;
|
|
244
|
+
while (j < src.length) {
|
|
245
|
+
const c = src[j];
|
|
246
|
+
if (c === "\\") {
|
|
247
|
+
j += 2;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (c === "\n") return null;
|
|
251
|
+
if (inClass) {
|
|
252
|
+
if (c === "]") inClass = false;
|
|
253
|
+
} else if (c === "[") inClass = true;
|
|
254
|
+
else if (c === "/") {
|
|
255
|
+
j++;
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
j++;
|
|
259
|
+
}
|
|
260
|
+
if (j > src.length) return null;
|
|
261
|
+
while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
|
|
262
|
+
return j;
|
|
263
|
+
}
|
|
264
|
+
function stripComments(src) {
|
|
265
|
+
let out = "";
|
|
266
|
+
let i = 0;
|
|
267
|
+
while (i < src.length) {
|
|
268
|
+
const lit = skipLiteral(src, i);
|
|
269
|
+
if (lit !== null) {
|
|
270
|
+
out += src.slice(i, lit);
|
|
271
|
+
i = lit;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (src.startsWith("//", i)) {
|
|
275
|
+
while (i < src.length && src[i] !== "\n") i++;
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (src.startsWith("/*", i)) {
|
|
279
|
+
i += 2;
|
|
280
|
+
while (i < src.length && !src.startsWith("*/", i)) i++;
|
|
281
|
+
i = Math.min(i + 2, src.length);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (src.startsWith("<!--", i)) {
|
|
285
|
+
i += 4;
|
|
286
|
+
while (i < src.length && !src.startsWith("-->", i)) i++;
|
|
287
|
+
i = Math.min(i + 3, src.length);
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
out += src[i++];
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
function stripGuardedBranches(src) {
|
|
295
|
+
const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
|
|
296
|
+
const ws = (i2) => {
|
|
297
|
+
while (i2 < src.length && /\s/.test(src[i2])) i2++;
|
|
298
|
+
return i2;
|
|
299
|
+
};
|
|
300
|
+
const ternaryColon = (q) => {
|
|
301
|
+
let depth = 0;
|
|
302
|
+
let i2 = q + 1;
|
|
303
|
+
while (i2 < src.length) {
|
|
304
|
+
const c = src[i2];
|
|
305
|
+
const lit = skipLiteral(src, i2);
|
|
306
|
+
if (lit !== null) {
|
|
307
|
+
i2 = lit;
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
311
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
312
|
+
depth--;
|
|
313
|
+
if (depth < 0) return -1;
|
|
314
|
+
} else if (depth === 0 && c === ":") return i2;
|
|
315
|
+
else if (depth === 0 && c === "?") {
|
|
316
|
+
const inner = ternaryColon(i2);
|
|
317
|
+
if (inner < 0) return -1;
|
|
318
|
+
i2 = inner + 1;
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
i2++;
|
|
322
|
+
}
|
|
323
|
+
return -1;
|
|
324
|
+
};
|
|
325
|
+
const exprEnd = (i2) => {
|
|
326
|
+
let depth = 0;
|
|
327
|
+
while (i2 < src.length) {
|
|
328
|
+
const c = src[i2];
|
|
329
|
+
const lit = skipLiteral(src, i2);
|
|
330
|
+
if (lit !== null) {
|
|
331
|
+
i2 = lit;
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
335
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
336
|
+
if (depth === 0) return i2;
|
|
337
|
+
depth--;
|
|
338
|
+
} else if (depth === 0 && (c === "," || c === ";")) return i2;
|
|
339
|
+
else if (depth === 0 && c === "?") {
|
|
340
|
+
const inner = ternaryColon(i2);
|
|
341
|
+
if (inner < 0) return src.length;
|
|
342
|
+
i2 = inner + 1;
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
i2++;
|
|
346
|
+
}
|
|
347
|
+
return src.length;
|
|
348
|
+
};
|
|
349
|
+
const braceEnd = (b) => {
|
|
350
|
+
let depth = 0;
|
|
351
|
+
let i2 = b;
|
|
352
|
+
while (i2 < src.length) {
|
|
353
|
+
const c = src[i2];
|
|
354
|
+
const lit = skipLiteral(src, i2);
|
|
355
|
+
if (lit !== null) {
|
|
356
|
+
i2 = lit;
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (c === "{") depth++;
|
|
360
|
+
else if (c === "}") {
|
|
361
|
+
depth--;
|
|
362
|
+
if (depth === 0) return i2;
|
|
363
|
+
}
|
|
364
|
+
i2++;
|
|
365
|
+
}
|
|
366
|
+
return src.length;
|
|
367
|
+
};
|
|
368
|
+
const stmtEnd = (i2) => {
|
|
369
|
+
let depth = 0;
|
|
370
|
+
while (i2 < src.length) {
|
|
371
|
+
const c = src[i2];
|
|
372
|
+
const lit = skipLiteral(src, i2);
|
|
373
|
+
if (lit !== null) {
|
|
374
|
+
i2 = lit;
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
378
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
379
|
+
if (depth === 0) return i2;
|
|
380
|
+
depth--;
|
|
381
|
+
} else if (depth === 0 && (c === ";" || c === "\n")) return i2;
|
|
382
|
+
i2++;
|
|
383
|
+
}
|
|
384
|
+
return src.length;
|
|
385
|
+
};
|
|
386
|
+
const isIfGuard = (src2, at) => {
|
|
387
|
+
let b = at - 1;
|
|
388
|
+
while (b >= 0 && /\s/.test(src2[b])) b--;
|
|
389
|
+
if (b < 0 || src2[b] !== "(") return false;
|
|
390
|
+
b--;
|
|
391
|
+
while (b >= 0 && /\s/.test(src2[b])) b--;
|
|
392
|
+
return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
|
|
393
|
+
};
|
|
394
|
+
const blanks = [];
|
|
395
|
+
let i = 0;
|
|
396
|
+
while (i < src.length) {
|
|
397
|
+
const lit = skipLiteral(src, i);
|
|
398
|
+
if (lit !== null) {
|
|
399
|
+
i = lit;
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
GUARD.lastIndex = i;
|
|
403
|
+
const m = GUARD.exec(src);
|
|
404
|
+
if (!m) {
|
|
405
|
+
i++;
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
const browserAfter = m[1] === "!==";
|
|
409
|
+
const j = ws(i + m[0].length);
|
|
410
|
+
const two = src.slice(j, j + 2);
|
|
411
|
+
if (two === "&&" && browserAfter) {
|
|
412
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
413
|
+
} else if (two === "||" && !browserAfter) {
|
|
414
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
415
|
+
} else if (src[j] === "?") {
|
|
416
|
+
const colon = ternaryColon(j);
|
|
417
|
+
if (colon < 0) {
|
|
418
|
+
if (browserAfter) blanks.push([j + 1, src.length]);
|
|
419
|
+
} else if (browserAfter) {
|
|
420
|
+
blanks.push([j + 1, colon]);
|
|
421
|
+
} else {
|
|
422
|
+
blanks.push([colon + 1, exprEnd(colon + 1)]);
|
|
423
|
+
}
|
|
424
|
+
} else if (src[j] === ")" && isIfGuard(src, i)) {
|
|
425
|
+
let bodyEnd;
|
|
426
|
+
const k = ws(j + 1);
|
|
427
|
+
if (src[k] === "{") {
|
|
428
|
+
bodyEnd = braceEnd(k);
|
|
429
|
+
if (browserAfter) blanks.push([k + 1, bodyEnd]);
|
|
430
|
+
} else {
|
|
431
|
+
bodyEnd = stmtEnd(k);
|
|
432
|
+
if (browserAfter) blanks.push([k, bodyEnd]);
|
|
433
|
+
}
|
|
434
|
+
const after = ws(bodyEnd + 1);
|
|
435
|
+
if (src.startsWith("else", after)) {
|
|
436
|
+
const e = ws(after + 4);
|
|
437
|
+
if (src[e] === "{") {
|
|
438
|
+
const close = braceEnd(e);
|
|
439
|
+
if (!browserAfter) blanks.push([e + 1, close]);
|
|
440
|
+
} else {
|
|
441
|
+
const stop = stmtEnd(e);
|
|
442
|
+
if (!browserAfter) blanks.push([e, stop]);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
i = j;
|
|
447
|
+
}
|
|
448
|
+
if (blanks.length === 0) return src;
|
|
449
|
+
const out = [...src];
|
|
450
|
+
for (const [a, b] of blanks) {
|
|
451
|
+
for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
|
|
452
|
+
}
|
|
453
|
+
return out.join("");
|
|
115
454
|
}
|
|
116
455
|
function scriptOf(source) {
|
|
117
456
|
return source.match(COMPONENT_RE)?.[1] ?? null;
|
|
@@ -130,21 +469,29 @@ async function loadPlugins(root) {
|
|
|
130
469
|
}
|
|
131
470
|
function resolveRoseImports(script, fromFile, registry) {
|
|
132
471
|
const imports = [];
|
|
133
|
-
const resolve3 = (spec) => {
|
|
472
|
+
const resolve3 = (spec, at) => {
|
|
134
473
|
const abs = path.resolve(path.dirname(fromFile), spec);
|
|
135
474
|
const hit = registry.get(abs);
|
|
136
475
|
if (!hit) {
|
|
137
|
-
throw new
|
|
476
|
+
throw new RoseError(
|
|
477
|
+
"E-IMPORT",
|
|
478
|
+
`${path.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
|
|
479
|
+
{
|
|
480
|
+
file: fromFile,
|
|
481
|
+
line: lineOf(script, at),
|
|
482
|
+
hint: `create ${abs} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`
|
|
483
|
+
}
|
|
484
|
+
);
|
|
138
485
|
}
|
|
139
486
|
return hit;
|
|
140
487
|
};
|
|
141
|
-
let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec) => {
|
|
142
|
-
const hit = resolve3(spec);
|
|
488
|
+
let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at) => {
|
|
489
|
+
const hit = resolve3(spec, at);
|
|
143
490
|
imports.push({ name, specifier: spec, index: hit.index });
|
|
144
491
|
return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
|
|
145
492
|
});
|
|
146
|
-
rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s
|
|
147
|
-
const hit = resolve3(spec);
|
|
493
|
+
rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at) => {
|
|
494
|
+
const hit = resolve3(spec, at);
|
|
148
495
|
const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? "render";
|
|
149
496
|
imports.push({ name: alias, specifier: spec, index: hit.index });
|
|
150
497
|
return `import ${clause} from ${q}__rose_${hit.index}__${q}`;
|
|
@@ -154,6 +501,60 @@ function resolveRoseImports(script, fromFile, registry) {
|
|
|
154
501
|
function rewriteRoseImports(script, kind) {
|
|
155
502
|
return script.replace(/from\s*(['"])__rose_(\d+)__\1/g, (_, q, n) => `from ${q}./comp-${n}.${kind}.js${q}`);
|
|
156
503
|
}
|
|
504
|
+
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)$)/;
|
|
505
|
+
function nodeOnlyImports(importStmts) {
|
|
506
|
+
const out = [];
|
|
507
|
+
for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
|
|
508
|
+
if (m[1]) continue;
|
|
509
|
+
if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
|
|
510
|
+
}
|
|
511
|
+
return out;
|
|
512
|
+
}
|
|
513
|
+
function wireEventBindings(template, actionNames) {
|
|
514
|
+
const bindings = [];
|
|
515
|
+
let out = "";
|
|
516
|
+
let rest = template;
|
|
517
|
+
for (; ; ) {
|
|
518
|
+
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
519
|
+
if (!m) {
|
|
520
|
+
out += rest;
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
out += rest.slice(0, m.index);
|
|
524
|
+
let i = m.index + m[0].length;
|
|
525
|
+
let depth = 1;
|
|
526
|
+
while (i < rest.length) {
|
|
527
|
+
const ch = rest[i];
|
|
528
|
+
if (ch === '"' || ch === "'") {
|
|
529
|
+
i = skipQuoted(rest, i);
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
if (ch === "`") {
|
|
533
|
+
i = skipTemplate(rest, i);
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
if (ch === "{") depth++;
|
|
537
|
+
else if (ch === "}") {
|
|
538
|
+
depth--;
|
|
539
|
+
if (depth === 0) break;
|
|
540
|
+
}
|
|
541
|
+
i++;
|
|
542
|
+
}
|
|
543
|
+
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
544
|
+
if (actionNames.has(expr)) {
|
|
545
|
+
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
546
|
+
} else if (/^\w+$/.test(expr)) {
|
|
547
|
+
out += `data-on-${m[1]}="${expr}"`;
|
|
548
|
+
bindings.push({ event: m[1], fn: expr });
|
|
549
|
+
} else {
|
|
550
|
+
const name = `__h${bindings.length}`;
|
|
551
|
+
out += `data-on-${m[1]}="${name}"`;
|
|
552
|
+
bindings.push({ event: m[1], fn: `${name}: ${expr}` });
|
|
553
|
+
}
|
|
554
|
+
rest = rest.slice(i + 1);
|
|
555
|
+
}
|
|
556
|
+
return { template: out, bindings };
|
|
557
|
+
}
|
|
157
558
|
function scanSlotDecls(filePath) {
|
|
158
559
|
let src;
|
|
159
560
|
try {
|
|
@@ -161,8 +562,9 @@ function scanSlotDecls(filePath) {
|
|
|
161
562
|
} catch {
|
|
162
563
|
return [];
|
|
163
564
|
}
|
|
164
|
-
const
|
|
165
|
-
const
|
|
565
|
+
const noScript = src.replace(COMPONENT_RE, "");
|
|
566
|
+
const noBlocks = noScript.replace(STYLE_RE, "");
|
|
567
|
+
const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
|
|
166
568
|
const out = [];
|
|
167
569
|
for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
|
|
168
570
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
|
|
@@ -216,7 +618,11 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
216
618
|
try {
|
|
217
619
|
source = await p.transform(source, filePath);
|
|
218
620
|
} catch (err) {
|
|
219
|
-
throw new
|
|
621
|
+
throw new RoseError(
|
|
622
|
+
"E-PLUGIN",
|
|
623
|
+
`plugin ${p.name} failed on ${path.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
624
|
+
{ file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
|
|
625
|
+
);
|
|
220
626
|
}
|
|
221
627
|
}
|
|
222
628
|
if (isApi) {
|
|
@@ -226,6 +632,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
226
632
|
const usesContext2 = /getContext\s*\(/.test(rawScript2);
|
|
227
633
|
const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
|
|
228
634
|
const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
|
|
635
|
+
const ownRuntimeImports = new Set(
|
|
636
|
+
[...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
|
|
637
|
+
);
|
|
638
|
+
const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
|
|
639
|
+
const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
|
|
640
|
+
` : "";
|
|
229
641
|
return {
|
|
230
642
|
ssr: "",
|
|
231
643
|
client: "",
|
|
@@ -234,49 +646,95 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
234
646
|
guardName: null,
|
|
235
647
|
style: "",
|
|
236
648
|
hasParams: false,
|
|
237
|
-
api:
|
|
238
|
-
${rewriteRoseImports(`${hoisted.imports}
|
|
649
|
+
api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
|
|
239
650
|
${hoisted.rest}`, "ssr").trim()}`,
|
|
240
651
|
apiMethods,
|
|
241
652
|
hasPrerender,
|
|
242
653
|
usesContext: usesContext2
|
|
243
654
|
};
|
|
244
655
|
}
|
|
245
|
-
const
|
|
656
|
+
const sourceNoScript = source.replace(COMPONENT_RE, "");
|
|
657
|
+
const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
|
|
658
|
+
const styleMatch = sourceNoHead.match(STYLE_RE);
|
|
246
659
|
const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
|
|
247
|
-
const sourceNoBlocks =
|
|
248
|
-
const scriptMatch =
|
|
660
|
+
const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
|
|
661
|
+
const scriptMatch = source.match(COMPONENT_RE);
|
|
249
662
|
const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
|
|
250
663
|
const rawScript = roseResolved.script;
|
|
251
664
|
const roseImports = roseResolved.imports;
|
|
252
665
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
666
|
+
if (path.basename(filePath) !== "_middleware.rose") {
|
|
667
|
+
for (const spec of nodeOnlyImports(importStmts)) {
|
|
668
|
+
const at = importStmts.indexOf(spec);
|
|
669
|
+
throw new RoseError(
|
|
670
|
+
"E-NODE-ONLY",
|
|
671
|
+
`${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
|
|
672
|
+
{
|
|
673
|
+
file: filePath,
|
|
674
|
+
line: at >= 0 ? lineOf(importStmts, at) : void 0,
|
|
675
|
+
hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`
|
|
676
|
+
}
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
253
680
|
const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
|
|
254
681
|
if (isComponent && /\$data\s*\(/.test(rawScript)) {
|
|
255
|
-
throw new
|
|
256
|
-
|
|
682
|
+
throw new RoseError(
|
|
683
|
+
"E-EXPORT",
|
|
684
|
+
`${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
|
|
685
|
+
{ file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
|
|
257
686
|
);
|
|
258
687
|
}
|
|
259
|
-
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript);
|
|
688
|
+
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
|
|
260
689
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
261
690
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
262
691
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
|
|
263
692
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
264
693
|
const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
|
|
265
694
|
if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
|
|
266
|
-
throw new
|
|
695
|
+
throw new RoseError(
|
|
696
|
+
"E-EXPORT",
|
|
697
|
+
`${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
|
|
698
|
+
{ file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
|
|
702
|
+
const vitals = vitalsMatch ? vitalsMatch[1].trim() === "true" : void 0;
|
|
703
|
+
if (vitalsMatch && !vitals) {
|
|
704
|
+
throw new RoseError(
|
|
705
|
+
"E-EXPORT",
|
|
706
|
+
`${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
|
|
707
|
+
{ file: filePath, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
|
|
708
|
+
);
|
|
267
709
|
}
|
|
268
710
|
const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
269
711
|
const bundle = bundleMatch ? bundleMatch[1] : void 0;
|
|
270
712
|
if (bundle && !["inline", "split"].includes(bundle)) {
|
|
271
|
-
throw new
|
|
713
|
+
throw new RoseError(
|
|
714
|
+
"E-EXPORT",
|
|
715
|
+
`${filePath}: export const bundle must be 'inline' or 'split'`,
|
|
716
|
+
{ file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
|
|
717
|
+
);
|
|
272
718
|
}
|
|
273
719
|
const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
|
|
274
720
|
const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
|
|
721
|
+
const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
|
|
722
|
+
const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
|
|
723
|
+
const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
|
|
724
|
+
const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
|
|
725
|
+
const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
|
|
275
726
|
if (csr === false) {
|
|
276
727
|
const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
|
|
277
728
|
if (dead) {
|
|
278
|
-
|
|
279
|
-
|
|
729
|
+
const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
|
|
730
|
+
throw new RoseError(
|
|
731
|
+
"E-EXPORT",
|
|
732
|
+
`${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
|
|
733
|
+
{
|
|
734
|
+
file: filePath,
|
|
735
|
+
line: lineAt(deadSrc, dead),
|
|
736
|
+
hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'
|
|
737
|
+
}
|
|
280
738
|
);
|
|
281
739
|
}
|
|
282
740
|
}
|
|
@@ -287,10 +745,18 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
287
745
|
try {
|
|
288
746
|
value = new Function(`return ${headersLiteral}`)();
|
|
289
747
|
} catch {
|
|
290
|
-
throw new
|
|
748
|
+
throw new RoseError(
|
|
749
|
+
"E-EXPORT",
|
|
750
|
+
`${filePath}: export const headers must be an object literal`,
|
|
751
|
+
{ file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
|
|
752
|
+
);
|
|
291
753
|
}
|
|
292
754
|
if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
|
|
293
|
-
throw new
|
|
755
|
+
throw new RoseError(
|
|
756
|
+
"E-EXPORT",
|
|
757
|
+
`${filePath}: export const headers must be a flat map of string -> string`,
|
|
758
|
+
{ file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
|
|
759
|
+
);
|
|
294
760
|
}
|
|
295
761
|
headers = value;
|
|
296
762
|
}
|
|
@@ -301,11 +767,19 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
301
767
|
try {
|
|
302
768
|
value = new Function(`return ${cspLiteral}`)();
|
|
303
769
|
} catch {
|
|
304
|
-
throw new
|
|
770
|
+
throw new RoseError(
|
|
771
|
+
"E-EXPORT",
|
|
772
|
+
`${filePath}: export const csp must be an object literal`,
|
|
773
|
+
{ file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
|
|
774
|
+
);
|
|
305
775
|
}
|
|
306
776
|
const nonce = value?.nonce;
|
|
307
777
|
if (nonce !== void 0 && typeof nonce !== "boolean") {
|
|
308
|
-
throw new
|
|
778
|
+
throw new RoseError(
|
|
779
|
+
"E-EXPORT",
|
|
780
|
+
`${filePath}: csp.nonce must be a boolean`,
|
|
781
|
+
{ file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
|
|
782
|
+
);
|
|
309
783
|
}
|
|
310
784
|
cspNonce = nonce === true;
|
|
311
785
|
}
|
|
@@ -314,54 +788,39 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
314
788
|
const actionNames = new Set(actions.map((a) => a.name));
|
|
315
789
|
const clientReasons = [];
|
|
316
790
|
if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push("event wiring (on:)");
|
|
317
|
-
if (/<form[
|
|
791
|
+
if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
|
|
792
|
+
clientReasons.push("a form bound to a client dispatch ($action)");
|
|
793
|
+
}
|
|
318
794
|
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
319
795
|
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
|
|
320
|
-
if (actionNames.size > 0) {
|
|
321
|
-
clientReasons.push(`server action${actionNames.size > 1 ? "s" : ""} (${[...actionNames].join(", ")})`);
|
|
322
|
-
}
|
|
323
796
|
const needsClient = clientReasons.length > 0;
|
|
324
797
|
const jsWarnings = [];
|
|
325
798
|
if (!needsClient) {
|
|
326
|
-
|
|
799
|
+
const codeOnly = stripComments(source);
|
|
800
|
+
const scriptCodeOnly = stripComments(rawScript);
|
|
801
|
+
const scriptScannable = stripGuardedBranches(scriptCodeOnly);
|
|
802
|
+
if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
|
|
327
803
|
jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
|
|
328
804
|
}
|
|
329
|
-
if (/javascript:/i.test(
|
|
805
|
+
if (/javascript:/i.test(codeOnly)) {
|
|
330
806
|
jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
|
|
331
807
|
}
|
|
332
|
-
if (/\b(?:eval|new Function)\s*\(/.test(
|
|
808
|
+
if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
|
|
333
809
|
jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
|
|
334
810
|
}
|
|
335
|
-
if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(
|
|
811
|
+
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(scriptScannable)) {
|
|
336
812
|
jsWarnings.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true");
|
|
337
813
|
}
|
|
338
814
|
}
|
|
339
815
|
const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
const sourceNoHead = sourceNoBlocks.replace(HEAD_RE, "");
|
|
343
|
-
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoHead.replace(COMPONENT_RE, "").trim();
|
|
816
|
+
const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
|
|
817
|
+
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
|
|
344
818
|
const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
|
|
345
819
|
const decls = extractDecls(script);
|
|
346
820
|
const stateDecls = decls.filter((d) => d.kind === "state");
|
|
347
821
|
const setterNames = /* @__PURE__ */ new Map();
|
|
348
822
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
349
|
-
const
|
|
350
|
-
let em;
|
|
351
|
-
EVENT_RE.lastIndex = 0;
|
|
352
|
-
while (em = EVENT_RE.exec(template)) {
|
|
353
|
-
if (!actionNames.has(em[2].trim())) eventBindings.push({ event: em[1], fn: em[2] });
|
|
354
|
-
}
|
|
355
|
-
let cleanScript = removeRanges(script, decls.map((d) => [d.start, d.end]));
|
|
356
|
-
cleanScript = cleanScript.replace(SETSTATE_RE, (_, key, val) => {
|
|
357
|
-
const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
|
|
358
|
-
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
359
|
-
return `${setter}(${val})`;
|
|
360
|
-
});
|
|
361
|
-
cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
|
|
362
|
-
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
363
|
-
const ssrTemplate = templateCalled.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}").replace(/on:(\w+)=\{([^}]+)\}/g, (_, ev, fn) => actionNames.has(fn.trim()) ? `data-on-${ev}="$action:${fn.trim()}"` : `data-on-${ev}="${fn}"`);
|
|
364
|
-
const stateDeclsCode = decls.map((d) => {
|
|
823
|
+
const declCode = (d) => {
|
|
365
824
|
const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
|
|
366
825
|
if (d.kind === "state") {
|
|
367
826
|
return `const [${d.name}, ${setterNames.get(d.name)}] = state(${JSON.stringify(key)}, ${d.expr});`;
|
|
@@ -371,15 +830,39 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
371
830
|
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
372
831
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
373
832
|
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
374
|
-
}
|
|
833
|
+
};
|
|
834
|
+
const nestedDecls = [];
|
|
835
|
+
let spliced = "";
|
|
836
|
+
let pos = 0;
|
|
837
|
+
decls.forEach((d, i) => {
|
|
838
|
+
const top = braceDepthAt(script, d.start) === 0;
|
|
839
|
+
if (!top) nestedDecls.push(d);
|
|
840
|
+
spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
|
|
841
|
+
pos = d.end;
|
|
842
|
+
});
|
|
843
|
+
spliced += script.slice(pos);
|
|
844
|
+
let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
|
|
845
|
+
const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
|
|
846
|
+
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
847
|
+
return `${setter}(${val})`;
|
|
848
|
+
});
|
|
849
|
+
cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
|
|
850
|
+
cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
|
|
851
|
+
const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
|
|
852
|
+
const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
|
|
853
|
+
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
854
|
+
const wired = wireEventBindings(templateCalled, actionNames);
|
|
855
|
+
const eventBindings = wired.bindings;
|
|
375
856
|
const stateKeys = decls.map((d) => d.name);
|
|
376
857
|
const comps = new Map(roseImports.map((r) => {
|
|
377
858
|
const abs = path.resolve(path.dirname(filePath), r.specifier);
|
|
378
859
|
const hit = registry.get(abs);
|
|
379
860
|
return [r.name, { index: hit.index, slots: hit.slots }];
|
|
380
861
|
}));
|
|
862
|
+
const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
|
|
863
|
+
assertKnownDirectives(ssrTemplate, filePath);
|
|
381
864
|
const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
|
|
382
|
-
const compiledHead = headContent.trim() ?
|
|
865
|
+
const compiledHead = headContent.trim() ? compileHead(headContent) : "";
|
|
383
866
|
const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
|
|
384
867
|
const ssrExports = actions.length > 0 ? `${exportStmts}
|
|
385
868
|
${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
|
|
@@ -394,8 +877,8 @@ ${ssrExports}
|
|
|
394
877
|
${ssrGuard}
|
|
395
878
|
|
|
396
879
|
${cleanScript}
|
|
397
|
-
` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard);
|
|
398
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent);
|
|
880
|
+
` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
881
|
+
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
399
882
|
return {
|
|
400
883
|
ssr: rewriteRoseImports(ssr, "ssr"),
|
|
401
884
|
client: rewriteRoseImports(client, "client"),
|
|
@@ -407,7 +890,11 @@ ${cleanScript}
|
|
|
407
890
|
usesContext,
|
|
408
891
|
revalidate,
|
|
409
892
|
csr,
|
|
893
|
+
shell,
|
|
894
|
+
buffer,
|
|
895
|
+
controlSignal,
|
|
410
896
|
prefetch,
|
|
897
|
+
vitals,
|
|
411
898
|
bundle,
|
|
412
899
|
needsClient,
|
|
413
900
|
clientReasons,
|
|
@@ -642,31 +1129,236 @@ function extractDecls(script) {
|
|
|
642
1129
|
}
|
|
643
1130
|
return decls;
|
|
644
1131
|
}
|
|
645
|
-
function
|
|
646
|
-
|
|
647
|
-
let
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
1132
|
+
function braceDepthAt(src, index) {
|
|
1133
|
+
let depth = 0;
|
|
1134
|
+
let i = 0;
|
|
1135
|
+
while (i < index) {
|
|
1136
|
+
const ch = src[i];
|
|
1137
|
+
if (ch === "'" || ch === '"' || ch === "`") {
|
|
1138
|
+
const quote = ch;
|
|
1139
|
+
i++;
|
|
1140
|
+
while (i < index) {
|
|
1141
|
+
if (src[i] === "\\") {
|
|
1142
|
+
i += 2;
|
|
1143
|
+
continue;
|
|
1144
|
+
}
|
|
1145
|
+
if (src[i] === quote) {
|
|
1146
|
+
i++;
|
|
1147
|
+
break;
|
|
1148
|
+
}
|
|
1149
|
+
if (quote === "`" && src[i] === "$" && src[i + 1] === "{") {
|
|
1150
|
+
let d = 1;
|
|
1151
|
+
i += 2;
|
|
1152
|
+
while (i < index && d > 0) {
|
|
1153
|
+
if (src[i] === "{") d++;
|
|
1154
|
+
else if (src[i] === "}") d--;
|
|
1155
|
+
i++;
|
|
1156
|
+
}
|
|
1157
|
+
continue;
|
|
1158
|
+
}
|
|
1159
|
+
i++;
|
|
1160
|
+
}
|
|
1161
|
+
continue;
|
|
1162
|
+
}
|
|
1163
|
+
if (ch === "/" && src[i + 1] === "/") {
|
|
1164
|
+
const nl = src.indexOf("\n", i);
|
|
1165
|
+
i = nl === -1 ? src.length : nl;
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
if (ch === "/" && src[i + 1] === "*") {
|
|
1169
|
+
const close = src.indexOf("*/", i + 2);
|
|
1170
|
+
i = close === -1 ? src.length : close + 2;
|
|
1171
|
+
continue;
|
|
1172
|
+
}
|
|
1173
|
+
if (ch === "{") depth++;
|
|
1174
|
+
else if (ch === "}") depth--;
|
|
1175
|
+
i++;
|
|
652
1176
|
}
|
|
653
|
-
|
|
654
|
-
return out;
|
|
1177
|
+
return depth;
|
|
655
1178
|
}
|
|
656
1179
|
function autoCall(expr) {
|
|
657
1180
|
const e = expr.trim();
|
|
658
1181
|
return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
|
|
659
1182
|
}
|
|
1183
|
+
function findBlock(src, kind) {
|
|
1184
|
+
const head = kind === "boundary" ? /\{#boundary\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : /\{#each\s+([^}]+?)\s+as\s+(\w+)\}/g;
|
|
1185
|
+
const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
|
|
1186
|
+
let open;
|
|
1187
|
+
while (open = head.exec(src)) {
|
|
1188
|
+
const start = open.index;
|
|
1189
|
+
const afterOpen = start + open[0].length;
|
|
1190
|
+
let depth = 1;
|
|
1191
|
+
let i = afterOpen;
|
|
1192
|
+
for (; ; ) {
|
|
1193
|
+
head.lastIndex = i;
|
|
1194
|
+
closeRe.lastIndex = i;
|
|
1195
|
+
const nextOpen = head.exec(src);
|
|
1196
|
+
const nextClose = closeRe.exec(src);
|
|
1197
|
+
if (!nextClose) break;
|
|
1198
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
1199
|
+
depth++;
|
|
1200
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
i = nextClose.index + nextClose[0].length;
|
|
1204
|
+
if (--depth === 0) {
|
|
1205
|
+
const content = src.slice(afterOpen, nextClose.index);
|
|
1206
|
+
const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
|
|
1207
|
+
const arr = [src.slice(start, i), ...groups];
|
|
1208
|
+
arr.index = start;
|
|
1209
|
+
return arr;
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
head.lastIndex = afterOpen;
|
|
1213
|
+
}
|
|
1214
|
+
return null;
|
|
1215
|
+
}
|
|
1216
|
+
function compileHead(head) {
|
|
1217
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/iy;
|
|
1218
|
+
let out = "";
|
|
1219
|
+
let buf = "";
|
|
1220
|
+
let seg = 0;
|
|
1221
|
+
let i = 0;
|
|
1222
|
+
const flush = () => {
|
|
1223
|
+
if (buf.trim()) out += compileTemplate(buf, "__hd", "__hc", null, seg++, false);
|
|
1224
|
+
buf = "";
|
|
1225
|
+
};
|
|
1226
|
+
while (i < head.length) {
|
|
1227
|
+
if (head.startsWith("<!--", i)) {
|
|
1228
|
+
const end = head.indexOf("-->", i + 4);
|
|
1229
|
+
i = end < 0 ? head.length : end + 3;
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
RAW_OPEN.lastIndex = i;
|
|
1233
|
+
const open = RAW_OPEN.exec(head);
|
|
1234
|
+
if (open) {
|
|
1235
|
+
const tag = open[1].toLowerCase();
|
|
1236
|
+
const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
|
|
1237
|
+
const gt = closeAt < 0 ? -1 : head.indexOf(">", closeAt);
|
|
1238
|
+
const end = gt < 0 ? head.length : gt + 1;
|
|
1239
|
+
flush();
|
|
1240
|
+
out += emitChunk(head.slice(i, end), "__hd", "__hc", null);
|
|
1241
|
+
i = end;
|
|
1242
|
+
continue;
|
|
1243
|
+
}
|
|
1244
|
+
buf += head[i++];
|
|
1245
|
+
}
|
|
1246
|
+
flush();
|
|
1247
|
+
return out;
|
|
1248
|
+
}
|
|
1249
|
+
var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
|
|
1250
|
+
function assertKnownDirectives(template, filePath) {
|
|
1251
|
+
const rawRanges = [];
|
|
1252
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
1253
|
+
let raw;
|
|
1254
|
+
while (raw = RAW_OPEN.exec(template)) {
|
|
1255
|
+
const tag = raw[1].toLowerCase();
|
|
1256
|
+
const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
|
|
1257
|
+
const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
|
|
1258
|
+
const end = gt < 0 ? template.length : gt + 1;
|
|
1259
|
+
rawRanges.push([raw.index, end]);
|
|
1260
|
+
RAW_OPEN.lastIndex = end;
|
|
1261
|
+
}
|
|
1262
|
+
const COMMENT_RE = /<!--[\s\S]*?-->/g;
|
|
1263
|
+
let note;
|
|
1264
|
+
while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
|
|
1265
|
+
rawRanges.sort((a, b) => a[0] - b[0]);
|
|
1266
|
+
const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
|
|
1267
|
+
const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
|
|
1268
|
+
let m;
|
|
1269
|
+
while (m = DIRECTIVE_RE.exec(template)) {
|
|
1270
|
+
if (inRaw(m.index)) continue;
|
|
1271
|
+
const [, sigil, word] = m;
|
|
1272
|
+
if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
|
|
1273
|
+
if (sigil === "/") {
|
|
1274
|
+
throw new RoseError(
|
|
1275
|
+
"E-TEMPLATE",
|
|
1276
|
+
`${filePath}: {/${word}} does not close anything`,
|
|
1277
|
+
{ file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
if (word === "else") {
|
|
1281
|
+
throw new RoseError(
|
|
1282
|
+
"E-TEMPLATE",
|
|
1283
|
+
`${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
|
|
1284
|
+
{ file: filePath, line: lineAt(template, m), hint: "nest a second {#if}: {#if cond}A{/if}{#if !cond}B{/if} - the negation of the first condition IS the else" }
|
|
1285
|
+
);
|
|
1286
|
+
}
|
|
1287
|
+
throw new RoseError(
|
|
1288
|
+
"E-TEMPLATE",
|
|
1289
|
+
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
1290
|
+
{ file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary} - and there is no {:else}: nest a second {#if} with the negated condition" }
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
|
|
1294
|
+
while (m = OPENER_RE.exec(template)) {
|
|
1295
|
+
if (inRaw(m.index)) continue;
|
|
1296
|
+
const [, kind, head] = m;
|
|
1297
|
+
if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
|
|
1298
|
+
throw new RoseError(
|
|
1299
|
+
"E-TEMPLATE",
|
|
1300
|
+
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
1301
|
+
{ file: filePath, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
|
|
1302
|
+
);
|
|
1303
|
+
}
|
|
1304
|
+
const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
|
|
1305
|
+
const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
|
|
1306
|
+
let depth = 1;
|
|
1307
|
+
let i = m.index + m[0].length;
|
|
1308
|
+
for (; ; ) {
|
|
1309
|
+
OPEN_RE.lastIndex = i;
|
|
1310
|
+
CLOSE_RE.lastIndex = i;
|
|
1311
|
+
const nextOpen = OPEN_RE.exec(template);
|
|
1312
|
+
const nextClose = CLOSE_RE.exec(template);
|
|
1313
|
+
if (!nextClose) break;
|
|
1314
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
1315
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
1316
|
+
continue;
|
|
1317
|
+
}
|
|
1318
|
+
i = nextClose.index + nextClose[0].length;
|
|
1319
|
+
if (--depth === 0) break;
|
|
1320
|
+
}
|
|
1321
|
+
if (depth !== 0) {
|
|
1322
|
+
throw new RoseError(
|
|
1323
|
+
"E-TEMPLATE",
|
|
1324
|
+
`${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
|
|
1325
|
+
{ file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
|
|
1326
|
+
);
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
function rewriteQuotedExprAttrs(template, comps) {
|
|
1331
|
+
const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
|
|
1332
|
+
return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
|
|
1333
|
+
if (comps.has(name) || !/\{/.test(attrs)) return tag;
|
|
1334
|
+
const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
|
|
1335
|
+
if (!/\{/.test(value) || value.includes("`")) return whole;
|
|
1336
|
+
const spans = templateExprSpans(value);
|
|
1337
|
+
if (spans.length === 0) return whole;
|
|
1338
|
+
let expr = "";
|
|
1339
|
+
let last = 0;
|
|
1340
|
+
for (const s of spans) {
|
|
1341
|
+
if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
|
|
1342
|
+
expr += (expr ? " + " : "") + `(${s.expr})`;
|
|
1343
|
+
last = s.end + 1;
|
|
1344
|
+
}
|
|
1345
|
+
if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
|
|
1346
|
+
return `${attr}={${expr}}`;
|
|
1347
|
+
});
|
|
1348
|
+
return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
660
1351
|
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
|
|
661
1352
|
let result = "";
|
|
662
1353
|
let remaining = template;
|
|
663
1354
|
let blockId = 0;
|
|
664
1355
|
const nextId = () => `${depth}_${blockId++}`;
|
|
665
1356
|
while (remaining.length > 0) {
|
|
666
|
-
const ifMatch = remaining
|
|
667
|
-
const eachMatch = remaining
|
|
668
|
-
const boundaryMatch = remaining
|
|
669
|
-
const
|
|
1357
|
+
const ifMatch = findBlock(remaining, "if");
|
|
1358
|
+
const eachMatch = findBlock(remaining, "each");
|
|
1359
|
+
const boundaryMatch = findBlock(remaining, "boundary");
|
|
1360
|
+
const firstExpr = templateExprSpans(remaining)[0];
|
|
1361
|
+
const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
|
|
670
1362
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
671
1363
|
const candidates = [];
|
|
672
1364
|
if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
|
|
@@ -675,6 +1367,25 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
675
1367
|
if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
|
|
676
1368
|
if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
|
|
677
1369
|
const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
|
|
1370
|
+
const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
|
|
1371
|
+
const rawHit = rawOpenRe.exec(remaining);
|
|
1372
|
+
if (rawHit && earliest && rawHit.index < earliest.index) {
|
|
1373
|
+
const tag = rawHit[1].toLowerCase();
|
|
1374
|
+
const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
|
|
1375
|
+
const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
|
|
1376
|
+
const end = gt < 0 ? remaining.length : gt + 1;
|
|
1377
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
1378
|
+
remaining = remaining.substring(end);
|
|
1379
|
+
continue;
|
|
1380
|
+
}
|
|
1381
|
+
const noteAt = remaining.indexOf("<!--");
|
|
1382
|
+
if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
|
|
1383
|
+
const noteEnd = remaining.indexOf("-->", noteAt + 4);
|
|
1384
|
+
const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
|
|
1385
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
1386
|
+
remaining = remaining.substring(end);
|
|
1387
|
+
continue;
|
|
1388
|
+
}
|
|
678
1389
|
if (!earliest) {
|
|
679
1390
|
result += emitChunk(remaining, acc, closes, scope);
|
|
680
1391
|
break;
|
|
@@ -704,7 +1415,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
704
1415
|
const call = autoCall(items);
|
|
705
1416
|
const id = nextId();
|
|
706
1417
|
const itemRe = new RegExp(`\\b${item}\\b`, "g");
|
|
707
|
-
|
|
1418
|
+
let scoped = "";
|
|
1419
|
+
let lastSpan = 0;
|
|
1420
|
+
for (const s of templateExprSpans(content.trim())) {
|
|
1421
|
+
scoped += content.trim().slice(lastSpan, s.start) + "{" + s.expr.replace(itemRe, "__s") + "}";
|
|
1422
|
+
lastSpan = s.end + 1;
|
|
1423
|
+
}
|
|
1424
|
+
scoped += content.trim().slice(lastSpan);
|
|
708
1425
|
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, markers, comps);
|
|
709
1426
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
|
|
710
1427
|
`;
|
|
@@ -744,7 +1461,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
744
1461
|
rest = remaining.substring(tag.end);
|
|
745
1462
|
} else {
|
|
746
1463
|
const closeIdx = findClose(remaining, tag.end, tag.name);
|
|
747
|
-
if (closeIdx < 0) throw new
|
|
1464
|
+
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)` });
|
|
748
1465
|
childrenSrc = remaining.substring(tag.end, closeIdx);
|
|
749
1466
|
rest = remaining.substring(closeIdx + tag.name.length + 3);
|
|
750
1467
|
}
|
|
@@ -758,7 +1475,14 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
758
1475
|
const decl = entry.slots.find((s) => s.name === nm);
|
|
759
1476
|
let content = src;
|
|
760
1477
|
for (const p of decl?.props ?? []) {
|
|
761
|
-
|
|
1478
|
+
const pRe = new RegExp(`\\b${p}\\b`, "g");
|
|
1479
|
+
let out = "";
|
|
1480
|
+
let lastSpan = 0;
|
|
1481
|
+
for (const s of templateExprSpans(content)) {
|
|
1482
|
+
out += content.slice(lastSpan, s.start) + "{" + s.expr.replace(pRe, `__s.${p}`) + "}";
|
|
1483
|
+
lastSpan = s.end + 1;
|
|
1484
|
+
}
|
|
1485
|
+
content = out + content.slice(lastSpan);
|
|
762
1486
|
}
|
|
763
1487
|
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, markers, comps)} return h; }`;
|
|
764
1488
|
});
|
|
@@ -789,6 +1513,21 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
789
1513
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
790
1514
|
continue;
|
|
791
1515
|
}
|
|
1516
|
+
const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
|
|
1517
|
+
if (rawMatch) {
|
|
1518
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1519
|
+
const expr2 = rawMatch[1].trim();
|
|
1520
|
+
if (!markers) {
|
|
1521
|
+
result += `${acc} += String(${expr2} ?? '');
|
|
1522
|
+
`;
|
|
1523
|
+
} else {
|
|
1524
|
+
const fn = scope ? `(${scope}) => (${expr2})` : `() => (${expr2})`;
|
|
1525
|
+
result += `${acc} += rawMark(${closes}, ${fn}${scope ? `, ${scope}` : ""});
|
|
1526
|
+
`;
|
|
1527
|
+
}
|
|
1528
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1529
|
+
continue;
|
|
1530
|
+
}
|
|
792
1531
|
const attrMatch = before.match(/([\w-]+)=\s*$/);
|
|
793
1532
|
if (attrMatch) {
|
|
794
1533
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
@@ -900,7 +1639,7 @@ function rejectNestedSlot(src, outer) {
|
|
|
900
1639
|
if (end < 0) return;
|
|
901
1640
|
const hit = /\bslot\s*=\s*["'](\w+)["']/.exec(src.slice(lt, end));
|
|
902
1641
|
if (hit && nm[1] !== "/") {
|
|
903
|
-
throw new
|
|
1642
|
+
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" });
|
|
904
1643
|
}
|
|
905
1644
|
i = end;
|
|
906
1645
|
}
|
|
@@ -954,7 +1693,7 @@ function splitSlots(src) {
|
|
|
954
1693
|
if (!selfClosing && !isVoid) elemDepth++;
|
|
955
1694
|
const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
|
|
956
1695
|
if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
|
|
957
|
-
throw new
|
|
1696
|
+
throw new RoseError("E-TEMPLATE", `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
|
|
958
1697
|
}
|
|
959
1698
|
if (slotName) {
|
|
960
1699
|
const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
|
|
@@ -962,7 +1701,7 @@ function splitSlots(src) {
|
|
|
962
1701
|
named.set(slotName, (named.get(slotName) ?? "") + stripped);
|
|
963
1702
|
} else {
|
|
964
1703
|
const closeIdx = findClose(src, end, nm[2]);
|
|
965
|
-
if (closeIdx < 0) throw new
|
|
1704
|
+
if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
|
|
966
1705
|
const tail = `</${nm[2]}>`;
|
|
967
1706
|
const inner = src.slice(end, closeIdx);
|
|
968
1707
|
rejectNestedSlot(inner, slotName);
|
|
@@ -1038,7 +1777,8 @@ function compileSlot(acc) {
|
|
|
1038
1777
|
return `${acc} += String(children);
|
|
1039
1778
|
`;
|
|
1040
1779
|
}
|
|
1041
|
-
var RUNTIME_IMPORTS = `import { state, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark } from './runtime.js';`;
|
|
1780
|
+
var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
|
|
1781
|
+
var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
1042
1782
|
function propsCode(props) {
|
|
1043
1783
|
if (props.length === 0) return "";
|
|
1044
1784
|
return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
|
|
@@ -1050,20 +1790,13 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
1050
1790
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
1051
1791
|
return { o, fn };
|
|
1052
1792
|
};
|
|
1053
|
-
const __slotBlock = (closes, sl, name, pairs) =>
|
|
1054
|
-
|
|
1055
|
-
const idx = closes.length;
|
|
1056
|
-
closes.push(() => {
|
|
1057
|
-
if (!hit) return null;
|
|
1058
|
-
const c = [];
|
|
1059
|
-
return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
|
|
1060
|
-
});
|
|
1061
|
-
return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
|
|
1062
|
-
};`;
|
|
1063
|
-
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "") {
|
|
1793
|
+
const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
|
|
1794
|
+
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
|
|
1064
1795
|
const headCode = headFn ? `
|
|
1065
1796
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
1066
1797
|
__html += headMark(closes, __head);` : "";
|
|
1798
|
+
const actionState = hasActions ? `
|
|
1799
|
+
const $setState = (key, value) => setState(key, value);` : "";
|
|
1067
1800
|
return `
|
|
1068
1801
|
${RUNTIME_IMPORTS}
|
|
1069
1802
|
|
|
@@ -1071,6 +1804,7 @@ ${imports}
|
|
|
1071
1804
|
|
|
1072
1805
|
${exports}
|
|
1073
1806
|
${guard}
|
|
1807
|
+
${actionState}
|
|
1074
1808
|
|
|
1075
1809
|
${namedSlots ? SLOT_HELPER : ""}
|
|
1076
1810
|
|
|
@@ -1078,20 +1812,20 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
|
|
|
1078
1812
|
${props.length > 0 ? "const __p = __props || {};" : ""}
|
|
1079
1813
|
${namedSlots ? "const __sl = __slots || {};" : ""}
|
|
1080
1814
|
${propsCode(props)}
|
|
1815
|
+
${script}
|
|
1081
1816
|
${stateDeclsCode}
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
// every path that is not a server action's re-render - see the runtime).
|
|
1817
|
+
${dataDeclsCode}
|
|
1818
|
+
|
|
1085
1819
|
${isComponent ? "" : "applyStateDeltas();"}
|
|
1086
|
-
${script}
|
|
1087
1820
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1088
1821
|
let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
|
|
1089
1822
|
return __html;
|
|
1090
1823
|
}
|
|
1091
1824
|
`;
|
|
1092
1825
|
}
|
|
1093
|
-
function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false) {
|
|
1826
|
+
function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
|
|
1094
1827
|
const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
|
|
1828
|
+
const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
|
|
1095
1829
|
const headCode = headFn ? `
|
|
1096
1830
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
1097
1831
|
__html += headMark(closes, __head);` : "";
|
|
@@ -1101,15 +1835,18 @@ ${RUNTIME_IMPORTS}
|
|
|
1101
1835
|
${imports}
|
|
1102
1836
|
|
|
1103
1837
|
${exports}
|
|
1104
|
-
|
|
1838
|
+
${clientSetState ? `
|
|
1839
|
+
${clientSetState}
|
|
1840
|
+
` : ""}
|
|
1105
1841
|
${namedSlots ? SLOT_HELPER : ""}
|
|
1106
1842
|
|
|
1107
1843
|
export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
|
|
1108
1844
|
${props.length > 0 ? "const __p = __props || {};" : ""}
|
|
1109
1845
|
${namedSlots ? "const __sl = __slots || {};" : ""}
|
|
1110
1846
|
${propsCode(props)}
|
|
1111
|
-
${stateDeclsCode}
|
|
1112
1847
|
${script}
|
|
1848
|
+
${stateDeclsCode}
|
|
1849
|
+
${dataDeclsCode}
|
|
1113
1850
|
${handlerRegistry}
|
|
1114
1851
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1115
1852
|
let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
|
|
@@ -1123,6 +1860,7 @@ var routeShipsNoJs = (infos, compiled, i) => {
|
|
|
1123
1860
|
if (compiled[i].needsClient) return false;
|
|
1124
1861
|
return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
|
|
1125
1862
|
};
|
|
1863
|
+
var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
|
|
1126
1864
|
function buildReport(infos, compiled) {
|
|
1127
1865
|
return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
|
|
1128
1866
|
if (routeShipsNoJs(infos, compiled, i)) {
|
|
@@ -1133,6 +1871,48 @@ function buildReport(infos, compiled) {
|
|
|
1133
1871
|
return `${info.routePath} client JS ${why}${forced}`;
|
|
1134
1872
|
});
|
|
1135
1873
|
}
|
|
1874
|
+
var MOUNT_ENTRY = `
|
|
1875
|
+
import { start, postForm } from '/client.js';
|
|
1876
|
+
|
|
1877
|
+
for (const el of document.querySelectorAll('[data-rosetack]')) {
|
|
1878
|
+
const route = el.getAttribute('data-rosetack');
|
|
1879
|
+
const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
|
|
1880
|
+
const parsed = new DOMParser().parseFromString(doc, 'text/html');
|
|
1881
|
+
// A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
|
|
1882
|
+
const app = parsed.getElementById('app');
|
|
1883
|
+
if (app) {
|
|
1884
|
+
el.innerHTML = app.innerHTML;
|
|
1885
|
+
} else {
|
|
1886
|
+
for (const node of Array.from(parsed.body.children)) {
|
|
1887
|
+
if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
// start() resumes from #__rosetack_state (zero hydration), so the state
|
|
1891
|
+
|
|
1892
|
+
const state = parsed.getElementById('__rosetack_state');
|
|
1893
|
+
if (state) el.appendChild(state);
|
|
1894
|
+
|
|
1895
|
+
const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
|
|
1896
|
+
await start(el, route, rendered === route);
|
|
1897
|
+
if (state) state.remove();
|
|
1898
|
+
|
|
1899
|
+
el.addEventListener('click', (e) => {
|
|
1900
|
+
const a = e.target.closest && e.target.closest('a[href^="/"]');
|
|
1901
|
+
if (!a || !el.contains(a)) return;
|
|
1902
|
+
e.preventDefault();
|
|
1903
|
+
el.setAttribute('data-rosetack', a.getAttribute('href'));
|
|
1904
|
+
start(el, a.getAttribute('href'), false);
|
|
1905
|
+
});
|
|
1906
|
+
// Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
|
|
1907
|
+
el.addEventListener('submit', (e) => {
|
|
1908
|
+
const f = e.target;
|
|
1909
|
+
if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
|
|
1910
|
+
if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
|
|
1911
|
+
e.preventDefault();
|
|
1912
|
+
postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
|
|
1913
|
+
});
|
|
1914
|
+
}
|
|
1915
|
+
`;
|
|
1136
1916
|
async function buildProject(root, outDir) {
|
|
1137
1917
|
await fs.promises.mkdir(outDir, { recursive: true });
|
|
1138
1918
|
const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
@@ -1141,7 +1921,11 @@ async function buildProject(root, outDir) {
|
|
|
1141
1921
|
const compFiles = await scanComponentFiles(root);
|
|
1142
1922
|
const files = [...pageFiles, ...compFiles];
|
|
1143
1923
|
if (pageFiles.length === 0) {
|
|
1144
|
-
throw new
|
|
1924
|
+
throw new RoseError(
|
|
1925
|
+
"E-ROUTE",
|
|
1926
|
+
`no .rose pages found under ${path.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
|
|
1927
|
+
{ file: path.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
|
|
1928
|
+
);
|
|
1145
1929
|
}
|
|
1146
1930
|
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
1147
1931
|
const config = await loadConfig(root);
|
|
@@ -1230,9 +2014,7 @@ async function buildProject(root, outDir) {
|
|
|
1230
2014
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
1231
2015
|
if (runtimePlugins.length > 0) {
|
|
1232
2016
|
const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
|
|
1233
|
-
await fs.promises.writeFile(path.join(buildDir, "plugins.js"),
|
|
1234
|
-
// Bundled into dist/server.js: these hooks run per request on every server
|
|
1235
|
-
// (Node, dev/preview, edge). Transform hooks already ran at build time.
|
|
2017
|
+
await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
|
|
1236
2018
|
import config from ${JSON.stringify(configRel)};
|
|
1237
2019
|
|
|
1238
2020
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -1245,7 +2027,7 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1245
2027
|
`);
|
|
1246
2028
|
}
|
|
1247
2029
|
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs.existsSync(p));
|
|
1248
|
-
if (!runtimeEntry) throw new
|
|
2030
|
+
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" });
|
|
1249
2031
|
await esbuild.build({
|
|
1250
2032
|
entryPoints: [runtimeEntry],
|
|
1251
2033
|
bundle: true,
|
|
@@ -1261,8 +2043,34 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1261
2043
|
await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
|
|
1262
2044
|
}
|
|
1263
2045
|
}
|
|
1264
|
-
const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
|
|
1265
|
-
|
|
2046
|
+
const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).sort((a, b) => {
|
|
2047
|
+
const rank = (pattern) => {
|
|
2048
|
+
const segs = pattern.split("/");
|
|
2049
|
+
return [
|
|
2050
|
+
segs.filter((s) => s.startsWith("**")).length,
|
|
2051
|
+
segs.filter((s) => s.startsWith("*")).length,
|
|
2052
|
+
segs.filter((s) => s.startsWith(":")).length
|
|
2053
|
+
];
|
|
2054
|
+
};
|
|
2055
|
+
const ra = rank(a.info.pattern);
|
|
2056
|
+
const rb = rank(b.info.pattern);
|
|
2057
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2058
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2059
|
+
});
|
|
2060
|
+
const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
|
|
2061
|
+
const rank = (pattern) => {
|
|
2062
|
+
const segs = pattern.split("/");
|
|
2063
|
+
return [
|
|
2064
|
+
segs.filter((s) => s.startsWith("**")).length,
|
|
2065
|
+
segs.filter((s) => s.startsWith("*")).length,
|
|
2066
|
+
segs.filter((s) => s.startsWith(":")).length
|
|
2067
|
+
];
|
|
2068
|
+
};
|
|
2069
|
+
const ra = rank(a.info.pattern);
|
|
2070
|
+
const rb = rank(b.info.pattern);
|
|
2071
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2072
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2073
|
+
});
|
|
1266
2074
|
const compose = (idx) => {
|
|
1267
2075
|
let expr = `render_${idx}`;
|
|
1268
2076
|
for (const i of layoutsOf(infos, idx)) {
|
|
@@ -1293,33 +2101,48 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1293
2101
|
const named = [actionImports, guardImport].filter(Boolean).join(", ");
|
|
1294
2102
|
return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
|
|
1295
2103
|
}).join("\n");
|
|
1296
|
-
const
|
|
1297
|
-
|
|
2104
|
+
const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
|
|
2105
|
+
const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
|
|
2106
|
+
const dir = path.posix.dirname(rel);
|
|
2107
|
+
const prefix = dir === "." ? "/" : "/" + dir;
|
|
2108
|
+
const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
|
|
2109
|
+
return { prefix, render: split ? loaderOf(i) : compose(i), flags };
|
|
2110
|
+
}).sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2111
|
+
const notFoundTable = `[
|
|
2112
|
+
${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
|
|
2113
|
+
]`;
|
|
1298
2114
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
1299
2115
|
const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
|
|
1300
2116
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
1301
2117
|
const serverRoutes = pages.map(({ info, i }) => {
|
|
1302
2118
|
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
1303
2119
|
if (compiled[i].csr === false && compiled[i].needsClient) {
|
|
1304
|
-
throw new
|
|
1305
|
-
|
|
2120
|
+
throw new RoseError(
|
|
2121
|
+
"E-EXPORT",
|
|
2122
|
+
`${info.filePath}: csr = false but this route needs the client bundle (${(compiled[i].clientReasons ?? ["needs the client"]).join(" + ")}).`,
|
|
2123
|
+
{ file: info.filePath, hint: "remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above" }
|
|
1306
2124
|
);
|
|
1307
2125
|
}
|
|
1308
2126
|
if (compiled[i].csr === false) {
|
|
1309
2127
|
const needy = layoutsOf(infos, i).find((li) => compiled[li].needsClient);
|
|
1310
2128
|
if (needy !== void 0) {
|
|
1311
|
-
throw new
|
|
1312
|
-
|
|
2129
|
+
throw new RoseError(
|
|
2130
|
+
"E-EXPORT",
|
|
2131
|
+
`${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).`,
|
|
2132
|
+
{ file: info.filePath, hint: "a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only" }
|
|
1313
2133
|
);
|
|
1314
2134
|
}
|
|
1315
2135
|
}
|
|
1316
2136
|
const csrFlag = routeNoJs(i) ? ", csr: false" : "";
|
|
2137
|
+
const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
|
|
2138
|
+
const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
|
|
2139
|
+
const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
|
|
1317
2140
|
const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
|
|
1318
|
-
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag} }`;
|
|
2141
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
|
|
1319
2142
|
}).join(",\n ");
|
|
1320
2143
|
const serverEntry = `
|
|
1321
2144
|
${serverImports}
|
|
1322
|
-
import { setState, clearRequestState, serializeState, resetRequestContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
|
|
2145
|
+
import { setState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta } from './runtime.js';
|
|
1323
2146
|
${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
|
|
1324
2147
|
// module to import - the runners below stay no-ops and the servers call them
|
|
1325
2148
|
// unconditionally (one code path, no flags to keep in sync).
|
|
@@ -1327,12 +2150,7 @@ const __pluginHooks = [];
|
|
|
1327
2150
|
const __hasRequestHooks = false;
|
|
1328
2151
|
const __hasResponseHooks = false;`}
|
|
1329
2152
|
|
|
1330
|
-
|
|
1331
|
-
// middleware and may short-circuit the request with its own Response; onResponse
|
|
1332
|
-
// runs once the response exists and may replace it. Both are no-ops when the
|
|
1333
|
-
// project declares no runtime hooks. A throwing hook is logged and skipped -
|
|
1334
|
-
// the request continues - so a broken logging plugin can never take a site
|
|
1335
|
-
// down (a build-time transform, by contrast, fails loudly).
|
|
2153
|
+
|
|
1336
2154
|
export async function runRequestHooks(ctx) {
|
|
1337
2155
|
for (const p of __pluginHooks) {
|
|
1338
2156
|
if (!p.onRequest) continue;
|
|
@@ -1360,22 +2178,20 @@ export async function runResponseHooks(ctx, res) {
|
|
|
1360
2178
|
return out;
|
|
1361
2179
|
}
|
|
1362
2180
|
|
|
1363
|
-
|
|
1364
|
-
|
|
2181
|
+
|
|
2182
|
+
|
|
1365
2183
|
export const hasRequestHooks = __hasRequestHooks;
|
|
1366
2184
|
export const hasResponseHooks = __hasResponseHooks;
|
|
1367
2185
|
|
|
1368
|
-
//
|
|
1369
|
-
|
|
1370
|
-
|
|
2186
|
+
// P0-1: the query of the request being rendered, for $query().
|
|
2187
|
+
export function setQuery(query) {
|
|
2188
|
+
setRequestQuery(query || {});
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
|
|
1371
2192
|
setLocales(${localesJson}, '${defaultLocale}');
|
|
1372
2193
|
|
|
1373
|
-
|
|
1374
|
-
// own process with its own dist/server.js module, so a $store write must
|
|
1375
|
-
// travel: this worker -> primary -> every other worker. process.send exists
|
|
1376
|
-
// only inside cluster workers, so a single-process runner (dev, preview,
|
|
1377
|
-
// the edge adapter) keeps the transport null and $store stays plain
|
|
1378
|
-
// per-process state - the documented boundary, not a bug.
|
|
2194
|
+
|
|
1379
2195
|
if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
1380
2196
|
setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
|
|
1381
2197
|
process.on('message', (msg) => {
|
|
@@ -1383,74 +2199,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
|
1383
2199
|
});
|
|
1384
2200
|
}
|
|
1385
2201
|
|
|
2202
|
+
// (the cross-machine seam): the cluster relay above covers ONE machine.
|
|
2203
|
+
export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
|
|
2204
|
+
setStoreTransport(send);
|
|
2205
|
+
}
|
|
2206
|
+
export function __deliverStorePatch(name: string, value: unknown): void {
|
|
2207
|
+
applyStorePatch(name, value);
|
|
2208
|
+
}
|
|
2209
|
+
|
|
1386
2210
|
export { localeList };
|
|
1387
2211
|
export const defaultLocale = '${defaultLocale}';
|
|
1388
2212
|
|
|
1389
|
-
// Route params maps, re-exported for the build's prerender step: routePath
|
|
1390
|
-
// -> the component's exported params (a static map or a function). Reading
|
|
1391
|
-
// them through the server bundle keeps the deploy dir free of component
|
|
1392
|
-
// modules - both bundles are self-contained, nothing else may ship. Only
|
|
1393
|
-
// components that actually export params appear here (a missing export
|
|
1394
|
-
// means the dynamic route renders on demand).
|
|
2213
|
+
// Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
|
|
1395
2214
|
${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
|
|
1396
2215
|
|
|
1397
2216
|
export const routeParams = {
|
|
1398
2217
|
${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
|
|
1399
2218
|
};
|
|
1400
2219
|
|
|
1401
|
-
// Routes whose component reads the request context (getContext()), mutates a
|
|
1402
|
-
// shared store ($store), or opted into nonce-based CSP: the bag is
|
|
1403
|
-
// per-request, the store is per-process, and a nonce is per-response, so
|
|
1404
|
-
// these are dynamic - the build never bakes them and the servers never
|
|
1405
|
-
// answer them from a prerendered file. Public routes keep the static fast
|
|
1406
|
-
// path (file cache, ETag/304, streaming) untouched.
|
|
2220
|
+
// Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
|
|
1407
2221
|
export const dynamicRoutes = [
|
|
1408
|
-
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
2222
|
+
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1409
2223
|
];
|
|
1410
2224
|
|
|
1411
|
-
// Which api routes opt into build-time baking (export const prerender = true):
|
|
1412
|
-
// routePath -> boolean. The build calls the GET handler once and writes the
|
|
1413
|
-
// body to dist/, so the Go single binary serves read-only APIs without Node.
|
|
2225
|
+
// Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
|
|
1414
2226
|
${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
|
|
1415
2227
|
|
|
1416
2228
|
export const apiPrerender = {
|
|
1417
2229
|
${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
|
|
1418
2230
|
};
|
|
1419
2231
|
|
|
1420
|
-
|
|
1421
|
-
// bakes these routes like any other, and the preview server serves the
|
|
1422
|
-
// baked file for up to N seconds - after which the next request is answered
|
|
1423
|
-
// STALE (instant, from disk) while a background pass re-renders and swaps
|
|
1424
|
-
// the file (ISR). Routes that read the request context are
|
|
1425
|
-
// excluded: they render per request and have no baked file to revalidate.
|
|
1426
|
-
// The dev server ignores the window (it rebuilds on change), the edge
|
|
1427
|
-
// adapter renders live (always fresh), and the Go binary serves the baked
|
|
1428
|
-
// file forever - the same static-half boundary as page POSTs.
|
|
2232
|
+
|
|
1429
2233
|
export const revalidate = [
|
|
1430
2234
|
${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
|
|
1431
2235
|
];
|
|
1432
2236
|
|
|
1433
|
-
//
|
|
1434
|
-
// every render on the server (pages, POSTs, api calls alike). Returning a
|
|
1435
|
-
// Response short-circuits the whole request - a redirect, an auth wall, a
|
|
1436
|
-
// rewrite; returning nothing continues, and getContext() hands the
|
|
1437
|
-
// per-request bag to $data, server actions and api handlers. Absent -> null,
|
|
1438
|
-
// and the servers keep their static fast paths.
|
|
2237
|
+
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
1439
2238
|
export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
|
|
1440
2239
|
|
|
1441
|
-
// Routes whose DOCUMENTS ship without the client bundle (
|
|
1442
|
-
// decided by the compiler since #29): HTML + CSS only - no runtime, no
|
|
1443
|
-
// state script, zero JavaScript for whoever lands on them. The compiler
|
|
1444
|
-
// picks these automatically: a route whose whole chain needs nothing from
|
|
1445
|
-
// the client (no event wiring, no lifecycle, no action, no form) is a
|
|
1446
|
-
// content route. An exported "csr = true" forces the bundle back in; an
|
|
1447
|
-
// exported "csr = false" is the same decision, asserted. The route's render
|
|
1448
|
-
// function still rides in the client bundle, so a client-side navigation
|
|
1449
|
-
// from an interactive page paints it normally and a static deploy's SPA
|
|
1450
|
-
// fallback can render it too; only the document is JS-free.
|
|
1451
|
-
// isNoJs() lets the servers keep these routes on the buffered path: a
|
|
1452
|
-
// streamed no-JS document would carry the shell's default <title> (the
|
|
1453
|
-
// route head is applied client-side at boot, and there is no client).
|
|
2240
|
+
// Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
|
|
1454
2241
|
export const noJsRoutes = [
|
|
1455
2242
|
${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
|
|
1456
2243
|
];
|
|
@@ -1459,11 +2246,12 @@ export function isNoJs(pathname) {
|
|
|
1459
2246
|
return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1460
2247
|
}
|
|
1461
2248
|
|
|
1462
|
-
//
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
2249
|
+
// P0-2 (bug report): routes that exported "buffer = true".
|
|
2250
|
+
export function isBuffered(pathname) {
|
|
2251
|
+
return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
|
|
1467
2255
|
export const routeHeaders = [
|
|
1468
2256
|
${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
|
|
1469
2257
|
];
|
|
@@ -1473,14 +2261,7 @@ export function headersFor(pathname) {
|
|
|
1473
2261
|
return hit ? hit.headers : null;
|
|
1474
2262
|
}
|
|
1475
2263
|
|
|
1476
|
-
|
|
1477
|
-
// ). The servers ask this BEFORE writing a document: when it is true they
|
|
1478
|
-
// mint one random nonce per response, put it in the CSP header ('nonce-...'
|
|
1479
|
-
// plus 'strict-dynamic', so the document's own code may load more code) and
|
|
1480
|
-
// stamp the same value on the script tag. The default policy stays a hash -
|
|
1481
|
-
// cspNonceRoutes is empty for an app that never asks, so the fast path is
|
|
1482
|
-
// unchanged. The Go binary never sees this: these routes are dynamic, so it
|
|
1483
|
-
// has no baked file for them to serve.
|
|
2264
|
+
|
|
1484
2265
|
export const cspNonceRoutes = [
|
|
1485
2266
|
${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1486
2267
|
];
|
|
@@ -1489,9 +2270,7 @@ export function cspNonce(pathname) {
|
|
|
1489
2270
|
return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1490
2271
|
}
|
|
1491
2272
|
|
|
1492
|
-
// A Web-standard Request from whatever the host provides: the edge adapter
|
|
1493
|
-
// passes one already; the Node server passes its IncomingMessage (plus the
|
|
1494
|
-
// already-parsed FormData for POSTs, so middleware can read form fields).
|
|
2273
|
+
// A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
|
|
1495
2274
|
function toWebRequest(raw, form) {
|
|
1496
2275
|
if (raw instanceof Request) return raw;
|
|
1497
2276
|
const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
|
|
@@ -1499,13 +2278,7 @@ function toWebRequest(raw, form) {
|
|
|
1499
2278
|
return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
|
|
1500
2279
|
}
|
|
1501
2280
|
|
|
1502
|
-
|
|
1503
|
-
// its short-circuit Response, or null to continue. The servers call this
|
|
1504
|
-
// EXACTLY ONCE per request, before anything else: it resets the per-request
|
|
1505
|
-
// context bag and the middleware fills it via getContext(), which $data,
|
|
1506
|
-
// server actions and api handlers then read while rendering. rawReq: the
|
|
1507
|
-
// host's request (Node IncomingMessage or a Web-standard Request); form:
|
|
1508
|
-
// the already-parsed FormData of a POST.
|
|
2281
|
+
|
|
1509
2282
|
export async function runMiddleware(rawReq, form) {
|
|
1510
2283
|
resetRequestContext();
|
|
1511
2284
|
if (!middleware || !rawReq) return null;
|
|
@@ -1517,10 +2290,7 @@ const routes = [
|
|
|
1517
2290
|
${serverRoutes}
|
|
1518
2291
|
];
|
|
1519
2292
|
|
|
1520
|
-
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
|
|
1521
|
-
// render HTML and never reach the client bundle. The middleware ran before
|
|
1522
|
-
// this (the servers call runMiddleware() first), so handlers can read
|
|
1523
|
-
// getContext() for auth without re-running anything.
|
|
2293
|
+
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
|
|
1524
2294
|
const apiRoutes = [
|
|
1525
2295
|
${apiRoutes.map(({ info, i }) => {
|
|
1526
2296
|
const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
@@ -1528,19 +2298,40 @@ const apiRoutes = [
|
|
|
1528
2298
|
}).join(",\n ")}
|
|
1529
2299
|
];
|
|
1530
2300
|
|
|
1531
|
-
// pages
|
|
1532
|
-
|
|
2301
|
+
// Not-found pages, deepest segment first: the root 404.rose ('/') and any
|
|
2302
|
+
// pages/<seg>/_notfound.rose, each already composed with its layout chain.
|
|
2303
|
+
// notFoundFor picks the nearest one up the path - an /admin miss answers
|
|
2304
|
+
// the admin 404, a public miss the site's - and notFoundPage is the whole
|
|
2305
|
+
// answer (real 404 status, or the built-in plain 404 when the app has none).
|
|
2306
|
+
const notFoundRoutes = ${notFoundTable};
|
|
2307
|
+
const notFoundFor = (pathname) => {
|
|
2308
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
2309
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
2310
|
+
}
|
|
2311
|
+
return null;
|
|
2312
|
+
};
|
|
2313
|
+
|
|
2314
|
+
const notFoundFlags = (pathname) => {
|
|
2315
|
+
for (const [prefix, render, flags] of notFoundRoutes) {
|
|
2316
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
|
|
2317
|
+
}
|
|
2318
|
+
return null;
|
|
2319
|
+
};
|
|
2320
|
+
const notFoundPage = async (pathname) => {
|
|
2321
|
+
const nf = notFoundFor(pathname);
|
|
2322
|
+
if (nf) {
|
|
2323
|
+
const page = await renderFallback(pathname, nf);
|
|
2324
|
+
// __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
|
|
2325
|
+
return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
|
|
2326
|
+
}
|
|
2327
|
+
return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
|
|
2328
|
+
};
|
|
2329
|
+
|
|
1533
2330
|
|
|
1534
|
-
// pages/500.rose (with its layouts) or null -> built-in plain 500: a route
|
|
1535
2331
|
// whose render throws degrades to this instead of failing the response.
|
|
1536
2332
|
const errorPage = ${errorRender};
|
|
1537
2333
|
|
|
1538
|
-
|
|
1539
|
-
// of its [lang] segment (the default when there is none, or when the segment
|
|
1540
|
-
// names no dictionary: that request 404s in the default language) and the
|
|
1541
|
-
// reading direction that locale implies. The buffered render returns the same
|
|
1542
|
-
// pair; the streaming path needs it BEFORE the shell flushes, which is why
|
|
1543
|
-
// the servers ask for it by pathname.
|
|
2334
|
+
|
|
1544
2335
|
export function docAttrs(pathname) {
|
|
1545
2336
|
for (const route of routes) {
|
|
1546
2337
|
if (!matchRoute(route.pattern, pathname)) continue;
|
|
@@ -1550,7 +2341,7 @@ export function docAttrs(pathname) {
|
|
|
1550
2341
|
const lang = pathname.split('/')[langIdx];
|
|
1551
2342
|
if (isLocale(lang)) return { lang, dir: localeDir(lang) };
|
|
1552
2343
|
}
|
|
1553
|
-
break;
|
|
2344
|
+
break;
|
|
1554
2345
|
}
|
|
1555
2346
|
return { lang: defaultLocale, dir: localeDir(defaultLocale) };
|
|
1556
2347
|
}
|
|
@@ -1563,8 +2354,22 @@ async function renderFallback(pathname, render) {
|
|
|
1563
2354
|
}
|
|
1564
2355
|
|
|
1565
2356
|
export function matchRoute(pattern, pathname) {
|
|
2357
|
+
// Q0 (bug report): one canonical URL per route.
|
|
2358
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
1566
2359
|
const patternParts = pattern.split('/');
|
|
1567
2360
|
const pathParts = pathname.split('/');
|
|
2361
|
+
|
|
2362
|
+
const last = patternParts[patternParts.length - 1];
|
|
2363
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
2364
|
+
const fixed = patternParts.slice(0, -1);
|
|
2365
|
+
if (pathParts.length < fixed.length) return false;
|
|
2366
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
2367
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
2368
|
+
if (fixed[i].startsWith(':')) continue;
|
|
2369
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
2370
|
+
}
|
|
2371
|
+
return true;
|
|
2372
|
+
}
|
|
1568
2373
|
if (patternParts.length !== pathParts.length) return false;
|
|
1569
2374
|
for (let i = 0; i < patternParts.length; i++) {
|
|
1570
2375
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -1573,13 +2378,7 @@ export function matchRoute(pattern, pathname) {
|
|
|
1573
2378
|
return true;
|
|
1574
2379
|
}
|
|
1575
2380
|
|
|
1576
|
-
// Head blocks (one per component in the route chain) are pulled out of the
|
|
1577
|
-
// page html: the shell injects them into <head>, and the client re-applies
|
|
1578
|
-
// them on navigation. Document order is page-first, so the shell's keyed
|
|
1579
|
-
// merge lets a page override its layouts. The EMPTY marker pair stays in the
|
|
1580
|
-
// body so the client's wire() still finds the block: at boot it adopts the
|
|
1581
|
-
// shell-injected elements in place (marked with the same keys, so no
|
|
1582
|
-
// duplicates) and keeps the head reactive.
|
|
2381
|
+
// Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
|
|
1583
2382
|
function extractHead(rendered) {
|
|
1584
2383
|
const head = [];
|
|
1585
2384
|
const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
|
|
@@ -1589,18 +2388,7 @@ function extractHead(rendered) {
|
|
|
1589
2388
|
return { html, head };
|
|
1590
2389
|
}
|
|
1591
2390
|
|
|
1592
|
-
//
|
|
1593
|
-
// selected server action runs first and returns a state patch (e.g.
|
|
1594
|
-
// { guests: [...] }); seeding those keys BEFORE the render makes state()
|
|
1595
|
-
// adopt them, so the response is the page as it looks AFTER the action -
|
|
1596
|
-
// with or without JS. A __action field picks the action by name (default
|
|
1597
|
-
// 'action', the conventional <form method="POST"> target); a click handler
|
|
1598
|
-
// bound to an action ($action('like')) sends the same field.
|
|
1599
|
-
// A route whose render throws degrades to pages/500.rose (status 500) - or
|
|
1600
|
-
// the built-in plain 500 - instead of failing the whole response.
|
|
1601
|
-
// The middleware does NOT run here: the servers run it once per request via
|
|
1602
|
-
// runMiddleware() (which also seeds the request context), so a page render
|
|
1603
|
-
// never re-runs it.
|
|
2391
|
+
// Form: the submitted FormData of a progressive-enhancement POST.
|
|
1604
2392
|
export async function renderPage(pathname, form) {
|
|
1605
2393
|
clearRequestState();
|
|
1606
2394
|
for (const route of routes) {
|
|
@@ -1608,31 +2396,21 @@ export async function renderPage(pathname, form) {
|
|
|
1608
2396
|
const patternParts = route.pattern.split('/');
|
|
1609
2397
|
const pathParts = pathname.split('/');
|
|
1610
2398
|
for (let i = 0; i < patternParts.length; i++) {
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
2399
|
+
const seg = patternParts[i];
|
|
2400
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
2401
|
+
|
|
2402
|
+
|
|
2403
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
1614
2404
|
}
|
|
1615
|
-
//
|
|
1616
|
-
// 404 - the URL is the contract, and rendering the page with fallback
|
|
1617
|
-
// strings would serve duplicate content under a bogus language
|
|
2405
|
+
// I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
|
|
1618
2406
|
const langIdx = patternParts.indexOf(':lang');
|
|
1619
2407
|
if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
|
|
1620
|
-
|
|
1621
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
2408
|
+
return await notFoundPage(pathname);
|
|
1622
2409
|
}
|
|
1623
|
-
|
|
1624
|
-
|
|
2410
|
+
|
|
2411
|
+
|
|
1625
2412
|
const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
|
|
1626
|
-
// The action dispatch. The page's guard (exported
|
|
1627
|
-
// beforeAction) runs FIRST and vetoes with an ActionError - the
|
|
1628
|
-
// action-level permission check. Then the selected action runs and its
|
|
1629
|
-
// return value seeds this render's state, per key, so an incremental
|
|
1630
|
-
// patch ($append and friends) grows a large list by one row instead of
|
|
1631
|
-
// re-sending the whole thing. An ActionError from either half is a
|
|
1632
|
-
// BUSINESS failure: it is seeded as the 'actionError' state, the
|
|
1633
|
-
// response carries its status, and the page renders with the failure
|
|
1634
|
-
// visible (a {#boundary} around the action's widget contains it).
|
|
1635
|
-
// Anything else is a bug and keeps going to the 500 page.
|
|
2413
|
+
// The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
|
|
1636
2414
|
let actionStatus = 0;
|
|
1637
2415
|
if (form && route.actions) {
|
|
1638
2416
|
const actionName = form.get('__action') || 'action';
|
|
@@ -1644,9 +2422,7 @@ export async function renderPage(pathname, form) {
|
|
|
1644
2422
|
if (patch && typeof patch === 'object') {
|
|
1645
2423
|
for (const key of Object.keys(patch)) {
|
|
1646
2424
|
const v = patch[key];
|
|
1647
|
-
// An incremental patch is RECORDED, not applied: the render's
|
|
1648
|
-
// own state declarations apply it, so the delta is relative to
|
|
1649
|
-
// the value the page was going to render anyway.
|
|
2425
|
+
// An incremental patch is RECORDED, not applied: the render's own state declarations apply.
|
|
1650
2426
|
if (v instanceof StateDelta) setStateDelta(key, v);
|
|
1651
2427
|
else setState(key, v);
|
|
1652
2428
|
}
|
|
@@ -1655,6 +2431,11 @@ export async function renderPage(pathname, form) {
|
|
|
1655
2431
|
if (err instanceof ActionError) {
|
|
1656
2432
|
setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
|
|
1657
2433
|
actionStatus = err.code;
|
|
2434
|
+
} else if (err && err.__rosetack === 'redirect') {
|
|
2435
|
+
|
|
2436
|
+
return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
|
|
2437
|
+
} else if (err && err.__rosetack === 'notFound') {
|
|
2438
|
+
return await notFoundPage(pathname);
|
|
1658
2439
|
} else {
|
|
1659
2440
|
throw err;
|
|
1660
2441
|
}
|
|
@@ -1665,32 +2446,27 @@ export async function renderPage(pathname, form) {
|
|
|
1665
2446
|
try {
|
|
1666
2447
|
rendered = extractHead(await route.render([], ''));
|
|
1667
2448
|
} catch (err) {
|
|
2449
|
+
// The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
|
|
2450
|
+
const signal = err && err.__rosetack;
|
|
2451
|
+
if (signal === 'redirect') {
|
|
2452
|
+
return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
|
|
2453
|
+
}
|
|
2454
|
+
if (signal === 'notFound') {
|
|
2455
|
+
return await notFoundPage(pathname);
|
|
2456
|
+
}
|
|
1668
2457
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
1669
2458
|
if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
|
|
1670
2459
|
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
1671
2460
|
}
|
|
1672
2461
|
// __route tells the bootstrap which route this document was rendered for.
|
|
1673
|
-
// A static-file server may serve another route's document (SPA fallback);
|
|
1674
|
-
// the bootstrap then client-renders instead of adopting mismatched DOM.
|
|
1675
2462
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
1676
|
-
//
|
|
1677
|
-
|
|
1678
|
-
// asserted csr = false) - the document ships no runtime, no state
|
|
1679
|
-
// script, zero JavaScript. Every other route keeps the bundle. The
|
|
1680
|
-
// caller passes this straight to the shell as js.
|
|
1681
|
-
// Status is the failed action's code when one failed - the page
|
|
1682
|
-
// rendered fine, so the body is the page with the failure visible, and
|
|
1683
|
-
// the status says what happened (a 403 from the guard, a 422 from a
|
|
1684
|
-
// validation action). 200 otherwise.
|
|
1685
|
-
// Lang/dir are the document's <html> attributes - the locale
|
|
1686
|
-
// this route rendered in, and its reading direction.
|
|
1687
|
-
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
|
|
2463
|
+
// Csr ( auto since #29): false when the compiler found nothing in the route's chain that needs the client (or the route asserted csr = false) .
|
|
2464
|
+
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
|
|
1688
2465
|
}
|
|
1689
2466
|
}
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
2467
|
+
|
|
2468
|
+
|
|
2469
|
+
return await notFoundPage(pathname);
|
|
1694
2470
|
}
|
|
1695
2471
|
|
|
1696
2472
|
// Would renderPageStream handle this path? (matched route = stream, anything
|
|
@@ -1698,21 +2474,20 @@ export async function renderPage(pathname, form) {
|
|
|
1698
2474
|
export function canStream(pathname) {
|
|
1699
2475
|
return routes.some((route) => {
|
|
1700
2476
|
if (!matchRoute(route.pattern, pathname)) return false;
|
|
1701
|
-
//
|
|
1702
|
-
// streamed response cannot change its status - so it takes the buffered
|
|
1703
|
-
// path (renderPage returns the real 404), never the streaming one
|
|
2477
|
+
// I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
|
|
1704
2478
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
1705
2479
|
return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
|
|
1706
2480
|
});
|
|
1707
2481
|
}
|
|
1708
2482
|
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
2483
|
+
|
|
2484
|
+
export function shellOff(pathname) {
|
|
2485
|
+
return routes.some(
|
|
2486
|
+
(route) => route.shell === false && matchRoute(route.pattern, pathname),
|
|
2487
|
+
);
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
// === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
|
|
1716
2491
|
export function isApi(pathname) {
|
|
1717
2492
|
return pathname === '/api' || pathname.startsWith('/api/');
|
|
1718
2493
|
}
|
|
@@ -1736,7 +2511,25 @@ export async function handleApi(method, pathname, request) {
|
|
|
1736
2511
|
headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
|
|
1737
2512
|
});
|
|
1738
2513
|
}
|
|
1739
|
-
|
|
2514
|
+
try {
|
|
2515
|
+
return toResponse(await fn(request));
|
|
2516
|
+
} catch (err) {
|
|
2517
|
+
|
|
2518
|
+
const signal = err && err.__rosetack;
|
|
2519
|
+
if (signal === 'redirect') {
|
|
2520
|
+
return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
|
|
2521
|
+
status: err.status ?? 307,
|
|
2522
|
+
headers: { 'content-type': 'application/json', location: err.path },
|
|
2523
|
+
});
|
|
2524
|
+
}
|
|
2525
|
+
if (signal === 'notFound') {
|
|
2526
|
+
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
2527
|
+
status: 404,
|
|
2528
|
+
headers: { 'content-type': 'application/json' },
|
|
2529
|
+
});
|
|
2530
|
+
}
|
|
2531
|
+
throw err;
|
|
2532
|
+
}
|
|
1740
2533
|
}
|
|
1741
2534
|
}
|
|
1742
2535
|
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
@@ -1745,18 +2538,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
1745
2538
|
});
|
|
1746
2539
|
}
|
|
1747
2540
|
|
|
1748
|
-
// === Streaming SSR ===
|
|
1749
|
-
// The static shell (doctype, <head>, body + container open) flushes BEFORE
|
|
1750
|
-
// the - possibly slow - render completes: the first byte leaves in
|
|
1751
|
-
// microseconds instead of after every $data resolves. The route HTML, the
|
|
1752
|
-
// state script, and the inlined bundle follow as later chunks of one chunked
|
|
1753
|
-
// response - still exactly one request.
|
|
1754
|
-
// The route's <head> tags are NOT in the streamed document: the client
|
|
1755
|
-
// applies them at boot from the body's head markers, so JS users see the
|
|
1756
|
-
// correct head immediately; no-JS consumers of streamed responses get the
|
|
1757
|
-
// static shell head (prerendered files stay complete documents).
|
|
1758
|
-
// Returns 200 (matched; a render throw degrades to the error-page body) or
|
|
1759
|
-
// 404 (unmatched - nothing written, so the caller can still buffer).
|
|
2541
|
+
// === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
|
|
1760
2542
|
export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
1761
2543
|
clearRequestState();
|
|
1762
2544
|
for (const route of routes) {
|
|
@@ -1764,9 +2546,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
1764
2546
|
const patternParts = route.pattern.split('/');
|
|
1765
2547
|
const pathParts = pathname.split('/');
|
|
1766
2548
|
for (let i = 0; i < patternParts.length; i++) {
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
2549
|
+
const seg = patternParts[i];
|
|
2550
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
2551
|
+
|
|
2552
|
+
|
|
2553
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
1770
2554
|
}
|
|
1771
2555
|
// i18n: an unknown locale must 404 BEFORE the shell flushes - a
|
|
1772
2556
|
// streamed response cannot change its status afterwards
|
|
@@ -1777,23 +2561,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
1777
2561
|
try {
|
|
1778
2562
|
html = extractHead(await route.render([], '')).html;
|
|
1779
2563
|
} catch (err) {
|
|
1780
|
-
|
|
1781
|
-
// (the status stays 200 - a real 500 needs the buffered path, which
|
|
1782
|
-
// the server picks for routes known-broken at build time)
|
|
2564
|
+
|
|
1783
2565
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
1784
2566
|
html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
|
|
1785
2567
|
}
|
|
1786
2568
|
write(html);
|
|
1787
|
-
//
|
|
1788
|
-
// ends here - no state script, no inlined bundle. (The servers keep
|
|
1789
|
-
// these routes off the streaming path so their <head> is complete;
|
|
1790
|
-
// this is the correctness floor if one streams anyway.)
|
|
2569
|
+
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
1791
2570
|
if (route.csr === false) {
|
|
1792
2571
|
write('</div>\\n</body>\\n</html>');
|
|
1793
2572
|
return 200;
|
|
1794
2573
|
}
|
|
1795
2574
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
1796
|
-
|
|
2575
|
+
// P1-6 (bug report): the JSON data block is embedded in the document.
|
|
2576
|
+
const stateSafe = state.replace(/</g, '\\\\u003c');
|
|
2577
|
+
write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
|
|
1797
2578
|
return 200;
|
|
1798
2579
|
}
|
|
1799
2580
|
}
|
|
@@ -1813,55 +2594,54 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
1813
2594
|
const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
|
|
1814
2595
|
const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
|
|
1815
2596
|
const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
|
|
2597
|
+
const vitalsOn = compiled.some((c) => c.vitals === true);
|
|
2598
|
+
const vitalsBlock = vitalsOn ? `
|
|
2599
|
+
// the app asked for web-vitals - measure once, at boot, and let the
|
|
2600
|
+
// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
|
|
2601
|
+
reportVitals();
|
|
2602
|
+
` : "";
|
|
1816
2603
|
const hasLang = infos.some((i) => i.pattern.includes(":lang"));
|
|
1817
2604
|
const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
|
|
1818
2605
|
// client-side navigation cannot leave stale (screen readers and CSS
|
|
1819
2606
|
// logical properties both read it). A route with no [lang] segment
|
|
1820
2607
|
// returns to the default locale, and a bogus segment falls back to it
|
|
1821
2608
|
// too, exactly like the server's docAttrs.
|
|
2609
|
+
// Only when this container IS the document's app root. A mount
|
|
2610
|
+
// (dist/mount.js) renders into a foreign page, whose language and
|
|
2611
|
+
// direction belong to the host, not to the mounted route.
|
|
1822
2612
|
const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
|
|
1823
2613
|
const known = !seg || isLocale(seg);
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
2614
|
+
if (container === document.getElementById('app')) {
|
|
2615
|
+
const docLang = known && seg ? seg : __defLocale;
|
|
2616
|
+
document.documentElement.lang = docLang;
|
|
2617
|
+
const docDir = localeDir(docLang);
|
|
2618
|
+
if (docDir) document.documentElement.setAttribute('dir', docDir);
|
|
2619
|
+
else document.documentElement.removeAttribute('dir');
|
|
2620
|
+
}
|
|
1829
2621
|
if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
1830
2622
|
const clientEntry = `
|
|
1831
2623
|
${clientImports}
|
|
1832
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir } from './runtime.js';
|
|
1833
|
-
|
|
1834
|
-
//
|
|
1835
|
-
// renders any PRELOADED locale from the bundle, so switching language costs
|
|
1836
|
-
// zero requests (the same bet as the inlined route table). a locale
|
|
1837
|
-
// the app left out of the preload (i18n.preload in rosetack.config.js) is a
|
|
1838
|
-
// pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
|
|
1839
|
-
// on first use - one request per language per session, then it renders from
|
|
1840
|
-
// memory like any other. The default build preloads everything and ships no
|
|
1841
|
-
// packs at all.
|
|
2624
|
+
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } from './runtime.js';
|
|
2625
|
+
|
|
2626
|
+
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
1842
2627
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
1843
2628
|
setLocalePacks(${JSON.stringify(packed)});
|
|
1844
2629
|
${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
|
|
1845
2630
|
// follow a route that carries no [lang] segment (a non-i18n page)
|
|
1846
2631
|
const __defLocale = '${defaultLocale}';` : ""}
|
|
1847
|
-
|
|
1848
|
-
//
|
|
1849
|
-
//
|
|
1850
|
-
|
|
2632
|
+
${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
|
|
2633
|
+
// reportVitals alive through minification and tree-shaking; the call is one
|
|
2634
|
+
// statement at boot, before the first render.
|
|
2635
|
+
import { reportVitals } from './runtime.js';` : ""}
|
|
2636
|
+
// The two pack doors, re-exported for an app that wants to warm a language before its visitor asks for it (ensureLocale) or to feed a dictionary.
|
|
1851
2637
|
export { ensureLocale, loadLocale } from './runtime.js';
|
|
2638
|
+
${vitalsBlock}
|
|
1852
2639
|
|
|
1853
2640
|
const routes = [
|
|
1854
2641
|
${clientRoutes}
|
|
1855
2642
|
];
|
|
1856
2643
|
|
|
1857
|
-
// === Mode B: lazy route chunks ===
|
|
1858
|
-
// Split mode's registry entries arrive without a render function: loadChain
|
|
1859
|
-
// loads the route's module graph (the page plus its layouts, one chunk per
|
|
1860
|
-
// module, the shared runtime in its own vendor chunk) in parallel and
|
|
1861
|
-
// composes it at runtime - the exact nesting compose() built at compile
|
|
1862
|
-
// time for inline mode. getRender memoizes the composed function on the
|
|
1863
|
-
// entry, so a chunk loads once per session; inline mode's entries are the
|
|
1864
|
-
// render functions themselves, so the helper is a pass-through there.
|
|
2644
|
+
// === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
|
|
1865
2645
|
const loadChain = async (loaders) => {
|
|
1866
2646
|
const mods = await Promise.all(loaders.map((load) => load()));
|
|
1867
2647
|
let expr = (closes, children) => mods[0].render(closes, children);
|
|
@@ -1877,36 +2657,62 @@ const getRender = async (route) => {
|
|
|
1877
2657
|
return (route.render ??= (await route.load()).render);
|
|
1878
2658
|
};
|
|
1879
2659
|
|
|
1880
|
-
// pages
|
|
1881
|
-
const
|
|
2660
|
+
// Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
|
|
2661
|
+
const notFoundRoutes = ${notFoundTable};
|
|
2662
|
+
const notFoundFor = (pathname) => {
|
|
2663
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
2664
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
2665
|
+
}
|
|
2666
|
+
return null;
|
|
2667
|
+
};
|
|
1882
2668
|
|
|
1883
|
-
//
|
|
1884
|
-
// whose render throws on the client degrades to this instead of breaking
|
|
1885
|
-
// navigation.
|
|
2669
|
+
// Pages/500.rose (with its layouts) or null -> built-in plain 500: a route whose render throws on the client degrades to this instead of breaking.
|
|
1886
2670
|
const errorPage = ${errorRender};
|
|
1887
2671
|
|
|
1888
2672
|
// Paint a fallback page (404/500) into the container, wired like any render.
|
|
1889
|
-
async function paintFallback(container, page, builtin) {
|
|
1890
|
-
|
|
1891
|
-
clearRequestState();
|
|
2673
|
+
async function paintFallback(container, page, builtin, keepState = false) {
|
|
2674
|
+
if (!keepState) __navReset(container);
|
|
1892
2675
|
clearMounts(); // a failed render leaves stale mounts behind
|
|
1893
2676
|
// inline mode passes the render itself; split mode passes a loader
|
|
1894
2677
|
const render = page ? await getRender(page) : null;
|
|
1895
2678
|
if (render) {
|
|
1896
2679
|
const closes = [];
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
2680
|
+
await __withOwner(container, async () => {
|
|
2681
|
+
const html = await render(closes, '');
|
|
2682
|
+
container.innerHTML = html;
|
|
2683
|
+
wire(container, closes);
|
|
2684
|
+
bindEvents(container);
|
|
2685
|
+
flushMounts();
|
|
2686
|
+
});
|
|
1902
2687
|
return;
|
|
1903
2688
|
}
|
|
1904
2689
|
container.innerHTML = builtin;
|
|
1905
2690
|
}
|
|
1906
2691
|
|
|
2692
|
+
|
|
2693
|
+
export async function startNotFound(container, pathname) {
|
|
2694
|
+
const el = document.getElementById('__rosetack_state');
|
|
2695
|
+
if (el) resumeState(el.textContent);
|
|
2696
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
|
|
2697
|
+
}
|
|
2698
|
+
|
|
1907
2699
|
export function matchRoute(pattern, pathname) {
|
|
2700
|
+
// Q0 (bug report): one canonical URL per route.
|
|
2701
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
1908
2702
|
const patternParts = pattern.split('/');
|
|
1909
2703
|
const pathParts = pathname.split('/');
|
|
2704
|
+
|
|
2705
|
+
const last = patternParts[patternParts.length - 1];
|
|
2706
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
2707
|
+
const fixed = patternParts.slice(0, -1);
|
|
2708
|
+
if (pathParts.length < fixed.length) return false;
|
|
2709
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
2710
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
2711
|
+
if (fixed[i].startsWith(':')) continue;
|
|
2712
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
2713
|
+
}
|
|
2714
|
+
return true;
|
|
2715
|
+
}
|
|
1910
2716
|
if (patternParts.length !== pathParts.length) return false;
|
|
1911
2717
|
for (let i = 0; i < patternParts.length; i++) {
|
|
1912
2718
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -1915,78 +2721,64 @@ export function matchRoute(pattern, pathname) {
|
|
|
1915
2721
|
return true;
|
|
1916
2722
|
}
|
|
1917
2723
|
|
|
1918
|
-
// === Link prefetch ===
|
|
1919
|
-
// Hover / focus / touch an internal link and the target route renders NOW -
|
|
1920
|
-
// $data included - against a throwaway signal map. The click that follows
|
|
1921
|
-
// paints from the cached HTML: no await, no request, no spinner. Other
|
|
1922
|
-
// frameworks prefetch data only; rosetack prefetches the whole render because
|
|
1923
|
-
// the inlined bundle already contains every route.
|
|
1924
|
-
// Trade-off: the cache holds either a result or the in-flight promise (dedupes
|
|
1925
|
-
// hover storms); one isolated render runs at a time so signal-map swapping
|
|
1926
|
-
// stays correct without any merging logic. Entries are single-use: a consumed
|
|
1927
|
-
// entry disappears from the cache, which is also how tests observe a hit.
|
|
1928
|
-
// P1, three guards for link-heavy pages:
|
|
1929
|
-
// 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
|
|
1930
|
-
// 'viewport' | 'all'" (root layout); 'all' is the original behavior.
|
|
1931
|
-
// Trade-off: app-global, not per-route - per-route would carry the mode
|
|
1932
|
-
// in each document's shell.
|
|
1933
|
-
// 2. budget - renders are serialized by the queue, so "concurrency" is 1;
|
|
1934
|
-
// the budget caps the QUEUE: a hover storm past it drops the excess
|
|
1935
|
-
// instead of rendering fifty routes nobody clicks.
|
|
1936
|
-
// 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
|
|
1937
|
-
// is evicted first (Map iteration order; entries are single-use, so
|
|
1938
|
-
// insertion order IS the recency order).
|
|
2724
|
+
// === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
|
|
1939
2725
|
let prefetchMode = ${JSON.stringify(prefetchMode)};
|
|
1940
2726
|
export function setPrefetchMode(mode) { prefetchMode = mode; }
|
|
1941
2727
|
const PREFETCH_BUDGET = 8;
|
|
1942
2728
|
const PREFETCH_MAX_CACHED = 4;
|
|
1943
|
-
const prefetchCache = new Map();
|
|
2729
|
+
const prefetchCache = new Map();
|
|
1944
2730
|
let prefetchQueue = Promise.resolve();
|
|
1945
2731
|
let prefetchPending = 0;
|
|
1946
2732
|
|
|
1947
|
-
|
|
1948
|
-
// a runtime pack (i18n.preload) is awaited HERE - the one place every client
|
|
1949
|
-
// render path goes through (navigation, prefetch, action adopt) - so a packed
|
|
1950
|
-
// locale costs one request per session and then renders from memory. A
|
|
1951
|
-
// preloaded locale (the default: every dictionary inline) resolves without
|
|
1952
|
-
// touching the network, so the common path stays synchronous in spirit.
|
|
2733
|
+
|
|
1953
2734
|
async function applyParams(route, pathname) {
|
|
1954
2735
|
const patternParts = route.pattern.split('/');
|
|
1955
2736
|
const pathParts = pathname.split('/');
|
|
1956
2737
|
for (let i = 0; i < patternParts.length; i++) {
|
|
1957
|
-
|
|
2738
|
+
const seg = patternParts[i];
|
|
2739
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
2740
|
+
|
|
2741
|
+
|
|
2742
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
1958
2743
|
}
|
|
1959
2744
|
const langIdx = patternParts.indexOf(':lang');
|
|
1960
2745
|
if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
|
|
1961
2746
|
}
|
|
1962
2747
|
|
|
2748
|
+
|
|
2749
|
+
function __netOk() {
|
|
2750
|
+
const c = navigator.connection;
|
|
2751
|
+
if (!c) return true;
|
|
2752
|
+
if (c.saveData) return false;
|
|
2753
|
+
const t = c.effectiveType;
|
|
2754
|
+
return t !== 'slow-2g' && t !== '2g';
|
|
2755
|
+
}
|
|
2756
|
+
|
|
1963
2757
|
export function prefetch(pathname, source = 'hover') {
|
|
1964
2758
|
if (prefetchMode === 'off') return;
|
|
1965
2759
|
if (prefetchMode === 'hover' && source !== 'hover') return;
|
|
1966
2760
|
if (prefetchMode === 'viewport' && source !== 'viewport') return;
|
|
2761
|
+
if (!__netOk()) return; // save-data / 2g: no bytes before the click
|
|
1967
2762
|
if (prefetchCache.has(pathname)) return;
|
|
1968
|
-
if (pathname === location.pathname) return;
|
|
2763
|
+
if (pathname === location.pathname) return;
|
|
1969
2764
|
const route = routes.find((r) => matchRoute(r.pattern, pathname));
|
|
1970
2765
|
if (!route) return;
|
|
1971
|
-
if (prefetchPending >= PREFETCH_BUDGET) return; //
|
|
2766
|
+
if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
|
|
2767
|
+
const qi = pathname.indexOf('?');
|
|
2768
|
+
const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
|
|
1972
2769
|
const p = prefetchQueue.then(async () => {
|
|
1973
2770
|
try {
|
|
1974
|
-
|
|
1975
|
-
// queued and the onCleanup disposers it registered: the paint that
|
|
1976
|
-
// consumes this entry replays the mounts after wiring and adopts the
|
|
1977
|
-
// cleanups, so the prefetched route's timers are disposed on the next
|
|
1978
|
-
// navigation like any live route's
|
|
2771
|
+
setPrefetchOverride(qOverride);
|
|
2772
|
+
// The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
|
|
1979
2773
|
const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
|
|
1980
2774
|
await applyParams(route, pathname); // a packed locale's dictionary lands before the render
|
|
1981
2775
|
const closes = [];
|
|
1982
|
-
const render = await getRender(route);
|
|
2776
|
+
const render = await getRender(route);
|
|
1983
2777
|
const html = await render(closes, '');
|
|
1984
2778
|
return { html, closes };
|
|
1985
2779
|
});
|
|
1986
2780
|
const entry = { ...result, state, mounts, cleanups };
|
|
1987
|
-
prefetchCache.set(pathname, entry); //
|
|
1988
|
-
// evict oldest-first; in-flight promises are never evicted (evicting
|
|
1989
|
-
// one would only force a duplicate render)
|
|
2781
|
+
prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
|
|
1990
2782
|
while (prefetchCache.size > PREFETCH_MAX_CACHED) {
|
|
1991
2783
|
const oldest = prefetchCache.keys().next().value;
|
|
1992
2784
|
if (prefetchCache.get(oldest) instanceof Promise) break;
|
|
@@ -1994,9 +2786,10 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
1994
2786
|
}
|
|
1995
2787
|
return entry;
|
|
1996
2788
|
} catch {
|
|
1997
|
-
prefetchCache.delete(pathname);
|
|
2789
|
+
prefetchCache.delete(pathname);
|
|
1998
2790
|
return null;
|
|
1999
2791
|
} finally {
|
|
2792
|
+
setPrefetchOverride(null);
|
|
2000
2793
|
prefetchPending--;
|
|
2001
2794
|
}
|
|
2002
2795
|
});
|
|
@@ -2006,13 +2799,10 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
2006
2799
|
}
|
|
2007
2800
|
|
|
2008
2801
|
export function prefetchStats() {
|
|
2009
|
-
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
|
|
2802
|
+
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
|
|
2010
2803
|
}
|
|
2011
2804
|
|
|
2012
|
-
// One delegated listener per event type on the app container: survives DOM
|
|
2013
|
-
// swaps and cloned blocks, so handlers never need re-binding. A handler
|
|
2014
|
-
// compiled from a server action (data-on-*="$action:name") dispatches to
|
|
2015
|
-
// $action instead of the local handler registry.
|
|
2805
|
+
// One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
|
|
2016
2806
|
const DELEGATED = ['click', 'input', 'change', 'submit'];
|
|
2017
2807
|
function bindEvents(container) {
|
|
2018
2808
|
if (container.__rosetack_bound) return;
|
|
@@ -2029,41 +2819,64 @@ function bindEvents(container) {
|
|
|
2029
2819
|
}
|
|
2030
2820
|
}
|
|
2031
2821
|
|
|
2032
|
-
// === Server actions from any event ===
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
async function postForm(body) {
|
|
2039
|
-
const res = await fetch(location.pathname, { method: 'POST', body });
|
|
2822
|
+
// === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
|
|
2823
|
+
async function postForm(body, container, pathname) {
|
|
2824
|
+
|
|
2825
|
+
const box = container || document.getElementById('app');
|
|
2826
|
+
const route = pathname || location.pathname;
|
|
2827
|
+
const res = await fetch(route, { method: 'POST', body });
|
|
2040
2828
|
const html = await res.text();
|
|
2041
2829
|
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
2042
2830
|
const next = doc.getElementById('app');
|
|
2043
2831
|
const st = doc.getElementById('__rosetack_state');
|
|
2044
2832
|
const paint = () => {
|
|
2045
|
-
|
|
2046
|
-
adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
|
|
2833
|
+
adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
|
|
2047
2834
|
};
|
|
2048
2835
|
if (document.startViewTransition) document.startViewTransition(paint);
|
|
2049
2836
|
else paint();
|
|
2050
2837
|
}
|
|
2051
2838
|
|
|
2052
|
-
// Call a page's server action by name from any event handler:
|
|
2053
|
-
// <button on:click={like}> compiles to $action('like'). Without JS the
|
|
2054
|
-
// binding is inert - the progressive-enhancement story stays with forms.
|
|
2839
|
+
// Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
|
|
2055
2840
|
export async function $action(name, e) {
|
|
2056
2841
|
if (e && e.preventDefault) e.preventDefault();
|
|
2057
2842
|
const body = new FormData();
|
|
2058
2843
|
body.append('__action', name);
|
|
2059
|
-
|
|
2844
|
+
// An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
|
|
2845
|
+
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
2846
|
+
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
2060
2847
|
}
|
|
2061
2848
|
|
|
2062
2849
|
export { postForm };
|
|
2063
2850
|
|
|
2064
|
-
//
|
|
2065
|
-
|
|
2066
|
-
|
|
2851
|
+
// The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
|
|
2852
|
+
export { serializeState };
|
|
2853
|
+
|
|
2854
|
+
// Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
|
|
2855
|
+
|
|
2856
|
+
|
|
2857
|
+
function __ownsDoc(container) {
|
|
2858
|
+
return container === document.getElementById('app');
|
|
2859
|
+
}
|
|
2860
|
+
function __navReset(container) {
|
|
2861
|
+
if (__ownsDoc(container)) {
|
|
2862
|
+
resetEffects();
|
|
2863
|
+
clearRequestState();
|
|
2864
|
+
} else {
|
|
2865
|
+
resetContainerFx(container);
|
|
2866
|
+
}
|
|
2867
|
+
}
|
|
2868
|
+
// Attribute everything a render creates (state keys, effects, onCleanups) to
|
|
2869
|
+
// its container. The document path sets no owner and keeps the global sets.
|
|
2870
|
+
async function __withOwner(container, fn) {
|
|
2871
|
+
if (__ownsDoc(container)) return fn();
|
|
2872
|
+
setFxOwner(container);
|
|
2873
|
+
try {
|
|
2874
|
+
return await fn();
|
|
2875
|
+
} finally {
|
|
2876
|
+
setFxOwner(null);
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
|
|
2067
2880
|
export async function start(container, pathname, initial) {
|
|
2068
2881
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2069
2882
|
if (initial) {
|
|
@@ -2072,104 +2885,110 @@ export async function start(container, pathname, initial) {
|
|
|
2072
2885
|
}
|
|
2073
2886
|
for (const route of routes) {
|
|
2074
2887
|
if (matchRoute(route.pattern, pathname)) {
|
|
2075
|
-
//
|
|
2076
|
-
// (before the prefetch check: a cached entry for a bogus locale is
|
|
2077
|
-
// discarded, never painted)
|
|
2888
|
+
// I18n: an unknown locale paints the 404 page, same as the server (before the prefetch check: a cached entry for a bogus locale is discarded).
|
|
2078
2889
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
2079
2890
|
${langDirBlock}
|
|
2080
|
-
await paintFallback(container,
|
|
2891
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2081
2892
|
return;
|
|
2082
2893
|
}
|
|
2083
|
-
// Prefetched on hover/focus/touch: the render already ran, so paint its
|
|
2084
|
-
// HTML and adopt its signal entries - events then patch the very nodes
|
|
2085
|
-
// we wire, and no $data re-runs on click.
|
|
2894
|
+
// Prefetched on hover/focus/touch: the render already ran, so paint its HTML and adopt its signal entries - events then patch the very nodes we.
|
|
2086
2895
|
let hit = initial ? undefined : prefetchCache.get(pathname);
|
|
2087
2896
|
if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
|
|
2088
2897
|
if (hit) {
|
|
2089
|
-
prefetchCache.delete(pathname);
|
|
2090
|
-
|
|
2898
|
+
prefetchCache.delete(pathname);
|
|
2899
|
+
__navReset(container);
|
|
2091
2900
|
restoreState(hit.state);
|
|
2092
2901
|
container.innerHTML = hit.html;
|
|
2093
|
-
|
|
2902
|
+
await __withOwner(container, () => {
|
|
2903
|
+
wire(container, hit.closes);
|
|
2904
|
+
bindEvents(container);
|
|
2905
|
+
hit.mounts.forEach((fn) => fn());
|
|
2906
|
+
adoptCleanups(hit.cleanups);
|
|
2907
|
+
});
|
|
2908
|
+
return;
|
|
2909
|
+
}
|
|
2910
|
+
if (!initial) __navReset(container);
|
|
2911
|
+
let broken = false;
|
|
2912
|
+
let signal = null;
|
|
2913
|
+
await __withOwner(container, async () => {
|
|
2914
|
+
await applyParams(route, pathname);
|
|
2915
|
+
const closes = [];
|
|
2916
|
+
let html;
|
|
2917
|
+
try {
|
|
2918
|
+
const render = await getRender(route);
|
|
2919
|
+
html = await render(closes, '');
|
|
2920
|
+
} catch (err) {
|
|
2921
|
+
|
|
2922
|
+
if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
|
|
2923
|
+
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
2924
|
+
|
|
2925
|
+
|
|
2926
|
+
broken = true;
|
|
2927
|
+
return;
|
|
2928
|
+
}
|
|
2929
|
+
if (!initial) container.innerHTML = html;
|
|
2930
|
+
wire(container, closes);
|
|
2094
2931
|
bindEvents(container);
|
|
2095
|
-
|
|
2096
|
-
|
|
2932
|
+
flushMounts();
|
|
2933
|
+
});
|
|
2934
|
+
if (signal === 'notFound') {
|
|
2935
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2097
2936
|
return;
|
|
2098
2937
|
}
|
|
2099
|
-
if (
|
|
2100
|
-
|
|
2101
|
-
|
|
2938
|
+
if (signal) {
|
|
2939
|
+
location.href = signal;
|
|
2940
|
+
return;
|
|
2102
2941
|
}
|
|
2103
|
-
|
|
2104
|
-
const closes = [];
|
|
2105
|
-
let html;
|
|
2106
|
-
try {
|
|
2107
|
-
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
2108
|
-
html = await render(closes, '');
|
|
2109
|
-
} catch {
|
|
2110
|
-
// the route itself is broken: degrade to pages/500.rose (or the
|
|
2111
|
-
// built-in plain 500) instead of leaving the container empty
|
|
2942
|
+
if (broken) {
|
|
2112
2943
|
await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
2113
|
-
return;
|
|
2114
2944
|
}
|
|
2115
|
-
if (!initial) container.innerHTML = html;
|
|
2116
|
-
wire(container, closes);
|
|
2117
|
-
bindEvents(container);
|
|
2118
|
-
flushMounts();
|
|
2119
2945
|
return;
|
|
2120
2946
|
}
|
|
2121
2947
|
}
|
|
2122
|
-
//
|
|
2123
|
-
|
|
2124
|
-
//
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2948
|
+
// Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
|
|
2949
|
+
${hasLang ? ` // the same app-root gate as above - a mount never touches the
|
|
2950
|
+
// host document's language or direction.
|
|
2951
|
+
if (container === document.getElementById('app')) {
|
|
2952
|
+
document.documentElement.lang = __defLocale;
|
|
2953
|
+
document.documentElement.removeAttribute('dir');
|
|
2954
|
+
}` : ""}
|
|
2955
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2128
2956
|
}
|
|
2129
2957
|
|
|
2130
|
-
// Adopt a server-rendered response in place - the JS-enabled half of
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
export async function adopt(container, html, stateJson) {
|
|
2137
|
-
resetEffects();
|
|
2138
|
-
clearRequestState();
|
|
2958
|
+
// Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
|
|
2959
|
+
export async function adopt(container, html, stateJson, pathname) {
|
|
2960
|
+
|
|
2961
|
+
|
|
2962
|
+
const route0 = pathname || location.pathname;
|
|
2963
|
+
__navReset(container);
|
|
2139
2964
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2140
2965
|
resumeState(stateJson);
|
|
2141
2966
|
container.innerHTML = html;
|
|
2142
|
-
|
|
2967
|
+
|
|
2143
2968
|
const st = document.getElementById('__rosetack_state');
|
|
2144
2969
|
if (st) st.textContent = stateJson;
|
|
2145
2970
|
for (const route of routes) {
|
|
2146
|
-
if (matchRoute(route.pattern,
|
|
2147
|
-
await
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2971
|
+
if (matchRoute(route.pattern, route0)) {
|
|
2972
|
+
await __withOwner(container, async () => {
|
|
2973
|
+
await applyParams(route, route0);
|
|
2974
|
+
const closes = [];
|
|
2975
|
+
try {
|
|
2976
|
+
const render = await getRender(route);
|
|
2977
|
+
await render(closes, '');
|
|
2978
|
+
} catch {
|
|
2979
|
+
|
|
2980
|
+
|
|
2981
|
+
return;
|
|
2982
|
+
}
|
|
2983
|
+
wire(container, closes);
|
|
2984
|
+
bindEvents(container);
|
|
2985
|
+
flushMounts();
|
|
2986
|
+
});
|
|
2160
2987
|
return;
|
|
2161
2988
|
}
|
|
2162
2989
|
}
|
|
2163
2990
|
}
|
|
2164
|
-
// === refresh() implementation ===
|
|
2165
|
-
// Re-render the current route in place: the client half of router.refresh()
|
|
2166
|
-
// (a router refresh) / (a full invalidation). Same machinery as a client-side
|
|
2167
|
-
// navigation to the current path - $data re-runs, state re-seeds from the
|
|
2168
|
-
// fresh render, wire() patches the marked nodes - but a refresh never lands
|
|
2169
|
-
// a prefetch entry: a hover from a minute ago is exactly what it exists to
|
|
2170
|
-
// bypass. Zero requests: the render (and its $data) runs in the page.
|
|
2171
|
-
// Trade-off: state resets like navigation (no per-key retention); add
|
|
2172
|
-
// retention when an app needs refresh-without-losing-input.
|
|
2991
|
+
// === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
|
|
2173
2992
|
setRefreshHook(async () => {
|
|
2174
2993
|
prefetchCache.delete(location.pathname);
|
|
2175
2994
|
await start(document.getElementById('app'), location.pathname, false);
|
|
@@ -2203,26 +3022,44 @@ setRefreshHook(async () => {
|
|
|
2203
3022
|
...TS_LOADER
|
|
2204
3023
|
});
|
|
2205
3024
|
}
|
|
3025
|
+
await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
|
|
2206
3026
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
2207
3027
|
const publicDir = path.join(root, "public");
|
|
2208
3028
|
if (fs.existsSync(publicDir)) {
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
await Promise.all(
|
|
2213
|
-
assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
|
|
2214
|
-
);
|
|
3029
|
+
await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
|
|
3030
|
+
const favicon = path.join(publicDir, "favicon.ico");
|
|
3031
|
+
if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
|
|
2215
3032
|
}
|
|
2216
3033
|
console.log("rosetack zero-JS report:");
|
|
2217
3034
|
for (const line of buildReport(infos, compiled)) console.log(" " + line);
|
|
3035
|
+
const warnGroups = /* @__PURE__ */ new Map();
|
|
2218
3036
|
for (const { info, i } of pages) {
|
|
2219
3037
|
if (!routeShipsNoJs(infos, compiled, i)) continue;
|
|
2220
3038
|
for (const ci of [i, ...layoutsOf(infos, i)]) {
|
|
2221
3039
|
for (const w of compiled[ci].jsWarnings ?? []) {
|
|
2222
|
-
|
|
3040
|
+
let g = warnGroups.get(w);
|
|
3041
|
+
if (!g) {
|
|
3042
|
+
g = { why: w, files: /* @__PURE__ */ new Map() };
|
|
3043
|
+
warnGroups.set(w, g);
|
|
3044
|
+
}
|
|
3045
|
+
const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
|
|
3046
|
+
let routes = g.files.get(file);
|
|
3047
|
+
if (!routes) {
|
|
3048
|
+
routes = /* @__PURE__ */ new Set();
|
|
3049
|
+
g.files.set(file, routes);
|
|
3050
|
+
}
|
|
3051
|
+
routes.add(info.routePath);
|
|
2223
3052
|
}
|
|
2224
3053
|
}
|
|
2225
3054
|
}
|
|
3055
|
+
for (const g of warnGroups.values()) {
|
|
3056
|
+
const allRoutes = /* @__PURE__ */ new Set();
|
|
3057
|
+
for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
|
|
3058
|
+
const parts = [...g.files.entries()].sort((a, b) => b[1].size - a[1].size).map(([file, routes]) => `${file} (${routes.size === 1 ? [...routes][0] : `${routes.size} routes`})`);
|
|
3059
|
+
const shown = parts.slice(0, 4).join(", ");
|
|
3060
|
+
const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
|
|
3061
|
+
console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
|
|
3062
|
+
}
|
|
2226
3063
|
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
2227
3064
|
}
|
|
2228
3065
|
async function scanRoseFiles(root) {
|
|
@@ -2267,15 +3104,21 @@ function getRouteInfo(filePath, root) {
|
|
|
2267
3104
|
const base = path.posix.basename(withoutExt);
|
|
2268
3105
|
const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
|
|
2269
3106
|
const isLayout = !isComponent && base === "_layout";
|
|
2270
|
-
const isNotFound = !isComponent && base === "404";
|
|
3107
|
+
const isNotFound = !isComponent && (base === "404" || base === "_notfound");
|
|
2271
3108
|
const isError = !isComponent && base === "500";
|
|
2272
3109
|
const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
|
|
2273
3110
|
const isMiddleware = !isComponent && withoutExt === "_middleware";
|
|
2274
|
-
let parts = withoutExt.split("/").filter((p) => p !== "_layout");
|
|
3111
|
+
let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
|
|
2275
3112
|
if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
|
|
2276
|
-
const
|
|
2277
|
-
|
|
2278
|
-
)
|
|
3113
|
+
const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
|
|
3114
|
+
const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
|
|
3115
|
+
const routeParts = parts.map((part) => {
|
|
3116
|
+
const optional = OPTIONAL_CATCH_ALL.exec(part);
|
|
3117
|
+
if (optional) return `**${optional[1]}`;
|
|
3118
|
+
const catchAll = CATCH_ALL.exec(part);
|
|
3119
|
+
if (catchAll) return `*${catchAll[1]}`;
|
|
3120
|
+
return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
|
|
3121
|
+
});
|
|
2279
3122
|
let routePath;
|
|
2280
3123
|
if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
|
|
2281
3124
|
routePath = "/";
|
|
@@ -2286,7 +3129,13 @@ function getRouteInfo(filePath, root) {
|
|
|
2286
3129
|
filePath,
|
|
2287
3130
|
routePath,
|
|
2288
3131
|
pattern: routePath,
|
|
2289
|
-
paramNames: parts.
|
|
3132
|
+
paramNames: parts.flatMap((p) => {
|
|
3133
|
+
const optional = OPTIONAL_CATCH_ALL.exec(p);
|
|
3134
|
+
if (optional) return [optional[1]];
|
|
3135
|
+
const catchAll = CATCH_ALL.exec(p);
|
|
3136
|
+
if (catchAll) return [catchAll[1]];
|
|
3137
|
+
return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
|
|
3138
|
+
}),
|
|
2290
3139
|
isLayout,
|
|
2291
3140
|
isNotFound,
|
|
2292
3141
|
isError,
|
|
@@ -2337,7 +3186,25 @@ function getStyles() {
|
|
|
2337
3186
|
}
|
|
2338
3187
|
}
|
|
2339
3188
|
var BOOTSTRAP = esbuild2.transformSync(`
|
|
2340
|
-
|
|
3189
|
+
// shell = false: the document's SSR content sits directly in <body> - no
|
|
3190
|
+
// #app wrapper, no demo styles, so a real theme's CSS owns the document from
|
|
3191
|
+
// the first byte (and a JS-less visitor never sees either). The bundle still
|
|
3192
|
+
// runs, and it still needs its container: wrap the content once, here, before
|
|
3193
|
+
// any theme script executes (module scripts run before DOMContentLoaded). The
|
|
3194
|
+
// wrapper is a plain unstyled div, so the re-parent is visually inert; every
|
|
3195
|
+
// later path - adoption, navigation, forms - is then the ordinary one.
|
|
3196
|
+
let __app = document.getElementById('app');
|
|
3197
|
+
if (!__app) {
|
|
3198
|
+
__app = document.createElement('div');
|
|
3199
|
+
__app.id = 'app';
|
|
3200
|
+
// scripts stay outside the wrapper, exactly where the dressed document
|
|
3201
|
+
// keeps them: the state element and the running module must survive a
|
|
3202
|
+
// navigation's innerHTML swap (they are the document's, not the route's).
|
|
3203
|
+
for (const node of Array.from(document.body.children)) {
|
|
3204
|
+
if (node.tagName !== 'SCRIPT') __app.appendChild(node);
|
|
3205
|
+
}
|
|
3206
|
+
document.body.appendChild(__app);
|
|
3207
|
+
}
|
|
2341
3208
|
// Native View Transitions around client-side navigation (progressive:
|
|
2342
3209
|
// browsers without the API navigate normally, no polyfill, no CSS required).
|
|
2343
3210
|
function __navigate(pathname) {
|
|
@@ -2400,22 +3267,52 @@ document.addEventListener('submit', (e) => {
|
|
|
2400
3267
|
e.preventDefault();
|
|
2401
3268
|
postForm(new FormData(f));
|
|
2402
3269
|
});
|
|
3270
|
+
// Dev seam: the live signal graph, readable as JSON. Three callers, one
|
|
3271
|
+
// implementation: the dev server's reload bridge snapshots it before a
|
|
3272
|
+
// rebuild-triggered reload so the edit lands on the state the developer had,
|
|
3273
|
+
// and the devtools extension (devtools/) reads it the same way - the signal
|
|
3274
|
+
// graph plus the prefetch counters, which is the whole observable state of a
|
|
3275
|
+
// running page. Both are DIRECT references (no wrapper arrow): the names take
|
|
3276
|
+
// no arguments, so the call is identical and every document that carries the
|
|
3277
|
+
// bundle pays eleven bytes for the pair instead of forty.
|
|
3278
|
+
window.__rosetack = { state: serializeState, prefetch: prefetchStats };
|
|
2403
3279
|
// initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
|
|
2404
3280
|
// If the document was rendered for a DIFFERENT route (a static-file server's
|
|
2405
3281
|
// SPA fallback serves index.html for unknown paths), adopt nothing - let the
|
|
2406
3282
|
// client router render the requested route from scratch.
|
|
2407
3283
|
const __st = document.getElementById('__rosetack_state');
|
|
2408
|
-
|
|
2409
|
-
|
|
3284
|
+
let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
|
|
3285
|
+
// The dev server's reload bridge hands the pre-reload signal graph back inside
|
|
3286
|
+
// the next document (window.__rosetack_resume). The resumed values win over the
|
|
3287
|
+
// fresh render's, but the ROUTE stays the one the server just rendered - and
|
|
3288
|
+
// the route renders client-side from the bundle rather than adopting the SSR
|
|
3289
|
+
// DOM, because a resumed list can be longer than the document's rows and
|
|
3290
|
+
// adoption could not add them. Absent in every non-dev document.
|
|
3291
|
+
const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
|
|
3292
|
+
if (__resumed) {
|
|
3293
|
+
const __route = __state.__route;
|
|
3294
|
+
__state = Object.assign(__state, __resumed);
|
|
3295
|
+
__state.__route = __route;
|
|
3296
|
+
}
|
|
3297
|
+
// A NOT-FOUND document (the server stamps __notFound onto its state) boots
|
|
3298
|
+
// into the app's own 404 route: the URL matches no route - or a catch-all
|
|
3299
|
+
// whose resolver threw notFound(), whose key sits null in the resumed state
|
|
3300
|
+
// and whose template would dereference it into a 500. startNotFound paints
|
|
3301
|
+
// the not-found route from the resumed state instead (zero requests).
|
|
3302
|
+
if (__state.__notFound) {
|
|
3303
|
+
startNotFound(__app, window.location.pathname);
|
|
3304
|
+
} else if (__resumed) {
|
|
3305
|
+
start(__app, window.location.pathname);
|
|
3306
|
+
} else if (__state.__route === window.location.pathname) {
|
|
2410
3307
|
start(__app, window.location.pathname, true);
|
|
2411
3308
|
} else {
|
|
2412
3309
|
start(__app, window.location.pathname);
|
|
2413
3310
|
}
|
|
2414
3311
|
`, { minify: true }).code;
|
|
2415
|
-
var CSP_TAIL = `style-src 'unsafe-inline'; img-src data
|
|
3312
|
+
var CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
|
|
2416
3313
|
var cspCache = null;
|
|
2417
3314
|
var EXTERNAL_BOOTSTRAP = `
|
|
2418
|
-
import { start, prefetch, postForm } from '/client.js';
|
|
3315
|
+
import { start, prefetch, postForm, prefetchStats } from '/client.js';
|
|
2419
3316
|
${BOOTSTRAP}`;
|
|
2420
3317
|
function inlineScript(client) {
|
|
2421
3318
|
return `
|
|
@@ -2466,6 +3363,7 @@ var STYLES_MIN = STYLES.replace(
|
|
|
2466
3363
|
function mergeHeadBlocks(blocks) {
|
|
2467
3364
|
const byKey = /* @__PURE__ */ new Map();
|
|
2468
3365
|
const order = [];
|
|
3366
|
+
const positional = /* @__PURE__ */ new Map();
|
|
2469
3367
|
const put = (key, html) => {
|
|
2470
3368
|
if (!byKey.has(key)) {
|
|
2471
3369
|
byKey.set(key, html);
|
|
@@ -2474,11 +3372,20 @@ function mergeHeadBlocks(blocks) {
|
|
|
2474
3372
|
};
|
|
2475
3373
|
for (const block of blocks) {
|
|
2476
3374
|
for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
|
|
2477
|
-
for (const m of block.matchAll(/<(
|
|
3375
|
+
for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
|
|
2478
3376
|
const tag = m[1].toLowerCase();
|
|
2479
|
-
|
|
2480
|
-
const
|
|
2481
|
-
const
|
|
3377
|
+
if (tag === "title") continue;
|
|
3378
|
+
const attrs = m[2];
|
|
3379
|
+
const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
|
|
3380
|
+
const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
|
|
3381
|
+
let key;
|
|
3382
|
+
if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
|
|
3383
|
+
else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
|
|
3384
|
+
else {
|
|
3385
|
+
key = `${tag}:#${positional.get(tag) ?? 0}`;
|
|
3386
|
+
positional.set(tag, (positional.get(tag) ?? 0) + 1);
|
|
3387
|
+
}
|
|
3388
|
+
const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
|
|
2482
3389
|
put(key, marked);
|
|
2483
3390
|
}
|
|
2484
3391
|
}
|
|
@@ -2489,51 +3396,184 @@ function clientScriptTag(client, nonce = "") {
|
|
|
2489
3396
|
return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
|
|
2490
3397
|
<script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
|
|
2491
3398
|
}
|
|
2492
|
-
function shellOpen(styles = getStyles(), lang = "en", dir = "") {
|
|
3399
|
+
function shellOpen(styles = getStyles(), lang = "en", dir = "", shell = true) {
|
|
2493
3400
|
const styleTag = styles ? `
|
|
2494
3401
|
<style>${styles}</style>` : "";
|
|
3402
|
+
const demoStyles = shell ? `
|
|
3403
|
+
<style>${STYLES_MIN}</style>` : "";
|
|
3404
|
+
const appOpen = shell ? `
|
|
3405
|
+
<div id="app">` : "";
|
|
2495
3406
|
return `<!DOCTYPE html>
|
|
2496
3407
|
<html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
|
|
2497
3408
|
<head>
|
|
2498
3409
|
<meta charset="UTF-8">
|
|
2499
3410
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
2500
|
-
<title>RoseTack</title
|
|
2501
|
-
<style>${STYLES_MIN}</style>${styleTag}
|
|
3411
|
+
<title>RoseTack</title>${demoStyles}${styleTag}
|
|
2502
3412
|
${FAVICON}
|
|
2503
3413
|
</head>
|
|
2504
|
-
<body
|
|
2505
|
-
<div id="app">`;
|
|
3414
|
+
<body>${appOpen}`;
|
|
2506
3415
|
}
|
|
2507
|
-
function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
|
|
3416
|
+
function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
|
|
2508
3417
|
const clientTag = clientScriptTag(client, nonce);
|
|
2509
3418
|
const mergedHead = mergeHeadBlocks(head);
|
|
3419
|
+
const headStamped = nonce ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs) => /\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`) : mergedHead;
|
|
3420
|
+
let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ""}`;
|
|
3421
|
+
let bodyAttrs = "";
|
|
3422
|
+
const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag, attrs) => {
|
|
3423
|
+
const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, "");
|
|
3424
|
+
if (tag === "html") htmlAttrs = clean;
|
|
3425
|
+
else bodyAttrs = clean;
|
|
3426
|
+
return "";
|
|
3427
|
+
});
|
|
2510
3428
|
const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
|
|
2511
3429
|
const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
|
|
2512
3430
|
${FAVICON}`;
|
|
2513
|
-
const headTags =
|
|
2514
|
-
${
|
|
3431
|
+
const headTags = headClean ? `
|
|
3432
|
+
${headClean}` : "";
|
|
2515
3433
|
const styleTag = styles ? `
|
|
2516
3434
|
<style>${styles}</style>` : "";
|
|
3435
|
+
const stateSafe = stateJson.replace(/</g, "\\u003c");
|
|
2517
3436
|
const jsTail = js ? `
|
|
2518
|
-
<script type="application/json" id="__rosetack_state">${
|
|
3437
|
+
<script type="application/json" id="__rosetack_state">${stateSafe}</script>
|
|
2519
3438
|
${clientTag}` : "";
|
|
3439
|
+
const open = js && shell ? '<div id="app">' : "";
|
|
3440
|
+
const close = js && shell ? "</div>" : "";
|
|
3441
|
+
const shellStyles = js && shell ? `
|
|
3442
|
+
<style>${STYLES_MIN}</style>` : "";
|
|
2520
3443
|
return `<!DOCTYPE html>
|
|
2521
|
-
<html
|
|
3444
|
+
<html${htmlAttrs}>
|
|
2522
3445
|
<head>
|
|
2523
3446
|
<meta charset="UTF-8">
|
|
2524
3447
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
|
|
2525
|
-
${titleTag}
|
|
2526
|
-
<style>${STYLES_MIN}</style>${styleTag}
|
|
3448
|
+
${titleTag}${shellStyles}${styleTag}
|
|
2527
3449
|
</head>
|
|
2528
|
-
<body>
|
|
2529
|
-
|
|
3450
|
+
<body${bodyAttrs}>
|
|
3451
|
+
${open}${ssrHtml}${close}${jsTail}
|
|
2530
3452
|
</body>
|
|
2531
3453
|
</html>`;
|
|
2532
3454
|
}
|
|
2533
|
-
function getHtmlShell(ssrHtml, stateJson, head = [], js = true, lang = "en", dir = "", nonce = "") {
|
|
2534
|
-
return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce);
|
|
3455
|
+
function getHtmlShell(ssrHtml, stateJson, head = [], js = true, lang = "en", dir = "", nonce = "", shell = true) {
|
|
3456
|
+
return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce, shell);
|
|
2535
3457
|
}
|
|
2536
3458
|
|
|
3459
|
+
// src/cli/prompt.ts
|
|
3460
|
+
var AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
|
|
3461
|
+
|
|
3462
|
+
rosetack is a zero-hydration web framework: a .rose file compiles to a server
|
|
3463
|
+
render plus a client resume bundle, one request per page, no hydration. Write
|
|
3464
|
+
the smallest thing that works - the compiler decides what ships.
|
|
3465
|
+
|
|
3466
|
+
## File layout (all paths relative to the project root)
|
|
3467
|
+
|
|
3468
|
+
- src/pages/index.rose -> route /
|
|
3469
|
+
- src/pages/about.rose -> route /about
|
|
3470
|
+
- src/pages/blog/[id].rose -> route /blog/:id (the param is readable as state \`id()\`)
|
|
3471
|
+
- src/pages/[lang]/about.rose -> localized route (see i18n below)
|
|
3472
|
+
- src/pages/_layout.rose -> root layout wrapping every route (app-global exports live here)
|
|
3473
|
+
- src/pages/_middleware.rose -> server-only request middleware (handle(request), getContext())
|
|
3474
|
+
- src/pages/404.rose, 500.rose -> error pages
|
|
3475
|
+
- src/pages/api/posts.rose -> JSON API route (export async function GET/POST/...)
|
|
3476
|
+
- src/components/Card.rose -> reusable component, imported by relative path
|
|
3477
|
+
- src/locales/en.json -> i18n dictionaries (one file per language)
|
|
3478
|
+
|
|
3479
|
+
## A page
|
|
3480
|
+
|
|
3481
|
+
\`\`\`rose
|
|
3482
|
+
<script>
|
|
3483
|
+
let count = $state(0); // reactive state: read it as count()
|
|
3484
|
+
let posts = $data(async () => db.query()); // server data: awaited on the server,
|
|
3485
|
+
// resumed on the client - never re-fetched
|
|
3486
|
+
const total = count() + 1; // a top-level read AFTER the declaration is fine
|
|
3487
|
+
async function like() { // a server action (progressive enhancement)
|
|
3488
|
+
return $merge({ likes: 1 });
|
|
3489
|
+
}
|
|
3490
|
+
</script>
|
|
3491
|
+
|
|
3492
|
+
<h1>Posts</h1>
|
|
3493
|
+
<p>Total: {total}</p>
|
|
3494
|
+
<button on:click={() => $setState('count', count() + 1)}>+1</button>
|
|
3495
|
+
<form method="POST"><input type="hidden" name="__action" value="like"><button type="submit">Like</button></form>
|
|
3496
|
+
\`\`\`
|
|
3497
|
+
|
|
3498
|
+
Rules the compiler enforces (breaking one fails the build):
|
|
3499
|
+
|
|
3500
|
+
- The script block is TypeScript. Types, interfaces, \`import type\`, \`as\` casts and
|
|
3501
|
+
type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
|
|
3502
|
+
- $state / $data declarations are top-level statements. The declared name IS the
|
|
3503
|
+
getter: write count() in the template and the script, never bare count.
|
|
3504
|
+
- A route param (pages/blog/[id].rose) is read as state too: declare it
|
|
3505
|
+
(\`let id = $state('1')\`) and read id() - the server overwrites the default
|
|
3506
|
+
with the URL's value, and export const params = { id: [...] } bakes those
|
|
3507
|
+
values at build time.
|
|
3508
|
+
- $data() is banned in components (src/components/**) - a component renders
|
|
3509
|
+
synchronously inside its parent. Fetch in the page or the middleware and pass
|
|
3510
|
+
the value down as a prop.
|
|
3511
|
+
- Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
|
|
3512
|
+
trusted-HTML escape hatch - use it only for content you control.
|
|
3513
|
+
- Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
|
|
3514
|
+
{#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
|
|
3515
|
+
- A <slot> with attributes is a named slot and must declare its name:
|
|
3516
|
+
<slot name="row" item={post} />. A named slot must be a DIRECT child of the
|
|
3517
|
+
component tag - never inside another element or an {#if}/{#each} block.
|
|
3518
|
+
- Every component tag needs its matching close tag (or self-closes with />).
|
|
3519
|
+
- In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
|
|
3520
|
+
through. A <style> inside <head> is document CSS; a <style> in the body is
|
|
3521
|
+
the component's scoped stylesheet.
|
|
3522
|
+
- Node-only modules (node:fs, better-sqlite3, pg, redis, ...) are REFUSED in
|
|
3523
|
+
pages and components: their script ships to the browser. Import them in
|
|
3524
|
+
src/pages/_middleware.rose or a pages/api/*.rose handler instead, and pass
|
|
3525
|
+
the rows to the page through getContext().
|
|
3526
|
+
|
|
3527
|
+
## Events and server actions
|
|
3528
|
+
|
|
3529
|
+
- on:click={handler} wires a client event. The handler is a named function from
|
|
3530
|
+
the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
|
|
3531
|
+
- A server action is an exported async function. Call it from a native form
|
|
3532
|
+
(method="POST", no JS needed - progressive enhancement) or from any event
|
|
3533
|
+
(on:click={like} - one POST, in-place adopt). Its return value is an
|
|
3534
|
+
incremental patch: $append(row) / $prepend(row) / $merge({...}).
|
|
3535
|
+
- A form selects its action by the __action FIELD: name the function
|
|
3536
|
+
\`action\` (the default) or add <input type="hidden" name="__action"
|
|
3537
|
+
value="like">. The server reads the field, not the URL.
|
|
3538
|
+
- Business failures: throw new ActionError('message', 422, 'field'). It lands
|
|
3539
|
+
in ordinary state - $actionError() reads it back, a {#boundary} contains it.
|
|
3540
|
+
- beforeAction(name, form) is the per-page guard that vetoes an action.
|
|
3541
|
+
|
|
3542
|
+
## Route exports (in the script block, validated at build time)
|
|
3543
|
+
|
|
3544
|
+
- export const csr = false | true force/assert zero-JS (absent = the compiler decides)
|
|
3545
|
+
- export const buffer = true keep this route off the streaming path
|
|
3546
|
+
- export const headers = { ... } flat string map, merged over the strict CSP default
|
|
3547
|
+
- export const csp = { nonce: true } per-response nonce instead of the hash (route becomes dynamic)
|
|
3548
|
+
- export const prefetch = 'off' | 'hover' | 'viewport' | 'all' app-global, root layout only
|
|
3549
|
+
- export const bundle = 'inline' | 'split' app-global; 'split' = mode B for large apps
|
|
3550
|
+
- export const vitals = true opt into the web-vitals hook
|
|
3551
|
+
- export const revalidate = N stale-while-revalidate ISR window, seconds
|
|
3552
|
+
- export const params = { id: ['1'] } prerender these param values at build time
|
|
3553
|
+
- export const prerender = true (api routes) bake the GET body for static deploys
|
|
3554
|
+
|
|
3555
|
+
## i18n
|
|
3556
|
+
|
|
3557
|
+
src/locales/<lang>.json is a dictionary; a [lang] route segment selects one;
|
|
3558
|
+
$t('key', { name }) translates reactively; unknown locales answer 404.
|
|
3559
|
+
|
|
3560
|
+
## When a build fails
|
|
3561
|
+
|
|
3562
|
+
Every compiler failure is structured: { code, file, line, message, hint }.
|
|
3563
|
+
Run \`rosetack build --json\` to read it as JSON, fix the named file at the named
|
|
3564
|
+
line, and build again. Codes: E-IMPORT (unresolvable .rose import), E-PLUGIN
|
|
3565
|
+
(transform threw), E-NODE-ONLY (server-only import in a page/component),
|
|
3566
|
+
E-EXPORT (invalid export const value), E-TEMPLATE (unclosed tag / slot
|
|
3567
|
+
placement), E-ROUTE (no pages found), E-INTERNAL (installation problem).
|
|
3568
|
+
|
|
3569
|
+
## The one invariant worth protecting
|
|
3570
|
+
|
|
3571
|
+
A route ships ONE request with ZERO hydration: the whole client bundle is
|
|
3572
|
+
inlined in the document. Keep it that way - browser-only code (document.,
|
|
3573
|
+
window., timers) belongs in onMount, and anything the predicate cannot see
|
|
3574
|
+
(inline on* attributes, javascript: URLs, eval) is reported by the build.
|
|
3575
|
+
`;
|
|
3576
|
+
|
|
2537
3577
|
// src/cli/index.ts
|
|
2538
3578
|
function pickEncoding(req) {
|
|
2539
3579
|
const ae = req.headers["accept-encoding"] || "";
|
|
@@ -2570,7 +3610,7 @@ function sendHtml(req, res, status, html, extraHeaders) {
|
|
|
2570
3610
|
return;
|
|
2571
3611
|
}
|
|
2572
3612
|
res.setHeader("ETag", etag);
|
|
2573
|
-
const enc = pickEncoding(req);
|
|
3613
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
2574
3614
|
if (enc) {
|
|
2575
3615
|
res.setHeader("Content-Encoding", enc);
|
|
2576
3616
|
res.end(compress(enc, html));
|
|
@@ -2593,19 +3633,46 @@ async function sendWebResponse(web, res) {
|
|
|
2593
3633
|
}
|
|
2594
3634
|
async function sendPage(req, res, ssrModule, hookCtx, page, routePath) {
|
|
2595
3635
|
let status = page.status ?? 200;
|
|
3636
|
+
if (page.redirect) {
|
|
3637
|
+
const body = `<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${page.redirect}">${page.redirect}</a>.</p>`;
|
|
3638
|
+
let headers2 = pageHeaders(ssrModule, routePath, "");
|
|
3639
|
+
if (hookCtx) {
|
|
3640
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(body, {
|
|
3641
|
+
status,
|
|
3642
|
+
headers: { "content-type": "text/html; charset=utf-8", location: page.redirect, ...headers2 }
|
|
3643
|
+
}));
|
|
3644
|
+
status = out.status;
|
|
3645
|
+
headers2 = webHeadersToNode(out);
|
|
3646
|
+
}
|
|
3647
|
+
headers2.location = page.redirect;
|
|
3648
|
+
res.statusCode = status;
|
|
3649
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
3650
|
+
res.setHeader("Location", page.redirect);
|
|
3651
|
+
for (const [k, v] of Object.entries(headers2)) if (k !== "location") res.setHeader(k, v);
|
|
3652
|
+
res.end(body);
|
|
3653
|
+
return;
|
|
3654
|
+
}
|
|
2596
3655
|
const nonce = nonceFor(ssrModule, routePath);
|
|
2597
|
-
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
|
|
3656
|
+
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
|
|
2598
3657
|
let headers = pageHeaders(ssrModule, routePath, nonce);
|
|
2599
3658
|
if (hookCtx) {
|
|
2600
|
-
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
3659
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
3660
|
+
status,
|
|
3661
|
+
headers: { "content-type": "text/html; charset=utf-8", ...headers }
|
|
3662
|
+
}));
|
|
2601
3663
|
status = out.status;
|
|
2602
3664
|
headers = webHeadersToNode(out);
|
|
2603
|
-
html = await out.text();
|
|
3665
|
+
html = out.bodyUsed ? html : await out.text();
|
|
2604
3666
|
}
|
|
2605
3667
|
sendHtml(req, res, status, html, headers);
|
|
2606
3668
|
}
|
|
2607
3669
|
var fileCache = /* @__PURE__ */ new Map();
|
|
2608
|
-
var
|
|
3670
|
+
var __portArg = process.argv.find((a) => a === "--port" || a.startsWith("--port="));
|
|
3671
|
+
if (__portArg) {
|
|
3672
|
+
const __v = __portArg.includes("=") ? __portArg.slice("--port=".length) : process.argv[process.argv.indexOf(__portArg) + 1];
|
|
3673
|
+
if (__v && Number(__v) > 0) process.env.PORT = __v;
|
|
3674
|
+
}
|
|
3675
|
+
var SRC_DIR = process.argv[3] && !process.argv[3].startsWith("-") ? path3.resolve(process.argv[3]) : process.cwd();
|
|
2609
3676
|
var OUT_DIR2 = path3.join(process.cwd(), "dist");
|
|
2610
3677
|
var PORT = Number(process.env.PORT) || 3e3;
|
|
2611
3678
|
var serverModule = null;
|
|
@@ -2617,7 +3684,13 @@ async function loadServer() {
|
|
|
2617
3684
|
if (!serverModule || mtimeMs !== serverMtime) {
|
|
2618
3685
|
serverMtime = mtimeMs;
|
|
2619
3686
|
serverVersion++;
|
|
2620
|
-
|
|
3687
|
+
let target = file;
|
|
3688
|
+
if (devMode) {
|
|
3689
|
+
target = path3.join(OUT_DIR2, ".build", `server-${serverVersion}.mjs`);
|
|
3690
|
+
await fs3.promises.mkdir(path3.dirname(target), { recursive: true });
|
|
3691
|
+
await fs3.promises.copyFile(file, target);
|
|
3692
|
+
}
|
|
3693
|
+
serverModule = await import(pathToFileURL2(target).href);
|
|
2621
3694
|
}
|
|
2622
3695
|
return serverModule;
|
|
2623
3696
|
}
|
|
@@ -2633,6 +3706,21 @@ async function build2() {
|
|
|
2633
3706
|
routes: ssrModule.routeHeaders ?? []
|
|
2634
3707
|
}));
|
|
2635
3708
|
await writeBrotli(OUT_DIR2);
|
|
3709
|
+
await analyze(OUT_DIR2, ssrModule.dynamicRoutes ?? []);
|
|
3710
|
+
if (argv.includes("--static")) {
|
|
3711
|
+
const dyn = ssrModule.dynamicRoutes ?? [];
|
|
3712
|
+
const unbakedApi = Object.entries(ssrModule.apiPrerender ?? {}).filter(([, baked]) => !baked).map(([routePath]) => routePath);
|
|
3713
|
+
const paramless = routes.filter((r) => r.paramNames.length > 0 && !(ssrModule.routeParams ?? {})[r.routePath]).map((r) => r.routePath);
|
|
3714
|
+
const problems = [.../* @__PURE__ */ new Set([...dyn, ...unbakedApi, ...paramless, ...skipped])];
|
|
3715
|
+
if (problems.length > 0) {
|
|
3716
|
+
console.error("rosetack: --static export refused - these routes need a server:");
|
|
3717
|
+
for (const p of problems) console.error(` ${p}`);
|
|
3718
|
+
console.error("(getContext()/$store()/$query(), csp.nonce, buffer = true, an unbaked /api route, a param route with no export const params, or a route the middleware walled)");
|
|
3719
|
+
console.error("drop --static to build the normal dist (the dynamic half renders on demand on Node/edge)");
|
|
3720
|
+
process.exit(1);
|
|
3721
|
+
}
|
|
3722
|
+
console.log("rosetack: static export verified - every route is a baked file, no server needed");
|
|
3723
|
+
}
|
|
2636
3724
|
}
|
|
2637
3725
|
var BROTLI_EXT = /* @__PURE__ */ new Set([".html", ".js", ".css", ".json", ".svg", ".txt"]);
|
|
2638
3726
|
async function writeBrotli(dir) {
|
|
@@ -2646,6 +3734,43 @@ async function writeBrotli(dir) {
|
|
|
2646
3734
|
await fs3.promises.writeFile(p + ".br", zlib.brotliCompressSync(await fs3.promises.readFile(p)));
|
|
2647
3735
|
}
|
|
2648
3736
|
}
|
|
3737
|
+
async function analyze(outDir, dynamic) {
|
|
3738
|
+
const rows = [];
|
|
3739
|
+
const walk = async (dir, prefix) => {
|
|
3740
|
+
for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
|
|
3741
|
+
if (e.isDirectory()) {
|
|
3742
|
+
await walk(path3.join(dir, e.name), `${prefix}/${e.name}`);
|
|
3743
|
+
continue;
|
|
3744
|
+
}
|
|
3745
|
+
if (!e.name.endsWith(".html")) continue;
|
|
3746
|
+
const file = path3.join(dir, e.name);
|
|
3747
|
+
const raw = await fs3.promises.readFile(file);
|
|
3748
|
+
const brFile = `${file}.br`;
|
|
3749
|
+
rows.push({
|
|
3750
|
+
route: prefix || "/",
|
|
3751
|
+
raw: raw.length,
|
|
3752
|
+
gzip: zlib.gzipSync(raw, { level: 9 }).length,
|
|
3753
|
+
br: fs3.existsSync(brFile) ? (await fs3.promises.stat(brFile)).size : 0,
|
|
3754
|
+
js: /<script type="module"/.test(raw.toString("utf8"))
|
|
3755
|
+
});
|
|
3756
|
+
}
|
|
3757
|
+
};
|
|
3758
|
+
await walk(outDir, "");
|
|
3759
|
+
const kb = (n) => `${(n / 1024).toFixed(1)} KB`;
|
|
3760
|
+
const lines = ["rosetack build analysis (measured from dist/; br = the precompressed bytes the Go binary serves):"];
|
|
3761
|
+
for (const r of rows.sort((a, b) => a.route < b.route ? -1 : 1)) {
|
|
3762
|
+
lines.push(` ${r.route.padEnd(16)}${kb(r.raw).padStart(9)} raw ${kb(r.gzip).padStart(8)} gzip ${kb(r.br).padStart(8)} br ${r.js ? "bundle inlined" : "zero-JS"}`);
|
|
3763
|
+
}
|
|
3764
|
+
const client = path3.join(outDir, "client.js");
|
|
3765
|
+
if (fs3.existsSync(client)) {
|
|
3766
|
+
const raw = await fs3.promises.readFile(client);
|
|
3767
|
+
lines.push(` shared bundle ${kb(raw.length).padStart(9)} raw ${kb(zlib.gzipSync(raw, { level: 9 }).length).padStart(8)} gzip ${kb(fs3.existsSync(`${client}.br`) ? (await fs3.promises.stat(`${client}.br`)).size : 0).padStart(8)} br inlined into every interactive document`);
|
|
3768
|
+
}
|
|
3769
|
+
if (dynamic.length > 0) {
|
|
3770
|
+
lines.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${dynamic.join(" ")}`);
|
|
3771
|
+
}
|
|
3772
|
+
for (const l of lines) console.log(l);
|
|
3773
|
+
}
|
|
2649
3774
|
async function clearPrerendered(dir, depth = 0) {
|
|
2650
3775
|
for (const e of await fs3.promises.readdir(dir, { withFileTypes: true })) {
|
|
2651
3776
|
if (depth === 0 && e.name === "locales" && e.isDirectory()) continue;
|
|
@@ -2676,6 +3801,7 @@ async function prerender(routes) {
|
|
|
2676
3801
|
skipped.push(routePath);
|
|
2677
3802
|
return;
|
|
2678
3803
|
}
|
|
3804
|
+
ssrModule.setQuery?.({});
|
|
2679
3805
|
const page = await ssrModule.renderPage(routePath);
|
|
2680
3806
|
if (page.status === 500) {
|
|
2681
3807
|
console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
|
|
@@ -2684,7 +3810,7 @@ async function prerender(routes) {
|
|
|
2684
3810
|
}
|
|
2685
3811
|
const routeDir = routePath === "/" ? OUT_DIR2 : path3.join(OUT_DIR2, routePath.slice(1));
|
|
2686
3812
|
await fs3.promises.mkdir(routeDir, { recursive: true });
|
|
2687
|
-
await fs3.promises.writeFile(path3.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
3813
|
+
await fs3.promises.writeFile(path3.join(routeDir, "index.html"), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
|
|
2688
3814
|
console.log(`prerendered ${routePath} -> ${path3.relative(process.cwd(), path3.join(routeDir, "index.html"))}`);
|
|
2689
3815
|
};
|
|
2690
3816
|
for (const info of routes) {
|
|
@@ -2740,7 +3866,11 @@ function enumerateParams(pattern, names, raw) {
|
|
|
2740
3866
|
}
|
|
2741
3867
|
return combos.map((values) => {
|
|
2742
3868
|
let i = 0;
|
|
2743
|
-
return pattern.split("/").map((seg) =>
|
|
3869
|
+
return pattern.split("/").map((seg) => {
|
|
3870
|
+
if (seg.startsWith(":")) return encodeURIComponent(values[i++]);
|
|
3871
|
+
if (seg.startsWith("*")) return values[i++].split("/").map(encodeURIComponent).join("/");
|
|
3872
|
+
return seg;
|
|
3873
|
+
}).join("/");
|
|
2744
3874
|
});
|
|
2745
3875
|
}
|
|
2746
3876
|
var ASSET_EXT = /* @__PURE__ */ new Set([".js", ".css", ".json", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp", ".woff", ".woff2", ".txt", ".xml"]);
|
|
@@ -2761,9 +3891,10 @@ function revalidateInBackground(routePath, filePath) {
|
|
|
2761
3891
|
void (async () => {
|
|
2762
3892
|
try {
|
|
2763
3893
|
const ssrModule = await loadServer();
|
|
3894
|
+
ssrModule.setQuery?.({});
|
|
2764
3895
|
const page = await ssrModule.renderPage(routePath);
|
|
2765
3896
|
if (page.status === 200) {
|
|
2766
|
-
await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
3897
|
+
await fs3.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, "", page.shell !== false));
|
|
2767
3898
|
fileCache.delete(filePath);
|
|
2768
3899
|
console.log(`rosetack: revalidated ${routePath} in the background`);
|
|
2769
3900
|
}
|
|
@@ -2860,7 +3991,98 @@ function webHeadersToNode(web) {
|
|
|
2860
3991
|
if (cookies.length) out["set-cookie"] = cookies;
|
|
2861
3992
|
return out;
|
|
2862
3993
|
}
|
|
2863
|
-
|
|
3994
|
+
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>`;
|
|
3995
|
+
var devResume = null;
|
|
3996
|
+
var devClients = /* @__PURE__ */ new Set();
|
|
3997
|
+
var devMode = false;
|
|
3998
|
+
function devReload(req, res) {
|
|
3999
|
+
res.writeHead(200, {
|
|
4000
|
+
"Content-Type": "text/event-stream",
|
|
4001
|
+
"Cache-Control": "no-cache, no-transform",
|
|
4002
|
+
Connection: "keep-alive"
|
|
4003
|
+
});
|
|
4004
|
+
res.write(": ok\n\n");
|
|
4005
|
+
devClients.add(res);
|
|
4006
|
+
req.on("close", () => devClients.delete(res));
|
|
4007
|
+
}
|
|
4008
|
+
function devSaveState(req, res) {
|
|
4009
|
+
let body = "";
|
|
4010
|
+
req.on("data", (c) => {
|
|
4011
|
+
body += c;
|
|
4012
|
+
if (body.length > 1e6) req.destroy();
|
|
4013
|
+
});
|
|
4014
|
+
req.on("end", () => {
|
|
4015
|
+
try {
|
|
4016
|
+
JSON.parse(body);
|
|
4017
|
+
devResume = body;
|
|
4018
|
+
} catch {
|
|
4019
|
+
}
|
|
4020
|
+
res.writeHead(204).end();
|
|
4021
|
+
});
|
|
4022
|
+
}
|
|
4023
|
+
function devNotify() {
|
|
4024
|
+
for (const res of devClients) {
|
|
4025
|
+
try {
|
|
4026
|
+
res.write("data: rebuild\n\n");
|
|
4027
|
+
} catch {
|
|
4028
|
+
devClients.delete(res);
|
|
4029
|
+
}
|
|
4030
|
+
}
|
|
4031
|
+
}
|
|
4032
|
+
var devBuild = null;
|
|
4033
|
+
var devBuildPending = false;
|
|
4034
|
+
function startDevBuild() {
|
|
4035
|
+
if (!devBuild) {
|
|
4036
|
+
devBuild = (async () => {
|
|
4037
|
+
try {
|
|
4038
|
+
console.log("Rebuilding...");
|
|
4039
|
+
await build2();
|
|
4040
|
+
devNotify();
|
|
4041
|
+
} catch (err) {
|
|
4042
|
+
console.error("Build failed (server still running):", err instanceof Error ? err.message : String(err));
|
|
4043
|
+
} finally {
|
|
4044
|
+
devBuild = null;
|
|
4045
|
+
devBuildPending = false;
|
|
4046
|
+
}
|
|
4047
|
+
})();
|
|
4048
|
+
}
|
|
4049
|
+
return devBuild;
|
|
4050
|
+
}
|
|
4051
|
+
function settleDevBuild() {
|
|
4052
|
+
if (!devMode || !devBuild && !devBuildPending) return null;
|
|
4053
|
+
return startDevBuild();
|
|
4054
|
+
}
|
|
4055
|
+
function devWrap(inner) {
|
|
4056
|
+
devMode = true;
|
|
4057
|
+
return (req, res) => {
|
|
4058
|
+
const url = req.url || "/";
|
|
4059
|
+
if (url.startsWith("/__rosetack_reload")) return devReload(req, res);
|
|
4060
|
+
if (url.startsWith("/__rosetack_state") && req.method === "POST") return devSaveState(req, res);
|
|
4061
|
+
let injected = false;
|
|
4062
|
+
const seed = devResume;
|
|
4063
|
+
devResume = null;
|
|
4064
|
+
const isHtml = () => String(res.getHeader("content-type") || "").includes("text/html");
|
|
4065
|
+
const inject = (chunk) => {
|
|
4066
|
+
if (injected || !isHtml()) return chunk;
|
|
4067
|
+
const s = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
|
4068
|
+
const at = s.indexOf("<head>");
|
|
4069
|
+
if (at < 0) return chunk;
|
|
4070
|
+
injected = true;
|
|
4071
|
+
const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\/script>/g, "")}</script>` : "";
|
|
4072
|
+
const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
|
|
4073
|
+
return Buffer.isBuffer(chunk) ? Buffer.from(out, "utf8") : out;
|
|
4074
|
+
};
|
|
4075
|
+
const write = res.write.bind(res);
|
|
4076
|
+
res.write = (chunk, ...rest) => write(inject(chunk), ...rest);
|
|
4077
|
+
const end = res.end.bind(res);
|
|
4078
|
+
res.end = (chunk, ...rest) => {
|
|
4079
|
+
if (!res.headersSent && isHtml()) res.removeHeader("Content-Security-Policy");
|
|
4080
|
+
end(chunk === void 0 || chunk === null ? chunk : inject(chunk), ...rest);
|
|
4081
|
+
};
|
|
4082
|
+
inner(req, res);
|
|
4083
|
+
};
|
|
4084
|
+
}
|
|
4085
|
+
function serveStatic(dir, isr = false, dev2 = false) {
|
|
2864
4086
|
return (req, res) => {
|
|
2865
4087
|
const blocked = crossSiteWrite(req);
|
|
2866
4088
|
if (blocked) {
|
|
@@ -2869,7 +4091,24 @@ function serveStatic(dir, isr = false) {
|
|
|
2869
4091
|
res.end(blocked.body);
|
|
2870
4092
|
return;
|
|
2871
4093
|
}
|
|
2872
|
-
|
|
4094
|
+
const want = pathnameOf(req.url || "/");
|
|
4095
|
+
const canonical = want.replace(/\/+$/, "") || "/";
|
|
4096
|
+
if (canonical !== want) {
|
|
4097
|
+
let search = "";
|
|
4098
|
+
try {
|
|
4099
|
+
search = new URL(req.url || "/", "http://localhost").search;
|
|
4100
|
+
} catch {
|
|
4101
|
+
}
|
|
4102
|
+
const to = canonical + search;
|
|
4103
|
+
res.statusCode = 308;
|
|
4104
|
+
res.setHeader("Location", to);
|
|
4105
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
4106
|
+
res.end(`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${to}">${to}</a>.</p>`);
|
|
4107
|
+
return;
|
|
4108
|
+
}
|
|
4109
|
+
const settled = settleDevBuild();
|
|
4110
|
+
const ready = settled ? settled.then(() => loadServer()) : loadServer();
|
|
4111
|
+
ready.then(async (ssrModule) => {
|
|
2873
4112
|
const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true ? await hookContext(req) : null;
|
|
2874
4113
|
if (hookCtx) {
|
|
2875
4114
|
const short = await ssrModule.runRequestHooks(hookCtx);
|
|
@@ -2900,12 +4139,14 @@ function serveStatic(dir, isr = false) {
|
|
|
2900
4139
|
headers,
|
|
2901
4140
|
body: body.length > 0 ? body : void 0
|
|
2902
4141
|
});
|
|
4142
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
2903
4143
|
let apiRes = await ssrModule.handleApi(req.method || "GET", apiPath, request);
|
|
2904
4144
|
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
2905
4145
|
writeWebHeaders(apiRes, res);
|
|
2906
4146
|
res.statusCode = apiRes.status;
|
|
2907
4147
|
res.end(Buffer.from(await apiRes.arrayBuffer()));
|
|
2908
|
-
} catch {
|
|
4148
|
+
} catch (err) {
|
|
4149
|
+
console.error(`rosetack: ${req.method} ${req.url} api handler failed:`, err instanceof Error ? err.stack ?? err.message : String(err));
|
|
2909
4150
|
res.statusCode = 500;
|
|
2910
4151
|
res.setHeader("Content-Type", "application/json");
|
|
2911
4152
|
res.end('{"error":"api handler failed"}');
|
|
@@ -2926,16 +4167,20 @@ function serveStatic(dir, isr = false) {
|
|
|
2926
4167
|
return;
|
|
2927
4168
|
}
|
|
2928
4169
|
}
|
|
2929
|
-
|
|
4170
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
4171
|
+
const page2 = await ssrModule.renderPage(pathnameOf(req.url || "/"), form);
|
|
2930
4172
|
await sendPage(req, res, ssrModule, hookCtx, page2, pathnameOf(req.url || "/"));
|
|
2931
|
-
} catch {
|
|
2932
|
-
|
|
2933
|
-
res.
|
|
4173
|
+
} catch (err) {
|
|
4174
|
+
console.error(`rosetack: POST ${pathnameOf(req.url || "/")} failed:`, err instanceof Error ? err.stack : err);
|
|
4175
|
+
if (!res.headersSent) {
|
|
4176
|
+
res.statusCode = 400;
|
|
4177
|
+
res.end("Bad request");
|
|
4178
|
+
}
|
|
2934
4179
|
}
|
|
2935
4180
|
});
|
|
2936
4181
|
return;
|
|
2937
4182
|
}
|
|
2938
|
-
let safe = path3.normalize(req.url || "/").replace(/^(\.\.(\/)?)+/, "");
|
|
4183
|
+
let safe = path3.normalize(pathnameOf(req.url || "/")).replace(/^(\.\.(\/)?)+/, "");
|
|
2939
4184
|
if (safe === "\\" || safe === "/") safe = "/";
|
|
2940
4185
|
let filePath = path3.join(dir, safe);
|
|
2941
4186
|
if (!fs3.existsSync(filePath) && ASSET_EXT.has(path3.extname(safe).toLowerCase())) {
|
|
@@ -2963,8 +4208,6 @@ function serveStatic(dir, isr = false) {
|
|
|
2963
4208
|
entry = {
|
|
2964
4209
|
mtimeMs: st.mtimeMs,
|
|
2965
4210
|
raw,
|
|
2966
|
-
// A file's compressed forms are computed ONCE and then served from this cache
|
|
2967
|
-
// forever …
|
|
2968
4211
|
br: zlib.brotliCompressSync(raw),
|
|
2969
4212
|
gzip: zlib.gzipSync(raw, { level: 9 }),
|
|
2970
4213
|
etag: `W/"${st.size}-${st.mtimeMs}"`
|
|
@@ -3004,7 +4247,7 @@ function serveStatic(dir, isr = false) {
|
|
|
3004
4247
|
res.end();
|
|
3005
4248
|
return;
|
|
3006
4249
|
}
|
|
3007
|
-
const enc = pickEncoding(req);
|
|
4250
|
+
const enc = devMode ? null : pickEncoding(req);
|
|
3008
4251
|
res.statusCode = status;
|
|
3009
4252
|
if (enc) {
|
|
3010
4253
|
res.setHeader("Content-Encoding", enc);
|
|
@@ -3019,12 +4262,13 @@ function serveStatic(dir, isr = false) {
|
|
|
3019
4262
|
broken = new Set(JSON.parse(fs3.readFileSync(path3.join(dir, "broken.json"), "utf-8")));
|
|
3020
4263
|
} catch {
|
|
3021
4264
|
}
|
|
3022
|
-
const safe2 = req.url || "/";
|
|
3023
|
-
|
|
4265
|
+
const safe2 = pathnameOf(req.url || "/");
|
|
4266
|
+
ssrModule.setQuery?.(queryOf(req.url));
|
|
4267
|
+
if (!dev2 && !broken.has(safe2) && !ssrModule.isBuffered?.(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
3024
4268
|
const enc = pickEncoding(req);
|
|
3025
4269
|
let status = 200;
|
|
3026
|
-
const nonce = nonceFor(ssrModule,
|
|
3027
|
-
let headers = pageHeaders(ssrModule,
|
|
4270
|
+
const nonce = nonceFor(ssrModule, safe2);
|
|
4271
|
+
let headers = pageHeaders(ssrModule, safe2, nonce);
|
|
3028
4272
|
if (hookCtx) {
|
|
3029
4273
|
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers }));
|
|
3030
4274
|
status = out.status;
|
|
@@ -3055,15 +4299,21 @@ function serveStatic(dir, isr = false) {
|
|
|
3055
4299
|
done = () => res.end();
|
|
3056
4300
|
}
|
|
3057
4301
|
const doc = ssrModule.docAttrs(safe2);
|
|
3058
|
-
await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
|
|
4302
|
+
await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir, !ssrModule.shellOff(safe2)), clientScriptTag(getClientSource(), nonce));
|
|
3059
4303
|
done();
|
|
3060
4304
|
return;
|
|
3061
4305
|
}
|
|
3062
4306
|
const page = await ssrModule.renderPage(safe2);
|
|
3063
|
-
await sendPage(req, res, ssrModule, hookCtx, page,
|
|
3064
|
-
}).catch(() => {
|
|
3065
|
-
|
|
3066
|
-
res.
|
|
4307
|
+
await sendPage(req, res, ssrModule, hookCtx, page, safe2);
|
|
4308
|
+
}).catch((err) => {
|
|
4309
|
+
console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
|
|
4310
|
+
if (res.headersSent) {
|
|
4311
|
+
res.destroy();
|
|
4312
|
+
return;
|
|
4313
|
+
}
|
|
4314
|
+
res.statusCode = 500;
|
|
4315
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
4316
|
+
res.end("<h1>500</h1><p>Something went wrong rendering this page.</p>");
|
|
3067
4317
|
});
|
|
3068
4318
|
};
|
|
3069
4319
|
}
|
|
@@ -3074,18 +4324,70 @@ function pathnameOf(url) {
|
|
|
3074
4324
|
return (url || "/").split("?")[0];
|
|
3075
4325
|
}
|
|
3076
4326
|
}
|
|
4327
|
+
function queryOf(url) {
|
|
4328
|
+
const q = {};
|
|
4329
|
+
try {
|
|
4330
|
+
new URL(url || "/", "http://localhost").searchParams.forEach((v, k) => {
|
|
4331
|
+
if (!(k in q)) q[k] = v;
|
|
4332
|
+
});
|
|
4333
|
+
} catch {
|
|
4334
|
+
}
|
|
4335
|
+
return q;
|
|
4336
|
+
}
|
|
4337
|
+
function listenFree(server, port, onReady) {
|
|
4338
|
+
const attempt = (p) => {
|
|
4339
|
+
const onError = (err) => {
|
|
4340
|
+
server.removeListener("error", onError);
|
|
4341
|
+
if (err && err.code === "EADDRINUSE" && p - port < 20) {
|
|
4342
|
+
console.log(`\u{1F339} port ${p} is in use - trying ${p + 1}`);
|
|
4343
|
+
attempt(p + 1);
|
|
4344
|
+
return;
|
|
4345
|
+
}
|
|
4346
|
+
console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
|
|
4347
|
+
process.exit(1);
|
|
4348
|
+
};
|
|
4349
|
+
server.once("error", onError);
|
|
4350
|
+
server.listen(p, () => {
|
|
4351
|
+
server.removeListener("error", onError);
|
|
4352
|
+
onReady(p);
|
|
4353
|
+
});
|
|
4354
|
+
};
|
|
4355
|
+
attempt(port);
|
|
4356
|
+
}
|
|
4357
|
+
async function freePort(from) {
|
|
4358
|
+
const net = await import("node:net");
|
|
4359
|
+
for (let p = from; p < from + 20; p++) {
|
|
4360
|
+
const free = await new Promise((resolve3) => {
|
|
4361
|
+
const probe = net.createServer();
|
|
4362
|
+
probe.once("error", () => resolve3(false));
|
|
4363
|
+
probe.listen(p, () => probe.close(() => resolve3(true)));
|
|
4364
|
+
});
|
|
4365
|
+
if (free) return p;
|
|
4366
|
+
}
|
|
4367
|
+
return from;
|
|
4368
|
+
}
|
|
3077
4369
|
function version() {
|
|
3078
|
-
for (const rel of ["../../package.json", "../package.json"]) {
|
|
4370
|
+
for (const rel of ["../FRAMEWORK_VERSION", "../../FRAMEWORK_VERSION", "../../package.json", "../package.json"]) {
|
|
3079
4371
|
try {
|
|
3080
|
-
const
|
|
4372
|
+
const raw = fs3.readFileSync(fileURLToPath2(new URL(rel, import.meta.url)), "utf-8");
|
|
4373
|
+
const v = rel.endsWith("FRAMEWORK_VERSION") ? raw.trim() : JSON.parse(raw).version;
|
|
3081
4374
|
if (v) return v;
|
|
3082
4375
|
} catch {
|
|
3083
4376
|
}
|
|
3084
4377
|
}
|
|
3085
4378
|
return "0.0.0";
|
|
3086
4379
|
}
|
|
4380
|
+
function projectTag() {
|
|
4381
|
+
try {
|
|
4382
|
+
const pkg = JSON.parse(fs3.readFileSync(path3.join(process.cwd(), "package.json"), "utf-8"));
|
|
4383
|
+
if (!pkg.version || pkg.name === "rosetack") return "";
|
|
4384
|
+
return ` - project: ${pkg.name} v${pkg.version}`;
|
|
4385
|
+
} catch {
|
|
4386
|
+
return "";
|
|
4387
|
+
}
|
|
4388
|
+
}
|
|
3087
4389
|
async function dev() {
|
|
3088
|
-
console.log(`\u{1F339} RoseTack v${version()} dev server starting...`);
|
|
4390
|
+
console.log(`\u{1F339} RoseTack v${version()}${projectTag()} dev server starting...`);
|
|
3089
4391
|
try {
|
|
3090
4392
|
await build2();
|
|
3091
4393
|
} catch (err) {
|
|
@@ -3093,28 +4395,24 @@ async function dev() {
|
|
|
3093
4395
|
}
|
|
3094
4396
|
let timeout;
|
|
3095
4397
|
fs3.watch(SRC_DIR, { recursive: true }, () => {
|
|
4398
|
+
devBuildPending = true;
|
|
3096
4399
|
clearTimeout(timeout);
|
|
3097
|
-
timeout = setTimeout(
|
|
3098
|
-
|
|
3099
|
-
console.log("Rebuilding...");
|
|
3100
|
-
await build2();
|
|
3101
|
-
} catch (err) {
|
|
3102
|
-
console.error("Build failed (server still running):", err instanceof Error ? err.message : err);
|
|
3103
|
-
}
|
|
4400
|
+
timeout = setTimeout(() => {
|
|
4401
|
+
void startDevBuild();
|
|
3104
4402
|
}, 200);
|
|
3105
4403
|
});
|
|
3106
4404
|
const http = await import("http");
|
|
3107
|
-
const server = http.createServer(serveStatic(OUT_DIR2));
|
|
3108
|
-
server
|
|
3109
|
-
console.log("\u{1F339} http://localhost:" +
|
|
4405
|
+
const server = http.createServer(devWrap(serveStatic(OUT_DIR2, false, true)));
|
|
4406
|
+
listenFree(server, PORT, (port) => {
|
|
4407
|
+
console.log("\u{1F339} http://localhost:" + port);
|
|
3110
4408
|
});
|
|
3111
4409
|
}
|
|
3112
4410
|
async function preview() {
|
|
3113
4411
|
await build2();
|
|
3114
4412
|
const http = await import("http");
|
|
3115
4413
|
const server = http.createServer(serveStatic(OUT_DIR2, true));
|
|
3116
|
-
server
|
|
3117
|
-
console.log(`\u{1F339} RoseTack v${version()} preview at http://localhost
|
|
4414
|
+
listenFree(server, PORT, (port) => {
|
|
4415
|
+
console.log(`\u{1F339} RoseTack v${version()}${projectTag()} preview at http://localhost:${port}`);
|
|
3118
4416
|
});
|
|
3119
4417
|
}
|
|
3120
4418
|
async function serve() {
|
|
@@ -3126,9 +4424,9 @@ async function serve() {
|
|
|
3126
4424
|
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
3127
4425
|
const os = await import("node:os");
|
|
3128
4426
|
const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
|
|
3129
|
-
const PORT2 = Number(process.env.PORT) || 3e3;
|
|
3130
4427
|
if (cluster.isPrimary) {
|
|
3131
|
-
|
|
4428
|
+
const port = await freePort(Number(process.env.PORT) || 3e3);
|
|
4429
|
+
for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
|
|
3132
4430
|
cluster.on("message", (worker, msg) => {
|
|
3133
4431
|
if (!msg || msg.type !== "rosetack:store") return;
|
|
3134
4432
|
for (const w of Object.values(cluster.workers ?? {})) {
|
|
@@ -3145,7 +4443,7 @@ async function serve() {
|
|
|
3145
4443
|
cluster.on("exit", () => {
|
|
3146
4444
|
if (--live <= 0) process.exit(0);
|
|
3147
4445
|
});
|
|
3148
|
-
console.log(`\u{1F339} RoseTack v${version()} serve: ${workers} worker${workers > 1 ? "s" : ""} on http://localhost:${
|
|
4446
|
+
console.log(`\u{1F339} RoseTack v${version()}${projectTag()} serve: ${workers} worker${workers > 1 ? "s" : ""} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
3149
4447
|
return;
|
|
3150
4448
|
}
|
|
3151
4449
|
process.on("disconnect", () => process.exit(0));
|
|
@@ -3153,20 +4451,39 @@ async function serve() {
|
|
|
3153
4451
|
try {
|
|
3154
4452
|
servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
|
|
3155
4453
|
} catch (err) {
|
|
3156
|
-
console.error("rosetack: rosetack.config.js failed to load for the serve hooks:", err instanceof Error ? err.message : err);
|
|
4454
|
+
console.error("rosetack: rosetack.config.js failed to load for the serve hooks:", err instanceof Error ? err.message : String(err));
|
|
4455
|
+
}
|
|
4456
|
+
const storeBridge = {
|
|
4457
|
+
install: (send) => {
|
|
4458
|
+
try {
|
|
4459
|
+
serverModule?.__installStoreTransport?.(send);
|
|
4460
|
+
} catch {
|
|
4461
|
+
}
|
|
4462
|
+
},
|
|
4463
|
+
deliver: (name, value) => {
|
|
4464
|
+
try {
|
|
4465
|
+
serverModule?.__deliverStorePatch?.(name, value);
|
|
4466
|
+
} catch {
|
|
4467
|
+
}
|
|
4468
|
+
}
|
|
4469
|
+
};
|
|
4470
|
+
try {
|
|
4471
|
+
await loadServer();
|
|
4472
|
+
} catch (err) {
|
|
4473
|
+
console.error("rosetack: dist/server.js failed to load for the serve hooks:", err instanceof Error ? err.message : String(err));
|
|
3157
4474
|
}
|
|
3158
4475
|
const http = await import("node:http");
|
|
3159
4476
|
const server = http.createServer(withAccessLog(serveStatic(OUT_DIR2, true), `w${process.pid}`));
|
|
3160
4477
|
server.requestTimeout = 3e4;
|
|
3161
4478
|
server.headersTimeout = 65e3;
|
|
3162
4479
|
server.keepAliveTimeout = 5e3;
|
|
3163
|
-
server
|
|
3164
|
-
console.log(`\u{1F339} RoseTack worker ${process.pid} listening on http://localhost:${
|
|
4480
|
+
listenFree(server, PORT, async (port) => {
|
|
4481
|
+
console.log(`\u{1F339} RoseTack worker ${process.pid} listening on http://localhost:${port}`);
|
|
3165
4482
|
for (const p of servicePlugins) {
|
|
3166
4483
|
try {
|
|
3167
|
-
await p.onServe({ port
|
|
4484
|
+
await p.onServe({ port, workers, store: storeBridge });
|
|
3168
4485
|
} catch (err) {
|
|
3169
|
-
console.error("rosetack: plugin", p.name, "onServe failed:", err instanceof Error ? err.message : err);
|
|
4486
|
+
console.error("rosetack: plugin", p.name, "onServe failed:", err instanceof Error ? err.message : String(err));
|
|
3170
4487
|
}
|
|
3171
4488
|
}
|
|
3172
4489
|
});
|
|
@@ -3188,10 +4505,65 @@ async function serve() {
|
|
|
3188
4505
|
process.on("SIGTERM", stop);
|
|
3189
4506
|
process.on("SIGINT", stop);
|
|
3190
4507
|
}
|
|
4508
|
+
function templatesDir() {
|
|
4509
|
+
for (const rel of ["../../templates", "../templates"]) {
|
|
4510
|
+
const p = fileURLToPath2(new URL(rel, import.meta.url));
|
|
4511
|
+
if (fs3.existsSync(p)) return p;
|
|
4512
|
+
}
|
|
4513
|
+
return null;
|
|
4514
|
+
}
|
|
4515
|
+
function writeTypeScriptReady(dir) {
|
|
4516
|
+
fs3.writeFileSync(path3.join(dir, "rosetack-env.d.ts"), `/// <reference types="rosetack" />
|
|
4517
|
+
`);
|
|
4518
|
+
fs3.writeFileSync(path3.join(dir, "tsconfig.json"), JSON.stringify({
|
|
4519
|
+
compilerOptions: {
|
|
4520
|
+
target: "ES2022",
|
|
4521
|
+
module: "ESNext",
|
|
4522
|
+
moduleResolution: "bundler",
|
|
4523
|
+
lib: ["ES2022", "DOM", "DOM.Iterable"],
|
|
4524
|
+
strict: true,
|
|
4525
|
+
noEmit: true,
|
|
4526
|
+
skipLibCheck: true
|
|
4527
|
+
},
|
|
4528
|
+
include: ["rosetack-env.d.ts", "src/**/*.ts"]
|
|
4529
|
+
}, null, 2) + "\n");
|
|
4530
|
+
}
|
|
4531
|
+
function copyTemplate(dir, name, display) {
|
|
4532
|
+
const base = templatesDir();
|
|
4533
|
+
const shipped = base ? path3.resolve(base, name) : "";
|
|
4534
|
+
const src = fs3.existsSync(shipped) ? shipped : path3.resolve(name);
|
|
4535
|
+
if (!fs3.existsSync(src) || !fs3.statSync(src).isDirectory()) {
|
|
4536
|
+
const available = base ? fs3.readdirSync(base).join(", ") : "(none found)";
|
|
4537
|
+
console.error(`rosetack: no template '${name}' - available: ${available} (or pass a path to any project directory)`);
|
|
4538
|
+
process.exit(1);
|
|
4539
|
+
}
|
|
4540
|
+
fs3.cpSync(src, dir, {
|
|
4541
|
+
recursive: true,
|
|
4542
|
+
filter: (s) => !/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(s)
|
|
4543
|
+
});
|
|
4544
|
+
const pkgFile = path3.join(dir, "package.json");
|
|
4545
|
+
if (fs3.existsSync(pkgFile)) {
|
|
4546
|
+
const pkg = JSON.parse(fs3.readFileSync(pkgFile, "utf8"));
|
|
4547
|
+
pkg.name = path3.basename(dir);
|
|
4548
|
+
if (pkg.dependencies?.rosetack) pkg.dependencies.rosetack = `^${version()}`;
|
|
4549
|
+
pkg.devDependencies = { ...pkg.devDependencies, typescript: "^5.6.0" };
|
|
4550
|
+
fs3.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
|
|
4551
|
+
}
|
|
4552
|
+
writeTypeScriptReady(dir);
|
|
4553
|
+
console.log(`\u{1F339} RoseTack new: ${display}/ from the '${path3.basename(src)}' template`);
|
|
4554
|
+
console.log(`
|
|
4555
|
+
cd ${display}`);
|
|
4556
|
+
console.log(` npm install && npm run dev`);
|
|
4557
|
+
console.log(` npm run build # then deploy dist/`);
|
|
4558
|
+
}
|
|
3191
4559
|
async function scaffold() {
|
|
3192
|
-
const
|
|
3193
|
-
|
|
3194
|
-
|
|
4560
|
+
const args = argv.slice(1);
|
|
4561
|
+
const tplIdx = args.indexOf("--template");
|
|
4562
|
+
const template = tplIdx >= 0 ? args[tplIdx + 1] : null;
|
|
4563
|
+
const name = args.find((a, i) => !a.startsWith("-") && i !== (tplIdx >= 0 ? tplIdx + 1 : -1));
|
|
4564
|
+
if (!name || tplIdx >= 0 && !template) {
|
|
4565
|
+
const available = templatesDir() ? fs3.readdirSync(templatesDir()).join(", ") : "blog, api, admin, site";
|
|
4566
|
+
console.log(`Usage: rosetack new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${available} - or any project directory)`);
|
|
3195
4567
|
return;
|
|
3196
4568
|
}
|
|
3197
4569
|
const dir = path3.resolve(name);
|
|
@@ -3199,6 +4571,10 @@ async function scaffold() {
|
|
|
3199
4571
|
console.error(`rosetack: ${dir} already exists - pick another name`);
|
|
3200
4572
|
process.exit(1);
|
|
3201
4573
|
}
|
|
4574
|
+
if (template) {
|
|
4575
|
+
copyTemplate(dir, template, name);
|
|
4576
|
+
return;
|
|
4577
|
+
}
|
|
3202
4578
|
const pages = path3.join(dir, "src", "pages");
|
|
3203
4579
|
fs3.mkdirSync(pages, { recursive: true });
|
|
3204
4580
|
fs3.writeFileSync(path3.join(dir, "package.json"), JSON.stringify({
|
|
@@ -3213,30 +4589,11 @@ async function scaffold() {
|
|
|
3213
4589
|
check: "rosetack check"
|
|
3214
4590
|
},
|
|
3215
4591
|
dependencies: { rosetack: `^${version()}` },
|
|
3216
|
-
// TypeScript is a first-class citizen: .rose scripts are typed, and `npm run check`
|
|
3217
|
-
// type-checks every one of them with THIS project's TypeScript …
|
|
3218
4592
|
devDependencies: { typescript: "^5.6.0" }
|
|
3219
4593
|
}, null, 2) + "\n");
|
|
3220
|
-
|
|
3221
|
-
`);
|
|
3222
|
-
fs3.writeFileSync(path3.join(dir, "tsconfig.json"), JSON.stringify({
|
|
3223
|
-
compilerOptions: {
|
|
3224
|
-
target: "ES2022",
|
|
3225
|
-
module: "ESNext",
|
|
3226
|
-
moduleResolution: "bundler",
|
|
3227
|
-
lib: ["ES2022", "DOM", "DOM.Iterable"],
|
|
3228
|
-
strict: true,
|
|
3229
|
-
noEmit: true,
|
|
3230
|
-
skipLibCheck: true
|
|
3231
|
-
},
|
|
3232
|
-
// the env file first (it is what makes the globals visible), then any
|
|
3233
|
-
// .ts the project grows - .rose scripts are checked by `npm run check`
|
|
3234
|
-
include: ["rosetack-env.d.ts", "src/**/*.ts"]
|
|
3235
|
-
}, null, 2) + "\n");
|
|
4594
|
+
writeTypeScriptReady(dir);
|
|
3236
4595
|
fs3.writeFileSync(path3.join(pages, "index.rose"), `<script>
|
|
3237
|
-
|
|
3238
|
-
// The script block is TypeScript - interfaces, annotations, generics and
|
|
3239
|
-
// casts all compile, and \`npm run check\` type-checks them.
|
|
4596
|
+
|
|
3240
4597
|
interface Item { label: string }
|
|
3241
4598
|
|
|
3242
4599
|
let count = $state(0);
|
|
@@ -3245,8 +4602,8 @@ async function scaffold() {
|
|
|
3245
4602
|
|
|
3246
4603
|
function increment() { $setState('count', count() + 1); }
|
|
3247
4604
|
function toggleList() { $setState('showList', !showList()); }
|
|
3248
|
-
|
|
3249
|
-
|
|
4605
|
+
|
|
4606
|
+
|
|
3250
4607
|
let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
|
|
3251
4608
|
</script>
|
|
3252
4609
|
|
|
@@ -3283,7 +4640,6 @@ npm run check # type-checks every .rose script
|
|
|
3283
4640
|
Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
|
|
3284
4641
|
\`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
|
|
3285
4642
|
runs before every request, \`src/pages/api/*.rose\` answers JSON.
|
|
3286
|
-
Full syntax: the README of the rosetack package.
|
|
3287
4643
|
`);
|
|
3288
4644
|
fs3.writeFileSync(path3.join(dir, ".gitignore"), "node_modules/\ndist/\n");
|
|
3289
4645
|
console.log(`\u{1F339} Created ${dir}`);
|
|
@@ -3365,13 +4721,8 @@ async function check() {
|
|
|
3365
4721
|
module: tsMod.ModuleKind.ESNext,
|
|
3366
4722
|
moduleResolution: tsMod.ModuleResolutionKind.Bundler,
|
|
3367
4723
|
lib: ["lib.es2022.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"],
|
|
3368
|
-
// the virtual files are named after the .rose files (so a diagnostic points at the real
|
|
3369
|
-
// path) …
|
|
3370
4724
|
allowNonTsExtensions: true,
|
|
3371
|
-
// the rewired './runtime.js' import points at a real .ts source
|
|
3372
4725
|
allowImportingTsExtensions: true,
|
|
3373
|
-
// `types` is deliberately NOT set: the project's own @types packages (@types/node for
|
|
3374
|
-
// node:sqlite, say) load automatically, the way they do for the user's own .ts files.
|
|
3375
4726
|
skipLibCheck: true
|
|
3376
4727
|
};
|
|
3377
4728
|
const host = tsMod.createCompilerHost(options);
|
|
@@ -3401,11 +4752,28 @@ async function check() {
|
|
|
3401
4752
|
console.error(`rosetack: ${errors} type error${errors === 1 ? "" : "s"} in ${checked} script${checked === 1 ? "" : "s"}`);
|
|
3402
4753
|
process.exit(1);
|
|
3403
4754
|
}
|
|
3404
|
-
var
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
else
|
|
4755
|
+
var argv = process.argv.slice(2);
|
|
4756
|
+
var cmd = argv[0];
|
|
4757
|
+
var asJson = argv.includes("--json");
|
|
4758
|
+
function reportFailure(err) {
|
|
4759
|
+
if (asJson) {
|
|
4760
|
+
process.stdout.write(`${JSON.stringify({ ok: false, errors: [errorInfo(err)] })}
|
|
4761
|
+
`);
|
|
4762
|
+
} else if (err instanceof RoseError) {
|
|
4763
|
+
console.error(`rosetack: ${err.message}`);
|
|
4764
|
+
if (err.hint) console.error(` hint: ${err.hint}`);
|
|
4765
|
+
const at = err.file ? `${err.file}${err.line ? `:${err.line}` : ""}` : null;
|
|
4766
|
+
if (at) console.error(` at ${at}`);
|
|
4767
|
+
} else {
|
|
4768
|
+
console.error(err instanceof Error ? err.stack ?? err.message : String(err));
|
|
4769
|
+
}
|
|
4770
|
+
process.exit(1);
|
|
4771
|
+
}
|
|
4772
|
+
if (cmd === "dev") void dev().catch(reportFailure);
|
|
4773
|
+
else if (cmd === "build") void build2().catch(reportFailure);
|
|
4774
|
+
else if (cmd === "preview") void preview().catch(reportFailure);
|
|
4775
|
+
else if (cmd === "serve") void serve().catch(reportFailure);
|
|
4776
|
+
else if (cmd === "new") void scaffold().catch(reportFailure);
|
|
4777
|
+
else if (cmd === "check") void check().catch(reportFailure);
|
|
4778
|
+
else if (cmd === "prompt") console.log(AI_PROMPT);
|
|
4779
|
+
else console.log("Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] [--static] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON; --static verifies the build is deployable with no server at all; `new <name> [--template blog|api|admin|site]` scaffolds a project)");
|