clarusjs 0.5.0 → 0.7.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 +2 -0
- package/dist/compiler/index.d.ts +6 -0
- package/dist/compiler/index.js +42 -3
- package/dist/compiler/parse.d.ts +9 -0
- package/dist/compiler/parse.js +32 -3
- package/dist/runtime/fragments.d.ts +5 -0
- package/dist/runtime/fragments.js +74 -0
- package/dist/runtime/loader.js +19 -2
- package/dist/runtime/router.js +16 -9
- package/dist/server/handler.d.ts +14 -1
- package/dist/server/handler.js +80 -13
- package/dist/server/views.js +1 -1
- package/dist/vite/build.d.ts +2 -2
- package/dist/vite/build.js +6 -3
- package/dist/vite/links.d.ts +18 -0
- package/dist/vite/links.js +93 -0
- package/dist/vite/manifest.js +2 -2
- package/dist/vite/netlify.d.ts +2 -2
- package/dist/vite/netlify.js +8 -4
- package/dist/vite/plugin.d.ts +28 -0
- package/dist/vite/plugin.js +224 -42
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
<p align="center"><strong>Clear, compiled views.</strong></p>
|
|
8
8
|
|
|
9
|
+
<p align="center"><a href="https://clarusjs.com">Documentation</a> · <a href="https://clarusjs.com/guide/getting-started">Getting started</a> · <a href="https://www.npmjs.com/package/clarusjs">npm</a></p>
|
|
10
|
+
|
|
9
11
|
Write components in a familiar template language. clarusjs compiles them to plain server HTML and ships JavaScript
|
|
10
12
|
only for the parts that are interactive. Static sites, server rendering and client apps share one component model,
|
|
11
13
|
and you can always see where each line runs.
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -3,14 +3,20 @@ export { ClarusError } from './errors.ts';
|
|
|
3
3
|
* `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
|
|
4
4
|
* browser (a client route's page, or a component re-rendered inside an island).
|
|
5
5
|
*/
|
|
6
|
+
/** `scope`: the id that scopes this component's styles (default: from the file name). */
|
|
6
7
|
export type CompileOptions = {
|
|
7
8
|
file: string;
|
|
8
9
|
target: 'server' | 'client';
|
|
9
10
|
clientUrl?: string;
|
|
10
11
|
renderImports?: boolean;
|
|
12
|
+
scope?: string;
|
|
11
13
|
};
|
|
14
|
+
/** `css`: the component's stylesheet (scoped blocks wrapped in @scope, global ones as written); '' without <style>. */
|
|
12
15
|
export type CompileResult = {
|
|
13
16
|
code: string;
|
|
14
17
|
stateful: boolean;
|
|
18
|
+
css: string;
|
|
15
19
|
};
|
|
16
20
|
export declare function compile(source: string, options: CompileOptions): CompileResult;
|
|
21
|
+
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
|
|
22
|
+
export declare function scopeId(file: string): string;
|
package/dist/compiler/index.js
CHANGED
|
@@ -5,10 +5,49 @@ import { lower } from './ir.js';
|
|
|
5
5
|
import { parse } from './parse.js';
|
|
6
6
|
export { ClarusError } from './errors.js';
|
|
7
7
|
export function compile(source, options) {
|
|
8
|
-
const
|
|
8
|
+
const parsed = parse(source, options.file);
|
|
9
|
+
let css = '';
|
|
10
|
+
if (parsed.styles.some((s) => !s.global)) {
|
|
11
|
+
// Native @scope: rules apply inside the component's top-level elements (style those with :scope) and stop at
|
|
12
|
+
// the next component's elements. The top-level elements are marked so the scope can find them.
|
|
13
|
+
const id = options.scope ?? scopeId(options.file);
|
|
14
|
+
const components = new Set(parsed.imports.map((imp) => imp.name));
|
|
15
|
+
markRoots(parsed.nodes, id, components);
|
|
16
|
+
for (const s of parsed.styles)
|
|
17
|
+
css += s.global ? s.css : `@scope ([data-cl-c="${id}"]) to ([data-cl-c]) {${s.css.replace(/\s*$/, '')}\n}\n`;
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
css = parsed.styles.map((s) => s.css).join('');
|
|
21
|
+
}
|
|
22
|
+
const ir = lower(parsed, options.file, source);
|
|
9
23
|
if (options.target === 'client')
|
|
10
|
-
return { code: emitClient(ir), stateful: ir.stateful };
|
|
24
|
+
return { code: emitClient(ir), stateful: ir.stateful, css };
|
|
11
25
|
if (ir.stateful && !options.clientUrl)
|
|
12
26
|
throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
|
|
13
|
-
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful };
|
|
27
|
+
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css };
|
|
28
|
+
}
|
|
29
|
+
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
|
|
30
|
+
export function scopeId(file) {
|
|
31
|
+
let h = 0x811c9dc5; // FNV-1a
|
|
32
|
+
for (let i = 0; i < file.length; i++)
|
|
33
|
+
h = Math.imul(h ^ file.charCodeAt(i), 0x01000193);
|
|
34
|
+
const name = (file.split(/[\\/]/).pop() ?? 'c').replace(/\.tscl$/, '').replace(/[^\w-]/g, '') || 'c';
|
|
35
|
+
return `${name}-${(h >>> 0).toString(36)}`;
|
|
36
|
+
}
|
|
37
|
+
/** The component's top-level HTML elements (also inside top-level @if/@for) get data-cl-c="id". */
|
|
38
|
+
function markRoots(nodes, id, components) {
|
|
39
|
+
for (const node of nodes) {
|
|
40
|
+
if (node.type === 'element' && !components.has(node.tag) && node.tag !== 'slot') {
|
|
41
|
+
node.attrs.push({ kind: 'static', name: 'data-cl-c', value: id, start: node.start });
|
|
42
|
+
}
|
|
43
|
+
else if (node.type === 'if') {
|
|
44
|
+
for (const b of node.branches)
|
|
45
|
+
markRoots(b.children, id, components);
|
|
46
|
+
}
|
|
47
|
+
else if (node.type === 'for') {
|
|
48
|
+
markRoots(node.children, id, components);
|
|
49
|
+
if (node.empty)
|
|
50
|
+
markRoots(node.empty, id, components);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
14
53
|
}
|
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -101,6 +101,15 @@ export type ParsedFile = {
|
|
|
101
101
|
code: string;
|
|
102
102
|
start: number;
|
|
103
103
|
};
|
|
104
|
+
styles: {
|
|
105
|
+
css: string;
|
|
106
|
+
global: boolean;
|
|
107
|
+
start: number;
|
|
108
|
+
}[];
|
|
109
|
+
cssImports: {
|
|
110
|
+
from: string;
|
|
111
|
+
start: number;
|
|
112
|
+
}[];
|
|
104
113
|
nodes: TemplateNode[];
|
|
105
114
|
};
|
|
106
115
|
export declare function parse(source: string, file: string): ParsedFile;
|
package/dist/compiler/parse.js
CHANGED
|
@@ -5,8 +5,9 @@ const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?
|
|
|
5
5
|
const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
6
6
|
const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
7
7
|
const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
|
|
8
|
+
const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
|
|
8
9
|
export function parse(source, file) {
|
|
9
|
-
const out = { inputs: [], imports: [], typeImports: [], dataImports: [], nodes: [] };
|
|
10
|
+
const out = { inputs: [], imports: [], typeImports: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
|
|
10
11
|
let i = 0;
|
|
11
12
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
12
13
|
const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
|
|
@@ -32,6 +33,11 @@ export function parse(source, file) {
|
|
|
32
33
|
else
|
|
33
34
|
out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + line.indexOf(m[1], 7) });
|
|
34
35
|
}
|
|
36
|
+
else if ((m = CSS_IMPORT_RE.exec(line))) {
|
|
37
|
+
if (!/\.css(\?|$)/.test(m[2]))
|
|
38
|
+
fail(`@import without a name only takes a stylesheet (.css): "${m[2]}"`, i);
|
|
39
|
+
out.cssImports.push({ from: m[2], start: i });
|
|
40
|
+
}
|
|
35
41
|
else
|
|
36
42
|
fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
|
|
37
43
|
i = end;
|
|
@@ -367,9 +373,21 @@ export function parse(source, file) {
|
|
|
367
373
|
fail(`unclosed <${tag}>`, start);
|
|
368
374
|
const selfClosing = source.startsWith('/>', i);
|
|
369
375
|
i += selfClosing ? 2 : 1;
|
|
370
|
-
if (tag === 'script') {
|
|
376
|
+
if (tag === 'script' && list.some((a) => a.name === 'inline')) {
|
|
377
|
+
// <script inline>: written out as is and run where it stands (e.g. in <head>, before the first paint).
|
|
378
|
+
const bound = list.find((a) => a.kind !== 'static');
|
|
379
|
+
if (bound)
|
|
380
|
+
fail('an inline script takes static attributes only', bound.start);
|
|
381
|
+
const end = source.indexOf('</script>', i);
|
|
382
|
+
if (end === -1)
|
|
383
|
+
fail('unclosed <script inline>', start);
|
|
384
|
+
const kids = selfClosing ? [] : [{ type: 'text', value: source.slice(i, end), start: i }];
|
|
385
|
+
nodes.push({ type: 'element', tag, attrs: list.filter((a) => a.name !== 'inline'), children: kids, start });
|
|
386
|
+
i = selfClosing ? i : end + '</script>'.length;
|
|
387
|
+
}
|
|
388
|
+
else if (tag === 'script') {
|
|
371
389
|
if (parent)
|
|
372
|
-
fail('<script> must be at the top level', start);
|
|
390
|
+
fail('<script> must be at the top level (a component script); add `inline` for a script that runs where it stands', start);
|
|
373
391
|
if (out.script)
|
|
374
392
|
fail('only one <script> block is allowed', start);
|
|
375
393
|
const end = source.indexOf('</script>', i);
|
|
@@ -378,6 +396,17 @@ export function parse(source, file) {
|
|
|
378
396
|
out.script = { code: source.slice(i, end), start: i };
|
|
379
397
|
i = end + '</script>'.length;
|
|
380
398
|
}
|
|
399
|
+
else if (tag === 'style' && !parent) {
|
|
400
|
+
// A top-level <style> is the component's stylesheet. One inside markup (a layout's <head>) stays HTML.
|
|
401
|
+
const end = source.indexOf('</style>', i);
|
|
402
|
+
if (end === -1)
|
|
403
|
+
fail('unclosed <style>', start);
|
|
404
|
+
const hole = source.slice(i, end).indexOf('{{');
|
|
405
|
+
if (hole !== -1)
|
|
406
|
+
fail('{{ }} holes are not supported in a component <style>: set a CSS custom property from the template instead (style="--x: {{ x }}")', i + hole);
|
|
407
|
+
out.styles.push({ css: source.slice(i, end), global: list.some((a) => a.name === 'global'), start: i });
|
|
408
|
+
i = end + '</style>'.length;
|
|
409
|
+
}
|
|
381
410
|
else if (list.some((a) => a.name === 'verbatim')) {
|
|
382
411
|
// Everything up to </tag> is text: no holes, tags or directives.
|
|
383
412
|
const attr = list.find((a) => a.name === 'verbatim');
|
|
@@ -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,74 @@
|
|
|
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
|
+
// The page's stylesheets: add the ones not loaded yet to <head>, and wait for them, so nothing shows unstyled.
|
|
29
|
+
const loading = [];
|
|
30
|
+
for (const link of doc.querySelectorAll('link[rel="stylesheet"]')) {
|
|
31
|
+
link.remove();
|
|
32
|
+
if (document.head.querySelector(`link[rel="stylesheet"][href="${CSS.escape(link.getAttribute('href'))}"]`))
|
|
33
|
+
continue;
|
|
34
|
+
const added = document.createElement('link');
|
|
35
|
+
added.rel = 'stylesheet';
|
|
36
|
+
added.href = link.getAttribute('href');
|
|
37
|
+
loading.push(new Promise((done) => { added.onload = added.onerror = done; }));
|
|
38
|
+
document.head.append(added);
|
|
39
|
+
}
|
|
40
|
+
await Promise.all(loading);
|
|
41
|
+
if (!isCurrent())
|
|
42
|
+
return;
|
|
43
|
+
// Persisted elements move into the new page as they are, with their state and attached islands.
|
|
44
|
+
for (const old of document.querySelectorAll('[data-cl-persist]')) {
|
|
45
|
+
next.querySelector(`[data-cl-persist="${CSS.escape(old.getAttribute('data-cl-persist'))}"]`)?.replaceWith(old);
|
|
46
|
+
}
|
|
47
|
+
document.title = doc.title;
|
|
48
|
+
old.replaceWith(next);
|
|
49
|
+
globalThis.__clAttach?.(next);
|
|
50
|
+
}
|
|
51
|
+
const navigation = typeof document !== 'undefined' ? globalThis.navigation : undefined;
|
|
52
|
+
// Only the latest navigation may change the document; a URL that failed loads normally, never intercepted again
|
|
53
|
+
// (the reload of a failed URL is itself a navigation to it, which the fallback check lets through).
|
|
54
|
+
let latest = 0;
|
|
55
|
+
let fallback = '';
|
|
56
|
+
navigation?.addEventListener('navigate', (event) => {
|
|
57
|
+
const e = event;
|
|
58
|
+
if (!e.canIntercept || e.hashChange || e.downloadRequest !== null || e.formData)
|
|
59
|
+
return;
|
|
60
|
+
const url = new URL(e.destination.url);
|
|
61
|
+
if (url.href === fallback)
|
|
62
|
+
return;
|
|
63
|
+
const id = ++latest;
|
|
64
|
+
const isCurrent = () => latest === id && !e.signal.aborted;
|
|
65
|
+
e.intercept({
|
|
66
|
+
handler: () => swap(url, fetch, isCurrent).catch(() => {
|
|
67
|
+
if (!isCurrent())
|
|
68
|
+
return;
|
|
69
|
+
fallback = url.href;
|
|
70
|
+
// The URL is already committed: reload it (assign() would only move within the page when it has a #hash).
|
|
71
|
+
location.reload();
|
|
72
|
+
}),
|
|
73
|
+
});
|
|
74
|
+
});
|
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) {
|
|
@@ -135,5 +146,11 @@ export async function attachAll(root = document, load = lastLoad) {
|
|
|
135
146
|
// Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook.
|
|
136
147
|
;
|
|
137
148
|
globalThis.__clAttach = (root) => void attachAll(root);
|
|
138
|
-
if (typeof document !== 'undefined')
|
|
149
|
+
if (typeof document !== 'undefined') {
|
|
150
|
+
// Islands never affect layout. Installed on the document (not in <head>), so it survives head swaps by the client
|
|
151
|
+
// router; the server also writes it as a <style> for the first paint.
|
|
152
|
+
const sheet = new CSSStyleSheet();
|
|
153
|
+
sheet.replaceSync('cl-island{display:contents}');
|
|
154
|
+
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
|
|
139
155
|
attachAll();
|
|
156
|
+
}
|
package/dist/runtime/router.js
CHANGED
|
@@ -45,24 +45,31 @@ isCurrent = () => true) {
|
|
|
45
45
|
load(found.r),
|
|
46
46
|
get(data).then(async (res) => {
|
|
47
47
|
if (!res.ok)
|
|
48
|
-
throw new Error(`${res.status
|
|
48
|
+
throw new Error(`${res.status} ${data}`);
|
|
49
49
|
return parse(await res.text());
|
|
50
50
|
}),
|
|
51
51
|
]);
|
|
52
52
|
if (!isCurrent())
|
|
53
53
|
return false;
|
|
54
54
|
const doc = new DOMParser().parseFromString(page.render(props), 'text/html');
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
doc.
|
|
58
|
-
// The page's <title> comes with its head; its own <html> attributes (lang, dir, …) replace the previous page's.
|
|
55
|
+
// The head stays (its stylesheets are every client page's, linked by the shell); the title and the page's own
|
|
56
|
+
// <html> attributes (lang, dir, …) are the new page's.
|
|
57
|
+
document.title = doc.title;
|
|
59
58
|
const root = document.documentElement;
|
|
60
59
|
for (const { name } of [...root.attributes])
|
|
61
60
|
root.removeAttribute(name);
|
|
62
61
|
for (const { name, value } of [...doc.documentElement.attributes])
|
|
63
62
|
root.setAttribute(name, value);
|
|
64
|
-
document.head.replaceWith(doc.head);
|
|
65
63
|
document.body.replaceWith(doc.body);
|
|
64
|
+
// The page's inline head scripts (such as setting the theme before paint) run once, as on a normal load.
|
|
65
|
+
for (const old of doc.head.querySelectorAll('script:not([src])')) {
|
|
66
|
+
const script = document.createElement('script');
|
|
67
|
+
script.textContent = old.textContent;
|
|
68
|
+
document.head.append(script);
|
|
69
|
+
script.remove();
|
|
70
|
+
}
|
|
71
|
+
// Attaches the new page's islands; the loader also releases the old page's.
|
|
72
|
+
;
|
|
66
73
|
globalThis.__clAttach?.(document.body);
|
|
67
74
|
return true;
|
|
68
75
|
}
|
|
@@ -74,7 +81,7 @@ if (routes) {
|
|
|
74
81
|
show(new URL(location.href), table, undefined, undefined, () => latest === 1).catch((err) => {
|
|
75
82
|
if (latest !== 1)
|
|
76
83
|
return;
|
|
77
|
-
document.body.textContent = err.message.startsWith('
|
|
84
|
+
document.body.textContent = err.message.startsWith('404') ? 'Page not found.' : 'Could not load page.';
|
|
78
85
|
});
|
|
79
86
|
// A URL that failed to render is loaded normally, never intercepted again (no retry loop). canIntercept is
|
|
80
87
|
// only true for same-origin navigations, so no origin check is needed.
|
|
@@ -82,7 +89,7 @@ if (routes) {
|
|
|
82
89
|
const navigation = globalThis.navigation;
|
|
83
90
|
navigation?.addEventListener('navigate', (event) => {
|
|
84
91
|
const e = event;
|
|
85
|
-
if (!e.canIntercept || e.hashChange || e.downloadRequest
|
|
92
|
+
if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
|
|
86
93
|
return;
|
|
87
94
|
const url = new URL(e.destination.url);
|
|
88
95
|
if (url.href === fallback || !matchRoute(table, url.pathname))
|
|
@@ -94,7 +101,7 @@ if (routes) {
|
|
|
94
101
|
if (!isCurrent())
|
|
95
102
|
return;
|
|
96
103
|
fallback = url.href;
|
|
97
|
-
location.assign(
|
|
104
|
+
location.reload(); // the URL is already committed; assign() would stay in the page with a #hash
|
|
98
105
|
}),
|
|
99
106
|
});
|
|
100
107
|
});
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ type DataModule = {
|
|
|
14
14
|
request: Request;
|
|
15
15
|
}): object | Promise<object>;
|
|
16
16
|
};
|
|
17
|
-
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.
|
|
17
|
+
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
18
18
|
export declare function routeFromFile(file: string): string;
|
|
19
19
|
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
|
|
20
20
|
loaderUrl?: string;
|
|
@@ -25,6 +25,14 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
25
25
|
routerUrl?: string;
|
|
26
26
|
/** Vite's base ('/' or '/docs/'): client routes are listed at their browser paths, under it. */
|
|
27
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;
|
|
32
|
+
/** URL of the stylesheet with every component's <style>, linked from every page. */
|
|
33
|
+
stylesUrl?: string;
|
|
34
|
+
/** Stylesheets each page imports (directly or through its components), by route as its file names it. */
|
|
35
|
+
css?: Record<string, string[]>;
|
|
28
36
|
}): {
|
|
29
37
|
fetch(request: Request): Promise<Response>;
|
|
30
38
|
routes: string[];
|
|
@@ -33,4 +41,9 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
33
41
|
hasLoader(route: string): Promise<boolean>;
|
|
34
42
|
isServerPath(pathname: string): boolean;
|
|
35
43
|
};
|
|
44
|
+
/**
|
|
45
|
+
* A page's fragment: its <title>, then the element marked data-cl-swap (the region fragment navigation replaces), or
|
|
46
|
+
* its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
|
|
47
|
+
*/
|
|
48
|
+
export declare function toFragment(html: string): string;
|
|
36
49
|
export {};
|
package/dist/server/handler.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { modeFor } from './modes.js';
|
|
2
2
|
import { stringify } from '../runtime/serialize.js';
|
|
3
3
|
const DATA = '__data.json';
|
|
4
|
+
const FRAG = 'index.frag.html';
|
|
4
5
|
/** JSON that is safe inside a <script> element and in any HTML context: '<' never appears raw. */
|
|
5
6
|
const safeJson = (json) => json.replace(/</g, '\\u003c');
|
|
6
7
|
/** A whole path segment that is a parameter: [id], [$id]. Anything else, like v[2], is literal text. */
|
|
@@ -17,9 +18,9 @@ function compile(path) {
|
|
|
17
18
|
}).join('/');
|
|
18
19
|
return { keys, regex: new RegExp(`^${source}$`) };
|
|
19
20
|
}
|
|
20
|
-
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.
|
|
21
|
+
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
21
22
|
export function routeFromFile(file) {
|
|
22
|
-
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.
|
|
23
|
+
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
|
|
23
24
|
return path || '/';
|
|
24
25
|
}
|
|
25
26
|
export function createHandler(pages, options = {}) {
|
|
@@ -46,11 +47,14 @@ export function createHandler(pages, options = {}) {
|
|
|
46
47
|
}
|
|
47
48
|
return null;
|
|
48
49
|
}
|
|
50
|
+
// A page's stylesheet links: what it imports, then the component styles (so components can build on the base).
|
|
51
|
+
const links = (urls) => [...new Set([...urls, ...(options.stylesUrl ? [options.stylesUrl] : [])])].map((u) => `<link rel="stylesheet" href="${u}">`).join('');
|
|
52
|
+
const pageLinks = (route) => links(options.css?.[route.path] ?? []);
|
|
49
53
|
// entries() per route, asked once: prerendering and requests see the same list. null when there is none.
|
|
50
54
|
const entriesCache = new Map();
|
|
51
55
|
function entriesOf(route) {
|
|
52
56
|
if (!entriesCache.has(route)) {
|
|
53
|
-
const file = `/${route.file.replace(/\.
|
|
57
|
+
const file = `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
|
|
54
58
|
entriesCache.set(route, (async () => {
|
|
55
59
|
const mod = data[file] ? await data[file]() : undefined;
|
|
56
60
|
return mod?.entries ? await mod.entries() : null;
|
|
@@ -69,13 +73,16 @@ export function createHandler(pages, options = {}) {
|
|
|
69
73
|
serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
|
|
70
74
|
/** Whether a URL path belongs to a server route (what a host must send to this handler instead of a file). */
|
|
71
75
|
isServerPath(pathname) {
|
|
72
|
-
const
|
|
76
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
77
|
+
// <page>/index.frag.html belongs to that page when it exists; otherwise it is an ordinary path.
|
|
78
|
+
const owner = options.fragments && pathname.endsWith(`/${FRAG}`) ? match(trim(pathname.slice(0, -FRAG.length - 1) || '/')) : null;
|
|
79
|
+
const found = owner ?? match(trim(pathname));
|
|
73
80
|
return Boolean(found && modeFor(found.route.path, modes) === 'server');
|
|
74
81
|
},
|
|
75
82
|
/** Whether a route (as its file names it) has a load(). */
|
|
76
83
|
async hasLoader(path) {
|
|
77
84
|
const route = routes.find((r) => r.path === path);
|
|
78
|
-
const file = route && `/${route.file.replace(/\.
|
|
85
|
+
const file = route && `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
|
|
79
86
|
return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
|
|
80
87
|
},
|
|
81
88
|
/** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
|
|
@@ -90,12 +97,15 @@ export function createHandler(pages, options = {}) {
|
|
|
90
97
|
// A client page's data, fetched by the router: written next to its shell.
|
|
91
98
|
if (mode === 'client')
|
|
92
99
|
out.push(path === '/' ? `/${DATA}` : `${path}/${DATA}`);
|
|
100
|
+
// A static page's fragment, for fragment navigation.
|
|
101
|
+
else if (options.fragments)
|
|
102
|
+
out.push(path === '/' ? `/${FRAG}` : `${path}/${FRAG}`);
|
|
93
103
|
};
|
|
94
104
|
if (!route.keys.length) {
|
|
95
105
|
add(route.path);
|
|
96
106
|
continue;
|
|
97
107
|
}
|
|
98
|
-
const dataFile = route.file.replace(/\.
|
|
108
|
+
const dataFile = route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
99
109
|
const list = await entriesOf(route);
|
|
100
110
|
if (!list)
|
|
101
111
|
throw new Error(`${route.path} is a dynamic route: export entries() from ${dataFile} to list the pages to prerender`);
|
|
@@ -107,9 +117,9 @@ export function createHandler(pages, options = {}) {
|
|
|
107
117
|
const value = params[key];
|
|
108
118
|
// Each value fills one path segment and names a folder in the build: never empty, '.' or '..'.
|
|
109
119
|
// Path separators on any OS ('/', '\\') and NUL could step out of that folder once the segment is decoded.
|
|
110
|
-
// __data.json
|
|
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 "${
|
|
120
|
+
// __data.json and index.frag.html are a page's data and fragment files, so they can't also name a page.
|
|
121
|
+
if (typeof value !== 'string' || value === '' || value === '.' || value === '..' || value === DATA || value === FRAG || /[/\\\0]/.test(value)) {
|
|
122
|
+
throw new Error(`${dataFile}: entries() gave ${JSON.stringify(value)} for "${key}"; each value must be a non-empty string without "/" or "\\", and not ".", "..", "${DATA}" or "${FRAG}"`);
|
|
113
123
|
}
|
|
114
124
|
return encodeURIComponent(value);
|
|
115
125
|
}).join('/'));
|
|
@@ -134,6 +144,15 @@ export function createHandler(pages, options = {}) {
|
|
|
134
144
|
wantsData = true;
|
|
135
145
|
}
|
|
136
146
|
}
|
|
147
|
+
// <static or server route>/index.frag.html: that page's fragment, for fragment navigation.
|
|
148
|
+
let wantsFrag = false;
|
|
149
|
+
if (options.fragments && !wantsData && pathname.endsWith(`/${FRAG}`)) {
|
|
150
|
+
const owner = match(trim(pathname.slice(0, -FRAG.length - 1) || '/'));
|
|
151
|
+
if (owner && modeFor(owner.route.path, modes) !== 'client') {
|
|
152
|
+
found = owner;
|
|
153
|
+
wantsFrag = true;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
137
156
|
const head = request.method === 'HEAD';
|
|
138
157
|
const notFound = () => new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
139
158
|
const mode = found && modeFor(found.route.path, modes);
|
|
@@ -148,13 +167,15 @@ export function createHandler(pages, options = {}) {
|
|
|
148
167
|
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
149
168
|
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
150
169
|
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
170
|
+
// Every client page's stylesheets: the router keeps the head, so this is all they get.
|
|
171
|
+
links(routes.filter((r) => client[r.path]).flatMap((r) => options.css?.[r.path] ?? [])) +
|
|
151
172
|
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${safeJson(JSON.stringify(table))}</script>` +
|
|
152
173
|
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
153
174
|
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
154
175
|
return new Response(head ? null : shell, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
155
176
|
}
|
|
156
177
|
let props = found.params;
|
|
157
|
-
const dataFile = found.route.file.replace(/\.
|
|
178
|
+
const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
158
179
|
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
159
180
|
if (mod?.load) {
|
|
160
181
|
let loaded;
|
|
@@ -175,11 +196,21 @@ export function createHandler(pages, options = {}) {
|
|
|
175
196
|
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
176
197
|
}
|
|
177
198
|
const html = (await found.route.load()).render(props);
|
|
199
|
+
if (wantsFrag) {
|
|
200
|
+
// The page's stylesheet links go right after its title, so fragment navigation can load any that are missing.
|
|
201
|
+
const fragment = toFragment(html).replace(/^(<title\b[^>]*>[\s\S]*?<\/title\s*>)/i, (t) => t + pageLinks(found.route));
|
|
202
|
+
return new Response(head ? null : fragment, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
203
|
+
}
|
|
178
204
|
const visible = maskComments(html);
|
|
179
205
|
const hasIslands = visible.includes('<cl-island ');
|
|
180
|
-
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk.
|
|
181
|
-
|
|
182
|
-
const
|
|
206
|
+
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk. With fragment
|
|
207
|
+
// navigation every page gets the navigation script instead, which brings the loader for islands that arrive.
|
|
208
|
+
const nav = options.fragments === true;
|
|
209
|
+
const sheet = pageLinks(found.route);
|
|
210
|
+
const style = sheet + (hasIslands || nav ? '<style>cl-island{display:contents}</style>' : ''); // islands never affect layout
|
|
211
|
+
const script = nav
|
|
212
|
+
? `<script type="module" src="${options.navUrl ?? '/cl-nav.js'}"></script>`
|
|
213
|
+
: hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
|
|
183
214
|
const body = /<html[\s>]/i.test(visible)
|
|
184
215
|
? fullDocument(html, style, script)
|
|
185
216
|
: `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title>${style}</head><body>${html}${script}</body></html>`;
|
|
@@ -192,6 +223,42 @@ function failure(message) {
|
|
|
192
223
|
console.error(`[clarusjs] ${message}`);
|
|
193
224
|
return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
194
225
|
}
|
|
226
|
+
/**
|
|
227
|
+
* A page's fragment: its <title>, then the element marked data-cl-swap (the region fragment navigation replaces), or
|
|
228
|
+
* its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
|
|
229
|
+
*/
|
|
230
|
+
export function toFragment(html) {
|
|
231
|
+
// Comments and raw-text contents (scripts, styles, textareas, the title) can hold tag-shaped text: blank them out.
|
|
232
|
+
const masked = maskComments(html).replace(/(<(script|style|textarea|title)\b[^>]*>)([\s\S]*?)(<\/\2\s*>)/gi, (_, open, _tag, body, close) => open + ' '.repeat(body.length) + close);
|
|
233
|
+
const title = /<title\b[^>]*>[\s\S]*?<\/title\s*>/i.exec(masked);
|
|
234
|
+
const titleHtml = title ? html.slice(title.index, title.index + title[0].length) : '<title>clarusjs</title>';
|
|
235
|
+
// The first start tag that carries a data-cl-swap attribute (boolean or with a value), attributes parsed properly.
|
|
236
|
+
const tags = /<([a-zA-Z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
|
|
237
|
+
let marked = null;
|
|
238
|
+
for (let m = tags.exec(masked); m; m = tags.exec(masked)) {
|
|
239
|
+
const names = [...m[2].matchAll(/\s+([^\s"'>/=]+)(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?/g)].map((a) => a[1].toLowerCase());
|
|
240
|
+
if (names.includes('data-cl-swap')) {
|
|
241
|
+
marked = m;
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (marked) {
|
|
246
|
+
const tag = marked[1].toLowerCase();
|
|
247
|
+
const same = new RegExp(`<(/?)${tag}(?=[\\s>/])`, 'gi');
|
|
248
|
+
same.lastIndex = marked.index;
|
|
249
|
+
let depth = 0;
|
|
250
|
+
for (let m = same.exec(masked); m; m = same.exec(masked)) {
|
|
251
|
+
depth += m[1] ? -1 : 1;
|
|
252
|
+
if (depth === 0)
|
|
253
|
+
return titleHtml + html.slice(marked.index, masked.indexOf('>', m.index) + 1);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const open = /<body\b[^>]*>/i.exec(masked);
|
|
257
|
+
const close = masked.lastIndexOf('</body>');
|
|
258
|
+
if (!open || close === -1)
|
|
259
|
+
return `${titleHtml}<body>${html}</body>`;
|
|
260
|
+
return titleHtml + html.slice(open.index, close) + '</body>';
|
|
261
|
+
}
|
|
195
262
|
/** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
|
|
196
263
|
function maskComments(html) {
|
|
197
264
|
return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
|
package/dist/server/views.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// which types each name with that view's inputs.
|
|
4
4
|
/** '/src/components/pill.tscl' → 'components/pill' */
|
|
5
5
|
export function viewName(file) {
|
|
6
|
-
return file.replace(/^.*?\/src\//, '').replace(/\.
|
|
6
|
+
return file.replace(/^.*?\/src\//, '').replace(/\.[^./]+$/, '');
|
|
7
7
|
}
|
|
8
8
|
// On globalThis: the bundled server and an app's own `import 'clarusjs/views'` may be two copies of this module.
|
|
9
9
|
const store = globalThis;
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/** Absolute paths of every
|
|
2
|
-
export declare function findClarusFiles(srcDir: string): string[];
|
|
1
|
+
/** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
|
|
2
|
+
export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
|
|
3
3
|
/**
|
|
4
4
|
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
5
5
|
* Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
|
package/dist/vite/build.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import { spawnSync } from 'node:child_process';
|
|
3
3
|
import { readdirSync } from 'node:fs';
|
|
4
4
|
import { resolve } from 'node:path';
|
|
5
|
-
/** Absolute paths of every
|
|
6
|
-
export function findClarusFiles(srcDir) {
|
|
5
|
+
/** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
|
|
6
|
+
export function findClarusFiles(srcDir, extensions = ['.tscl']) {
|
|
7
7
|
let entries;
|
|
8
8
|
try {
|
|
9
9
|
entries = readdirSync(srcDir, { recursive: true });
|
|
@@ -11,7 +11,7 @@ export function findClarusFiles(srcDir) {
|
|
|
11
11
|
catch {
|
|
12
12
|
return [];
|
|
13
13
|
}
|
|
14
|
-
return entries.filter((f) => f.endsWith(
|
|
14
|
+
return entries.filter((f) => extensions.some((ext) => f.endsWith(ext))).map((f) => resolve(srcDir, f)).sort();
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
17
|
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
@@ -30,6 +30,9 @@ export function routeToFile(route) {
|
|
|
30
30
|
// A client page's data file is written as itself, next to the page's shell.
|
|
31
31
|
if (path === '__data.json' || path.endsWith('/__data.json'))
|
|
32
32
|
return path;
|
|
33
|
+
// A page's fragment, likewise.
|
|
34
|
+
if (path === 'index.frag.html' || path.endsWith('/index.frag.html'))
|
|
35
|
+
return path;
|
|
33
36
|
return path ? `${path}/index.html` : 'index.html';
|
|
34
37
|
}
|
|
35
38
|
/**
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type LinkIssue = {
|
|
2
|
+
kind: 'pages' | 'anchors';
|
|
3
|
+
page: string;
|
|
4
|
+
href: string;
|
|
5
|
+
message: string;
|
|
6
|
+
};
|
|
7
|
+
type Options = {
|
|
8
|
+
outDir: string;
|
|
9
|
+
/** Every built route (static pages and client shells), as URLs without the base. */
|
|
10
|
+
routes: string[];
|
|
11
|
+
/** Server routes as their files name them ('/account/[id]'): rendered per request, so any match counts. */
|
|
12
|
+
serverRoutes: string[];
|
|
13
|
+
/** Client routes render in the browser: their pages exist, but their anchors can't be checked at build. */
|
|
14
|
+
clientRoutes: string[];
|
|
15
|
+
base: string;
|
|
16
|
+
};
|
|
17
|
+
export declare function checkLinks(options: Options): LinkIssue[];
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Build-time link checking: once every page is built, links between pages and to #anchors are checked against
|
|
2
|
+
// what was actually written. Reads dist/client only; reporting and failing are up to the caller.
|
|
3
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { routeToFile } from './build.js';
|
|
6
|
+
// A stray % is kept as written, as routeToFile does, instead of failing the build with a URIError.
|
|
7
|
+
const decode = (s) => { try {
|
|
8
|
+
return decodeURIComponent(s);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return s;
|
|
12
|
+
} };
|
|
13
|
+
const isFile = (path) => { try {
|
|
14
|
+
return statSync(path).isFile();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
} };
|
|
19
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
20
|
+
/** Edit distance, for "did you mean". */
|
|
21
|
+
function distance(a, b) {
|
|
22
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
23
|
+
for (let i = 1; i <= a.length; i++) {
|
|
24
|
+
let prev = row[0];
|
|
25
|
+
row[0] = i;
|
|
26
|
+
for (let j = 1; j <= b.length; j++) {
|
|
27
|
+
const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
28
|
+
prev = row[j];
|
|
29
|
+
row[j] = next;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return row[b.length];
|
|
33
|
+
}
|
|
34
|
+
/** The closest candidate, if it is close enough to be a likely typo. */
|
|
35
|
+
function closest(target, candidates) {
|
|
36
|
+
let best;
|
|
37
|
+
let score = Infinity;
|
|
38
|
+
for (const c of candidates) {
|
|
39
|
+
const d = distance(target, c);
|
|
40
|
+
if (d < score) {
|
|
41
|
+
best = c;
|
|
42
|
+
score = d;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return best !== undefined && score <= Math.max(2, Math.floor(target.length / 3)) ? best : undefined;
|
|
46
|
+
}
|
|
47
|
+
const ids = (html) => new Set([...html.matchAll(/\s(?:id|name)="([^"]+)"/g)].map((m) => m[1]));
|
|
48
|
+
const hrefs = (html) => [...html.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)].map((m) => m[1].replace(/&/g, '&'));
|
|
49
|
+
export function checkLinks(options) {
|
|
50
|
+
const { outDir } = options;
|
|
51
|
+
// An absolute base (https://cdn.example.com/docs/) is compared by its path.
|
|
52
|
+
const base = /^https?:\/\//.test(options.base) ? new URL(options.base).pathname : options.base;
|
|
53
|
+
const routes = new Set(options.routes.map(trim));
|
|
54
|
+
const client = new Set(options.clientRoutes.map(trim));
|
|
55
|
+
const serverPatterns = options.serverRoutes.map((r) => new RegExp(`^${r.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`));
|
|
56
|
+
const html = new Map();
|
|
57
|
+
const read = (route) => {
|
|
58
|
+
if (!html.has(route)) {
|
|
59
|
+
const file = resolve(outDir, routeToFile(route));
|
|
60
|
+
html.set(route, existsSync(file) ? readFileSync(file, 'utf8') : '');
|
|
61
|
+
}
|
|
62
|
+
return html.get(route);
|
|
63
|
+
};
|
|
64
|
+
const issues = [];
|
|
65
|
+
for (const page of [...routes].filter((r) => !client.has(r))) {
|
|
66
|
+
for (const href of hrefs(read(page))) {
|
|
67
|
+
if (/^[a-z][\w+.-]*:|^\/\//i.test(href) || href === '')
|
|
68
|
+
continue; // external, mailto:, tel:, …
|
|
69
|
+
const url = new URL(href, `http://site${base}${page === '/' ? '' : page.slice(1) + '/'}`);
|
|
70
|
+
if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base)
|
|
71
|
+
continue; // outside this site
|
|
72
|
+
let path = trim(decode(url.pathname.slice(base.length - 1)) || '/');
|
|
73
|
+
if (path.endsWith('/index.html'))
|
|
74
|
+
path = trim(path.slice(0, -'index.html'.length));
|
|
75
|
+
const anchor = decode(url.hash.slice(1));
|
|
76
|
+
const isPage = routes.has(path);
|
|
77
|
+
const exists = isPage || serverPatterns.some((re) => re.test(path)) || isFile(resolve(outDir, `.${path}`)); // a directory without a page is a 404
|
|
78
|
+
if (!exists) {
|
|
79
|
+
const guess = closest(path, routes);
|
|
80
|
+
issues.push({ kind: 'pages', page, href, message: `no page at ${path}${guess ? ` (did you mean ${guess}?)` : ''}` });
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!anchor || !isPage || client.has(path))
|
|
84
|
+
continue;
|
|
85
|
+
const targets = ids(read(path));
|
|
86
|
+
if (targets.has(anchor))
|
|
87
|
+
continue;
|
|
88
|
+
const guess = closest(anchor, targets);
|
|
89
|
+
issues.push({ kind: 'anchors', page, href, message: `no #${anchor} on ${path}${guess ? ` (did you mean #${guess}?)` : ''}` });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return issues;
|
|
93
|
+
}
|
package/dist/vite/manifest.js
CHANGED
|
@@ -70,8 +70,8 @@ export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
|
70
70
|
const manifest = { version: 1, routes: {} };
|
|
71
71
|
const dataFile = (route) => (route === '/' ? '/__data.json' : `${route}/__data.json`);
|
|
72
72
|
for (const route of routes) {
|
|
73
|
-
if (route.endsWith('/__data.json'))
|
|
74
|
-
continue; //
|
|
73
|
+
if (route.endsWith('/__data.json') || route.endsWith('/index.frag.html'))
|
|
74
|
+
continue; // data and fragments, not pages
|
|
75
75
|
const isClient = routes.includes(dataFile(route));
|
|
76
76
|
// A client route's loader runs when its data file is written.
|
|
77
77
|
const ran = loaded.includes(route) || (isClient && loaded.includes(dataFile(route)));
|
package/dist/vite/netlify.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
|
|
2
|
-
export declare function netlifyPaths(route: string): string[];
|
|
2
|
+
export declare function netlifyPaths(route: string, fragments?: boolean): string[];
|
|
3
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;
|
|
4
|
+
export declare function writeNetlifyFunction(root: string, serverEntry: string, serverRoutes: string[], fragments?: boolean): void;
|
package/dist/vite/netlify.js
CHANGED
|
@@ -4,7 +4,7 @@ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
|
4
4
|
import { dirname, relative, resolve, sep } from 'node:path';
|
|
5
5
|
const FUNCTION = '.netlify/v1/functions/clarusjs-server.mjs';
|
|
6
6
|
/** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
|
|
7
|
-
export function netlifyPaths(route) {
|
|
7
|
+
export function netlifyPaths(route, fragments = false) {
|
|
8
8
|
const segments = route.split('/');
|
|
9
9
|
const keyOf = (seg) => /^\[([A-Za-z_$][\w$]*)\]$/.exec(seg)?.[1];
|
|
10
10
|
const valid = (key) => /^[A-Za-z_]\w*$/.test(key);
|
|
@@ -23,10 +23,14 @@ export function netlifyPaths(route) {
|
|
|
23
23
|
return `:${valid(key) ? key : fresh()}`;
|
|
24
24
|
return seg.replace(/[:*?+(){}\\]/g, '\\$&'); // literal text, not pattern syntax
|
|
25
25
|
}).join('/');
|
|
26
|
-
|
|
26
|
+
const paths = path === '/' || path === '' ? ['/'] : [path, `${path}/`];
|
|
27
|
+
// The page's fragment, for fragment navigation, comes from the same function.
|
|
28
|
+
if (fragments)
|
|
29
|
+
paths.push(path === '/' || path === '' ? '/index.frag.html' : `${path}/index.frag.html`);
|
|
30
|
+
return paths;
|
|
27
31
|
}
|
|
28
32
|
/** Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. */
|
|
29
|
-
export function writeNetlifyFunction(root, serverEntry, serverRoutes) {
|
|
33
|
+
export function writeNetlifyFunction(root, serverEntry, serverRoutes, fragments = false) {
|
|
30
34
|
const file = resolve(root, FUNCTION);
|
|
31
35
|
if (!serverRoutes.length) {
|
|
32
36
|
rmSync(file, { force: true });
|
|
@@ -40,7 +44,7 @@ export function writeNetlifyFunction(root, serverEntry, serverRoutes) {
|
|
|
40
44
|
'',
|
|
41
45
|
'export default (request) => handler.fetch(request)',
|
|
42
46
|
'',
|
|
43
|
-
`export const config = ${JSON.stringify({ path: serverRoutes.flatMap(netlifyPaths), preferStatic: true })}`,
|
|
47
|
+
`export const config = ${JSON.stringify({ path: serverRoutes.flatMap((r) => netlifyPaths(r, fragments)), preferStatic: true })}`,
|
|
44
48
|
'',
|
|
45
49
|
].join('\n'));
|
|
46
50
|
}
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -7,5 +7,33 @@ export type ClarusOptions = {
|
|
|
7
7
|
routes?: ModeTable;
|
|
8
8
|
/** Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. */
|
|
9
9
|
adapter?: 'netlify';
|
|
10
|
+
/** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
|
|
11
|
+
fragments?: boolean;
|
|
12
|
+
/** Page sources for other file types, such as Markdown from @clarusjs/content: `sources: [markdown()]`. */
|
|
13
|
+
sources?: Source[];
|
|
14
|
+
/**
|
|
15
|
+
* Build-time link checking, after every page is built. `pages`: links to pages or files that don't exist (default
|
|
16
|
+
* 'error'). `anchors`: links to a #id the target page doesn't have (default 'warn'). `strict`: warnings fail too.
|
|
17
|
+
*/
|
|
18
|
+
links?: {
|
|
19
|
+
pages?: LinkLevel;
|
|
20
|
+
anchors?: LinkLevel;
|
|
21
|
+
strict?: boolean;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export type LinkLevel = 'error' | 'warn' | 'off';
|
|
25
|
+
/**
|
|
26
|
+
* A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any
|
|
27
|
+
* page. `route` is the page's route when the file is under src/pages.
|
|
28
|
+
*/
|
|
29
|
+
export type Source = {
|
|
30
|
+
extension: string;
|
|
31
|
+
toTscl(code: string, file: string, context: SourceContext): string;
|
|
32
|
+
};
|
|
33
|
+
/** `root`: the app root. `addDependency(file)`: another file the output depends on (rebuilt when it changes in dev). */
|
|
34
|
+
export type SourceContext = {
|
|
35
|
+
route: string;
|
|
36
|
+
root: string;
|
|
37
|
+
addDependency(file: string): void;
|
|
10
38
|
};
|
|
11
39
|
export default function clarusjs(options?: ClarusOptions): Plugin;
|
package/dist/vite/plugin.js
CHANGED
|
@@ -8,14 +8,16 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
8
8
|
};
|
|
9
9
|
// The clarusjs Vite plugin: a thin adapter around the compiler.
|
|
10
10
|
// Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
|
|
11
|
-
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
12
12
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
13
13
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
|
-
import { isRunnableDevEnvironment } from 'vite';
|
|
15
|
-
import { compile, ClarusError } from '../compiler/index.js';
|
|
14
|
+
import { isRunnableDevEnvironment, normalizePath } from 'vite';
|
|
15
|
+
import { compile, scopeId, ClarusError } from '../compiler/index.js';
|
|
16
|
+
import { parse } from '../compiler/parse.js';
|
|
16
17
|
import { findClarusFiles, prerender } from './build.js';
|
|
17
18
|
import { writeManifest } from './manifest.js';
|
|
18
19
|
import { writeNetlifyFunction } from './netlify.js';
|
|
20
|
+
import { checkLinks } from './links.js';
|
|
19
21
|
import { checkModes, modeFor } from '../server/modes.js';
|
|
20
22
|
import { routeFromFile } from '../server/handler.js';
|
|
21
23
|
import { sendResponse, toRequest } from './node.js';
|
|
@@ -30,17 +32,85 @@ export function clientUrlFor(root, file) {
|
|
|
30
32
|
}
|
|
31
33
|
const LOADER_ENTRY = 'cl-loader';
|
|
32
34
|
const ROUTER_ENTRY = 'cl-router';
|
|
35
|
+
const NAV_ENTRY = 'cl-nav';
|
|
36
|
+
const STYLES_ENTRY = 'cl-styles';
|
|
37
|
+
// Every component's <style>, generated into one stylesheet (gitignored, like the rest of .clarusjs/).
|
|
38
|
+
const STYLES_FILE = '.clarusjs/styles.css';
|
|
39
|
+
/** Scope ids come from the path relative to the app root, so server, client and stylesheet always agree. */
|
|
40
|
+
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
41
|
+
/**
|
|
42
|
+
* Each page's stylesheets (absolute paths), from its own `@import './x.css'` and its components', transitively.
|
|
43
|
+
* Dependencies come first, so a layout's base CSS is linked before what the page adds.
|
|
44
|
+
*/
|
|
45
|
+
function pageStylesheets(root, files) {
|
|
46
|
+
const deps = new Map();
|
|
47
|
+
const read = (file) => {
|
|
48
|
+
if (!deps.has(file)) {
|
|
49
|
+
let parsed;
|
|
50
|
+
try {
|
|
51
|
+
parsed = parse(files.read(file, root), file);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
parsed = null;
|
|
55
|
+
} // errors surface on compile
|
|
56
|
+
// Relative to the file, or root-relative ('/src/layouts/docs.tscl', as Vite resolves it).
|
|
57
|
+
const near = (from) => {
|
|
58
|
+
const path = from.replace(/\?.*$/, '');
|
|
59
|
+
return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
|
|
60
|
+
};
|
|
61
|
+
deps.set(file, {
|
|
62
|
+
css: parsed?.cssImports.map((c) => near(c.from)) ?? [],
|
|
63
|
+
components: parsed?.imports.filter((imp) => /^[./]/.test(imp.from)).map((imp) => near(imp.from)) ?? [],
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return deps.get(file);
|
|
67
|
+
};
|
|
68
|
+
const collect = (file, out, seen) => {
|
|
69
|
+
if (seen.has(file))
|
|
70
|
+
return;
|
|
71
|
+
seen.add(file);
|
|
72
|
+
const { css, components } = read(file);
|
|
73
|
+
for (const c of components)
|
|
74
|
+
if (existsSync(c))
|
|
75
|
+
collect(c, out, seen);
|
|
76
|
+
for (const sheet of css)
|
|
77
|
+
if (!out.includes(sheet))
|
|
78
|
+
out.push(sheet);
|
|
79
|
+
};
|
|
80
|
+
const pages = new Map();
|
|
81
|
+
for (const file of files.find(resolve(root, 'src/pages'))) {
|
|
82
|
+
const out = [];
|
|
83
|
+
collect(file, out, new Set());
|
|
84
|
+
pages.set(routeFromFile(`/${relative(root, file).split(sep).join('/')}`), out);
|
|
85
|
+
}
|
|
86
|
+
return pages;
|
|
87
|
+
}
|
|
88
|
+
/** Write .clarusjs/styles.css from every component under src/; false when no component has a <style>. */
|
|
89
|
+
function writeStyles(root, files) {
|
|
90
|
+
let css = '';
|
|
91
|
+
for (const file of files.find(resolve(root, 'src'))) {
|
|
92
|
+
try {
|
|
93
|
+
const out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file) }).css;
|
|
94
|
+
if (out)
|
|
95
|
+
css += `/* ${relative(root, file).split(sep).join('/')} */\n${out}`;
|
|
96
|
+
}
|
|
97
|
+
catch { } // compile errors are reported when the component itself is compiled
|
|
98
|
+
}
|
|
99
|
+
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
100
|
+
writeFileSync(resolve(root, STYLES_FILE), css);
|
|
101
|
+
return css !== '';
|
|
102
|
+
}
|
|
33
103
|
// Client entry name of a client-mode page's browser render module.
|
|
34
104
|
const renderEntry = (name) => `render/${name}`;
|
|
35
105
|
const CLIENT_OUT = 'dist/client';
|
|
36
106
|
// Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
|
|
37
107
|
const CHUNK_TOKEN = '__CLARUS_CHUNK__';
|
|
38
108
|
const SERVER_OUT = 'dist/server';
|
|
39
|
-
const entryName = (root, file) => relative(root, file).replace(/\.
|
|
109
|
+
const entryName = (root, file) => relative(root, file).replace(/\.[^./\\]+$/, '');
|
|
40
110
|
/** Client-mode pages: route (as the file names it) → absolute file. */
|
|
41
|
-
function clientPages(appRoot, modes) {
|
|
111
|
+
function clientPages(appRoot, modes, files) {
|
|
42
112
|
const pages = new Map();
|
|
43
|
-
for (const file of
|
|
113
|
+
for (const file of files.find(resolve(appRoot, 'src/pages'))) {
|
|
44
114
|
const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
|
|
45
115
|
if (modeFor(route, modes) === 'client')
|
|
46
116
|
pages.set(route, file);
|
|
@@ -50,6 +120,29 @@ function clientPages(appRoot, modes) {
|
|
|
50
120
|
export default function clarusjs(options = {}) {
|
|
51
121
|
const modes = options.routes ?? {};
|
|
52
122
|
checkModes(modes);
|
|
123
|
+
const sources = options.sources ?? [];
|
|
124
|
+
for (const src of sources) {
|
|
125
|
+
if (!/^\.[\w-]+$/.test(src.extension))
|
|
126
|
+
throw new Error(`clarusjs: a source extension must look like ".md", got "${src.extension}"`);
|
|
127
|
+
if (src.extension === '.tscl')
|
|
128
|
+
throw new Error('clarusjs: .tscl files are compiled directly; a source needs its own extension');
|
|
129
|
+
}
|
|
130
|
+
const extensions = ['.tscl', ...sources.map((src) => src.extension)];
|
|
131
|
+
// Component files of every kind, read as .tscl text (a source's output, or the file itself).
|
|
132
|
+
// Page sources only apply under src/pages: elsewhere (src/parts, …) their files are plain files, not components.
|
|
133
|
+
const files = {
|
|
134
|
+
find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
|
|
135
|
+
read: (file, appRoot) => {
|
|
136
|
+
const code = readFileSync(file, 'utf8');
|
|
137
|
+
const src = sources.find((x) => file.endsWith(x.extension));
|
|
138
|
+
if (!src)
|
|
139
|
+
return code;
|
|
140
|
+
const rel = relative(appRoot, file).split(sep).join('/');
|
|
141
|
+
return src.toTscl(code, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root: appRoot, addDependency: () => { } });
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
const fileRe = new RegExp(`\\.(${extensions.map((e) => e.slice(1)).join('|')})(\\?|$)`);
|
|
145
|
+
const glob = (dir) => JSON.stringify(extensions.map((e) => `${dir}/**/*${e}`));
|
|
53
146
|
if (options.adapter !== undefined && options.adapter !== 'netlify') {
|
|
54
147
|
throw new Error(`clarusjs: adapter "${options.adapter}" is not supported; use 'netlify'`);
|
|
55
148
|
}
|
|
@@ -104,14 +197,24 @@ export default function clarusjs(options = {}) {
|
|
|
104
197
|
// Client entries: the island loader plus every stateful component. Stateless components never reach the client.
|
|
105
198
|
const appRoot = resolve(userConfig.root ?? process.cwd());
|
|
106
199
|
const input = { [LOADER_ENTRY]: here('../runtime/loader') };
|
|
107
|
-
for (const file of
|
|
108
|
-
if (compile(
|
|
200
|
+
for (const file of files.find(resolve(appRoot, 'src'))) {
|
|
201
|
+
if (compile(files.read(file, appRoot), { file, target: 'client' }).stateful)
|
|
109
202
|
input[entryName(appRoot, file)] = file;
|
|
110
203
|
}
|
|
111
204
|
// Client routes: the router, and each page's render function for the browser.
|
|
112
|
-
const client = clientPages(appRoot, modes);
|
|
205
|
+
const client = clientPages(appRoot, modes, files);
|
|
113
206
|
if (client.size)
|
|
114
207
|
input[ROUTER_ENTRY] = here('../runtime/router');
|
|
208
|
+
if (options.fragments)
|
|
209
|
+
input[NAV_ENTRY] = here('../runtime/fragments');
|
|
210
|
+
if (writeStyles(appRoot, files))
|
|
211
|
+
input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
|
|
212
|
+
// Stylesheets imported by pages and components: each goes through Vite's CSS pipeline as its own entry.
|
|
213
|
+
for (const sheet of new Set([...pageStylesheets(appRoot, files).values()].flat())) {
|
|
214
|
+
if (!existsSync(sheet))
|
|
215
|
+
throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
|
|
216
|
+
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '')}`] = sheet;
|
|
217
|
+
}
|
|
115
218
|
for (const file of client.values())
|
|
116
219
|
input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
|
|
117
220
|
config.builder = {};
|
|
@@ -174,50 +277,122 @@ export default function clarusjs(options = {}) {
|
|
|
174
277
|
await prerender(entry, out, manifestFile, readers);
|
|
175
278
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
176
279
|
}
|
|
280
|
+
// Links between pages and to anchors, checked against what was written.
|
|
281
|
+
const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
|
|
282
|
+
const issues = checkLinks({
|
|
283
|
+
outDir: out,
|
|
284
|
+
routes: pageRoutes,
|
|
285
|
+
serverRoutes: server.map((x) => x.route),
|
|
286
|
+
clientRoutes: pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`)),
|
|
287
|
+
base: builder.config.base,
|
|
288
|
+
});
|
|
289
|
+
const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
|
|
290
|
+
// Each problem names the page's source file, and the line where the link is written literally.
|
|
291
|
+
const sourceOf = new Map(files.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
|
|
292
|
+
const locate = (page, href) => {
|
|
293
|
+
const file = sourceOf.get(page) ?? [...sourceOf].find(([route]) => new RegExp(`^${route.replace(/\[[^\]]+\]/g, '[^/]+')}$`).test(page))?.[1];
|
|
294
|
+
if (!file)
|
|
295
|
+
return page;
|
|
296
|
+
const rel = relative(builder.config.root, file).split(sep).join('/');
|
|
297
|
+
const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href));
|
|
298
|
+
return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
|
|
299
|
+
};
|
|
300
|
+
const errors = [];
|
|
301
|
+
for (const issue of issues) {
|
|
302
|
+
const level = levels[issue.kind];
|
|
303
|
+
if (level === 'off')
|
|
304
|
+
continue;
|
|
305
|
+
const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
|
|
306
|
+
if (level === 'error' || options.links?.strict)
|
|
307
|
+
errors.push(text);
|
|
308
|
+
else
|
|
309
|
+
builder.config.logger.warn(`clarusjs: ${text}`);
|
|
310
|
+
}
|
|
311
|
+
if (errors.length)
|
|
312
|
+
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
177
313
|
if (options.adapter === 'netlify')
|
|
178
|
-
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route));
|
|
314
|
+
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
179
315
|
},
|
|
180
316
|
resolveId(id) {
|
|
181
317
|
if (id === '/cl-loader.js')
|
|
182
318
|
return here('../runtime/loader');
|
|
183
319
|
if (id === '/cl-router.js')
|
|
184
320
|
return here('../runtime/router');
|
|
321
|
+
if (id === '/cl-nav.js')
|
|
322
|
+
return here('../runtime/fragments');
|
|
185
323
|
if (id === ENTRY)
|
|
186
324
|
return '\0' + ENTRY;
|
|
187
325
|
},
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
326
|
+
// order 'pre': a page source's file is read as text before Vite's asset loader can claim it (.txt,
|
|
327
|
+
// assetsInclude), so the transform converts the original text, never a URL module.
|
|
328
|
+
load: { order: 'pre', handler(id) {
|
|
329
|
+
if (id !== '\0' + ENTRY) {
|
|
330
|
+
if (/[?&](raw|url|inline)\b/.test(id) || id.startsWith('\0'))
|
|
331
|
+
return null;
|
|
332
|
+
const file = id.replace(/\?.*$/, '');
|
|
333
|
+
if (!sources.some((x) => file.endsWith(x.extension)) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/'))
|
|
334
|
+
return null;
|
|
335
|
+
return readFileSync(file, 'utf8');
|
|
336
|
+
}
|
|
337
|
+
const urls = builtUrls();
|
|
338
|
+
const loaderUrl = urls?.get(LOADER_ENTRY) ?? '/cl-loader.js';
|
|
339
|
+
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
340
|
+
const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
|
|
341
|
+
// Each page's imported stylesheets: built URLs (by source key), or the source served by Vite in dev.
|
|
342
|
+
const css = {};
|
|
343
|
+
for (const [route, sheets] of pageStylesheets(root, files)) {
|
|
344
|
+
if (!sheets.length)
|
|
345
|
+
continue;
|
|
346
|
+
css[route] = sheets.map((sheet) => {
|
|
347
|
+
const key = relative(root, sheet).split(sep).join('/');
|
|
348
|
+
const url = urls ? urls.get(key) : clientUrlFor(root, sheet).replace(/\?.*$/, '');
|
|
349
|
+
if (!url)
|
|
350
|
+
throw new Error(`clarusjs: no built stylesheet for ${key}`);
|
|
351
|
+
return url;
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
// Built: the hashed stylesheet, if any component has styles. Dev: the generated file, served by Vite.
|
|
355
|
+
const stylesUrl = urls ? urls.get(STYLES_ENTRY) : writeStyles(root, files) ? `/${STYLES_FILE}` : undefined;
|
|
356
|
+
// Built: hashed chunk URLs. Dev: the source, served as JS by Vite.
|
|
357
|
+
const client = {};
|
|
358
|
+
for (const [route, file] of clientPages(root, modes, files)) {
|
|
359
|
+
const key = `${relative(root, file).split(sep).join('/')}?render`;
|
|
360
|
+
const url = urls ? urls.get(key) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
361
|
+
if (!url)
|
|
362
|
+
throw new Error(`clarusjs: no client chunk for ${key}`);
|
|
363
|
+
client[route] = url;
|
|
364
|
+
}
|
|
365
|
+
return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
|
|
366
|
+
`import { registerViews, render } from ${JSON.stringify(here('../server/views'))}\n` +
|
|
367
|
+
// Every view under src/, for render(name, props) in server code. Also exported for apps that import the build.
|
|
368
|
+
`registerViews(import.meta.glob(${JSON.stringify(['/src/**/*.tscl', ...extensions.slice(1).map((e) => `/src/pages/**/*${e}`)])}))\n` +
|
|
369
|
+
`export { render }\n` +
|
|
370
|
+
`export default createHandler(import.meta.glob(${glob('/src/pages')}), {\n` +
|
|
371
|
+
` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
|
|
372
|
+
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
373
|
+
` modes: ${JSON.stringify(modes)},\n` +
|
|
374
|
+
` routerUrl: ${JSON.stringify(routerUrl)},\n` +
|
|
375
|
+
` client: ${JSON.stringify(client)},\n` +
|
|
376
|
+
` base: ${JSON.stringify(base)},\n` +
|
|
377
|
+
` fragments: ${options.fragments === true},\n` +
|
|
378
|
+
` navUrl: ${JSON.stringify(navUrl)},\n` +
|
|
379
|
+
` stylesUrl: ${JSON.stringify(stylesUrl)},\n` +
|
|
380
|
+
` css: ${JSON.stringify(css)},\n` +
|
|
381
|
+
`})\n`;
|
|
382
|
+
} },
|
|
217
383
|
transform: {
|
|
218
|
-
filter: { id:
|
|
219
|
-
handler(
|
|
384
|
+
filter: { id: fileRe },
|
|
385
|
+
handler(raw, id) {
|
|
220
386
|
const file = id.replace(/\?.*$/, '');
|
|
387
|
+
// A page source's file is compiled from the .tscl text it produces: only under src/pages, and never when it is
|
|
388
|
+
// imported as text or a URL (CHANGELOG.md?raw stays a string).
|
|
389
|
+
const src = sources.find((x) => file.endsWith(x.extension));
|
|
390
|
+
if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
|
|
391
|
+
return null;
|
|
392
|
+
const rel = relative(root, file).split(sep).join('/');
|
|
393
|
+
const code = src
|
|
394
|
+
? src.toTscl(raw, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root, addDependency: (dep) => this.addWatchFile(dep) })
|
|
395
|
+
: raw;
|
|
221
396
|
// ?render: a component's server render function, used in the browser to render children of islands.
|
|
222
397
|
const renderQuery = /[?&]render\b/.test(id);
|
|
223
398
|
const target = this.environment.config.consumer === 'server' || renderQuery ? 'server' : 'client';
|
|
@@ -236,7 +411,8 @@ export default function clarusjs(options = {}) {
|
|
|
236
411
|
try {
|
|
237
412
|
// A ?render module runs in the browser: its child components must be render modules too.
|
|
238
413
|
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
239
|
-
|
|
414
|
+
// moduleType: a source extension may have its own built-in type in Rolldown (.txt is text); the output is JS.
|
|
415
|
+
return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
|
|
240
416
|
}
|
|
241
417
|
catch (err) {
|
|
242
418
|
if (err instanceof ClarusError)
|
|
@@ -288,6 +464,12 @@ export default function clarusjs(options = {}) {
|
|
|
288
464
|
};
|
|
289
465
|
},
|
|
290
466
|
configureServer(server) {
|
|
467
|
+
// Component styles change with their .tscl files: regenerate the stylesheet (Vite then updates the page's CSS).
|
|
468
|
+
const restyle = (file) => { if (fileRe.test(file))
|
|
469
|
+
writeStyles(server.config.root, files); };
|
|
470
|
+
server.watcher.on('change', restyle);
|
|
471
|
+
server.watcher.on('add', restyle);
|
|
472
|
+
server.watcher.on('unlink', restyle);
|
|
291
473
|
return () => {
|
|
292
474
|
server.middlewares.use(async (req, res, next) => {
|
|
293
475
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"html-first",
|
|
19
19
|
"typescript"
|
|
20
20
|
],
|
|
21
|
-
"homepage": "https://
|
|
21
|
+
"homepage": "https://clarusjs.com",
|
|
22
22
|
"repository": {
|
|
23
23
|
"type": "git",
|
|
24
24
|
"url": "git+https://github.com/forinda/clarusjs.git",
|