rosetack 0.1.2 → 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/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 +818 -445
- package/dist-cli/edge.mjs +115 -39
- package/dist-cli/rosetack.mjs +1078 -529
- package/dist-cli/runtime.mjs +115 -34
- package/dist-cli/test.mjs +875 -464
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/edge.ts +69 -61
- package/src/cli/index.ts +243 -328
- package/src/cli/prompt.ts +4 -1
- package/src/cli/shell.ts +67 -69
- package/src/cli/test.ts +9 -70
- package/src/compiler/index.ts +921 -851
- package/src/runtime/index.ts +155 -158
- package/src/types/rosetack.d.ts +16 -66
- 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/test.mjs
CHANGED
|
@@ -218,21 +218,50 @@ function skipTemplate(src, i) {
|
|
|
218
218
|
}
|
|
219
219
|
return j;
|
|
220
220
|
}
|
|
221
|
+
function skipLiteral(src, i) {
|
|
222
|
+
const q = src[i];
|
|
223
|
+
if (q === '"' || q === "'") return skipQuoted(src, i);
|
|
224
|
+
if (q === "`") return skipTemplate(src, i);
|
|
225
|
+
if (q !== "/") return null;
|
|
226
|
+
if (src[i + 1] === "/" || src[i + 1] === "*") return null;
|
|
227
|
+
let b = i - 1;
|
|
228
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
229
|
+
if (b >= 0) {
|
|
230
|
+
if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
|
|
231
|
+
const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
|
|
232
|
+
if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
let j = i + 1;
|
|
236
|
+
let inClass = false;
|
|
237
|
+
while (j < src.length) {
|
|
238
|
+
const c = src[j];
|
|
239
|
+
if (c === "\\") {
|
|
240
|
+
j += 2;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (c === "\n") return null;
|
|
244
|
+
if (inClass) {
|
|
245
|
+
if (c === "]") inClass = false;
|
|
246
|
+
} else if (c === "[") inClass = true;
|
|
247
|
+
else if (c === "/") {
|
|
248
|
+
j++;
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
j++;
|
|
252
|
+
}
|
|
253
|
+
if (j > src.length) return null;
|
|
254
|
+
while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
|
|
255
|
+
return j;
|
|
256
|
+
}
|
|
221
257
|
function stripComments(src) {
|
|
222
258
|
let out = "";
|
|
223
259
|
let i = 0;
|
|
224
260
|
while (i < src.length) {
|
|
225
|
-
const
|
|
226
|
-
if (
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
i = end;
|
|
230
|
-
continue;
|
|
231
|
-
}
|
|
232
|
-
if (q === "`") {
|
|
233
|
-
const end = skipTemplate(src, i);
|
|
234
|
-
out += src.slice(i, end);
|
|
235
|
-
i = end;
|
|
261
|
+
const lit = skipLiteral(src, i);
|
|
262
|
+
if (lit !== null) {
|
|
263
|
+
out += src.slice(i, lit);
|
|
264
|
+
i = lit;
|
|
236
265
|
continue;
|
|
237
266
|
}
|
|
238
267
|
if (src.startsWith("//", i)) {
|
|
@@ -255,6 +284,167 @@ function stripComments(src) {
|
|
|
255
284
|
}
|
|
256
285
|
return out;
|
|
257
286
|
}
|
|
287
|
+
function stripGuardedBranches(src) {
|
|
288
|
+
const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
|
|
289
|
+
const ws = (i2) => {
|
|
290
|
+
while (i2 < src.length && /\s/.test(src[i2])) i2++;
|
|
291
|
+
return i2;
|
|
292
|
+
};
|
|
293
|
+
const ternaryColon = (q) => {
|
|
294
|
+
let depth = 0;
|
|
295
|
+
let i2 = q + 1;
|
|
296
|
+
while (i2 < src.length) {
|
|
297
|
+
const c = src[i2];
|
|
298
|
+
const lit = skipLiteral(src, i2);
|
|
299
|
+
if (lit !== null) {
|
|
300
|
+
i2 = lit;
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
304
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
305
|
+
depth--;
|
|
306
|
+
if (depth < 0) return -1;
|
|
307
|
+
} else if (depth === 0 && c === ":") return i2;
|
|
308
|
+
else if (depth === 0 && c === "?") {
|
|
309
|
+
const inner = ternaryColon(i2);
|
|
310
|
+
if (inner < 0) return -1;
|
|
311
|
+
i2 = inner + 1;
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
i2++;
|
|
315
|
+
}
|
|
316
|
+
return -1;
|
|
317
|
+
};
|
|
318
|
+
const exprEnd = (i2) => {
|
|
319
|
+
let depth = 0;
|
|
320
|
+
while (i2 < src.length) {
|
|
321
|
+
const c = src[i2];
|
|
322
|
+
const lit = skipLiteral(src, i2);
|
|
323
|
+
if (lit !== null) {
|
|
324
|
+
i2 = lit;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
328
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
329
|
+
if (depth === 0) return i2;
|
|
330
|
+
depth--;
|
|
331
|
+
} else if (depth === 0 && (c === "," || c === ";")) return i2;
|
|
332
|
+
else if (depth === 0 && c === "?") {
|
|
333
|
+
const inner = ternaryColon(i2);
|
|
334
|
+
if (inner < 0) return src.length;
|
|
335
|
+
i2 = inner + 1;
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
i2++;
|
|
339
|
+
}
|
|
340
|
+
return src.length;
|
|
341
|
+
};
|
|
342
|
+
const braceEnd = (b) => {
|
|
343
|
+
let depth = 0;
|
|
344
|
+
let i2 = b;
|
|
345
|
+
while (i2 < src.length) {
|
|
346
|
+
const c = src[i2];
|
|
347
|
+
const lit = skipLiteral(src, i2);
|
|
348
|
+
if (lit !== null) {
|
|
349
|
+
i2 = lit;
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
if (c === "{") depth++;
|
|
353
|
+
else if (c === "}") {
|
|
354
|
+
depth--;
|
|
355
|
+
if (depth === 0) return i2;
|
|
356
|
+
}
|
|
357
|
+
i2++;
|
|
358
|
+
}
|
|
359
|
+
return src.length;
|
|
360
|
+
};
|
|
361
|
+
const stmtEnd = (i2) => {
|
|
362
|
+
let depth = 0;
|
|
363
|
+
while (i2 < src.length) {
|
|
364
|
+
const c = src[i2];
|
|
365
|
+
const lit = skipLiteral(src, i2);
|
|
366
|
+
if (lit !== null) {
|
|
367
|
+
i2 = lit;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
371
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
372
|
+
if (depth === 0) return i2;
|
|
373
|
+
depth--;
|
|
374
|
+
} else if (depth === 0 && (c === ";" || c === "\n")) return i2;
|
|
375
|
+
i2++;
|
|
376
|
+
}
|
|
377
|
+
return src.length;
|
|
378
|
+
};
|
|
379
|
+
const isIfGuard = (src2, at) => {
|
|
380
|
+
let b = at - 1;
|
|
381
|
+
while (b >= 0 && /\s/.test(src2[b])) b--;
|
|
382
|
+
if (b < 0 || src2[b] !== "(") return false;
|
|
383
|
+
b--;
|
|
384
|
+
while (b >= 0 && /\s/.test(src2[b])) b--;
|
|
385
|
+
return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
|
|
386
|
+
};
|
|
387
|
+
const blanks = [];
|
|
388
|
+
let i = 0;
|
|
389
|
+
while (i < src.length) {
|
|
390
|
+
const lit = skipLiteral(src, i);
|
|
391
|
+
if (lit !== null) {
|
|
392
|
+
i = lit;
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
GUARD.lastIndex = i;
|
|
396
|
+
const m = GUARD.exec(src);
|
|
397
|
+
if (!m) {
|
|
398
|
+
i++;
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
const browserAfter = m[1] === "!==";
|
|
402
|
+
const j = ws(i + m[0].length);
|
|
403
|
+
const two = src.slice(j, j + 2);
|
|
404
|
+
if (two === "&&" && browserAfter) {
|
|
405
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
406
|
+
} else if (two === "||" && !browserAfter) {
|
|
407
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
408
|
+
} else if (src[j] === "?") {
|
|
409
|
+
const colon = ternaryColon(j);
|
|
410
|
+
if (colon < 0) {
|
|
411
|
+
if (browserAfter) blanks.push([j + 1, src.length]);
|
|
412
|
+
} else if (browserAfter) {
|
|
413
|
+
blanks.push([j + 1, colon]);
|
|
414
|
+
} else {
|
|
415
|
+
blanks.push([colon + 1, exprEnd(colon + 1)]);
|
|
416
|
+
}
|
|
417
|
+
} else if (src[j] === ")" && isIfGuard(src, i)) {
|
|
418
|
+
let bodyEnd;
|
|
419
|
+
const k = ws(j + 1);
|
|
420
|
+
if (src[k] === "{") {
|
|
421
|
+
bodyEnd = braceEnd(k);
|
|
422
|
+
if (browserAfter) blanks.push([k + 1, bodyEnd]);
|
|
423
|
+
} else {
|
|
424
|
+
bodyEnd = stmtEnd(k);
|
|
425
|
+
if (browserAfter) blanks.push([k, bodyEnd]);
|
|
426
|
+
}
|
|
427
|
+
const after = ws(bodyEnd + 1);
|
|
428
|
+
if (src.startsWith("else", after)) {
|
|
429
|
+
const e = ws(after + 4);
|
|
430
|
+
if (src[e] === "{") {
|
|
431
|
+
const close = braceEnd(e);
|
|
432
|
+
if (!browserAfter) blanks.push([e + 1, close]);
|
|
433
|
+
} else {
|
|
434
|
+
const stop = stmtEnd(e);
|
|
435
|
+
if (!browserAfter) blanks.push([e, stop]);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
i = j;
|
|
440
|
+
}
|
|
441
|
+
if (blanks.length === 0) return src;
|
|
442
|
+
const out = [...src];
|
|
443
|
+
for (const [a, b] of blanks) {
|
|
444
|
+
for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
|
|
445
|
+
}
|
|
446
|
+
return out.join("");
|
|
447
|
+
}
|
|
258
448
|
async function loadConfig(root) {
|
|
259
449
|
const file = path.join(root, "rosetack.config.js");
|
|
260
450
|
if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
|
|
@@ -359,8 +549,9 @@ function scanSlotDecls(filePath) {
|
|
|
359
549
|
} catch {
|
|
360
550
|
return [];
|
|
361
551
|
}
|
|
362
|
-
const
|
|
363
|
-
const
|
|
552
|
+
const noScript = src.replace(COMPONENT_RE, "");
|
|
553
|
+
const noBlocks = noScript.replace(STYLE_RE, "");
|
|
554
|
+
const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
|
|
364
555
|
const out = [];
|
|
365
556
|
for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
|
|
366
557
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
|
|
@@ -428,6 +619,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
428
619
|
const usesContext2 = /getContext\s*\(/.test(rawScript2);
|
|
429
620
|
const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
|
|
430
621
|
const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
|
|
622
|
+
const ownRuntimeImports = new Set(
|
|
623
|
+
[...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))
|
|
624
|
+
);
|
|
625
|
+
const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
|
|
626
|
+
const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
|
|
627
|
+
` : "";
|
|
431
628
|
return {
|
|
432
629
|
ssr: "",
|
|
433
630
|
client: "",
|
|
@@ -436,19 +633,19 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
436
633
|
guardName: null,
|
|
437
634
|
style: "",
|
|
438
635
|
hasParams: false,
|
|
439
|
-
api:
|
|
440
|
-
${rewriteRoseImports(`${hoisted.imports}
|
|
636
|
+
api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
|
|
441
637
|
${hoisted.rest}`, "ssr").trim()}`,
|
|
442
638
|
apiMethods,
|
|
443
639
|
hasPrerender,
|
|
444
640
|
usesContext: usesContext2
|
|
445
641
|
};
|
|
446
642
|
}
|
|
447
|
-
const
|
|
643
|
+
const sourceNoScript = source.replace(COMPONENT_RE, "");
|
|
644
|
+
const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
|
|
448
645
|
const styleMatch = sourceNoHead.match(STYLE_RE);
|
|
449
646
|
const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
|
|
450
647
|
const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
|
|
451
|
-
const scriptMatch =
|
|
648
|
+
const scriptMatch = source.match(COMPONENT_RE);
|
|
452
649
|
const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
|
|
453
650
|
const rawScript = roseResolved.script;
|
|
454
651
|
const roseImports = roseResolved.imports;
|
|
@@ -508,8 +705,11 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
508
705
|
}
|
|
509
706
|
const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
|
|
510
707
|
const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
|
|
708
|
+
const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
|
|
709
|
+
const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
|
|
511
710
|
const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
|
|
512
711
|
const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
|
|
712
|
+
const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
|
|
513
713
|
if (csr === false) {
|
|
514
714
|
const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
|
|
515
715
|
if (dead) {
|
|
@@ -585,21 +785,22 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
585
785
|
if (!needsClient) {
|
|
586
786
|
const codeOnly = stripComments(source);
|
|
587
787
|
const scriptCodeOnly = stripComments(rawScript);
|
|
788
|
+
const scriptScannable = stripGuardedBranches(scriptCodeOnly);
|
|
588
789
|
if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
|
|
589
790
|
jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
|
|
590
791
|
}
|
|
591
792
|
if (/javascript:/i.test(codeOnly)) {
|
|
592
793
|
jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
|
|
593
794
|
}
|
|
594
|
-
if (/\b(?:eval|new Function)\s*\(/.test(
|
|
795
|
+
if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
|
|
595
796
|
jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
|
|
596
797
|
}
|
|
597
|
-
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(
|
|
798
|
+
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)) {
|
|
598
799
|
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");
|
|
599
800
|
}
|
|
600
801
|
}
|
|
601
802
|
const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
|
|
602
|
-
const headContent =
|
|
803
|
+
const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
|
|
603
804
|
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
|
|
604
805
|
const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
|
|
605
806
|
const decls = extractDecls(script);
|
|
@@ -639,13 +840,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
639
840
|
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
640
841
|
const wired = wireEventBindings(templateCalled, actionNames);
|
|
641
842
|
const eventBindings = wired.bindings;
|
|
642
|
-
const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
|
|
643
843
|
const stateKeys = decls.map((d) => d.name);
|
|
644
844
|
const comps = new Map(roseImports.map((r) => {
|
|
645
845
|
const abs = path.resolve(path.dirname(filePath), r.specifier);
|
|
646
846
|
const hit = registry.get(abs);
|
|
647
847
|
return [r.name, { index: hit.index, slots: hit.slots }];
|
|
648
848
|
}));
|
|
849
|
+
const ssrTemplate = rewriteQuotedExprAttrs(wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}"), comps);
|
|
850
|
+
assertKnownDirectives(ssrTemplate, filePath);
|
|
649
851
|
const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
|
|
650
852
|
const compiledHead = headContent.trim() ? compileHead(headContent) : "";
|
|
651
853
|
const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
|
|
@@ -675,7 +877,9 @@ ${cleanScript}
|
|
|
675
877
|
usesContext,
|
|
676
878
|
revalidate,
|
|
677
879
|
csr,
|
|
880
|
+
shell,
|
|
678
881
|
buffer,
|
|
882
|
+
controlSignal,
|
|
679
883
|
prefetch,
|
|
680
884
|
vitals,
|
|
681
885
|
bundle,
|
|
@@ -1029,6 +1233,108 @@ function compileHead(head) {
|
|
|
1029
1233
|
flush();
|
|
1030
1234
|
return out;
|
|
1031
1235
|
}
|
|
1236
|
+
var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
|
|
1237
|
+
function assertKnownDirectives(template, filePath) {
|
|
1238
|
+
const rawRanges = [];
|
|
1239
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
1240
|
+
let raw;
|
|
1241
|
+
while (raw = RAW_OPEN.exec(template)) {
|
|
1242
|
+
const tag = raw[1].toLowerCase();
|
|
1243
|
+
const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
|
|
1244
|
+
const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
|
|
1245
|
+
const end = gt < 0 ? template.length : gt + 1;
|
|
1246
|
+
rawRanges.push([raw.index, end]);
|
|
1247
|
+
RAW_OPEN.lastIndex = end;
|
|
1248
|
+
}
|
|
1249
|
+
const COMMENT_RE = /<!--[\s\S]*?-->/g;
|
|
1250
|
+
let note;
|
|
1251
|
+
while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
|
|
1252
|
+
rawRanges.sort((a, b) => a[0] - b[0]);
|
|
1253
|
+
const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
|
|
1254
|
+
const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
|
|
1255
|
+
let m;
|
|
1256
|
+
while (m = DIRECTIVE_RE.exec(template)) {
|
|
1257
|
+
if (inRaw(m.index)) continue;
|
|
1258
|
+
const [, sigil, word] = m;
|
|
1259
|
+
if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
|
|
1260
|
+
if (sigil === "/") {
|
|
1261
|
+
throw new RoseError(
|
|
1262
|
+
"E-TEMPLATE",
|
|
1263
|
+
`${filePath}: {/${word}} does not close anything`,
|
|
1264
|
+
{ file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
|
|
1265
|
+
);
|
|
1266
|
+
}
|
|
1267
|
+
if (word === "else") {
|
|
1268
|
+
throw new RoseError(
|
|
1269
|
+
"E-TEMPLATE",
|
|
1270
|
+
`${filePath}: {:else} is not rosetack syntax - RoseTack has no else branch`,
|
|
1271
|
+
{ 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" }
|
|
1272
|
+
);
|
|
1273
|
+
}
|
|
1274
|
+
throw new RoseError(
|
|
1275
|
+
"E-TEMPLATE",
|
|
1276
|
+
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
1277
|
+
{ 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" }
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
|
|
1281
|
+
while (m = OPENER_RE.exec(template)) {
|
|
1282
|
+
if (inRaw(m.index)) continue;
|
|
1283
|
+
const [, kind, head] = m;
|
|
1284
|
+
if (kind === "each" && !/\bas\s+(\w+)\s*$/.test(head)) {
|
|
1285
|
+
throw new RoseError(
|
|
1286
|
+
"E-TEMPLATE",
|
|
1287
|
+
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
1288
|
+
{ 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)" }
|
|
1289
|
+
);
|
|
1290
|
+
}
|
|
1291
|
+
const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
|
|
1292
|
+
const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
|
|
1293
|
+
let depth = 1;
|
|
1294
|
+
let i = m.index + m[0].length;
|
|
1295
|
+
for (; ; ) {
|
|
1296
|
+
OPEN_RE.lastIndex = i;
|
|
1297
|
+
CLOSE_RE.lastIndex = i;
|
|
1298
|
+
const nextOpen = OPEN_RE.exec(template);
|
|
1299
|
+
const nextClose = CLOSE_RE.exec(template);
|
|
1300
|
+
if (!nextClose) break;
|
|
1301
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
1302
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
1303
|
+
continue;
|
|
1304
|
+
}
|
|
1305
|
+
i = nextClose.index + nextClose[0].length;
|
|
1306
|
+
if (--depth === 0) break;
|
|
1307
|
+
}
|
|
1308
|
+
if (depth !== 0) {
|
|
1309
|
+
throw new RoseError(
|
|
1310
|
+
"E-TEMPLATE",
|
|
1311
|
+
`${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
|
|
1312
|
+
{ file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
|
|
1313
|
+
);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
function rewriteQuotedExprAttrs(template, comps) {
|
|
1318
|
+
const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
|
|
1319
|
+
return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
|
|
1320
|
+
if (comps.has(name) || !/\{/.test(attrs)) return tag;
|
|
1321
|
+
const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
|
|
1322
|
+
if (!/\{/.test(value) || value.includes("`")) return whole;
|
|
1323
|
+
const spans = templateExprSpans(value);
|
|
1324
|
+
if (spans.length === 0) return whole;
|
|
1325
|
+
let expr = "";
|
|
1326
|
+
let last = 0;
|
|
1327
|
+
for (const s of spans) {
|
|
1328
|
+
if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
|
|
1329
|
+
expr += (expr ? " + " : "") + `(${s.expr})`;
|
|
1330
|
+
last = s.end + 1;
|
|
1331
|
+
}
|
|
1332
|
+
if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
|
|
1333
|
+
return `${attr}={${expr}}`;
|
|
1334
|
+
});
|
|
1335
|
+
return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1032
1338
|
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
|
|
1033
1339
|
let result = "";
|
|
1034
1340
|
let remaining = template;
|
|
@@ -1048,6 +1354,25 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1048
1354
|
if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
|
|
1049
1355
|
if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
|
|
1050
1356
|
const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
|
|
1357
|
+
const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
|
|
1358
|
+
const rawHit = rawOpenRe.exec(remaining);
|
|
1359
|
+
if (rawHit && earliest && rawHit.index < earliest.index) {
|
|
1360
|
+
const tag = rawHit[1].toLowerCase();
|
|
1361
|
+
const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
|
|
1362
|
+
const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
|
|
1363
|
+
const end = gt < 0 ? remaining.length : gt + 1;
|
|
1364
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
1365
|
+
remaining = remaining.substring(end);
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1368
|
+
const noteAt = remaining.indexOf("<!--");
|
|
1369
|
+
if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
|
|
1370
|
+
const noteEnd = remaining.indexOf("-->", noteAt + 4);
|
|
1371
|
+
const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
|
|
1372
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
1373
|
+
remaining = remaining.substring(end);
|
|
1374
|
+
continue;
|
|
1375
|
+
}
|
|
1051
1376
|
if (!earliest) {
|
|
1052
1377
|
result += emitChunk(remaining, acc, closes, scope);
|
|
1053
1378
|
break;
|
|
@@ -1439,7 +1764,8 @@ function compileSlot(acc) {
|
|
|
1439
1764
|
return `${acc} += String(children);
|
|
1440
1765
|
`;
|
|
1441
1766
|
}
|
|
1442
|
-
var RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, ifMark, eachMark, headMark, rawMark } from './runtime.js';`;
|
|
1767
|
+
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';`;
|
|
1768
|
+
var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
1443
1769
|
function propsCode(props) {
|
|
1444
1770
|
if (props.length === 0) return "";
|
|
1445
1771
|
return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
|
|
@@ -1451,16 +1777,7 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
1451
1777
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
1452
1778
|
return { o, fn };
|
|
1453
1779
|
};
|
|
1454
|
-
const __slotBlock = (closes, sl, name, pairs) =>
|
|
1455
|
-
const hit = __slot(sl, name, pairs);
|
|
1456
|
-
const idx = closes.length;
|
|
1457
|
-
closes.push(() => {
|
|
1458
|
-
if (!hit) return null;
|
|
1459
|
-
const c = [];
|
|
1460
|
-
return { html: String(hit.fn(hit.o, c)), closes: c, scope: hit.o };
|
|
1461
|
-
});
|
|
1462
|
-
return "<!--\\u27e6i:" + idx + "\\u27e7-->" + (hit ? String(hit.fn(hit.o, [])) : "") + "<!--\\u27e6/i:" + idx + "\\u27e7-->";
|
|
1463
|
-
};`;
|
|
1780
|
+
const __slotBlock = (closes, sl, name, pairs) => slotBlockMark(closes, __slot(sl, name, pairs));`;
|
|
1464
1781
|
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
|
|
1465
1782
|
const headCode = headFn ? `
|
|
1466
1783
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
@@ -1485,9 +1802,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
|
|
|
1485
1802
|
${script}
|
|
1486
1803
|
${stateDeclsCode}
|
|
1487
1804
|
${dataDeclsCode}
|
|
1488
|
-
|
|
1489
|
-
// applied to the state the declarations above just established (a no-op on
|
|
1490
|
-
// every path that is not a server action's re-render - see the runtime).
|
|
1805
|
+
|
|
1491
1806
|
${isComponent ? "" : "applyStateDeltas();"}
|
|
1492
1807
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1493
1808
|
let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
|
|
@@ -1497,6 +1812,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
|
|
|
1497
1812
|
}
|
|
1498
1813
|
function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
|
|
1499
1814
|
const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
|
|
1815
|
+
const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
|
|
1500
1816
|
const headCode = headFn ? `
|
|
1501
1817
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
1502
1818
|
__html += headMark(closes, __head);` : "";
|
|
@@ -1506,7 +1822,9 @@ ${RUNTIME_IMPORTS}
|
|
|
1506
1822
|
${imports}
|
|
1507
1823
|
|
|
1508
1824
|
${exports}
|
|
1509
|
-
|
|
1825
|
+
${clientSetState ? `
|
|
1826
|
+
${clientSetState}
|
|
1827
|
+
` : ""}
|
|
1510
1828
|
${namedSlots ? SLOT_HELPER : ""}
|
|
1511
1829
|
|
|
1512
1830
|
export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
|
|
@@ -1529,6 +1847,7 @@ var routeShipsNoJs = (infos, compiled, i) => {
|
|
|
1529
1847
|
if (compiled[i].needsClient) return false;
|
|
1530
1848
|
return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
|
|
1531
1849
|
};
|
|
1850
|
+
var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
|
|
1532
1851
|
function buildReport(infos, compiled) {
|
|
1533
1852
|
return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
|
|
1534
1853
|
if (routeShipsNoJs(infos, compiled, i)) {
|
|
@@ -1539,6 +1858,48 @@ function buildReport(infos, compiled) {
|
|
|
1539
1858
|
return `${info.routePath} client JS ${why}${forced}`;
|
|
1540
1859
|
});
|
|
1541
1860
|
}
|
|
1861
|
+
var MOUNT_ENTRY = `
|
|
1862
|
+
import { start, postForm } from '/client.js';
|
|
1863
|
+
|
|
1864
|
+
for (const el of document.querySelectorAll('[data-rosetack]')) {
|
|
1865
|
+
const route = el.getAttribute('data-rosetack');
|
|
1866
|
+
const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
|
|
1867
|
+
const parsed = new DOMParser().parseFromString(doc, 'text/html');
|
|
1868
|
+
// A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
|
|
1869
|
+
const app = parsed.getElementById('app');
|
|
1870
|
+
if (app) {
|
|
1871
|
+
el.innerHTML = app.innerHTML;
|
|
1872
|
+
} else {
|
|
1873
|
+
for (const node of Array.from(parsed.body.children)) {
|
|
1874
|
+
if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
// start() resumes from #__rosetack_state (zero hydration), so the state
|
|
1878
|
+
|
|
1879
|
+
const state = parsed.getElementById('__rosetack_state');
|
|
1880
|
+
if (state) el.appendChild(state);
|
|
1881
|
+
|
|
1882
|
+
const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
|
|
1883
|
+
await start(el, route, rendered === route);
|
|
1884
|
+
if (state) state.remove();
|
|
1885
|
+
|
|
1886
|
+
el.addEventListener('click', (e) => {
|
|
1887
|
+
const a = e.target.closest && e.target.closest('a[href^="/"]');
|
|
1888
|
+
if (!a || !el.contains(a)) return;
|
|
1889
|
+
e.preventDefault();
|
|
1890
|
+
el.setAttribute('data-rosetack', a.getAttribute('href'));
|
|
1891
|
+
start(el, a.getAttribute('href'), false);
|
|
1892
|
+
});
|
|
1893
|
+
// Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
|
|
1894
|
+
el.addEventListener('submit', (e) => {
|
|
1895
|
+
const f = e.target;
|
|
1896
|
+
if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
|
|
1897
|
+
if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
|
|
1898
|
+
e.preventDefault();
|
|
1899
|
+
postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
`;
|
|
1542
1903
|
async function buildProject(root, outDir) {
|
|
1543
1904
|
await fs.promises.mkdir(outDir, { recursive: true });
|
|
1544
1905
|
const stale = (await fs.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
@@ -1640,9 +2001,7 @@ async function buildProject(root, outDir) {
|
|
|
1640
2001
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
1641
2002
|
if (runtimePlugins.length > 0) {
|
|
1642
2003
|
const configRel = path.relative(buildDir, path.join(root, "rosetack.config.js")).replace(/\\/g, "/");
|
|
1643
|
-
await fs.promises.writeFile(path.join(buildDir, "plugins.js"),
|
|
1644
|
-
// Bundled into dist/server.js: these hooks run per request on every server
|
|
1645
|
-
// (Node, dev/preview, edge). Transform hooks already ran at build time.
|
|
2004
|
+
await fs.promises.writeFile(path.join(buildDir, "plugins.js"), `
|
|
1646
2005
|
import config from ${JSON.stringify(configRel)};
|
|
1647
2006
|
|
|
1648
2007
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -1671,8 +2030,34 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1671
2030
|
await fs.promises.writeFile(path.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
|
|
1672
2031
|
}
|
|
1673
2032
|
}
|
|
1674
|
-
const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
|
|
1675
|
-
|
|
2033
|
+
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) => {
|
|
2034
|
+
const rank = (pattern) => {
|
|
2035
|
+
const segs = pattern.split("/");
|
|
2036
|
+
return [
|
|
2037
|
+
segs.filter((s) => s.startsWith("**")).length,
|
|
2038
|
+
segs.filter((s) => s.startsWith("*")).length,
|
|
2039
|
+
segs.filter((s) => s.startsWith(":")).length
|
|
2040
|
+
];
|
|
2041
|
+
};
|
|
2042
|
+
const ra = rank(a.info.pattern);
|
|
2043
|
+
const rb = rank(b.info.pattern);
|
|
2044
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2045
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2046
|
+
});
|
|
2047
|
+
const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
|
|
2048
|
+
const rank = (pattern) => {
|
|
2049
|
+
const segs = pattern.split("/");
|
|
2050
|
+
return [
|
|
2051
|
+
segs.filter((s) => s.startsWith("**")).length,
|
|
2052
|
+
segs.filter((s) => s.startsWith("*")).length,
|
|
2053
|
+
segs.filter((s) => s.startsWith(":")).length
|
|
2054
|
+
];
|
|
2055
|
+
};
|
|
2056
|
+
const ra = rank(a.info.pattern);
|
|
2057
|
+
const rb = rank(b.info.pattern);
|
|
2058
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2059
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2060
|
+
});
|
|
1676
2061
|
const compose = (idx) => {
|
|
1677
2062
|
let expr = `render_${idx}`;
|
|
1678
2063
|
for (const i of layoutsOf(infos, idx)) {
|
|
@@ -1703,8 +2088,16 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1703
2088
|
const named = [actionImports, guardImport].filter(Boolean).join(", ");
|
|
1704
2089
|
return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
|
|
1705
2090
|
}).join("\n");
|
|
1706
|
-
const
|
|
1707
|
-
|
|
2091
|
+
const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
|
|
2092
|
+
const rel = path.relative(path.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
|
|
2093
|
+
const dir = path.posix.dirname(rel);
|
|
2094
|
+
const prefix = dir === "." ? "/" : "/" + dir;
|
|
2095
|
+
const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
|
|
2096
|
+
return { prefix, render: split ? loaderOf(i) : compose(i), flags };
|
|
2097
|
+
}).sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2098
|
+
const notFoundTable = `[
|
|
2099
|
+
${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
|
|
2100
|
+
]`;
|
|
1708
2101
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
1709
2102
|
const errorRender = errIdx >= 0 ? split ? loaderOf(errIdx) : compose(errIdx) : "null";
|
|
1710
2103
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
@@ -1728,9 +2121,11 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1728
2121
|
}
|
|
1729
2122
|
}
|
|
1730
2123
|
const csrFlag = routeNoJs(i) ? ", csr: false" : "";
|
|
2124
|
+
const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
|
|
1731
2125
|
const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
|
|
2126
|
+
const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
|
|
1732
2127
|
const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
|
|
1733
|
-
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
|
|
2128
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
|
|
1734
2129
|
}).join(",\n ");
|
|
1735
2130
|
const serverEntry = `
|
|
1736
2131
|
${serverImports}
|
|
@@ -1742,12 +2137,7 @@ const __pluginHooks = [];
|
|
|
1742
2137
|
const __hasRequestHooks = false;
|
|
1743
2138
|
const __hasResponseHooks = false;`}
|
|
1744
2139
|
|
|
1745
|
-
|
|
1746
|
-
// middleware and may short-circuit the request with its own Response; onResponse
|
|
1747
|
-
// runs once the response exists and may replace it. Both are no-ops when the
|
|
1748
|
-
// project declares no runtime hooks. A throwing hook is logged and skipped -
|
|
1749
|
-
// the request continues - so a broken logging plugin can never take a site
|
|
1750
|
-
// down (a build-time transform, by contrast, fails loudly).
|
|
2140
|
+
|
|
1751
2141
|
export async function runRequestHooks(ctx) {
|
|
1752
2142
|
for (const p of __pluginHooks) {
|
|
1753
2143
|
if (!p.onRequest) continue;
|
|
@@ -1775,32 +2165,20 @@ export async function runResponseHooks(ctx, res) {
|
|
|
1775
2165
|
return out;
|
|
1776
2166
|
}
|
|
1777
2167
|
|
|
1778
|
-
|
|
1779
|
-
|
|
2168
|
+
|
|
2169
|
+
|
|
1780
2170
|
export const hasRequestHooks = __hasRequestHooks;
|
|
1781
2171
|
export const hasResponseHooks = __hasResponseHooks;
|
|
1782
2172
|
|
|
1783
|
-
// P0-1: the query of the request being rendered, for $query().
|
|
1784
|
-
// call this before every render (stream, buffered, POST, api) with the parsed
|
|
1785
|
-
// query string; routing itself matches the pathname, which is what fixed the
|
|
1786
|
-
// query-404. A render with no query (the build's prerender, the ISR
|
|
1787
|
-
// background pass) passes {} explicitly - the bag is per request, so a stale
|
|
1788
|
-
// one must never leak into the next.
|
|
2173
|
+
// P0-1: the query of the request being rendered, for $query().
|
|
1789
2174
|
export function setQuery(query) {
|
|
1790
2175
|
setRequestQuery(query || {});
|
|
1791
2176
|
}
|
|
1792
2177
|
|
|
1793
|
-
|
|
1794
|
-
// src/locales/*.json. A route segment named [lang] is the locale: the value
|
|
1795
|
-
// must name one of these dictionaries, and $t resolves keys against it.
|
|
2178
|
+
|
|
1796
2179
|
setLocales(${localesJson}, '${defaultLocale}');
|
|
1797
2180
|
|
|
1798
|
-
|
|
1799
|
-
// own process with its own dist/server.js module, so a $store write must
|
|
1800
|
-
// travel: this worker -> primary -> every other worker. process.send exists
|
|
1801
|
-
// only inside cluster workers, so a single-process runner (dev, preview,
|
|
1802
|
-
// the edge adapter) keeps the transport null and $store stays plain
|
|
1803
|
-
// per-process state - the documented boundary, not a bug.
|
|
2181
|
+
|
|
1804
2182
|
if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
1805
2183
|
setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
|
|
1806
2184
|
process.on('message', (msg) => {
|
|
@@ -1808,76 +2186,45 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
|
1808
2186
|
});
|
|
1809
2187
|
}
|
|
1810
2188
|
|
|
2189
|
+
// (the cross-machine seam): the cluster relay above covers ONE machine.
|
|
2190
|
+
export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
|
|
2191
|
+
setStoreTransport(send);
|
|
2192
|
+
}
|
|
2193
|
+
export function __deliverStorePatch(name: string, value: unknown): void {
|
|
2194
|
+
applyStorePatch(name, value);
|
|
2195
|
+
}
|
|
2196
|
+
|
|
1811
2197
|
export { localeList };
|
|
1812
2198
|
export const defaultLocale = '${defaultLocale}';
|
|
1813
2199
|
|
|
1814
|
-
// Route params maps, re-exported for the build's prerender step: routePath
|
|
1815
|
-
// -> the component's exported params (a static map or a function). Reading
|
|
1816
|
-
// them through the server bundle keeps the deploy dir free of component
|
|
1817
|
-
// modules - both bundles are self-contained, nothing else may ship. Only
|
|
1818
|
-
// components that actually export params appear here (a missing export
|
|
1819
|
-
// means the dynamic route renders on demand).
|
|
2200
|
+
// Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
|
|
1820
2201
|
${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
|
|
1821
2202
|
|
|
1822
2203
|
export const routeParams = {
|
|
1823
2204
|
${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
|
|
1824
2205
|
};
|
|
1825
2206
|
|
|
1826
|
-
// Routes whose component reads the request context (getContext()), mutates a
|
|
1827
|
-
// shared store ($store()), reads the query ($query(), P0-1), opted into
|
|
1828
|
-
// nonce-based CSP or into the buffered path (buffer = true, P0-2):
|
|
1829
|
-
// the bag is per-request, the store is per-process, a nonce is per-response,
|
|
1830
|
-
// and a buffered route's hooks must run per request - so these are dynamic.
|
|
1831
|
-
// The build never bakes them and the servers never answer them from a
|
|
1832
|
-
// prerendered file. Public routes keep the static fast path (file cache,
|
|
1833
|
-
// ETag/304, streaming) untouched.
|
|
2207
|
+
// Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
|
|
1834
2208
|
export const dynamicRoutes = [
|
|
1835
|
-
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
2209
|
+
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1836
2210
|
];
|
|
1837
2211
|
|
|
1838
|
-
// Which api routes opt into build-time baking (export const prerender = true):
|
|
1839
|
-
// routePath -> boolean. The build calls the GET handler once and writes the
|
|
1840
|
-
// body to dist/, so the Go single binary serves read-only APIs without Node.
|
|
2212
|
+
// Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
|
|
1841
2213
|
${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
|
|
1842
2214
|
|
|
1843
2215
|
export const apiPrerender = {
|
|
1844
2216
|
${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
|
|
1845
2217
|
};
|
|
1846
2218
|
|
|
1847
|
-
|
|
1848
|
-
// bakes these routes like any other, and the preview server serves the
|
|
1849
|
-
// baked file for up to N seconds - after which the next request is answered
|
|
1850
|
-
// STALE (instant, from disk) while a background pass re-renders and swaps
|
|
1851
|
-
// the file (ISR). Routes that read the request context are
|
|
1852
|
-
// excluded: they render per request and have no baked file to revalidate.
|
|
1853
|
-
// The dev server ignores the window (it rebuilds on change), the edge
|
|
1854
|
-
// adapter renders live (always fresh), and the Go binary serves the baked
|
|
1855
|
-
// file forever - the same static-half boundary as page POSTs.
|
|
2219
|
+
|
|
1856
2220
|
export const revalidate = [
|
|
1857
2221
|
${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
|
|
1858
2222
|
];
|
|
1859
2223
|
|
|
1860
|
-
//
|
|
1861
|
-
// every render on the server (pages, POSTs, api calls alike). Returning a
|
|
1862
|
-
// Response short-circuits the whole request - a redirect, an auth wall, a
|
|
1863
|
-
// rewrite; returning nothing continues, and getContext() hands the
|
|
1864
|
-
// per-request bag to $data, server actions and api handlers. Absent -> null,
|
|
1865
|
-
// and the servers keep their static fast paths.
|
|
2224
|
+
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
1866
2225
|
export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
|
|
1867
2226
|
|
|
1868
|
-
// Routes whose DOCUMENTS ship without the client bundle (
|
|
1869
|
-
// decided by the compiler since #29): HTML + CSS only - no runtime, no
|
|
1870
|
-
// state script, zero JavaScript for whoever lands on them. The compiler
|
|
1871
|
-
// picks these automatically: a route whose whole chain needs nothing from
|
|
1872
|
-
// the client (no event wiring, no lifecycle, no action, no form) is a
|
|
1873
|
-
// content route. An exported "csr = true" forces the bundle back in; an
|
|
1874
|
-
// exported "csr = false" is the same decision, asserted. The route's render
|
|
1875
|
-
// function still rides in the client bundle, so a client-side navigation
|
|
1876
|
-
// from an interactive page paints it normally and a static deploy's SPA
|
|
1877
|
-
// fallback can render it too; only the document is JS-free.
|
|
1878
|
-
// isNoJs() lets the servers keep these routes on the buffered path: a
|
|
1879
|
-
// streamed no-JS document would carry the shell's default <title> (the
|
|
1880
|
-
// route head is applied client-side at boot, and there is no client).
|
|
2227
|
+
// Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
|
|
1881
2228
|
export const noJsRoutes = [
|
|
1882
2229
|
${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
|
|
1883
2230
|
];
|
|
@@ -1886,21 +2233,12 @@ export function isNoJs(pathname) {
|
|
|
1886
2233
|
return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1887
2234
|
}
|
|
1888
2235
|
|
|
1889
|
-
// P0-2 (bug report): routes that exported "buffer = true".
|
|
1890
|
-
// this BEFORE choosing a path: a streamed response commits its status and
|
|
1891
|
-
// headers before the body exists, so its onResponse hooks cannot see the
|
|
1892
|
-
// document and a render that throws mid-flight still answers 200. A buffered
|
|
1893
|
-
// route keeps every capability and gives up the early flush - the trade is
|
|
1894
|
-
// the route's to make, per route, not the framework's.
|
|
2236
|
+
// P0-2 (bug report): routes that exported "buffer = true".
|
|
1895
2237
|
export function isBuffered(pathname) {
|
|
1896
|
-
return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
|
|
2238
|
+
return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
|
|
1897
2239
|
}
|
|
1898
2240
|
|
|
1899
|
-
|
|
1900
|
-
// map carries them into every response the servers write for it, merged
|
|
1901
|
-
// OVER the framework defaults (the strict CSP) - so an app can tighten or
|
|
1902
|
-
// relax the policy per route. Absent -> null, and the servers keep sending
|
|
1903
|
-
// the defaults alone.
|
|
2241
|
+
|
|
1904
2242
|
export const routeHeaders = [
|
|
1905
2243
|
${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
|
|
1906
2244
|
];
|
|
@@ -1910,14 +2248,7 @@ export function headersFor(pathname) {
|
|
|
1910
2248
|
return hit ? hit.headers : null;
|
|
1911
2249
|
}
|
|
1912
2250
|
|
|
1913
|
-
|
|
1914
|
-
// ). The servers ask this BEFORE writing a document: when it is true they
|
|
1915
|
-
// mint one random nonce per response, put it in the CSP header ('nonce-...'
|
|
1916
|
-
// plus 'strict-dynamic', so the document's own code may load more code) and
|
|
1917
|
-
// stamp the same value on the script tag. The default policy stays a hash -
|
|
1918
|
-
// cspNonceRoutes is empty for an app that never asks, so the fast path is
|
|
1919
|
-
// unchanged. The Go binary never sees this: these routes are dynamic, so it
|
|
1920
|
-
// has no baked file for them to serve.
|
|
2251
|
+
|
|
1921
2252
|
export const cspNonceRoutes = [
|
|
1922
2253
|
${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1923
2254
|
];
|
|
@@ -1926,9 +2257,7 @@ export function cspNonce(pathname) {
|
|
|
1926
2257
|
return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1927
2258
|
}
|
|
1928
2259
|
|
|
1929
|
-
// A Web-standard Request from whatever the host provides: the edge adapter
|
|
1930
|
-
// passes one already; the Node server passes its IncomingMessage (plus the
|
|
1931
|
-
// already-parsed FormData for POSTs, so middleware can read form fields).
|
|
2260
|
+
// A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
|
|
1932
2261
|
function toWebRequest(raw, form) {
|
|
1933
2262
|
if (raw instanceof Request) return raw;
|
|
1934
2263
|
const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
|
|
@@ -1936,13 +2265,7 @@ function toWebRequest(raw, form) {
|
|
|
1936
2265
|
return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
|
|
1937
2266
|
}
|
|
1938
2267
|
|
|
1939
|
-
|
|
1940
|
-
// its short-circuit Response, or null to continue. The servers call this
|
|
1941
|
-
// EXACTLY ONCE per request, before anything else: it resets the per-request
|
|
1942
|
-
// context bag and the middleware fills it via getContext(), which $data,
|
|
1943
|
-
// server actions and api handlers then read while rendering. rawReq: the
|
|
1944
|
-
// host's request (Node IncomingMessage or a Web-standard Request); form:
|
|
1945
|
-
// the already-parsed FormData of a POST.
|
|
2268
|
+
|
|
1946
2269
|
export async function runMiddleware(rawReq, form) {
|
|
1947
2270
|
resetRequestContext();
|
|
1948
2271
|
if (!middleware || !rawReq) return null;
|
|
@@ -1954,10 +2277,7 @@ const routes = [
|
|
|
1954
2277
|
${serverRoutes}
|
|
1955
2278
|
];
|
|
1956
2279
|
|
|
1957
|
-
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
|
|
1958
|
-
// render HTML and never reach the client bundle. The middleware ran before
|
|
1959
|
-
// this (the servers call runMiddleware() first), so handlers can read
|
|
1960
|
-
// getContext() for auth without re-running anything.
|
|
2280
|
+
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
|
|
1961
2281
|
const apiRoutes = [
|
|
1962
2282
|
${apiRoutes.map(({ info, i }) => {
|
|
1963
2283
|
const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
@@ -1965,19 +2285,40 @@ const apiRoutes = [
|
|
|
1965
2285
|
}).join(",\n ")}
|
|
1966
2286
|
];
|
|
1967
2287
|
|
|
1968
|
-
// pages
|
|
1969
|
-
|
|
2288
|
+
// Not-found pages, deepest segment first: the root 404.rose ('/') and any
|
|
2289
|
+
// pages/<seg>/_notfound.rose, each already composed with its layout chain.
|
|
2290
|
+
// notFoundFor picks the nearest one up the path - an /admin miss answers
|
|
2291
|
+
// the admin 404, a public miss the site's - and notFoundPage is the whole
|
|
2292
|
+
// answer (real 404 status, or the built-in plain 404 when the app has none).
|
|
2293
|
+
const notFoundRoutes = ${notFoundTable};
|
|
2294
|
+
const notFoundFor = (pathname) => {
|
|
2295
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
2296
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
2297
|
+
}
|
|
2298
|
+
return null;
|
|
2299
|
+
};
|
|
2300
|
+
|
|
2301
|
+
const notFoundFlags = (pathname) => {
|
|
2302
|
+
for (const [prefix, render, flags] of notFoundRoutes) {
|
|
2303
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
|
|
2304
|
+
}
|
|
2305
|
+
return null;
|
|
2306
|
+
};
|
|
2307
|
+
const notFoundPage = async (pathname) => {
|
|
2308
|
+
const nf = notFoundFor(pathname);
|
|
2309
|
+
if (nf) {
|
|
2310
|
+
const page = await renderFallback(pathname, nf);
|
|
2311
|
+
// __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
|
|
2312
|
+
return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
|
|
2313
|
+
}
|
|
2314
|
+
return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
|
|
2315
|
+
};
|
|
2316
|
+
|
|
1970
2317
|
|
|
1971
|
-
// pages/500.rose (with its layouts) or null -> built-in plain 500: a route
|
|
1972
2318
|
// whose render throws degrades to this instead of failing the response.
|
|
1973
2319
|
const errorPage = ${errorRender};
|
|
1974
2320
|
|
|
1975
|
-
|
|
1976
|
-
// of its [lang] segment (the default when there is none, or when the segment
|
|
1977
|
-
// names no dictionary: that request 404s in the default language) and the
|
|
1978
|
-
// reading direction that locale implies. The buffered render returns the same
|
|
1979
|
-
// pair; the streaming path needs it BEFORE the shell flushes, which is why
|
|
1980
|
-
// the servers ask for it by pathname.
|
|
2321
|
+
|
|
1981
2322
|
export function docAttrs(pathname) {
|
|
1982
2323
|
for (const route of routes) {
|
|
1983
2324
|
if (!matchRoute(route.pattern, pathname)) continue;
|
|
@@ -1987,7 +2328,7 @@ export function docAttrs(pathname) {
|
|
|
1987
2328
|
const lang = pathname.split('/')[langIdx];
|
|
1988
2329
|
if (isLocale(lang)) return { lang, dir: localeDir(lang) };
|
|
1989
2330
|
}
|
|
1990
|
-
break;
|
|
2331
|
+
break;
|
|
1991
2332
|
}
|
|
1992
2333
|
return { lang: defaultLocale, dir: localeDir(defaultLocale) };
|
|
1993
2334
|
}
|
|
@@ -2000,8 +2341,22 @@ async function renderFallback(pathname, render) {
|
|
|
2000
2341
|
}
|
|
2001
2342
|
|
|
2002
2343
|
export function matchRoute(pattern, pathname) {
|
|
2344
|
+
// Q0 (bug report): one canonical URL per route.
|
|
2345
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
2003
2346
|
const patternParts = pattern.split('/');
|
|
2004
2347
|
const pathParts = pathname.split('/');
|
|
2348
|
+
|
|
2349
|
+
const last = patternParts[patternParts.length - 1];
|
|
2350
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
2351
|
+
const fixed = patternParts.slice(0, -1);
|
|
2352
|
+
if (pathParts.length < fixed.length) return false;
|
|
2353
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
2354
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
2355
|
+
if (fixed[i].startsWith(':')) continue;
|
|
2356
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
2357
|
+
}
|
|
2358
|
+
return true;
|
|
2359
|
+
}
|
|
2005
2360
|
if (patternParts.length !== pathParts.length) return false;
|
|
2006
2361
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2007
2362
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -2010,13 +2365,7 @@ export function matchRoute(pattern, pathname) {
|
|
|
2010
2365
|
return true;
|
|
2011
2366
|
}
|
|
2012
2367
|
|
|
2013
|
-
// Head blocks (one per component in the route chain) are pulled out of the
|
|
2014
|
-
// page html: the shell injects them into <head>, and the client re-applies
|
|
2015
|
-
// them on navigation. Document order is page-first, so the shell's keyed
|
|
2016
|
-
// merge lets a page override its layouts. The EMPTY marker pair stays in the
|
|
2017
|
-
// body so the client's wire() still finds the block: at boot it adopts the
|
|
2018
|
-
// shell-injected elements in place (marked with the same keys, so no
|
|
2019
|
-
// duplicates) and keeps the head reactive.
|
|
2368
|
+
// Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
|
|
2020
2369
|
function extractHead(rendered) {
|
|
2021
2370
|
const head = [];
|
|
2022
2371
|
const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
|
|
@@ -2026,18 +2375,7 @@ function extractHead(rendered) {
|
|
|
2026
2375
|
return { html, head };
|
|
2027
2376
|
}
|
|
2028
2377
|
|
|
2029
|
-
//
|
|
2030
|
-
// selected server action runs first and returns a state patch (e.g.
|
|
2031
|
-
// { guests: [...] }); seeding those keys BEFORE the render makes state()
|
|
2032
|
-
// adopt them, so the response is the page as it looks AFTER the action -
|
|
2033
|
-
// with or without JS. A __action field picks the action by name (default
|
|
2034
|
-
// 'action', the conventional <form method="POST"> target); a click handler
|
|
2035
|
-
// bound to an action ($action('like')) sends the same field.
|
|
2036
|
-
// A route whose render throws degrades to pages/500.rose (status 500) - or
|
|
2037
|
-
// the built-in plain 500 - instead of failing the whole response.
|
|
2038
|
-
// The middleware does NOT run here: the servers run it once per request via
|
|
2039
|
-
// runMiddleware() (which also seeds the request context), so a page render
|
|
2040
|
-
// never re-runs it.
|
|
2378
|
+
// Form: the submitted FormData of a progressive-enhancement POST.
|
|
2041
2379
|
export async function renderPage(pathname, form) {
|
|
2042
2380
|
clearRequestState();
|
|
2043
2381
|
for (const route of routes) {
|
|
@@ -2045,31 +2383,21 @@ export async function renderPage(pathname, form) {
|
|
|
2045
2383
|
const patternParts = route.pattern.split('/');
|
|
2046
2384
|
const pathParts = pathname.split('/');
|
|
2047
2385
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2386
|
+
const seg = patternParts[i];
|
|
2387
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
2388
|
+
|
|
2389
|
+
|
|
2390
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2051
2391
|
}
|
|
2052
|
-
//
|
|
2053
|
-
// 404 - the URL is the contract, and rendering the page with fallback
|
|
2054
|
-
// strings would serve duplicate content under a bogus language
|
|
2392
|
+
// I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
|
|
2055
2393
|
const langIdx = patternParts.indexOf(':lang');
|
|
2056
2394
|
if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
|
|
2057
|
-
|
|
2058
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
2395
|
+
return await notFoundPage(pathname);
|
|
2059
2396
|
}
|
|
2060
|
-
|
|
2061
|
-
|
|
2397
|
+
|
|
2398
|
+
|
|
2062
2399
|
const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
|
|
2063
|
-
// The action dispatch. The page's guard (exported
|
|
2064
|
-
// beforeAction) runs FIRST and vetoes with an ActionError - the
|
|
2065
|
-
// action-level permission check. Then the selected action runs and its
|
|
2066
|
-
// return value seeds this render's state, per key, so an incremental
|
|
2067
|
-
// patch ($append and friends) grows a large list by one row instead of
|
|
2068
|
-
// re-sending the whole thing. An ActionError from either half is a
|
|
2069
|
-
// BUSINESS failure: it is seeded as the 'actionError' state, the
|
|
2070
|
-
// response carries its status, and the page renders with the failure
|
|
2071
|
-
// visible (a {#boundary} around the action's widget contains it).
|
|
2072
|
-
// Anything else is a bug and keeps going to the 500 page.
|
|
2400
|
+
// The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
|
|
2073
2401
|
let actionStatus = 0;
|
|
2074
2402
|
if (form && route.actions) {
|
|
2075
2403
|
const actionName = form.get('__action') || 'action';
|
|
@@ -2081,9 +2409,7 @@ export async function renderPage(pathname, form) {
|
|
|
2081
2409
|
if (patch && typeof patch === 'object') {
|
|
2082
2410
|
for (const key of Object.keys(patch)) {
|
|
2083
2411
|
const v = patch[key];
|
|
2084
|
-
// An incremental patch is RECORDED, not applied: the render's
|
|
2085
|
-
// own state declarations apply it, so the delta is relative to
|
|
2086
|
-
// the value the page was going to render anyway.
|
|
2412
|
+
// An incremental patch is RECORDED, not applied: the render's own state declarations apply.
|
|
2087
2413
|
if (v instanceof StateDelta) setStateDelta(key, v);
|
|
2088
2414
|
else setState(key, v);
|
|
2089
2415
|
}
|
|
@@ -2092,6 +2418,11 @@ export async function renderPage(pathname, form) {
|
|
|
2092
2418
|
if (err instanceof ActionError) {
|
|
2093
2419
|
setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
|
|
2094
2420
|
actionStatus = err.code;
|
|
2421
|
+
} else if (err && err.__rosetack === 'redirect') {
|
|
2422
|
+
|
|
2423
|
+
return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
|
|
2424
|
+
} else if (err && err.__rosetack === 'notFound') {
|
|
2425
|
+
return await notFoundPage(pathname);
|
|
2095
2426
|
} else {
|
|
2096
2427
|
throw err;
|
|
2097
2428
|
}
|
|
@@ -2102,32 +2433,27 @@ export async function renderPage(pathname, form) {
|
|
|
2102
2433
|
try {
|
|
2103
2434
|
rendered = extractHead(await route.render([], ''));
|
|
2104
2435
|
} catch (err) {
|
|
2436
|
+
// The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
|
|
2437
|
+
const signal = err && err.__rosetack;
|
|
2438
|
+
if (signal === 'redirect') {
|
|
2439
|
+
return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
|
|
2440
|
+
}
|
|
2441
|
+
if (signal === 'notFound') {
|
|
2442
|
+
return await notFoundPage(pathname);
|
|
2443
|
+
}
|
|
2105
2444
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2106
2445
|
if (errorPage) return { ...(await renderFallback(pathname, errorPage)), status: 500 };
|
|
2107
2446
|
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>', state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
2108
2447
|
}
|
|
2109
2448
|
// __route tells the bootstrap which route this document was rendered for.
|
|
2110
|
-
// A static-file server may serve another route's document (SPA fallback);
|
|
2111
|
-
// the bootstrap then client-renders instead of adopting mismatched DOM.
|
|
2112
2449
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2113
|
-
//
|
|
2114
|
-
|
|
2115
|
-
// asserted csr = false) - the document ships no runtime, no state
|
|
2116
|
-
// script, zero JavaScript. Every other route keeps the bundle. The
|
|
2117
|
-
// caller passes this straight to the shell as js.
|
|
2118
|
-
// Status is the failed action's code when one failed - the page
|
|
2119
|
-
// rendered fine, so the body is the page with the failure visible, and
|
|
2120
|
-
// the status says what happened (a 403 from the guard, a 422 from a
|
|
2121
|
-
// validation action). 200 otherwise.
|
|
2122
|
-
// Lang/dir are the document's <html> attributes - the locale
|
|
2123
|
-
// this route rendered in, and its reading direction.
|
|
2124
|
-
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
|
|
2450
|
+
// 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) .
|
|
2451
|
+
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
|
|
2125
2452
|
}
|
|
2126
2453
|
}
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
2454
|
+
|
|
2455
|
+
|
|
2456
|
+
return await notFoundPage(pathname);
|
|
2131
2457
|
}
|
|
2132
2458
|
|
|
2133
2459
|
// Would renderPageStream handle this path? (matched route = stream, anything
|
|
@@ -2135,21 +2461,20 @@ export async function renderPage(pathname, form) {
|
|
|
2135
2461
|
export function canStream(pathname) {
|
|
2136
2462
|
return routes.some((route) => {
|
|
2137
2463
|
if (!matchRoute(route.pattern, pathname)) return false;
|
|
2138
|
-
//
|
|
2139
|
-
// streamed response cannot change its status - so it takes the buffered
|
|
2140
|
-
// path (renderPage returns the real 404), never the streaming one
|
|
2464
|
+
// I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
|
|
2141
2465
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
2142
2466
|
return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
|
|
2143
2467
|
});
|
|
2144
2468
|
}
|
|
2145
2469
|
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2470
|
+
|
|
2471
|
+
export function shellOff(pathname) {
|
|
2472
|
+
return routes.some(
|
|
2473
|
+
(route) => route.shell === false && matchRoute(route.pattern, pathname),
|
|
2474
|
+
);
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
// === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
|
|
2153
2478
|
export function isApi(pathname) {
|
|
2154
2479
|
return pathname === '/api' || pathname.startsWith('/api/');
|
|
2155
2480
|
}
|
|
@@ -2173,7 +2498,25 @@ export async function handleApi(method, pathname, request) {
|
|
|
2173
2498
|
headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
|
|
2174
2499
|
});
|
|
2175
2500
|
}
|
|
2176
|
-
|
|
2501
|
+
try {
|
|
2502
|
+
return toResponse(await fn(request));
|
|
2503
|
+
} catch (err) {
|
|
2504
|
+
|
|
2505
|
+
const signal = err && err.__rosetack;
|
|
2506
|
+
if (signal === 'redirect') {
|
|
2507
|
+
return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
|
|
2508
|
+
status: err.status ?? 307,
|
|
2509
|
+
headers: { 'content-type': 'application/json', location: err.path },
|
|
2510
|
+
});
|
|
2511
|
+
}
|
|
2512
|
+
if (signal === 'notFound') {
|
|
2513
|
+
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
2514
|
+
status: 404,
|
|
2515
|
+
headers: { 'content-type': 'application/json' },
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2518
|
+
throw err;
|
|
2519
|
+
}
|
|
2177
2520
|
}
|
|
2178
2521
|
}
|
|
2179
2522
|
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
@@ -2182,18 +2525,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
2182
2525
|
});
|
|
2183
2526
|
}
|
|
2184
2527
|
|
|
2185
|
-
// === Streaming SSR ===
|
|
2186
|
-
// The static shell (doctype, <head>, body + container open) flushes BEFORE
|
|
2187
|
-
// the - possibly slow - render completes: the first byte leaves in
|
|
2188
|
-
// microseconds instead of after every $data resolves. The route HTML, the
|
|
2189
|
-
// state script, and the inlined bundle follow as later chunks of one chunked
|
|
2190
|
-
// response - still exactly one request.
|
|
2191
|
-
// The route's <head> tags are NOT in the streamed document: the client
|
|
2192
|
-
// applies them at boot from the body's head markers, so JS users see the
|
|
2193
|
-
// correct head immediately; no-JS consumers of streamed responses get the
|
|
2194
|
-
// static shell head (prerendered files stay complete documents).
|
|
2195
|
-
// Returns 200 (matched; a render throw degrades to the error-page body) or
|
|
2196
|
-
// 404 (unmatched - nothing written, so the caller can still buffer).
|
|
2528
|
+
// === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
|
|
2197
2529
|
export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
2198
2530
|
clearRequestState();
|
|
2199
2531
|
for (const route of routes) {
|
|
@@ -2201,9 +2533,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2201
2533
|
const patternParts = route.pattern.split('/');
|
|
2202
2534
|
const pathParts = pathname.split('/');
|
|
2203
2535
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2536
|
+
const seg = patternParts[i];
|
|
2537
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
2538
|
+
|
|
2539
|
+
|
|
2540
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2207
2541
|
}
|
|
2208
2542
|
// i18n: an unknown locale must 404 BEFORE the shell flushes - a
|
|
2209
2543
|
// streamed response cannot change its status afterwards
|
|
@@ -2214,23 +2548,20 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2214
2548
|
try {
|
|
2215
2549
|
html = extractHead(await route.render([], '')).html;
|
|
2216
2550
|
} catch (err) {
|
|
2217
|
-
|
|
2218
|
-
// (the status stays 200 - a real 500 needs the buffered path, which
|
|
2219
|
-
// the server picks for routes known-broken at build time)
|
|
2551
|
+
|
|
2220
2552
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2221
2553
|
html = errorPage ? extractHead(await errorPage([], '')).html : '<h1>500</h1><p>Something went wrong rendering this page.</p>';
|
|
2222
2554
|
}
|
|
2223
2555
|
write(html);
|
|
2224
|
-
//
|
|
2225
|
-
// ends here - no state script, no inlined bundle. (The servers keep
|
|
2226
|
-
// these routes off the streaming path so their <head> is complete;
|
|
2227
|
-
// this is the correctness floor if one streams anyway.)
|
|
2556
|
+
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
2228
2557
|
if (route.csr === false) {
|
|
2229
2558
|
write('</div>\\n</body>\\n</html>');
|
|
2230
2559
|
return 200;
|
|
2231
2560
|
}
|
|
2232
2561
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2233
|
-
|
|
2562
|
+
// P1-6 (bug report): the JSON data block is embedded in the document.
|
|
2563
|
+
const stateSafe = state.replace(/</g, '\\\\u003c');
|
|
2564
|
+
write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
|
|
2234
2565
|
return 200;
|
|
2235
2566
|
}
|
|
2236
2567
|
}
|
|
@@ -2254,7 +2585,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2254
2585
|
const vitalsBlock = vitalsOn ? `
|
|
2255
2586
|
// the app asked for web-vitals - measure once, at boot, and let the
|
|
2256
2587
|
// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
|
|
2257
|
-
reportVitals;
|
|
2588
|
+
reportVitals();
|
|
2258
2589
|
` : "";
|
|
2259
2590
|
const hasLang = infos.some((i) => i.pattern.includes(":lang"));
|
|
2260
2591
|
const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
|
|
@@ -2262,26 +2593,24 @@ reportVitals;
|
|
|
2262
2593
|
// logical properties both read it). A route with no [lang] segment
|
|
2263
2594
|
// returns to the default locale, and a bogus segment falls back to it
|
|
2264
2595
|
// too, exactly like the server's docAttrs.
|
|
2596
|
+
// Only when this container IS the document's app root. A mount
|
|
2597
|
+
// (dist/mount.js) renders into a foreign page, whose language and
|
|
2598
|
+
// direction belong to the host, not to the mounted route.
|
|
2265
2599
|
const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
|
|
2266
2600
|
const known = !seg || isLocale(seg);
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2601
|
+
if (container === document.getElementById('app')) {
|
|
2602
|
+
const docLang = known && seg ? seg : __defLocale;
|
|
2603
|
+
document.documentElement.lang = docLang;
|
|
2604
|
+
const docDir = localeDir(docLang);
|
|
2605
|
+
if (docDir) document.documentElement.setAttribute('dir', docDir);
|
|
2606
|
+
else document.documentElement.removeAttribute('dir');
|
|
2607
|
+
}
|
|
2272
2608
|
if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
2273
2609
|
const clientEntry = `
|
|
2274
2610
|
${clientImports}
|
|
2275
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
|
|
2276
|
-
|
|
2277
|
-
//
|
|
2278
|
-
// renders any PRELOADED locale from the bundle, so switching language costs
|
|
2279
|
-
// zero requests (the same bet as the inlined route table). a locale
|
|
2280
|
-
// the app left out of the preload (i18n.preload in rosetack.config.js) is a
|
|
2281
|
-
// pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
|
|
2282
|
-
// on first use - one request per language per session, then it renders from
|
|
2283
|
-
// memory like any other. The default build preloads everything and ships no
|
|
2284
|
-
// packs at all.
|
|
2611
|
+
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';
|
|
2612
|
+
|
|
2613
|
+
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
2285
2614
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
2286
2615
|
setLocalePacks(${JSON.stringify(packed)});
|
|
2287
2616
|
${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
|
|
@@ -2291,10 +2620,7 @@ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
|
|
|
2291
2620
|
// reportVitals alive through minification and tree-shaking; the call is one
|
|
2292
2621
|
// statement at boot, before the first render.
|
|
2293
2622
|
import { reportVitals } from './runtime.js';` : ""}
|
|
2294
|
-
// The two pack doors, re-exported for an app that wants to warm a language
|
|
2295
|
-
// before its visitor asks for it (ensureLocale) or to feed a dictionary it
|
|
2296
|
-
// fetched itself (loadLocale). Both are already in the bundle - ensureLocale
|
|
2297
|
-
// is what applyParams calls - so the re-export costs the statement alone.
|
|
2623
|
+
// 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.
|
|
2298
2624
|
export { ensureLocale, loadLocale } from './runtime.js';
|
|
2299
2625
|
${vitalsBlock}
|
|
2300
2626
|
|
|
@@ -2302,14 +2628,7 @@ const routes = [
|
|
|
2302
2628
|
${clientRoutes}
|
|
2303
2629
|
];
|
|
2304
2630
|
|
|
2305
|
-
// === Mode B: lazy route chunks ===
|
|
2306
|
-
// Split mode's registry entries arrive without a render function: loadChain
|
|
2307
|
-
// loads the route's module graph (the page plus its layouts, one chunk per
|
|
2308
|
-
// module, the shared runtime in its own vendor chunk) in parallel and
|
|
2309
|
-
// composes it at runtime - the exact nesting compose() built at compile
|
|
2310
|
-
// time for inline mode. getRender memoizes the composed function on the
|
|
2311
|
-
// entry, so a chunk loads once per session; inline mode's entries are the
|
|
2312
|
-
// render functions themselves, so the helper is a pass-through there.
|
|
2631
|
+
// === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
|
|
2313
2632
|
const loadChain = async (loaders) => {
|
|
2314
2633
|
const mods = await Promise.all(loaders.map((load) => load()));
|
|
2315
2634
|
let expr = (closes, children) => mods[0].render(closes, children);
|
|
@@ -2325,36 +2644,62 @@ const getRender = async (route) => {
|
|
|
2325
2644
|
return (route.render ??= (await route.load()).render);
|
|
2326
2645
|
};
|
|
2327
2646
|
|
|
2328
|
-
// pages
|
|
2329
|
-
const
|
|
2647
|
+
// Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
|
|
2648
|
+
const notFoundRoutes = ${notFoundTable};
|
|
2649
|
+
const notFoundFor = (pathname) => {
|
|
2650
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
2651
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
2652
|
+
}
|
|
2653
|
+
return null;
|
|
2654
|
+
};
|
|
2330
2655
|
|
|
2331
|
-
//
|
|
2332
|
-
// whose render throws on the client degrades to this instead of breaking
|
|
2333
|
-
// navigation.
|
|
2656
|
+
// 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.
|
|
2334
2657
|
const errorPage = ${errorRender};
|
|
2335
2658
|
|
|
2336
2659
|
// Paint a fallback page (404/500) into the container, wired like any render.
|
|
2337
|
-
async function paintFallback(container, page, builtin) {
|
|
2338
|
-
|
|
2339
|
-
clearRequestState();
|
|
2660
|
+
async function paintFallback(container, page, builtin, keepState = false) {
|
|
2661
|
+
if (!keepState) __navReset(container);
|
|
2340
2662
|
clearMounts(); // a failed render leaves stale mounts behind
|
|
2341
2663
|
// inline mode passes the render itself; split mode passes a loader
|
|
2342
2664
|
const render = page ? await getRender(page) : null;
|
|
2343
2665
|
if (render) {
|
|
2344
2666
|
const closes = [];
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2667
|
+
await __withOwner(container, async () => {
|
|
2668
|
+
const html = await render(closes, '');
|
|
2669
|
+
container.innerHTML = html;
|
|
2670
|
+
wire(container, closes);
|
|
2671
|
+
bindEvents(container);
|
|
2672
|
+
flushMounts();
|
|
2673
|
+
});
|
|
2350
2674
|
return;
|
|
2351
2675
|
}
|
|
2352
2676
|
container.innerHTML = builtin;
|
|
2353
2677
|
}
|
|
2354
2678
|
|
|
2679
|
+
|
|
2680
|
+
export async function startNotFound(container, pathname) {
|
|
2681
|
+
const el = document.getElementById('__rosetack_state');
|
|
2682
|
+
if (el) resumeState(el.textContent);
|
|
2683
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
|
|
2684
|
+
}
|
|
2685
|
+
|
|
2355
2686
|
export function matchRoute(pattern, pathname) {
|
|
2687
|
+
// Q0 (bug report): one canonical URL per route.
|
|
2688
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
2356
2689
|
const patternParts = pattern.split('/');
|
|
2357
2690
|
const pathParts = pathname.split('/');
|
|
2691
|
+
|
|
2692
|
+
const last = patternParts[patternParts.length - 1];
|
|
2693
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
2694
|
+
const fixed = patternParts.slice(0, -1);
|
|
2695
|
+
if (pathParts.length < fixed.length) return false;
|
|
2696
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
2697
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
2698
|
+
if (fixed[i].startsWith(':')) continue;
|
|
2699
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
2700
|
+
}
|
|
2701
|
+
return true;
|
|
2702
|
+
}
|
|
2358
2703
|
if (patternParts.length !== pathParts.length) return false;
|
|
2359
2704
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2360
2705
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -2363,85 +2708,64 @@ export function matchRoute(pattern, pathname) {
|
|
|
2363
2708
|
return true;
|
|
2364
2709
|
}
|
|
2365
2710
|
|
|
2366
|
-
// === Link prefetch ===
|
|
2367
|
-
// Hover / focus / touch an internal link and the target route renders NOW -
|
|
2368
|
-
// $data included - against a throwaway signal map. The click that follows
|
|
2369
|
-
// paints from the cached HTML: no await, no request, no spinner. Other
|
|
2370
|
-
// frameworks prefetch data only; rosetack prefetches the whole render because
|
|
2371
|
-
// the inlined bundle already contains every route.
|
|
2372
|
-
// Trade-off: the cache holds either a result or the in-flight promise (dedupes
|
|
2373
|
-
// hover storms); one isolated render runs at a time so signal-map swapping
|
|
2374
|
-
// stays correct without any merging logic. Entries are single-use: a consumed
|
|
2375
|
-
// entry disappears from the cache, which is also how tests observe a hit.
|
|
2376
|
-
// P1, three guards for link-heavy pages:
|
|
2377
|
-
// 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
|
|
2378
|
-
// 'viewport' | 'all'" (root layout); 'all' is the original behavior.
|
|
2379
|
-
// Trade-off: app-global, not per-route - per-route would carry the mode
|
|
2380
|
-
// in each document's shell.
|
|
2381
|
-
// 2. budget - renders are serialized by the queue, so "concurrency" is 1;
|
|
2382
|
-
// the budget caps the QUEUE: a hover storm past it drops the excess
|
|
2383
|
-
// instead of rendering fifty routes nobody clicks.
|
|
2384
|
-
// 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
|
|
2385
|
-
// is evicted first (Map iteration order; entries are single-use, so
|
|
2386
|
-
// insertion order IS the recency order).
|
|
2711
|
+
// === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
|
|
2387
2712
|
let prefetchMode = ${JSON.stringify(prefetchMode)};
|
|
2388
2713
|
export function setPrefetchMode(mode) { prefetchMode = mode; }
|
|
2389
2714
|
const PREFETCH_BUDGET = 8;
|
|
2390
2715
|
const PREFETCH_MAX_CACHED = 4;
|
|
2391
|
-
const prefetchCache = new Map();
|
|
2716
|
+
const prefetchCache = new Map();
|
|
2392
2717
|
let prefetchQueue = Promise.resolve();
|
|
2393
2718
|
let prefetchPending = 0;
|
|
2394
2719
|
|
|
2395
|
-
|
|
2396
|
-
// a runtime pack (i18n.preload) is awaited HERE - the one place every client
|
|
2397
|
-
// render path goes through (navigation, prefetch, action adopt) - so a packed
|
|
2398
|
-
// locale costs one request per session and then renders from memory. A
|
|
2399
|
-
// preloaded locale (the default: every dictionary inline) resolves without
|
|
2400
|
-
// touching the network, so the common path stays synchronous in spirit.
|
|
2720
|
+
|
|
2401
2721
|
async function applyParams(route, pathname) {
|
|
2402
2722
|
const patternParts = route.pattern.split('/');
|
|
2403
2723
|
const pathParts = pathname.split('/');
|
|
2404
2724
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2405
|
-
|
|
2725
|
+
const seg = patternParts[i];
|
|
2726
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
2727
|
+
|
|
2728
|
+
|
|
2729
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2406
2730
|
}
|
|
2407
2731
|
const langIdx = patternParts.indexOf(':lang');
|
|
2408
2732
|
if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
|
|
2409
2733
|
}
|
|
2410
2734
|
|
|
2735
|
+
|
|
2736
|
+
function __netOk() {
|
|
2737
|
+
const c = navigator.connection;
|
|
2738
|
+
if (!c) return true;
|
|
2739
|
+
if (c.saveData) return false;
|
|
2740
|
+
const t = c.effectiveType;
|
|
2741
|
+
return t !== 'slow-2g' && t !== '2g';
|
|
2742
|
+
}
|
|
2743
|
+
|
|
2411
2744
|
export function prefetch(pathname, source = 'hover') {
|
|
2412
2745
|
if (prefetchMode === 'off') return;
|
|
2413
2746
|
if (prefetchMode === 'hover' && source !== 'hover') return;
|
|
2414
2747
|
if (prefetchMode === 'viewport' && source !== 'viewport') return;
|
|
2748
|
+
if (!__netOk()) return; // save-data / 2g: no bytes before the click
|
|
2415
2749
|
if (prefetchCache.has(pathname)) return;
|
|
2416
|
-
if (pathname === location.pathname) return;
|
|
2750
|
+
if (pathname === location.pathname) return;
|
|
2417
2751
|
const route = routes.find((r) => matchRoute(r.pattern, pathname));
|
|
2418
2752
|
if (!route) return;
|
|
2419
|
-
if (prefetchPending >= PREFETCH_BUDGET) return; //
|
|
2420
|
-
// P0-1: the link may carry a query (/search?q=cats). $query() reads the
|
|
2421
|
-
// browser's own URL, which is the page being LEFT - so the prefetched
|
|
2422
|
-
// render would see the wrong one. Override it for the duration and clear
|
|
2423
|
-
// it after; the queue below serializes renders, so one slot is enough.
|
|
2753
|
+
if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
|
|
2424
2754
|
const qi = pathname.indexOf('?');
|
|
2425
2755
|
const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
|
|
2426
2756
|
const p = prefetchQueue.then(async () => {
|
|
2427
2757
|
try {
|
|
2428
2758
|
setPrefetchOverride(qOverride);
|
|
2429
|
-
//
|
|
2430
|
-
// queued and the onCleanup disposers it registered: the paint that
|
|
2431
|
-
// consumes this entry replays the mounts after wiring and adopts the
|
|
2432
|
-
// cleanups, so the prefetched route's timers are disposed on the next
|
|
2433
|
-
// navigation like any live route's
|
|
2759
|
+
// The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
|
|
2434
2760
|
const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
|
|
2435
2761
|
await applyParams(route, pathname); // a packed locale's dictionary lands before the render
|
|
2436
2762
|
const closes = [];
|
|
2437
|
-
const render = await getRender(route);
|
|
2763
|
+
const render = await getRender(route);
|
|
2438
2764
|
const html = await render(closes, '');
|
|
2439
2765
|
return { html, closes };
|
|
2440
2766
|
});
|
|
2441
2767
|
const entry = { ...result, state, mounts, cleanups };
|
|
2442
|
-
prefetchCache.set(pathname, entry); //
|
|
2443
|
-
// evict oldest-first; in-flight promises are never evicted (evicting
|
|
2444
|
-
// one would only force a duplicate render)
|
|
2768
|
+
prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
|
|
2445
2769
|
while (prefetchCache.size > PREFETCH_MAX_CACHED) {
|
|
2446
2770
|
const oldest = prefetchCache.keys().next().value;
|
|
2447
2771
|
if (prefetchCache.get(oldest) instanceof Promise) break;
|
|
@@ -2449,7 +2773,7 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
2449
2773
|
}
|
|
2450
2774
|
return entry;
|
|
2451
2775
|
} catch {
|
|
2452
|
-
prefetchCache.delete(pathname);
|
|
2776
|
+
prefetchCache.delete(pathname);
|
|
2453
2777
|
return null;
|
|
2454
2778
|
} finally {
|
|
2455
2779
|
setPrefetchOverride(null);
|
|
@@ -2462,13 +2786,10 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
2462
2786
|
}
|
|
2463
2787
|
|
|
2464
2788
|
export function prefetchStats() {
|
|
2465
|
-
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
|
|
2789
|
+
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
|
|
2466
2790
|
}
|
|
2467
2791
|
|
|
2468
|
-
// One delegated listener per event type on the app container: survives DOM
|
|
2469
|
-
// swaps and cloned blocks, so handlers never need re-binding. A handler
|
|
2470
|
-
// compiled from a server action (data-on-*="$action:name") dispatches to
|
|
2471
|
-
// $action instead of the local handler registry.
|
|
2792
|
+
// One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
|
|
2472
2793
|
const DELEGATED = ['click', 'input', 'change', 'submit'];
|
|
2473
2794
|
function bindEvents(container) {
|
|
2474
2795
|
if (container.__rosetack_bound) return;
|
|
@@ -2485,48 +2806,64 @@ function bindEvents(container) {
|
|
|
2485
2806
|
}
|
|
2486
2807
|
}
|
|
2487
2808
|
|
|
2488
|
-
// === Server actions from any event ===
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
async function postForm(body) {
|
|
2495
|
-
const res = await fetch(location.pathname, { method: 'POST', body });
|
|
2809
|
+
// === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
|
|
2810
|
+
async function postForm(body, container, pathname) {
|
|
2811
|
+
|
|
2812
|
+
const box = container || document.getElementById('app');
|
|
2813
|
+
const route = pathname || location.pathname;
|
|
2814
|
+
const res = await fetch(route, { method: 'POST', body });
|
|
2496
2815
|
const html = await res.text();
|
|
2497
2816
|
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
2498
2817
|
const next = doc.getElementById('app');
|
|
2499
2818
|
const st = doc.getElementById('__rosetack_state');
|
|
2500
2819
|
const paint = () => {
|
|
2501
|
-
|
|
2502
|
-
adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
|
|
2820
|
+
adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
|
|
2503
2821
|
};
|
|
2504
2822
|
if (document.startViewTransition) document.startViewTransition(paint);
|
|
2505
2823
|
else paint();
|
|
2506
2824
|
}
|
|
2507
2825
|
|
|
2508
|
-
// Call a page's server action by name from any event handler:
|
|
2509
|
-
// <button on:click={like}> compiles to $action('like'). Without JS the
|
|
2510
|
-
// binding is inert - the progressive-enhancement story stays with forms.
|
|
2826
|
+
// Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
|
|
2511
2827
|
export async function $action(name, e) {
|
|
2512
2828
|
if (e && e.preventDefault) e.preventDefault();
|
|
2513
2829
|
const body = new FormData();
|
|
2514
2830
|
body.append('__action', name);
|
|
2515
|
-
|
|
2831
|
+
// An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
|
|
2832
|
+
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
2833
|
+
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
2516
2834
|
}
|
|
2517
2835
|
|
|
2518
2836
|
export { postForm };
|
|
2519
2837
|
|
|
2520
|
-
// The live signal graph as JSON - the same serializeState the zero-hydration
|
|
2521
|
-
// resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
|
|
2522
|
-
// can hand it to the dev server's reload bridge and to a devtools extension.
|
|
2523
|
-
// A local re-export on purpose: it keeps the binding alive through minification
|
|
2524
|
-
// for the bootstrap text appended after the bundle.
|
|
2838
|
+
// The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
|
|
2525
2839
|
export { serializeState };
|
|
2526
2840
|
|
|
2527
|
-
//
|
|
2528
|
-
|
|
2529
|
-
|
|
2841
|
+
// Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
|
|
2842
|
+
|
|
2843
|
+
|
|
2844
|
+
function __ownsDoc(container) {
|
|
2845
|
+
return container === document.getElementById('app');
|
|
2846
|
+
}
|
|
2847
|
+
function __navReset(container) {
|
|
2848
|
+
if (__ownsDoc(container)) {
|
|
2849
|
+
resetEffects();
|
|
2850
|
+
clearRequestState();
|
|
2851
|
+
} else {
|
|
2852
|
+
resetContainerFx(container);
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
// Attribute everything a render creates (state keys, effects, onCleanups) to
|
|
2856
|
+
// its container. The document path sets no owner and keeps the global sets.
|
|
2857
|
+
async function __withOwner(container, fn) {
|
|
2858
|
+
if (__ownsDoc(container)) return fn();
|
|
2859
|
+
setFxOwner(container);
|
|
2860
|
+
try {
|
|
2861
|
+
return await fn();
|
|
2862
|
+
} finally {
|
|
2863
|
+
setFxOwner(null);
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2530
2867
|
export async function start(container, pathname, initial) {
|
|
2531
2868
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2532
2869
|
if (initial) {
|
|
@@ -2535,104 +2872,110 @@ export async function start(container, pathname, initial) {
|
|
|
2535
2872
|
}
|
|
2536
2873
|
for (const route of routes) {
|
|
2537
2874
|
if (matchRoute(route.pattern, pathname)) {
|
|
2538
|
-
//
|
|
2539
|
-
// (before the prefetch check: a cached entry for a bogus locale is
|
|
2540
|
-
// discarded, never painted)
|
|
2875
|
+
// 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).
|
|
2541
2876
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
2542
2877
|
${langDirBlock}
|
|
2543
|
-
await paintFallback(container,
|
|
2878
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2544
2879
|
return;
|
|
2545
2880
|
}
|
|
2546
|
-
// Prefetched on hover/focus/touch: the render already ran, so paint its
|
|
2547
|
-
// HTML and adopt its signal entries - events then patch the very nodes
|
|
2548
|
-
// we wire, and no $data re-runs on click.
|
|
2881
|
+
// 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.
|
|
2549
2882
|
let hit = initial ? undefined : prefetchCache.get(pathname);
|
|
2550
2883
|
if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
|
|
2551
2884
|
if (hit) {
|
|
2552
|
-
prefetchCache.delete(pathname);
|
|
2553
|
-
|
|
2885
|
+
prefetchCache.delete(pathname);
|
|
2886
|
+
__navReset(container);
|
|
2554
2887
|
restoreState(hit.state);
|
|
2555
2888
|
container.innerHTML = hit.html;
|
|
2556
|
-
|
|
2889
|
+
await __withOwner(container, () => {
|
|
2890
|
+
wire(container, hit.closes);
|
|
2891
|
+
bindEvents(container);
|
|
2892
|
+
hit.mounts.forEach((fn) => fn());
|
|
2893
|
+
adoptCleanups(hit.cleanups);
|
|
2894
|
+
});
|
|
2895
|
+
return;
|
|
2896
|
+
}
|
|
2897
|
+
if (!initial) __navReset(container);
|
|
2898
|
+
let broken = false;
|
|
2899
|
+
let signal = null;
|
|
2900
|
+
await __withOwner(container, async () => {
|
|
2901
|
+
await applyParams(route, pathname);
|
|
2902
|
+
const closes = [];
|
|
2903
|
+
let html;
|
|
2904
|
+
try {
|
|
2905
|
+
const render = await getRender(route);
|
|
2906
|
+
html = await render(closes, '');
|
|
2907
|
+
} catch (err) {
|
|
2908
|
+
|
|
2909
|
+
if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
|
|
2910
|
+
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
2911
|
+
|
|
2912
|
+
|
|
2913
|
+
broken = true;
|
|
2914
|
+
return;
|
|
2915
|
+
}
|
|
2916
|
+
if (!initial) container.innerHTML = html;
|
|
2917
|
+
wire(container, closes);
|
|
2557
2918
|
bindEvents(container);
|
|
2558
|
-
|
|
2559
|
-
|
|
2919
|
+
flushMounts();
|
|
2920
|
+
});
|
|
2921
|
+
if (signal === 'notFound') {
|
|
2922
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2560
2923
|
return;
|
|
2561
2924
|
}
|
|
2562
|
-
if (
|
|
2563
|
-
|
|
2564
|
-
|
|
2925
|
+
if (signal) {
|
|
2926
|
+
location.href = signal;
|
|
2927
|
+
return;
|
|
2565
2928
|
}
|
|
2566
|
-
|
|
2567
|
-
const closes = [];
|
|
2568
|
-
let html;
|
|
2569
|
-
try {
|
|
2570
|
-
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
2571
|
-
html = await render(closes, '');
|
|
2572
|
-
} catch {
|
|
2573
|
-
// the route itself is broken: degrade to pages/500.rose (or the
|
|
2574
|
-
// built-in plain 500) instead of leaving the container empty
|
|
2929
|
+
if (broken) {
|
|
2575
2930
|
await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
2576
|
-
return;
|
|
2577
2931
|
}
|
|
2578
|
-
if (!initial) container.innerHTML = html;
|
|
2579
|
-
wire(container, closes);
|
|
2580
|
-
bindEvents(container);
|
|
2581
|
-
flushMounts();
|
|
2582
2932
|
return;
|
|
2583
2933
|
}
|
|
2584
2934
|
}
|
|
2585
|
-
//
|
|
2586
|
-
|
|
2587
|
-
//
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2935
|
+
// Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
|
|
2936
|
+
${hasLang ? ` // the same app-root gate as above - a mount never touches the
|
|
2937
|
+
// host document's language or direction.
|
|
2938
|
+
if (container === document.getElementById('app')) {
|
|
2939
|
+
document.documentElement.lang = __defLocale;
|
|
2940
|
+
document.documentElement.removeAttribute('dir');
|
|
2941
|
+
}` : ""}
|
|
2942
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2591
2943
|
}
|
|
2592
2944
|
|
|
2593
|
-
// Adopt a server-rendered response in place - the JS-enabled half of
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
export async function adopt(container, html, stateJson) {
|
|
2600
|
-
resetEffects();
|
|
2601
|
-
clearRequestState();
|
|
2945
|
+
// Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
|
|
2946
|
+
export async function adopt(container, html, stateJson, pathname) {
|
|
2947
|
+
|
|
2948
|
+
|
|
2949
|
+
const route0 = pathname || location.pathname;
|
|
2950
|
+
__navReset(container);
|
|
2602
2951
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2603
2952
|
resumeState(stateJson);
|
|
2604
2953
|
container.innerHTML = html;
|
|
2605
|
-
|
|
2954
|
+
|
|
2606
2955
|
const st = document.getElementById('__rosetack_state');
|
|
2607
2956
|
if (st) st.textContent = stateJson;
|
|
2608
2957
|
for (const route of routes) {
|
|
2609
|
-
if (matchRoute(route.pattern,
|
|
2610
|
-
await
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2958
|
+
if (matchRoute(route.pattern, route0)) {
|
|
2959
|
+
await __withOwner(container, async () => {
|
|
2960
|
+
await applyParams(route, route0);
|
|
2961
|
+
const closes = [];
|
|
2962
|
+
try {
|
|
2963
|
+
const render = await getRender(route);
|
|
2964
|
+
await render(closes, '');
|
|
2965
|
+
} catch {
|
|
2966
|
+
|
|
2967
|
+
|
|
2968
|
+
return;
|
|
2969
|
+
}
|
|
2970
|
+
wire(container, closes);
|
|
2971
|
+
bindEvents(container);
|
|
2972
|
+
flushMounts();
|
|
2973
|
+
});
|
|
2623
2974
|
return;
|
|
2624
2975
|
}
|
|
2625
2976
|
}
|
|
2626
2977
|
}
|
|
2627
|
-
// === refresh() implementation ===
|
|
2628
|
-
// Re-render the current route in place: the client half of router.refresh()
|
|
2629
|
-
// (a router refresh) / (a full invalidation). Same machinery as a client-side
|
|
2630
|
-
// navigation to the current path - $data re-runs, state re-seeds from the
|
|
2631
|
-
// fresh render, wire() patches the marked nodes - but a refresh never lands
|
|
2632
|
-
// a prefetch entry: a hover from a minute ago is exactly what it exists to
|
|
2633
|
-
// bypass. Zero requests: the render (and its $data) runs in the page.
|
|
2634
|
-
// Trade-off: state resets like navigation (no per-key retention); add
|
|
2635
|
-
// retention when an app needs refresh-without-losing-input.
|
|
2978
|
+
// === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
|
|
2636
2979
|
setRefreshHook(async () => {
|
|
2637
2980
|
prefetchCache.delete(location.pathname);
|
|
2638
2981
|
await start(document.getElementById('app'), location.pathname, false);
|
|
@@ -2666,26 +3009,44 @@ setRefreshHook(async () => {
|
|
|
2666
3009
|
...TS_LOADER
|
|
2667
3010
|
});
|
|
2668
3011
|
}
|
|
3012
|
+
await fs.promises.writeFile(path.join(outDir, "mount.js"), MOUNT_ENTRY);
|
|
2669
3013
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
2670
3014
|
const publicDir = path.join(root, "public");
|
|
2671
3015
|
if (fs.existsSync(publicDir)) {
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
await Promise.all(
|
|
2676
|
-
assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
|
|
2677
|
-
);
|
|
3016
|
+
await fs.promises.cp(publicDir, path.join(outDir, "public"), { recursive: true });
|
|
3017
|
+
const favicon = path.join(publicDir, "favicon.ico");
|
|
3018
|
+
if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, "favicon.ico"));
|
|
2678
3019
|
}
|
|
2679
3020
|
console.log("rosetack zero-JS report:");
|
|
2680
3021
|
for (const line of buildReport(infos, compiled)) console.log(" " + line);
|
|
3022
|
+
const warnGroups = /* @__PURE__ */ new Map();
|
|
2681
3023
|
for (const { info, i } of pages) {
|
|
2682
3024
|
if (!routeShipsNoJs(infos, compiled, i)) continue;
|
|
2683
3025
|
for (const ci of [i, ...layoutsOf(infos, i)]) {
|
|
2684
3026
|
for (const w of compiled[ci].jsWarnings ?? []) {
|
|
2685
|
-
|
|
3027
|
+
let g = warnGroups.get(w);
|
|
3028
|
+
if (!g) {
|
|
3029
|
+
g = { why: w, files: /* @__PURE__ */ new Map() };
|
|
3030
|
+
warnGroups.set(w, g);
|
|
3031
|
+
}
|
|
3032
|
+
const file = path.relative(root, infos[ci].filePath).replace(/\\/g, "/");
|
|
3033
|
+
let routes = g.files.get(file);
|
|
3034
|
+
if (!routes) {
|
|
3035
|
+
routes = /* @__PURE__ */ new Set();
|
|
3036
|
+
g.files.set(file, routes);
|
|
3037
|
+
}
|
|
3038
|
+
routes.add(info.routePath);
|
|
2686
3039
|
}
|
|
2687
3040
|
}
|
|
2688
3041
|
}
|
|
3042
|
+
for (const g of warnGroups.values()) {
|
|
3043
|
+
const allRoutes = /* @__PURE__ */ new Set();
|
|
3044
|
+
for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
|
|
3045
|
+
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`})`);
|
|
3046
|
+
const shown = parts.slice(0, 4).join(", ");
|
|
3047
|
+
const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
|
|
3048
|
+
console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
|
|
3049
|
+
}
|
|
2689
3050
|
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
2690
3051
|
}
|
|
2691
3052
|
async function scanRoseFiles(root) {
|
|
@@ -2730,15 +3091,21 @@ function getRouteInfo(filePath, root) {
|
|
|
2730
3091
|
const base = path.posix.basename(withoutExt);
|
|
2731
3092
|
const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
|
|
2732
3093
|
const isLayout = !isComponent && base === "_layout";
|
|
2733
|
-
const isNotFound = !isComponent && base === "404";
|
|
3094
|
+
const isNotFound = !isComponent && (base === "404" || base === "_notfound");
|
|
2734
3095
|
const isError = !isComponent && base === "500";
|
|
2735
3096
|
const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
|
|
2736
3097
|
const isMiddleware = !isComponent && withoutExt === "_middleware";
|
|
2737
|
-
let parts = withoutExt.split("/").filter((p) => p !== "_layout");
|
|
3098
|
+
let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
|
|
2738
3099
|
if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
|
|
2739
|
-
const
|
|
2740
|
-
|
|
2741
|
-
)
|
|
3100
|
+
const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
|
|
3101
|
+
const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
|
|
3102
|
+
const routeParts = parts.map((part) => {
|
|
3103
|
+
const optional = OPTIONAL_CATCH_ALL.exec(part);
|
|
3104
|
+
if (optional) return `**${optional[1]}`;
|
|
3105
|
+
const catchAll = CATCH_ALL.exec(part);
|
|
3106
|
+
if (catchAll) return `*${catchAll[1]}`;
|
|
3107
|
+
return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
|
|
3108
|
+
});
|
|
2742
3109
|
let routePath;
|
|
2743
3110
|
if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
|
|
2744
3111
|
routePath = "/";
|
|
@@ -2749,7 +3116,13 @@ function getRouteInfo(filePath, root) {
|
|
|
2749
3116
|
filePath,
|
|
2750
3117
|
routePath,
|
|
2751
3118
|
pattern: routePath,
|
|
2752
|
-
paramNames: parts.
|
|
3119
|
+
paramNames: parts.flatMap((p) => {
|
|
3120
|
+
const optional = OPTIONAL_CATCH_ALL.exec(p);
|
|
3121
|
+
if (optional) return [optional[1]];
|
|
3122
|
+
const catchAll = CATCH_ALL.exec(p);
|
|
3123
|
+
if (catchAll) return [catchAll[1]];
|
|
3124
|
+
return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
|
|
3125
|
+
}),
|
|
2753
3126
|
isLayout,
|
|
2754
3127
|
isNotFound,
|
|
2755
3128
|
isError,
|
|
@@ -2781,7 +3154,25 @@ function getStyles() {
|
|
|
2781
3154
|
}
|
|
2782
3155
|
}
|
|
2783
3156
|
var BOOTSTRAP = esbuild2.transformSync(`
|
|
2784
|
-
|
|
3157
|
+
// shell = false: the document's SSR content sits directly in <body> - no
|
|
3158
|
+
// #app wrapper, no demo styles, so a real theme's CSS owns the document from
|
|
3159
|
+
// the first byte (and a JS-less visitor never sees either). The bundle still
|
|
3160
|
+
// runs, and it still needs its container: wrap the content once, here, before
|
|
3161
|
+
// any theme script executes (module scripts run before DOMContentLoaded). The
|
|
3162
|
+
// wrapper is a plain unstyled div, so the re-parent is visually inert; every
|
|
3163
|
+
// later path - adoption, navigation, forms - is then the ordinary one.
|
|
3164
|
+
let __app = document.getElementById('app');
|
|
3165
|
+
if (!__app) {
|
|
3166
|
+
__app = document.createElement('div');
|
|
3167
|
+
__app.id = 'app';
|
|
3168
|
+
// scripts stay outside the wrapper, exactly where the dressed document
|
|
3169
|
+
// keeps them: the state element and the running module must survive a
|
|
3170
|
+
// navigation's innerHTML swap (they are the document's, not the route's).
|
|
3171
|
+
for (const node of Array.from(document.body.children)) {
|
|
3172
|
+
if (node.tagName !== 'SCRIPT') __app.appendChild(node);
|
|
3173
|
+
}
|
|
3174
|
+
document.body.appendChild(__app);
|
|
3175
|
+
}
|
|
2785
3176
|
// Native View Transitions around client-side navigation (progressive:
|
|
2786
3177
|
// browsers without the API navigate normally, no polyfill, no CSS required).
|
|
2787
3178
|
function __navigate(pathname) {
|
|
@@ -2844,13 +3235,15 @@ document.addEventListener('submit', (e) => {
|
|
|
2844
3235
|
e.preventDefault();
|
|
2845
3236
|
postForm(new FormData(f));
|
|
2846
3237
|
});
|
|
2847
|
-
// Dev seam: the live signal graph, readable as JSON.
|
|
3238
|
+
// Dev seam: the live signal graph, readable as JSON. Three callers, one
|
|
2848
3239
|
// implementation: the dev server's reload bridge snapshots it before a
|
|
2849
3240
|
// rebuild-triggered reload so the edit lands on the state the developer had,
|
|
2850
|
-
// and
|
|
2851
|
-
//
|
|
2852
|
-
//
|
|
2853
|
-
|
|
3241
|
+
// and the devtools extension (devtools/) reads it the same way - the signal
|
|
3242
|
+
// graph plus the prefetch counters, which is the whole observable state of a
|
|
3243
|
+
// running page. Both are DIRECT references (no wrapper arrow): the names take
|
|
3244
|
+
// no arguments, so the call is identical and every document that carries the
|
|
3245
|
+
// bundle pays eleven bytes for the pair instead of forty.
|
|
3246
|
+
window.__rosetack = { state: serializeState, prefetch: prefetchStats };
|
|
2854
3247
|
// initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
|
|
2855
3248
|
// If the document was rendered for a DIFFERENT route (a static-file server's
|
|
2856
3249
|
// SPA fallback serves index.html for unknown paths), adopt nothing - let the
|
|
@@ -2869,7 +3262,14 @@ if (__resumed) {
|
|
|
2869
3262
|
__state = Object.assign(__state, __resumed);
|
|
2870
3263
|
__state.__route = __route;
|
|
2871
3264
|
}
|
|
2872
|
-
|
|
3265
|
+
// A NOT-FOUND document (the server stamps __notFound onto its state) boots
|
|
3266
|
+
// into the app's own 404 route: the URL matches no route - or a catch-all
|
|
3267
|
+
// whose resolver threw notFound(), whose key sits null in the resumed state
|
|
3268
|
+
// and whose template would dereference it into a 500. startNotFound paints
|
|
3269
|
+
// the not-found route from the resumed state instead (zero requests).
|
|
3270
|
+
if (__state.__notFound) {
|
|
3271
|
+
startNotFound(__app, window.location.pathname);
|
|
3272
|
+
} else if (__resumed) {
|
|
2873
3273
|
start(__app, window.location.pathname);
|
|
2874
3274
|
} else if (__state.__route === window.location.pathname) {
|
|
2875
3275
|
start(__app, window.location.pathname, true);
|
|
@@ -2878,7 +3278,7 @@ if (__resumed) {
|
|
|
2878
3278
|
}
|
|
2879
3279
|
`, { minify: true }).code;
|
|
2880
3280
|
var EXTERNAL_BOOTSTRAP = `
|
|
2881
|
-
import { start, prefetch, postForm } from '/client.js';
|
|
3281
|
+
import { start, prefetch, postForm, prefetchStats } from '/client.js';
|
|
2882
3282
|
${BOOTSTRAP}`;
|
|
2883
3283
|
function inlineScript(client) {
|
|
2884
3284
|
return `
|
|
@@ -2944,31 +3344,41 @@ function clientScriptTag(client, nonce = "") {
|
|
|
2944
3344
|
return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
|
|
2945
3345
|
<script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
|
|
2946
3346
|
}
|
|
2947
|
-
function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
|
|
3347
|
+
function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
|
|
2948
3348
|
const clientTag = clientScriptTag(client, nonce);
|
|
2949
3349
|
const mergedHead = mergeHeadBlocks(head);
|
|
3350
|
+
const headStamped = nonce ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs) => /\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`) : mergedHead;
|
|
3351
|
+
let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ""}`;
|
|
3352
|
+
let bodyAttrs = "";
|
|
3353
|
+
const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag, attrs) => {
|
|
3354
|
+
const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, "");
|
|
3355
|
+
if (tag === "html") htmlAttrs = clean;
|
|
3356
|
+
else bodyAttrs = clean;
|
|
3357
|
+
return "";
|
|
3358
|
+
});
|
|
2950
3359
|
const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
|
|
2951
3360
|
const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
|
|
2952
3361
|
${FAVICON}`;
|
|
2953
|
-
const headTags =
|
|
2954
|
-
${
|
|
3362
|
+
const headTags = headClean ? `
|
|
3363
|
+
${headClean}` : "";
|
|
2955
3364
|
const styleTag = styles ? `
|
|
2956
3365
|
<style>${styles}</style>` : "";
|
|
3366
|
+
const stateSafe = stateJson.replace(/</g, "\\u003c");
|
|
2957
3367
|
const jsTail = js ? `
|
|
2958
|
-
<script type="application/json" id="__rosetack_state">${
|
|
3368
|
+
<script type="application/json" id="__rosetack_state">${stateSafe}</script>
|
|
2959
3369
|
${clientTag}` : "";
|
|
2960
|
-
const open = js ? '<div id="app">' : "";
|
|
2961
|
-
const close = js ? "</div>" : "";
|
|
2962
|
-
const shellStyles = js ? `
|
|
3370
|
+
const open = js && shell ? '<div id="app">' : "";
|
|
3371
|
+
const close = js && shell ? "</div>" : "";
|
|
3372
|
+
const shellStyles = js && shell ? `
|
|
2963
3373
|
<style>${STYLES_MIN}</style>` : "";
|
|
2964
3374
|
return `<!DOCTYPE html>
|
|
2965
|
-
<html
|
|
3375
|
+
<html${htmlAttrs}>
|
|
2966
3376
|
<head>
|
|
2967
3377
|
<meta charset="UTF-8">
|
|
2968
3378
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
|
|
2969
3379
|
${titleTag}${shellStyles}${styleTag}
|
|
2970
3380
|
</head>
|
|
2971
|
-
<body>
|
|
3381
|
+
<body${bodyAttrs}>
|
|
2972
3382
|
${open}${ssrHtml}${close}${jsTail}
|
|
2973
3383
|
</body>
|
|
2974
3384
|
</html>`;
|
|
@@ -3061,15 +3471,16 @@ async function test(file, opts = {}) {
|
|
|
3061
3471
|
state: page.state ? JSON.parse(page.state) : {},
|
|
3062
3472
|
head: page.head ?? [],
|
|
3063
3473
|
csr: page.csr,
|
|
3474
|
+
shell: page.shell,
|
|
3064
3475
|
lang: page.lang ?? "en",
|
|
3065
3476
|
dir: page.dir ?? "",
|
|
3066
|
-
document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? ""),
|
|
3477
|
+
document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? "en", page.dir ?? "", "", page.shell !== false),
|
|
3067
3478
|
redirect
|
|
3068
3479
|
});
|
|
3069
3480
|
const toRequest = (pathname, req = {}, body) => {
|
|
3070
3481
|
const headers = new Headers(req.headers ?? {});
|
|
3071
3482
|
for (const [k, v] of Object.entries(req.cookies ?? {})) headers.append("cookie", `${k}=${v}`);
|
|
3072
|
-
return new Request(`http://localhost${pathname}`, { method:
|
|
3483
|
+
return new Request(`http://localhost${pathname}`, { method: req.method ?? "GET", headers, body: body ?? void 0 });
|
|
3073
3484
|
};
|
|
3074
3485
|
const request = async (pathname, req, body) => {
|
|
3075
3486
|
if (mod.middleware) {
|