rosetack 0.1.2 → 0.1.4
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 +2194 -561
- package/dist-cli/edge.mjs +159 -48
- package/dist-cli/rosetack.mjs +2899 -739
- package/dist-cli/runtime.mjs +305 -43
- package/dist-cli/test.mjs +2332 -630
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +78 -62
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +391 -334
- package/src/cli/prod-server.ts +324 -0
- package/src/cli/prompt.ts +51 -20
- package/src/cli/shell.ts +105 -74
- package/src/cli/test.ts +9 -70
- package/src/compiler/index.ts +2107 -913
- package/src/runtime/index.ts +367 -168
- 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/src/compiler/index.ts
CHANGED
|
@@ -1,44 +1,27 @@
|
|
|
1
|
-
|
|
2
|
-
* rosetack Compiler - Compile .rose components to SSR + client-resume JS
|
|
3
|
-
*
|
|
4
|
-
* Features: compile-time reactivity, zero-hydration resume, file-system
|
|
5
|
-
* routing, nested layouts, server data fetching ($data) with request cache.
|
|
6
|
-
*/
|
|
1
|
+
// rosetack Compiler - Compile .rose components to SSR + client-resume JS
|
|
7
2
|
|
|
8
3
|
import * as fs from 'fs';
|
|
9
4
|
import * as path from 'path';
|
|
10
5
|
import { pathToFileURL, fileURLToPath } from 'url';
|
|
11
6
|
import * as esbuild from 'esbuild';
|
|
12
|
-
// The error contract every compiler failure speaks: a stable code, the file, the line when
|
|
13
|
-
// known, and the fix …
|
|
14
7
|
import { RoseError, lineOf, lineAt } from './errors.js';
|
|
15
8
|
export { RoseError, lineOf, lineAt, errorInfo } from './errors.js';
|
|
16
9
|
export type { RoseErrorInfo } from './errors.js';
|
|
17
10
|
|
|
18
11
|
const COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
19
12
|
const TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
20
|
-
// <head> block: per-route document metadata (title/meta/link), compiled
|
|
21
|
-
// without markers so the SSR output stays clean for <head> injection.
|
|
22
13
|
const HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
23
|
-
// <style> block: component CSS, scoped by a build-time attribute on the component's
|
|
24
|
-
// top-level elements and inlined into the document …
|
|
25
14
|
const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
26
|
-
|
|
27
|
-
// Post>>(...)`) and/or a cast (`$state(0) as Counter`).
|
|
28
|
-
const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
15
|
+
const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
|
|
29
16
|
const DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
30
17
|
const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
31
18
|
const EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
|
|
32
|
-
const SLOT_RE = /<slot\s
|
|
19
|
+
const SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
|
|
33
20
|
/** A named slot: `<slot name="row" item={post} />` . The lookahead
|
|
34
21
|
* keeps the plain `<slot />` out of it - that one is the default slot. */
|
|
35
|
-
const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)
|
|
22
|
+
const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
|
|
36
23
|
|
|
37
|
-
|
|
38
|
-
* Encode a named slot tag as the template expression
|
|
39
|
-
* `__slot('row', [['item', (post)]])` - array pairs, because the template
|
|
40
|
-
* scanner matches `{...}` without nested braces.
|
|
41
|
-
*/
|
|
24
|
+
// Encode a named slot tag as the template expression `__slot('row', [['item', (post)]])` - array pairs.
|
|
42
25
|
function encodeSlotCall(attrs: string): string {
|
|
43
26
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
|
|
44
27
|
if (!name) throw new RoseError('E-TEMPLATE', '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
|
|
@@ -47,13 +30,8 @@ function encodeSlotCall(attrs: string): string {
|
|
|
47
30
|
.map((m) => `['${m[1]}', (${m[2].trim()})]`);
|
|
48
31
|
return `${JSON.stringify(name)}, [${pairs.join(', ')}]`;
|
|
49
32
|
}
|
|
50
|
-
// {#boundary}...{/boundary}: an error boundary - its content renders into its own string; a
|
|
51
|
-
// throw anywhere inside swaps in a fallback instead of failing the whole page.
|
|
52
33
|
const BOUNDARY_FALLBACK = '<p>This section failed to render.</p>';
|
|
53
|
-
// API route handlers are exported functions named by HTTP method (pages/api/*.rose).
|
|
54
34
|
const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
55
|
-
// A .rose <script> block is TypeScript: interfaces, annotations, `as`, generics. The
|
|
56
|
-
// compiler's intermediates therefore hold TypeScript, and esbuild must STRIP the types …
|
|
57
35
|
const TS_LOADER = { loader: { '.js': 'ts' as const } };
|
|
58
36
|
|
|
59
37
|
export interface CompileResult {
|
|
@@ -77,8 +55,19 @@ export interface CompileResult {
|
|
|
77
55
|
usesContext?: boolean;
|
|
78
56
|
/** the component exports `revalidate = N` (ISR window in seconds) */
|
|
79
57
|
revalidate?: number;
|
|
58
|
+
/** the component exports `cache = N` (per-request render memo, seconds) */
|
|
59
|
+
cache?: number;
|
|
80
60
|
/** the component exports `csr = false` (document ships without the client bundle) */
|
|
81
61
|
csr?: boolean;
|
|
62
|
+
/**
|
|
63
|
+
* The component exports `shell = false`: keep the client bundle (this route
|
|
64
|
+
* still needs it - comments widgets, third-party scripts) but drop the
|
|
65
|
+
* shell's demo dressing - the #app wrapper and STYLES_MIN. A real app ships
|
|
66
|
+
* its own theme CSS; the scaffold's `body{padding:2rem}` / pink links then
|
|
67
|
+
* outrank it on equal specificity. Same escape the zero-JS branch has, for
|
|
68
|
+
* routes that cannot go JS-free.
|
|
69
|
+
*/
|
|
70
|
+
shell?: boolean;
|
|
82
71
|
/**
|
|
83
72
|
* P0-2 (bug report): the component exports `buffer = true` - render it per
|
|
84
73
|
* request on the BUFFERED path instead of streaming. A streamed response
|
|
@@ -90,6 +79,14 @@ export interface CompileResult {
|
|
|
90
79
|
* run on, so `buffer = true` routes are never prerendered.
|
|
91
80
|
*/
|
|
92
81
|
buffer?: boolean;
|
|
82
|
+
/**
|
|
83
|
+
* The script calls `redirect()` or `notFound()` (the control-flow pair).
|
|
84
|
+
* Both are thrown signals whose answer is the RESPONSE's status - a 30x
|
|
85
|
+
* with a Location, or a real 404 - and a streamed response has committed
|
|
86
|
+
* its status before the render runs. Such a route is therefore buffered
|
|
87
|
+
* by construction, exactly like `buffer = true`, and never prerendered.
|
|
88
|
+
*/
|
|
89
|
+
controlSignal?: boolean;
|
|
93
90
|
/** the component exports `prefetch = 'off' | 'hover' | 'viewport' | 'all'` (app-global link-prefetch strategy) */
|
|
94
91
|
prefetch?: string;
|
|
95
92
|
/** The component exports `vitals = true` (app-global web-vitals reporting) */
|
|
@@ -152,7 +149,7 @@ export interface RouteInfo {
|
|
|
152
149
|
|
|
153
150
|
interface Decl {
|
|
154
151
|
name: string;
|
|
155
|
-
kind: 'state' | 'data';
|
|
152
|
+
kind: 'state' | 'data' | 'kv' | 'persist';
|
|
156
153
|
expr: string;
|
|
157
154
|
start: number;
|
|
158
155
|
end: number;
|
|
@@ -174,7 +171,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
174
171
|
let i = 0;
|
|
175
172
|
while (i < src.length) {
|
|
176
173
|
const ch = src[i];
|
|
177
|
-
// string literal: copy verbatim
|
|
178
174
|
if (ch === "'" || ch === '"') {
|
|
179
175
|
let j = i + 1;
|
|
180
176
|
while (j < src.length && src[j] !== ch) {
|
|
@@ -185,7 +181,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
185
181
|
i = j + 1;
|
|
186
182
|
continue;
|
|
187
183
|
}
|
|
188
|
-
// template literal: copy text verbatim, scan ${...} as code
|
|
189
184
|
if (ch === '`') {
|
|
190
185
|
out += ch;
|
|
191
186
|
i++;
|
|
@@ -215,7 +210,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
215
210
|
i++;
|
|
216
211
|
continue;
|
|
217
212
|
}
|
|
218
|
-
// comments: copy verbatim
|
|
219
213
|
if (ch === '/' && src[i + 1] === '/') {
|
|
220
214
|
const nl = src.indexOf('\n', i);
|
|
221
215
|
const end = nl === -1 ? src.length : nl;
|
|
@@ -230,7 +224,6 @@ function callifyStateReads(script: string, names: string[]): string {
|
|
|
230
224
|
i = end;
|
|
231
225
|
continue;
|
|
232
226
|
}
|
|
233
|
-
// identifier: rewrite bare state reads only
|
|
234
227
|
if (/[A-Za-z_$]/.test(ch)) {
|
|
235
228
|
let j = i;
|
|
236
229
|
while (j < src.length && /[\w$]/.test(src[j])) j++;
|
|
@@ -293,8 +286,6 @@ export function templateExprSpans(src: string): Array<{ start: number; end: numb
|
|
|
293
286
|
while (i < src.length) {
|
|
294
287
|
if (src[i] === '{') {
|
|
295
288
|
const end = scanExprEnd(src, i);
|
|
296
|
-
// An empty `{}` is prose, not an expression (the old regex's `+` said
|
|
297
|
-
// the same thing): skipping it leaves the braces for emitChunk.
|
|
298
289
|
if (end > i + 1) {
|
|
299
290
|
spans.push({ start: i, end, expr: src.slice(i + 1, end) });
|
|
300
291
|
i = end + 1;
|
|
@@ -362,32 +353,46 @@ function skipTemplate(src: string, i: number): number {
|
|
|
362
353
|
return j;
|
|
363
354
|
}
|
|
364
355
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
356
|
+
// The literal that starts at `i`, if any: a quoted string, a template literal, or - the one that keeps derailing scanners - a REGEX literal.
|
|
357
|
+
function skipLiteral(src: string, i: number): number | null {
|
|
358
|
+
const q = src[i];
|
|
359
|
+
if (q === '"' || q === "'") return skipQuoted(src, i);
|
|
360
|
+
if (q === '`') return skipTemplate(src, i);
|
|
361
|
+
if (q !== '/') return null;
|
|
362
|
+
if (src[i + 1] === '/' || src[i + 1] === '*') return null;
|
|
363
|
+
let b = i - 1;
|
|
364
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
365
|
+
if (b >= 0) {
|
|
366
|
+
if (!'(,=:[!&|?{};+-*%~^'.includes(src[b])) {
|
|
367
|
+
const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? '';
|
|
368
|
+
if (!['return', 'typeof', 'case', 'in', 'of', 'new', 'delete', 'void', 'do', 'else', 'instanceof', 'yield', 'await'].includes(word)) return null;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
let j = i + 1;
|
|
372
|
+
let inClass = false;
|
|
373
|
+
while (j < src.length) {
|
|
374
|
+
const c = src[j];
|
|
375
|
+
if (c === '\\') { j += 2; continue; }
|
|
376
|
+
if (c === '\n') return null;
|
|
377
|
+
if (inClass) { if (c === ']') inClass = false; }
|
|
378
|
+
else if (c === '[') inClass = true;
|
|
379
|
+
else if (c === '/') { j++; break; }
|
|
380
|
+
j++;
|
|
381
|
+
}
|
|
382
|
+
if (j > src.length) return null;
|
|
383
|
+
while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
|
|
384
|
+
return j;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// 's scanners are syntactic, and prose is not code: the demo's own "the same zero-JS document." (a sentence ending).
|
|
376
388
|
function stripComments(src: string): string {
|
|
377
389
|
let out = '';
|
|
378
390
|
let i = 0;
|
|
379
391
|
while (i < src.length) {
|
|
380
|
-
const
|
|
381
|
-
if (
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
i = end;
|
|
385
|
-
continue;
|
|
386
|
-
}
|
|
387
|
-
if (q === '`') {
|
|
388
|
-
const end = skipTemplate(src, i);
|
|
389
|
-
out += src.slice(i, end);
|
|
390
|
-
i = end;
|
|
392
|
+
const lit = skipLiteral(src, i);
|
|
393
|
+
if (lit !== null) {
|
|
394
|
+
out += src.slice(i, lit);
|
|
395
|
+
i = lit;
|
|
391
396
|
continue;
|
|
392
397
|
}
|
|
393
398
|
if (src.startsWith('//', i)) {
|
|
@@ -411,22 +416,136 @@ function stripComments(src: string): string {
|
|
|
411
416
|
return out;
|
|
412
417
|
}
|
|
413
418
|
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
+
// Q1 (bug report): the zero-JS scanner cried wolf on the standard isomorphic guard.
|
|
420
|
+
function stripGuardedBranches(src: string): string {
|
|
421
|
+
const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
|
|
422
|
+
const ws = (i: number): number => { while (i < src.length && /\s/.test(src[i])) i++; return i; };
|
|
423
|
+
const ternaryColon = (q: number): number => {
|
|
424
|
+
let depth = 0;
|
|
425
|
+
let i = q + 1;
|
|
426
|
+
while (i < src.length) {
|
|
427
|
+
const c = src[i];
|
|
428
|
+
const lit = skipLiteral(src, i);
|
|
429
|
+
if (lit !== null) { i = lit; continue; }
|
|
430
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
431
|
+
else if (c === ')' || c === ']' || c === '}') { depth--; if (depth < 0) return -1; }
|
|
432
|
+
else if (depth === 0 && c === ':') return i;
|
|
433
|
+
else if (depth === 0 && c === '?') { const inner = ternaryColon(i); if (inner < 0) return -1; i = inner + 1; continue; }
|
|
434
|
+
i++;
|
|
435
|
+
}
|
|
436
|
+
return -1;
|
|
437
|
+
};
|
|
438
|
+
const exprEnd = (i: number): number => {
|
|
439
|
+
let depth = 0;
|
|
440
|
+
while (i < src.length) {
|
|
441
|
+
const c = src[i];
|
|
442
|
+
const lit = skipLiteral(src, i);
|
|
443
|
+
if (lit !== null) { i = lit; continue; }
|
|
444
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
445
|
+
else if (c === ')' || c === ']' || c === '}') { if (depth === 0) return i; depth--; }
|
|
446
|
+
else if (depth === 0 && (c === ',' || c === ';')) return i;
|
|
447
|
+
else if (depth === 0 && c === '?') { const inner = ternaryColon(i); if (inner < 0) return src.length; i = inner + 1; continue; }
|
|
448
|
+
i++;
|
|
449
|
+
}
|
|
450
|
+
return src.length;
|
|
451
|
+
};
|
|
452
|
+
const braceEnd = (b: number): number => {
|
|
453
|
+
let depth = 0;
|
|
454
|
+
let i = b;
|
|
455
|
+
while (i < src.length) {
|
|
456
|
+
const c = src[i];
|
|
457
|
+
const lit = skipLiteral(src, i);
|
|
458
|
+
if (lit !== null) { i = lit; continue; }
|
|
459
|
+
if (c === '{') depth++;
|
|
460
|
+
else if (c === '}') { depth--; if (depth === 0) return i; }
|
|
461
|
+
i++;
|
|
462
|
+
}
|
|
463
|
+
return src.length;
|
|
464
|
+
};
|
|
465
|
+
const stmtEnd = (i: number): number => {
|
|
466
|
+
let depth = 0;
|
|
467
|
+
while (i < src.length) {
|
|
468
|
+
const c = src[i];
|
|
469
|
+
const lit = skipLiteral(src, i);
|
|
470
|
+
if (lit !== null) { i = lit; continue; }
|
|
471
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
472
|
+
else if (c === ')' || c === ']' || c === '}') { if (depth === 0) return i; depth--; }
|
|
473
|
+
else if (depth === 0 && (c === ';' || c === '\n')) return i;
|
|
474
|
+
i++;
|
|
475
|
+
}
|
|
476
|
+
return src.length;
|
|
477
|
+
};
|
|
478
|
+
const isIfGuard = (src: string, at: number): boolean => {
|
|
479
|
+
let b = at - 1;
|
|
480
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
481
|
+
if (b < 0 || src[b] !== '(') return false;
|
|
482
|
+
b--;
|
|
483
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
484
|
+
return b >= 1 && src[b] === 'f' && src[b - 1] === 'i' && (b < 2 || !/[\w$]/.test(src[b - 2]));
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
const blanks: Array<[number, number]> = [];
|
|
488
|
+
let i = 0;
|
|
489
|
+
while (i < src.length) {
|
|
490
|
+
const lit = skipLiteral(src, i);
|
|
491
|
+
if (lit !== null) { i = lit; continue; }
|
|
492
|
+
GUARD.lastIndex = i;
|
|
493
|
+
const m = GUARD.exec(src);
|
|
494
|
+
if (!m) { i++; continue; }
|
|
495
|
+
const browserAfter = m[1] === '!==';
|
|
496
|
+
const j = ws(i + m[0].length);
|
|
497
|
+
const two = src.slice(j, j + 2);
|
|
498
|
+
if (two === '&&' && browserAfter) {
|
|
499
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
500
|
+
} else if (two === '||' && !browserAfter) {
|
|
501
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
502
|
+
} else if (src[j] === '?') {
|
|
503
|
+
const colon = ternaryColon(j);
|
|
504
|
+
if (colon < 0) {
|
|
505
|
+
if (browserAfter) blanks.push([j + 1, src.length]);
|
|
506
|
+
} else if (browserAfter) {
|
|
507
|
+
blanks.push([j + 1, colon]);
|
|
508
|
+
} else {
|
|
509
|
+
blanks.push([colon + 1, exprEnd(colon + 1)]);
|
|
510
|
+
}
|
|
511
|
+
} else if (src[j] === ')' && isIfGuard(src, i)) {
|
|
512
|
+
let bodyEnd: number;
|
|
513
|
+
const k = ws(j + 1);
|
|
514
|
+
if (src[k] === '{') {
|
|
515
|
+
bodyEnd = braceEnd(k);
|
|
516
|
+
if (browserAfter) blanks.push([k + 1, bodyEnd]);
|
|
517
|
+
} else {
|
|
518
|
+
bodyEnd = stmtEnd(k);
|
|
519
|
+
if (browserAfter) blanks.push([k, bodyEnd]);
|
|
520
|
+
}
|
|
521
|
+
const after = ws(bodyEnd + 1);
|
|
522
|
+
if (src.startsWith('else', after)) {
|
|
523
|
+
const e = ws(after + 4);
|
|
524
|
+
if (src[e] === '{') {
|
|
525
|
+
const close = braceEnd(e);
|
|
526
|
+
if (!browserAfter) blanks.push([e + 1, close]);
|
|
527
|
+
} else {
|
|
528
|
+
const stop = stmtEnd(e);
|
|
529
|
+
if (!browserAfter) blanks.push([e, stop]);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
i = j;
|
|
534
|
+
}
|
|
535
|
+
if (blanks.length === 0) return src;
|
|
536
|
+
const out = [...src];
|
|
537
|
+
for (const [a, b] of blanks) {
|
|
538
|
+
for (let k = a; k < b && k < out.length; k++) if (out[k] !== '\n') out[k] = ' ';
|
|
539
|
+
}
|
|
540
|
+
return out.join('');
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// The <script> block of a .rose source, verbatim.
|
|
419
544
|
export function scriptOf(source: string): string | null {
|
|
420
545
|
return source.match(COMPONENT_RE)?.[1] ?? null;
|
|
421
546
|
}
|
|
422
547
|
|
|
423
|
-
|
|
424
|
-
* The per-request bag the runtime hooks receive. Web-standard on purpose:
|
|
425
|
-
* the same object reaches a hook on the Node server, the preview server and
|
|
426
|
-
* the edge adapter, so hook code is written once and runs everywhere.
|
|
427
|
-
* `state` is scratch space - one hook writes, a later hook (or the page,
|
|
428
|
-
* through getContext()) reads.
|
|
429
|
-
*/
|
|
548
|
+
// The per-request bag the runtime hooks receive.
|
|
430
549
|
export interface RequestHookContext {
|
|
431
550
|
request: Request;
|
|
432
551
|
url: URL;
|
|
@@ -435,18 +554,15 @@ export interface RequestHookContext {
|
|
|
435
554
|
state: Record<string, unknown>;
|
|
436
555
|
}
|
|
437
556
|
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
* module that declares it, so its imports must load in the target runtime
|
|
448
|
-
* (Node and edge both): keep node-only code out of rosetack.config.js.
|
|
449
|
-
*/
|
|
557
|
+
|
|
558
|
+
export interface StoreBridge {
|
|
559
|
+
/** Install the sender: every $store write in this worker calls it. Pass null to detach. */
|
|
560
|
+
install(send: ((name: string, value: unknown) => void) | null): void;
|
|
561
|
+
/** Apply a patch that arrived from another process or machine. */
|
|
562
|
+
deliver(name: string, value: unknown): void;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
|
|
450
566
|
export interface Plugin {
|
|
451
567
|
name: string;
|
|
452
568
|
transform?(code: string, filePath: string): string | Promise<string>;
|
|
@@ -454,26 +570,13 @@ export interface Plugin {
|
|
|
454
570
|
onRequest?(ctx: RequestHookContext): Response | void | Promise<Response | void>;
|
|
455
571
|
/** After the response exists, before it is sent. Return a Response to replace it. */
|
|
456
572
|
onResponse?(ctx: RequestHookContext, res: Response): Response | void | Promise<Response | void>;
|
|
457
|
-
/** Worker start: open a connection pool, warm a cache. */
|
|
458
|
-
onServe?(meta: { port: number; workers: number }): void | Promise<void>;
|
|
573
|
+
/** Worker start: open a connection pool, warm a cache, install a cross-machine store driver. */
|
|
574
|
+
onServe?(meta: { port: number; workers: number; store: StoreBridge }): void | Promise<void>;
|
|
459
575
|
/** Worker drain, before exit: close the pool. */
|
|
460
576
|
onShutdown?(): void | Promise<void>;
|
|
461
577
|
}
|
|
462
578
|
|
|
463
|
-
|
|
464
|
-
* The i18n half of rosetack.config.js - a named export beside the
|
|
465
|
-
* plugins:
|
|
466
|
-
*
|
|
467
|
-
* export const i18n = { preload: ['en', 'zh'] };
|
|
468
|
-
*
|
|
469
|
-
* `preload` lists the locales baked into the CLIENT bundle. The default is
|
|
470
|
-
* every locale: a language switch then costs zero requests, which is the
|
|
471
|
-
* one-request bet taken to its conclusion. An app with many languages lists
|
|
472
|
-
* the ones it wants inline; the rest are written to dist/locales/<lang>.json
|
|
473
|
-
* and fetched on first use (ensureLocale in the runtime). The SERVER bundle
|
|
474
|
-
* always carries every locale - it renders any language on demand, and its
|
|
475
|
-
* size is nobody's hot path.
|
|
476
|
-
*/
|
|
579
|
+
|
|
477
580
|
export interface I18nConfig {
|
|
478
581
|
preload?: string[];
|
|
479
582
|
}
|
|
@@ -483,20 +586,7 @@ export interface rosetackConfig {
|
|
|
483
586
|
i18n: I18nConfig;
|
|
484
587
|
}
|
|
485
588
|
|
|
486
|
-
|
|
487
|
-
* Plugins live in `<root>/rosetack.config.js` as the default export: an array
|
|
488
|
-
* of `{ name, transform, onRequest, onResponse, onServe, onShutdown }`.
|
|
489
|
-
* `transform` runs over each component's raw source (template + script +
|
|
490
|
-
* style, before any parsing) at build time; the runtime hooks are bundled
|
|
491
|
-
* into dist/server.js by build() below. trade-off: transform alone covers
|
|
492
|
-
* macros, custom syntax, includes and auto-imports - a transform can rewrite
|
|
493
|
-
* anything, including the script block; the request/serve hooks cover auth,
|
|
494
|
-
* logging and lifecycle, which no source rewrite can express. The import is
|
|
495
|
-
* cache-busted per build so a config edit takes effect on the dev server's
|
|
496
|
-
* next rebuild, and a missing file is simply "no config" (existence is
|
|
497
|
-
* checked first, so a config with a syntax error still fails loudly).
|
|
498
|
-
* One import, one evaluation: the i18n options ride in the same module.
|
|
499
|
-
*/
|
|
589
|
+
|
|
500
590
|
export async function loadConfig(root: string): Promise<rosetackConfig> {
|
|
501
591
|
const file = path.join(root, 'rosetack.config.js');
|
|
502
592
|
if (!fs.existsSync(file)) return { plugins: [], i18n: {} };
|
|
@@ -553,15 +643,11 @@ function resolveRoseImports(script: string, fromFile: string, registry: RoseRegi
|
|
|
553
643
|
}
|
|
554
644
|
return hit;
|
|
555
645
|
};
|
|
556
|
-
// A default import becomes a named one: the compiled module exports
|
|
557
|
-
// `render`, and the parent's `<Card>` tag calls exactly that.
|
|
558
646
|
let rewritten = script.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, name, q, spec, at: number) => {
|
|
559
647
|
const hit = resolve(spec, at);
|
|
560
648
|
imports.push({ name, specifier: spec, index: hit.index });
|
|
561
649
|
return `import { render as ${name} } from ${q}__rose_${hit.index}__${q}`;
|
|
562
650
|
});
|
|
563
|
-
// A named import (`import { render as Card }`) keeps its clause; only the
|
|
564
|
-
// specifier becomes the placeholder.
|
|
565
651
|
rewritten = rewritten.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g, (whole, clause, q, spec, at: number) => {
|
|
566
652
|
const hit = resolve(spec, at);
|
|
567
653
|
const alias = /\bas\s+(\w+)/.exec(clause)?.[1] ?? 'render';
|
|
@@ -598,7 +684,7 @@ const NODE_ONLY_SPEC = /^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream
|
|
|
598
684
|
function nodeOnlyImports(importStmts: string): string[] {
|
|
599
685
|
const out: string[] = [];
|
|
600
686
|
for (const m of importStmts.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g)) {
|
|
601
|
-
if (m[1]) continue;
|
|
687
|
+
if (m[1]) continue;
|
|
602
688
|
if (NODE_ONLY_SPEC.test(m[2])) out.push(m[2]);
|
|
603
689
|
}
|
|
604
690
|
return out;
|
|
@@ -623,19 +709,48 @@ function nodeOnlyImports(importStmts: string): string[] {
|
|
|
623
709
|
* the state declarations, so the arrow closes over the same `count()`/`setN`
|
|
624
710
|
* the rest of the page uses.
|
|
625
711
|
*/
|
|
626
|
-
function wireEventBindings(template: string, actionNames: Set<string>): {
|
|
712
|
+
function wireEventBindings(template: string, actionNames: Set<string>, filePath = '<template>'): {
|
|
627
713
|
template: string;
|
|
628
714
|
bindings: Array<{ event: string; fn: string }>;
|
|
629
715
|
} {
|
|
630
716
|
const bindings: Array<{ event: string; fn: string }> = [];
|
|
631
717
|
let out = '';
|
|
632
718
|
let rest = template;
|
|
719
|
+
const TARGET_MODS: Record<string, string> = { window: 'w', document: 'd' };
|
|
720
|
+
const MOD_PRE: Record<string, (p: string) => string> = {
|
|
721
|
+
preventDefault: () => 'e.preventDefault()',
|
|
722
|
+
stopPropagation: () => 'e.stopPropagation()',
|
|
723
|
+
self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`,
|
|
724
|
+
};
|
|
725
|
+
const MOD_POST: Record<string, (p: string) => string> = {
|
|
726
|
+
once: (p) => `const __o = e.target && e.target.closest ? e.target.closest('[data-${p}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${p}-' + e.type);`,
|
|
727
|
+
};
|
|
728
|
+
const KNOWN_MODS: string[] = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
|
|
633
729
|
for (;;) {
|
|
634
|
-
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
730
|
+
const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
|
|
635
731
|
if (!m) {
|
|
636
732
|
out += rest;
|
|
637
733
|
break;
|
|
638
734
|
}
|
|
735
|
+
const mods = m[2] ? m[2].slice(1).split('|') : [];
|
|
736
|
+
const targets = mods.filter((mod) => TARGET_MODS[mod]);
|
|
737
|
+
if (targets.length > 1) {
|
|
738
|
+
throw new RoseError(
|
|
739
|
+
'E-TEMPLATE',
|
|
740
|
+
`${filePath}: on:${m[1]} carries both |${targets.join(' and |')}`,
|
|
741
|
+
{ hint: 'a handler binds to one target - the element (default), |window or |document' },
|
|
742
|
+
);
|
|
743
|
+
}
|
|
744
|
+
const prefix = targets.length ? 'on' + TARGET_MODS[targets[0]] : 'on';
|
|
745
|
+
for (const mod of mods) {
|
|
746
|
+
if (!KNOWN_MODS.includes(mod)) {
|
|
747
|
+
throw new RoseError(
|
|
748
|
+
'E-TEMPLATE',
|
|
749
|
+
`${filePath}: unknown event modifier |${mod}`,
|
|
750
|
+
{ hint: `the supported modifiers are ${KNOWN_MODS.map((k) => '|' + k).join(' ')} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` },
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
639
754
|
out += rest.slice(0, m.index);
|
|
640
755
|
let i = m.index + m[0].length;
|
|
641
756
|
let depth = 1;
|
|
@@ -657,7 +772,24 @@ function wireEventBindings(template: string, actionNames: Set<string>): {
|
|
|
657
772
|
i++;
|
|
658
773
|
}
|
|
659
774
|
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
660
|
-
|
|
775
|
+
const wrap = (body: string): string => {
|
|
776
|
+
if (!mods.length) return body;
|
|
777
|
+
const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
|
|
778
|
+
const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
|
|
779
|
+
return `(e) => {${pre.length ? ' ' + pre.join('; ') + ';' : ''} (${body})(e);${post.length ? ' ' + post.join('; ') + ';' : ''} }`;
|
|
780
|
+
};
|
|
781
|
+
if (mods.length && actionNames.has(expr)) {
|
|
782
|
+
throw new RoseError(
|
|
783
|
+
'E-TEMPLATE',
|
|
784
|
+
`${filePath}: event modifiers are not supported on the server action ${expr}`,
|
|
785
|
+
{ hint: '$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action' },
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
if (mods.length) {
|
|
789
|
+
const name = `__h${bindings.length}`;
|
|
790
|
+
out += `data-${prefix}-${m[1]}="${name}"`;
|
|
791
|
+
bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
|
|
792
|
+
} else if (actionNames.has(expr)) {
|
|
661
793
|
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
662
794
|
} else if (/^\w+$/.test(expr)) {
|
|
663
795
|
out += `data-on-${m[1]}="${expr}"`;
|
|
@@ -685,10 +817,9 @@ function scanSlotDecls(filePath: string): Array<{ name: string; props: string[]
|
|
|
685
817
|
} catch {
|
|
686
818
|
return [];
|
|
687
819
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
const
|
|
691
|
-
const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, '').replace(COMPONENT_RE, '').trim();
|
|
820
|
+
const noScript = src.replace(COMPONENT_RE, '');
|
|
821
|
+
const noBlocks = noScript.replace(STYLE_RE, '');
|
|
822
|
+
const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, '').trim();
|
|
692
823
|
const out: Array<{ name: string; props: string[] }> = [];
|
|
693
824
|
for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
|
|
694
825
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
|
|
@@ -740,16 +871,13 @@ function hoistImports(script: string): { imports: string; rest: string } {
|
|
|
740
871
|
}
|
|
741
872
|
rest.push(line);
|
|
742
873
|
}
|
|
743
|
-
if (buf) imports.push(buf.join('\n'));
|
|
874
|
+
if (buf) imports.push(buf.join('\n'));
|
|
744
875
|
return { imports: imports.join('\n'), rest: rest.join('\n') };
|
|
745
876
|
}
|
|
746
877
|
|
|
747
878
|
export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = [], registry: RoseRegistry = new Map()): Promise<CompileResult> {
|
|
748
879
|
let source = await fs.promises.readFile(filePath, 'utf-8');
|
|
749
|
-
// Plugins see the raw source first: whatever they return is what the compiler parses.
|
|
750
880
|
for (const p of plugins) {
|
|
751
|
-
// a runtime-only plugin (onRequest/onServe, no transform) has nothing to
|
|
752
|
-
// rewrite - it must not break the build for lacking a build-time hook
|
|
753
881
|
if (!p.transform) continue;
|
|
754
882
|
try {
|
|
755
883
|
source = await p.transform(source, filePath);
|
|
@@ -762,19 +890,21 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
762
890
|
}
|
|
763
891
|
}
|
|
764
892
|
|
|
765
|
-
// API route (pages/api/*.rose): no template, no state, no markers - the script's exported
|
|
766
|
-
// functions ARE the handlers …
|
|
767
893
|
if (isApi) {
|
|
768
894
|
const scriptMatch = source.match(COMPONENT_RE);
|
|
769
895
|
const rawScript = scriptMatch?.[1] ?? '';
|
|
770
896
|
const apiMethods = [...rawScript.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)]
|
|
771
897
|
.map((m) => m[1])
|
|
772
898
|
.filter((name) => HTTP_METHODS.has(name));
|
|
773
|
-
// a handler that reads the request context cannot be baked: the bag is
|
|
774
|
-
// per-request, a baked body would freeze one request's answer
|
|
775
899
|
const usesContext = /getContext\s*\(/.test(rawScript);
|
|
776
900
|
const hasPrerender = !usesContext && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript);
|
|
777
901
|
const hoisted = hoistImports(resolveRoseImports(rawScript, filePath, registry).script);
|
|
902
|
+
const ownRuntimeImports = new Set(
|
|
903
|
+
[...rawScript.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)]
|
|
904
|
+
.flatMap((m) => m[1].split(',').map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
|
|
905
|
+
);
|
|
906
|
+
const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
|
|
907
|
+
const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(', ')} } from './runtime.js';\n` : '';
|
|
778
908
|
return {
|
|
779
909
|
ssr: '',
|
|
780
910
|
client: '',
|
|
@@ -783,31 +913,24 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
783
913
|
guardName: null,
|
|
784
914
|
style: '',
|
|
785
915
|
hasParams: false,
|
|
786
|
-
api:
|
|
916
|
+
api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}\n${hoisted.rest}`, 'ssr').trim()}`,
|
|
787
917
|
apiMethods,
|
|
788
918
|
hasPrerender,
|
|
789
919
|
usesContext,
|
|
790
920
|
};
|
|
791
921
|
}
|
|
792
922
|
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
const sourceNoHead = source.replace(HEAD_RE, '');
|
|
923
|
+
const sourceNoScript = source.replace(COMPONENT_RE, '');
|
|
924
|
+
const sourceNoHead = sourceNoScript.replace(HEAD_RE, '');
|
|
796
925
|
const styleMatch = sourceNoHead.match(STYLE_RE);
|
|
797
926
|
const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : '';
|
|
798
927
|
const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, '');
|
|
799
928
|
|
|
800
|
-
const scriptMatch =
|
|
801
|
-
// Resolve `import Card from '../components/Card.rose'` against the build registry before
|
|
802
|
-
// anything else looks at the script: the rewritten specifier (a `__rose_N__` placeholder) …
|
|
929
|
+
const scriptMatch = source.match(COMPONENT_RE);
|
|
803
930
|
const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? '', filePath, registry);
|
|
804
931
|
const rawScript = roseResolved.script;
|
|
805
932
|
const roseImports = roseResolved.imports;
|
|
806
|
-
// The imports (a component import above all) belong at module scope,
|
|
807
|
-
// not inside render() - hoisted here, emitted by the generators.
|
|
808
933
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
809
|
-
// The npm interop boundary, enforced instead of documented and hoped for. A page's or a
|
|
810
|
-
// component's script ships to the browser - the $data bodies included …
|
|
811
934
|
if (path.basename(filePath) !== '_middleware.rose') {
|
|
812
935
|
for (const spec of nodeOnlyImports(importStmts)) {
|
|
813
936
|
const at = importStmts.indexOf(spec);
|
|
@@ -825,11 +948,7 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
825
948
|
);
|
|
826
949
|
}
|
|
827
950
|
}
|
|
828
|
-
// A component (src/components/*.rose) is not a route: the build marks it in the registry
|
|
829
|
-
// with a `components/...` scope key …
|
|
830
951
|
const isComponent = registry.get(filePath)?.scopeKey.startsWith('components/') ?? false;
|
|
831
|
-
// Boundary, stated loudly at build time: a component renders INSIDE its parent's template
|
|
832
|
-
// phase, which is synchronous by design (that is what keeps wire …
|
|
833
952
|
if (isComponent && /\$data\s*\(/.test(rawScript)) {
|
|
834
953
|
throw new RoseError(
|
|
835
954
|
'E-EXPORT',
|
|
@@ -838,17 +957,12 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
838
957
|
{ file: filePath, hint: 'move the fetch to the page (or the middleware) and pass the value down as a prop' },
|
|
839
958
|
);
|
|
840
959
|
}
|
|
841
|
-
// getContext() in the script makes the route dynamic: the request bag is per-request, so
|
|
842
|
-
// the build must not bake it and the servers must not answer it from a prerendered file.
|
|
843
960
|
const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
|
|
844
|
-
// an exported `params` marks a dynamic route for prerender enumeration
|
|
845
961
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
846
|
-
// an exported `revalidate = N` opts the route into stale-while-revalidate: the baked file
|
|
847
|
-
// is served for up to N seconds …
|
|
848
962
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
849
963
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
|
|
850
|
-
|
|
851
|
-
|
|
964
|
+
const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
|
|
965
|
+
const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : undefined;
|
|
852
966
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
853
967
|
const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
|
|
854
968
|
if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
|
|
@@ -858,8 +972,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
858
972
|
{ file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" },
|
|
859
973
|
);
|
|
860
974
|
}
|
|
861
|
-
// `export const vitals = true` turns on the client-side web-vitals hook (runtime
|
|
862
|
-
// reportVitals). App-global like prefetch, declared once (the root layout).
|
|
863
975
|
const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
|
|
864
976
|
const vitals = vitalsMatch ? vitalsMatch[1].trim() === 'true' : undefined;
|
|
865
977
|
if (vitalsMatch && !vitals) {
|
|
@@ -869,8 +981,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
869
981
|
{ file: filePath, line: lineAt(rawScript, vitalsMatch), hint: 'omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app' },
|
|
870
982
|
);
|
|
871
983
|
}
|
|
872
|
-
// The bundle mode - the fix for the large-app architecture gap. 'inline' (the default) is
|
|
873
|
-
// the single-document mode: the whole client bundle rides inside the HTML, one request …
|
|
874
984
|
const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
875
985
|
const bundle = bundleMatch ? bundleMatch[1] : undefined;
|
|
876
986
|
if (bundle && !['inline', 'split'].includes(bundle)) {
|
|
@@ -880,14 +990,13 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
880
990
|
{ file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" },
|
|
881
991
|
);
|
|
882
992
|
}
|
|
883
|
-
// The compiler decides zero-JS, not the developer. This is the same "does anything here
|
|
884
|
-
// need the client bundle" predicate that Used to REFUSE `csr = false`: event wiring in the …
|
|
885
993
|
const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
|
|
886
994
|
const csr: boolean | undefined = csrMatch ? csrMatch[1] !== 'false' : undefined;
|
|
887
|
-
|
|
888
|
-
|
|
995
|
+
const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
|
|
996
|
+
const shell: boolean | undefined = shellMatch ? shellMatch[1] !== 'false' : undefined;
|
|
889
997
|
const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
|
|
890
998
|
const buffer: boolean | undefined = bufferMatch ? bufferMatch[1] !== 'false' : undefined;
|
|
999
|
+
const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || undefined;
|
|
891
1000
|
if (csr === false) {
|
|
892
1001
|
const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
|
|
893
1002
|
if (dead) {
|
|
@@ -905,7 +1014,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
905
1014
|
}
|
|
906
1015
|
}
|
|
907
1016
|
|
|
908
|
-
// An exported `headers = { ... }` sets this route's response headers
|
|
909
1017
|
let headers: Record<string, string> | undefined;
|
|
910
1018
|
const headersLiteral = extractObjectLiteral(rawScript, 'headers');
|
|
911
1019
|
if (headersLiteral) {
|
|
@@ -929,8 +1037,6 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
929
1037
|
headers = value as Record<string, string>;
|
|
930
1038
|
}
|
|
931
1039
|
|
|
932
|
-
// An exported `csp = { nonce: true }` switches this route from the hashed policy to a
|
|
933
|
-
// per-request nonce . The hash is the stronger default
|
|
934
1040
|
let cspNonce: boolean | undefined;
|
|
935
1041
|
const cspLiteral = extractObjectLiteral(rawScript, 'csp');
|
|
936
1042
|
if (cspLiteral) {
|
|
@@ -955,105 +1061,81 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
955
1061
|
cspNonce = nonce === true;
|
|
956
1062
|
}
|
|
957
1063
|
|
|
958
|
-
// Top-level `export` statements (e.g. `export const params = {...}` for dynamic-route
|
|
959
|
-
// prerendering) are hoisted to module scope: the script body itself is embedded inside …
|
|
960
1064
|
const { clean: scriptNoExports, exports: exportStmts, actions, props, guard } = extractExports(scriptNoImports);
|
|
961
1065
|
const script = scriptNoExports;
|
|
962
1066
|
const actionNames = new Set(actions.map((a) => a.name));
|
|
963
1067
|
|
|
964
|
-
// Does anything in this component need the client bundle?
|
|
965
1068
|
const clientReasons: string[] = [];
|
|
966
|
-
if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)');
|
|
967
|
-
// P1-3 (bug report): a bare <form method="POST"> is the progressive-
|
|
968
|
-
// enhancement path, not a reason to ship JavaScript. With the bundle the
|
|
969
|
-
// bootstrap intercepts the submit and adopts the response in place; without
|
|
970
|
-
// it the browser performs the native POST and the server re-renders the
|
|
971
|
-
// page - the action runs either way. Only a form WIRED to the client (an
|
|
972
|
-
// on: handler, a $action dispatch) needs the runtime, and that wiring is
|
|
973
|
-
// already a reason above, so a native form must not force the bundle onto
|
|
974
|
-
// its page. This is what lets a CMS ship a real search form at zero JS.
|
|
1069
|
+
if (/\son:[a-z]+\s*=/.test(source)) clientReasons.push('event wiring (on:)');
|
|
975
1070
|
if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
|
|
976
1071
|
clientReasons.push('a form bound to a client dispatch ($action)');
|
|
977
1072
|
}
|
|
978
1073
|
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
979
|
-
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`);
|
|
980
|
-
|
|
981
|
-
// it on the server and re-renders, which is the whole progressive-
|
|
982
|
-
// enhancement story. The in-place adopt is the enhancement a page opts into
|
|
983
|
-
// with on: wiring, not a tax every action page pays.
|
|
1074
|
+
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`);
|
|
1075
|
+
if (source.includes('{#defer')) clientReasons.push('{#defer} progressive content');
|
|
984
1076
|
const needsClient = clientReasons.length > 0;
|
|
985
1077
|
|
|
986
|
-
// The predicate is SYNTACTIC, so a component that ships no runtime is scanned for the
|
|
987
|
-
// shapes that would silently need one …
|
|
988
1078
|
const jsWarnings: string[] = [];
|
|
989
1079
|
if (!needsClient) {
|
|
990
|
-
// comments are prose, not code (see stripComments) - a sentence that happens to end in
|
|
991
|
-
// "document." must not warn, and a commented-out handler must not either.
|
|
992
1080
|
const codeOnly = stripComments(source);
|
|
993
1081
|
const scriptCodeOnly = stripComments(rawScript);
|
|
1082
|
+
const scriptScannable = stripGuardedBranches(scriptCodeOnly);
|
|
994
1083
|
if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
|
|
995
1084
|
jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
|
|
996
1085
|
}
|
|
997
1086
|
if (/javascript:/i.test(codeOnly)) {
|
|
998
1087
|
jsWarnings.push('a javascript: URL - it needs the bundle to run; link to a real route');
|
|
999
1088
|
}
|
|
1000
|
-
if (/\b(?:eval|new Function)\s*\(/.test(
|
|
1089
|
+
if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
|
|
1001
1090
|
jsWarnings.push('eval()/new Function() - client code the predicate cannot see');
|
|
1002
1091
|
}
|
|
1003
|
-
|
|
1004
|
-
if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(scriptCodeOnly)) {
|
|
1092
|
+
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)) {
|
|
1005
1093
|
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');
|
|
1006
1094
|
}
|
|
1007
1095
|
}
|
|
1008
1096
|
|
|
1009
1097
|
const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
|
|
1010
|
-
|
|
1011
|
-
const headContent = source.match(HEAD_RE)?.[1] ?? '';
|
|
1098
|
+
const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? '';
|
|
1012
1099
|
const rawTemplate = templateMatch
|
|
1013
1100
|
? templateMatch[1]
|
|
1014
1101
|
: sourceNoBlocks.replace(COMPONENT_RE, '').trim();
|
|
1015
|
-
// a component with styles carries its scope attribute on every top-level
|
|
1016
|
-
// element, so its rules match only its own subtree
|
|
1017
1102
|
const template = scopedStyle
|
|
1018
1103
|
? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey)
|
|
1019
1104
|
: inlineImages(rawTemplate, publicDir);
|
|
1020
1105
|
|
|
1021
|
-
// Extract state / data declarations with balanced-paren scanning
|
|
1022
1106
|
const decls = extractDecls(script);
|
|
1023
|
-
const stateDecls = decls.filter((d) => d.kind === 'state');
|
|
1107
|
+
const stateDecls = decls.filter((d) => d.kind === 'state' || d.kind === 'kv' || d.kind === 'persist');
|
|
1024
1108
|
|
|
1025
|
-
// setter name per state: setCount
|
|
1026
1109
|
const setterNames = new Map<string, string>();
|
|
1027
1110
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
1028
1111
|
|
|
1029
|
-
// The render body's emission order, and why it is what it is: props -> script (every
|
|
1030
|
-
// top-level declaration left where the developer wrote it) -> hoisted nested declarations
|
|
1031
|
-
// -> …
|
|
1032
1112
|
const declCode = (d: (typeof decls)[number]): string => {
|
|
1033
|
-
// A component's state keys are namespaced by its file, so two components that both declare
|
|
1034
|
-
// `let open = $state(false)` no longer share one signal …
|
|
1035
1113
|
const key = isComponent ? `${scopeKey}:${d.name}` : d.name;
|
|
1036
1114
|
if (d.kind === 'state') {
|
|
1037
1115
|
return `const [${d.name}, ${setterNames.get(d.name)!}] = state(${JSON.stringify(key)}, ${d.expr});`;
|
|
1038
1116
|
}
|
|
1039
|
-
// $data: fetch only when this key has no value yet (server: always after
|
|
1040
|
-
// clearRequestState; client: only on first visit or client-side nav)
|
|
1041
1117
|
const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
|
|
1042
1118
|
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
1119
|
+
if (d.kind === 'persist') {
|
|
1120
|
+
return `const [${d.name}, ${setterNames.get(d.name)!}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
|
|
1121
|
+
}
|
|
1122
|
+
if (d.kind === 'kv') {
|
|
1123
|
+
const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
|
|
1124
|
+
const fnExpr = mTtl ? mTtl[1] : d.expr;
|
|
1125
|
+
const ttl = mTtl ? mTtl[2] : '300';
|
|
1126
|
+
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1127
|
+
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1128
|
+
if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify('__kvh:' + scopeKey + ':' + d.name)}, ${fnExpr}, ${ttl}));`;
|
|
1129
|
+
}
|
|
1043
1130
|
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1044
1131
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1045
1132
|
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
1046
1133
|
};
|
|
1047
1134
|
|
|
1048
|
-
// Splice every top-level declaration back where it was written. The placeholder is a
|
|
1049
|
-
// string literal: both rewrites below (the $setState rewrite and the bare-read callify)
|
|
1050
|
-
// copy …
|
|
1051
1135
|
const nestedDecls: (typeof decls)[number][] = [];
|
|
1052
1136
|
let spliced = '';
|
|
1053
1137
|
let pos = 0;
|
|
1054
1138
|
decls.forEach((d, i) => {
|
|
1055
|
-
// A top-level declaration is replaced by its placeholder (its generated code comes back
|
|
1056
|
-
// after the rewrites) …
|
|
1057
1139
|
const top = braceDepthAt(script, d.start) === 0;
|
|
1058
1140
|
if (!top) nestedDecls.push(d);
|
|
1059
1141
|
spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : '');
|
|
@@ -1061,66 +1143,167 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1061
1143
|
});
|
|
1062
1144
|
spliced += script.slice(pos);
|
|
1063
1145
|
|
|
1064
|
-
// Rewrite $setState to setters, then replace bare state reads with getter calls. A plain
|
|
1065
|
-
// regex would also rewrite state names inside string literals …
|
|
1066
1146
|
let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
|
|
1067
1147
|
const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, '');
|
|
1068
1148
|
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
1069
1149
|
return `${setter}(${val})`;
|
|
1070
1150
|
});
|
|
1071
1151
|
cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
|
|
1072
|
-
// ...and put each top-level declaration back, exactly where it was written.
|
|
1073
1152
|
cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
|
|
1074
1153
|
|
|
1075
|
-
// Only the nested declarations still ride the hoisted block (after the
|
|
1076
|
-
// script, before the deltas - the position they have always had).
|
|
1077
1154
|
const stateDeclsCode = nestedDecls.filter((d) => d.kind === 'state').map(declCode).join('\n');
|
|
1078
1155
|
const dataDeclsCode = nestedDecls.filter((d) => d.kind === 'data').map(declCode).join('\n');
|
|
1079
1156
|
|
|
1080
|
-
// The template gets the same treatment: the script auto-calls a bare state read, so
|
|
1081
|
-
// `{liked}` must not silently render the getter's source text.
|
|
1082
1157
|
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
const
|
|
1087
|
-
|
|
1088
|
-
// on:event={fn} -> data-on-event="fn" (wireEventBindings: brace-aware, so an inline
|
|
1089
|
-
// arrow's own braces are part of the expression) …
|
|
1090
|
-
const ssrTemplate = wired.template
|
|
1091
|
-
.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`)
|
|
1092
|
-
.replace(SLOT_RE, '{__slot__}');
|
|
1158
|
+
const imgDefaulted = templateCalled
|
|
1159
|
+
.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"')
|
|
1160
|
+
.replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"')
|
|
1161
|
+
const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
|
|
1093
1162
|
|
|
1094
1163
|
const stateKeys = decls.map((d) => d.name);
|
|
1095
1164
|
|
|
1096
|
-
|
|
1097
|
-
|
|
1165
|
+
const bindBindings: Array<{ event: string; fn: string }> = [];
|
|
1166
|
+
let bindCounter = 0;
|
|
1167
|
+
const bindExpanded = wired.template.replace(
|
|
1168
|
+
/\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
|
|
1169
|
+
(whole, kind: string, name: string) => {
|
|
1170
|
+
if (!stateKeys.includes(name)) {
|
|
1171
|
+
throw new Error(
|
|
1172
|
+
`${filePath}: bind:${kind}={${name}} must name a $state declaration` +
|
|
1173
|
+
(stateKeys.length ? ` (state keys here: ${stateKeys.join(', ')})` : ' (this file declares no $state)'),
|
|
1174
|
+
);
|
|
1175
|
+
}
|
|
1176
|
+
if (kind === 'this') return ` data-bind-this="${name}"`;
|
|
1177
|
+
const setter = setterNames.get(name)!;
|
|
1178
|
+
const evt = kind === 'checked' ? 'change' : 'input';
|
|
1179
|
+
const hname = `__rvbind_${scopeKey.replace(/\W/g, '_')}_${bindCounter++}`;
|
|
1180
|
+
bindBindings.push({
|
|
1181
|
+
event: evt,
|
|
1182
|
+
fn:
|
|
1183
|
+
kind === 'checked'
|
|
1184
|
+
? `${hname}: (e) => ${setter}(e.target.checked)`
|
|
1185
|
+
: `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`,
|
|
1186
|
+
});
|
|
1187
|
+
const evtAttr = kind === 'checked'
|
|
1188
|
+
? ` data-on-change="${hname}"`
|
|
1189
|
+
: ` data-on-input="${hname}" data-on-change="${hname}"`;
|
|
1190
|
+
return ` ${kind}={${name}()}${evtAttr}`;
|
|
1191
|
+
},
|
|
1192
|
+
);
|
|
1193
|
+
|
|
1098
1194
|
const comps = new Map(roseImports.map((r) => {
|
|
1099
1195
|
const abs = path.resolve(path.dirname(filePath), r.specifier);
|
|
1100
1196
|
const hit = registry.get(abs)!;
|
|
1101
1197
|
return [r.name, { index: hit.index, slots: hit.slots }] as const;
|
|
1102
1198
|
}));
|
|
1199
|
+
const groupBindings: Array<{ event: string; fn: string }> = [];
|
|
1200
|
+
let groupCounter = 0;
|
|
1201
|
+
const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1202
|
+
const groupExpanded = (() => {
|
|
1203
|
+
if (!bindExpanded.includes('bind:group')) return bindExpanded;
|
|
1204
|
+
let out = '';
|
|
1205
|
+
let pos = 0;
|
|
1206
|
+
let m: RegExpExecArray | null;
|
|
1207
|
+
TAG_SCAN_RE.lastIndex = 0;
|
|
1208
|
+
while ((m = TAG_SCAN_RE.exec(bindExpanded))) {
|
|
1209
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1210
|
+
const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
|
|
1211
|
+
if (!gm) continue;
|
|
1212
|
+
const name = gm[1];
|
|
1213
|
+
if (!stateKeys.includes(name)) {
|
|
1214
|
+
throw new RoseError(
|
|
1215
|
+
'E-TEMPLATE',
|
|
1216
|
+
`${filePath}: bind:group={${name}} must name a $state declaration`,
|
|
1217
|
+
{ hint: 'the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let ' + name + ' = $state("")' },
|
|
1218
|
+
);
|
|
1219
|
+
}
|
|
1220
|
+
if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
|
|
1221
|
+
throw new RoseError(
|
|
1222
|
+
'E-TEMPLATE',
|
|
1223
|
+
`${filePath}: bind:group is for radio and checkbox inputs`,
|
|
1224
|
+
{ hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' },
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
|
|
1228
|
+
const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
|
|
1229
|
+
if (!vm || /\{/.test(vm[0])) {
|
|
1230
|
+
throw new RoseError(
|
|
1231
|
+
'E-TEMPLATE',
|
|
1232
|
+
`${filePath}: a bind:group input needs a static value attribute`,
|
|
1233
|
+
{ hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' },
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
if (/\schecked\s*=/.test(attrs)) {
|
|
1237
|
+
throw new RoseError(
|
|
1238
|
+
'E-TEMPLATE',
|
|
1239
|
+
`${filePath}: a bind:group input cannot also carry checked=`,
|
|
1240
|
+
{ hint: 'the group state alone decides which inputs are checked' },
|
|
1241
|
+
);
|
|
1242
|
+
}
|
|
1243
|
+
const setter = setterNames.get(name)!;
|
|
1244
|
+
const hname = `__rvbg_${scopeKey.replace(/\W/g, '_')}_${groupCounter++}`;
|
|
1245
|
+
const groupValue = JSON.stringify(vm[1] ?? vm[2]);
|
|
1246
|
+
const checkedExpr = isArrayGroup
|
|
1247
|
+
? `${name}().includes(${groupValue})`
|
|
1248
|
+
: `${name}() === ${groupValue}`;
|
|
1249
|
+
const handlerBody = isArrayGroup
|
|
1250
|
+
? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))`
|
|
1251
|
+
: `${setter}(e.target.value)`;
|
|
1252
|
+
groupBindings.push({ event: 'change', fn: `${hname}: (e) => { ${handlerBody}; }` });
|
|
1253
|
+
const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
|
|
1254
|
+
out += bindExpanded.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1255
|
+
pos = m.index + whole.length;
|
|
1256
|
+
}
|
|
1257
|
+
if (pos === 0) return bindExpanded;
|
|
1258
|
+
out += bindExpanded.slice(pos);
|
|
1259
|
+
return out;
|
|
1260
|
+
})();
|
|
1261
|
+
const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
|
|
1262
|
+
const useExpanded = groupExpanded.replace(
|
|
1263
|
+
/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
|
|
1264
|
+
(_w, name: string, hasParam: string | undefined, expr: string) =>
|
|
1265
|
+
hasParam
|
|
1266
|
+
? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}`
|
|
1267
|
+
: ` data-use="${name}"`,
|
|
1268
|
+
);
|
|
1269
|
+
const classExpanded = expandClassDirectives(useExpanded, filePath);
|
|
1270
|
+
const styleExpanded = expandStyleDirectives(classExpanded, filePath);
|
|
1271
|
+
const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
|
|
1272
|
+
const elseExpanded = expandIfElse(keyExpanded);
|
|
1273
|
+
const deferExpanded = expandDeferBlocks(elseExpanded);
|
|
1274
|
+
const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
|
|
1275
|
+
const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded
|
|
1276
|
+
.replace(SLOT_NAMED_RE, (_w: unknown, attrs: string, fallback: string) => {
|
|
1277
|
+
const call = `{__slot(${encodeSlotCall(attrs)})}`;
|
|
1278
|
+
if (fallback) {
|
|
1279
|
+
if (/\{[^{}]*\}/.test(fallback)) {
|
|
1280
|
+
throw new RoseError(
|
|
1281
|
+
'E-TEMPLATE',
|
|
1282
|
+
`${filePath}: slot fallback content must be static markup`,
|
|
1283
|
+
{ hint: 'a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content' },
|
|
1284
|
+
);
|
|
1285
|
+
}
|
|
1286
|
+
return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
|
|
1287
|
+
}
|
|
1288
|
+
return call;
|
|
1289
|
+
})
|
|
1290
|
+
.replace(SLOT_RE, (_w: unknown, fallback: string) =>
|
|
1291
|
+
fallback && fallback.trim()
|
|
1292
|
+
? `{__slotDefault(${JSON.stringify(fallback)})}`
|
|
1293
|
+
: '{__slot__}'), comps);
|
|
1294
|
+
assertKnownDirectives(ssrTemplate, filePath);
|
|
1103
1295
|
const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0, true, comps);
|
|
1104
|
-
// head block: no markers (esc() inline) - the whole block re-renders per call, so one
|
|
1105
|
-
// reactive closure drives document title/meta on navigation.
|
|
1106
1296
|
const compiledHead = headContent.trim() ? compileHead(headContent) : '';
|
|
1107
|
-
// A named slot in the template needs the __slot() helper in the module.
|
|
1108
1297
|
const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
|
|
1109
1298
|
|
|
1110
|
-
// Actions ship in the SSR module only; the client bundle gets every other
|
|
1111
|
-
// export (params, sync helpers) but never an action body.
|
|
1112
1299
|
const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
|
|
1113
|
-
// The guard is emitted at the SSR module's scope, beside the actions it fronts …
|
|
1114
1300
|
const ssrGuard = guard ? `\n${guard}` : '';
|
|
1115
|
-
// pages/_middleware.rose is a hook module, not a route: no template, no state, no head.
|
|
1116
1301
|
const isMiddleware = path.basename(filePath) === '_middleware.rose';
|
|
1117
1302
|
const ssr = isMiddleware
|
|
1118
1303
|
? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
|
|
1119
|
-
: generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1120
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
1304
|
+
: generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1305
|
+
const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
1121
1306
|
|
|
1122
|
-
// One rewrite for both bundles and every branch above: the `__rose_N__` placeholder
|
|
1123
|
-
// resolves to this bundle's own module path …
|
|
1124
1307
|
return {
|
|
1125
1308
|
ssr: rewriteRoseImports(ssr, 'ssr'),
|
|
1126
1309
|
client: rewriteRoseImports(client, 'client'),
|
|
@@ -1131,8 +1314,11 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1131
1314
|
hasParams,
|
|
1132
1315
|
usesContext,
|
|
1133
1316
|
revalidate,
|
|
1317
|
+
cache: cacheSeconds,
|
|
1134
1318
|
csr,
|
|
1319
|
+
shell,
|
|
1135
1320
|
buffer,
|
|
1321
|
+
controlSignal,
|
|
1136
1322
|
prefetch,
|
|
1137
1323
|
vitals,
|
|
1138
1324
|
bundle,
|
|
@@ -1188,8 +1374,6 @@ function scopeCss(css: string, key: string): string {
|
|
|
1188
1374
|
const block = clean.slice(i + 1, j - 1);
|
|
1189
1375
|
const sel = prelude.trim();
|
|
1190
1376
|
if (sel.startsWith('@')) {
|
|
1191
|
-
// at-rule: keep the prelude, scope the inner rules (keyframes pass
|
|
1192
|
-
// through: their 0%/from/to "selectors" are not selectors)
|
|
1193
1377
|
out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
|
|
1194
1378
|
} else if (sel) {
|
|
1195
1379
|
const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(',');
|
|
@@ -1223,7 +1407,6 @@ function injectScopeAttr(template: string, key: string): string {
|
|
|
1223
1407
|
break;
|
|
1224
1408
|
}
|
|
1225
1409
|
out += template.slice(i, lt);
|
|
1226
|
-
// scan one tag, respecting quoted attribute values
|
|
1227
1410
|
let j = lt + 1;
|
|
1228
1411
|
let quote = '';
|
|
1229
1412
|
while (j < template.length) {
|
|
@@ -1234,12 +1417,11 @@ function injectScopeAttr(template: string, key: string): string {
|
|
|
1234
1417
|
else if (c === '>') break;
|
|
1235
1418
|
j++;
|
|
1236
1419
|
}
|
|
1237
|
-
const tagText = template.slice(lt, j + 1);
|
|
1420
|
+
const tagText = template.slice(lt, j + 1);
|
|
1238
1421
|
const closing = /^<\//.test(tagText);
|
|
1239
1422
|
const nameMatch = tagText.match(/^<\/?([a-zA-Z][\w-]*)/);
|
|
1240
1423
|
const selfClosing = /\/>$/.test(tagText) || (nameMatch && VOID_TAGS.has(nameMatch[1].toLowerCase()));
|
|
1241
1424
|
if (nameMatch && !closing && depth === 0 && !selfClosing) {
|
|
1242
|
-
// inject before the closing > (or before a trailing />)
|
|
1243
1425
|
const injectAt = tagText.endsWith('/>') ? tagText.length - 2 : tagText.length - 1;
|
|
1244
1426
|
out += tagText.slice(0, injectAt) + attr + tagText.slice(injectAt);
|
|
1245
1427
|
depth++;
|
|
@@ -1254,7 +1436,6 @@ function injectScopeAttr(template: string, key: string): string {
|
|
|
1254
1436
|
|
|
1255
1437
|
const VOID_TAGS = new Set(['img', 'br', 'hr', 'input', 'meta', 'link', 'source', 'wbr']);
|
|
1256
1438
|
|
|
1257
|
-
// Trade-off: tolerate leading indentation - .rose script blocks are indented
|
|
1258
1439
|
const EXPORT_RE = /^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;
|
|
1259
1440
|
|
|
1260
1441
|
/**
|
|
@@ -1295,28 +1476,20 @@ function extractObjectLiteral(script: string, name: string): string | null {
|
|
|
1295
1476
|
return script.slice(start, i);
|
|
1296
1477
|
}
|
|
1297
1478
|
|
|
1298
|
-
// Exported for `rosetack check`: it synthesizes a module declaration for every imported
|
|
1299
|
-
// .rose component from the SAME prop parse the compiler uses …
|
|
1300
1479
|
export function extractExports(script: string): { clean: string; exports: string; actions: Array<{ name: string; stmt: string }>; props: Array<{ name: string; def: string | null }>; guard: string } {
|
|
1301
1480
|
const stmts: string[] = [];
|
|
1302
1481
|
const actions: Array<{ name: string; stmt: string }> = [];
|
|
1303
|
-
// `export let` is a PROP, not a module-scope value - it is read from the caller's props
|
|
1304
|
-
// object per invocation.
|
|
1305
1482
|
const props: Array<{ name: string; def: string | null }> = [];
|
|
1306
|
-
// `export async function beforeAction(name, form)` is the page's action GUARD - it runs
|
|
1307
|
-
// before every action and vetoes with an ActionError.
|
|
1308
1483
|
const guards: string[] = [];
|
|
1309
1484
|
let out = '';
|
|
1310
1485
|
let pos = 0;
|
|
1311
1486
|
let m: RegExpExecArray | null;
|
|
1312
1487
|
EXPORT_RE.lastIndex = 0;
|
|
1313
1488
|
while ((m = EXPORT_RE.exec(script))) {
|
|
1314
|
-
const kind = m[1];
|
|
1315
|
-
const start = m.index + m[0].indexOf('export');
|
|
1489
|
+
const kind = m[1];
|
|
1490
|
+
const start = m.index + m[0].indexOf('export');
|
|
1316
1491
|
let i = start + m[0].length - m[0].indexOf('export');
|
|
1317
1492
|
if (kind) {
|
|
1318
|
-
// balanced scan: object/array literals, calls, arrows end at their
|
|
1319
|
-
// matching close; primitive literals end at `;` or a plain newline.
|
|
1320
1493
|
let depth = 0;
|
|
1321
1494
|
while (i < script.length) {
|
|
1322
1495
|
const ch = script[i];
|
|
@@ -1341,7 +1514,6 @@ export function extractExports(script: string): { clean: string; exports: string
|
|
|
1341
1514
|
}
|
|
1342
1515
|
if (script[i] === ';') i++;
|
|
1343
1516
|
} else {
|
|
1344
|
-
// function declaration: skip the parameter list, balance the body
|
|
1345
1517
|
while (i < script.length && script[i] !== '{') i++;
|
|
1346
1518
|
let depth = 0;
|
|
1347
1519
|
while (i < script.length) {
|
|
@@ -1362,15 +1534,13 @@ export function extractExports(script: string): { clean: string; exports: string
|
|
|
1362
1534
|
const asyncFn = stmt.match(/^export\s+async\s+function\s+(\w+)/);
|
|
1363
1535
|
const anyFn = stmt.match(/^export\s+(?:async\s+)?function\s+(\w+)/);
|
|
1364
1536
|
if (anyFn?.[1] === 'beforeAction') {
|
|
1365
|
-
guards.push(stmt);
|
|
1537
|
+
guards.push(stmt);
|
|
1366
1538
|
} else if (asyncFn) {
|
|
1367
|
-
actions.push({ name: asyncFn[1], stmt });
|
|
1539
|
+
actions.push({ name: asyncFn[1], stmt });
|
|
1368
1540
|
} else if (kind === 'let') {
|
|
1369
|
-
// A prop. The declaration never reaches module scope - the generated render reads it from
|
|
1370
|
-
// the props object (with this default) …
|
|
1371
1541
|
const pm = stmt.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);
|
|
1372
1542
|
if (pm) props.push({ name: pm[1], def: pm[2]?.trim() ?? null });
|
|
1373
|
-
else stmts.push(stmt);
|
|
1543
|
+
else stmts.push(stmt);
|
|
1374
1544
|
} else {
|
|
1375
1545
|
stmts.push(stmt);
|
|
1376
1546
|
}
|
|
@@ -1380,13 +1550,26 @@ export function extractExports(script: string): { clean: string; exports: string
|
|
|
1380
1550
|
return { clean: out, exports: stmts.join('\n'), actions, props, guard: guards.join('\n') };
|
|
1381
1551
|
}
|
|
1382
1552
|
|
|
1553
|
+
const REGEX_PRECEDERS = new Set('(,=:[!&|?{};+-*%<>~^'.split(''));
|
|
1554
|
+
function isRegexStart(src: string, i: number): boolean {
|
|
1555
|
+
let j = i - 1;
|
|
1556
|
+
while (j >= 0 && /\s/.test(src[j])) j--;
|
|
1557
|
+
if (j < 0) return true;
|
|
1558
|
+
const p = src[j];
|
|
1559
|
+
if (REGEX_PRECEDERS.has(p)) return true;
|
|
1560
|
+
if (/[A-Za-z0-9_$]/.test(p)) {
|
|
1561
|
+
const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
|
|
1562
|
+
if (!w) return false;
|
|
1563
|
+
return ['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else'].includes(w[1]);
|
|
1564
|
+
}
|
|
1565
|
+
return false;
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1383
1568
|
function extractDecls(script: string): Decl[] {
|
|
1384
1569
|
const decls: Decl[] = [];
|
|
1385
1570
|
DECL_RE.lastIndex = 0;
|
|
1386
1571
|
let m: RegExpExecArray | null;
|
|
1387
1572
|
while ((m = DECL_RE.exec(script))) {
|
|
1388
|
-
// The regex matched up to `$state`/`$data`; what follows is an optional type-argument
|
|
1389
|
-
// list and then the call.
|
|
1390
1573
|
let j = m.index + m[0].length;
|
|
1391
1574
|
const skipSpace = () => { while (j < script.length && /\s/.test(script[j])) j++; };
|
|
1392
1575
|
skipSpace();
|
|
@@ -1398,12 +1581,12 @@ function extractDecls(script: string): Decl[] {
|
|
|
1398
1581
|
else if (ch === '>' && script[j - 1] !== '=') {
|
|
1399
1582
|
depth--;
|
|
1400
1583
|
if (depth === 0) { j++; break; }
|
|
1401
|
-
} else if (ch === '=' && script[j + 1] === '>') j++;
|
|
1584
|
+
} else if (ch === '=' && script[j + 1] === '>') j++;
|
|
1402
1585
|
j++;
|
|
1403
1586
|
}
|
|
1404
1587
|
skipSpace();
|
|
1405
1588
|
}
|
|
1406
|
-
if (script[j] !== '(') continue;
|
|
1589
|
+
if (script[j] !== '(') continue;
|
|
1407
1590
|
const open = j + 1;
|
|
1408
1591
|
let depth = 1;
|
|
1409
1592
|
let i = open;
|
|
@@ -1419,7 +1602,7 @@ function extractDecls(script: string): Decl[] {
|
|
|
1419
1602
|
if (script[end] === ';') end++;
|
|
1420
1603
|
decls.push({
|
|
1421
1604
|
name: m[1],
|
|
1422
|
-
kind: m[2] as 'state' | 'data',
|
|
1605
|
+
kind: m[2] as 'state' | 'data' | 'persist',
|
|
1423
1606
|
expr: script.slice(open, i - 1).trim(),
|
|
1424
1607
|
start: m.index,
|
|
1425
1608
|
end,
|
|
@@ -1446,7 +1629,6 @@ function braceDepthAt(src: string, index: number): number {
|
|
|
1446
1629
|
while (i < index) {
|
|
1447
1630
|
if (src[i] === '\\') { i += 2; continue; }
|
|
1448
1631
|
if (src[i] === quote) { i++; break; }
|
|
1449
|
-
// a ${...} inside a template literal is code again
|
|
1450
1632
|
if (quote === '`' && src[i] === '$' && src[i + 1] === '{') {
|
|
1451
1633
|
let d = 1;
|
|
1452
1634
|
i += 2;
|
|
@@ -1471,6 +1653,21 @@ function braceDepthAt(src: string, index: number): number {
|
|
|
1471
1653
|
i = close === -1 ? src.length : close + 2;
|
|
1472
1654
|
continue;
|
|
1473
1655
|
}
|
|
1656
|
+
if (ch === '/' && isRegexStart(src, i)) {
|
|
1657
|
+
i++;
|
|
1658
|
+
let inClass = false;
|
|
1659
|
+
while (i < index) {
|
|
1660
|
+
const c2 = src[i];
|
|
1661
|
+
if (c2 === '\\') { i += 2; continue; }
|
|
1662
|
+
if (inClass) { if (c2 === ']') inClass = false; i++; continue; }
|
|
1663
|
+
if (c2 === '[') { inClass = true; i++; continue; }
|
|
1664
|
+
if (c2 === '/') { i++; break; }
|
|
1665
|
+
if (c2 === '\n') break;
|
|
1666
|
+
i++;
|
|
1667
|
+
}
|
|
1668
|
+
while (i < index && /[a-z]/.test(src[i])) i++;
|
|
1669
|
+
continue;
|
|
1670
|
+
}
|
|
1474
1671
|
if (ch === '{') depth++;
|
|
1475
1672
|
else if (ch === '}') depth--;
|
|
1476
1673
|
i++;
|
|
@@ -1478,35 +1675,9 @@ function braceDepthAt(src: string, index: number): number {
|
|
|
1478
1675
|
return depth;
|
|
1479
1676
|
}
|
|
1480
1677
|
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
* reactive markers, and push update closures into the shared `closes` array.
|
|
1484
|
-
*
|
|
1485
|
-
* Marker protocol (identical on server and client, so the client can adopt
|
|
1486
|
-
* the SSR DOM instead of re-rendering it):
|
|
1487
|
-
* text: <!--⟦m:K⟧-->value wire() updates the following text node
|
|
1488
|
-
* if block: <!--⟦i:K⟧-->html<!--⟦/i:K⟧--> wire() inserts/removes the block
|
|
1489
|
-
* each list: <!--⟦l:K⟧-->items<!--⟦/l:K⟧--> wire() rebuilds the list
|
|
1490
|
-
* attr: name="value" data-b="K:name" wire() re-sets the attribute
|
|
1491
|
-
*
|
|
1492
|
-
* Text/attr values are HTML-escaped on the server; wire() writes raw values
|
|
1493
|
-
* because DOM text nodes and attributes are not HTML-parsed.
|
|
1494
|
-
*
|
|
1495
|
-
* `comps` maps an imported component's local name to its module index
|
|
1496
|
-
* and slot declarations. A `<Card title={x}>` tag compiles to a call of that
|
|
1497
|
-
* module's render() - the child pushes its markers into the SAME closes array
|
|
1498
|
-
* the parent is using, so one wire() pass covers the whole tree (the same
|
|
1499
|
-
* trick the layout chain already uses with children html).
|
|
1500
|
-
*/
|
|
1678
|
+
// Compile a .rose template to statements that build an HTML string with reactive markers, and push update closures into the shared `closes` array.
|
|
1679
|
+
|
|
1501
1680
|
|
|
1502
|
-
/**
|
|
1503
|
-
* Auto-call a BARE state read and nothing else. The callify pass has already
|
|
1504
|
-
* rewritten a bare name to `name()`, so what reaches here is that - or an
|
|
1505
|
-
* expression the developer wrote (a comparison, a member read, a call with
|
|
1506
|
-
* arguments). Appending () to THOSE is a crash the developer reads as a
|
|
1507
|
-
* framework bug: `{#if flash().name}` must not become `flash().name()`, and
|
|
1508
|
-
* `{#each rows.filter(ok) as row}` must not become `rows.filter(ok)()`.
|
|
1509
|
-
*/
|
|
1510
1681
|
function autoCall(expr: string): string {
|
|
1511
1682
|
const e = expr.trim();
|
|
1512
1683
|
return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
|
|
@@ -1529,12 +1700,444 @@ function autoCall(expr: string): string {
|
|
|
1529
1700
|
* Returns a RegExpExecArray-shaped value (index + capture groups in the
|
|
1530
1701
|
* same order the old regexes produced) so the call sites are unchanged.
|
|
1531
1702
|
*/
|
|
1532
|
-
|
|
1703
|
+
|
|
1704
|
+
const DEFER_ENABLED = true;
|
|
1705
|
+
|
|
1706
|
+
/**
|
|
1707
|
+
* F4 ({#key} block): `{#key expr}body{/key}` re-creates the body whenever
|
|
1708
|
+
* `expr` changes - the escape hatch for DOM whose local state must reset
|
|
1709
|
+
* (a form re-keyed by its subject, a chart re-keyed by its dataset).
|
|
1710
|
+
* Pure compiler sugar: it desugars to `{#each [expr] as __rvkv}body{/each}` -
|
|
1711
|
+
* the each's items closure reads expr, so any dependency change re-runs the
|
|
1712
|
+
* map and rebuilds every node, which IS key semantics. Zero runtime change.
|
|
1713
|
+
* Unclosed blocks fail loudly here instead of rendering as prose.
|
|
1714
|
+
*/
|
|
1715
|
+
function expandKeyBlocks(template: string, filePath: string): string {
|
|
1716
|
+
if (!template.includes('{#key')) return template;
|
|
1717
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1718
|
+
const OPEN_RE = /\{#key\s+([^}]+)\}/g;
|
|
1719
|
+
OPEN_RE.lastIndex = 0;
|
|
1720
|
+
const openM = OPEN_RE.exec(template);
|
|
1721
|
+
if (!openM) return template;
|
|
1722
|
+
const expr = openM[1].trim();
|
|
1723
|
+
const bodyStart = openM.index + openM[0].length;
|
|
1724
|
+
const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
|
|
1725
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1726
|
+
let depth = 1;
|
|
1727
|
+
let closeAt = -1;
|
|
1728
|
+
let tm: RegExpExecArray | null;
|
|
1729
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
1730
|
+
if (tm[0].startsWith('{#')) { depth++; continue; }
|
|
1731
|
+
depth--;
|
|
1732
|
+
if (depth === 0) { closeAt = tm.index; break; }
|
|
1733
|
+
}
|
|
1734
|
+
if (closeAt < 0) {
|
|
1735
|
+
throw new RoseError(
|
|
1736
|
+
'E-TEMPLATE',
|
|
1737
|
+
`${filePath}: {#key ${expr}} is never closed`,
|
|
1738
|
+
{ hint: 'every {#key} needs its {/key}' },
|
|
1739
|
+
);
|
|
1740
|
+
}
|
|
1741
|
+
template =
|
|
1742
|
+
template.slice(0, openM.index) +
|
|
1743
|
+
`{#each [${expr}] as __rvkv}` +
|
|
1744
|
+
template.slice(bodyStart, closeAt) +
|
|
1745
|
+
'{/each}' +
|
|
1746
|
+
template.slice(closeAt + '{/key}'.length);
|
|
1747
|
+
}
|
|
1748
|
+
return template;
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
/**
|
|
1752
|
+
* F2 (ergonomics): `{:else}` and `{:else if cond}` on {#if} blocks - the
|
|
1753
|
+
* branch syntax every other template language has, retracted here after the
|
|
1754
|
+
* author judged the earlier refusal over-strict. One pass walks every {#if}
|
|
1755
|
+
* block, splits its TOP-LEVEL `{:else}` chain (nested blocks' elses are
|
|
1756
|
+
* theirs), and re-emits the block as complementary {#if}s:
|
|
1757
|
+
* {#if A}a{:else}b{/if} -> {#if A}a{/if}{#if !(A)}b{/if}
|
|
1758
|
+
* {#if A}a{:else if B}b{:else}c{/if}
|
|
1759
|
+
* -> {#if A}a{/if}{#if !(A)}{#if B}b{/if}{#if !(B)}c{/if}{/if}
|
|
1760
|
+
* Zero new runtime, zero new marker kinds: wire()/ifMark already adopt and
|
|
1761
|
+
* flip both shapes, and each condition re-evaluates - free for the pure
|
|
1762
|
+
* state reads that are the only legal condition kind here. Runs BEFORE
|
|
1763
|
+
* defer expansion (so a {:else} inside a {#defer} body lands on expanded
|
|
1764
|
+
* ground) and repeated until stable, because nested ifs with their own
|
|
1765
|
+
* elses surface one level per pass. Defer bodies are transparent to the
|
|
1766
|
+
* depth walk on purpose: {#defer} is not a block kind, and every {#if}
|
|
1767
|
+
* inside it is balanced on its own.
|
|
1768
|
+
*/
|
|
1769
|
+
function expandIfElseOnce(template: string): { template: string; changed: boolean } {
|
|
1770
|
+
const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
|
|
1771
|
+
let out = '';
|
|
1772
|
+
let pos = 0;
|
|
1773
|
+
let changed = false;
|
|
1774
|
+
for (;;) {
|
|
1775
|
+
const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
|
|
1776
|
+
if (!openM) { out += template.slice(pos); break; }
|
|
1777
|
+
const kind = openM[1];
|
|
1778
|
+
const head = openM[2];
|
|
1779
|
+
const start = pos + openM.index;
|
|
1780
|
+
const cond = kind === 'if' ? head.trim() : '';
|
|
1781
|
+
const bodyStart = start + openM[0].length;
|
|
1782
|
+
out += template.slice(pos, start);
|
|
1783
|
+
|
|
1784
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1785
|
+
let depth = 1;
|
|
1786
|
+
let closeAt = -1;
|
|
1787
|
+
let closeLen = 0;
|
|
1788
|
+
const elses: Array<{ at: number; len: number; cond: string | null }> = [];
|
|
1789
|
+
let tm: RegExpExecArray | null;
|
|
1790
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
1791
|
+
const tok = tm[0];
|
|
1792
|
+
if (tok.startsWith('{:else')) {
|
|
1793
|
+
if (depth === 1) {
|
|
1794
|
+
const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
|
|
1795
|
+
elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
|
|
1796
|
+
}
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
if (tok.startsWith('{#')) { depth++; continue; }
|
|
1800
|
+
depth--;
|
|
1801
|
+
if (depth === 0) { closeAt = tm.index; closeLen = tok.length; break; }
|
|
1802
|
+
}
|
|
1803
|
+
if (closeAt < 0 || elses.length === 0) {
|
|
1804
|
+
out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
|
|
1805
|
+
if (closeAt < 0) break;
|
|
1806
|
+
pos = closeAt + closeLen;
|
|
1807
|
+
continue;
|
|
1808
|
+
}
|
|
1809
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1810
|
+
if (kind === 'each') {
|
|
1811
|
+
const lastBare = [...elses].reverse().find((e) => e.cond === null);
|
|
1812
|
+
if (!lastBare) {
|
|
1813
|
+
out += template.slice(start, closeAt + closeLen);
|
|
1814
|
+
pos = closeAt + closeLen;
|
|
1815
|
+
continue;
|
|
1816
|
+
}
|
|
1817
|
+
const relLast = lastBare.at - bodyStart;
|
|
1818
|
+
const eachBody = body.slice(0, relLast);
|
|
1819
|
+
const elseBody = body.slice(relLast + lastBare.len);
|
|
1820
|
+
const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, '').trim();
|
|
1821
|
+
out += template.slice(start, bodyStart) + eachBody + '{/each}'
|
|
1822
|
+
+ `{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
|
|
1823
|
+
pos = closeAt + closeLen;
|
|
1824
|
+
changed = true;
|
|
1825
|
+
continue;
|
|
1826
|
+
}
|
|
1827
|
+
const branches: Array<{ cond: string | null; body: string }> = [];
|
|
1828
|
+
let cursor = 0;
|
|
1829
|
+
for (let i = 0; i < elses.length; i++) {
|
|
1830
|
+
const e = elses[i];
|
|
1831
|
+
const rel = e.at - bodyStart;
|
|
1832
|
+
branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
|
|
1833
|
+
cursor = rel + e.len;
|
|
1834
|
+
}
|
|
1835
|
+
branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
|
|
1836
|
+
const first = branches.shift()!;
|
|
1837
|
+
const build = (bs: Array<{ cond: string | null; body: string }>): string => {
|
|
1838
|
+
if (!bs.length) return '';
|
|
1839
|
+
const head = bs[0];
|
|
1840
|
+
const rest = bs.slice(1);
|
|
1841
|
+
if (head.cond == null) return head.body;
|
|
1842
|
+
let s = `{#if ${head.cond}}${head.body}{/if}`;
|
|
1843
|
+
if (rest.length) s += `{#if !(${head.cond})}` + build(rest) + `{/if}`;
|
|
1844
|
+
return s;
|
|
1845
|
+
};
|
|
1846
|
+
let emitted = `{#if ${cond}}${first.body}{/if}`;
|
|
1847
|
+
if (branches.length) emitted += `{#if !(${cond})}` + build(branches) + `{/if}`;
|
|
1848
|
+
out += emitted;
|
|
1849
|
+
pos = closeAt + closeLen;
|
|
1850
|
+
changed = true;
|
|
1851
|
+
}
|
|
1852
|
+
return { template: out, changed };
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
/**
|
|
1856
|
+
* F2c (class: directive): `class:NAME={expr}` merges with the tag's static
|
|
1857
|
+
* class into ONE reactive class attribute whose closure concatenates the
|
|
1858
|
+
* static value plus each conditional segment - one attrMark, one data-b
|
|
1859
|
+
* marker, all conditions re-evaluated together on every toggle. This runs
|
|
1860
|
+
* AFTER callifyTemplateExprs, so the expressions arrive pre-callified and
|
|
1861
|
+
* are re-emitted verbatim inside a template literal. A tag that already
|
|
1862
|
+
* carries a REACTIVE class={...} cannot merge (two writers, one attribute)
|
|
1863
|
+
* and fails here, at the .rose file.
|
|
1864
|
+
*/
|
|
1865
|
+
function expandClassDirectives(template: string, filePath: string): string {
|
|
1866
|
+
if (!template.includes('class:')) return template;
|
|
1867
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1868
|
+
let out = '';
|
|
1869
|
+
let pos = 0;
|
|
1870
|
+
let m: RegExpExecArray | null;
|
|
1871
|
+
TAG_RE.lastIndex = 0;
|
|
1872
|
+
while ((m = TAG_RE.exec(template))) {
|
|
1873
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1874
|
+
if (!attrs.includes('class:')) continue;
|
|
1875
|
+
const pairs: Array<{ name: string; expr: string; start: number; end: number }> = [];
|
|
1876
|
+
const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
|
|
1877
|
+
let nm: RegExpExecArray | null;
|
|
1878
|
+
while ((nm = NAME_RE.exec(attrs))) {
|
|
1879
|
+
let i = nm.index + nm[0].length;
|
|
1880
|
+
let depth = 1;
|
|
1881
|
+
while (i < attrs.length && depth > 0) {
|
|
1882
|
+
const ch = attrs[i];
|
|
1883
|
+
if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
|
|
1884
|
+
if (ch === '{') depth++;
|
|
1885
|
+
else if (ch === '}') depth--;
|
|
1886
|
+
i++;
|
|
1887
|
+
}
|
|
1888
|
+
if (depth !== 0) {
|
|
1889
|
+
throw new RoseError('E-TEMPLATE', `${filePath}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: 'the binding expression needs a matching } before the tag ends' });
|
|
1890
|
+
}
|
|
1891
|
+
pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1892
|
+
}
|
|
1893
|
+
const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1894
|
+
const clsM = clsRe.exec(attrs);
|
|
1895
|
+
if (clsM && clsM[2].startsWith('{')) {
|
|
1896
|
+
throw new RoseError('E-TEMPLATE', `${filePath}: <${tag}> has both class={...} and class: directives`, { file: filePath, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
|
|
1897
|
+
}
|
|
1898
|
+
const staticCls = clsM ? (clsM[3] ?? clsM[4] ?? '') : '';
|
|
1899
|
+
let closure = `(${JSON.stringify(staticCls)}`;
|
|
1900
|
+
for (const p of pairs) {
|
|
1901
|
+
closure += `+((${p.expr})?${JSON.stringify(' ' + p.name)}:'')`;
|
|
1902
|
+
}
|
|
1903
|
+
closure += `)`;
|
|
1904
|
+
let newAttrs = attrs;
|
|
1905
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1906
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1907
|
+
}
|
|
1908
|
+
if (clsM) {
|
|
1909
|
+
newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
|
|
1910
|
+
} else {
|
|
1911
|
+
newAttrs = ` class={${closure}}` + newAttrs;
|
|
1912
|
+
}
|
|
1913
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1914
|
+
pos = m.index + whole.length;
|
|
1915
|
+
}
|
|
1916
|
+
if (pos === 0) return template;
|
|
1917
|
+
out += template.slice(pos);
|
|
1918
|
+
return out;
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/**
|
|
1922
|
+
* F2f (style: directive): `style:PROP={expr}` merges with the tag's static
|
|
1923
|
+
* style into ONE reactive style attribute - the overrides are appended AFTER
|
|
1924
|
+
* the static declarations, so CSS last-wins makes them authoritative, exactly
|
|
1925
|
+
* the expected precedence. Same quote-aware tag scanner and same
|
|
1926
|
+
* reactive-class={...} conflict rule as expandClassDirectives.
|
|
1927
|
+
*/
|
|
1928
|
+
function expandStyleDirectives(template: string, filePath: string): string {
|
|
1929
|
+
if (!template.includes('style:')) return template;
|
|
1930
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1931
|
+
let out = '';
|
|
1932
|
+
let pos = 0;
|
|
1933
|
+
let m: RegExpExecArray | null;
|
|
1934
|
+
TAG_RE.lastIndex = 0;
|
|
1935
|
+
while ((m = TAG_RE.exec(template))) {
|
|
1936
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1937
|
+
if (!attrs.includes('style:')) continue;
|
|
1938
|
+
const pairs: Array<{ prop: string; expr: string; start: number; end: number }> = [];
|
|
1939
|
+
const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
|
|
1940
|
+
let nm: RegExpExecArray | null;
|
|
1941
|
+
while ((nm = NAME_RE.exec(attrs))) {
|
|
1942
|
+
let i = nm.index + nm[0].length;
|
|
1943
|
+
let depth = 1;
|
|
1944
|
+
while (i < attrs.length && depth > 0) {
|
|
1945
|
+
const ch = attrs[i];
|
|
1946
|
+
if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
|
|
1947
|
+
if (ch === '{') depth++;
|
|
1948
|
+
else if (ch === '}') depth--;
|
|
1949
|
+
i++;
|
|
1950
|
+
}
|
|
1951
|
+
if (depth !== 0) {
|
|
1952
|
+
throw new RoseError('E-TEMPLATE', `${filePath}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: 'the binding expression needs a matching } before the tag ends' });
|
|
1953
|
+
}
|
|
1954
|
+
pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1955
|
+
}
|
|
1956
|
+
const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1957
|
+
const stM = styleRe.exec(attrs);
|
|
1958
|
+
if (stM && stM[2].startsWith('{')) {
|
|
1959
|
+
throw new RoseError('E-TEMPLATE', `${filePath}: <${tag}> has both style={...} and style: directives`, { file: filePath, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
|
|
1960
|
+
}
|
|
1961
|
+
const staticStyle = stM ? (stM[3] ?? stM[4] ?? '') : '';
|
|
1962
|
+
let closure = `${JSON.stringify(staticStyle.endsWith(';') || staticStyle === '' ? staticStyle : staticStyle + ';')}`;
|
|
1963
|
+
for (const p of pairs) {
|
|
1964
|
+
closure += `+${JSON.stringify(p.prop + ':')}+(${p.expr})+';'`;
|
|
1965
|
+
}
|
|
1966
|
+
let newAttrs = attrs;
|
|
1967
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1968
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1969
|
+
}
|
|
1970
|
+
if (stM) {
|
|
1971
|
+
newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
|
|
1972
|
+
} else {
|
|
1973
|
+
newAttrs = ` style={${closure}}` + newAttrs;
|
|
1974
|
+
}
|
|
1975
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1976
|
+
pos = m.index + whole.length;
|
|
1977
|
+
}
|
|
1978
|
+
if (pos === 0) return template;
|
|
1979
|
+
out += template.slice(pos);
|
|
1980
|
+
return out;
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
/**
|
|
1984
|
+
* F11 (boundary {:fallback}): extracts each {#boundary} block's top-level
|
|
1985
|
+
* `{:fallback}` segment and encodes it as a base64 `__fb` attribute on the
|
|
1986
|
+
* boundary opener — base64 so the encoded markup survives every `[^}]*`
|
|
1987
|
+
* attr scan downstream. The dispatch decodes it and compiles the fallback
|
|
1988
|
+
* like any block (reactive exprs supported). Nested boundaries surface one
|
|
1989
|
+
* level per pass; a stray {:fallback} is left for assertKnownDirectives.
|
|
1990
|
+
*/
|
|
1991
|
+
function expandBoundaryFallbacks(template: string, filePath: string): string {
|
|
1992
|
+
if (!template.includes('{:fallback')) return template;
|
|
1993
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1994
|
+
const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
|
|
1995
|
+
let out = '';
|
|
1996
|
+
let pos = 0;
|
|
1997
|
+
let changed = false;
|
|
1998
|
+
let tm: RegExpExecArray | null;
|
|
1999
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
2000
|
+
if (tm[0] !== '{#boundary}') continue;
|
|
2001
|
+
const start = tm.index;
|
|
2002
|
+
const bodyStart = start + tm[0].length;
|
|
2003
|
+
let depth = 1;
|
|
2004
|
+
let closeAt = -1;
|
|
2005
|
+
let tm2: RegExpExecArray | null;
|
|
2006
|
+
while ((tm2 = TOK_RE.exec(template))) {
|
|
2007
|
+
if (tm2[0] === '{#boundary}') { depth++; continue; }
|
|
2008
|
+
if (tm2[0] === '{/boundary}') { depth--; if (depth === 0) { closeAt = tm2.index; break; } }
|
|
2009
|
+
}
|
|
2010
|
+
if (closeAt < 0) break;
|
|
2011
|
+
const body = template.slice(bodyStart, closeAt);
|
|
2012
|
+
const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
|
|
2013
|
+
const kindStack = ['boundary'];
|
|
2014
|
+
let d = 1;
|
|
2015
|
+
let fbAt = -1;
|
|
2016
|
+
let fbLen = 0;
|
|
2017
|
+
let tm3: RegExpExecArray | null;
|
|
2018
|
+
BTOK2.lastIndex = 0;
|
|
2019
|
+
while ((tm3 = BTOK2.exec(body))) {
|
|
2020
|
+
const tok = tm3[0];
|
|
2021
|
+
if (tok === '{:fallback}') {
|
|
2022
|
+
const top = kindStack[kindStack.length - 1];
|
|
2023
|
+
if (top !== 'boundary') {
|
|
2024
|
+
throw new RoseError(
|
|
2025
|
+
'E-TEMPLATE',
|
|
2026
|
+
`${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
|
|
2027
|
+
{ hint: 'move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent' },
|
|
2028
|
+
);
|
|
2029
|
+
}
|
|
2030
|
+
if (fbAt >= 0) {
|
|
2031
|
+
throw new RoseError('E-TEMPLATE', `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: 'remove the extra {:fallback} segment' });
|
|
2032
|
+
}
|
|
2033
|
+
fbAt = tm3.index;
|
|
2034
|
+
fbLen = tok.length;
|
|
2035
|
+
continue;
|
|
2036
|
+
}
|
|
2037
|
+
if (tok.startsWith('{#')) { d++; kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]); continue; }
|
|
2038
|
+
d--; kindStack.pop();
|
|
2039
|
+
}
|
|
2040
|
+
if (fbAt < 0) continue;
|
|
2041
|
+
const custom = body.slice(0, fbAt);
|
|
2042
|
+
const fbMarkup = body.slice(fbAt + fbLen);
|
|
2043
|
+
const b64 = Buffer.from(fbMarkup, 'utf-8').toString('base64');
|
|
2044
|
+
out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + '{/boundary}';
|
|
2045
|
+
pos = closeAt + '{/boundary}'.length;
|
|
2046
|
+
changed = true;
|
|
2047
|
+
}
|
|
2048
|
+
if (!changed) break;
|
|
2049
|
+
template = out + template.slice(pos);
|
|
2050
|
+
}
|
|
2051
|
+
return template;
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
function expandIfElse(template: string): string { for (let pass = 0; pass < 10; pass++) {
|
|
2055
|
+
if (!/\{:else\b/.test(template)) return template;
|
|
2056
|
+
const r = expandIfElseOnce(template);
|
|
2057
|
+
template = r.template;
|
|
2058
|
+
if (!r.changed) return template;
|
|
2059
|
+
}
|
|
2060
|
+
return template;
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
function expandDeferBlocks(template: string): { template: string; count: number; holds: number[] } {
|
|
2064
|
+
if (!DEFER_ENABLED) {
|
|
2065
|
+
const openRe = /\{#defer(?:\s+hold=\\d+)?\}/g;
|
|
2066
|
+
let out = '';
|
|
2067
|
+
let dpos = 0;
|
|
2068
|
+
for (;;) {
|
|
2069
|
+
openRe.lastIndex = dpos;
|
|
2070
|
+
const openM = openRe.exec(template);
|
|
2071
|
+
if (!openM) break;
|
|
2072
|
+
const openAt = openM.index;
|
|
2073
|
+
const openLen = openM[0].length;
|
|
2074
|
+
const closeAt = template.indexOf('{/defer}', openAt + openLen);
|
|
2075
|
+
if (closeAt < 0) break;
|
|
2076
|
+
out += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
|
|
2077
|
+
dpos = closeAt + 8;
|
|
2078
|
+
}
|
|
2079
|
+
return { template: dpos === 0 ? template : out, count: 0, holds: [] };
|
|
2080
|
+
}
|
|
2081
|
+
let count = 0;
|
|
2082
|
+
const holds: number[] = [];
|
|
2083
|
+
let out = '';
|
|
2084
|
+
let pos = 0;
|
|
2085
|
+
const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
|
|
2086
|
+
for (;;) {
|
|
2087
|
+
openRe.lastIndex = pos;
|
|
2088
|
+
const openM = openRe.exec(template);
|
|
2089
|
+
if (!openM) break;
|
|
2090
|
+
const openAt = openM.index;
|
|
2091
|
+
const openLen = openM[0].length;
|
|
2092
|
+
const hold = openM[1] ? Number(openM[1]) : 0;
|
|
2093
|
+
let depth = 1;
|
|
2094
|
+
let i = openAt + openLen;
|
|
2095
|
+
let closeAt = -1;
|
|
2096
|
+
while (i < template.length) {
|
|
2097
|
+
openRe.lastIndex = i;
|
|
2098
|
+
const nextOpenM = openRe.exec(template);
|
|
2099
|
+
const nextOpen = nextOpenM ? nextOpenM.index : -1;
|
|
2100
|
+
const nextClose = template.indexOf('{/defer}', i);
|
|
2101
|
+
if (nextClose < 0) break;
|
|
2102
|
+
if (nextOpen >= 0 && nextOpen < nextClose) { depth++; i = nextOpen + nextOpenM![0].length; continue; }
|
|
2103
|
+
depth--;
|
|
2104
|
+
if (depth === 0) { closeAt = nextClose; break; }
|
|
2105
|
+
i = nextClose + 8;
|
|
2106
|
+
}
|
|
2107
|
+
if (closeAt < 0) break;
|
|
2108
|
+
const content = template.slice(openAt + openLen, closeAt);
|
|
2109
|
+
holds.push(hold);
|
|
2110
|
+
const n = ++count;
|
|
2111
|
+
out += template.slice(pos, openAt);
|
|
2112
|
+
out += '{#if __rvDefer' + n + '()}' + content + '{/if}' + '\n' +
|
|
2113
|
+
'{#if !__rvDefer' + n + '()}<div class="rv-defer-loading"></div>{/if}';
|
|
2114
|
+
pos = closeAt + 8;
|
|
2115
|
+
}
|
|
2116
|
+
if (count === 0) return { template, count: 0, holds: [] };
|
|
2117
|
+
out += template.slice(pos);
|
|
2118
|
+
return { template: out, count, holds };
|
|
2119
|
+
}
|
|
2120
|
+
|
|
2121
|
+
function deferBootCode(count: number, holds: number[] = []): string {
|
|
2122
|
+
let code = '';
|
|
2123
|
+
for (let n = 1; n <= count; n++) {
|
|
2124
|
+
code += 'const [__rvDefer' + n + ', set__rvDefer' + n + '] = state("__rvdefer' + n + '", false);\n';
|
|
2125
|
+
const hold = holds[n - 1] || 0;
|
|
2126
|
+
code += hold > 0
|
|
2127
|
+
? 'onMount(function () { setTimeout(function () { set__rvDefer' + n + '(true); }, ' + hold + '); });\n'
|
|
2128
|
+
: 'onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer' + n + '(true); }); }); });\n';
|
|
2129
|
+
}
|
|
2130
|
+
return code;
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
function findBlock(src: string, kind: 'if' | 'each' | 'boundary' | 'island'): RegExpExecArray | null {
|
|
1533
2134
|
const head = kind === 'boundary'
|
|
1534
|
-
? /\{#boundary
|
|
2135
|
+
? /\{#boundary(?:\s+([^}]*))?\}/g
|
|
1535
2136
|
: kind === 'if'
|
|
1536
2137
|
? /\{#if\s+([^}]+)\}/g
|
|
1537
|
-
:
|
|
2138
|
+
: kind === 'island'
|
|
2139
|
+
? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g
|
|
2140
|
+
: /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
|
|
1538
2141
|
const closeRe = new RegExp(`\\{/${kind}\\}`, 'g');
|
|
1539
2142
|
let open: RegExpExecArray | null;
|
|
1540
2143
|
while ((open = head.exec(src))) {
|
|
@@ -1547,7 +2150,7 @@ function findBlock(src: string, kind: 'if' | 'each' | 'boundary'): RegExpExecArr
|
|
|
1547
2150
|
closeRe.lastIndex = i;
|
|
1548
2151
|
const nextOpen = head.exec(src);
|
|
1549
2152
|
const nextClose = closeRe.exec(src);
|
|
1550
|
-
if (!nextClose) break;
|
|
2153
|
+
if (!nextClose) break;
|
|
1551
2154
|
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
1552
2155
|
depth++;
|
|
1553
2156
|
i = nextOpen.index + nextOpen[0].length;
|
|
@@ -1556,7 +2159,9 @@ function findBlock(src: string, kind: 'if' | 'each' | 'boundary'): RegExpExecArr
|
|
|
1556
2159
|
i = nextClose.index + nextClose[0].length;
|
|
1557
2160
|
if (--depth === 0) {
|
|
1558
2161
|
const content = src.slice(afterOpen, nextClose.index);
|
|
1559
|
-
const groups = kind === 'boundary' ? [
|
|
2162
|
+
const groups = kind === 'boundary' ? [open[1] ?? '', content]
|
|
2163
|
+
: kind === 'island' ? [open[1] ?? '', open[2] ?? '', content]
|
|
2164
|
+
: kind === 'if' ? [open[1], content] : [open[1], open[2], open[3] ?? '', content];
|
|
1560
2165
|
const arr = [src.slice(start, i), ...groups] as unknown as RegExpExecArray;
|
|
1561
2166
|
(arr as any).index = start;
|
|
1562
2167
|
return arr;
|
|
@@ -1599,22 +2204,170 @@ function compileHead(head: string): string {
|
|
|
1599
2204
|
i = end < 0 ? head.length : end + 3;
|
|
1600
2205
|
continue;
|
|
1601
2206
|
}
|
|
1602
|
-
RAW_OPEN.lastIndex = i;
|
|
1603
|
-
const open = RAW_OPEN.exec(head);
|
|
1604
|
-
if (open) {
|
|
1605
|
-
const tag = open[1].toLowerCase();
|
|
1606
|
-
const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
|
|
1607
|
-
const gt = closeAt < 0 ? -1 : head.indexOf('>', closeAt);
|
|
1608
|
-
const end = gt < 0 ? head.length : gt + 1;
|
|
1609
|
-
flush();
|
|
1610
|
-
out += emitChunk(head.slice(i, end), '__hd', '__hc', null);
|
|
1611
|
-
i = end;
|
|
1612
|
-
continue;
|
|
2207
|
+
RAW_OPEN.lastIndex = i;
|
|
2208
|
+
const open = RAW_OPEN.exec(head);
|
|
2209
|
+
if (open) {
|
|
2210
|
+
const tag = open[1].toLowerCase();
|
|
2211
|
+
const closeAt = head.toLowerCase().indexOf(`</${tag}`, i + open[0].length);
|
|
2212
|
+
const gt = closeAt < 0 ? -1 : head.indexOf('>', closeAt);
|
|
2213
|
+
const end = gt < 0 ? head.length : gt + 1;
|
|
2214
|
+
flush();
|
|
2215
|
+
out += emitChunk(head.slice(i, end), '__hd', '__hc', null);
|
|
2216
|
+
i = end;
|
|
2217
|
+
continue;
|
|
2218
|
+
}
|
|
2219
|
+
buf += head[i++];
|
|
2220
|
+
}
|
|
2221
|
+
flush();
|
|
2222
|
+
return out;
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
/**
|
|
2226
|
+
* - "errors an agent can fix" - closed on a real
|
|
2227
|
+
* failure from the field. A template directive rosetack does not implement
|
|
2228
|
+
* used to reach esbuild as generated code and die THERE: the oboext port
|
|
2229
|
+
* wrote `{:else}` (the branch syntax every other template language has and
|
|
2230
|
+
* rosetack deliberately does not - `prompt.ts` says so in one line) and got
|
|
2231
|
+
* `dist/.build/comp-12.ssr.js:87: ERROR: Unexpected ":"` - a file the author
|
|
2232
|
+
* never wrote, a construct never named, a fix never suggested. An unknown
|
|
2233
|
+
* directive is now a build error at the .rose file, with the line, the
|
|
2234
|
+
* construct and the rosetack shape that replaces it.
|
|
2235
|
+
*
|
|
2236
|
+
* The known set is exactly what findBlock matches: `{#if}`, `{#each}`,
|
|
2237
|
+
* `{#boundary}` and their closers. There is no `{:...}` directive at all.
|
|
2238
|
+
* The same gate catches the two shapes findBlock cannot match at all - an
|
|
2239
|
+
* `{#each}` with no `as <name>` and an opener with no closer - which used to
|
|
2240
|
+
* reach esbuild the same way (`Unexpected "#each"`, `Unexpected "#if"`).
|
|
2241
|
+
* Adversarial probing found all three in one afternoon; a template compiler
|
|
2242
|
+
* that emits broken code silently is the worst failure mode it has.
|
|
2243
|
+
*/
|
|
2244
|
+
const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary', 'island']);
|
|
2245
|
+
function assertKnownDirectives(template: string, filePath: string): void {
|
|
2246
|
+
const rawRanges: Array<[number, number]> = [];
|
|
2247
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
2248
|
+
let raw: RegExpExecArray | null;
|
|
2249
|
+
while ((raw = RAW_OPEN.exec(template))) {
|
|
2250
|
+
const tag = raw[1].toLowerCase();
|
|
2251
|
+
const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
|
|
2252
|
+
const gt = closeAt < 0 ? -1 : template.indexOf('>', closeAt);
|
|
2253
|
+
const end = gt < 0 ? template.length : gt + 1;
|
|
2254
|
+
rawRanges.push([raw.index, end]);
|
|
2255
|
+
RAW_OPEN.lastIndex = end;
|
|
2256
|
+
}
|
|
2257
|
+
const COMMENT_RE = /<!--[\s\S]*?-->/g;
|
|
2258
|
+
let note: RegExpExecArray | null;
|
|
2259
|
+
while ((note = COMMENT_RE.exec(template))) rawRanges.push([note.index, note.index + note[0].length]);
|
|
2260
|
+
rawRanges.sort((a, b) => a[0] - b[0]);
|
|
2261
|
+
const inRaw = (idx: number): boolean => rawRanges.some(([s, e]) => idx >= s && idx < e);
|
|
2262
|
+
const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
|
|
2263
|
+
let m: RegExpExecArray | null;
|
|
2264
|
+
while ((m = DIRECTIVE_RE.exec(template))) {
|
|
2265
|
+
if (inRaw(m.index)) continue;
|
|
2266
|
+
const [, sigil, word] = m;
|
|
2267
|
+
if (sigil === '/' && KNOWN_CLOSERS.has(word)) continue;
|
|
2268
|
+
if (sigil === '/') {
|
|
2269
|
+
throw new RoseError(
|
|
2270
|
+
'E-TEMPLATE',
|
|
2271
|
+
`${filePath}: {/${word}} does not close anything`,
|
|
2272
|
+
{ file: filePath, line: lineAt(template, m), hint: 'the closers are {/if}, {/each} and {/boundary} - one per block you opened' },
|
|
2273
|
+
);
|
|
2274
|
+
}
|
|
2275
|
+
if (word === 'else') {
|
|
2276
|
+
throw new RoseError(
|
|
2277
|
+
'E-TEMPLATE',
|
|
2278
|
+
`${filePath}: a stray {:else} with no {#if} above it`,
|
|
2279
|
+
{ file: filePath, line: lineAt(template, m), hint: '{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}' },
|
|
2280
|
+
);
|
|
2281
|
+
}
|
|
2282
|
+
if (word === 'fallback') {
|
|
2283
|
+
throw new RoseError(
|
|
2284
|
+
'E-TEMPLATE',
|
|
2285
|
+
`${filePath}: a stray {:fallback} with no {#boundary} above it`,
|
|
2286
|
+
{ file: filePath, line: lineAt(template, m), hint: '{:fallback} belongs directly inside a {#boundary} ... {/boundary} block' },
|
|
2287
|
+
);
|
|
2288
|
+
}
|
|
2289
|
+
throw new RoseError(
|
|
2290
|
+
'E-TEMPLATE',
|
|
2291
|
+
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
2292
|
+
{ file: filePath, line: lineAt(template, m), hint: 'rosetack templates support {#if}/{:else}, {#each} and {#boundary}' },
|
|
2293
|
+
);
|
|
2294
|
+
}
|
|
2295
|
+
const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
|
|
2296
|
+
while ((m = OPENER_RE.exec(template))) {
|
|
2297
|
+
if (inRaw(m.index)) continue;
|
|
2298
|
+
const [, kind, head] = m;
|
|
2299
|
+
if (kind === 'each' && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
|
|
2300
|
+
throw new RoseError(
|
|
2301
|
+
'E-TEMPLATE',
|
|
2302
|
+
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
2303
|
+
{ 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)' },
|
|
2304
|
+
);
|
|
2305
|
+
}
|
|
2306
|
+
const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, 'g');
|
|
2307
|
+
const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, 'g');
|
|
2308
|
+
let depth = 1;
|
|
2309
|
+
let i = m.index + m[0].length;
|
|
2310
|
+
for (;;) {
|
|
2311
|
+
OPEN_RE.lastIndex = i;
|
|
2312
|
+
CLOSE_RE.lastIndex = i;
|
|
2313
|
+
const nextOpen = OPEN_RE.exec(template);
|
|
2314
|
+
const nextClose = CLOSE_RE.exec(template);
|
|
2315
|
+
if (!nextClose) break;
|
|
2316
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
2317
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
2318
|
+
continue;
|
|
2319
|
+
}
|
|
2320
|
+
i = nextClose.index + nextClose[0].length;
|
|
2321
|
+
if (--depth === 0) break;
|
|
2322
|
+
}
|
|
2323
|
+
if (depth !== 0) {
|
|
2324
|
+
throw new RoseError(
|
|
2325
|
+
'E-TEMPLATE',
|
|
2326
|
+
`${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
|
|
2327
|
+
{ file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` },
|
|
2328
|
+
);
|
|
1613
2329
|
}
|
|
1614
|
-
buf += head[i++];
|
|
1615
2330
|
}
|
|
1616
|
-
|
|
1617
|
-
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
/**
|
|
2334
|
+
* A QUOTED attribute whose value carries an expression - `class="{x}"`,
|
|
2335
|
+
* `style="color:{c};"`, `href="/p{id}"` - used to be compiled as if the value
|
|
2336
|
+
* were body text: the reactive markers landed INSIDE the attribute
|
|
2337
|
+
* (`class="<!--⟦m:0⟧-->yes<!--⟦/m:0⟧-->"`), a class list no selector matches,
|
|
2338
|
+
* and no wire pass can repair it (markers inside an attribute value are not
|
|
2339
|
+
* nodes). The real CMS writes `style="background:{p.enabled ? ...};"` on
|
|
2340
|
+
* every row, so this was not exotic. The unquoted form (`class={x}`) has
|
|
2341
|
+
* always compiled correctly through attrMark(); this pass rewrites the quoted
|
|
2342
|
+
* form into a single equivalent expression - `class={('yes')}`,
|
|
2343
|
+
* `style={('background:' + (p.enabled ? …) + ';')}` - so there is ONE
|
|
2344
|
+
* attribute path in the compiler instead of two, one of them broken.
|
|
2345
|
+
*
|
|
2346
|
+
* Component tags keep their own attribute parser (a quoted value is a string
|
|
2347
|
+
* prop there, by design), and a value holding a template literal is left
|
|
2348
|
+
* alone: rewriting it would need the literal-aware scanner the value does not
|
|
2349
|
+
* have, and the old path was no better.
|
|
2350
|
+
*/
|
|
2351
|
+
function rewriteQuotedExprAttrs(template: string, comps: Map<string, unknown>): string {
|
|
2352
|
+
const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
|
|
2353
|
+
return template.replace(TAG_RE, (tag: string, name: string, attrs: string, selfClose: string) => {
|
|
2354
|
+
if (comps.has(name) || !/\{/.test(attrs)) return tag;
|
|
2355
|
+
const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole: string, attr: string, value: string) => {
|
|
2356
|
+
if (!/\{/.test(value) || value.includes('`')) return whole;
|
|
2357
|
+
const spans = templateExprSpans(value);
|
|
2358
|
+
if (spans.length === 0) return whole;
|
|
2359
|
+
let expr = '';
|
|
2360
|
+
let last = 0;
|
|
2361
|
+
for (const s of spans) {
|
|
2362
|
+
if (last < s.start) expr += (expr ? ' + ' : '') + JSON.stringify(value.slice(last, s.start));
|
|
2363
|
+
expr += (expr ? ' + ' : '') + `(${s.expr})`;
|
|
2364
|
+
last = s.end + 1;
|
|
2365
|
+
}
|
|
2366
|
+
if (last < value.length) expr += (expr ? ' + ' : '') + JSON.stringify(value.slice(last));
|
|
2367
|
+
return `${attr}={${expr}}`;
|
|
2368
|
+
});
|
|
2369
|
+
return `<${name}${rewritten}${selfClose ? ' /' : ''}>`;
|
|
2370
|
+
});
|
|
1618
2371
|
}
|
|
1619
2372
|
|
|
1620
2373
|
function compileTemplate(
|
|
@@ -1624,39 +2377,61 @@ function compileTemplate(
|
|
|
1624
2377
|
scope: string | null,
|
|
1625
2378
|
depth: number,
|
|
1626
2379
|
markers = true,
|
|
1627
|
-
comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map()
|
|
2380
|
+
comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map(),
|
|
2381
|
+
islandDepth = 0
|
|
1628
2382
|
): string {
|
|
1629
2383
|
let result = '';
|
|
1630
2384
|
let remaining = template;
|
|
1631
2385
|
let blockId = 0;
|
|
1632
2386
|
|
|
2387
|
+
const islandsMode = /\{#island\b/.test(template);
|
|
2388
|
+
const effMarkers = markers && (!islandsMode || islandDepth > 0);
|
|
2389
|
+
|
|
1633
2390
|
const nextId = () => `${depth}_${blockId++}`;
|
|
1634
2391
|
|
|
1635
2392
|
while (remaining.length > 0) {
|
|
1636
|
-
// nesting-aware: an inner block's close tag must not end its parent
|
|
1637
2393
|
const ifMatch = findBlock(remaining, 'if');
|
|
1638
2394
|
const eachMatch = findBlock(remaining, 'each');
|
|
1639
2395
|
const boundaryMatch = findBlock(remaining, 'boundary');
|
|
1640
|
-
// The first top-level expression, found with the literal-aware scanner
|
|
1641
|
-
// (templateExprSpans) rather than a flat `[^{}]+` regex …
|
|
1642
2396
|
const firstExpr = templateExprSpans(remaining)[0];
|
|
1643
|
-
// The same RegExpExecArray shape findBlock returns (an array plus `index`),
|
|
1644
|
-
// so every call site below reads it exactly as it read the old regex match.
|
|
1645
2397
|
const exprMatch = firstExpr
|
|
1646
2398
|
? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) as unknown as RegExpExecArray
|
|
1647
2399
|
: null;
|
|
1648
2400
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
2401
|
+
const islandMatch = findBlock(remaining, 'island');
|
|
1649
2402
|
|
|
1650
2403
|
const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
|
|
1651
2404
|
if (ifMatch?.index !== undefined) candidates.push({ type: 'if', match: ifMatch, index: ifMatch.index });
|
|
1652
2405
|
if (eachMatch?.index !== undefined) candidates.push({ type: 'each', match: eachMatch, index: eachMatch.index });
|
|
1653
2406
|
if (boundaryMatch?.index !== undefined) candidates.push({ type: 'boundary', match: boundaryMatch, index: boundaryMatch.index });
|
|
2407
|
+
if (islandMatch?.index !== undefined) candidates.push({ type: 'island', match: islandMatch, index: islandMatch.index });
|
|
1654
2408
|
if (exprMatch?.index !== undefined) candidates.push({ type: 'expr', match: exprMatch, index: exprMatch.index });
|
|
1655
2409
|
if (compTag) candidates.push({ type: 'comp', match: exprMatch!, index: compTag.start, tag: compTag });
|
|
1656
2410
|
const earliest = candidates.length > 0
|
|
1657
2411
|
? candidates.reduce((a, b) => (a.index <= b.index ? a : b))
|
|
1658
2412
|
: null;
|
|
1659
2413
|
|
|
2414
|
+
const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
|
|
2415
|
+
const rawHit = rawOpenRe.exec(remaining);
|
|
2416
|
+
if (rawHit && earliest && rawHit.index < earliest.index) {
|
|
2417
|
+
const tag = rawHit[1].toLowerCase();
|
|
2418
|
+
const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
|
|
2419
|
+
const gt = closeAt < 0 ? -1 : remaining.indexOf('>', closeAt);
|
|
2420
|
+
const end = gt < 0 ? remaining.length : gt + 1;
|
|
2421
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
2422
|
+
remaining = remaining.substring(end);
|
|
2423
|
+
continue;
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
const noteAt = remaining.indexOf('<!--');
|
|
2427
|
+
if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
|
|
2428
|
+
const noteEnd = remaining.indexOf('-->', noteAt + 4);
|
|
2429
|
+
const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
|
|
2430
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
2431
|
+
remaining = remaining.substring(end);
|
|
2432
|
+
continue;
|
|
2433
|
+
}
|
|
2434
|
+
|
|
1660
2435
|
if (!earliest) {
|
|
1661
2436
|
result += emitChunk(remaining, acc, closes, scope);
|
|
1662
2437
|
break;
|
|
@@ -1669,60 +2444,69 @@ function compileTemplate(
|
|
|
1669
2444
|
const call = autoCall(cond);
|
|
1670
2445
|
const id = nextId();
|
|
1671
2446
|
const innerScope = scope ?? '__s';
|
|
1672
|
-
|
|
1673
|
-
// adopted/cloned block never re-touches the parent's markers.
|
|
1674
|
-
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, markers, comps);
|
|
2447
|
+
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, effMarkers, comps, islandDepth);
|
|
1675
2448
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
|
|
1676
|
-
if (
|
|
1677
|
-
// The content renders the FIRST time the block shows, never before - see the
|
|
1678
|
-
// runtime's ifMark for why the eager version crashed `{#if
|
|
1679
|
-
// user()}{user().name}{/if}`.
|
|
2449
|
+
if (effMarkers) {
|
|
1680
2450
|
result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ''});\n`;
|
|
1681
2451
|
} else {
|
|
1682
2452
|
result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
|
|
1683
2453
|
}
|
|
1684
2454
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1685
2455
|
} else if (earliest.type === 'each') {
|
|
1686
|
-
const [, items, item, content] = earliest.match;
|
|
2456
|
+
const [, items, item, index, content] = earliest.match;
|
|
1687
2457
|
const before = remaining.substring(0, earliest.index);
|
|
1688
2458
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1689
2459
|
const call = autoCall(items);
|
|
1690
2460
|
const id = nextId();
|
|
1691
|
-
|
|
1692
|
-
const itemRe = new RegExp(`\\b${item}\\b`, 'g');
|
|
2461
|
+
const isDestructure = /^[{[]/.test(item);
|
|
2462
|
+
const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, 'g');
|
|
2463
|
+
const indexRe = index ? new RegExp(`\\b${index}\\b`, 'g') : null;
|
|
1693
2464
|
let scoped = '';
|
|
1694
2465
|
let lastSpan = 0;
|
|
1695
2466
|
for (const s of templateExprSpans(content.trim())) {
|
|
1696
|
-
|
|
2467
|
+
let expr = itemRe ? s.expr.replace(itemRe, '__s') : s.expr;
|
|
2468
|
+
if (indexRe) expr = expr.replace(indexRe, '__i');
|
|
2469
|
+
scoped += content.trim().slice(lastSpan, s.start) + '{' + expr + '}';
|
|
1697
2470
|
lastSpan = s.end + 1;
|
|
1698
2471
|
}
|
|
1699
2472
|
scoped += content.trim().slice(lastSpan);
|
|
1700
|
-
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1,
|
|
1701
|
-
|
|
1702
|
-
|
|
2473
|
+
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth);
|
|
2474
|
+
const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
|
|
2475
|
+
result += `const __b${id} = (__s, __c${index ? ', __i' : ''}) => { let h = ''; ${body} return h; };\n`;
|
|
2476
|
+
if (effMarkers) {
|
|
1703
2477
|
result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});\n`;
|
|
1704
2478
|
} else {
|
|
1705
|
-
|
|
2479
|
+
const param = isDestructure ? '__s' : item;
|
|
2480
|
+
result += `${acc} += (${call}).map((${param}${index ? ', __i' : ''}) => __b${id}(${param}, []${index ? ', __i' : ''}))).join('');\n`;
|
|
1706
2481
|
}
|
|
1707
2482
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1708
2483
|
} else if (earliest.type === 'boundary') {
|
|
1709
|
-
const [, content] = earliest.match;
|
|
2484
|
+
const [, fbAttr, content] = earliest.match;
|
|
2485
|
+
let fallbackSrc = '';
|
|
2486
|
+
if (fbAttr) {
|
|
2487
|
+
const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
|
|
2488
|
+
if (fbM) fallbackSrc = Buffer.from(fbM[1], 'base64').toString('utf-8');
|
|
2489
|
+
}
|
|
2490
|
+
const custom = content;
|
|
1710
2491
|
const before = remaining.substring(0, earliest.index);
|
|
1711
2492
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1712
2493
|
const id = nextId();
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
const catchesAction = /\$action:|<form[\s>]/.test(content);
|
|
1716
|
-
const inner = compileTemplate(content.trim(), 'h', closes, scope, depth + 1, markers, comps);
|
|
2494
|
+
const catchesAction = /\$action:|<form[\s>]/.test(custom);
|
|
2495
|
+
const inner = compileTemplate(custom.trim(), 'h', closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
1717
2496
|
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
|
|
2497
|
+
let fbBlock = '';
|
|
2498
|
+
if (fallbackSrc.trim()) {
|
|
2499
|
+
const fbInner = compileTemplate(fallbackSrc.trim(), 'h', closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
2500
|
+
fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };\n`;
|
|
2501
|
+
}
|
|
2502
|
+
result += fbBlock;
|
|
1718
2503
|
result += `let __bd${id} = '';\n`;
|
|
1719
2504
|
result += catchesAction
|
|
1720
|
-
? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }\n`
|
|
1721
|
-
: `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
|
|
2505
|
+
? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : '$boundaryFallback(e)'}; }\n`
|
|
2506
|
+
: `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
|
|
1722
2507
|
result += `${acc} += __bd${id};\n`;
|
|
1723
2508
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1724
2509
|
} else if (earliest.type === 'comp') {
|
|
1725
|
-
// <Card prop={x}>...</Card> -> Card(closes, children, props, slots).
|
|
1726
2510
|
const tag = earliest.tag!;
|
|
1727
2511
|
if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
|
|
1728
2512
|
const entry = comps.get(tag.name)!;
|
|
@@ -1738,14 +2522,10 @@ function compileTemplate(
|
|
|
1738
2522
|
rest = remaining.substring(closeIdx + tag.name.length + 3);
|
|
1739
2523
|
}
|
|
1740
2524
|
const { def, named } = splitSlots(childrenSrc);
|
|
1741
|
-
// Default children render at CALL time with the enclosing scope (inside an {#each}
|
|
1742
|
-
// that scope is the item), exactly like a layout's children.
|
|
1743
2525
|
const hasChildren = def.trim().length > 0;
|
|
1744
2526
|
if (hasChildren) {
|
|
1745
|
-
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1,
|
|
2527
|
+
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1, effMarkers, comps, islandDepth)} return h; };\n`;
|
|
1746
2528
|
}
|
|
1747
|
-
// Named slots are functions of the object the child passes in AND of a marker array
|
|
1748
|
-
// of their own: their content is a block scoped to that object (see SLOT_HELPER) …
|
|
1749
2529
|
const slotFns = named.map(([nm, src]) => {
|
|
1750
2530
|
const decl = entry.slots.find((s) => s.name === nm);
|
|
1751
2531
|
let content = src;
|
|
@@ -1759,52 +2539,69 @@ function compileTemplate(
|
|
|
1759
2539
|
}
|
|
1760
2540
|
content = out + content.slice(lastSpan);
|
|
1761
2541
|
}
|
|
1762
|
-
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1,
|
|
2542
|
+
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth)} return h; }`;
|
|
1763
2543
|
});
|
|
1764
2544
|
const propsObj = parseCompAttrs(tag.attrs)
|
|
1765
2545
|
.filter((a) => a.name !== 'slot')
|
|
1766
2546
|
.map((a) => {
|
|
1767
|
-
|
|
1768
|
-
// and calls it - no extra machinery, a prop is a function like any other value.
|
|
2547
|
+
if (a.kind === 'spread') return `...(${a.value})`;
|
|
1769
2548
|
const key = a.name.startsWith('on:') ? `on${capitalize(a.name.slice(3))}` : a.name;
|
|
1770
2549
|
const val = a.kind === 'expr' ? `(${a.value})` : a.kind === 'str' ? JSON.stringify(a.value) : 'true';
|
|
1771
2550
|
return `${JSON.stringify(key)}: ${val}`;
|
|
1772
2551
|
})
|
|
1773
2552
|
.join(', ');
|
|
1774
|
-
// The imported binding IS the child's render function (a default `import Card from
|
|
1775
|
-
// '...rose'` compiles to `import { render as Card }`), so the call is direct …
|
|
1776
2553
|
const childrenArg = hasChildren ? `__ch${id}(${scope ?? 'undefined'}, ${closes})` : `''`;
|
|
1777
2554
|
result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(', ')} });\n`;
|
|
1778
2555
|
remaining = rest;
|
|
2556
|
+
} else if (earliest.type === 'island') {
|
|
2557
|
+
const [, name, hydrate, content] = earliest.match;
|
|
2558
|
+
const before = remaining.substring(0, earliest.index);
|
|
2559
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2560
|
+
const hydrateAttr = hydrate === 'visible' || hydrate === 'idle'
|
|
2561
|
+
? ` data-rv-island-hydrate="${hydrate}"`
|
|
2562
|
+
: '';
|
|
2563
|
+
result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ''}"${hydrateAttr}>`)};\n`;
|
|
2564
|
+
const inner = compileTemplate(content.trim(), 'h', '__c', scope, depth + 1, markers, comps, islandDepth + 1);
|
|
2565
|
+
result += inner;
|
|
2566
|
+
result += `${acc} += '</div>';\n`;
|
|
2567
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1779
2568
|
} else {
|
|
1780
2569
|
const [, expr] = earliest.match;
|
|
1781
2570
|
const trimmed = expr.trim();
|
|
1782
2571
|
const before = remaining.substring(0, earliest.index);
|
|
2572
|
+
const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
|
|
2573
|
+
if (constMatch) {
|
|
2574
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2575
|
+
result += `const ${constMatch[1]} = (${constMatch[2].trim()});\n`;
|
|
2576
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2577
|
+
continue;
|
|
2578
|
+
}
|
|
1783
2579
|
if (trimmed === '__slot__') {
|
|
1784
2580
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1785
2581
|
result += compileSlot(acc);
|
|
1786
2582
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1787
2583
|
continue;
|
|
1788
2584
|
}
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
2585
|
+
const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
|
|
2586
|
+
if (slotDefault) {
|
|
2587
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2588
|
+
result += `${acc} += __slotDefault(children, ${slotDefault[1]});\n`;
|
|
2589
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2590
|
+
continue;
|
|
2591
|
+
}
|
|
2592
|
+
const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
|
|
1792
2593
|
if (slotCall) {
|
|
1793
2594
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]);\n`;
|
|
2595
|
+
const fb = slotCall[4] ? `, ${slotCall[4]}` : '';
|
|
2596
|
+
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});\n`;
|
|
1797
2597
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1798
2598
|
continue;
|
|
1799
2599
|
}
|
|
1800
|
-
// P1-2 (bug report): {@html expr} is the explicit reverse of esc() - trusted HTML,
|
|
1801
|
-
// emitted verbatim.
|
|
1802
2600
|
const rawMatch = /^@html\s+([\s\S]+)$/.exec(trimmed);
|
|
1803
2601
|
if (rawMatch) {
|
|
1804
2602
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1805
2603
|
const expr = rawMatch[1].trim();
|
|
1806
|
-
if (!
|
|
1807
|
-
// head block: the value is markup, so it is concatenated raw
|
|
2604
|
+
if (!effMarkers) {
|
|
1808
2605
|
result += `${acc} += String(${expr} ?? '');\n`;
|
|
1809
2606
|
} else {
|
|
1810
2607
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
@@ -1813,19 +2610,16 @@ function compileTemplate(
|
|
|
1813
2610
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1814
2611
|
continue;
|
|
1815
2612
|
}
|
|
1816
|
-
// attr={expr} -> reactive attribute; otherwise a text marker
|
|
1817
2613
|
const attrMatch = before.match(/([\w-]+)=\s*$/);
|
|
1818
2614
|
if (attrMatch) {
|
|
1819
2615
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
1820
2616
|
if (lit) result += emitChunk(lit, acc, closes, scope);
|
|
1821
|
-
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope,
|
|
2617
|
+
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
|
|
1822
2618
|
} else {
|
|
1823
2619
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1824
|
-
// A marker whose value is followed by LITERAL TEXT needs an end marker: the wire
|
|
1825
|
-
// patches the text node after the start marker …
|
|
1826
2620
|
const after = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1827
2621
|
const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith('{');
|
|
1828
|
-
result += emitText(trimmed, acc, closes, scope,
|
|
2622
|
+
result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
|
|
1829
2623
|
}
|
|
1830
2624
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1831
2625
|
}
|
|
@@ -1846,11 +2640,7 @@ interface CompTag {
|
|
|
1846
2640
|
selfClosing: boolean;
|
|
1847
2641
|
}
|
|
1848
2642
|
|
|
1849
|
-
|
|
1850
|
-
* Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside
|
|
1851
|
-
* an attribute expression (`title={a > b}`) does not end the tag. Returns the
|
|
1852
|
-
* index just past `>`, or -1 when the tag is never closed.
|
|
1853
|
-
*/
|
|
2643
|
+
// Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside an attribute expression (`title={a > b}`) does not end the tag.
|
|
1854
2644
|
function scanTagEnd(src: string, start: number): number {
|
|
1855
2645
|
let j = start + 1;
|
|
1856
2646
|
let quote = '';
|
|
@@ -1905,13 +2695,19 @@ function findClose(src: string, from: number, name: string): number {
|
|
|
1905
2695
|
return -1;
|
|
1906
2696
|
}
|
|
1907
2697
|
|
|
1908
|
-
interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool'; value: string }
|
|
2698
|
+
interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool' | 'spread'; value: string }
|
|
1909
2699
|
|
|
1910
2700
|
/** Parse a component tag's attributes into prop={expr} / prop="lit" / bool. */
|
|
1911
2701
|
function parseCompAttrs(attrs: string): CompAttr[] {
|
|
1912
2702
|
const out: CompAttr[] = [];
|
|
1913
2703
|
let i = 0;
|
|
1914
2704
|
while (i < attrs.length) {
|
|
2705
|
+
const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
|
|
2706
|
+
if (spread) {
|
|
2707
|
+
out.push({ name: '...', kind: 'spread', value: spread[1].trim() });
|
|
2708
|
+
i += spread[0].length;
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
1915
2711
|
const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
|
|
1916
2712
|
if (!nm) break;
|
|
1917
2713
|
i += nm[0].length;
|
|
@@ -2032,8 +2828,6 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
|
|
|
2032
2828
|
if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
|
|
2033
2829
|
const tail = `</${nm[2]}>`;
|
|
2034
2830
|
const inner = src.slice(end, closeIdx);
|
|
2035
|
-
// The same rule one level down: a slot= INSIDE a named slot's
|
|
2036
|
-
// content is nested too, and the child would silently never call it.
|
|
2037
2831
|
rejectNestedSlot(inner, slotName);
|
|
2038
2832
|
named.set(slotName, (named.get(slotName) ?? '') + stripped + inner + tail);
|
|
2039
2833
|
elemDepth = Math.max(0, elemDepth - 1);
|
|
@@ -2055,9 +2849,6 @@ function emitChunk(text: string, acc: string, closes: string, scope: string | nu
|
|
|
2055
2849
|
return `${acc} += ${JSON.stringify(text)};\n`;
|
|
2056
2850
|
}
|
|
2057
2851
|
|
|
2058
|
-
// --- Build-time image inlining ------------------------------------------- One fewer
|
|
2059
|
-
// request per small local image: <img src="/logo.svg"> ships as a data URI inside the …
|
|
2060
|
-
|
|
2061
2852
|
const IMG_RE = /<img\b(?:[^<>]|\{[^{}]*\})*>/g;
|
|
2062
2853
|
const IMG_MIME: Record<string, string> = {
|
|
2063
2854
|
'.png': 'image/png',
|
|
@@ -2068,28 +2859,72 @@ const IMG_MIME: Record<string, string> = {
|
|
|
2068
2859
|
'.svg': 'image/svg+xml',
|
|
2069
2860
|
'.ico': 'image/x-icon',
|
|
2070
2861
|
};
|
|
2071
|
-
// Trade-off: fixed 4 KB cap; make it configurable when a real app cares
|
|
2072
2862
|
const INLINE_IMG_MAX = 4096;
|
|
2073
2863
|
|
|
2864
|
+
import { readImageSize } from "../cli/image-size";
|
|
2865
|
+
import { scanContentDir, renderMarkdown, buildRss } from "../cli/content";
|
|
2866
|
+
|
|
2867
|
+
/**
|
|
2868
|
+
* A4 (responsive variants): the sibling `name.wNNN.ext` files of a local
|
|
2869
|
+
* image (e.g. `hero.jpg` with `hero.w400.jpg` / `hero.w800.jpg` next to it
|
|
2870
|
+
* in public/) become a sorted srcset on the URL-kept <img>. Zero-dependency
|
|
2871
|
+
* by design - the variants themselves are plain files, generated by whatever
|
|
2872
|
+
* resizer the app prefers (oboext ships tools/make-variants.mjs). Author-set
|
|
2873
|
+
* srcset/sizes always win; no variants means no attribute, byte-identical.
|
|
2874
|
+
*/
|
|
2875
|
+
function listImageVariants(publicDir: string, url: string): Array<{ url: string; width: number }> {
|
|
2876
|
+
const ext = path.extname(url);
|
|
2877
|
+
const base = path.basename(url, ext);
|
|
2878
|
+
const dirUrl = url.slice(0, url.length - (base + ext).length);
|
|
2879
|
+
let entries: string[];
|
|
2880
|
+
try {
|
|
2881
|
+
entries = fs.readdirSync(path.join(publicDir, path.dirname(url)));
|
|
2882
|
+
} catch {
|
|
2883
|
+
return [];
|
|
2884
|
+
}
|
|
2885
|
+
const re = new RegExp(
|
|
2886
|
+
'^' + base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\.w(\\d+)' + ext.replace('.', '\\.') + '$',
|
|
2887
|
+
'i',
|
|
2888
|
+
);
|
|
2889
|
+
const out: Array<{ url: string; width: number }> = [];
|
|
2890
|
+
for (const e of entries) {
|
|
2891
|
+
const m = re.exec(e);
|
|
2892
|
+
const width = m ? Number(m[1]) : 0;
|
|
2893
|
+
if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
|
|
2894
|
+
}
|
|
2895
|
+
return out.sort((a, b) => a.width - b.width);
|
|
2896
|
+
}
|
|
2897
|
+
|
|
2074
2898
|
function inlineImages(template: string, publicDir: string): string {
|
|
2075
2899
|
return template.replace(IMG_RE, (tag) => {
|
|
2076
|
-
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
2077
|
-
if (!src) return tag;
|
|
2900
|
+
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
2901
|
+
if (!src) return tag;
|
|
2078
2902
|
const ext = path.extname(src[1]).toLowerCase();
|
|
2079
2903
|
const mime = IMG_MIME[ext];
|
|
2080
2904
|
if (!mime) return tag;
|
|
2905
|
+
const rel = src[1].replace(/^\/public(?=\/)/, '');
|
|
2906
|
+
const filePath = path.join(publicDir, rel);
|
|
2081
2907
|
let file: Buffer;
|
|
2082
2908
|
try {
|
|
2083
|
-
file = fs.readFileSync(
|
|
2909
|
+
file = fs.readFileSync(filePath);
|
|
2084
2910
|
} catch {
|
|
2085
|
-
return tag;
|
|
2911
|
+
return tag;
|
|
2912
|
+
}
|
|
2913
|
+
const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
|
|
2914
|
+
const dims = authorDims ? null : readImageSize(filePath);
|
|
2915
|
+
const withDims = (t: string): string =>
|
|
2916
|
+
dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
|
|
2917
|
+
if (file.length > INLINE_IMG_MAX) {
|
|
2918
|
+
const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
|
|
2919
|
+
const variants = hasSS ? [] : listImageVariants(publicDir, rel);
|
|
2920
|
+
if (!variants.length) return withDims(tag);
|
|
2921
|
+
const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(', ');
|
|
2922
|
+
return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
|
|
2086
2923
|
}
|
|
2087
|
-
if (file.length > INLINE_IMG_MAX) return tag;
|
|
2088
|
-
// SVG inlines as text (percent-encoded for #, ", %); binaries as base64
|
|
2089
2924
|
const uri = ext === '.svg'
|
|
2090
2925
|
? `data:image/svg+xml,${file.toString('utf-8').replace(/%/g, '%25').replace(/#/g, '%23').replace(/\{/g, '%7B').replace(/\}/g, '%7D').replace(/"/g, '%22')}`
|
|
2091
2926
|
: `data:${mime};base64,${file.toString('base64')}`;
|
|
2092
|
-
return tag.replace(src[0], `src="${uri}"`);
|
|
2927
|
+
return withDims(tag.replace(src[0], `src="${uri}"`));
|
|
2093
2928
|
});
|
|
2094
2929
|
}
|
|
2095
2930
|
|
|
@@ -2101,7 +2936,6 @@ function inlineImages(template: string, publicDir: string): string {
|
|
|
2101
2936
|
*/
|
|
2102
2937
|
function emitText(expr: string, acc: string, closes: string, scope: string | null, markers = true, pair = false): string {
|
|
2103
2938
|
if (!markers) {
|
|
2104
|
-
// head block: inline escaped value, no marker comment (clean SSR html)
|
|
2105
2939
|
return `${acc} += esc(${expr});\n`;
|
|
2106
2940
|
}
|
|
2107
2941
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
@@ -2111,12 +2945,17 @@ function emitText(expr: string, acc: string, closes: string, scope: string | nul
|
|
|
2111
2945
|
}
|
|
2112
2946
|
|
|
2113
2947
|
/** Emit a reactive attribute through the runtime's attrMark(). */
|
|
2948
|
+
const BOOLEAN_ATTRS = new Set(['checked', 'disabled', 'readonly', 'required', 'selected', 'multiple', 'autofocus', 'open']);
|
|
2949
|
+
|
|
2114
2950
|
function emitAttr(attr: string, expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
|
|
2115
2951
|
if (!markers) {
|
|
2116
2952
|
return `${acc} += '${attr}="' + esc(${expr}) + '"';\n`;
|
|
2117
2953
|
}
|
|
2118
2954
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
2119
2955
|
const arg = scope ? `, ${scope}` : '';
|
|
2956
|
+
if (BOOLEAN_ATTRS.has(attr)) {
|
|
2957
|
+
return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
|
|
2958
|
+
}
|
|
2120
2959
|
return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
|
|
2121
2960
|
}
|
|
2122
2961
|
|
|
@@ -2128,9 +2967,14 @@ function compileSlot(acc: string): string {
|
|
|
2128
2967
|
return `${acc} += String(children);\n`;
|
|
2129
2968
|
}
|
|
2130
2969
|
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
const
|
|
2970
|
+
const RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
|
|
2971
|
+
|
|
2972
|
+
const API_RUNTIME_HELPERS = RUNTIME_IMPORTS
|
|
2973
|
+
.replace(/^import\s*\{/, '')
|
|
2974
|
+
.replace(/\}\s*from[\s\S]*$/, '')
|
|
2975
|
+
.split(',')
|
|
2976
|
+
.map((s) => s.trim())
|
|
2977
|
+
.filter(Boolean);
|
|
2134
2978
|
|
|
2135
2979
|
/**
|
|
2136
2980
|
* `export let title = 'x'` -> a per-invocation const read from the
|
|
@@ -2145,8 +2989,6 @@ function propsCode(props: Array<{ name: string; def: string | null }>): string {
|
|
|
2145
2989
|
.join('\n');
|
|
2146
2990
|
}
|
|
2147
2991
|
|
|
2148
|
-
// The named-slot helpers, identical in both bundles . __slot resolves the parent's slot
|
|
2149
|
-
// function and builds the object its <slot name item={...}> declared …
|
|
2150
2992
|
const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
2151
2993
|
const fn = sl[name];
|
|
2152
2994
|
if (typeof fn !== 'function') return null;
|
|
@@ -2154,31 +2996,25 @@ const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
2154
2996
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
2155
2997
|
return { o, fn };
|
|
2156
2998
|
};
|
|
2157
|
-
const __slotBlock = (closes, sl, name, pairs) => {
|
|
2999
|
+
const __slotBlock = (closes, sl, name, pairs, fallback) => {
|
|
2158
3000
|
const hit = __slot(sl, name, pairs);
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
return
|
|
3001
|
+
if (hit) return slotBlockMark(closes, hit);
|
|
3002
|
+
return fallback || '';
|
|
3003
|
+
};
|
|
3004
|
+
const __slotDefault = (children, fallback) => {
|
|
3005
|
+
const c = children == null ? '' : String(children);
|
|
3006
|
+
if (c.trim()) return c;
|
|
3007
|
+
return fallback || '';
|
|
2166
3008
|
};`;
|
|
2167
3009
|
|
|
2168
3010
|
function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = '', props: Array<{ name: string; def: string | null }> = [], namedSlots = false, imports = '', isComponent = false, guard = '', hasActions = false, dataDeclsCode = ''): string {
|
|
2169
|
-
// The head block renders to a clean html string (no markers) and is wrapped in an h
|
|
2170
|
-
// marker pair: renderPage extracts it for <head> injection …
|
|
2171
3011
|
const headCode = headFn
|
|
2172
3012
|
? `
|
|
2173
3013
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
2174
3014
|
__html += headMark(closes, __head);`
|
|
2175
3015
|
: '';
|
|
2176
|
-
// A page's actions live at MODULE scope (the server entry imports them and dispatches by
|
|
2177
|
-
// name), where render()'s per-state setters do not exist …
|
|
2178
3016
|
const actionState = hasActions ? `
|
|
2179
3017
|
const $setState = (key, value) => setState(key, value);` : '';
|
|
2180
|
-
// A page's render is async ($data awaits); a component's is not - its parent calls it
|
|
2181
|
-
// inside a string concatenation (`h += Card(...)`) …
|
|
2182
3018
|
return `
|
|
2183
3019
|
${RUNTIME_IMPORTS}
|
|
2184
3020
|
|
|
@@ -2197,9 +3033,7 @@ export ${isComponent ? 'function' : 'async function'} render(closes, children, _
|
|
|
2197
3033
|
${script}
|
|
2198
3034
|
${stateDeclsCode}
|
|
2199
3035
|
${dataDeclsCode}
|
|
2200
|
-
|
|
2201
|
-
// applied to the state the declarations above just established (a no-op on
|
|
2202
|
-
// every path that is not a server action's re-render - see the runtime).
|
|
3036
|
+
|
|
2203
3037
|
${isComponent ? '' : 'applyStateDeltas();'}
|
|
2204
3038
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
2205
3039
|
let __html = ${isComponent ? '' : 'await '}__root(closes, children);${headCode}
|
|
@@ -2221,11 +3055,12 @@ function generateClient(
|
|
|
2221
3055
|
isComponent = false,
|
|
2222
3056
|
dataDeclsCode = ''
|
|
2223
3057
|
): string {
|
|
2224
|
-
// Handlers live on a shared global (the runtime's `handlers` registry) so one delegated
|
|
2225
|
-
// listener per event type can dispatch for any component, including freshly cloned nodes.
|
|
2226
3058
|
const handlerRegistry = eventBindings.length > 0
|
|
2227
3059
|
? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(', ')} });`
|
|
2228
3060
|
: '';
|
|
3061
|
+
const clientSetState = eventBindings.length > 0
|
|
3062
|
+
? `const $setState = (key, value) => setState(key, value);`
|
|
3063
|
+
: '';
|
|
2229
3064
|
const headCode = headFn
|
|
2230
3065
|
? `
|
|
2231
3066
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
@@ -2238,7 +3073,7 @@ ${RUNTIME_IMPORTS}
|
|
|
2238
3073
|
${imports}
|
|
2239
3074
|
|
|
2240
3075
|
${exports}
|
|
2241
|
-
|
|
3076
|
+
${clientSetState ? `\n${clientSetState}\n` : ''}
|
|
2242
3077
|
${namedSlots ? SLOT_HELPER : ''}
|
|
2243
3078
|
|
|
2244
3079
|
export ${isComponent ? 'function' : 'async function'} render(closes, children, __props, __slots) {
|
|
@@ -2263,7 +3098,7 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
|
|
|
2263
3098
|
infos
|
|
2264
3099
|
.map((li, i) => ({ li, i }))
|
|
2265
3100
|
.filter(({ li }) => li.isLayout && isAncestorDir(li.filePath, infos[idx].filePath))
|
|
2266
|
-
.sort((a, b) => b.li.filePath.length - a.li.filePath.length)
|
|
3101
|
+
.sort((a, b) => b.li.filePath.length - a.li.filePath.length)
|
|
2267
3102
|
.map(({ i }) => i);
|
|
2268
3103
|
|
|
2269
3104
|
/**
|
|
@@ -2274,11 +3109,12 @@ const layoutsOf = (infos: RouteInfo[], idx: number): number[] =>
|
|
|
2274
3109
|
const routeShipsNoJs = (infos: RouteInfo[], compiled: CompileResult[], i: number): boolean => {
|
|
2275
3110
|
if (compiled[i].csr === true) return false;
|
|
2276
3111
|
if (compiled[i].needsClient) return false;
|
|
2277
|
-
// a layout needing the client bundles every document under it: its
|
|
2278
|
-
// handlers would be dead code in a runtime-less document
|
|
2279
3112
|
return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
|
|
2280
3113
|
};
|
|
2281
3114
|
|
|
3115
|
+
const routeShellOff = (infos: RouteInfo[], compiled: CompileResult[], i: number): boolean =>
|
|
3116
|
+
compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
|
|
3117
|
+
|
|
2282
3118
|
/**
|
|
2283
3119
|
* The build's zero-JS lint report: one line per route with
|
|
2284
3120
|
* its verdict and the exact reason - which component in the chain needs the
|
|
@@ -2302,11 +3138,72 @@ export function buildReport(infos: RouteInfo[], compiled: CompileResult[]): stri
|
|
|
2302
3138
|
});
|
|
2303
3139
|
}
|
|
2304
3140
|
|
|
3141
|
+
/**
|
|
3142
|
+
* The mount entry - the migration door. A foreign
|
|
3143
|
+
* page (the legacy half of a micro-frontend, or an old app adopting rosetack
|
|
3144
|
+
* one route at a time) marks containers and includes this one file:
|
|
3145
|
+
*
|
|
3146
|
+
* <div data-rosetack="/checkout"></div>
|
|
3147
|
+
* <script type="module" src="/mount.js"></script>
|
|
3148
|
+
*
|
|
3149
|
+
* Each container fetches its route's own document - the same one-request,
|
|
3150
|
+
* zero-hydration shape a standalone page gets - adopts the server's DOM in
|
|
3151
|
+
* place, and navigates inside itself: the host page keeps its URL, its
|
|
3152
|
+
* history, its <head> and every node outside the container. It imports the
|
|
3153
|
+
* same /client.js the documents use (mode B's entry, or the inline build's
|
|
3154
|
+
* bundle), so there is no second runtime and no hydration.
|
|
3155
|
+
*
|
|
3156
|
+
* Written verbatim, not minified: it ships once per app (not once per
|
|
3157
|
+
* document) and the servers compress it like any other asset. The cost to a
|
|
3158
|
+
* normal rosetack document is zero bytes - nothing references it unless the
|
|
3159
|
+
* host page does.
|
|
3160
|
+
*/
|
|
3161
|
+
const MOUNT_ENTRY = `
|
|
3162
|
+
import { start, postForm } from '/client.js';
|
|
3163
|
+
|
|
3164
|
+
for (const el of document.querySelectorAll('[data-rosetack]')) {
|
|
3165
|
+
const route = el.getAttribute('data-rosetack');
|
|
3166
|
+
const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
|
|
3167
|
+
const parsed = new DOMParser().parseFromString(doc, 'text/html');
|
|
3168
|
+
// A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
|
|
3169
|
+
const app = parsed.getElementById('app');
|
|
3170
|
+
if (app) {
|
|
3171
|
+
el.innerHTML = app.innerHTML;
|
|
3172
|
+
} else {
|
|
3173
|
+
for (const node of Array.from(parsed.body.children)) {
|
|
3174
|
+
if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
|
|
3175
|
+
}
|
|
3176
|
+
}
|
|
3177
|
+
// start() resumes from #__rosetack_state (zero hydration), so the state
|
|
3178
|
+
|
|
3179
|
+
const state = parsed.getElementById('__rosetack_state');
|
|
3180
|
+
if (state) el.appendChild(state);
|
|
3181
|
+
|
|
3182
|
+
const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
|
|
3183
|
+
await start(el, route, rendered === route);
|
|
3184
|
+
if (state) state.remove();
|
|
3185
|
+
|
|
3186
|
+
el.addEventListener('click', (e) => {
|
|
3187
|
+
const a = e.target.closest && e.target.closest('a[href^="/"]');
|
|
3188
|
+
if (!a || !el.contains(a)) return;
|
|
3189
|
+
e.preventDefault();
|
|
3190
|
+
el.setAttribute('data-rosetack', a.getAttribute('href'));
|
|
3191
|
+
start(el, a.getAttribute('href'), false);
|
|
3192
|
+
});
|
|
3193
|
+
// Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
|
|
3194
|
+
el.addEventListener('submit', (e) => {
|
|
3195
|
+
const f = e.target;
|
|
3196
|
+
if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
|
|
3197
|
+
if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
|
|
3198
|
+
e.preventDefault();
|
|
3199
|
+
postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
|
|
3200
|
+
});
|
|
3201
|
+
}
|
|
3202
|
+
`;
|
|
3203
|
+
|
|
2305
3204
|
export async function buildProject(root: string, outDir: string): Promise<{ routes: RouteInfo[]; bundle: string }> {
|
|
2306
3205
|
await fs.promises.mkdir(outDir, { recursive: true });
|
|
2307
3206
|
|
|
2308
|
-
// stale intermediates from an older build layout must not survive into the
|
|
2309
|
-
// deploy dir (they used to live directly in outDir)
|
|
2310
3207
|
const stale = (await fs.promises.readdir(outDir)).filter((f) =>
|
|
2311
3208
|
/^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
2312
3209
|
await Promise.all(stale.map((f) => fs.promises.rm(path.join(outDir, f), { force: true })));
|
|
@@ -2314,8 +3211,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2314
3211
|
const pageFiles = await scanRoseFiles(root);
|
|
2315
3212
|
const compFiles = await scanComponentFiles(root);
|
|
2316
3213
|
const files = [...pageFiles, ...compFiles];
|
|
2317
|
-
// A build that silently produces nothing is the worst possible failure mode (an empty
|
|
2318
|
-
// dist/ deploys as a blank site).
|
|
2319
3214
|
if (pageFiles.length === 0) {
|
|
2320
3215
|
throw new RoseError(
|
|
2321
3216
|
'E-ROUTE',
|
|
@@ -2324,17 +3219,12 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2324
3219
|
);
|
|
2325
3220
|
}
|
|
2326
3221
|
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
2327
|
-
// rosetack.config.js: the plugins and the i18n options , loaded fresh per build so the dev
|
|
2328
|
-
// server's hot rebuild picks up config edits.
|
|
2329
3222
|
const config = await loadConfig(root);
|
|
2330
3223
|
const plugins = config.plugins;
|
|
2331
|
-
// scope key: the component's path under pages/ (index, _layout, blog/[id])
|
|
2332
3224
|
const scopeKeys = files.map((f, i) => {
|
|
2333
3225
|
const base = infos[i].isComponent ? path.join(root, 'src') : path.join(root, 'src', 'pages');
|
|
2334
3226
|
return path.relative(base, f).replace(/\\/g, '/').replace(/\.rose$/, '');
|
|
2335
3227
|
});
|
|
2336
|
-
// The build-wide import registry: absolute path -> module index, scope key, and the named
|
|
2337
|
-
// slots the component declares.
|
|
2338
3228
|
const registry: RoseRegistry = new Map(
|
|
2339
3229
|
files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
|
|
2340
3230
|
);
|
|
@@ -2342,8 +3232,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2342
3232
|
files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
|
|
2343
3233
|
);
|
|
2344
3234
|
|
|
2345
|
-
// A component that needs the client drags every page that imports it into the client
|
|
2346
|
-
// bundle - the page renders it, so it must be able to resume it.
|
|
2347
3235
|
const importsOf = new Map<number, number[]>();
|
|
2348
3236
|
files.forEach((_, i) => {
|
|
2349
3237
|
const list: number[] = [];
|
|
@@ -2354,8 +3242,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2354
3242
|
}
|
|
2355
3243
|
importsOf.set(i, list);
|
|
2356
3244
|
});
|
|
2357
|
-
// The walk reports WHICH dependency needs the client, so the build's lint
|
|
2358
|
-
// line names the component instead of the page.
|
|
2359
3245
|
const needyDep = (i: number, seen = new Set<number>()): string | null => {
|
|
2360
3246
|
if (compiled[i].needsClient) return path.basename(files[i]);
|
|
2361
3247
|
if (seen.has(i)) return null;
|
|
@@ -2375,8 +3261,6 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2375
3261
|
}
|
|
2376
3262
|
});
|
|
2377
3263
|
|
|
2378
|
-
// Reachability: a component no page (transitively) imports ships in neither
|
|
2379
|
-
// bundle - not the server's, not the client's.
|
|
2380
3264
|
const reachable = new Set<number>();
|
|
2381
3265
|
const visit = (i: number) => {
|
|
2382
3266
|
if (reachable.has(i)) return;
|
|
@@ -2391,16 +3275,12 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2391
3275
|
if (!infos[i].isComponent) visit(i);
|
|
2392
3276
|
});
|
|
2393
3277
|
|
|
2394
|
-
// Every component's scoped CSS in one stylesheet, inlined into the shell:
|
|
2395
|
-
// styles ship inside the document like the JS bundle - zero requests.
|
|
2396
3278
|
const styles = compiled
|
|
2397
3279
|
.map((c, i) => (reachable.has(i) ? c.style : ''))
|
|
2398
3280
|
.filter(Boolean).join('\n');
|
|
2399
3281
|
if (styles) await fs.promises.writeFile(path.join(outDir, 'styles.css'), styles);
|
|
2400
3282
|
else await fs.promises.rm(path.join(outDir, 'styles.css'), { force: true });
|
|
2401
3283
|
|
|
2402
|
-
// i18n: every JSON file in src/locales/ is a language. The dictionaries are baked into
|
|
2403
|
-
// BOTH bundles at build time …
|
|
2404
3284
|
let locales: Record<string, Record<string, string>> = {};
|
|
2405
3285
|
try {
|
|
2406
3286
|
for (const f of await fs.promises.readdir(path.join(root, 'src', 'locales'))) {
|
|
@@ -2408,13 +3288,11 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2408
3288
|
locales[f.slice(0, -5)] = JSON.parse(await fs.promises.readFile(path.join(root, 'src', 'locales', f), 'utf-8'));
|
|
2409
3289
|
}
|
|
2410
3290
|
} catch {
|
|
2411
|
-
locales = {};
|
|
3291
|
+
locales = {};
|
|
2412
3292
|
}
|
|
2413
3293
|
const defaultLocale = locales.en ? 'en' : Object.keys(locales).sort()[0] ?? 'en';
|
|
2414
3294
|
const localesJson = JSON.stringify(locales).replace(/</g, '\\u003c');
|
|
2415
3295
|
|
|
2416
|
-
// Which dictionaries ride in the CLIENT bundle. Default: all of them, so a locale switch
|
|
2417
|
-
// stays a zero-request navigation.
|
|
2418
3296
|
const preload: string[] = config.i18n.preload ?? Object.keys(locales);
|
|
2419
3297
|
const packed = Object.keys(locales).filter((l) => !preload.includes(l));
|
|
2420
3298
|
for (const l of preload) {
|
|
@@ -2429,22 +3307,17 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2429
3307
|
const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
|
|
2430
3308
|
const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, '\\u003c');
|
|
2431
3309
|
|
|
2432
|
-
// Intermediates (component modules, shared runtime, bundle entries) live in a build dir
|
|
2433
|
-
// that is removed before returning: both bundles are fully self-contained …
|
|
2434
3310
|
const buildDir = path.join(outDir, '.build');
|
|
2435
3311
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
2436
3312
|
await fs.promises.mkdir(buildDir, { recursive: true });
|
|
3313
|
+
const contentSrcCands = [path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'cli', 'content.ts'), path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'cli', 'content.ts')];
|
|
3314
|
+
const contentSrc = contentSrcCands.find((c) => fs.existsSync(c)) ?? contentSrcCands[0];
|
|
3315
|
+
fs.copyFileSync(contentSrc, path.join(buildDir, 'content-md.ts'));
|
|
2437
3316
|
|
|
2438
|
-
// The runtime half of the plugins. A transform already ran at build time (in
|
|
2439
|
-
// compileComponent); onRequest/onResponse must run per request INSIDE the server bundle …
|
|
2440
3317
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
2441
3318
|
if (runtimePlugins.length > 0) {
|
|
2442
|
-
// Relative from .build/, so the build works from any cwd (`rosetack build <dir>` from
|
|
2443
|
-
// elsewhere).
|
|
2444
3319
|
const configRel = path.relative(buildDir, path.join(root, 'rosetack.config.js')).replace(/\\/g, '/');
|
|
2445
|
-
await fs.promises.writeFile(path.join(buildDir, 'plugins.js'),
|
|
2446
|
-
// Bundled into dist/server.js: these hooks run per request on every server
|
|
2447
|
-
// (Node, dev/preview, edge). Transform hooks already ran at build time.
|
|
3320
|
+
await fs.promises.writeFile(path.join(buildDir, 'plugins.js'), `
|
|
2448
3321
|
import config from ${JSON.stringify(configRel)};
|
|
2449
3322
|
|
|
2450
3323
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -2457,8 +3330,6 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2457
3330
|
`);
|
|
2458
3331
|
}
|
|
2459
3332
|
|
|
2460
|
-
// Shared runtime module, bundled once into client and server output. The runtime ships
|
|
2461
|
-
// WITH THE COMPILER …
|
|
2462
3333
|
const runtimeEntry = ['../runtime/index.ts', '../src/runtime/index.ts']
|
|
2463
3334
|
.map((rel) => fileURLToPath(new URL(rel, import.meta.url)))
|
|
2464
3335
|
.find((p) => fs.existsSync(p));
|
|
@@ -2473,8 +3344,6 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2473
3344
|
});
|
|
2474
3345
|
|
|
2475
3346
|
for (let i = 0; i < compiled.length; i++) {
|
|
2476
|
-
// api routes compile to a handler module (no render): still an
|
|
2477
|
-
// intermediate, still removed with the rest of the build dir
|
|
2478
3347
|
const src = compiled[i].api ?? compiled[i].ssr;
|
|
2479
3348
|
await fs.promises.writeFile(path.join(buildDir, `comp-${i}.ssr.js`), src);
|
|
2480
3349
|
if (!infos[i].isApi) {
|
|
@@ -2484,15 +3353,46 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2484
3353
|
|
|
2485
3354
|
const pages = infos
|
|
2486
3355
|
.map((info, i) => ({ info, i }))
|
|
2487
|
-
.filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
|
|
3356
|
+
.filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
|
|
3357
|
+
// Specificity order, by route specificity: a literal segment
|
|
3358
|
+
// beats a param, a param beats a catch-all, and an optional catch-all
|
|
3359
|
+
// (which also matches the parent path) goes last. Without this a root
|
|
3360
|
+
// `[[...slug]]` - the shape a CMS's public site is written as - would
|
|
3361
|
+
// match EVERY pathname first and shadow every real route. The order is
|
|
3362
|
+
// stable within a class, so an app without catch-alls is unchanged.
|
|
3363
|
+
.sort((a, b) => {
|
|
3364
|
+
const rank = (pattern: string): number[] => {
|
|
3365
|
+
const segs = pattern.split('/');
|
|
3366
|
+
return [
|
|
3367
|
+
segs.filter((s) => s.startsWith('**')).length,
|
|
3368
|
+
segs.filter((s) => s.startsWith('*')).length,
|
|
3369
|
+
segs.filter((s) => s.startsWith(':')).length,
|
|
3370
|
+
];
|
|
3371
|
+
};
|
|
3372
|
+
const ra = rank(a.info.pattern);
|
|
3373
|
+
const rb = rank(b.info.pattern);
|
|
3374
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
3375
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
3376
|
+
});
|
|
2488
3377
|
|
|
2489
|
-
// API routes (pages/api/*.rose) dispatch handlers, never render HTML: they live in the
|
|
2490
|
-
// server bundle only and are excluded from the client route table entirely.
|
|
2491
3378
|
const apiRoutes = infos
|
|
2492
3379
|
.map((info, i) => ({ info, i }))
|
|
2493
|
-
.filter(({ info }) => info.isApi)
|
|
3380
|
+
.filter(({ info }) => info.isApi)
|
|
3381
|
+
.sort((a, b) => {
|
|
3382
|
+
const rank = (pattern: string): number[] => {
|
|
3383
|
+
const segs = pattern.split('/');
|
|
3384
|
+
return [
|
|
3385
|
+
segs.filter((s) => s.startsWith('**')).length,
|
|
3386
|
+
segs.filter((s) => s.startsWith('*')).length,
|
|
3387
|
+
segs.filter((s) => s.startsWith(':')).length,
|
|
3388
|
+
];
|
|
3389
|
+
};
|
|
3390
|
+
const ra = rank(a.info.pattern);
|
|
3391
|
+
const rb = rank(b.info.pattern);
|
|
3392
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
3393
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
3394
|
+
});
|
|
2494
3395
|
|
|
2495
|
-
// Compose render chains: page wrapped by its layouts (deepest first)
|
|
2496
3396
|
const compose = (idx: number): string => {
|
|
2497
3397
|
let expr = `render_${idx}`;
|
|
2498
3398
|
for (const i of layoutsOf(infos, idx)) {
|
|
@@ -2501,45 +3401,31 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2501
3401
|
return expr;
|
|
2502
3402
|
};
|
|
2503
3403
|
|
|
2504
|
-
// Mode B. `export const bundle = 'split'` (declared once, the root layout) turns every
|
|
2505
|
-
// route's client module into its own chunk: the document references /client.js externally …
|
|
2506
3404
|
const bundleMode = compiled.find((c) => c.bundle)?.bundle ?? 'inline';
|
|
2507
3405
|
const split = bundleMode === 'split';
|
|
2508
|
-
// The chain a route's chunk graph must load: the page first, then its layouts
|
|
2509
|
-
// deepest-first - exactly compose()'s nesting order …
|
|
2510
3406
|
const chainOf = (idx: number): number[] => [idx, ...layoutsOf(infos, idx)];
|
|
2511
|
-
// Mode B's loader expression: literal dynamic imports (esbuild needs the paths statically
|
|
2512
|
-
// analyzable to emit one chunk per module) …
|
|
2513
3407
|
const loaderInner = (idx: number): string =>
|
|
2514
3408
|
`load: () => loadChain([${chainOf(idx).map((i) => `() => import('./comp-${i}.client.js')`).join(', ')}])`;
|
|
2515
3409
|
const loaderOf = (idx: number): string => `{ ${loaderInner(idx)} }`;
|
|
2516
3410
|
|
|
2517
|
-
// The compiler decides zero-JS, not the developer. A route ships no client bundle - no
|
|
2518
|
-
// runtime, no state script, zero JavaScript …
|
|
2519
3411
|
const routeNoJs = (i: number): boolean => routeShipsNoJs(infos, compiled, i);
|
|
2520
3412
|
|
|
2521
3413
|
const serverImports = compiled
|
|
2522
3414
|
.map((_, i) => {
|
|
2523
|
-
if (!reachable.has(i)) return '';
|
|
3415
|
+
if (!reachable.has(i)) return '';
|
|
2524
3416
|
if (infos[i].isMiddleware) {
|
|
2525
|
-
// pages/_middleware.rose: server-only, imported as a namespace so a missing
|
|
2526
|
-
// `handle` export is simply "no middleware" (null), never a build error
|
|
2527
3417
|
return `import * as middlewareMod from './comp-${i}.ssr.js';`;
|
|
2528
3418
|
}
|
|
2529
3419
|
if (infos[i].isApi) {
|
|
2530
|
-
// api route: import its HTTP-method handlers (aliased per component)
|
|
2531
3420
|
const names = compiled[i].apiMethods ?? [];
|
|
2532
3421
|
const handlerImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
|
|
2533
3422
|
return handlerImports
|
|
2534
3423
|
? `import { ${handlerImports} } from './comp-${i}.ssr.js';`
|
|
2535
3424
|
: `import './comp-${i}.ssr.js';`;
|
|
2536
3425
|
}
|
|
2537
|
-
// a page's server actions are imported alongside its render; layouts
|
|
2538
|
-
// and the 404 page never receive POSTs, so they never need one
|
|
2539
3426
|
const isPage = !infos[i].isLayout && !infos[i].isNotFound;
|
|
2540
3427
|
const names = isPage ? compiled[i].actionNames : [];
|
|
2541
3428
|
const actionImports = names.map((n) => `${n} as ${n}_${i}`).join(', ');
|
|
2542
|
-
// The action guard rides the same import, server-only like the actions it fronts
|
|
2543
3429
|
const guardImport = isPage && compiled[i].guardName ? `beforeAction as beforeAction_${i}` : '';
|
|
2544
3430
|
const named = [actionImports, guardImport].filter(Boolean).join(', ');
|
|
2545
3431
|
return named
|
|
@@ -2548,25 +3434,27 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2548
3434
|
})
|
|
2549
3435
|
.join('\n');
|
|
2550
3436
|
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
3437
|
+
const notFoundEntries = infos
|
|
3438
|
+
.map((info, i) => ({ info, i }))
|
|
3439
|
+
.filter(({ info }) => info.isNotFound)
|
|
3440
|
+
.map(({ info, i }) => {
|
|
3441
|
+
const rel = path.relative(path.join(root, 'src', 'pages'), info.filePath).replace(/\\/g, '/');
|
|
3442
|
+
const dir = path.posix.dirname(rel);
|
|
3443
|
+
const prefix = dir === '.' ? '/' : '/' + dir;
|
|
3444
|
+
const flags = routeShellOff(infos, compiled, i) ? ', { shell: false }' : '';
|
|
3445
|
+
return { prefix, render: compose(i), flags };
|
|
3446
|
+
})
|
|
3447
|
+
.sort((a, b) => b.prefix.length - a.prefix.length);
|
|
3448
|
+
const notFoundTable = `[\n${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join('\n')}\n]`;
|
|
2555
3449
|
|
|
2556
|
-
// pages/500.rose renders for routes whose render throws (a dead $data source, a bad
|
|
2557
|
-
// expression): the page degrades instead of crashing the response …
|
|
2558
3450
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
2559
|
-
const errorRender = errIdx >= 0 ?
|
|
3451
|
+
const errorRender = errIdx >= 0 ? compose(errIdx) : 'null';
|
|
2560
3452
|
|
|
2561
|
-
// pages/_middleware.rose: the request interceptor (absent -> null).
|
|
2562
3453
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
2563
3454
|
|
|
2564
3455
|
const serverRoutes = pages
|
|
2565
3456
|
.map(({ info, i }) => {
|
|
2566
|
-
// actions: name -> imported fn, so a POST's __action field …
|
|
2567
3457
|
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(', ');
|
|
2568
|
-
// csr: false rides on the route so renderPage/renderPageStream can drop the state
|
|
2569
|
-
// script + bundle from the document (; the decision is the compiler's since #29).
|
|
2570
3458
|
if (compiled[i].csr === false && compiled[i].needsClient) {
|
|
2571
3459
|
throw new RoseError(
|
|
2572
3460
|
'E-EXPORT',
|
|
@@ -2587,19 +3475,19 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2587
3475
|
}
|
|
2588
3476
|
}
|
|
2589
3477
|
const csrFlag = routeNoJs(i) ? ', csr: false' : '';
|
|
2590
|
-
|
|
2591
|
-
// off the streaming path …
|
|
3478
|
+
const shellFlag = routeShellOff(infos, compiled, i) ? ', shell: false' : '';
|
|
2592
3479
|
const bufferFlag = compiled[i].buffer ? ', buffer: true' : '';
|
|
2593
|
-
|
|
2594
|
-
// page exports no beforeAction)
|
|
3480
|
+
const signalFlag = compiled[i].controlSignal ? ', signal: true' : '';
|
|
2595
3481
|
const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : '';
|
|
2596
|
-
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag}${bufferFlag} }`;
|
|
3482
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : 'null'}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
|
|
2597
3483
|
})
|
|
2598
3484
|
.join(',\n ');
|
|
2599
3485
|
|
|
2600
3486
|
const serverEntry = `
|
|
2601
3487
|
${serverImports}
|
|
2602
|
-
import {
|
|
3488
|
+
import { renderMarkdown } from './content-md.ts';
|
|
3489
|
+
import crypto from 'node:crypto';
|
|
3490
|
+
import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
|
|
2603
3491
|
${runtimePlugins.length > 0
|
|
2604
3492
|
? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
|
|
2605
3493
|
: `// no plugin declares a runtime hook, so there is no plugins
|
|
@@ -2609,12 +3497,7 @@ const __pluginHooks = [];
|
|
|
2609
3497
|
const __hasRequestHooks = false;
|
|
2610
3498
|
const __hasResponseHooks = false;`}
|
|
2611
3499
|
|
|
2612
|
-
|
|
2613
|
-
// middleware and may short-circuit the request with its own Response; onResponse
|
|
2614
|
-
// runs once the response exists and may replace it. Both are no-ops when the
|
|
2615
|
-
// project declares no runtime hooks. A throwing hook is logged and skipped -
|
|
2616
|
-
// the request continues - so a broken logging plugin can never take a site
|
|
2617
|
-
// down (a build-time transform, by contrast, fails loudly).
|
|
3500
|
+
|
|
2618
3501
|
export async function runRequestHooks(ctx) {
|
|
2619
3502
|
for (const p of __pluginHooks) {
|
|
2620
3503
|
if (!p.onRequest) continue;
|
|
@@ -2642,32 +3525,20 @@ export async function runResponseHooks(ctx, res) {
|
|
|
2642
3525
|
return out;
|
|
2643
3526
|
}
|
|
2644
3527
|
|
|
2645
|
-
|
|
2646
|
-
|
|
3528
|
+
|
|
3529
|
+
|
|
2647
3530
|
export const hasRequestHooks = __hasRequestHooks;
|
|
2648
3531
|
export const hasResponseHooks = __hasResponseHooks;
|
|
2649
3532
|
|
|
2650
|
-
// P0-1: the query of the request being rendered, for $query().
|
|
2651
|
-
// call this before every render (stream, buffered, POST, api) with the parsed
|
|
2652
|
-
// query string; routing itself matches the pathname, which is what fixed the
|
|
2653
|
-
// query-404. A render with no query (the build's prerender, the ISR
|
|
2654
|
-
// background pass) passes {} explicitly - the bag is per request, so a stale
|
|
2655
|
-
// one must never leak into the next.
|
|
3533
|
+
// P0-1: the query of the request being rendered, for $query().
|
|
2656
3534
|
export function setQuery(query) {
|
|
2657
3535
|
setRequestQuery(query || {});
|
|
2658
3536
|
}
|
|
2659
3537
|
|
|
2660
|
-
|
|
2661
|
-
// src/locales/*.json. A route segment named [lang] is the locale: the value
|
|
2662
|
-
// must name one of these dictionaries, and $t resolves keys against it.
|
|
3538
|
+
|
|
2663
3539
|
setLocales(${localesJson}, '${defaultLocale}');
|
|
2664
3540
|
|
|
2665
|
-
|
|
2666
|
-
// own process with its own dist/server.js module, so a $store write must
|
|
2667
|
-
// travel: this worker -> primary -> every other worker. process.send exists
|
|
2668
|
-
// only inside cluster workers, so a single-process runner (dev, preview,
|
|
2669
|
-
// the edge adapter) keeps the transport null and $store stays plain
|
|
2670
|
-
// per-process state - the documented boundary, not a bug.
|
|
3541
|
+
|
|
2671
3542
|
if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
2672
3543
|
setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
|
|
2673
3544
|
process.on('message', (msg) => {
|
|
@@ -2675,76 +3546,274 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
|
2675
3546
|
});
|
|
2676
3547
|
}
|
|
2677
3548
|
|
|
3549
|
+
// (the cross-machine seam): the cluster relay above covers ONE machine.
|
|
3550
|
+
export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
|
|
3551
|
+
setStoreTransport(send);
|
|
3552
|
+
}
|
|
3553
|
+
export function __deliverStorePatch(name: string, value: unknown): void {
|
|
3554
|
+
applyStorePatch(name, value);
|
|
3555
|
+
}
|
|
3556
|
+
|
|
2678
3557
|
export { localeList };
|
|
2679
3558
|
export const defaultLocale = '${defaultLocale}';
|
|
2680
3559
|
|
|
2681
|
-
// Route params maps, re-exported for the build's prerender step: routePath
|
|
2682
|
-
// -> the component's exported params (a static map or a function). Reading
|
|
2683
|
-
// them through the server bundle keeps the deploy dir free of component
|
|
2684
|
-
// modules - both bundles are self-contained, nothing else may ship. Only
|
|
2685
|
-
// components that actually export params appear here (a missing export
|
|
2686
|
-
// means the dynamic route renders on demand).
|
|
3560
|
+
// Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
|
|
2687
3561
|
${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join('\n')}
|
|
2688
3562
|
|
|
2689
3563
|
export const routeParams = {
|
|
2690
3564
|
${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(',\n ')}
|
|
2691
3565
|
};
|
|
2692
3566
|
|
|
2693
|
-
// Routes whose component reads the request context (getContext()), mutates a
|
|
2694
|
-
// shared store ($store()), reads the query ($query(), P0-1), opted into
|
|
2695
|
-
// nonce-based CSP or into the buffered path (buffer = true, P0-2):
|
|
2696
|
-
// the bag is per-request, the store is per-process, a nonce is per-response,
|
|
2697
|
-
// and a buffered route's hooks must run per request - so these are dynamic.
|
|
2698
|
-
// The build never bakes them and the servers never answer them from a
|
|
2699
|
-
// prerendered file. Public routes keep the static fast path (file cache,
|
|
2700
|
-
// ETag/304, streaming) untouched.
|
|
3567
|
+
// Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
|
|
2701
3568
|
export const dynamicRoutes = [
|
|
2702
|
-
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
3569
|
+
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
2703
3570
|
];
|
|
2704
3571
|
|
|
2705
|
-
// Which api routes opt into build-time baking (export const prerender = true):
|
|
2706
|
-
// routePath -> boolean. The build calls the GET handler once and writes the
|
|
2707
|
-
// body to dist/, so the Go single binary serves read-only APIs without Node.
|
|
3572
|
+
// Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
|
|
2708
3573
|
${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join('\n')}
|
|
2709
3574
|
|
|
2710
3575
|
export const apiPrerender = {
|
|
2711
3576
|
${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : 'false'}`).join(',\n ')}
|
|
2712
3577
|
};
|
|
2713
3578
|
|
|
2714
|
-
|
|
2715
|
-
// bakes these routes like any other, and the preview server serves the
|
|
2716
|
-
// baked file for up to N seconds - after which the next request is answered
|
|
2717
|
-
// STALE (instant, from disk) while a background pass re-renders and swaps
|
|
2718
|
-
// the file (ISR). Routes that read the request context are
|
|
2719
|
-
// excluded: they render per request and have no baked file to revalidate.
|
|
2720
|
-
// The dev server ignores the window (it rebuilds on change), the edge
|
|
2721
|
-
// adapter renders live (always fresh), and the Go binary serves the baked
|
|
2722
|
-
// file forever - the same static-half boundary as page POSTs.
|
|
3579
|
+
|
|
2723
3580
|
export const revalidate = [
|
|
2724
3581
|
${pages.filter(({ i }) => compiled[i].revalidate !== undefined && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(',\n ')}
|
|
2725
3582
|
];
|
|
2726
3583
|
|
|
2727
|
-
//
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
3584
|
+
// Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
|
|
3585
|
+
export const routeCaches = [
|
|
3586
|
+
${pages.filter(({ i }) => compiled[i].cache !== undefined).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(',\n ')}
|
|
3587
|
+
];
|
|
3588
|
+
const __dynCache = new Map();
|
|
3589
|
+
export function invalidateRenderCache(): void {
|
|
3590
|
+
__dynCache.clear();
|
|
3591
|
+
}
|
|
3592
|
+
// Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
|
|
3593
|
+
const __kvStore = new Map<string, { v: unknown; exp: number }>();
|
|
3594
|
+
// Content collections: src/content/<coll>/*.md scanned once at build time,
|
|
3595
|
+
|
|
3596
|
+
const contentCollections = ${JSON.stringify(scanContentDir(path.join(root, 'src', 'content')))};
|
|
3597
|
+
export const kv = {
|
|
3598
|
+
get(key: string): unknown {
|
|
3599
|
+
const e = __kvStore.get(key);
|
|
3600
|
+
if (!e) return undefined;
|
|
3601
|
+
if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
|
|
3602
|
+
return e.v;
|
|
3603
|
+
},
|
|
3604
|
+
set(key: string, value: unknown, ttlSeconds = 300): void {
|
|
3605
|
+
if (__kvStore.size > 1000) {
|
|
3606
|
+
const cutoff = Date.now();
|
|
3607
|
+
for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
|
|
3608
|
+
if (__kvStore.size > 2000) __kvStore.clear();
|
|
3609
|
+
}
|
|
3610
|
+
__kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
|
|
3611
|
+
},
|
|
3612
|
+
del(key: string): void { __kvStore.delete(key); },
|
|
3613
|
+
has(key: string): boolean {
|
|
3614
|
+
const e = __kvStore.get(key);
|
|
3615
|
+
return !!e && e.exp >= Date.now();
|
|
3616
|
+
},
|
|
3617
|
+
};
|
|
3618
|
+
globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
|
|
3619
|
+
globalThis.__rosetackContent = {
|
|
3620
|
+
list: (coll: string, filter?: { tag: string }) => {
|
|
3621
|
+
let items = contentCollections[coll] ?? [];
|
|
3622
|
+
if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
|
|
3623
|
+
return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
|
|
3624
|
+
},
|
|
3625
|
+
rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
|
|
3626
|
+
return buildRss(contentCollections[coll] ?? [], opts);
|
|
3627
|
+
},
|
|
3628
|
+
get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
|
|
3629
|
+
const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
|
|
3630
|
+
if (!e) return null;
|
|
3631
|
+
return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
|
|
3632
|
+
},
|
|
3633
|
+
};
|
|
3634
|
+
|
|
3635
|
+
const v = {
|
|
3636
|
+
validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
|
|
3637
|
+
const errors: Record<string, string> = {};
|
|
3638
|
+
const values: Record<string, unknown> = {};
|
|
3639
|
+
for (const [field, ruleList] of Object.entries(rules)) {
|
|
3640
|
+
let val = body[field];
|
|
3641
|
+
for (const rule of ruleList) {
|
|
3642
|
+
if (val === undefined || val === null || val === "") {
|
|
3643
|
+
if (rule === "required") errors[field] = field + " is required";
|
|
3644
|
+
else if (rule.startsWith("default:")) val = rule.slice(8);
|
|
3645
|
+
continue;
|
|
3646
|
+
}
|
|
3647
|
+
if (rule === "string") val = String(val);
|
|
3648
|
+
else if (rule === "trim") val = String(val).trim();
|
|
3649
|
+
else if (rule === "number") {
|
|
3650
|
+
const num = Number(val);
|
|
3651
|
+
if (Number.isNaN(num)) errors[field] = field + " must be a number";
|
|
3652
|
+
else val = num;
|
|
3653
|
+
} else if (rule === "email") {
|
|
3654
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
|
|
3655
|
+
} else if (rule.startsWith("min:")) {
|
|
3656
|
+
const min = Number(rule.slice(4));
|
|
3657
|
+
if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
|
|
3658
|
+
} else if (rule.startsWith("max:")) {
|
|
3659
|
+
const max = Number(rule.slice(4));
|
|
3660
|
+
if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
values[field] = val;
|
|
3664
|
+
}
|
|
3665
|
+
return { ok: Object.keys(errors).length === 0, errors, values };
|
|
3666
|
+
},
|
|
3667
|
+
};
|
|
3668
|
+
|
|
3669
|
+
const jobs = {
|
|
3670
|
+
_timers: new Map<string, ReturnType<typeof setInterval>>(),
|
|
3671
|
+
every(name: string, seconds: number, fn: () => void | Promise<void>): void {
|
|
3672
|
+
if (this._timers.has(name)) return;
|
|
3673
|
+
const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
|
|
3674
|
+
this._timers.set(name, t as any);
|
|
3675
|
+
},
|
|
3676
|
+
cancel(name: string): void {
|
|
3677
|
+
const t = this._timers.get(name);
|
|
3678
|
+
if (t) { clearInterval(t); this._timers.delete(name); }
|
|
3679
|
+
},
|
|
3680
|
+
cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
|
|
3681
|
+
};
|
|
3682
|
+
|
|
3683
|
+
function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
|
|
3684
|
+
const encoder = new TextEncoder();
|
|
3685
|
+
const stream = new ReadableStream({
|
|
3686
|
+
async start(controller) {
|
|
3687
|
+
let closed = false;
|
|
3688
|
+
const send = (event: string, data: unknown) => {
|
|
3689
|
+
if (closed) return;
|
|
3690
|
+
controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
|
|
3691
|
+
};
|
|
3692
|
+
try {
|
|
3693
|
+
await handler(send);
|
|
3694
|
+
} finally {
|
|
3695
|
+
closed = true;
|
|
3696
|
+
try { controller.close(); } catch { }
|
|
3697
|
+
}
|
|
3698
|
+
},
|
|
3699
|
+
});
|
|
3700
|
+
return new Response(stream, {
|
|
3701
|
+
headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
|
|
3702
|
+
});
|
|
3703
|
+
}
|
|
3704
|
+
globalThis.__rosetackExtras = { v, jobs, sse };
|
|
3705
|
+
const auth = {
|
|
3706
|
+
hashPassword(password: string): string {
|
|
3707
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
3708
|
+
const hash = crypto.scryptSync(password, salt, 32).toString("hex");
|
|
3709
|
+
return salt + ":" + hash;
|
|
3710
|
+
},
|
|
3711
|
+
verifyPassword(password: string, stored: string): boolean {
|
|
3712
|
+
const [salt, hash] = stored.split(":");
|
|
3713
|
+
if (!salt || !hash) return false;
|
|
3714
|
+
return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
|
|
3715
|
+
},
|
|
3716
|
+
signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
|
|
3717
|
+
const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
|
|
3718
|
+
const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3719
|
+
return payload + "." + sig;
|
|
3720
|
+
},
|
|
3721
|
+
verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
|
|
3722
|
+
const dot = token.lastIndexOf(".");
|
|
3723
|
+
if (dot < 0) return null;
|
|
3724
|
+
const payload = token.slice(0, dot);
|
|
3725
|
+
const sig = token.slice(dot + 1);
|
|
3726
|
+
const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3727
|
+
try {
|
|
3728
|
+
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
|
|
3729
|
+
} catch { return null; }
|
|
3730
|
+
try {
|
|
3731
|
+
const data = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
3732
|
+
if (data.exp < Date.now()) return null;
|
|
3733
|
+
return data as T;
|
|
3734
|
+
} catch { return null; }
|
|
3735
|
+
},
|
|
3736
|
+
csrfToken(secret: string, sessionId: string): string {
|
|
3737
|
+
return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
|
|
3738
|
+
},
|
|
3739
|
+
verifyCsrf(token: string, secret: string, sessionId: string): boolean {
|
|
3740
|
+
try {
|
|
3741
|
+
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
|
|
3742
|
+
} catch { return false; }
|
|
3743
|
+
},
|
|
3744
|
+
};
|
|
3745
|
+
globalThis.__rosetackAuth = auth;
|
|
3746
|
+
|
|
3747
|
+
export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
|
|
3748
|
+
const hit = kv.get(key);
|
|
3749
|
+
if (hit !== undefined) return hit;
|
|
3750
|
+
const v = await compute();
|
|
3751
|
+
if (v !== undefined) kv.set(key, v, ttlSeconds);
|
|
3752
|
+
return v;
|
|
3753
|
+
}
|
|
3754
|
+
export function isCachedRoute(pathname: string): boolean {
|
|
3755
|
+
return routeCaches.some((r) => matchRoute(r.pattern, pathname));
|
|
3756
|
+
}
|
|
3757
|
+
export function invalidatePath(pathname: string): number {
|
|
3758
|
+
let n = 0;
|
|
3759
|
+
for (const key of [...__dynCache.keys()]) {
|
|
3760
|
+
if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
|
|
3761
|
+
}
|
|
3762
|
+
return n;
|
|
3763
|
+
}
|
|
3764
|
+
export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
|
|
3765
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3766
|
+
if (!cfg) return null;
|
|
3767
|
+
let h = 0x811c9dc5;
|
|
3768
|
+
const c = cookieHeader || '';
|
|
3769
|
+
for (let i = 0; i < c.length; i++) {
|
|
3770
|
+
h ^= c.charCodeAt(i);
|
|
3771
|
+
h = (h * 0x01000193) >>> 0;
|
|
3772
|
+
}
|
|
3773
|
+
const hit = __dynCache.get(pathname + '|' + h.toString(16));
|
|
3774
|
+
return hit && hit.expires > Date.now() ? hit.page : null;
|
|
3775
|
+
}
|
|
3776
|
+
export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
|
|
3777
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3778
|
+
if (!cfg) return renderPage(pathname);
|
|
3779
|
+
let h = 0x811c9dc5;
|
|
3780
|
+
for (let i = 0; i < cookieHeader.length; i++) {
|
|
3781
|
+
h ^= cookieHeader.charCodeAt(i);
|
|
3782
|
+
h = (h * 0x01000193) >>> 0;
|
|
3783
|
+
}
|
|
3784
|
+
const key = pathname + '|' + h.toString(16);
|
|
3785
|
+
const hit = __dynCache.get(key);
|
|
3786
|
+
if (hit && hit.expires > Date.now()) {
|
|
3787
|
+
__dynCache.delete(key);
|
|
3788
|
+
__dynCache.set(key, hit);
|
|
3789
|
+
return hit.page;
|
|
3790
|
+
}
|
|
3791
|
+
// Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
|
|
3792
|
+
if (hit && !hit.refreshing) {
|
|
3793
|
+
hit.refreshing = true;
|
|
3794
|
+
renderPage(pathname).then((fresh: any) => {
|
|
3795
|
+
if (fresh.status === 200 && !fresh.redirect) {
|
|
3796
|
+
__dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
|
|
3797
|
+
} else {
|
|
3798
|
+
__dynCache.delete(key);
|
|
3799
|
+
}
|
|
3800
|
+
}).catch(() => { __dynCache.delete(key); });
|
|
3801
|
+
return hit.page;
|
|
3802
|
+
}
|
|
3803
|
+
const page = await renderPage(pathname);
|
|
3804
|
+
if (page.status === 200 && !page.redirect) {
|
|
3805
|
+
__dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
|
|
3806
|
+
if (__dynCache.size > 300) {
|
|
3807
|
+
__dynCache.delete(__dynCache.keys().next().value as string);
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
return page;
|
|
3811
|
+
}
|
|
3812
|
+
|
|
3813
|
+
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
2733
3814
|
export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
|
|
2734
3815
|
|
|
2735
|
-
// Routes whose DOCUMENTS ship without the client bundle (
|
|
2736
|
-
// decided by the compiler since #29): HTML + CSS only - no runtime, no
|
|
2737
|
-
// state script, zero JavaScript for whoever lands on them. The compiler
|
|
2738
|
-
// picks these automatically: a route whose whole chain needs nothing from
|
|
2739
|
-
// the client (no event wiring, no lifecycle, no action, no form) is a
|
|
2740
|
-
// content route. An exported "csr = true" forces the bundle back in; an
|
|
2741
|
-
// exported "csr = false" is the same decision, asserted. The route's render
|
|
2742
|
-
// function still rides in the client bundle, so a client-side navigation
|
|
2743
|
-
// from an interactive page paints it normally and a static deploy's SPA
|
|
2744
|
-
// fallback can render it too; only the document is JS-free.
|
|
2745
|
-
// isNoJs() lets the servers keep these routes on the buffered path: a
|
|
2746
|
-
// streamed no-JS document would carry the shell's default <title> (the
|
|
2747
|
-
// route head is applied client-side at boot, and there is no client).
|
|
3816
|
+
// Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
|
|
2748
3817
|
export const noJsRoutes = [
|
|
2749
3818
|
${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(',\n ')}
|
|
2750
3819
|
];
|
|
@@ -2753,21 +3822,12 @@ export function isNoJs(pathname) {
|
|
|
2753
3822
|
return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
2754
3823
|
}
|
|
2755
3824
|
|
|
2756
|
-
// P0-2 (bug report): routes that exported "buffer = true".
|
|
2757
|
-
// this BEFORE choosing a path: a streamed response commits its status and
|
|
2758
|
-
// headers before the body exists, so its onResponse hooks cannot see the
|
|
2759
|
-
// document and a render that throws mid-flight still answers 200. A buffered
|
|
2760
|
-
// route keeps every capability and gives up the early flush - the trade is
|
|
2761
|
-
// the route's to make, per route, not the framework's.
|
|
3825
|
+
// P0-2 (bug report): routes that exported "buffer = true".
|
|
2762
3826
|
export function isBuffered(pathname) {
|
|
2763
|
-
return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
|
|
3827
|
+
return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
|
|
2764
3828
|
}
|
|
2765
3829
|
|
|
2766
|
-
|
|
2767
|
-
// map carries them into every response the servers write for it, merged
|
|
2768
|
-
// OVER the framework defaults (the strict CSP) - so an app can tighten or
|
|
2769
|
-
// relax the policy per route. Absent -> null, and the servers keep sending
|
|
2770
|
-
// the defaults alone.
|
|
3830
|
+
|
|
2771
3831
|
export const routeHeaders = [
|
|
2772
3832
|
${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(',\n ')}
|
|
2773
3833
|
];
|
|
@@ -2777,14 +3837,7 @@ export function headersFor(pathname) {
|
|
|
2777
3837
|
return hit ? hit.headers : null;
|
|
2778
3838
|
}
|
|
2779
3839
|
|
|
2780
|
-
|
|
2781
|
-
// ). The servers ask this BEFORE writing a document: when it is true they
|
|
2782
|
-
// mint one random nonce per response, put it in the CSP header ('nonce-...'
|
|
2783
|
-
// plus 'strict-dynamic', so the document's own code may load more code) and
|
|
2784
|
-
// stamp the same value on the script tag. The default policy stays a hash -
|
|
2785
|
-
// cspNonceRoutes is empty for an app that never asks, so the fast path is
|
|
2786
|
-
// unchanged. The Go binary never sees this: these routes are dynamic, so it
|
|
2787
|
-
// has no baked file for them to serve.
|
|
3840
|
+
|
|
2788
3841
|
export const cspNonceRoutes = [
|
|
2789
3842
|
${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
2790
3843
|
];
|
|
@@ -2793,9 +3846,7 @@ export function cspNonce(pathname) {
|
|
|
2793
3846
|
return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
2794
3847
|
}
|
|
2795
3848
|
|
|
2796
|
-
// A Web-standard Request from whatever the host provides: the edge adapter
|
|
2797
|
-
// passes one already; the Node server passes its IncomingMessage (plus the
|
|
2798
|
-
// already-parsed FormData for POSTs, so middleware can read form fields).
|
|
3849
|
+
// A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
|
|
2799
3850
|
function toWebRequest(raw, form) {
|
|
2800
3851
|
if (raw instanceof Request) return raw;
|
|
2801
3852
|
const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
|
|
@@ -2803,13 +3854,7 @@ function toWebRequest(raw, form) {
|
|
|
2803
3854
|
return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
|
|
2804
3855
|
}
|
|
2805
3856
|
|
|
2806
|
-
|
|
2807
|
-
// its short-circuit Response, or null to continue. The servers call this
|
|
2808
|
-
// EXACTLY ONCE per request, before anything else: it resets the per-request
|
|
2809
|
-
// context bag and the middleware fills it via getContext(), which $data,
|
|
2810
|
-
// server actions and api handlers then read while rendering. rawReq: the
|
|
2811
|
-
// host's request (Node IncomingMessage or a Web-standard Request); form:
|
|
2812
|
-
// the already-parsed FormData of a POST.
|
|
3857
|
+
|
|
2813
3858
|
export async function runMiddleware(rawReq, form) {
|
|
2814
3859
|
resetRequestContext();
|
|
2815
3860
|
if (!middleware || !rawReq) return null;
|
|
@@ -2821,10 +3866,7 @@ const routes = [
|
|
|
2821
3866
|
${serverRoutes}
|
|
2822
3867
|
];
|
|
2823
3868
|
|
|
2824
|
-
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
|
|
2825
|
-
// render HTML and never reach the client bundle. The middleware ran before
|
|
2826
|
-
// this (the servers call runMiddleware() first), so handlers can read
|
|
2827
|
-
// getContext() for auth without re-running anything.
|
|
3869
|
+
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
|
|
2828
3870
|
const apiRoutes = [
|
|
2829
3871
|
${apiRoutes.map(({ info, i }) => {
|
|
2830
3872
|
const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(', ');
|
|
@@ -2832,19 +3874,40 @@ const apiRoutes = [
|
|
|
2832
3874
|
}).join(',\n ')}
|
|
2833
3875
|
];
|
|
2834
3876
|
|
|
2835
|
-
// pages
|
|
2836
|
-
|
|
3877
|
+
// Not-found pages, deepest segment first: the root 404.rose ('/') and any
|
|
3878
|
+
// pages/<seg>/_notfound.rose, each already composed with its layout chain.
|
|
3879
|
+
// notFoundFor picks the nearest one up the path - an /admin miss answers
|
|
3880
|
+
// the admin 404, a public miss the site's - and notFoundPage is the whole
|
|
3881
|
+
// answer (real 404 status, or the built-in plain 404 when the app has none).
|
|
3882
|
+
const notFoundRoutes = ${notFoundTable};
|
|
3883
|
+
const notFoundFor = (pathname) => {
|
|
3884
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
3885
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
3886
|
+
}
|
|
3887
|
+
return null;
|
|
3888
|
+
};
|
|
3889
|
+
|
|
3890
|
+
const notFoundFlags = (pathname) => {
|
|
3891
|
+
for (const [prefix, render, flags] of notFoundRoutes) {
|
|
3892
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
|
|
3893
|
+
}
|
|
3894
|
+
return null;
|
|
3895
|
+
};
|
|
3896
|
+
const notFoundPage = async (pathname) => {
|
|
3897
|
+
const nf = notFoundFor(pathname);
|
|
3898
|
+
if (nf) {
|
|
3899
|
+
const page = await renderFallback(pathname, nf);
|
|
3900
|
+
// __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
|
|
3901
|
+
return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
|
|
3902
|
+
}
|
|
3903
|
+
return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
|
|
3904
|
+
};
|
|
3905
|
+
|
|
2837
3906
|
|
|
2838
|
-
// pages/500.rose (with its layouts) or null -> built-in plain 500: a route
|
|
2839
3907
|
// whose render throws degrades to this instead of failing the response.
|
|
2840
3908
|
const errorPage = ${errorRender};
|
|
2841
3909
|
|
|
2842
|
-
|
|
2843
|
-
// of its [lang] segment (the default when there is none, or when the segment
|
|
2844
|
-
// names no dictionary: that request 404s in the default language) and the
|
|
2845
|
-
// reading direction that locale implies. The buffered render returns the same
|
|
2846
|
-
// pair; the streaming path needs it BEFORE the shell flushes, which is why
|
|
2847
|
-
// the servers ask for it by pathname.
|
|
3910
|
+
|
|
2848
3911
|
export function docAttrs(pathname) {
|
|
2849
3912
|
for (const route of routes) {
|
|
2850
3913
|
if (!matchRoute(route.pattern, pathname)) continue;
|
|
@@ -2854,21 +3917,42 @@ export function docAttrs(pathname) {
|
|
|
2854
3917
|
const lang = pathname.split('/')[langIdx];
|
|
2855
3918
|
if (isLocale(lang)) return { lang, dir: localeDir(lang) };
|
|
2856
3919
|
}
|
|
2857
|
-
break;
|
|
3920
|
+
break;
|
|
2858
3921
|
}
|
|
2859
3922
|
return { lang: defaultLocale, dir: localeDir(defaultLocale) };
|
|
2860
3923
|
}
|
|
2861
3924
|
|
|
2862
3925
|
// Paint a fallback page (404/500) and serialize its state.
|
|
2863
3926
|
async function renderFallback(pathname, render) {
|
|
2864
|
-
|
|
3927
|
+
// Split mode: the not-found entry's render is a loader object — resolve it through getRender (which memoizes the composed function) exactly like.
|
|
3928
|
+
let fn = render;
|
|
3929
|
+
if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
|
|
3930
|
+
|
|
3931
|
+
// { render } once the route's chunk graph is loaded
|
|
3932
|
+
fn = (await fn.load()).render;
|
|
3933
|
+
}
|
|
3934
|
+
const { html, head } = extractHead(await fn([], ''));
|
|
2865
3935
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2866
3936
|
return { html, state, head, ...docAttrs(pathname) };
|
|
2867
3937
|
}
|
|
2868
3938
|
|
|
2869
3939
|
export function matchRoute(pattern, pathname) {
|
|
3940
|
+
// Q0 (bug report): one canonical URL per route.
|
|
3941
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
2870
3942
|
const patternParts = pattern.split('/');
|
|
2871
3943
|
const pathParts = pathname.split('/');
|
|
3944
|
+
|
|
3945
|
+
const last = patternParts[patternParts.length - 1];
|
|
3946
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
3947
|
+
const fixed = patternParts.slice(0, -1);
|
|
3948
|
+
if (pathParts.length < fixed.length) return false;
|
|
3949
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
3950
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
3951
|
+
if (fixed[i].startsWith(':')) continue;
|
|
3952
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
3953
|
+
}
|
|
3954
|
+
return true;
|
|
3955
|
+
}
|
|
2872
3956
|
if (patternParts.length !== pathParts.length) return false;
|
|
2873
3957
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2874
3958
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -2877,13 +3961,7 @@ export function matchRoute(pattern, pathname) {
|
|
|
2877
3961
|
return true;
|
|
2878
3962
|
}
|
|
2879
3963
|
|
|
2880
|
-
// Head blocks (one per component in the route chain) are pulled out of the
|
|
2881
|
-
// page html: the shell injects them into <head>, and the client re-applies
|
|
2882
|
-
// them on navigation. Document order is page-first, so the shell's keyed
|
|
2883
|
-
// merge lets a page override its layouts. The EMPTY marker pair stays in the
|
|
2884
|
-
// body so the client's wire() still finds the block: at boot it adopts the
|
|
2885
|
-
// shell-injected elements in place (marked with the same keys, so no
|
|
2886
|
-
// duplicates) and keeps the head reactive.
|
|
3964
|
+
// Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
|
|
2887
3965
|
function extractHead(rendered) {
|
|
2888
3966
|
const head = [];
|
|
2889
3967
|
const html = rendered.replace(/<!--\u27e6h:(\\d+)\u27e7-->([\\s\\S]*?)<!--\u27e6\\/h:\\1\u27e7-->/g, (_, id, content) => {
|
|
@@ -2893,18 +3971,7 @@ function extractHead(rendered) {
|
|
|
2893
3971
|
return { html, head };
|
|
2894
3972
|
}
|
|
2895
3973
|
|
|
2896
|
-
//
|
|
2897
|
-
// selected server action runs first and returns a state patch (e.g.
|
|
2898
|
-
// { guests: [...] }); seeding those keys BEFORE the render makes state()
|
|
2899
|
-
// adopt them, so the response is the page as it looks AFTER the action -
|
|
2900
|
-
// with or without JS. A __action field picks the action by name (default
|
|
2901
|
-
// 'action', the conventional <form method="POST"> target); a click handler
|
|
2902
|
-
// bound to an action ($action('like')) sends the same field.
|
|
2903
|
-
// A route whose render throws degrades to pages/500.rose (status 500) - or
|
|
2904
|
-
// the built-in plain 500 - instead of failing the whole response.
|
|
2905
|
-
// The middleware does NOT run here: the servers run it once per request via
|
|
2906
|
-
// runMiddleware() (which also seeds the request context), so a page render
|
|
2907
|
-
// never re-runs it.
|
|
3974
|
+
// Form: the submitted FormData of a progressive-enhancement POST.
|
|
2908
3975
|
export async function renderPage(pathname, form) {
|
|
2909
3976
|
clearRequestState();
|
|
2910
3977
|
for (const route of routes) {
|
|
@@ -2912,31 +3979,21 @@ export async function renderPage(pathname, form) {
|
|
|
2912
3979
|
const patternParts = route.pattern.split('/');
|
|
2913
3980
|
const pathParts = pathname.split('/');
|
|
2914
3981
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
3982
|
+
const seg = patternParts[i];
|
|
3983
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
3984
|
+
|
|
3985
|
+
|
|
3986
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2918
3987
|
}
|
|
2919
|
-
//
|
|
2920
|
-
// 404 - the URL is the contract, and rendering the page with fallback
|
|
2921
|
-
// strings would serve duplicate content under a bogus language
|
|
3988
|
+
// I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
|
|
2922
3989
|
const langIdx = patternParts.indexOf(':lang');
|
|
2923
3990
|
if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
|
|
2924
|
-
|
|
2925
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
3991
|
+
return await notFoundPage(pathname);
|
|
2926
3992
|
}
|
|
2927
|
-
|
|
2928
|
-
|
|
3993
|
+
|
|
3994
|
+
|
|
2929
3995
|
const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
|
|
2930
|
-
// The action dispatch. The page's guard (exported
|
|
2931
|
-
// beforeAction) runs FIRST and vetoes with an ActionError - the
|
|
2932
|
-
// action-level permission check. Then the selected action runs and its
|
|
2933
|
-
// return value seeds this render's state, per key, so an incremental
|
|
2934
|
-
// patch ($append and friends) grows a large list by one row instead of
|
|
2935
|
-
// re-sending the whole thing. An ActionError from either half is a
|
|
2936
|
-
// BUSINESS failure: it is seeded as the 'actionError' state, the
|
|
2937
|
-
// response carries its status, and the page renders with the failure
|
|
2938
|
-
// visible (a {#boundary} around the action's widget contains it).
|
|
2939
|
-
// Anything else is a bug and keeps going to the 500 page.
|
|
3996
|
+
// The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
|
|
2940
3997
|
let actionStatus = 0;
|
|
2941
3998
|
if (form && route.actions) {
|
|
2942
3999
|
const actionName = form.get('__action') || 'action';
|
|
@@ -2948,9 +4005,7 @@ export async function renderPage(pathname, form) {
|
|
|
2948
4005
|
if (patch && typeof patch === 'object') {
|
|
2949
4006
|
for (const key of Object.keys(patch)) {
|
|
2950
4007
|
const v = patch[key];
|
|
2951
|
-
// An incremental patch is RECORDED, not applied: the render's
|
|
2952
|
-
// own state declarations apply it, so the delta is relative to
|
|
2953
|
-
// the value the page was going to render anyway.
|
|
4008
|
+
// An incremental patch is RECORDED, not applied: the render's own state declarations apply.
|
|
2954
4009
|
if (v instanceof StateDelta) setStateDelta(key, v);
|
|
2955
4010
|
else setState(key, v);
|
|
2956
4011
|
}
|
|
@@ -2959,6 +4014,11 @@ export async function renderPage(pathname, form) {
|
|
|
2959
4014
|
if (err instanceof ActionError) {
|
|
2960
4015
|
setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
|
|
2961
4016
|
actionStatus = err.code;
|
|
4017
|
+
} else if (err && err.__rosetack === 'redirect') {
|
|
4018
|
+
|
|
4019
|
+
return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
|
|
4020
|
+
} else if (err && err.__rosetack === 'notFound') {
|
|
4021
|
+
return await notFoundPage(pathname);
|
|
2962
4022
|
} else {
|
|
2963
4023
|
throw err;
|
|
2964
4024
|
}
|
|
@@ -2969,32 +4029,46 @@ export async function renderPage(pathname, form) {
|
|
|
2969
4029
|
try {
|
|
2970
4030
|
rendered = extractHead(await route.render([], ''));
|
|
2971
4031
|
} catch (err) {
|
|
4032
|
+
// The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
|
|
4033
|
+
const signal = err && err.__rosetack;
|
|
4034
|
+
if (signal === 'redirect') {
|
|
4035
|
+
return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
|
|
4036
|
+
}
|
|
4037
|
+
if (signal === 'notFound') {
|
|
4038
|
+
return await notFoundPage(pathname);
|
|
4039
|
+
}
|
|
2972
4040
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2973
|
-
|
|
2974
|
-
|
|
4041
|
+
// F10: in dev the response body carries the real error — message, file:line and the fix hint.
|
|
4042
|
+
let devDetail = '';
|
|
4043
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
4044
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
4045
|
+
const file = esc(String(err.file || ''));
|
|
4046
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
4047
|
+
const hint = esc(String(err.hint || ''));
|
|
4048
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
4049
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
4050
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
4051
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
4052
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
4053
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
4054
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
4055
|
+
+ '</div>';
|
|
4056
|
+
}
|
|
4057
|
+
if (errorPage) {
|
|
4058
|
+
const fb = await renderFallback(pathname, errorPage);
|
|
4059
|
+
return { ...fb, html: fb.html + devDetail, status: 500 };
|
|
4060
|
+
}
|
|
4061
|
+
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
2975
4062
|
}
|
|
2976
4063
|
// __route tells the bootstrap which route this document was rendered for.
|
|
2977
|
-
// A static-file server may serve another route's document (SPA fallback);
|
|
2978
|
-
// the bootstrap then client-renders instead of adopting mismatched DOM.
|
|
2979
4064
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2980
|
-
//
|
|
2981
|
-
|
|
2982
|
-
// asserted csr = false) - the document ships no runtime, no state
|
|
2983
|
-
// script, zero JavaScript. Every other route keeps the bundle. The
|
|
2984
|
-
// caller passes this straight to the shell as js.
|
|
2985
|
-
// Status is the failed action's code when one failed - the page
|
|
2986
|
-
// rendered fine, so the body is the page with the failure visible, and
|
|
2987
|
-
// the status says what happened (a 403 from the guard, a 422 from a
|
|
2988
|
-
// validation action). 200 otherwise.
|
|
2989
|
-
// Lang/dir are the document's <html> attributes - the locale
|
|
2990
|
-
// this route rendered in, and its reading direction.
|
|
2991
|
-
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
|
|
4065
|
+
// 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) .
|
|
4066
|
+
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
|
|
2992
4067
|
}
|
|
2993
4068
|
}
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
4069
|
+
|
|
4070
|
+
|
|
4071
|
+
return await notFoundPage(pathname);
|
|
2998
4072
|
}
|
|
2999
4073
|
|
|
3000
4074
|
// Would renderPageStream handle this path? (matched route = stream, anything
|
|
@@ -3002,21 +4076,20 @@ export async function renderPage(pathname, form) {
|
|
|
3002
4076
|
export function canStream(pathname) {
|
|
3003
4077
|
return routes.some((route) => {
|
|
3004
4078
|
if (!matchRoute(route.pattern, pathname)) return false;
|
|
3005
|
-
//
|
|
3006
|
-
// streamed response cannot change its status - so it takes the buffered
|
|
3007
|
-
// path (renderPage returns the real 404), never the streaming one
|
|
4079
|
+
// I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
|
|
3008
4080
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
3009
4081
|
return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
|
|
3010
4082
|
});
|
|
3011
4083
|
}
|
|
3012
4084
|
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
4085
|
+
|
|
4086
|
+
export function shellOff(pathname) {
|
|
4087
|
+
return routes.some(
|
|
4088
|
+
(route) => route.shell === false && matchRoute(route.pattern, pathname),
|
|
4089
|
+
);
|
|
4090
|
+
}
|
|
4091
|
+
|
|
4092
|
+
// === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
|
|
3020
4093
|
export function isApi(pathname) {
|
|
3021
4094
|
return pathname === '/api' || pathname.startsWith('/api/');
|
|
3022
4095
|
}
|
|
@@ -3040,7 +4113,25 @@ export async function handleApi(method, pathname, request) {
|
|
|
3040
4113
|
headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
|
|
3041
4114
|
});
|
|
3042
4115
|
}
|
|
3043
|
-
|
|
4116
|
+
try {
|
|
4117
|
+
return toResponse(await fn(request));
|
|
4118
|
+
} catch (err) {
|
|
4119
|
+
|
|
4120
|
+
const signal = err && err.__rosetack;
|
|
4121
|
+
if (signal === 'redirect') {
|
|
4122
|
+
return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
|
|
4123
|
+
status: err.status ?? 307,
|
|
4124
|
+
headers: { 'content-type': 'application/json', location: err.path },
|
|
4125
|
+
});
|
|
4126
|
+
}
|
|
4127
|
+
if (signal === 'notFound') {
|
|
4128
|
+
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
4129
|
+
status: 404,
|
|
4130
|
+
headers: { 'content-type': 'application/json' },
|
|
4131
|
+
});
|
|
4132
|
+
}
|
|
4133
|
+
throw err;
|
|
4134
|
+
}
|
|
3044
4135
|
}
|
|
3045
4136
|
}
|
|
3046
4137
|
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
@@ -3049,18 +4140,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
3049
4140
|
});
|
|
3050
4141
|
}
|
|
3051
4142
|
|
|
3052
|
-
// === Streaming SSR ===
|
|
3053
|
-
// The static shell (doctype, <head>, body + container open) flushes BEFORE
|
|
3054
|
-
// the - possibly slow - render completes: the first byte leaves in
|
|
3055
|
-
// microseconds instead of after every $data resolves. The route HTML, the
|
|
3056
|
-
// state script, and the inlined bundle follow as later chunks of one chunked
|
|
3057
|
-
// response - still exactly one request.
|
|
3058
|
-
// The route's <head> tags are NOT in the streamed document: the client
|
|
3059
|
-
// applies them at boot from the body's head markers, so JS users see the
|
|
3060
|
-
// correct head immediately; no-JS consumers of streamed responses get the
|
|
3061
|
-
// static shell head (prerendered files stay complete documents).
|
|
3062
|
-
// Returns 200 (matched; a render throw degrades to the error-page body) or
|
|
3063
|
-
// 404 (unmatched - nothing written, so the caller can still buffer).
|
|
4143
|
+
// === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
|
|
3064
4144
|
export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
3065
4145
|
clearRequestState();
|
|
3066
4146
|
for (const route of routes) {
|
|
@@ -3068,9 +4148,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3068
4148
|
const patternParts = route.pattern.split('/');
|
|
3069
4149
|
const pathParts = pathname.split('/');
|
|
3070
4150
|
for (let i = 0; i < patternParts.length; i++) {
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
4151
|
+
const seg = patternParts[i];
|
|
4152
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
4153
|
+
|
|
4154
|
+
|
|
4155
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
3074
4156
|
}
|
|
3075
4157
|
// i18n: an unknown locale must 404 BEFORE the shell flushes - a
|
|
3076
4158
|
// streamed response cannot change its status afterwards
|
|
@@ -3081,29 +4163,80 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3081
4163
|
try {
|
|
3082
4164
|
html = extractHead(await route.render([], '')).html;
|
|
3083
4165
|
} catch (err) {
|
|
3084
|
-
|
|
3085
|
-
// (the status stays 200 - a real 500 needs the buffered path, which
|
|
3086
|
-
// the server picks for routes known-broken at build time)
|
|
4166
|
+
|
|
3087
4167
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
3088
|
-
|
|
4168
|
+
// F10: dev carries the real error in the body here too — the shell
|
|
4169
|
+
// is out, so the detail rides after the error page body.
|
|
4170
|
+
let devDetail = '';
|
|
4171
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
4172
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
4173
|
+
const file = esc(String(err.file || ''));
|
|
4174
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
4175
|
+
const hint = esc(String(err.hint || ''));
|
|
4176
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
4177
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
4178
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
4179
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
4180
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
4181
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
4182
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
4183
|
+
+ '</div>';
|
|
4184
|
+
}
|
|
4185
|
+
html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
|
|
3089
4186
|
}
|
|
3090
4187
|
write(html);
|
|
3091
|
-
//
|
|
3092
|
-
// ends here - no state script, no inlined bundle. (The servers keep
|
|
3093
|
-
// these routes off the streaming path so their <head> is complete;
|
|
3094
|
-
// this is the correctness floor if one streams anyway.)
|
|
4188
|
+
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
3095
4189
|
if (route.csr === false) {
|
|
3096
4190
|
write('</div>\\n</body>\\n</html>');
|
|
3097
4191
|
return 200;
|
|
3098
4192
|
}
|
|
3099
4193
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
3100
|
-
|
|
4194
|
+
// P1-6 (bug report): the JSON data block is embedded in the document.
|
|
4195
|
+
const stateSafe = state.replace(/</g, '\\\\u003c');
|
|
4196
|
+
write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
|
|
3101
4197
|
return 200;
|
|
3102
4198
|
}
|
|
3103
4199
|
}
|
|
3104
4200
|
return 404;
|
|
3105
4201
|
}
|
|
3106
4202
|
`;
|
|
4203
|
+
try {
|
|
4204
|
+
const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
|
|
4205
|
+
const uniq = [...new Set(patterns)].sort();
|
|
4206
|
+
const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
|
|
4207
|
+
const paramsOf = (pattern: string): string[] =>
|
|
4208
|
+
(pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
|
|
4209
|
+
const paramSig = uniq
|
|
4210
|
+
.map((p) => {
|
|
4211
|
+
const ps = paramsOf(p);
|
|
4212
|
+
if (!ps.length) return "";
|
|
4213
|
+
return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
|
|
4214
|
+
})
|
|
4215
|
+
.join("");
|
|
4216
|
+
const outDirTs = path.join(root, "src", ".rosetack");
|
|
4217
|
+
await fs.promises.mkdir(outDirTs, { recursive: true });
|
|
4218
|
+
const srcLines = [
|
|
4219
|
+
"// GENERATED by rosetack build - do not edit.",
|
|
4220
|
+
"export type RoutePath = " + lit + ";",
|
|
4221
|
+
"export const routePatterns = " + JSON.stringify(uniq) + " as const;",
|
|
4222
|
+
"export type RouteParams = {",
|
|
4223
|
+
paramSig,
|
|
4224
|
+
"};",
|
|
4225
|
+
"/** Build a URL from a route pattern and its params. */",
|
|
4226
|
+
"export function url(",
|
|
4227
|
+
" path: RoutePath,",
|
|
4228
|
+
" params: RouteParams[keyof RouteParams] = {} as never,",
|
|
4229
|
+
"): string {",
|
|
4230
|
+
" let out = path as string;",
|
|
4231
|
+
" for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
|
|
4232
|
+
" out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
|
|
4233
|
+
" }",
|
|
4234
|
+
" return out;",
|
|
4235
|
+
"}",
|
|
4236
|
+
].join("\n") + "\n";
|
|
4237
|
+
await fs.promises.writeFile(path.join(outDirTs, "routes.ts"), srcLines);
|
|
4238
|
+
} catch { /* types are a convenience: never fail the build over them */ }
|
|
4239
|
+
|
|
3107
4240
|
await fs.promises.writeFile(path.join(buildDir, 'server-entry.js'), serverEntry);
|
|
3108
4241
|
await esbuild.build({
|
|
3109
4242
|
entryPoints: [path.join(buildDir, 'server-entry.js')],
|
|
@@ -3115,8 +4248,25 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3115
4248
|
...TS_LOADER,
|
|
3116
4249
|
});
|
|
3117
4250
|
|
|
3118
|
-
|
|
3119
|
-
|
|
4251
|
+
await esbuild.build({
|
|
4252
|
+
entryPoints: [(() => {
|
|
4253
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
4254
|
+
for (const cand of [path.join(here, '..', 'cli', 'prod-server.ts'), path.join(here, '..', 'src', 'cli', 'prod-server.ts')]) {
|
|
4255
|
+
if (fs.existsSync(cand)) return cand;
|
|
4256
|
+
}
|
|
4257
|
+
return path.join(here, '..', 'cli', 'prod-server.ts');
|
|
4258
|
+
})()],
|
|
4259
|
+
bundle: true,
|
|
4260
|
+
outfile: path.join(outDir, 'prod.mjs'),
|
|
4261
|
+
format: 'esm',
|
|
4262
|
+
platform: 'node',
|
|
4263
|
+
write: true,
|
|
4264
|
+
banner: {
|
|
4265
|
+
js: "import { createRequire } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = createRequire(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);"
|
|
4266
|
+
},
|
|
4267
|
+
...TS_LOADER,
|
|
4268
|
+
});
|
|
4269
|
+
|
|
3120
4270
|
const clientImports = split ? '' : compiled
|
|
3121
4271
|
.map((_, i) => ({ i }))
|
|
3122
4272
|
.filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i))
|
|
@@ -3129,18 +4279,12 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3129
4279
|
: `{ pattern: '${info.pattern}', render: ${compose(i)} }`))
|
|
3130
4280
|
.join(',\n ');
|
|
3131
4281
|
|
|
3132
|
-
// P1: the app-global prefetch strategy, declared once (the root layout) as `export const
|
|
3133
|
-
// prefetch = 'off' | 'hover' | 'viewport' | 'all'`.
|
|
3134
4282
|
const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? 'all';
|
|
3135
|
-
// The client-side web-vitals hook, declared once (the root layout) as `export const vitals
|
|
3136
|
-
// = true`. First declaration wins, app-global like prefetch.
|
|
3137
4283
|
const vitalsOn = compiled.some((c) => c.vitals === true);
|
|
3138
|
-
|
|
3139
|
-
|
|
4284
|
+
const vitalsBlock = vitalsOn
|
|
4285
|
+
? `\n// the app asked for web-vitals - measure once, at boot, and let the\n// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).\nreportVitals();\n`
|
|
3140
4286
|
: '';
|
|
3141
4287
|
|
|
3142
|
-
// The <html lang dir> tracker only exists when the app actually has a [lang] route - an
|
|
3143
|
-
// app without i18n pays nothing for it …
|
|
3144
4288
|
const hasLang = infos.some((i) => i.pattern.includes(':lang'));
|
|
3145
4289
|
const langDirBlock = hasLang
|
|
3146
4290
|
? ` // <html lang dir> follows the route - the one part of the document
|
|
@@ -3148,38 +4292,33 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3148
4292
|
// logical properties both read it). A route with no [lang] segment
|
|
3149
4293
|
// returns to the default locale, and a bogus segment falls back to it
|
|
3150
4294
|
// too, exactly like the server's docAttrs.
|
|
4295
|
+
// Only when this container IS the document's app root. A mount
|
|
4296
|
+
// (dist/mount.js) renders into a foreign page, whose language and
|
|
4297
|
+
// direction belong to the host, not to the mounted route.
|
|
3151
4298
|
const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
|
|
3152
4299
|
const known = !seg || isLocale(seg);
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
4300
|
+
if (container === document.getElementById('app')) {
|
|
4301
|
+
const docLang = known && seg ? seg : __defLocale;
|
|
4302
|
+
document.documentElement.lang = docLang;
|
|
4303
|
+
const docDir = localeDir(docLang);
|
|
4304
|
+
if (docDir) document.documentElement.setAttribute('dir', docDir);
|
|
4305
|
+
else document.documentElement.removeAttribute('dir');
|
|
4306
|
+
}
|
|
3158
4307
|
if (!known) {`
|
|
3159
4308
|
: ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
3160
4309
|
|
|
3161
4310
|
const clientEntry = `
|
|
3162
4311
|
${clientImports}
|
|
3163
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
|
|
3164
|
-
|
|
3165
|
-
//
|
|
3166
|
-
// renders any PRELOADED locale from the bundle, so switching language costs
|
|
3167
|
-
// zero requests (the same bet as the inlined route table). a locale
|
|
3168
|
-
// the app left out of the preload (i18n.preload in rosetack.config.js) is a
|
|
3169
|
-
// pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
|
|
3170
|
-
// on first use - one request per language per session, then it renders from
|
|
3171
|
-
// memory like any other. The default build preloads everything and ships no
|
|
3172
|
-
// packs at all.
|
|
4312
|
+
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
|
|
4313
|
+
|
|
4314
|
+
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
3173
4315
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
3174
4316
|
setLocalePacks(${JSON.stringify(packed)});
|
|
3175
4317
|
${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
|
|
3176
4318
|
// follow a route that carries no [lang] segment (a non-i18n page)
|
|
3177
4319
|
const __defLocale = '${defaultLocale}';` : ''}
|
|
3178
4320
|
${vitalsOn ? `// the app asked for web-vitals. The import is what keeps\n// reportVitals alive through minification and tree-shaking; the call is one\n// statement at boot, before the first render.\nimport { reportVitals } from './runtime.js';`: ''}
|
|
3179
|
-
// The two pack doors, re-exported for an app that wants to warm a language
|
|
3180
|
-
// before its visitor asks for it (ensureLocale) or to feed a dictionary it
|
|
3181
|
-
// fetched itself (loadLocale). Both are already in the bundle - ensureLocale
|
|
3182
|
-
// is what applyParams calls - so the re-export costs the statement alone.
|
|
4321
|
+
// 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.
|
|
3183
4322
|
export { ensureLocale, loadLocale } from './runtime.js';
|
|
3184
4323
|
${vitalsBlock}
|
|
3185
4324
|
|
|
@@ -3187,14 +4326,7 @@ const routes = [
|
|
|
3187
4326
|
${clientRoutes}
|
|
3188
4327
|
];
|
|
3189
4328
|
|
|
3190
|
-
// === Mode B: lazy route chunks ===
|
|
3191
|
-
// Split mode's registry entries arrive without a render function: loadChain
|
|
3192
|
-
// loads the route's module graph (the page plus its layouts, one chunk per
|
|
3193
|
-
// module, the shared runtime in its own vendor chunk) in parallel and
|
|
3194
|
-
// composes it at runtime - the exact nesting compose() built at compile
|
|
3195
|
-
// time for inline mode. getRender memoizes the composed function on the
|
|
3196
|
-
// entry, so a chunk loads once per session; inline mode's entries are the
|
|
3197
|
-
// render functions themselves, so the helper is a pass-through there.
|
|
4329
|
+
// === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
|
|
3198
4330
|
const loadChain = async (loaders) => {
|
|
3199
4331
|
const mods = await Promise.all(loaders.map((load) => load()));
|
|
3200
4332
|
let expr = (closes, children) => mods[0].render(closes, children);
|
|
@@ -3210,36 +4342,62 @@ const getRender = async (route) => {
|
|
|
3210
4342
|
return (route.render ??= (await route.load()).render);
|
|
3211
4343
|
};
|
|
3212
4344
|
|
|
3213
|
-
// pages
|
|
3214
|
-
const
|
|
4345
|
+
// Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
|
|
4346
|
+
const notFoundRoutes = ${notFoundTable};
|
|
4347
|
+
const notFoundFor = (pathname) => {
|
|
4348
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
4349
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
4350
|
+
}
|
|
4351
|
+
return null;
|
|
4352
|
+
};
|
|
3215
4353
|
|
|
3216
|
-
//
|
|
3217
|
-
// whose render throws on the client degrades to this instead of breaking
|
|
3218
|
-
// navigation.
|
|
4354
|
+
// 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.
|
|
3219
4355
|
const errorPage = ${errorRender};
|
|
3220
4356
|
|
|
3221
4357
|
// Paint a fallback page (404/500) into the container, wired like any render.
|
|
3222
|
-
async function paintFallback(container, page, builtin) {
|
|
3223
|
-
|
|
3224
|
-
clearRequestState();
|
|
4358
|
+
async function paintFallback(container, page, builtin, keepState = false) {
|
|
4359
|
+
if (!keepState) __navReset(container);
|
|
3225
4360
|
clearMounts(); // a failed render leaves stale mounts behind
|
|
3226
4361
|
// inline mode passes the render itself; split mode passes a loader
|
|
3227
4362
|
const render = page ? await getRender(page) : null;
|
|
3228
4363
|
if (render) {
|
|
3229
4364
|
const closes = [];
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
4365
|
+
await __withOwner(container, async () => {
|
|
4366
|
+
const html = await render(closes, '');
|
|
4367
|
+
container.innerHTML = html;
|
|
4368
|
+
wire(container, closes);
|
|
4369
|
+
bindEvents(container);
|
|
4370
|
+
flushMounts();
|
|
4371
|
+
});
|
|
3235
4372
|
return;
|
|
3236
4373
|
}
|
|
3237
4374
|
container.innerHTML = builtin;
|
|
3238
4375
|
}
|
|
3239
4376
|
|
|
4377
|
+
|
|
4378
|
+
export async function startNotFound(container, pathname) {
|
|
4379
|
+
const el = document.getElementById('__rosetack_state');
|
|
4380
|
+
if (el) resumeState(el.textContent);
|
|
4381
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
|
|
4382
|
+
}
|
|
4383
|
+
|
|
3240
4384
|
export function matchRoute(pattern, pathname) {
|
|
4385
|
+
// Q0 (bug report): one canonical URL per route.
|
|
4386
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
3241
4387
|
const patternParts = pattern.split('/');
|
|
3242
4388
|
const pathParts = pathname.split('/');
|
|
4389
|
+
|
|
4390
|
+
const last = patternParts[patternParts.length - 1];
|
|
4391
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
4392
|
+
const fixed = patternParts.slice(0, -1);
|
|
4393
|
+
if (pathParts.length < fixed.length) return false;
|
|
4394
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
4395
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
4396
|
+
if (fixed[i].startsWith(':')) continue;
|
|
4397
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
4398
|
+
}
|
|
4399
|
+
return true;
|
|
4400
|
+
}
|
|
3243
4401
|
if (patternParts.length !== pathParts.length) return false;
|
|
3244
4402
|
for (let i = 0; i < patternParts.length; i++) {
|
|
3245
4403
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -3248,85 +4406,64 @@ export function matchRoute(pattern, pathname) {
|
|
|
3248
4406
|
return true;
|
|
3249
4407
|
}
|
|
3250
4408
|
|
|
3251
|
-
// === Link prefetch ===
|
|
3252
|
-
// Hover / focus / touch an internal link and the target route renders NOW -
|
|
3253
|
-
// $data included - against a throwaway signal map. The click that follows
|
|
3254
|
-
// paints from the cached HTML: no await, no request, no spinner. Other
|
|
3255
|
-
// frameworks prefetch data only; rosetack prefetches the whole render because
|
|
3256
|
-
// the inlined bundle already contains every route.
|
|
3257
|
-
// Trade-off: the cache holds either a result or the in-flight promise (dedupes
|
|
3258
|
-
// hover storms); one isolated render runs at a time so signal-map swapping
|
|
3259
|
-
// stays correct without any merging logic. Entries are single-use: a consumed
|
|
3260
|
-
// entry disappears from the cache, which is also how tests observe a hit.
|
|
3261
|
-
// P1, three guards for link-heavy pages:
|
|
3262
|
-
// 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
|
|
3263
|
-
// 'viewport' | 'all'" (root layout); 'all' is the original behavior.
|
|
3264
|
-
// Trade-off: app-global, not per-route - per-route would carry the mode
|
|
3265
|
-
// in each document's shell.
|
|
3266
|
-
// 2. budget - renders are serialized by the queue, so "concurrency" is 1;
|
|
3267
|
-
// the budget caps the QUEUE: a hover storm past it drops the excess
|
|
3268
|
-
// instead of rendering fifty routes nobody clicks.
|
|
3269
|
-
// 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
|
|
3270
|
-
// is evicted first (Map iteration order; entries are single-use, so
|
|
3271
|
-
// insertion order IS the recency order).
|
|
4409
|
+
// === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
|
|
3272
4410
|
let prefetchMode = ${JSON.stringify(prefetchMode)};
|
|
3273
4411
|
export function setPrefetchMode(mode) { prefetchMode = mode; }
|
|
3274
4412
|
const PREFETCH_BUDGET = 8;
|
|
3275
4413
|
const PREFETCH_MAX_CACHED = 4;
|
|
3276
|
-
const prefetchCache = new Map();
|
|
4414
|
+
const prefetchCache = new Map();
|
|
3277
4415
|
let prefetchQueue = Promise.resolve();
|
|
3278
4416
|
let prefetchPending = 0;
|
|
3279
4417
|
|
|
3280
|
-
|
|
3281
|
-
// a runtime pack (i18n.preload) is awaited HERE - the one place every client
|
|
3282
|
-
// render path goes through (navigation, prefetch, action adopt) - so a packed
|
|
3283
|
-
// locale costs one request per session and then renders from memory. A
|
|
3284
|
-
// preloaded locale (the default: every dictionary inline) resolves without
|
|
3285
|
-
// touching the network, so the common path stays synchronous in spirit.
|
|
4418
|
+
|
|
3286
4419
|
async function applyParams(route, pathname) {
|
|
3287
4420
|
const patternParts = route.pattern.split('/');
|
|
3288
4421
|
const pathParts = pathname.split('/');
|
|
3289
4422
|
for (let i = 0; i < patternParts.length; i++) {
|
|
3290
|
-
|
|
4423
|
+
const seg = patternParts[i];
|
|
4424
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
4425
|
+
|
|
4426
|
+
|
|
4427
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
3291
4428
|
}
|
|
3292
4429
|
const langIdx = patternParts.indexOf(':lang');
|
|
3293
4430
|
if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
|
|
3294
4431
|
}
|
|
3295
4432
|
|
|
4433
|
+
|
|
4434
|
+
function __netOk() {
|
|
4435
|
+
const c = navigator.connection;
|
|
4436
|
+
if (!c) return true;
|
|
4437
|
+
if (c.saveData) return false;
|
|
4438
|
+
const t = c.effectiveType;
|
|
4439
|
+
return t !== 'slow-2g' && t !== '2g';
|
|
4440
|
+
}
|
|
4441
|
+
|
|
3296
4442
|
export function prefetch(pathname, source = 'hover') {
|
|
3297
4443
|
if (prefetchMode === 'off') return;
|
|
3298
4444
|
if (prefetchMode === 'hover' && source !== 'hover') return;
|
|
3299
4445
|
if (prefetchMode === 'viewport' && source !== 'viewport') return;
|
|
4446
|
+
if (!__netOk()) return; // save-data / 2g: no bytes before the click
|
|
3300
4447
|
if (prefetchCache.has(pathname)) return;
|
|
3301
|
-
if (pathname === location.pathname) return;
|
|
4448
|
+
if (pathname === location.pathname) return;
|
|
3302
4449
|
const route = routes.find((r) => matchRoute(r.pattern, pathname));
|
|
3303
4450
|
if (!route) return;
|
|
3304
|
-
if (prefetchPending >= PREFETCH_BUDGET) return; //
|
|
3305
|
-
// P0-1: the link may carry a query (/search?q=cats). $query() reads the
|
|
3306
|
-
// browser's own URL, which is the page being LEFT - so the prefetched
|
|
3307
|
-
// render would see the wrong one. Override it for the duration and clear
|
|
3308
|
-
// it after; the queue below serializes renders, so one slot is enough.
|
|
4451
|
+
if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
|
|
3309
4452
|
const qi = pathname.indexOf('?');
|
|
3310
4453
|
const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
|
|
3311
4454
|
const p = prefetchQueue.then(async () => {
|
|
3312
4455
|
try {
|
|
3313
4456
|
setPrefetchOverride(qOverride);
|
|
3314
|
-
//
|
|
3315
|
-
// queued and the onCleanup disposers it registered: the paint that
|
|
3316
|
-
// consumes this entry replays the mounts after wiring and adopts the
|
|
3317
|
-
// cleanups, so the prefetched route's timers are disposed on the next
|
|
3318
|
-
// navigation like any live route's
|
|
4457
|
+
// The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
|
|
3319
4458
|
const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
|
|
3320
4459
|
await applyParams(route, pathname); // a packed locale's dictionary lands before the render
|
|
3321
4460
|
const closes = [];
|
|
3322
|
-
const render = await getRender(route);
|
|
4461
|
+
const render = await getRender(route);
|
|
3323
4462
|
const html = await render(closes, '');
|
|
3324
4463
|
return { html, closes };
|
|
3325
4464
|
});
|
|
3326
4465
|
const entry = { ...result, state, mounts, cleanups };
|
|
3327
|
-
prefetchCache.set(pathname, entry); //
|
|
3328
|
-
// evict oldest-first; in-flight promises are never evicted (evicting
|
|
3329
|
-
// one would only force a duplicate render)
|
|
4466
|
+
prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
|
|
3330
4467
|
while (prefetchCache.size > PREFETCH_MAX_CACHED) {
|
|
3331
4468
|
const oldest = prefetchCache.keys().next().value;
|
|
3332
4469
|
if (prefetchCache.get(oldest) instanceof Promise) break;
|
|
@@ -3334,7 +4471,7 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
3334
4471
|
}
|
|
3335
4472
|
return entry;
|
|
3336
4473
|
} catch {
|
|
3337
|
-
prefetchCache.delete(pathname);
|
|
4474
|
+
prefetchCache.delete(pathname);
|
|
3338
4475
|
return null;
|
|
3339
4476
|
} finally {
|
|
3340
4477
|
setPrefetchOverride(null);
|
|
@@ -3347,13 +4484,10 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
3347
4484
|
}
|
|
3348
4485
|
|
|
3349
4486
|
export function prefetchStats() {
|
|
3350
|
-
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
|
|
4487
|
+
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
|
|
3351
4488
|
}
|
|
3352
4489
|
|
|
3353
|
-
// One delegated listener per event type on the app container: survives DOM
|
|
3354
|
-
// swaps and cloned blocks, so handlers never need re-binding. A handler
|
|
3355
|
-
// compiled from a server action (data-on-*="$action:name") dispatches to
|
|
3356
|
-
// $action instead of the local handler registry.
|
|
4490
|
+
// One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
|
|
3357
4491
|
const DELEGATED = ['click', 'input', 'change', 'submit'];
|
|
3358
4492
|
function bindEvents(container) {
|
|
3359
4493
|
if (container.__rosetack_bound) return;
|
|
@@ -3370,48 +4504,76 @@ function bindEvents(container) {
|
|
|
3370
4504
|
}
|
|
3371
4505
|
}
|
|
3372
4506
|
|
|
3373
|
-
// === Server actions from any event ===
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
async function postForm(body) {
|
|
3380
|
-
const res = await fetch(location.pathname, { method: 'POST', body });
|
|
4507
|
+
// === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
|
|
4508
|
+
async function postForm(body, container, pathname) {
|
|
4509
|
+
|
|
4510
|
+
const box = container || document.getElementById('app');
|
|
4511
|
+
const route = pathname || location.pathname;
|
|
4512
|
+
const res = await fetch(route, { method: 'POST', body });
|
|
3381
4513
|
const html = await res.text();
|
|
3382
4514
|
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
3383
4515
|
const next = doc.getElementById('app');
|
|
3384
4516
|
const st = doc.getElementById('__rosetack_state');
|
|
3385
4517
|
const paint = () => {
|
|
3386
|
-
|
|
3387
|
-
adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
|
|
4518
|
+
adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
|
|
3388
4519
|
};
|
|
3389
4520
|
if (document.startViewTransition) document.startViewTransition(paint);
|
|
3390
4521
|
else paint();
|
|
3391
4522
|
}
|
|
3392
4523
|
|
|
3393
|
-
// Call a page's server action by name from any event handler:
|
|
3394
|
-
// <button on:click={like}> compiles to $action('like'). Without JS the
|
|
3395
|
-
// binding is inert - the progressive-enhancement story stays with forms.
|
|
4524
|
+
// Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
|
|
3396
4525
|
export async function $action(name, e) {
|
|
3397
4526
|
if (e && e.preventDefault) e.preventDefault();
|
|
3398
4527
|
const body = new FormData();
|
|
3399
4528
|
body.append('__action', name);
|
|
3400
|
-
|
|
4529
|
+
// An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
|
|
4530
|
+
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
4531
|
+
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
3401
4532
|
}
|
|
4533
|
+
// F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
|
|
4534
|
+
setActionDispatcher($action);
|
|
3402
4535
|
|
|
3403
4536
|
export { postForm };
|
|
3404
4537
|
|
|
3405
|
-
// The live signal graph as JSON - the same serializeState the zero-hydration
|
|
3406
|
-
// resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
|
|
3407
|
-
// can hand it to the dev server's reload bridge and to a devtools extension.
|
|
3408
|
-
// A local re-export on purpose: it keeps the binding alive through minification
|
|
3409
|
-
// for the bootstrap text appended after the bundle.
|
|
4538
|
+
// The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
|
|
3410
4539
|
export { serializeState };
|
|
3411
4540
|
|
|
3412
|
-
//
|
|
3413
|
-
|
|
3414
|
-
|
|
4541
|
+
// Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
|
|
4542
|
+
|
|
4543
|
+
|
|
4544
|
+
function __ownsDoc(container) {
|
|
4545
|
+
return container === document.getElementById('app');
|
|
4546
|
+
}
|
|
4547
|
+
function __navReset(container) {
|
|
4548
|
+
if (__ownsDoc(container)) {
|
|
4549
|
+
resetEffects();
|
|
4550
|
+
clearRequestState();
|
|
4551
|
+
} else {
|
|
4552
|
+
resetContainerFx(container);
|
|
4553
|
+
}
|
|
4554
|
+
}
|
|
4555
|
+
// Attribute everything a render creates (state keys, effects, onCleanups) to
|
|
4556
|
+
// its container. The document path sets no owner and keeps the global sets.
|
|
4557
|
+
async function __withOwner(container, fn) {
|
|
4558
|
+
if (__ownsDoc(container)) return fn();
|
|
4559
|
+
setFxOwner(container);
|
|
4560
|
+
try {
|
|
4561
|
+
return await fn();
|
|
4562
|
+
} finally {
|
|
4563
|
+
setFxOwner(null);
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
4566
|
+
// View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
|
|
4567
|
+
async function __swap(container, html) {
|
|
4568
|
+
const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
4569
|
+
if (typeof document.startViewTransition === 'function' && !reduce) {
|
|
4570
|
+
const vt = document.startViewTransition(() => { container.innerHTML = html; });
|
|
4571
|
+
await vt.updateCallbackDone.catch(() => {});
|
|
4572
|
+
} else {
|
|
4573
|
+
container.innerHTML = html;
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
4576
|
+
|
|
3415
4577
|
export async function start(container, pathname, initial) {
|
|
3416
4578
|
clearMounts(); // stale mounts from a failed render never fire
|
|
3417
4579
|
if (initial) {
|
|
@@ -3420,104 +4582,113 @@ export async function start(container, pathname, initial) {
|
|
|
3420
4582
|
}
|
|
3421
4583
|
for (const route of routes) {
|
|
3422
4584
|
if (matchRoute(route.pattern, pathname)) {
|
|
3423
|
-
//
|
|
3424
|
-
// (before the prefetch check: a cached entry for a bogus locale is
|
|
3425
|
-
// discarded, never painted)
|
|
4585
|
+
// 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).
|
|
3426
4586
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
3427
4587
|
${langDirBlock}
|
|
3428
|
-
await paintFallback(container,
|
|
4588
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
3429
4589
|
return;
|
|
3430
4590
|
}
|
|
3431
|
-
// Prefetched on hover/focus/touch: the render already ran, so paint its
|
|
3432
|
-
// HTML and adopt its signal entries - events then patch the very nodes
|
|
3433
|
-
// we wire, and no $data re-runs on click.
|
|
4591
|
+
// 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.
|
|
3434
4592
|
let hit = initial ? undefined : prefetchCache.get(pathname);
|
|
3435
4593
|
if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
|
|
3436
4594
|
if (hit) {
|
|
3437
|
-
prefetchCache.delete(pathname);
|
|
3438
|
-
|
|
4595
|
+
prefetchCache.delete(pathname);
|
|
4596
|
+
__navReset(container);
|
|
3439
4597
|
restoreState(hit.state);
|
|
3440
|
-
container
|
|
3441
|
-
|
|
4598
|
+
await __swap(container, hit.html);
|
|
4599
|
+
await __withOwner(container, () => {
|
|
4600
|
+
wire(container, hit.closes);
|
|
4601
|
+
bindEvents(container);
|
|
4602
|
+
hit.mounts.forEach((fn) => fn());
|
|
4603
|
+
adoptCleanups(hit.cleanups);
|
|
4604
|
+
});
|
|
4605
|
+
return;
|
|
4606
|
+
}
|
|
4607
|
+
if (!initial) __navReset(container);
|
|
4608
|
+
let broken = false;
|
|
4609
|
+
let signal = null;
|
|
4610
|
+
await __withOwner(container, async () => {
|
|
4611
|
+
await applyParams(route, pathname);
|
|
4612
|
+
const closes = [];
|
|
4613
|
+
let html;
|
|
4614
|
+
try {
|
|
4615
|
+
const render = await getRender(route);
|
|
4616
|
+
html = await render(closes, '');
|
|
4617
|
+
} catch (err) {
|
|
4618
|
+
|
|
4619
|
+
if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
|
|
4620
|
+
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
4621
|
+
|
|
4622
|
+
|
|
4623
|
+
console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
|
|
4624
|
+
broken = true;
|
|
4625
|
+
return;
|
|
4626
|
+
}
|
|
4627
|
+
if (!initial) await __swap(container, html);
|
|
4628
|
+
wire(container, closes);
|
|
3442
4629
|
bindEvents(container);
|
|
3443
|
-
|
|
3444
|
-
|
|
4630
|
+
flushMounts();
|
|
4631
|
+
});
|
|
4632
|
+
if (signal === 'notFound') {
|
|
4633
|
+
// T17: a client-side render of a $data route without a prefetch entry has no data source (the server fills the context bag) - the correct.
|
|
4634
|
+
if (!initial) { try { location.assign(pathname); return; } catch { } }
|
|
4635
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
3445
4636
|
return;
|
|
3446
4637
|
}
|
|
3447
|
-
if (
|
|
3448
|
-
|
|
3449
|
-
|
|
4638
|
+
if (signal) {
|
|
4639
|
+
location.href = signal;
|
|
4640
|
+
return;
|
|
3450
4641
|
}
|
|
3451
|
-
|
|
3452
|
-
const closes = [];
|
|
3453
|
-
let html;
|
|
3454
|
-
try {
|
|
3455
|
-
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
3456
|
-
html = await render(closes, '');
|
|
3457
|
-
} catch {
|
|
3458
|
-
// the route itself is broken: degrade to pages/500.rose (or the
|
|
3459
|
-
// built-in plain 500) instead of leaving the container empty
|
|
4642
|
+
if (broken) {
|
|
3460
4643
|
await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
3461
|
-
return;
|
|
3462
4644
|
}
|
|
3463
|
-
if (!initial) container.innerHTML = html;
|
|
3464
|
-
wire(container, closes);
|
|
3465
|
-
bindEvents(container);
|
|
3466
|
-
flushMounts();
|
|
3467
4645
|
return;
|
|
3468
4646
|
}
|
|
3469
4647
|
}
|
|
3470
|
-
//
|
|
3471
|
-
|
|
3472
|
-
//
|
|
3473
|
-
|
|
3474
|
-
|
|
3475
|
-
|
|
4648
|
+
// Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
|
|
4649
|
+
${hasLang ? ` // the same app-root gate as above - a mount never touches the
|
|
4650
|
+
// host document's language or direction.
|
|
4651
|
+
if (container === document.getElementById('app')) {
|
|
4652
|
+
document.documentElement.lang = __defLocale;
|
|
4653
|
+
document.documentElement.removeAttribute('dir');
|
|
4654
|
+
}` : ''}
|
|
4655
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
3476
4656
|
}
|
|
3477
4657
|
|
|
3478
|
-
// Adopt a server-rendered response in place - the JS-enabled half of
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
export async function adopt(container, html, stateJson) {
|
|
3485
|
-
resetEffects();
|
|
3486
|
-
clearRequestState();
|
|
4658
|
+
// Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
|
|
4659
|
+
export async function adopt(container, html, stateJson, pathname) {
|
|
4660
|
+
|
|
4661
|
+
|
|
4662
|
+
const route0 = pathname || location.pathname;
|
|
4663
|
+
__navReset(container);
|
|
3487
4664
|
clearMounts(); // stale mounts from a failed render never fire
|
|
3488
4665
|
resumeState(stateJson);
|
|
3489
4666
|
container.innerHTML = html;
|
|
3490
|
-
|
|
4667
|
+
|
|
3491
4668
|
const st = document.getElementById('__rosetack_state');
|
|
3492
4669
|
if (st) st.textContent = stateJson;
|
|
3493
4670
|
for (const route of routes) {
|
|
3494
|
-
if (matchRoute(route.pattern,
|
|
3495
|
-
await
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
4671
|
+
if (matchRoute(route.pattern, route0)) {
|
|
4672
|
+
await __withOwner(container, async () => {
|
|
4673
|
+
await applyParams(route, route0);
|
|
4674
|
+
const closes = [];
|
|
4675
|
+
try {
|
|
4676
|
+
const render = await getRender(route);
|
|
4677
|
+
await render(closes, '');
|
|
4678
|
+
} catch {
|
|
4679
|
+
|
|
4680
|
+
|
|
4681
|
+
return;
|
|
4682
|
+
}
|
|
4683
|
+
wire(container, closes);
|
|
4684
|
+
bindEvents(container);
|
|
4685
|
+
flushMounts();
|
|
4686
|
+
});
|
|
3508
4687
|
return;
|
|
3509
4688
|
}
|
|
3510
4689
|
}
|
|
3511
4690
|
}
|
|
3512
|
-
// === refresh() implementation ===
|
|
3513
|
-
// Re-render the current route in place: the client half of router.refresh()
|
|
3514
|
-
// (a router refresh) / (a full invalidation). Same machinery as a client-side
|
|
3515
|
-
// navigation to the current path - $data re-runs, state re-seeds from the
|
|
3516
|
-
// fresh render, wire() patches the marked nodes - but a refresh never lands
|
|
3517
|
-
// a prefetch entry: a hover from a minute ago is exactly what it exists to
|
|
3518
|
-
// bypass. Zero requests: the render (and its $data) runs in the page.
|
|
3519
|
-
// Trade-off: state resets like navigation (no per-key retention); add
|
|
3520
|
-
// retention when an app needs refresh-without-losing-input.
|
|
4691
|
+
// === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
|
|
3521
4692
|
setRefreshHook(async () => {
|
|
3522
4693
|
prefetchCache.delete(location.pathname);
|
|
3523
4694
|
await start(document.getElementById('app'), location.pathname, false);
|
|
@@ -3525,8 +4696,6 @@ setRefreshHook(async () => {
|
|
|
3525
4696
|
`;
|
|
3526
4697
|
await fs.promises.writeFile(path.join(buildDir, 'client-entry.js'), clientEntry);
|
|
3527
4698
|
if (split) {
|
|
3528
|
-
// Mode B: esbuild code splitting. One chunk per route module, the shared runtime in its
|
|
3529
|
-
// own vendor chunk …
|
|
3530
4699
|
await fs.promises.rm(path.join(outDir, 'chunks'), { recursive: true, force: true });
|
|
3531
4700
|
await esbuild.build({
|
|
3532
4701
|
entryPoints: [path.join(buildDir, 'client-entry.js')],
|
|
@@ -3549,36 +4718,57 @@ setRefreshHook(async () => {
|
|
|
3549
4718
|
format: 'esm',
|
|
3550
4719
|
platform: 'browser',
|
|
3551
4720
|
minify: true,
|
|
4721
|
+
|
|
3552
4722
|
write: true,
|
|
3553
4723
|
...TS_LOADER,
|
|
3554
4724
|
});
|
|
3555
4725
|
}
|
|
3556
4726
|
|
|
3557
|
-
|
|
4727
|
+
await fs.promises.writeFile(path.join(outDir, 'mount.js'), MOUNT_ENTRY);
|
|
4728
|
+
|
|
3558
4729
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
3559
4730
|
|
|
3560
4731
|
const publicDir = path.join(root, 'public');
|
|
3561
4732
|
if (fs.existsSync(publicDir)) {
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
);
|
|
4733
|
+
await fs.promises.cp(publicDir, path.join(outDir, 'public'), { recursive: true });
|
|
4734
|
+
// Browsers ask for /favicon.ico without being told to: an app that ships one in public/
|
|
4735
|
+
// gets it at the root of the build too, so every server …
|
|
4736
|
+
const favicon = path.join(publicDir, 'favicon.ico');
|
|
4737
|
+
if (fs.existsSync(favicon)) await fs.promises.copyFile(favicon, path.join(outDir, 'favicon.ico'));
|
|
3568
4738
|
}
|
|
3569
4739
|
|
|
3570
|
-
// The build's zero-JS lint report - every route, its verdict, and the reason. Printed on
|
|
3571
|
-
// every build (dev rebuilds included) so the decision is auditable instead of silent.
|
|
3572
4740
|
console.log('rosetack zero-JS report:');
|
|
3573
4741
|
for (const line of buildReport(infos, compiled)) console.log(' ' + line);
|
|
4742
|
+
const warnGroups = new Map<string, { why: string; files: Map<string, Set<string>> }>();
|
|
3574
4743
|
for (const { info, i } of pages) {
|
|
3575
4744
|
if (!routeShipsNoJs(infos, compiled, i)) continue;
|
|
3576
4745
|
for (const ci of [i, ...layoutsOf(infos, i)]) {
|
|
3577
4746
|
for (const w of compiled[ci].jsWarnings ?? []) {
|
|
3578
|
-
|
|
4747
|
+
let g = warnGroups.get(w);
|
|
4748
|
+
if (!g) {
|
|
4749
|
+
g = { why: w, files: new Map() };
|
|
4750
|
+
warnGroups.set(w, g);
|
|
4751
|
+
}
|
|
4752
|
+
const file = path.relative(root, infos[ci].filePath).replace(/\\/g, '/');
|
|
4753
|
+
let routes = g.files.get(file);
|
|
4754
|
+
if (!routes) {
|
|
4755
|
+
routes = new Set();
|
|
4756
|
+
g.files.set(file, routes);
|
|
4757
|
+
}
|
|
4758
|
+
routes.add(info.routePath);
|
|
3579
4759
|
}
|
|
3580
4760
|
}
|
|
3581
4761
|
}
|
|
4762
|
+
for (const g of warnGroups.values()) {
|
|
4763
|
+
const allRoutes = new Set<string>();
|
|
4764
|
+
for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
|
|
4765
|
+
const parts = [...g.files.entries()]
|
|
4766
|
+
.sort((a, b) => b[1].size - a[1].size)
|
|
4767
|
+
.map(([file, routes]) => `${file} (${routes.size === 1 ? [...routes][0] : `${routes.size} routes`})`);
|
|
4768
|
+
const shown = parts.slice(0, 4).join(', ');
|
|
4769
|
+
const more = parts.length > 4 ? `, +${parts.length - 4} more files` : '';
|
|
4770
|
+
console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
|
|
4771
|
+
}
|
|
3582
4772
|
|
|
3583
4773
|
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
3584
4774
|
}
|
|
@@ -3634,26 +4824,24 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
|
|
|
3634
4824
|
const relative = path.relative(pagesDir, filePath).replace(/\\/g, '/');
|
|
3635
4825
|
const withoutExt = relative.replace(/\.rose$/, '');
|
|
3636
4826
|
const base = path.posix.basename(withoutExt);
|
|
3637
|
-
// A component (src/components/**) is not a route at all - it is imported by one.
|
|
3638
|
-
// Everything below still runs so a broken file reports a sane routePath in build errors …
|
|
3639
4827
|
const isComponent = filePath.replace(/\\/g, '/').includes('/src/components/');
|
|
3640
4828
|
const isLayout = !isComponent && base === '_layout';
|
|
3641
|
-
const isNotFound = !isComponent && base === '404';
|
|
4829
|
+
const isNotFound = !isComponent && (base === '404' || base === '_notfound');
|
|
3642
4830
|
const isError = !isComponent && base === '500';
|
|
3643
|
-
// pages/api/*.rose: Web-standard handler routes (JSON in, JSON out), never
|
|
3644
|
-
// HTML pages - they dispatch by method and never reach the client bundle.
|
|
3645
4831
|
const isApi = !isComponent && (withoutExt === 'api' || withoutExt.startsWith('api/'));
|
|
3646
|
-
// pages/_middleware.rose: the request interceptor. It runs before every render and is not
|
|
3647
|
-
// a route: it matches nothing and never reaches the client bundle.
|
|
3648
4832
|
const isMiddleware = !isComponent && withoutExt === '_middleware';
|
|
3649
4833
|
|
|
3650
|
-
let parts = withoutExt.split('/').filter((p) => p !== '_layout');
|
|
3651
|
-
// a trailing `index` segment names its directory (blog/index -> /blog,
|
|
3652
|
-
// api/index -> /api); only the root index collapses to '/'
|
|
4834
|
+
let parts = withoutExt.split('/').filter((p) => p !== '_layout' && p !== '_notfound');
|
|
3653
4835
|
if (parts.length > 1 && parts[parts.length - 1] === 'index') parts = parts.slice(0, -1);
|
|
3654
|
-
const
|
|
3655
|
-
|
|
3656
|
-
)
|
|
4836
|
+
const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
|
|
4837
|
+
const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
|
|
4838
|
+
const routeParts = parts.map((part) => {
|
|
4839
|
+
const optional = OPTIONAL_CATCH_ALL.exec(part);
|
|
4840
|
+
if (optional) return `**${optional[1]}`;
|
|
4841
|
+
const catchAll = CATCH_ALL.exec(part);
|
|
4842
|
+
if (catchAll) return `*${catchAll[1]}`;
|
|
4843
|
+
return part.startsWith('[') && part.endsWith(']') ? `:${part.slice(1, -1)}` : part;
|
|
4844
|
+
});
|
|
3657
4845
|
|
|
3658
4846
|
let routePath: string;
|
|
3659
4847
|
if (routeParts.length === 0 || (routeParts.length === 1 && routeParts[0] === 'index')) {
|
|
@@ -3666,7 +4854,13 @@ function getRouteInfo(filePath: string, root: string): RouteInfo {
|
|
|
3666
4854
|
filePath,
|
|
3667
4855
|
routePath,
|
|
3668
4856
|
pattern: routePath,
|
|
3669
|
-
paramNames: parts.
|
|
4857
|
+
paramNames: parts.flatMap((p) => {
|
|
4858
|
+
const optional = OPTIONAL_CATCH_ALL.exec(p);
|
|
4859
|
+
if (optional) return [optional[1]];
|
|
4860
|
+
const catchAll = CATCH_ALL.exec(p);
|
|
4861
|
+
if (catchAll) return [catchAll[1]];
|
|
4862
|
+
return p.startsWith('[') && p.endsWith(']') ? [p.slice(1, -1)] : [];
|
|
4863
|
+
}),
|
|
3670
4864
|
isLayout,
|
|
3671
4865
|
isNotFound,
|
|
3672
4866
|
isError,
|