clarusjs 0.8.0 → 0.9.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/dist/check/generate.d.ts +26 -4
- package/dist/check/generate.js +160 -21
- package/dist/cli/check.d.ts +13 -0
- package/dist/cli/check.js +76 -19
- package/dist/cli/index.js +9 -3
- package/dist/cli/mapper.d.ts +25 -0
- package/dist/cli/mapper.js +65 -0
- package/dist/cli/project.d.ts +5 -0
- package/dist/cli/project.js +21 -0
- package/dist/compiler/emit-client.js +23 -4
- package/dist/compiler/emit-server.js +3 -2
- package/dist/compiler/html-expr.js +5 -2
- package/dist/compiler/index.d.ts +8 -1
- package/dist/compiler/index.js +34 -23
- package/dist/compiler/ir.d.ts +13 -0
- package/dist/compiler/ir.js +157 -7
- package/dist/compiler/parse.d.ts +18 -1
- package/dist/compiler/parse.js +134 -6
- package/dist/compiler/script.d.ts +22 -1
- package/dist/compiler/script.js +81 -5
- package/dist/forms/index.d.ts +7 -0
- package/dist/forms/index.js +374 -0
- package/dist/forms/types.d.ts +94 -0
- package/dist/forms/types.js +1 -0
- package/dist/runtime/dom.d.ts +12 -5
- package/dist/runtime/dom.js +76 -5
- package/dist/runtime/env.d.ts +7 -0
- package/dist/runtime/env.js +7 -0
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -35
- package/dist/runtime/index.d.ts +3 -2
- package/dist/runtime/index.js +3 -2
- package/dist/runtime/loader.d.ts +1 -1
- package/dist/runtime/loader.js +38 -5
- package/dist/runtime/navigate.d.ts +38 -0
- package/dist/runtime/navigate.js +88 -0
- package/dist/runtime/navigation.d.ts +88 -0
- package/dist/runtime/navigation.js +165 -0
- package/dist/runtime/router.d.ts +8 -1
- package/dist/runtime/router.js +38 -40
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +4 -2
- package/dist/runtime/signals.d.ts +2 -0
- package/dist/runtime/signals.js +25 -3
- package/dist/server/handler.d.ts +8 -0
- package/dist/server/handler.js +36 -9
- package/dist/vite/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +3 -2
- package/dist/vite/plugin.d.ts +6 -0
- package/dist/vite/plugin.js +82 -20
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/package.json +29 -1
package/dist/runtime/router.js
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
|
-
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
|
|
2
2
|
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
if (extraExtensions) {
|
|
4
|
+
for (var extension in extraExtensions) {
|
|
5
|
+
var suffix = path.slice(-extension.length);
|
|
6
|
+
if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
|
|
7
|
+
var output = extraExtensions[extension];
|
|
8
|
+
return output === extension ? path : path.slice(0, -extension.length) + output;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
}
|
|
3
12
|
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
13
|
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
14
|
});
|
|
@@ -11,6 +20,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
11
20
|
// the island loader attach. Later navigations between client routes are intercepted with the Navigation API;
|
|
12
21
|
// browsers without it simply load pages normally.
|
|
13
22
|
import { parse } from './serialize.js';
|
|
23
|
+
import { latest, takeOver } from './navigate.js';
|
|
14
24
|
/** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
|
|
15
25
|
export function matchRoute(table, pathname) {
|
|
16
26
|
const got = pathname.replace(/(.)\/+$/, '$1').split('/');
|
|
@@ -35,7 +45,8 @@ export function matchRoute(table, pathname) {
|
|
|
35
45
|
}
|
|
36
46
|
/** Render the client route at `url` into the document. False when `url` is not a client route. */
|
|
37
47
|
export async function show(url, table,
|
|
38
|
-
//
|
|
48
|
+
// Awaited right before the swap (where the in-between hooks run): false once a newer navigation has started,
|
|
49
|
+
// then this one must not touch the document.
|
|
39
50
|
isCurrent = () => true, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src)), get = fetch) {
|
|
40
51
|
const found = matchRoute(table, url.pathname);
|
|
41
52
|
if (!found)
|
|
@@ -49,61 +60,48 @@ isCurrent = () => true, load = (src) => import(__rewriteRelativeImportExtension(
|
|
|
49
60
|
return parse(await res.text());
|
|
50
61
|
}),
|
|
51
62
|
]);
|
|
52
|
-
if (!isCurrent())
|
|
63
|
+
if (!(await isCurrent()))
|
|
53
64
|
return false;
|
|
54
|
-
|
|
55
|
-
//
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
65
|
+
// The head stays (its stylesheets are every client page's, linked by the shell); the title gets the site's
|
|
66
|
+
// titleTemplate, from the shell (always set: '%s' without one).
|
|
67
|
+
await swapIn(page.render(props), (title) => document.getElementById('cl-routes').dataset.title.replace('%s', () => title));
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Puts a whole page in: its body, its own <html> attributes (lang, dir, …), its title (through `title`, else as
|
|
72
|
+
* written) and its inline head scripts (such as setting the theme before paint, run once as on a normal load); then
|
|
73
|
+
* attaches its islands (the loader also releases the old page's). The head stays. Resolves once the islands that
|
|
74
|
+
* attach right away are attached.
|
|
75
|
+
*/
|
|
76
|
+
export async function swapIn(html, title = (t) => t) {
|
|
77
|
+
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
59
78
|
const root = document.documentElement;
|
|
60
79
|
for (const { name } of [...root.attributes])
|
|
61
80
|
root.removeAttribute(name);
|
|
62
81
|
for (const { name, value } of [...doc.documentElement.attributes])
|
|
63
82
|
root.setAttribute(name, value);
|
|
83
|
+
document.title = title(doc.title); // before islands attach: the loader announces it
|
|
64
84
|
document.body.replaceWith(doc.body);
|
|
65
|
-
// The page's inline head scripts (such as setting the theme before paint) run once, as on a normal load.
|
|
66
85
|
for (const old of doc.head.querySelectorAll('script:not([src])')) {
|
|
67
86
|
const script = document.createElement('script');
|
|
68
87
|
script.textContent = old.textContent;
|
|
69
88
|
document.head.append(script);
|
|
70
89
|
script.remove();
|
|
71
90
|
}
|
|
72
|
-
|
|
73
|
-
;
|
|
74
|
-
globalThis.__clAttach?.(document.body, 1); // 1: navigated (bytes)
|
|
75
|
-
return true;
|
|
91
|
+
await globalThis.__clAttach?.(document.body, 1); // 1: navigated (bytes)
|
|
76
92
|
}
|
|
77
93
|
const routes = globalThis.document?.getElementById('cl-routes');
|
|
78
94
|
if (routes) {
|
|
79
95
|
const table = JSON.parse(routes.textContent);
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (latest !== 1)
|
|
96
|
+
// The first render is current until a navigation is taken over.
|
|
97
|
+
show(new URL(location.href), table, () => !latest).catch((err) => {
|
|
98
|
+
if (latest)
|
|
84
99
|
return;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
let fallback = '';
|
|
90
|
-
const navigation = globalThis.navigation;
|
|
91
|
-
navigation?.addEventListener('navigate', (event) => {
|
|
92
|
-
const e = event;
|
|
93
|
-
if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
|
|
94
|
-
return;
|
|
95
|
-
const url = new URL(e.destination.url);
|
|
96
|
-
if (url.href === fallback || !matchRoute(table, url.pathname))
|
|
97
|
-
return;
|
|
98
|
-
const id = ++latest;
|
|
99
|
-
const isCurrent = () => latest === id && !e.signal.aborted;
|
|
100
|
-
e.intercept({
|
|
101
|
-
handler: () => show(url, table, isCurrent).then(() => { }, () => {
|
|
102
|
-
if (!isCurrent())
|
|
103
|
-
return;
|
|
104
|
-
fallback = url.href;
|
|
105
|
-
location.reload(); // the URL is already committed; assign() would stay in the page with a #hash
|
|
106
|
-
}),
|
|
107
|
-
});
|
|
100
|
+
// The site's 404 or 500 page, at this same URL (its title as written); plain text when the site has none.
|
|
101
|
+
fetch(routes.dataset.base + (/^404/.test(err.message) ? 404 : 500))
|
|
102
|
+
.then((res) => (res.ok ? res.text() : Promise.reject()))
|
|
103
|
+
.then((html) => swapIn(html), () => { document.body.textContent = 'Could not load page.'; });
|
|
108
104
|
});
|
|
105
|
+
// Later navigations to client routes.
|
|
106
|
+
takeOver((url) => matchRoute(table, url.pathname) && ((url, isCurrent, signal) => show(url, table, isCurrent, undefined, (src) => fetch(src, { signal }))));
|
|
109
107
|
}
|
package/dist/runtime/server.d.ts
CHANGED
|
@@ -4,6 +4,6 @@ export { escape, json, blockHtml, forHtml, regionHtml } from './html.ts';
|
|
|
4
4
|
* Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
|
|
5
5
|
* component has state, the state values it rendered with (`s`), so the browser starts from the same values.
|
|
6
6
|
*/
|
|
7
|
-
export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string): string;
|
|
7
|
+
export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string, paths?: Record<string, unknown>): string;
|
|
8
8
|
/** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
|
|
9
9
|
export declare const attr: typeof attrHtml;
|
package/dist/runtime/server.js
CHANGED
|
@@ -6,10 +6,12 @@ export { escape, json, blockHtml, forHtml, regionHtml } from './html.js';
|
|
|
6
6
|
* Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
|
|
7
7
|
* component has state, the state values it rendered with (`s`), so the browser starts from the same values.
|
|
8
8
|
*/
|
|
9
|
-
export function island(name, src, props, html, state, attach) {
|
|
9
|
+
export function island(name, src, props, html, state, attach, paths) {
|
|
10
10
|
const s = state === undefined ? '' : ` s="${escape(stringify(state))}"`;
|
|
11
11
|
const a = attach && attach !== 'load' ? ` a="${escape(attach)}"` : ''; // when to attach: see runtime/loader.ts
|
|
12
|
-
|
|
12
|
+
// A component bound two ways carries each binding's path for the forms engine (clarusjs/forms), given by its parent.
|
|
13
|
+
const d = Object.entries(paths ?? {}).map(([model, path]) => ` data-cl-path-${escape(model)}="${escape(String(path))}"`).join('');
|
|
14
|
+
return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(stringify(props))}"${s}${a}${d}>${html}</cl-island>`;
|
|
13
15
|
}
|
|
14
16
|
/** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
|
|
15
17
|
export const attr = attrHtml;
|
|
@@ -12,6 +12,8 @@ export declare function scope(fn: () => void): () => void;
|
|
|
12
12
|
export declare function onDispose(fn: () => void): void;
|
|
13
13
|
/** Read signals without subscribing the running effect to them. */
|
|
14
14
|
export declare function untrack<T>(fn: () => T): T;
|
|
15
|
+
/** Run `fn`, then the effects its writes affect, once each: they never see some of its writes without the others. */
|
|
16
|
+
export declare function batch(fn: () => void): void;
|
|
15
17
|
export declare function state<T>(initial: T): Signal<T>;
|
|
16
18
|
export declare function effect(fn: () => void): () => void;
|
|
17
19
|
export declare function derived<T>(fn: () => T): ReadSignal<T>;
|
package/dist/runtime/signals.js
CHANGED
|
@@ -33,6 +33,24 @@ export function untrack(fn) {
|
|
|
33
33
|
current = prev;
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
|
+
// Effects waiting for the current batch to end (null outside a batch).
|
|
37
|
+
let queue = null;
|
|
38
|
+
/** Run `fn`, then the effects its writes affect, once each: they never see some of its writes without the others. */
|
|
39
|
+
export function batch(fn) {
|
|
40
|
+
if (queue)
|
|
41
|
+
return fn();
|
|
42
|
+
queue = new Set();
|
|
43
|
+
try {
|
|
44
|
+
fn();
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
const waiting = queue;
|
|
48
|
+
queue = null;
|
|
49
|
+
for (const e of waiting)
|
|
50
|
+
if (e.active)
|
|
51
|
+
e.run();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
36
54
|
export function state(initial) {
|
|
37
55
|
let value = initial;
|
|
38
56
|
const subs = new Set();
|
|
@@ -49,9 +67,13 @@ export function state(initial) {
|
|
|
49
67
|
if (Object.is(v, value))
|
|
50
68
|
return;
|
|
51
69
|
value = v;
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
70
|
+
if (queue)
|
|
71
|
+
for (const e of subs)
|
|
72
|
+
queue.add(e); // in a batch: run once it ends
|
|
73
|
+
else
|
|
74
|
+
for (const e of [...subs])
|
|
75
|
+
if (e.active)
|
|
76
|
+
e.run(); // an effect disposed earlier in this loop must not run
|
|
55
77
|
},
|
|
56
78
|
};
|
|
57
79
|
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -16,6 +16,12 @@ type DataModule = {
|
|
|
16
16
|
}): object | Promise<object>;
|
|
17
17
|
};
|
|
18
18
|
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
19
|
+
/**
|
|
20
|
+
* A redirect for a server page's `load()` to return: `return redirect('/login')`. 302 by default; 301 or 308 for
|
|
21
|
+
* a page that moved for good, 303 after a form, 307 to keep the method.
|
|
22
|
+
* @see https://clarusjs.com/guide/routing
|
|
23
|
+
*/
|
|
24
|
+
export declare function redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
|
|
19
25
|
export declare function routeFromFile(file: string): string;
|
|
20
26
|
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
|
|
21
27
|
loaderUrl?: string;
|
|
@@ -38,6 +44,8 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
38
44
|
head?: HeadOptions;
|
|
39
45
|
/** The site's public address: canonical URLs and social cards (see head.ts). */
|
|
40
46
|
site?: SiteOptions;
|
|
47
|
+
/** Development: a failing page throws its error (the dev server shows it with its stack) instead of answering 500. */
|
|
48
|
+
dev?: boolean;
|
|
41
49
|
}): {
|
|
42
50
|
fetch(request: Request): Promise<Response>;
|
|
43
51
|
routes: string[];
|
package/dist/server/handler.js
CHANGED
|
@@ -17,6 +17,9 @@ function compile(path) {
|
|
|
17
17
|
}).join('/');
|
|
18
18
|
return { keys, regex: new RegExp(`^${source}$`) };
|
|
19
19
|
}
|
|
20
|
+
export function redirect(to, status = 302) {
|
|
21
|
+
return new Response(null, { status, headers: { location: to } });
|
|
22
|
+
}
|
|
20
23
|
export function routeFromFile(file) {
|
|
21
24
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
|
|
22
25
|
return path || '/';
|
|
@@ -143,6 +146,22 @@ export function createHandler(pages, options = {}) {
|
|
|
143
146
|
return plain();
|
|
144
147
|
return new Response(head ? null : rootLinks(await page.text(), options.base ?? '/'), { status: 404, headers: page.headers });
|
|
145
148
|
};
|
|
149
|
+
const fail = async (message, err) => {
|
|
150
|
+
if (options.dev)
|
|
151
|
+
throw err ?? new Error(message);
|
|
152
|
+
const plain500 = failure(message);
|
|
153
|
+
if (wantsData || wantsFrag || trim(pathname) === '/500' || !routes.some((r) => r.path === '/500'))
|
|
154
|
+
return plain500;
|
|
155
|
+
try {
|
|
156
|
+
const page = await handler.fetch(new Request(new URL('/500', request.url), { method: request.method }));
|
|
157
|
+
if (page.status !== 200)
|
|
158
|
+
return plain500;
|
|
159
|
+
return new Response(head ? null : rootLinks(await page.text(), options.base ?? '/'), { status: 500, headers: page.headers });
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return plain500;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
146
165
|
const mode = found && modeFor(found.route.path, modes);
|
|
147
166
|
if (!found)
|
|
148
167
|
return notFound();
|
|
@@ -153,8 +172,8 @@ export function createHandler(pages, options = {}) {
|
|
|
153
172
|
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
154
173
|
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
155
174
|
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
156
|
-
links(routes.filter((r) => client[r.path]).flatMap((r) => options.css?.[r.path] ?? [])) +
|
|
157
|
-
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes" data-title="${escape(options.head?.titleTemplate ?? '%s')}">${safeJson(JSON.stringify(table))}</script>` +
|
|
175
|
+
links(routes.filter((r) => client[r.path] || r.path === '/404' || r.path === '/500').flatMap((r) => options.css?.[r.path] ?? [])) +
|
|
176
|
+
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes" data-title="${escape(options.head?.titleTemplate ?? '%s')}" data-base="${escape(options.base ?? '/')}">${safeJson(JSON.stringify(table))}</script>` +
|
|
158
177
|
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
159
178
|
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
160
179
|
const { titleTemplate: _, ...siteHead } = options.head ?? {};
|
|
@@ -163,11 +182,11 @@ export function createHandler(pages, options = {}) {
|
|
|
163
182
|
page = completeHead(shell, maskComments, { ...siteHead, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, false) });
|
|
164
183
|
}
|
|
165
184
|
catch (err) {
|
|
166
|
-
return
|
|
185
|
+
return fail(`${found.route.file}: ${err.message}`, err);
|
|
167
186
|
}
|
|
168
187
|
return new Response(head ? null : page, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
169
188
|
}
|
|
170
|
-
let props = found.params;
|
|
189
|
+
let props = found.route.path === '/500' ? { status: 500, ...found.params } : found.params;
|
|
171
190
|
const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
172
191
|
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
173
192
|
if (mod?.load) {
|
|
@@ -176,26 +195,34 @@ export function createHandler(pages, options = {}) {
|
|
|
176
195
|
loaded = await mod.load({ params: found.params, request });
|
|
177
196
|
}
|
|
178
197
|
catch (err) {
|
|
179
|
-
return
|
|
198
|
+
return fail(`${dataFile}: load() failed: ${err?.message ?? err}`, err);
|
|
180
199
|
}
|
|
200
|
+
if (loaded instanceof Response)
|
|
201
|
+
return loaded;
|
|
181
202
|
if (loaded === null || typeof loaded !== 'object' || Array.isArray(loaded)) {
|
|
182
|
-
return
|
|
203
|
+
return fail(`${dataFile}: load() must return an object of page inputs (or a Response, such as redirect()), got ${Array.isArray(loaded) ? 'an array' : loaded === null ? 'null' : typeof loaded}`);
|
|
183
204
|
}
|
|
184
205
|
;
|
|
185
206
|
globalThis.__clLoaderRan = true;
|
|
186
|
-
props = { ...
|
|
207
|
+
props = { ...props, ...loaded };
|
|
187
208
|
}
|
|
188
209
|
if (wantsData) {
|
|
189
210
|
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
190
211
|
}
|
|
191
|
-
let html
|
|
212
|
+
let html;
|
|
213
|
+
try {
|
|
214
|
+
html = (await found.route.load()).render(props);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
return fail(`${found.route.file}: render failed: ${err?.message ?? err}`, err);
|
|
218
|
+
}
|
|
192
219
|
if (!/<html[\s>]/i.test(maskComments(html)))
|
|
193
220
|
html = `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title></head><body>${html}</body></html>`;
|
|
194
221
|
try {
|
|
195
222
|
html = completeHead(html, maskComments, { ...options.head, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, wantsFrag) });
|
|
196
223
|
}
|
|
197
224
|
catch (err) {
|
|
198
|
-
return
|
|
225
|
+
return fail(`${found.route.file}: ${err.message}`, err);
|
|
199
226
|
}
|
|
200
227
|
if (wantsFrag) {
|
|
201
228
|
const fragment = toFragment(html).replace(/^(<title\b[^>]*>[\s\S]*?<\/title\s*>)/i, (t) => t + pageLinks(found.route));
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** `find` ending in '/' is a prefix; otherwise it matches itself, and (unless `exact`) itself followed by '/…'. */
|
|
2
|
+
export type Alias = {
|
|
3
|
+
find: string;
|
|
4
|
+
replacement: string;
|
|
5
|
+
exact?: boolean;
|
|
6
|
+
};
|
|
7
|
+
/** The project's aliases; `vite`: the Vite config's `resolve.alias` (an object or a list). */
|
|
8
|
+
export declare function projectAliases(root: string, vite?: unknown): Alias[];
|
|
9
|
+
/** Where `spec` points when an alias matches it (an absolute path), else undefined. */
|
|
10
|
+
export declare function resolveAlias(spec: string, aliases: Alias[]): string | undefined;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
function readJsonc(text) {
|
|
4
|
+
const bare = text.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '');
|
|
5
|
+
return JSON.parse(bare.replace(/,(\s*[}\]])/g, '$1'));
|
|
6
|
+
}
|
|
7
|
+
export function projectAliases(root, vite = []) {
|
|
8
|
+
const aliases = [{ find: '~/', replacement: resolve(root, 'src') + '/' }];
|
|
9
|
+
const config = ['tsconfig.json', 'jsconfig.json'].map((name) => resolve(root, name)).find(existsSync);
|
|
10
|
+
if (config) {
|
|
11
|
+
let options = {};
|
|
12
|
+
try {
|
|
13
|
+
options = readJsonc(readFileSync(config, 'utf8')).compilerOptions ?? {};
|
|
14
|
+
}
|
|
15
|
+
catch { }
|
|
16
|
+
const base = resolve(root, options.baseUrl ?? '.');
|
|
17
|
+
for (const [key, targets] of Object.entries(options.paths ?? {})) {
|
|
18
|
+
const target = targets?.[0];
|
|
19
|
+
if (!target)
|
|
20
|
+
continue;
|
|
21
|
+
if (key.endsWith('/*') && target.endsWith('/*'))
|
|
22
|
+
aliases.push({ find: key.slice(0, -1), replacement: resolve(base, target.slice(0, -2)) + '/' });
|
|
23
|
+
else if (!key.includes('*'))
|
|
24
|
+
aliases.push({ find: key, replacement: resolve(base, target), exact: true });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const list = Array.isArray(vite) ? vite : vite && typeof vite === 'object' ? Object.entries(vite).map(([find, replacement]) => ({ find, replacement })) : [];
|
|
28
|
+
for (const { find, replacement } of list) {
|
|
29
|
+
if (typeof find === 'string' && typeof replacement === 'string')
|
|
30
|
+
aliases.push({ find, replacement });
|
|
31
|
+
}
|
|
32
|
+
return aliases.sort((a, b) => b.find.length - a.find.length);
|
|
33
|
+
}
|
|
34
|
+
export function resolveAlias(spec, aliases) {
|
|
35
|
+
for (const { find, replacement, exact } of aliases) {
|
|
36
|
+
if (find.endsWith('/') ? spec.startsWith(find) : spec === find)
|
|
37
|
+
return spec === find ? replacement : replacement + spec.slice(find.length);
|
|
38
|
+
if (!exact && !find.endsWith('/') && spec.startsWith(find + '/'))
|
|
39
|
+
return replacement + spec.slice(find.length);
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Alias } from './aliases.ts';
|
|
1
2
|
/** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
|
|
2
3
|
export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
|
|
3
4
|
/**
|
|
@@ -27,4 +28,4 @@ export declare function packageOf(file: string): string | undefined;
|
|
|
27
28
|
* specifiers ('@clarusjs/theme-docs/layout.tscl', resolved as Node would from the app). Real paths, so a workspace
|
|
28
29
|
* package linked into node_modules is one file, not two.
|
|
29
30
|
*/
|
|
30
|
-
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[]): string[];
|
|
31
|
+
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[]): string[];
|
package/dist/vite/build.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resolveAlias } from './aliases.js';
|
|
1
2
|
import { spawnSync } from 'node:child_process';
|
|
2
3
|
import { readdirSync, realpathSync } from 'node:fs';
|
|
3
4
|
import { createRequire } from 'node:module';
|
|
@@ -84,7 +85,7 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
84
85
|
export function packageOf(file) {
|
|
85
86
|
return /.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(file)?.[1].replace(/\\/g, '/');
|
|
86
87
|
}
|
|
87
|
-
export function reachableComponents(root, start, read, extensions) {
|
|
88
|
+
export function reachableComponents(root, start, read, extensions, aliases = []) {
|
|
88
89
|
const require = createRequire(resolve(root, 'package.json'));
|
|
89
90
|
const seen = new Set();
|
|
90
91
|
const queue = start.map((f) => realpathSync(f));
|
|
@@ -106,7 +107,7 @@ export function reachableComponents(root, start, read, extensions) {
|
|
|
106
107
|
continue;
|
|
107
108
|
let target;
|
|
108
109
|
try {
|
|
109
|
-
target = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : require.resolve(spec);
|
|
110
|
+
target = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : resolveAlias(spec, aliases) ?? require.resolve(spec);
|
|
110
111
|
target = realpathSync(target);
|
|
111
112
|
}
|
|
112
113
|
catch {
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export type ClarusOptions = {
|
|
|
24
24
|
anchors?: LinkLevel;
|
|
25
25
|
strict?: boolean;
|
|
26
26
|
};
|
|
27
|
+
/**
|
|
28
|
+
* Paths that moved: `{ '/old': '/new' }` (a site path or a full URL). The build writes a page at each old path that
|
|
29
|
+
* sends visitors on, and `_redirects` lines (a real 301 on Netlify and Cloudflare Pages); dev answers 301.
|
|
30
|
+
* @see https://clarusjs.com/guide/routing
|
|
31
|
+
*/
|
|
32
|
+
redirects?: Record<string, string>;
|
|
27
33
|
/**
|
|
28
34
|
* Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
|
|
29
35
|
* its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
|