clarusjs 0.4.0 → 0.6.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/fragments.d.ts +5 -0
- package/dist/runtime/fragments.js +59 -0
- package/dist/runtime/loader.js +12 -1
- package/dist/runtime/router.d.ts +15 -0
- package/dist/runtime/router.js +101 -0
- package/dist/server/handler.d.ts +33 -0
- package/dist/server/handler.js +229 -10
- 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 +38 -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 +50 -0
- package/dist/vite/plugin.d.ts +10 -1
- package/dist/vite/plugin.js +127 -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,5 @@
|
|
|
1
|
+
import './loader.ts';
|
|
2
|
+
/** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
|
|
3
|
+
export declare function fragmentUrl(url: URL): string;
|
|
4
|
+
/** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
|
|
5
|
+
export declare function swap(url: URL, get?: (url: string) => Promise<Response>, isCurrent?: () => boolean): Promise<void>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Fragment navigation: moving between static and server pages swaps their region (data-cl-swap, or the body)
|
|
2
|
+
// instead of reloading. Browser only. Each page's fragment is <path>/index.frag.html; elements marked
|
|
3
|
+
// data-cl-persist="key" are kept across swaps, and the island loader attaches whatever islands arrive.
|
|
4
|
+
import './loader.js';
|
|
5
|
+
/** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
|
|
6
|
+
export function fragmentUrl(url) {
|
|
7
|
+
return `${url.pathname.replace(/\/+$/, '')}/index.frag.html${url.search}`;
|
|
8
|
+
}
|
|
9
|
+
const region = (doc) => doc.querySelector('[data-cl-swap]') ?? doc.body;
|
|
10
|
+
/** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
|
|
11
|
+
export async function swap(url, get = fetch,
|
|
12
|
+
// False once a newer navigation has started: then this one must not touch the document.
|
|
13
|
+
isCurrent = () => true) {
|
|
14
|
+
const src = fragmentUrl(url);
|
|
15
|
+
const res = await get(src);
|
|
16
|
+
if (!res.ok)
|
|
17
|
+
throw new Error(`${res.status}: ${src}`);
|
|
18
|
+
const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
|
|
19
|
+
if (!isCurrent())
|
|
20
|
+
return;
|
|
21
|
+
const next = region(doc);
|
|
22
|
+
const old = region(document);
|
|
23
|
+
// A body can only replace a body, and a marked region a marked region: otherwise load the page normally.
|
|
24
|
+
if ((next === doc.body) !== (old === document.body))
|
|
25
|
+
throw new Error('different swap regions');
|
|
26
|
+
for (const title of next.querySelectorAll('title'))
|
|
27
|
+
title.remove(); // some parsers leave the leading <title> in the body
|
|
28
|
+
// Persisted elements move into the new page as they are, with their state and attached islands.
|
|
29
|
+
for (const old of document.querySelectorAll('[data-cl-persist]')) {
|
|
30
|
+
next.querySelector(`[data-cl-persist="${CSS.escape(old.getAttribute('data-cl-persist'))}"]`)?.replaceWith(old);
|
|
31
|
+
}
|
|
32
|
+
document.title = doc.title;
|
|
33
|
+
old.replaceWith(next);
|
|
34
|
+
globalThis.__clAttach?.(next);
|
|
35
|
+
}
|
|
36
|
+
const navigation = typeof document !== 'undefined' ? globalThis.navigation : undefined;
|
|
37
|
+
// Only the latest navigation may change the document; a URL that failed loads normally, never intercepted again
|
|
38
|
+
// (the reload of a failed URL is itself a navigation to it, which the fallback check lets through).
|
|
39
|
+
let latest = 0;
|
|
40
|
+
let fallback = '';
|
|
41
|
+
navigation?.addEventListener('navigate', (event) => {
|
|
42
|
+
const e = event;
|
|
43
|
+
if (!e.canIntercept || e.hashChange || e.downloadRequest !== null || e.formData)
|
|
44
|
+
return;
|
|
45
|
+
const url = new URL(e.destination.url);
|
|
46
|
+
if (url.href === fallback)
|
|
47
|
+
return;
|
|
48
|
+
const id = ++latest;
|
|
49
|
+
const isCurrent = () => latest === id && !e.signal.aborted;
|
|
50
|
+
e.intercept({
|
|
51
|
+
handler: () => swap(url, fetch, isCurrent).catch(() => {
|
|
52
|
+
if (!isCurrent())
|
|
53
|
+
return;
|
|
54
|
+
fallback = url.href;
|
|
55
|
+
// The URL is already committed: reload it (assign() would only move within the page when it has a #hash).
|
|
56
|
+
location.reload();
|
|
57
|
+
}),
|
|
58
|
+
});
|
|
59
|
+
});
|
package/dist/runtime/loader.js
CHANGED
|
@@ -9,8 +9,11 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
9
9
|
return path;
|
|
10
10
|
};
|
|
11
11
|
import { parse } from './serialize.js';
|
|
12
|
+
import { scope } from './signals.js';
|
|
12
13
|
// Islands scheduled or loading. `data-cl-ready` is set only after attach() succeeds.
|
|
13
14
|
const loading = new WeakSet();
|
|
15
|
+
// Each attached island's disposer: everything its attach() wired (effects, listeners) is released by it.
|
|
16
|
+
const attached = new Map();
|
|
14
17
|
let lastLoad = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src));
|
|
15
18
|
// Events recorded until an island attaches, then replayed. Clicks and submits are held back (no navigation, no
|
|
16
19
|
// form post) so the island can handle them once it is ready.
|
|
@@ -100,7 +103,7 @@ async function attachOne(el, load, recorded) {
|
|
|
100
103
|
return;
|
|
101
104
|
}
|
|
102
105
|
try {
|
|
103
|
-
mod.attach(el, props, state);
|
|
106
|
+
attached.set(el, scope(() => mod.attach(el, props, state)));
|
|
104
107
|
el.setAttribute('data-cl-ready', '');
|
|
105
108
|
}
|
|
106
109
|
catch (err) {
|
|
@@ -120,6 +123,14 @@ async function attachOne(el, load, recorded) {
|
|
|
120
123
|
*/
|
|
121
124
|
export async function attachAll(root = document, load = lastLoad) {
|
|
122
125
|
lastLoad = load;
|
|
126
|
+
// Islands a navigation swap (or a re-render) took out of the document stop running: their effects and listeners
|
|
127
|
+
// are released. Islands kept across a swap stay connected, so they keep running.
|
|
128
|
+
for (const [el, dispose] of attached) {
|
|
129
|
+
if (!el.isConnected) {
|
|
130
|
+
dispose();
|
|
131
|
+
attached.delete(el);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
123
134
|
const islands = [...root.querySelectorAll('cl-island:not([data-cl-ready]):not([data-cl-error])')].filter((el) => !loading.has(el));
|
|
124
135
|
const now = [];
|
|
125
136
|
for (const el of islands) {
|
|
@@ -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.reload(); // the URL is already committed; assign() would stay in the page with a #hash
|
|
98
|
+
}),
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -1,12 +1,45 @@
|
|
|
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;
|
|
28
|
+
/** Fragment navigation: every static and server page also answers at <path>/index.frag.html. */
|
|
29
|
+
fragments?: boolean;
|
|
30
|
+
/** URL of the fragment navigation script (with fragments on, every static and server page loads it). */
|
|
31
|
+
navUrl?: string;
|
|
8
32
|
}): {
|
|
9
33
|
fetch(request: Request): Promise<Response>;
|
|
10
34
|
routes: string[];
|
|
35
|
+
serverRoutes: string[];
|
|
36
|
+
paths(): Promise<string[]>;
|
|
37
|
+
hasLoader(route: string): Promise<boolean>;
|
|
38
|
+
isServerPath(pathname: string): boolean;
|
|
11
39
|
};
|
|
40
|
+
/**
|
|
41
|
+
* A page's fragment: its <title>, then the element marked data-cl-swap (the region fragment navigation replaces), or
|
|
42
|
+
* its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
|
|
43
|
+
*/
|
|
44
|
+
export declare function toFragment(html: string): string;
|
|
12
45
|
export {};
|