clarusjs 0.4.0 → 0.5.0
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/README.md +1 -1
- package/dist/check/generate.d.ts +17 -1
- package/dist/check/generate.js +73 -3
- package/dist/cli/check.js +16 -6
- package/dist/cli/explain.js +13 -3
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +2 -2
- package/dist/compiler/index.d.ts +5 -0
- package/dist/compiler/index.js +1 -1
- package/dist/runtime/router.d.ts +15 -0
- package/dist/runtime/router.js +101 -0
- package/dist/server/handler.d.ts +24 -0
- package/dist/server/handler.js +168 -7
- package/dist/server/modes.d.ts +6 -0
- package/dist/server/modes.js +28 -0
- package/dist/server/views.d.ts +17 -0
- package/dist/server/views.js +23 -0
- package/dist/vite/build.d.ts +10 -1
- package/dist/vite/build.js +35 -5
- package/dist/vite/manifest.d.ts +15 -4
- package/dist/vite/manifest.js +21 -4
- package/dist/vite/netlify.d.ts +4 -0
- package/dist/vite/netlify.js +46 -0
- package/dist/vite/plugin.d.ts +8 -1
- package/dist/vite/plugin.js +119 -17
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://raw.githubusercontent.com/forinda/clarusjs/main/docs/assets/logo.svg" width="96" height="96" alt="clarusjs logo
|
|
2
|
+
<img src="https://raw.githubusercontent.com/forinda/clarusjs/main/docs/assets/logo.svg" width="96" height="96" alt="clarusjs logo">
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
5
|
<h1 align="center">clarusjs</h1>
|
package/dist/check/generate.d.ts
CHANGED
|
@@ -3,9 +3,25 @@
|
|
|
3
3
|
* spans stand for a whole template construct and map to its start.
|
|
4
4
|
*/
|
|
5
5
|
export type Mapping = [number, number, number, boolean];
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
|
|
8
|
+
* the page's inputs. `loaderSpan` is where that check sits in the generated code, so its errors can say so.
|
|
9
|
+
*/
|
|
10
|
+
export declare function generateTs(source: string, file: string, options?: {
|
|
11
|
+
loader?: string;
|
|
12
|
+
}): {
|
|
7
13
|
code: string;
|
|
8
14
|
mappings: Mapping[];
|
|
15
|
+
loaderSpan?: [number, number];
|
|
9
16
|
};
|
|
10
17
|
/** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
|
|
11
18
|
export declare function toSourceOffset(mappings: Mapping[], virtualOffset: number): number | null;
|
|
19
|
+
/**
|
|
20
|
+
* .clarusjs/views.d.ts: view name → inputs, as declarations only, so an app's own tsconfig can include it. Each view's
|
|
21
|
+
* inputs are written inline in a namespace; its `@import type`s become import() types with paths relative to
|
|
22
|
+
* .clarusjs/ (where this file lives). Views that don't parse are left out (check reports them).
|
|
23
|
+
*/
|
|
24
|
+
export declare function viewsDeclaration(views: {
|
|
25
|
+
file: string;
|
|
26
|
+
source: string;
|
|
27
|
+
}[]): string;
|
package/dist/check/generate.js
CHANGED
|
@@ -3,7 +3,11 @@
|
|
|
3
3
|
// every copied span is recorded so tsc's errors can be mapped back to the template. Pure: string in, string out.
|
|
4
4
|
import { parse } from '../compiler/parse.js';
|
|
5
5
|
import { splitImports } from '../compiler/script.js';
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
|
|
8
|
+
* the page's inputs. `loaderSpan` is where that check sits in the generated code, so its errors can say so.
|
|
9
|
+
*/
|
|
10
|
+
export function generateTs(source, file, options = {}) {
|
|
7
11
|
const parsed = parse(source, file);
|
|
8
12
|
const mappings = [];
|
|
9
13
|
let code = '';
|
|
@@ -32,6 +36,8 @@ export function generateTs(source, file) {
|
|
|
32
36
|
copy(d.clause, d.clauseStart);
|
|
33
37
|
emit(` from ${JSON.stringify(d.from)}\n`);
|
|
34
38
|
}
|
|
39
|
+
if (options.loader)
|
|
40
|
+
emit(`import { load as __cl_load } from ${JSON.stringify(options.loader)}\n`);
|
|
35
41
|
const script = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : null;
|
|
36
42
|
if (parsed.script && script) {
|
|
37
43
|
for (const imp of script.imports) {
|
|
@@ -47,7 +53,17 @@ export function generateTs(source, file) {
|
|
|
47
53
|
copy(input.type, input.typeStart);
|
|
48
54
|
emit('\n');
|
|
49
55
|
}
|
|
50
|
-
emit('}\n
|
|
56
|
+
emit('}\n');
|
|
57
|
+
let loaderSpan;
|
|
58
|
+
if (options.loader) {
|
|
59
|
+
// Params and defaults fill the rest, so load() may return any subset of the inputs, each with the right type.
|
|
60
|
+
emit('declare const __cl_loaded: Awaited<ReturnType<typeof __cl_load>>\n');
|
|
61
|
+
const start = code.length;
|
|
62
|
+
point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
|
|
63
|
+
loaderSpan = [start, code.length];
|
|
64
|
+
emit('\n');
|
|
65
|
+
}
|
|
66
|
+
emit('\nexport default function __cl_check(__cl_props: Inputs) {\n');
|
|
51
67
|
if (parsed.inputs.length) {
|
|
52
68
|
emit(' const { ');
|
|
53
69
|
parsed.inputs.forEach((input, i) => {
|
|
@@ -152,7 +168,7 @@ export function generateTs(source, file) {
|
|
|
152
168
|
}
|
|
153
169
|
parsed.nodes.forEach(visit);
|
|
154
170
|
emit('}\n');
|
|
155
|
-
return { code, mappings };
|
|
171
|
+
return { code, mappings, loaderSpan };
|
|
156
172
|
}
|
|
157
173
|
/** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
|
|
158
174
|
export function toSourceOffset(mappings, virtualOffset) {
|
|
@@ -162,3 +178,57 @@ export function toSourceOffset(mappings, virtualOffset) {
|
|
|
162
178
|
}
|
|
163
179
|
return null;
|
|
164
180
|
}
|
|
181
|
+
/** 'src/components' + '../domain/user' → 'src/domain/user' (POSIX, no fs). */
|
|
182
|
+
function joinPath(dir, rel) {
|
|
183
|
+
const out = dir.split('/').filter(Boolean);
|
|
184
|
+
for (const part of rel.split('/')) {
|
|
185
|
+
if (part === '..')
|
|
186
|
+
out.pop();
|
|
187
|
+
else if (part !== '.' && part !== '')
|
|
188
|
+
out.push(part);
|
|
189
|
+
}
|
|
190
|
+
return out.join('/');
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* .clarusjs/views.d.ts: view name → inputs, as declarations only, so an app's own tsconfig can include it. Each view's
|
|
194
|
+
* inputs are written inline in a namespace; its `@import type`s become import() types with paths relative to
|
|
195
|
+
* .clarusjs/ (where this file lives). Views that don't parse are left out (check reports them).
|
|
196
|
+
*/
|
|
197
|
+
export function viewsDeclaration(views) {
|
|
198
|
+
const lines = ['// Generated by clarusjs check: view name → inputs, for render() from clarusjs/views. Declarations only.'];
|
|
199
|
+
const entries = [];
|
|
200
|
+
views.forEach(({ file, source }, i) => {
|
|
201
|
+
let parsed;
|
|
202
|
+
try {
|
|
203
|
+
parsed = parse(source, file);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const ns = `__cl_v${i}`;
|
|
209
|
+
const body = [];
|
|
210
|
+
for (const t of parsed.typeImports) {
|
|
211
|
+
// Relative paths are written from .clarusjs/, one level below the project root.
|
|
212
|
+
const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from;
|
|
213
|
+
const clause = t.clause.trim();
|
|
214
|
+
if (clause.startsWith('{')) {
|
|
215
|
+
for (const part of clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '')).filter(Boolean)) {
|
|
216
|
+
const [name, local = name] = part.split(/\s+as\s+/).map((x) => x.trim());
|
|
217
|
+
body.push(` type ${local} = import(${JSON.stringify(from)}).${name}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
else if (!clause.startsWith('*')) {
|
|
221
|
+
// ponytail: `* as N` type imports aren't carried into the registry; use named type imports for inputs.
|
|
222
|
+
body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
body.push(` interface Inputs {`);
|
|
226
|
+
for (const input of parsed.inputs)
|
|
227
|
+
body.push(` ${input.name}${input.default !== undefined ? '?' : ''}: ${input.type}`);
|
|
228
|
+
body.push(' }');
|
|
229
|
+
lines.push(`declare namespace ${ns} {`, ...body, '}');
|
|
230
|
+
entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.tscl$/, ''))}: ${ns}.Inputs`);
|
|
231
|
+
});
|
|
232
|
+
lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
|
|
233
|
+
return lines.join('\n');
|
|
234
|
+
}
|
package/dist/cli/check.js
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
import { spawnSync } from 'node:child_process';
|
|
4
4
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
|
-
import { dirname, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { basename, dirname, relative, resolve, sep } from 'node:path';
|
|
7
7
|
import { ClarusError } from '../compiler/errors.js';
|
|
8
|
-
import { generateTs, toSourceOffset } from '../check/generate.js';
|
|
8
|
+
import { generateTs, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
9
9
|
import { findClarusFiles } from '../vite/build.js';
|
|
10
10
|
const VIRTUAL = '.clarusjs/virtual';
|
|
11
11
|
const posix = (path) => path.split(sep).join('/');
|
|
@@ -30,11 +30,14 @@ export function check(options) {
|
|
|
30
30
|
const file = posix(relative(root, path));
|
|
31
31
|
const source = readFileSync(path, 'utf8');
|
|
32
32
|
try {
|
|
33
|
-
|
|
33
|
+
// A page's .load.ts that exports load(): what it returns is checked against the page's inputs.
|
|
34
|
+
const loaderPath = path.replace(/\.tscl$/, '.load.ts');
|
|
35
|
+
const hasLoad = existsSync(loaderPath) && /export\s+(async\s+)?function\s+load\b|export\s+(const|let)\s+load\b/.test(readFileSync(loaderPath, 'utf8'));
|
|
36
|
+
const { code, mappings, loaderSpan } = generateTs(source, file, hasLoad ? { loader: `./${basename(loaderPath)}` } : {});
|
|
34
37
|
const vpath = resolve(virtualRoot, `${file}.ts`);
|
|
35
38
|
mkdirSync(dirname(vpath), { recursive: true });
|
|
36
39
|
writeFileSync(vpath, code);
|
|
37
|
-
generated.set(vpath, { file, source, code, mappings });
|
|
40
|
+
generated.set(vpath, { file, source, code, mappings, loaderSpan });
|
|
38
41
|
}
|
|
39
42
|
catch (err) {
|
|
40
43
|
if (!(err instanceof ClarusError))
|
|
@@ -43,6 +46,11 @@ export function check(options) {
|
|
|
43
46
|
diagnostics.push({ file, line: err.line, column: err.column, code: 'clarus', message });
|
|
44
47
|
}
|
|
45
48
|
}
|
|
49
|
+
// The view registry: every view's name → its inputs, so render(name, props) is checked. Declarations only, so apps
|
|
50
|
+
// can add .clarusjs/views.d.ts to their own tsconfig's include and get the same types in their editor.
|
|
51
|
+
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
52
|
+
const sources = findClarusFiles(resolve(root, 'src')).map((path) => ({ file: posix(relative(root, path)), source: readFileSync(path, 'utf8') }));
|
|
53
|
+
writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(sources));
|
|
46
54
|
// The project's own settings, plus what checking templates needs. Scripts are JavaScript, so untyped parameters
|
|
47
55
|
// are expected (noImplicitAny off). rootDirs lets virtual files and real sources import each other.
|
|
48
56
|
const hasConfig = existsSync(resolve(root, 'tsconfig.json'));
|
|
@@ -56,7 +64,7 @@ export function check(options) {
|
|
|
56
64
|
skipLibCheck: true,
|
|
57
65
|
rootDirs: ['..', './virtual'],
|
|
58
66
|
},
|
|
59
|
-
include: ['../src', './virtual'],
|
|
67
|
+
include: ['../src', './virtual', './views.d.ts'],
|
|
60
68
|
};
|
|
61
69
|
const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
|
|
62
70
|
mkdirSync(dirname(configPath), { recursive: true });
|
|
@@ -79,7 +87,9 @@ export function check(options) {
|
|
|
79
87
|
const offset = lines.slice(0, Number(m[2]) - 1).reduce((n, l) => n + l.length + 1, 0) + Number(m[3]) - 1;
|
|
80
88
|
const source = toSourceOffset(g.mappings, offset);
|
|
81
89
|
const at = source === null ? { line: 1, column: 1 } : position(g.source, source);
|
|
82
|
-
|
|
90
|
+
const fromLoader = g.loaderSpan && offset >= g.loaderSpan[0] && offset < g.loaderSpan[1];
|
|
91
|
+
const message = fromLoader ? `load() returns a value that doesn't fit this page's inputs: ${m[5]}` : source === null ? `${m[5]} (in generated code)` : m[5];
|
|
92
|
+
diagnostics.push({ file: g.file, ...at, code: m[4], message });
|
|
83
93
|
}
|
|
84
94
|
diagnostics.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
|
|
85
95
|
return {
|
package/dist/cli/explain.js
CHANGED
|
@@ -10,11 +10,19 @@ const WHEN = {
|
|
|
10
10
|
const kb = (bytes) => (bytes ? `${(bytes / 1024).toFixed(1)} KB` : '0 KB');
|
|
11
11
|
const row = (label, lines) => lines.map((l, i) => ` ${(i ? '' : label).padEnd(12)}${l}`);
|
|
12
12
|
function describe(path, r) {
|
|
13
|
+
if (r.mode === 'server') {
|
|
14
|
+
return [
|
|
15
|
+
path,
|
|
16
|
+
...row('Rendered', ['on every request, by dist/server/index.mjs']),
|
|
17
|
+
...row('Data', [r.loader === 'request' ? 'load() runs on every request' : 'no loader']),
|
|
18
|
+
...row('Islands', ['decided per request']),
|
|
19
|
+
].join('\n');
|
|
20
|
+
}
|
|
13
21
|
const islands = r.islands.map((i) => `${i.component}${i.count > 1 ? ` ×${i.count}` : ''} (${kb(i.gzip)}, ${WHEN[i.attach]})`);
|
|
14
22
|
return [
|
|
15
23
|
path,
|
|
16
|
-
...row('Rendered', [`at build time, to dist/client/${r.html}`]),
|
|
17
|
-
...row('Data', [r.loader
|
|
24
|
+
...row('Rendered', [r.mode === 'client' ? `in the browser, by the router (shell: dist/client/${r.html})` : `at build time, to dist/client/${r.html}`]),
|
|
25
|
+
...row('Data', [r.loader === 'build' ? (r.mode === 'client' ? 'load() ran once, at build time; fetched as __data.json' : 'load() ran once, at build time') : 'no loader']),
|
|
18
26
|
...row('Islands', islands.length ? islands : ['none']),
|
|
19
27
|
...row('JavaScript', [r.js.files.length ? `${kb(r.js.initialGzip)} on page load, ${kb(r.js.gzip)} in all (gzip, ${r.js.files.length} files)` : 'none']),
|
|
20
28
|
...row('CSS', [r.css.length ? r.css.join(', ') : 'none']),
|
|
@@ -25,7 +33,9 @@ function table(routes) {
|
|
|
25
33
|
const line = (cells) => cells[0].padEnd(width) + cells[1].padEnd(9) + cells[2].padEnd(12) + cells[3];
|
|
26
34
|
return [
|
|
27
35
|
line(['Route', 'Islands', 'JS on load', 'JS in all']),
|
|
28
|
-
...Object.entries(routes).map(([path, r]) =>
|
|
36
|
+
...Object.entries(routes).map(([path, r]) => r.mode === 'server'
|
|
37
|
+
? line([path, '-', 'per request', ''])
|
|
38
|
+
: line([path, String(r.islands.reduce((n, i) => n + i.count, 0)), kb(r.js.initialGzip), kb(r.js.gzip)])),
|
|
29
39
|
].join('\n');
|
|
30
40
|
}
|
|
31
41
|
export function explain(options) {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { ComponentIR } from './ir.ts';
|
|
2
|
-
export declare function emitServer(ir: ComponentIR, clientUrl: string): string;
|
|
2
|
+
export declare function emitServer(ir: ComponentIR, clientUrl: string, renderImports?: boolean): string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { htmlExpr, walk } from './html-expr.js';
|
|
2
2
|
import { rewriteServer } from './script.js';
|
|
3
3
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
4
|
-
export function emitServer(ir, clientUrl) {
|
|
4
|
+
export function emitServer(ir, clientUrl, renderImports = false) {
|
|
5
5
|
const all = walk(ir.nodes);
|
|
6
6
|
const runtime = [
|
|
7
7
|
'escape as __cl_escape',
|
|
@@ -13,7 +13,7 @@ export function emitServer(ir, clientUrl) {
|
|
|
13
13
|
].filter(Boolean).join(', ');
|
|
14
14
|
let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
|
|
15
15
|
for (const imp of ir.imports)
|
|
16
|
-
out += `import { render as ${renderName(imp.name)} } from '${imp.from}'\n`;
|
|
16
|
+
out += `import { render as ${renderName(imp.name)} } from '${imp.from}${renderImports ? '?render' : ''}'\n`;
|
|
17
17
|
for (const d of ir.dataImports)
|
|
18
18
|
out += `import ${d.clause} from '${d.from}'\n`;
|
|
19
19
|
for (const line of ir.scriptImports)
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
export { ClarusError } from './errors.ts';
|
|
2
|
+
/**
|
|
3
|
+
* `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
|
|
4
|
+
* browser (a client route's page, or a component re-rendered inside an island).
|
|
5
|
+
*/
|
|
2
6
|
export type CompileOptions = {
|
|
3
7
|
file: string;
|
|
4
8
|
target: 'server' | 'client';
|
|
5
9
|
clientUrl?: string;
|
|
10
|
+
renderImports?: boolean;
|
|
6
11
|
};
|
|
7
12
|
export type CompileResult = {
|
|
8
13
|
code: string;
|
package/dist/compiler/index.js
CHANGED
|
@@ -10,5 +10,5 @@ export function compile(source, options) {
|
|
|
10
10
|
return { code: emitClient(ir), stateful: ir.stateful };
|
|
11
11
|
if (ir.stateful && !options.clientUrl)
|
|
12
12
|
throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
|
|
13
|
-
return { code: emitServer(ir, options.clientUrl ?? ''), stateful: ir.stateful };
|
|
13
|
+
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful };
|
|
14
14
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type Entry = {
|
|
2
|
+
p: string;
|
|
3
|
+
r: string;
|
|
4
|
+
};
|
|
5
|
+
type Page = {
|
|
6
|
+
render(props: object): string;
|
|
7
|
+
};
|
|
8
|
+
/** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
|
|
9
|
+
export declare function matchRoute(table: Entry[], pathname: string): {
|
|
10
|
+
r: string;
|
|
11
|
+
params: Record<string, string>;
|
|
12
|
+
} | null;
|
|
13
|
+
/** Render the client route at `url` into the document. False when `url` is not a client route. */
|
|
14
|
+
export declare function show(url: URL, table: Entry[], load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>, isCurrent?: () => boolean): Promise<boolean>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
// Client router: renders client-mode routes in the browser. Browser only. The server sends a shell with the client
|
|
10
|
+
// route table; the router loads the page's render module and its <path>/__data.json, swaps the document, and lets
|
|
11
|
+
// the island loader attach. Later navigations between client routes are intercepted with the Navigation API;
|
|
12
|
+
// browsers without it simply load pages normally.
|
|
13
|
+
import { parse } from './serialize.js';
|
|
14
|
+
/** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
|
|
15
|
+
export function matchRoute(table, pathname) {
|
|
16
|
+
const got = pathname.replace(/(.)\/+$/, '$1').split('/');
|
|
17
|
+
try {
|
|
18
|
+
for (const { p, r } of table) {
|
|
19
|
+
const want = p.split('/');
|
|
20
|
+
const params = {};
|
|
21
|
+
// Segment by segment: a [param] takes any one non-empty segment, anything else must be equal.
|
|
22
|
+
const hit = want.length === got.length && want.every((w, i) => {
|
|
23
|
+
const key = /^\[([A-Za-z_$][\w$]*)\]$/.exec(w)?.[1];
|
|
24
|
+
if (key === undefined)
|
|
25
|
+
return w === got[i];
|
|
26
|
+
params[key] = decodeURIComponent(got[i]);
|
|
27
|
+
return got[i] !== '';
|
|
28
|
+
});
|
|
29
|
+
if (hit)
|
|
30
|
+
return { r, params };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch { } // a malformed %-escape names no page
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/** Render the client route at `url` into the document. False when `url` is not a client route. */
|
|
37
|
+
export async function show(url, table, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src)), get = fetch,
|
|
38
|
+
// False once a newer navigation has started: then this one must not touch the document.
|
|
39
|
+
isCurrent = () => true) {
|
|
40
|
+
const found = matchRoute(table, url.pathname);
|
|
41
|
+
if (!found)
|
|
42
|
+
return false;
|
|
43
|
+
const data = `${url.pathname.replace(/\/+$/, '')}/__data.json`;
|
|
44
|
+
const [page, props] = await Promise.all([
|
|
45
|
+
load(found.r),
|
|
46
|
+
get(data).then(async (res) => {
|
|
47
|
+
if (!res.ok)
|
|
48
|
+
throw new Error(`${res.status === 404 ? 'not found' : res.status}: ${data}`);
|
|
49
|
+
return parse(await res.text());
|
|
50
|
+
}),
|
|
51
|
+
]);
|
|
52
|
+
if (!isCurrent())
|
|
53
|
+
return false;
|
|
54
|
+
const doc = new DOMParser().parseFromString(page.render(props), 'text/html');
|
|
55
|
+
const style = doc.createElement('style');
|
|
56
|
+
style.textContent = 'cl-island{display:contents}'; // islands never affect layout
|
|
57
|
+
doc.head.append(style);
|
|
58
|
+
// The page's <title> comes with its head; its own <html> attributes (lang, dir, …) replace the previous page's.
|
|
59
|
+
const root = document.documentElement;
|
|
60
|
+
for (const { name } of [...root.attributes])
|
|
61
|
+
root.removeAttribute(name);
|
|
62
|
+
for (const { name, value } of [...doc.documentElement.attributes])
|
|
63
|
+
root.setAttribute(name, value);
|
|
64
|
+
document.head.replaceWith(doc.head);
|
|
65
|
+
document.body.replaceWith(doc.body);
|
|
66
|
+
globalThis.__clAttach?.(document.body);
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
const routes = typeof document !== 'undefined' ? document.getElementById('cl-routes') : null;
|
|
70
|
+
if (routes) {
|
|
71
|
+
const table = JSON.parse(routes.textContent ?? '[]');
|
|
72
|
+
// Each navigation gets a number; only the latest may change the document or fall back.
|
|
73
|
+
let latest = 1; // the first render is navigation 1
|
|
74
|
+
show(new URL(location.href), table, undefined, undefined, () => latest === 1).catch((err) => {
|
|
75
|
+
if (latest !== 1)
|
|
76
|
+
return;
|
|
77
|
+
document.body.textContent = err.message.startsWith('not found') ? 'Page not found.' : 'Could not load this page.';
|
|
78
|
+
});
|
|
79
|
+
// A URL that failed to render is loaded normally, never intercepted again (no retry loop). canIntercept is
|
|
80
|
+
// only true for same-origin navigations, so no origin check is needed.
|
|
81
|
+
let fallback = '';
|
|
82
|
+
const navigation = globalThis.navigation;
|
|
83
|
+
navigation?.addEventListener('navigate', (event) => {
|
|
84
|
+
const e = event;
|
|
85
|
+
if (!e.canIntercept || e.hashChange || e.downloadRequest !== null || e.formData)
|
|
86
|
+
return;
|
|
87
|
+
const url = new URL(e.destination.url);
|
|
88
|
+
if (url.href === fallback || !matchRoute(table, url.pathname))
|
|
89
|
+
return;
|
|
90
|
+
const id = ++latest;
|
|
91
|
+
const isCurrent = () => latest === id && !e.signal.aborted;
|
|
92
|
+
e.intercept({
|
|
93
|
+
handler: () => show(url, table, undefined, undefined, isCurrent).then(() => { }, () => {
|
|
94
|
+
if (!isCurrent())
|
|
95
|
+
return;
|
|
96
|
+
fallback = url.href;
|
|
97
|
+
location.assign(url.href);
|
|
98
|
+
}),
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -1,12 +1,36 @@
|
|
|
1
|
+
import { type ModeTable } from './modes.ts';
|
|
1
2
|
type PageModule = {
|
|
2
3
|
render(props?: object): string;
|
|
3
4
|
};
|
|
5
|
+
type Params = Record<string, string>;
|
|
6
|
+
/**
|
|
7
|
+
* `[page].load.ts`: data for a route, server only. entries() lists a dynamic route's pages to prerender; load()
|
|
8
|
+
* returns the page's inputs and runs per request on the server, or once per page at build.
|
|
9
|
+
*/
|
|
10
|
+
type DataModule = {
|
|
11
|
+
entries?(): Params[] | Promise<Params[]>;
|
|
12
|
+
load?(context: {
|
|
13
|
+
params: Params;
|
|
14
|
+
request: Request;
|
|
15
|
+
}): object | Promise<object>;
|
|
16
|
+
};
|
|
4
17
|
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
|
|
5
18
|
export declare function routeFromFile(file: string): string;
|
|
6
19
|
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
|
|
7
20
|
loaderUrl?: string;
|
|
21
|
+
data?: Record<string, () => Promise<DataModule>>;
|
|
22
|
+
modes?: ModeTable;
|
|
23
|
+
/** Client routes (as their files name them) → URL of the page's browser render module. */
|
|
24
|
+
client?: Record<string, string>;
|
|
25
|
+
routerUrl?: string;
|
|
26
|
+
/** Vite's base ('/' or '/docs/'): client routes are listed at their browser paths, under it. */
|
|
27
|
+
base?: string;
|
|
8
28
|
}): {
|
|
9
29
|
fetch(request: Request): Promise<Response>;
|
|
10
30
|
routes: string[];
|
|
31
|
+
serverRoutes: string[];
|
|
32
|
+
paths(): Promise<string[]>;
|
|
33
|
+
hasLoader(route: string): Promise<boolean>;
|
|
34
|
+
isServerPath(pathname: string): boolean;
|
|
11
35
|
};
|
|
12
36
|
export {};
|
package/dist/server/handler.js
CHANGED
|
@@ -1,24 +1,180 @@
|
|
|
1
|
-
|
|
1
|
+
import { modeFor } from './modes.js';
|
|
2
|
+
import { stringify } from '../runtime/serialize.js';
|
|
3
|
+
const DATA = '__data.json';
|
|
4
|
+
/** JSON that is safe inside a <script> element and in any HTML context: '<' never appears raw. */
|
|
5
|
+
const safeJson = (json) => json.replace(/</g, '\\u003c');
|
|
6
|
+
/** A whole path segment that is a parameter: [id], [$id]. Anything else, like v[2], is literal text. */
|
|
7
|
+
const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
|
|
8
|
+
/** '/users/[id]' → keys ['id'] and a RegExp that captures each segment. */
|
|
9
|
+
function compile(path) {
|
|
10
|
+
const keys = [];
|
|
11
|
+
const source = path.split('/').map((seg) => {
|
|
12
|
+
const m = PARAM.exec(seg);
|
|
13
|
+
if (!m)
|
|
14
|
+
return seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
15
|
+
keys.push(m[1]);
|
|
16
|
+
return '([^/]+)';
|
|
17
|
+
}).join('/');
|
|
18
|
+
return { keys, regex: new RegExp(`^${source}$`) };
|
|
19
|
+
}
|
|
2
20
|
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
|
|
3
21
|
export function routeFromFile(file) {
|
|
4
22
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.tscl$/, '').replace(/\/index$/, '');
|
|
5
23
|
return path || '/';
|
|
6
24
|
}
|
|
7
25
|
export function createHandler(pages, options = {}) {
|
|
8
|
-
|
|
26
|
+
// Static routes first, then dynamic ones with more fixed segments first: /users/new beats /users/[id].
|
|
27
|
+
const routes = Object.entries(pages)
|
|
28
|
+
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
29
|
+
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
30
|
+
const data = options.data ?? {};
|
|
31
|
+
const modes = options.modes ?? {};
|
|
9
32
|
const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
|
|
33
|
+
function match(pathname) {
|
|
34
|
+
for (const route of routes) {
|
|
35
|
+
const m = route.regex.exec(pathname);
|
|
36
|
+
if (!m)
|
|
37
|
+
continue;
|
|
38
|
+
const params = {};
|
|
39
|
+
try {
|
|
40
|
+
route.keys.forEach((key, i) => { params[key] = decodeURIComponent(m[i + 1]); });
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null; // a malformed %-escape names no page
|
|
44
|
+
}
|
|
45
|
+
return { route, params };
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
// entries() per route, asked once: prerendering and requests see the same list. null when there is none.
|
|
50
|
+
const entriesCache = new Map();
|
|
51
|
+
function entriesOf(route) {
|
|
52
|
+
if (!entriesCache.has(route)) {
|
|
53
|
+
const file = `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
|
|
54
|
+
entriesCache.set(route, (async () => {
|
|
55
|
+
const mod = data[file] ? await data[file]() : undefined;
|
|
56
|
+
return mod?.entries ? await mod.entries() : null;
|
|
57
|
+
})());
|
|
58
|
+
}
|
|
59
|
+
return entriesCache.get(route);
|
|
60
|
+
}
|
|
61
|
+
// Without entries() a route isn't restricted here (the build reports it).
|
|
62
|
+
async function listed(route, params) {
|
|
63
|
+
const list = await entriesOf(route);
|
|
64
|
+
return !list || list.some((entry) => route.keys.every((key) => entry[key] === params[key]));
|
|
65
|
+
}
|
|
10
66
|
return {
|
|
11
|
-
routes:
|
|
67
|
+
routes: routes.map((r) => r.path).sort(),
|
|
68
|
+
/** Routes rendered per request ('server' mode), as their files name them. */
|
|
69
|
+
serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
|
|
70
|
+
/** Whether a URL path belongs to a server route (what a host must send to this handler instead of a file). */
|
|
71
|
+
isServerPath(pathname) {
|
|
72
|
+
const found = match(pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname);
|
|
73
|
+
return Boolean(found && modeFor(found.route.path, modes) === 'server');
|
|
74
|
+
},
|
|
75
|
+
/** Whether a route (as its file names it) has a load(). */
|
|
76
|
+
async hasLoader(path) {
|
|
77
|
+
const route = routes.find((r) => r.path === path);
|
|
78
|
+
const file = route && `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
|
|
79
|
+
return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
|
|
80
|
+
},
|
|
81
|
+
/** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
|
|
82
|
+
async paths() {
|
|
83
|
+
const out = [];
|
|
84
|
+
for (const route of routes) {
|
|
85
|
+
const mode = modeFor(route.path, modes);
|
|
86
|
+
if (mode === 'server')
|
|
87
|
+
continue;
|
|
88
|
+
const add = (path) => {
|
|
89
|
+
out.push(path);
|
|
90
|
+
// A client page's data, fetched by the router: written next to its shell.
|
|
91
|
+
if (mode === 'client')
|
|
92
|
+
out.push(path === '/' ? `/${DATA}` : `${path}/${DATA}`);
|
|
93
|
+
};
|
|
94
|
+
if (!route.keys.length) {
|
|
95
|
+
add(route.path);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const dataFile = route.file.replace(/\.tscl$/, '.load.ts');
|
|
99
|
+
const list = await entriesOf(route);
|
|
100
|
+
if (!list)
|
|
101
|
+
throw new Error(`${route.path} is a dynamic route: export entries() from ${dataFile} to list the pages to prerender`);
|
|
102
|
+
for (const params of list) {
|
|
103
|
+
add(route.path.split('/').map((seg) => {
|
|
104
|
+
const key = PARAM.exec(seg)?.[1];
|
|
105
|
+
if (key === undefined)
|
|
106
|
+
return seg;
|
|
107
|
+
const value = params[key];
|
|
108
|
+
// Each value fills one path segment and names a folder in the build: never empty, '.' or '..'.
|
|
109
|
+
// Path separators on any OS ('/', '\\') and NUL could step out of that folder once the segment is decoded.
|
|
110
|
+
// __data.json is a client route's data file, so it can't also name a page.
|
|
111
|
+
if (typeof value !== 'string' || value === '' || value === '.' || value === '..' || value === DATA || /[/\\\0]/.test(value)) {
|
|
112
|
+
throw new Error(`${dataFile}: entries() gave ${JSON.stringify(value)} for "${key}"; each value must be a non-empty string without "/" or "\\", and not ".", ".." or "${DATA}"`);
|
|
113
|
+
}
|
|
114
|
+
return encodeURIComponent(value);
|
|
115
|
+
}).join('/'));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return out.sort();
|
|
119
|
+
},
|
|
12
120
|
async fetch(request) {
|
|
13
121
|
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
14
122
|
return new Response('Method Not Allowed', { status: 405 });
|
|
15
123
|
const pathname = new URL(request.url).pathname;
|
|
16
124
|
// '/guide/x/' is the same page as '/guide/x', in dev as on a static host.
|
|
17
|
-
const
|
|
125
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
126
|
+
// <client route>/__data.json is that page's props, for the router. Only for a client route: anywhere else the
|
|
127
|
+
// path is an ordinary page path (a server route may well have an [id] of "__data.json").
|
|
128
|
+
let found = match(trim(pathname));
|
|
129
|
+
let wantsData = false;
|
|
130
|
+
if (pathname.endsWith(`/${DATA}`)) {
|
|
131
|
+
const owner = match(trim(pathname.slice(0, -DATA.length - 1) || '/'));
|
|
132
|
+
if (owner && modeFor(owner.route.path, modes) === 'client') {
|
|
133
|
+
found = owner;
|
|
134
|
+
wantsData = true;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
18
137
|
const head = request.method === 'HEAD';
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
138
|
+
const notFound = () => new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
139
|
+
const mode = found && modeFor(found.route.path, modes);
|
|
140
|
+
if (!found)
|
|
141
|
+
return notFound();
|
|
142
|
+
// A prerendered dynamic route only has the pages its entries() lists, as on a static host.
|
|
143
|
+
if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
|
|
144
|
+
return notFound();
|
|
145
|
+
if (mode === 'client' && !wantsData) {
|
|
146
|
+
// In matching order (static before dynamic, as on the server): the router takes the first match.
|
|
147
|
+
const client = options.client ?? {};
|
|
148
|
+
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
149
|
+
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
150
|
+
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
151
|
+
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${safeJson(JSON.stringify(table))}</script>` +
|
|
152
|
+
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
153
|
+
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
154
|
+
return new Response(head ? null : shell, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
155
|
+
}
|
|
156
|
+
let props = found.params;
|
|
157
|
+
const dataFile = found.route.file.replace(/\.tscl$/, '.load.ts');
|
|
158
|
+
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
159
|
+
if (mod?.load) {
|
|
160
|
+
let loaded;
|
|
161
|
+
try {
|
|
162
|
+
loaded = await mod.load({ params: found.params, request });
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
return failure(`${dataFile}: load() failed: ${err?.message ?? err}`);
|
|
166
|
+
}
|
|
167
|
+
if (loaded === null || typeof loaded !== 'object' || Array.isArray(loaded)) {
|
|
168
|
+
return failure(`${dataFile}: load() must return an object of page inputs, got ${Array.isArray(loaded) ? 'an array' : loaded === null ? 'null' : typeof loaded}`);
|
|
169
|
+
}
|
|
170
|
+
;
|
|
171
|
+
globalThis.__clLoaderRan = true; // recorded by prerender for the manifest
|
|
172
|
+
props = { ...found.params, ...loaded };
|
|
173
|
+
}
|
|
174
|
+
if (wantsData) {
|
|
175
|
+
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
176
|
+
}
|
|
177
|
+
const html = (await found.route.load()).render(props);
|
|
22
178
|
const visible = maskComments(html);
|
|
23
179
|
const hasIslands = visible.includes('<cl-island ');
|
|
24
180
|
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk.
|
|
@@ -31,6 +187,11 @@ export function createHandler(pages, options = {}) {
|
|
|
31
187
|
},
|
|
32
188
|
};
|
|
33
189
|
}
|
|
190
|
+
/** A 500 that tells the visitor nothing internal; the details go to the server log (and the build's output). */
|
|
191
|
+
function failure(message) {
|
|
192
|
+
console.error(`[clarusjs] ${message}`);
|
|
193
|
+
return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
194
|
+
}
|
|
34
195
|
/** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
|
|
35
196
|
function maskComments(html) {
|
|
36
197
|
return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type Mode = 'static' | 'server' | 'client';
|
|
2
|
+
export type ModeTable = Record<string, string>;
|
|
3
|
+
/** Throws on an unknown mode or a malformed pattern, naming it. */
|
|
4
|
+
export declare function checkModes(table: ModeTable): void;
|
|
5
|
+
/** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
|
|
6
|
+
export declare function modeFor(route: string, table: ModeTable): Mode;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Per-route rendering modes: when each route renders. 'static' at build (the default), 'server' per request,
|
|
2
|
+
// 'client' in the browser (the server sends a shell; the router renders the page from its data).
|
|
3
|
+
const MODES = ['static', 'server', 'client'];
|
|
4
|
+
/** Throws on an unknown mode or a malformed pattern, naming it. */
|
|
5
|
+
export function checkModes(table) {
|
|
6
|
+
for (const [pattern, mode] of Object.entries(table)) {
|
|
7
|
+
if (!pattern.startsWith('/'))
|
|
8
|
+
throw new Error(`clarusjs: route pattern "${pattern}" must start with /`);
|
|
9
|
+
if (pattern.slice(0, -1).includes('*') || (pattern.endsWith('*') && !pattern.endsWith('/*'))) {
|
|
10
|
+
throw new Error(`clarusjs: route pattern "${pattern}" may only use * as its last segment`);
|
|
11
|
+
}
|
|
12
|
+
if (!MODES.includes(mode))
|
|
13
|
+
throw new Error(`clarusjs: routes['${pattern}'] is "${mode}"; use 'static', 'server' or 'client'`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
|
|
17
|
+
export function modeFor(route, table) {
|
|
18
|
+
let best;
|
|
19
|
+
for (const [pattern, mode] of Object.entries(table)) {
|
|
20
|
+
const folder = pattern.endsWith('/*') ? pattern.slice(0, -2) : undefined;
|
|
21
|
+
const hit = folder !== undefined ? route === (folder || '/') || route.startsWith(`${folder}/`) : route === pattern;
|
|
22
|
+
// An exact pattern beats a folder of the same length.
|
|
23
|
+
const length = folder !== undefined ? folder.length : pattern.length + 0.5;
|
|
24
|
+
if (hit && (!best || length > best.length))
|
|
25
|
+
best = { length, mode: mode };
|
|
26
|
+
}
|
|
27
|
+
return best?.mode ?? 'static';
|
|
28
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
type View = {
|
|
2
|
+
render(props?: object): string;
|
|
3
|
+
};
|
|
4
|
+
type Registry = Record<string, () => Promise<View>>;
|
|
5
|
+
/** View name → inputs. Filled in by the generated .clarusjs/views.d.ts (declaration merging). */
|
|
6
|
+
export interface Views {
|
|
7
|
+
}
|
|
8
|
+
/** Without the generated registry any name is accepted; with it, only real views. */
|
|
9
|
+
export type ViewName = [keyof Views] extends [never] ? string : Extract<keyof Views, string>;
|
|
10
|
+
export type ViewProps<N> = N extends keyof Views ? Views[N] : Record<string, unknown>;
|
|
11
|
+
/** '/src/components/pill.tscl' → 'components/pill' */
|
|
12
|
+
export declare function viewName(file: string): string;
|
|
13
|
+
/** Called by the server entry with import.meta.glob('/src/**\/*.tscl'). */
|
|
14
|
+
export declare function registerViews(files: Registry): void;
|
|
15
|
+
/** Render a view to HTML. Its props are checked against its inputs once `clarusjs check` has generated the registry. */
|
|
16
|
+
export declare function render<N extends ViewName>(name: N, props: ViewProps<N>): Promise<string>;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// render(name, props): any view under src/ rendered to HTML from server code (a loader, an endpoint, a script that
|
|
2
|
+
// imports the built server). The server entry registers the views; `clarusjs check` writes .clarusjs/views.d.ts,
|
|
3
|
+
// which types each name with that view's inputs.
|
|
4
|
+
/** '/src/components/pill.tscl' → 'components/pill' */
|
|
5
|
+
export function viewName(file) {
|
|
6
|
+
return file.replace(/^.*?\/src\//, '').replace(/\.tscl$/, '');
|
|
7
|
+
}
|
|
8
|
+
// On globalThis: the bundled server and an app's own `import 'clarusjs/views'` may be two copies of this module.
|
|
9
|
+
const store = globalThis;
|
|
10
|
+
/** Called by the server entry with import.meta.glob('/src/**\/*.tscl'). */
|
|
11
|
+
export function registerViews(files) {
|
|
12
|
+
store.__clViews = new Map(Object.entries(files).map(([file, load]) => [viewName(file), load]));
|
|
13
|
+
}
|
|
14
|
+
/** Render a view to HTML. Its props are checked against its inputs once `clarusjs check` has generated the registry. */
|
|
15
|
+
export async function render(name, props) {
|
|
16
|
+
const views = store.__clViews;
|
|
17
|
+
if (!views)
|
|
18
|
+
throw new Error('clarusjs: no views are registered; render() runs in server code, after the server entry has loaded');
|
|
19
|
+
const load = views.get(name);
|
|
20
|
+
if (!load)
|
|
21
|
+
throw new Error(`clarusjs: no view "${name}"; views: ${[...views.keys()].sort().join(', ')}`);
|
|
22
|
+
return (await load()).render(props);
|
|
23
|
+
}
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
/** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
|
|
2
2
|
export declare function findClarusFiles(srcDir: string): string[];
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
5
|
+
* Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
|
|
6
|
+
* entries() values never contain '/' (and a page file's own name has none).
|
|
7
|
+
*/
|
|
4
8
|
export declare function routeToFile(route: string): string;
|
|
5
9
|
/**
|
|
6
10
|
* Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
|
|
@@ -10,4 +14,9 @@ export declare function routeToFile(route: string): string;
|
|
|
10
14
|
export declare function prerender(serverEntry: string, outDir: string, manifestFile: string, only?: string[]): Promise<{
|
|
11
15
|
routes: string[];
|
|
12
16
|
readers: string[];
|
|
17
|
+
loaded: string[];
|
|
18
|
+
server: {
|
|
19
|
+
route: string;
|
|
20
|
+
loader: boolean;
|
|
21
|
+
}[];
|
|
13
22
|
}>;
|
package/dist/vite/build.js
CHANGED
|
@@ -13,9 +13,23 @@ export function findClarusFiles(srcDir) {
|
|
|
13
13
|
}
|
|
14
14
|
return entries.filter((f) => f.endsWith('.tscl')).map((f) => resolve(srcDir, f)).sort();
|
|
15
15
|
}
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
18
|
+
* Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
|
|
19
|
+
* entries() values never contain '/' (and a page file's own name has none).
|
|
20
|
+
*/
|
|
17
21
|
export function routeToFile(route) {
|
|
18
|
-
const path = route.replace(/^\/+|\/+$/g, '')
|
|
22
|
+
const path = route.replace(/^\/+|\/+$/g, '').split('/').map((seg) => {
|
|
23
|
+
try {
|
|
24
|
+
return decodeURIComponent(seg);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return seg;
|
|
28
|
+
} // '100%' is a name, not an escape
|
|
29
|
+
}).join('/');
|
|
30
|
+
// A client page's data file is written as itself, next to the page's shell.
|
|
31
|
+
if (path === '__data.json' || path.endsWith('/__data.json'))
|
|
32
|
+
return path;
|
|
19
33
|
return path ? `${path}/index.html` : 'index.html';
|
|
20
34
|
}
|
|
21
35
|
/**
|
|
@@ -26,15 +40,23 @@ export function routeToFile(route) {
|
|
|
26
40
|
export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
27
41
|
const script = `
|
|
28
42
|
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
29
|
-
import { dirname, resolve } from 'node:path'
|
|
43
|
+
import { dirname, resolve, sep } from 'node:path'
|
|
30
44
|
import { pathToFileURL } from 'node:url'
|
|
31
45
|
const routeToFile = ${routeToFile.toString()}
|
|
32
46
|
const [entry, outDir, only] = process.argv.slice(1)
|
|
33
47
|
const { default: handler } = await import(pathToFileURL(entry).href)
|
|
34
|
-
|
|
48
|
+
let routes
|
|
49
|
+
try {
|
|
50
|
+
routes = only ? JSON.parse(only) : await handler.paths()
|
|
51
|
+
} catch (err) {
|
|
52
|
+
process.stderr.write('prerender: ' + (err && err.message || err))
|
|
53
|
+
process.exit(1)
|
|
54
|
+
}
|
|
35
55
|
const readers = []
|
|
56
|
+
const loaded = []
|
|
36
57
|
for (const route of routes) {
|
|
37
58
|
globalThis.__clManifestRead = false
|
|
59
|
+
globalThis.__clLoaderRan = false
|
|
38
60
|
let response
|
|
39
61
|
try {
|
|
40
62
|
response = await handler.fetch(new Request('http://localhost' + route))
|
|
@@ -47,11 +69,19 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
47
69
|
process.exit(1)
|
|
48
70
|
}
|
|
49
71
|
const file = resolve(outDir, routeToFile(route))
|
|
72
|
+
// Whatever a route decodes to, its page must land inside the output folder.
|
|
73
|
+
if (!file.startsWith(resolve(outDir) + sep)) {
|
|
74
|
+
process.stderr.write('prerender ' + route + ': outside the output folder')
|
|
75
|
+
process.exit(1)
|
|
76
|
+
}
|
|
50
77
|
mkdirSync(dirname(file), { recursive: true })
|
|
51
78
|
writeFileSync(file, await response.text())
|
|
52
79
|
if (globalThis.__clManifestRead) readers.push(route)
|
|
80
|
+
if (globalThis.__clLoaderRan) loaded.push(route)
|
|
53
81
|
}
|
|
54
|
-
|
|
82
|
+
const server = []
|
|
83
|
+
for (const route of handler.serverRoutes ?? []) server.push({ route, loader: await handler.hasLoader(route) })
|
|
84
|
+
process.stdout.write(JSON.stringify({ routes, readers, loaded, server }))
|
|
55
85
|
`;
|
|
56
86
|
const args = ['--input-type=module', '-e', script, serverEntry, outDir, ...(only ? [JSON.stringify(only)] : [])];
|
|
57
87
|
const env = { ...process.env, CLARUS_MANIFEST: manifestFile };
|
package/dist/vite/manifest.d.ts
CHANGED
|
@@ -7,9 +7,15 @@ export type IslandInfo = {
|
|
|
7
7
|
gzip: number;
|
|
8
8
|
};
|
|
9
9
|
export type RouteInfo = {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
/**
|
|
11
|
+
* 'static': prerendered at build. 'server': rendered per request by dist/server/index.mjs (its key is the route as
|
|
12
|
+
* its file names it). 'client': a prerendered shell; the router renders it in the browser from its __data.json.
|
|
13
|
+
*/
|
|
14
|
+
mode: 'static' | 'server' | 'client';
|
|
15
|
+
/** The prerendered file in dist/client (a client route's shell), or null for a server route. */
|
|
16
|
+
html: string | null;
|
|
17
|
+
/** 'build': load() ran once, when the page was prerendered. 'request': it runs on every request. */
|
|
18
|
+
loader: 'build' | 'request' | null;
|
|
13
19
|
islands: IslandInfo[];
|
|
14
20
|
/** Files relative to dist/client; gzip sizes in bytes. initialGzip is what loads with the page (attach="load"). */
|
|
15
21
|
js: {
|
|
@@ -33,6 +39,11 @@ export declare function describeRoute(route: string, html: string, opts: {
|
|
|
33
39
|
base: string;
|
|
34
40
|
chunks: ChunkGraph;
|
|
35
41
|
size(file: string): number;
|
|
42
|
+
loaded?: boolean;
|
|
43
|
+
client?: boolean;
|
|
36
44
|
}): RouteInfo;
|
|
37
45
|
/** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
|
|
38
|
-
export declare function writeManifest(distDir: string, routes: string[], base: string
|
|
46
|
+
export declare function writeManifest(distDir: string, routes: string[], base: string, loaded?: string[], server?: {
|
|
47
|
+
route: string;
|
|
48
|
+
loader: boolean;
|
|
49
|
+
}[]): Manifest;
|
package/dist/vite/manifest.js
CHANGED
|
@@ -4,6 +4,7 @@ import { readFileSync, writeFileSync } from 'node:fs';
|
|
|
4
4
|
import { resolve } from 'node:path';
|
|
5
5
|
import { gzipSync } from 'node:zlib';
|
|
6
6
|
import { routeToFile } from './build.js';
|
|
7
|
+
import { matchRoute } from '../runtime/router.js';
|
|
7
8
|
const attrsOf = (tag) => {
|
|
8
9
|
const out = {};
|
|
9
10
|
for (const m of tag.matchAll(/([\w-]+)="([^"]*)"/g))
|
|
@@ -40,6 +41,13 @@ export function describeRoute(route, html, opts) {
|
|
|
40
41
|
closure(local(m[1]), all);
|
|
41
42
|
closure(local(m[1]), initial);
|
|
42
43
|
}
|
|
44
|
+
// A client route also loads its page's render module, named in the shell's route table.
|
|
45
|
+
const table = /<script type="application\/json" id="cl-routes">(.*?)<\/script>/.exec(html)?.[1];
|
|
46
|
+
const render = opts.client && table ? matchRoute(JSON.parse(table), route)?.r : undefined;
|
|
47
|
+
if (render) {
|
|
48
|
+
closure(local(render), all);
|
|
49
|
+
closure(local(render), initial);
|
|
50
|
+
}
|
|
43
51
|
for (const island of islands) {
|
|
44
52
|
closure(island.src, all);
|
|
45
53
|
if (island.attach === 'load')
|
|
@@ -47,11 +55,10 @@ export function describeRoute(route, html, opts) {
|
|
|
47
55
|
}
|
|
48
56
|
const sum = (files) => files.reduce((n, f) => n + opts.size(f), 0);
|
|
49
57
|
const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
|
|
50
|
-
|
|
51
|
-
return { mode: 'static', html: routeToFile(route), loader: null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
|
|
58
|
+
return { mode: opts.client ? 'client' : 'static', html: routeToFile(route), loader: opts.loaded ? 'build' : null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
|
|
52
59
|
}
|
|
53
60
|
/** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
|
|
54
|
-
export function writeManifest(distDir, routes, base) {
|
|
61
|
+
export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
55
62
|
const client = resolve(distDir, 'client');
|
|
56
63
|
const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
|
|
57
64
|
const sizes = new Map();
|
|
@@ -61,8 +68,18 @@ export function writeManifest(distDir, routes, base) {
|
|
|
61
68
|
return sizes.get(file);
|
|
62
69
|
};
|
|
63
70
|
const manifest = { version: 1, routes: {} };
|
|
71
|
+
const dataFile = (route) => (route === '/' ? '/__data.json' : `${route}/__data.json`);
|
|
64
72
|
for (const route of routes) {
|
|
65
|
-
|
|
73
|
+
if (route.endsWith('/__data.json'))
|
|
74
|
+
continue; // a client route's data, not a page
|
|
75
|
+
const isClient = routes.includes(dataFile(route));
|
|
76
|
+
// A client route's loader runs when its data file is written.
|
|
77
|
+
const ran = loaded.includes(route) || (isClient && loaded.includes(dataFile(route)));
|
|
78
|
+
manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size, loaded: ran, client: isClient });
|
|
79
|
+
}
|
|
80
|
+
// Server routes have no HTML at build time: what they ship is decided per request.
|
|
81
|
+
for (const { route, loader } of server) {
|
|
82
|
+
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
66
83
|
}
|
|
67
84
|
writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
68
85
|
return manifest;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
|
|
2
|
+
export declare function netlifyPaths(route: string): string[];
|
|
3
|
+
/** Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. */
|
|
4
|
+
export declare function writeNetlifyFunction(root: string, serverEntry: string, serverRoutes: string[]): void;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Netlify adapter: server routes run as one Netlify Function (Frameworks API) calling the same fetch handler.
|
|
2
|
+
// Static routes stay files; preferStatic makes Netlify serve those first.
|
|
3
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, relative, resolve, sep } from 'node:path';
|
|
5
|
+
const FUNCTION = '.netlify/v1/functions/clarusjs-server.mjs';
|
|
6
|
+
/** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
|
|
7
|
+
export function netlifyPaths(route) {
|
|
8
|
+
const segments = route.split('/');
|
|
9
|
+
const keyOf = (seg) => /^\[([A-Za-z_$][\w$]*)\]$/.exec(seg)?.[1];
|
|
10
|
+
const valid = (key) => /^[A-Za-z_]\w*$/.test(key);
|
|
11
|
+
// Names already valid in URLPattern are kept; others get p0, p1, … that aren't taken (URLPattern rejects duplicates).
|
|
12
|
+
const taken = new Set(segments.map(keyOf).filter((k) => k !== undefined && valid(k)));
|
|
13
|
+
let n = 0;
|
|
14
|
+
const fresh = () => {
|
|
15
|
+
while (taken.has(`p${n}`))
|
|
16
|
+
n++;
|
|
17
|
+
taken.add(`p${n}`);
|
|
18
|
+
return `p${n}`;
|
|
19
|
+
};
|
|
20
|
+
const path = segments.map((seg) => {
|
|
21
|
+
const key = keyOf(seg);
|
|
22
|
+
if (key !== undefined)
|
|
23
|
+
return `:${valid(key) ? key : fresh()}`;
|
|
24
|
+
return seg.replace(/[:*?+(){}\\]/g, '\\$&'); // literal text, not pattern syntax
|
|
25
|
+
}).join('/');
|
|
26
|
+
return path === '/' || path === '' ? ['/'] : [path, `${path}/`];
|
|
27
|
+
}
|
|
28
|
+
/** Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. */
|
|
29
|
+
export function writeNetlifyFunction(root, serverEntry, serverRoutes) {
|
|
30
|
+
const file = resolve(root, FUNCTION);
|
|
31
|
+
if (!serverRoutes.length) {
|
|
32
|
+
rmSync(file, { force: true });
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const entry = relative(dirname(file), serverEntry).split(sep).join('/');
|
|
36
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
37
|
+
writeFileSync(file, [
|
|
38
|
+
'// Generated by clarusjs: server routes on Netlify Functions. Static routes are files.',
|
|
39
|
+
`import handler from ${JSON.stringify(entry.startsWith('.') ? entry : `./${entry}`)}`,
|
|
40
|
+
'',
|
|
41
|
+
'export default (request) => handler.fetch(request)',
|
|
42
|
+
'',
|
|
43
|
+
`export const config = ${JSON.stringify({ path: serverRoutes.flatMap(netlifyPaths), preferStatic: true })}`,
|
|
44
|
+
'',
|
|
45
|
+
].join('\n'));
|
|
46
|
+
}
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { type Plugin } from 'vite';
|
|
2
|
+
import { type ModeTable } from '../server/modes.ts';
|
|
2
3
|
/** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
|
|
3
4
|
export declare function clientUrlFor(root: string, file: string): string;
|
|
4
|
-
export
|
|
5
|
+
export type ClarusOptions = {
|
|
6
|
+
/** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
|
|
7
|
+
routes?: ModeTable;
|
|
8
|
+
/** Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. */
|
|
9
|
+
adapter?: 'netlify';
|
|
10
|
+
};
|
|
11
|
+
export default function clarusjs(options?: ClarusOptions): Plugin;
|
package/dist/vite/plugin.js
CHANGED
|
@@ -1,12 +1,23 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
1
9
|
// The clarusjs Vite plugin: a thin adapter around the compiler.
|
|
2
10
|
// Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
|
|
3
11
|
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
4
|
-
import { dirname, isAbsolute, relative, resolve } from 'node:path';
|
|
5
|
-
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
14
|
import { isRunnableDevEnvironment } from 'vite';
|
|
7
15
|
import { compile, ClarusError } from '../compiler/index.js';
|
|
8
16
|
import { findClarusFiles, prerender } from './build.js';
|
|
9
17
|
import { writeManifest } from './manifest.js';
|
|
18
|
+
import { writeNetlifyFunction } from './netlify.js';
|
|
19
|
+
import { checkModes, modeFor } from '../server/modes.js';
|
|
20
|
+
import { routeFromFile } from '../server/handler.js';
|
|
10
21
|
import { sendResponse, toRequest } from './node.js';
|
|
11
22
|
// From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
|
|
12
23
|
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
@@ -18,12 +29,30 @@ export function clientUrlFor(root, file) {
|
|
|
18
29
|
return rel.startsWith('..') || isAbsolute(rel) ? `/@fs${file}?import` : `/${rel}?import`;
|
|
19
30
|
}
|
|
20
31
|
const LOADER_ENTRY = 'cl-loader';
|
|
32
|
+
const ROUTER_ENTRY = 'cl-router';
|
|
33
|
+
// Client entry name of a client-mode page's browser render module.
|
|
34
|
+
const renderEntry = (name) => `render/${name}`;
|
|
21
35
|
const CLIENT_OUT = 'dist/client';
|
|
22
36
|
// Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
|
|
23
37
|
const CHUNK_TOKEN = '__CLARUS_CHUNK__';
|
|
24
38
|
const SERVER_OUT = 'dist/server';
|
|
25
39
|
const entryName = (root, file) => relative(root, file).replace(/\.tscl$/, '');
|
|
26
|
-
|
|
40
|
+
/** Client-mode pages: route (as the file names it) → absolute file. */
|
|
41
|
+
function clientPages(appRoot, modes) {
|
|
42
|
+
const pages = new Map();
|
|
43
|
+
for (const file of findClarusFiles(resolve(appRoot, 'src/pages'))) {
|
|
44
|
+
const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
|
|
45
|
+
if (modeFor(route, modes) === 'client')
|
|
46
|
+
pages.set(route, file);
|
|
47
|
+
}
|
|
48
|
+
return pages;
|
|
49
|
+
}
|
|
50
|
+
export default function clarusjs(options = {}) {
|
|
51
|
+
const modes = options.routes ?? {};
|
|
52
|
+
checkModes(modes);
|
|
53
|
+
if (options.adapter !== undefined && options.adapter !== 'netlify') {
|
|
54
|
+
throw new Error(`clarusjs: adapter "${options.adapter}" is not supported; use 'netlify'`);
|
|
55
|
+
}
|
|
27
56
|
let root = process.cwd();
|
|
28
57
|
let command = 'serve';
|
|
29
58
|
let base = '/';
|
|
@@ -42,9 +71,14 @@ export default function clarusjs() {
|
|
|
42
71
|
}
|
|
43
72
|
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
44
73
|
built = new Map();
|
|
45
|
-
|
|
46
|
-
|
|
74
|
+
// By entry name, and by source key: names are sanitized ([id] → _id_), keys keep the real path.
|
|
75
|
+
for (const [key, chunk] of Object.entries(manifest)) {
|
|
76
|
+
if (!chunk.isEntry)
|
|
77
|
+
continue;
|
|
78
|
+
if (chunk.name)
|
|
47
79
|
built.set(chunk.name, base + chunk.file);
|
|
80
|
+
built.set(key, base + chunk.file);
|
|
81
|
+
}
|
|
48
82
|
return built;
|
|
49
83
|
};
|
|
50
84
|
return {
|
|
@@ -74,6 +108,12 @@ export default function clarusjs() {
|
|
|
74
108
|
if (compile(readFileSync(file, 'utf8'), { file, target: 'client' }).stateful)
|
|
75
109
|
input[entryName(appRoot, file)] = file;
|
|
76
110
|
}
|
|
111
|
+
// Client routes: the router, and each page's render function for the browser.
|
|
112
|
+
const client = clientPages(appRoot, modes);
|
|
113
|
+
if (client.size)
|
|
114
|
+
input[ROUTER_ENTRY] = here('../runtime/router');
|
|
115
|
+
for (const file of client.values())
|
|
116
|
+
input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
|
|
77
117
|
config.builder = {};
|
|
78
118
|
config.environments = {
|
|
79
119
|
// Island chunks are loaded with import() and must keep their `attach` export.
|
|
@@ -90,9 +130,15 @@ export default function clarusjs() {
|
|
|
90
130
|
if (this.environment.config.consumer !== 'client' || command !== 'build')
|
|
91
131
|
return;
|
|
92
132
|
const byName = new Map();
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
133
|
+
// By sanitized name and by the raw entry name from the source path ([id] stays [id]).
|
|
134
|
+
for (const out of Object.values(bundle)) {
|
|
135
|
+
if (out.type !== 'chunk' || !out.isEntry)
|
|
136
|
+
continue;
|
|
137
|
+
byName.set(out.name, base + out.fileName);
|
|
138
|
+
// Only island chunks: a client page's ?render chunk would otherwise take its island's place.
|
|
139
|
+
if (out.facadeModuleId && !/[?&]render\b/.test(out.facadeModuleId))
|
|
140
|
+
byName.set(entryName(root, out.facadeModuleId.replace(/\?.*$/, '')), base + out.fileName);
|
|
141
|
+
}
|
|
96
142
|
for (const out of Object.values(bundle)) {
|
|
97
143
|
if (out.type !== 'chunk' || !out.code.includes(CHUNK_TOKEN))
|
|
98
144
|
continue;
|
|
@@ -121,46 +167,76 @@ export default function clarusjs() {
|
|
|
121
167
|
const dist = dirname(out);
|
|
122
168
|
const manifestFile = resolve(dist, 'clarusjs-manifest.json');
|
|
123
169
|
rmSync(manifestFile, { force: true }); // a page reading the manifest must never see the previous build's
|
|
124
|
-
const { routes, readers } = await prerender(entry, out, manifestFile);
|
|
125
|
-
writeManifest(dist, routes, builder.config.base);
|
|
170
|
+
const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
|
|
171
|
+
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
126
172
|
// Pages that read the manifest saw none on the first pass: render them again now that it exists.
|
|
127
173
|
if (readers.length) {
|
|
128
174
|
await prerender(entry, out, manifestFile, readers);
|
|
129
|
-
writeManifest(dist, routes, builder.config.base);
|
|
175
|
+
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
130
176
|
}
|
|
177
|
+
if (options.adapter === 'netlify')
|
|
178
|
+
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route));
|
|
131
179
|
},
|
|
132
180
|
resolveId(id) {
|
|
133
181
|
if (id === '/cl-loader.js')
|
|
134
182
|
return here('../runtime/loader');
|
|
183
|
+
if (id === '/cl-router.js')
|
|
184
|
+
return here('../runtime/router');
|
|
135
185
|
if (id === ENTRY)
|
|
136
186
|
return '\0' + ENTRY;
|
|
137
187
|
},
|
|
138
188
|
load(id) {
|
|
139
189
|
if (id !== '\0' + ENTRY)
|
|
140
190
|
return;
|
|
141
|
-
const
|
|
191
|
+
const urls = builtUrls();
|
|
192
|
+
const loaderUrl = urls?.get(LOADER_ENTRY) ?? '/cl-loader.js';
|
|
193
|
+
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
194
|
+
// Built: hashed chunk URLs. Dev: the source, served as JS by Vite.
|
|
195
|
+
const client = {};
|
|
196
|
+
for (const [route, file] of clientPages(root, modes)) {
|
|
197
|
+
const key = `${relative(root, file).split(sep).join('/')}?render`;
|
|
198
|
+
const url = urls ? urls.get(key) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
199
|
+
if (!url)
|
|
200
|
+
throw new Error(`clarusjs: no client chunk for ${key}`);
|
|
201
|
+
client[route] = url;
|
|
202
|
+
}
|
|
142
203
|
return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
|
|
143
|
-
`
|
|
204
|
+
`import { registerViews, render } from ${JSON.stringify(here('../server/views'))}\n` +
|
|
205
|
+
// Every view under src/, for render(name, props) in server code. Also exported for apps that import the build.
|
|
206
|
+
`registerViews(import.meta.glob('/src/**/*.tscl'))\n` +
|
|
207
|
+
`export { render }\n` +
|
|
208
|
+
`export default createHandler(import.meta.glob('/src/pages/**/*.tscl'), {\n` +
|
|
209
|
+
` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
|
|
210
|
+
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
211
|
+
` modes: ${JSON.stringify(modes)},\n` +
|
|
212
|
+
` routerUrl: ${JSON.stringify(routerUrl)},\n` +
|
|
213
|
+
` client: ${JSON.stringify(client)},\n` +
|
|
214
|
+
` base: ${JSON.stringify(base)},\n` +
|
|
215
|
+
`})\n`;
|
|
144
216
|
},
|
|
145
217
|
transform: {
|
|
146
218
|
filter: { id: /\.tscl(\?|$)/ },
|
|
147
219
|
handler(code, id) {
|
|
148
220
|
const file = id.replace(/\?.*$/, '');
|
|
149
221
|
// ?render: a component's server render function, used in the browser to render children of islands.
|
|
150
|
-
const
|
|
222
|
+
const renderQuery = /[?&]render\b/.test(id);
|
|
223
|
+
const target = this.environment.config.consumer === 'server' || renderQuery ? 'server' : 'client';
|
|
151
224
|
// ponytail: ?import makes Vite's dev transform middleware serve .tscl as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
|
|
152
225
|
const consumer = this.environment.config.consumer;
|
|
153
226
|
// Server build: chunk URLs come from the client manifest. Client build (a ?render child): the chunk doesn't
|
|
154
227
|
// exist yet, so write a placeholder that generateBundle swaps for the real file name. Dev: the source URL.
|
|
155
228
|
const urls = consumer === 'server' ? builtUrls() : undefined;
|
|
229
|
+
// Built URLs by entry name, or by source key when the name was sanitized ([tag] → _tag_).
|
|
156
230
|
const clientUrl = urls
|
|
157
|
-
? urls.get(entryName(root, file))
|
|
231
|
+
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/'))
|
|
158
232
|
: command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
|
|
159
233
|
if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
|
|
160
234
|
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
161
235
|
}
|
|
162
236
|
try {
|
|
163
|
-
|
|
237
|
+
// A ?render module runs in the browser: its child components must be render modules too.
|
|
238
|
+
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
239
|
+
return { code: compile(code, { file, target, clientUrl, renderImports }).code, map: null };
|
|
164
240
|
}
|
|
165
241
|
catch (err) {
|
|
166
242
|
if (err instanceof ClarusError)
|
|
@@ -174,7 +250,13 @@ export default function clarusjs() {
|
|
|
174
250
|
const outDir = resolve(server.config.root, server.config.build.outDir);
|
|
175
251
|
const base = server.config.base; // e.g. '/' or '/docs/'; Vite strips it after this middleware
|
|
176
252
|
server.middlewares.use((req, _res, next) => {
|
|
177
|
-
|
|
253
|
+
let url;
|
|
254
|
+
try {
|
|
255
|
+
url = decodeURIComponent((req.url ?? '/').split('?')[0]);
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return next(); // a malformed %-escape names no built page
|
|
259
|
+
}
|
|
178
260
|
const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
|
|
179
261
|
if (inBase !== undefined) {
|
|
180
262
|
// A built page wins; anything else (assets, /x.css) falls through to Vite's static files.
|
|
@@ -184,6 +266,26 @@ export default function clarusjs() {
|
|
|
184
266
|
}
|
|
185
267
|
next();
|
|
186
268
|
});
|
|
269
|
+
// Server routes go to the built handler, as they would in production; anything else that isn't a file is a 404.
|
|
270
|
+
return () => {
|
|
271
|
+
server.middlewares.use(async (req, res, next) => {
|
|
272
|
+
try {
|
|
273
|
+
const entry = resolve(server.config.root, SERVER_OUT, 'index.mjs');
|
|
274
|
+
if (!existsSync(entry))
|
|
275
|
+
return next();
|
|
276
|
+
const app = (await import(__rewriteRelativeImportExtension(pathToFileURL(entry).href)));
|
|
277
|
+
if (!app.default.isServerPath((req.url ?? '/').split('?')[0]))
|
|
278
|
+
return next();
|
|
279
|
+
const response = await app.default.fetch(toRequest(req));
|
|
280
|
+
if (response.status === 404)
|
|
281
|
+
return next();
|
|
282
|
+
await sendResponse(res, response);
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
next(err);
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
};
|
|
187
289
|
},
|
|
188
290
|
configureServer(server) {
|
|
189
291
|
return () => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. SSR, SSG and CSR from one component model, built on Vite.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -52,6 +52,10 @@
|
|
|
52
52
|
"./manifest": {
|
|
53
53
|
"types": "./dist/server/manifest.d.ts",
|
|
54
54
|
"default": "./dist/server/manifest.js"
|
|
55
|
+
},
|
|
56
|
+
"./views": {
|
|
57
|
+
"types": "./dist/server/views.d.ts",
|
|
58
|
+
"default": "./dist/server/views.js"
|
|
55
59
|
}
|
|
56
60
|
},
|
|
57
61
|
"bin": {
|