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