clarusjs 0.7.0 → 0.8.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.js +1 -21
- package/dist/cli/check.js +44 -11
- package/dist/cli/explain.js +0 -1
- package/dist/cli/index.js +0 -1
- package/dist/compiler/emit-client.js +1 -11
- package/dist/compiler/emit-server.js +1 -2
- package/dist/compiler/errors.js +0 -1
- package/dist/compiler/html-expr.js +2 -7
- package/dist/compiler/index.js +10 -8
- package/dist/compiler/ir.d.ts +1 -0
- package/dist/compiler/ir.js +9 -14
- package/dist/compiler/parse.d.ts +1 -0
- package/dist/compiler/parse.js +18 -19
- package/dist/compiler/script.js +2 -31
- package/dist/compiler/shared.js +0 -5
- package/dist/runtime/fragments.js +8 -3
- package/dist/runtime/html.d.ts +2 -0
- package/dist/runtime/html.js +4 -0
- package/dist/runtime/loader.js +39 -2
- package/dist/runtime/router.d.ts +1 -1
- package/dist/runtime/router.js +9 -8
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +1 -1
- package/dist/server/handler.d.ts +10 -0
- package/dist/server/handler.js +48 -48
- package/dist/server/head.d.ts +36 -0
- package/dist/server/head.js +129 -0
- package/dist/server/manifest.js +0 -3
- package/dist/server/modes.js +0 -5
- package/dist/server/views.js +0 -7
- package/dist/vite/build.d.ts +8 -0
- package/dist/vite/build.js +42 -17
- package/dist/vite/links.d.ts +2 -0
- package/dist/vite/links.js +11 -10
- package/dist/vite/manifest.js +2 -10
- package/dist/vite/netlify.js +1 -7
- package/dist/vite/plugin.d.ts +29 -0
- package/dist/vite/plugin.js +99 -73
- package/dist/vite/sitemap.d.ts +11 -0
- package/dist/vite/sitemap.js +31 -0
- package/package.json +4 -2
package/dist/server/handler.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { modeFor } from './modes.js';
|
|
2
2
|
import { stringify } from '../runtime/serialize.js';
|
|
3
|
+
import { completeHead } from './head.js';
|
|
4
|
+
import { escape } from '../runtime/html.js';
|
|
3
5
|
const DATA = '__data.json';
|
|
4
6
|
const FRAG = 'index.frag.html';
|
|
5
|
-
/** JSON that is safe inside a <script> element and in any HTML context: '<' never appears raw. */
|
|
6
7
|
const safeJson = (json) => json.replace(/</g, '\\u003c');
|
|
7
|
-
/** A whole path segment that is a parameter: [id], [$id]. Anything else, like v[2], is literal text. */
|
|
8
8
|
const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
|
|
9
|
-
/** '/users/[id]' → keys ['id'] and a RegExp that captures each segment. */
|
|
10
9
|
function compile(path) {
|
|
11
10
|
const keys = [];
|
|
12
11
|
const source = path.split('/').map((seg) => {
|
|
@@ -18,13 +17,11 @@ function compile(path) {
|
|
|
18
17
|
}).join('/');
|
|
19
18
|
return { keys, regex: new RegExp(`^${source}$`) };
|
|
20
19
|
}
|
|
21
|
-
/** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
|
|
22
20
|
export function routeFromFile(file) {
|
|
23
21
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
|
|
24
22
|
return path || '/';
|
|
25
23
|
}
|
|
26
24
|
export function createHandler(pages, options = {}) {
|
|
27
|
-
// Static routes first, then dynamic ones with more fixed segments first: /users/new beats /users/[id].
|
|
28
25
|
const routes = Object.entries(pages)
|
|
29
26
|
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
30
27
|
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
@@ -41,16 +38,14 @@ export function createHandler(pages, options = {}) {
|
|
|
41
38
|
route.keys.forEach((key, i) => { params[key] = decodeURIComponent(m[i + 1]); });
|
|
42
39
|
}
|
|
43
40
|
catch {
|
|
44
|
-
return null;
|
|
41
|
+
return null;
|
|
45
42
|
}
|
|
46
43
|
return { route, params };
|
|
47
44
|
}
|
|
48
45
|
return null;
|
|
49
46
|
}
|
|
50
|
-
// A page's stylesheet links: what it imports, then the component styles (so components can build on the base).
|
|
51
47
|
const links = (urls) => [...new Set([...urls, ...(options.stylesUrl ? [options.stylesUrl] : [])])].map((u) => `<link rel="stylesheet" href="${u}">`).join('');
|
|
52
48
|
const pageLinks = (route) => links(options.css?.[route.path] ?? []);
|
|
53
|
-
// entries() per route, asked once: prerendering and requests see the same list. null when there is none.
|
|
54
49
|
const entriesCache = new Map();
|
|
55
50
|
function entriesOf(route) {
|
|
56
51
|
if (!entriesCache.has(route)) {
|
|
@@ -62,30 +57,24 @@ export function createHandler(pages, options = {}) {
|
|
|
62
57
|
}
|
|
63
58
|
return entriesCache.get(route);
|
|
64
59
|
}
|
|
65
|
-
// Without entries() a route isn't restricted here (the build reports it).
|
|
66
60
|
async function listed(route, params) {
|
|
67
61
|
const list = await entriesOf(route);
|
|
68
62
|
return !list || list.some((entry) => route.keys.every((key) => entry[key] === params[key]));
|
|
69
63
|
}
|
|
70
|
-
|
|
64
|
+
const handler = {
|
|
71
65
|
routes: routes.map((r) => r.path).sort(),
|
|
72
|
-
/** Routes rendered per request ('server' mode), as their files name them. */
|
|
73
66
|
serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
|
|
74
|
-
/** Whether a URL path belongs to a server route (what a host must send to this handler instead of a file). */
|
|
75
67
|
isServerPath(pathname) {
|
|
76
68
|
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
69
|
const owner = options.fragments && pathname.endsWith(`/${FRAG}`) ? match(trim(pathname.slice(0, -FRAG.length - 1) || '/')) : null;
|
|
79
70
|
const found = owner ?? match(trim(pathname));
|
|
80
71
|
return Boolean(found && modeFor(found.route.path, modes) === 'server');
|
|
81
72
|
},
|
|
82
|
-
/** Whether a route (as its file names it) has a load(). */
|
|
83
73
|
async hasLoader(path) {
|
|
84
74
|
const route = routes.find((r) => r.path === path);
|
|
85
75
|
const file = route && `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
|
|
86
76
|
return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
|
|
87
77
|
},
|
|
88
|
-
/** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
|
|
89
78
|
async paths() {
|
|
90
79
|
const out = [];
|
|
91
80
|
for (const route of routes) {
|
|
@@ -94,10 +83,8 @@ export function createHandler(pages, options = {}) {
|
|
|
94
83
|
continue;
|
|
95
84
|
const add = (path) => {
|
|
96
85
|
out.push(path);
|
|
97
|
-
// A client page's data, fetched by the router: written next to its shell.
|
|
98
86
|
if (mode === 'client')
|
|
99
87
|
out.push(path === '/' ? `/${DATA}` : `${path}/${DATA}`);
|
|
100
|
-
// A static page's fragment, for fragment navigation.
|
|
101
88
|
else if (options.fragments)
|
|
102
89
|
out.push(path === '/' ? `/${FRAG}` : `${path}/${FRAG}`);
|
|
103
90
|
};
|
|
@@ -115,9 +102,6 @@ export function createHandler(pages, options = {}) {
|
|
|
115
102
|
if (key === undefined)
|
|
116
103
|
return seg;
|
|
117
104
|
const value = params[key];
|
|
118
|
-
// Each value fills one path segment and names a folder in the build: never empty, '.' or '..'.
|
|
119
|
-
// Path separators on any OS ('/', '\\') and NUL could step out of that folder once the segment is decoded.
|
|
120
|
-
// __data.json and index.frag.html are a page's data and fragment files, so they can't also name a page.
|
|
121
105
|
if (typeof value !== 'string' || value === '' || value === '.' || value === '..' || value === DATA || value === FRAG || /[/\\\0]/.test(value)) {
|
|
122
106
|
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}"`);
|
|
123
107
|
}
|
|
@@ -131,10 +115,7 @@ export function createHandler(pages, options = {}) {
|
|
|
131
115
|
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
132
116
|
return new Response('Method Not Allowed', { status: 405 });
|
|
133
117
|
const pathname = new URL(request.url).pathname;
|
|
134
|
-
// '/guide/x/' is the same page as '/guide/x', in dev as on a static host.
|
|
135
118
|
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
136
|
-
// <client route>/__data.json is that page's props, for the router. Only for a client route: anywhere else the
|
|
137
|
-
// path is an ordinary page path (a server route may well have an [id] of "__data.json").
|
|
138
119
|
let found = match(trim(pathname));
|
|
139
120
|
let wantsData = false;
|
|
140
121
|
if (pathname.endsWith(`/${DATA}`)) {
|
|
@@ -144,7 +125,6 @@ export function createHandler(pages, options = {}) {
|
|
|
144
125
|
wantsData = true;
|
|
145
126
|
}
|
|
146
127
|
}
|
|
147
|
-
// <static or server route>/index.frag.html: that page's fragment, for fragment navigation.
|
|
148
128
|
let wantsFrag = false;
|
|
149
129
|
if (options.fragments && !wantsData && pathname.endsWith(`/${FRAG}`)) {
|
|
150
130
|
const owner = match(trim(pathname.slice(0, -FRAG.length - 1) || '/'));
|
|
@@ -154,25 +134,38 @@ export function createHandler(pages, options = {}) {
|
|
|
154
134
|
}
|
|
155
135
|
}
|
|
156
136
|
const head = request.method === 'HEAD';
|
|
157
|
-
const
|
|
137
|
+
const plain = () => new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
138
|
+
const notFound = async () => {
|
|
139
|
+
if (pathname.endsWith(`/${DATA}`) || pathname.endsWith(`/${FRAG}`) || trim(pathname) === '/404' || !routes.some((r) => r.path === '/404'))
|
|
140
|
+
return plain();
|
|
141
|
+
const page = await handler.fetch(new Request(new URL('/404', request.url), { method: request.method }));
|
|
142
|
+
if (page.status !== 200)
|
|
143
|
+
return plain();
|
|
144
|
+
return new Response(head ? null : rootLinks(await page.text(), options.base ?? '/'), { status: 404, headers: page.headers });
|
|
145
|
+
};
|
|
158
146
|
const mode = found && modeFor(found.route.path, modes);
|
|
159
147
|
if (!found)
|
|
160
148
|
return notFound();
|
|
161
|
-
// A prerendered dynamic route only has the pages its entries() lists, as on a static host.
|
|
162
149
|
if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
|
|
163
150
|
return notFound();
|
|
164
151
|
if (mode === 'client' && !wantsData) {
|
|
165
|
-
// In matching order (static before dynamic, as on the server): the router takes the first match.
|
|
166
152
|
const client = options.client ?? {};
|
|
167
153
|
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
168
154
|
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
169
155
|
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
156
|
links(routes.filter((r) => client[r.path]).flatMap((r) => options.css?.[r.path] ?? [])) +
|
|
172
|
-
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${safeJson(JSON.stringify(table))}</script>` +
|
|
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>` +
|
|
173
158
|
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
174
159
|
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
175
|
-
|
|
160
|
+
const { titleTemplate: _, ...siteHead } = options.head ?? {};
|
|
161
|
+
let page;
|
|
162
|
+
try {
|
|
163
|
+
page = completeHead(shell, maskComments, { ...siteHead, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, false) });
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
return failure(`${found.route.file}: ${err.message}`);
|
|
167
|
+
}
|
|
168
|
+
return new Response(head ? null : page, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
176
169
|
}
|
|
177
170
|
let props = found.params;
|
|
178
171
|
const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
@@ -189,50 +182,51 @@ export function createHandler(pages, options = {}) {
|
|
|
189
182
|
return failure(`${dataFile}: load() must return an object of page inputs, got ${Array.isArray(loaded) ? 'an array' : loaded === null ? 'null' : typeof loaded}`);
|
|
190
183
|
}
|
|
191
184
|
;
|
|
192
|
-
globalThis.__clLoaderRan = true;
|
|
185
|
+
globalThis.__clLoaderRan = true;
|
|
193
186
|
props = { ...found.params, ...loaded };
|
|
194
187
|
}
|
|
195
188
|
if (wantsData) {
|
|
196
189
|
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
197
190
|
}
|
|
198
|
-
|
|
191
|
+
let html = (await found.route.load()).render(props);
|
|
192
|
+
if (!/<html[\s>]/i.test(maskComments(html)))
|
|
193
|
+
html = `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title></head><body>${html}</body></html>`;
|
|
194
|
+
try {
|
|
195
|
+
html = completeHead(html, maskComments, { ...options.head, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, wantsFrag) });
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
return failure(`${found.route.file}: ${err.message}`);
|
|
199
|
+
}
|
|
199
200
|
if (wantsFrag) {
|
|
200
|
-
// The page's stylesheet links go right after its title, so fragment navigation can load any that are missing.
|
|
201
201
|
const fragment = toFragment(html).replace(/^(<title\b[^>]*>[\s\S]*?<\/title\s*>)/i, (t) => t + pageLinks(found.route));
|
|
202
202
|
return new Response(head ? null : fragment, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
203
203
|
}
|
|
204
204
|
const visible = maskComments(html);
|
|
205
205
|
const hasIslands = visible.includes('<cl-island ');
|
|
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
206
|
const nav = options.fragments === true;
|
|
209
207
|
const sheet = pageLinks(found.route);
|
|
210
|
-
const style = sheet + (hasIslands || nav ? '<style>cl-island{display:contents}</style>' : '');
|
|
208
|
+
const style = sheet + (hasIslands || nav ? '<style>cl-island{display:contents}</style>' : '');
|
|
211
209
|
const script = nav
|
|
212
210
|
? `<script type="module" src="${options.navUrl ?? '/cl-nav.js'}"></script>`
|
|
213
211
|
: hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
|
|
214
|
-
const body =
|
|
215
|
-
? fullDocument(html, style, script)
|
|
216
|
-
: `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title>${style}</head><body>${html}${script}</body></html>`;
|
|
212
|
+
const body = fullDocument(html, style, script);
|
|
217
213
|
return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
218
214
|
},
|
|
219
215
|
};
|
|
216
|
+
return handler;
|
|
217
|
+
}
|
|
218
|
+
function pagePath(pathname, fragment) {
|
|
219
|
+
const path = fragment ? pathname.slice(0, -FRAG.length) : pathname;
|
|
220
|
+
return path.replace(/(.)\/+$/, '$1') || '/';
|
|
220
221
|
}
|
|
221
|
-
/** A 500 that tells the visitor nothing internal; the details go to the server log (and the build's output). */
|
|
222
222
|
function failure(message) {
|
|
223
223
|
console.error(`[clarusjs] ${message}`);
|
|
224
224
|
return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
225
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
226
|
export function toFragment(html) {
|
|
231
|
-
// Comments and raw-text contents (scripts, styles, textareas, the title) can hold tag-shaped text: blank them out.
|
|
232
227
|
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
228
|
const title = /<title\b[^>]*>[\s\S]*?<\/title\s*>/i.exec(masked);
|
|
234
229
|
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
230
|
const tags = /<([a-zA-Z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
|
|
237
231
|
let marked = null;
|
|
238
232
|
for (let m = tags.exec(masked); m; m = tags.exec(masked)) {
|
|
@@ -259,11 +253,9 @@ export function toFragment(html) {
|
|
|
259
253
|
return `${titleHtml}<body>${html}</body>`;
|
|
260
254
|
return titleHtml + html.slice(open.index, close) + '</body>';
|
|
261
255
|
}
|
|
262
|
-
/** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
|
|
263
256
|
function maskComments(html) {
|
|
264
257
|
return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
|
|
265
258
|
}
|
|
266
|
-
/** A page whose layout renders the whole document: add the doctype if missing, and put style/script in place. */
|
|
267
259
|
function fullDocument(html, style, script) {
|
|
268
260
|
let out = /^\s*<!doctype/i.test(html) ? html : `<!doctype html>${html}`;
|
|
269
261
|
if (style) {
|
|
@@ -277,3 +269,11 @@ function fullDocument(html, style, script) {
|
|
|
277
269
|
}
|
|
278
270
|
return out;
|
|
279
271
|
}
|
|
272
|
+
export function rootLinks(html, base) {
|
|
273
|
+
return html.replace(/(\s(?:href|src)=")([^"]*)"/gi, (all, attr, url) => {
|
|
274
|
+
if (/^(?:[a-z][\w+.-]*:|\/|#|\?)/i.test(url))
|
|
275
|
+
return all;
|
|
276
|
+
const resolved = new URL(url.replace(/&/g, '&'), `http://x${base}`);
|
|
277
|
+
return `${attr}${(resolved.pathname + resolved.search + resolved.hash).replace(/&/g, '&')}"`;
|
|
278
|
+
});
|
|
279
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** A head tag as data: ['meta', { name: 'theme-color', content: '#fff' }], ['script', { src }, ''] */
|
|
2
|
+
export type HeadTag = [tag: string, attrs: Record<string, string | true>, content?: string];
|
|
3
|
+
export type HeadOptions = {
|
|
4
|
+
/** '%s · Site': wraps the document's <title>. A <title> inside <cl-head> is used as written. */
|
|
5
|
+
titleTemplate?: string;
|
|
6
|
+
/** Tags on every page, unless the page has its own with the same key. */
|
|
7
|
+
tags?: HeadTag[];
|
|
8
|
+
/** Structured data on every page (schema.org WebSite, Organization…): one JSON-LD script per object. */
|
|
9
|
+
jsonLd?: object | object[];
|
|
10
|
+
/** The site's public address: canonical URLs and social cards (Open Graph, Twitter) on every page. */
|
|
11
|
+
site?: SiteOptions;
|
|
12
|
+
/** Vite's base ('/' or '/docs/'): public files and pages live under it. */
|
|
13
|
+
base?: string;
|
|
14
|
+
/** Last word on the head's HTML (from src/head.ts in an app). */
|
|
15
|
+
transform?: (head: string, page: {
|
|
16
|
+
route: string;
|
|
17
|
+
path: string;
|
|
18
|
+
}) => string;
|
|
19
|
+
};
|
|
20
|
+
export type SiteOptions = {
|
|
21
|
+
url: string;
|
|
22
|
+
name?: string;
|
|
23
|
+
image?: string;
|
|
24
|
+
};
|
|
25
|
+
export declare function renderTag([tag, attrs, content]: HeadTag): string;
|
|
26
|
+
/**
|
|
27
|
+
* The full document `html` with its head completed, in order: <cl-head> tags from the page (they win), the title
|
|
28
|
+
* template, site tags for keys the page left unset, canonical and social defaults for keys still unset, JSON-LD,
|
|
29
|
+
* then the transform. `mask` blanks comments (keeping offsets), so tag-shaped text in comments is never used.
|
|
30
|
+
*/
|
|
31
|
+
export declare function completeHead(html: string, mask: (html: string) => string, options: HeadOptions, page: {
|
|
32
|
+
route: string;
|
|
33
|
+
path: string;
|
|
34
|
+
}): string;
|
|
35
|
+
/** Vite's base as a path: an absolute base (https://cdn.example.com/docs/) counts by its pathname. */
|
|
36
|
+
export declare function basePath(base?: string): string;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { escape, json } from '../runtime/html.js';
|
|
2
|
+
const VOID = new Set(['meta', 'link', 'base']);
|
|
3
|
+
export function renderTag([tag, attrs, content]) {
|
|
4
|
+
const a = Object.entries(attrs).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escape(v)}"`)).join('');
|
|
5
|
+
return VOID.has(tag) && content === undefined ? `<${tag}${a}>` : `<${tag}${a}>${content ?? ''}</${tag}>`;
|
|
6
|
+
}
|
|
7
|
+
function key(tag) {
|
|
8
|
+
const name = /^<([a-z]+)/i.exec(tag)?.[1].toLowerCase();
|
|
9
|
+
const attr = (n) => {
|
|
10
|
+
const m = new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag);
|
|
11
|
+
return m ? m[1] ?? m[2] ?? m[3] : undefined;
|
|
12
|
+
};
|
|
13
|
+
if (name === 'title' || name === 'base')
|
|
14
|
+
return name;
|
|
15
|
+
if (name === 'meta') {
|
|
16
|
+
if (/\scharset\b/i.test(tag))
|
|
17
|
+
return 'meta:charset';
|
|
18
|
+
for (const n of ['name', 'property', 'http-equiv'])
|
|
19
|
+
if (attr(n) !== undefined)
|
|
20
|
+
return `meta:${n}:${attr(n)}`;
|
|
21
|
+
}
|
|
22
|
+
if (name === 'link' && attr('rel') === 'canonical')
|
|
23
|
+
return 'link:canonical';
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
const TAGS = /<(title|script|style|noscript|template)\b[^>]*>[\s\S]*?<\/\1\s*>|<(?:meta|link|base)\b[^>]*>/gi;
|
|
27
|
+
function spansOf(html, mask) {
|
|
28
|
+
return [...mask(html).matchAll(TAGS)].map((m) => ({ at: m.index, text: html.slice(m.index, m.index + m[0].length) }));
|
|
29
|
+
}
|
|
30
|
+
function setTag(head, tag, mask) {
|
|
31
|
+
const k = key(tag);
|
|
32
|
+
const same = k ? spansOf(head, mask).find((t) => key(t.text) === k) : undefined;
|
|
33
|
+
return same ? head.slice(0, same.at) + tag + head.slice(same.at + same.text.length) : head + tag;
|
|
34
|
+
}
|
|
35
|
+
export function completeHead(html, mask, options, page) {
|
|
36
|
+
const own = [];
|
|
37
|
+
for (const m of [...mask(html).matchAll(/<cl-head>([\s\S]*?)<\/cl-head>/gi)].reverse()) {
|
|
38
|
+
const inner = m.index + '<cl-head>'.length;
|
|
39
|
+
own.unshift(...spansOf(html.slice(inner, m.index + m[0].length - '</cl-head>'.length), mask).map((t) => t.text));
|
|
40
|
+
html = html.slice(0, m.index) + html.slice(m.index + m[0].length);
|
|
41
|
+
}
|
|
42
|
+
if (mask(html).search(/<head\b[^>]*>/i) === -1) {
|
|
43
|
+
const tag = /<html\b[^>]*>/i.exec(mask(html));
|
|
44
|
+
if (!tag)
|
|
45
|
+
return html;
|
|
46
|
+
html = html.slice(0, tag.index + tag[0].length) + '<head></head>' + html.slice(tag.index + tag[0].length);
|
|
47
|
+
}
|
|
48
|
+
const masked = mask(html);
|
|
49
|
+
const open = /<head\b[^>]*>/i.exec(masked);
|
|
50
|
+
const close = masked.search(/<\/head\s*>/i);
|
|
51
|
+
if (close === -1)
|
|
52
|
+
return html;
|
|
53
|
+
const start = open.index + open[0].length;
|
|
54
|
+
let head = html.slice(start, close);
|
|
55
|
+
const find = (k) => spansOf(head, mask).find((t) => key(t.text) === k);
|
|
56
|
+
const rawTitle = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(own.find((t) => key(t) === 'title') ?? find('title')?.text ?? '')?.[1] ?? '';
|
|
57
|
+
const title = find('title');
|
|
58
|
+
if (options.titleTemplate && title && !own.some((t) => key(t) === 'title')) {
|
|
59
|
+
const wrapped = title.text.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title\s*>)/i, (_, a, text, b) => a + escape(options.titleTemplate).replace('%s', () => text) + b);
|
|
60
|
+
head = head.slice(0, title.at) + wrapped + head.slice(title.at + title.text.length);
|
|
61
|
+
}
|
|
62
|
+
for (const tag of own)
|
|
63
|
+
head = setTag(head, tag, mask);
|
|
64
|
+
const pageSet = { image: content(find('meta:property:og:image')?.text), url: content(find('meta:property:og:url')?.text) };
|
|
65
|
+
const fill = (tag) => { if (!find(key(tag) ?? ''))
|
|
66
|
+
head += tag; };
|
|
67
|
+
for (const t of options.tags ?? []) {
|
|
68
|
+
const tag = renderTag(t);
|
|
69
|
+
if (key(tag))
|
|
70
|
+
fill(tag);
|
|
71
|
+
else
|
|
72
|
+
head += tag;
|
|
73
|
+
}
|
|
74
|
+
head = social(head, rawTitle, options, page, pageSet, mask);
|
|
75
|
+
for (const data of [options.jsonLd ?? []].flat())
|
|
76
|
+
head += `<script type="application/ld+json">${json(data)}</script>`;
|
|
77
|
+
if (options.transform)
|
|
78
|
+
head = options.transform(head, page);
|
|
79
|
+
return html.slice(0, start) + head + html.slice(close);
|
|
80
|
+
}
|
|
81
|
+
const decode = (html) => html.replace(/&(#x?[\da-f]+|amp|lt|gt|quot|apos|#39);/gi, (m, e) => {
|
|
82
|
+
const named = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
83
|
+
if (e[0] !== '#')
|
|
84
|
+
return named[e.toLowerCase()] ?? m;
|
|
85
|
+
return String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10));
|
|
86
|
+
});
|
|
87
|
+
function content(tag) {
|
|
88
|
+
const m = /\scontent\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag ?? '');
|
|
89
|
+
return decode(m ? m[1] ?? m[2] ?? m[3] ?? '' : '');
|
|
90
|
+
}
|
|
91
|
+
function social(head, title, options, page, pageSet, mask) {
|
|
92
|
+
const find = (k) => spansOf(head, mask).find((t) => key(t.text) === k);
|
|
93
|
+
const relative = (u) => u !== '' && !/^[a-z][\w+.-]*:|^\/\//i.test(u);
|
|
94
|
+
if (!options.site) {
|
|
95
|
+
for (const k of ['meta:property:og:image', 'meta:property:og:url']) {
|
|
96
|
+
const value = content(find(k)?.text);
|
|
97
|
+
if (relative(value))
|
|
98
|
+
throw new Error(`${page.path}: ${k.slice(14)} "${value}" is relative: set site.url in the clarusjs plugin so it can be made absolute`);
|
|
99
|
+
}
|
|
100
|
+
return head;
|
|
101
|
+
}
|
|
102
|
+
const root = new URL(basePath(options.base), options.site.url.replace(/\/?$/, '/'));
|
|
103
|
+
const url = new URL(`./${page.path.slice(1)}`, root).href;
|
|
104
|
+
const absolute = (u) => (u.startsWith('/') && !u.startsWith('//') ? new URL(u.slice(1), root).href : new URL(u, url.endsWith('/') ? url : `${url}/`).href);
|
|
105
|
+
for (const [property, value] of [['og:image', pageSet.image], ['og:url', pageSet.url]]) {
|
|
106
|
+
if (relative(value))
|
|
107
|
+
head = setTag(head, `<meta property="${property}" content="${escape(absolute(value))}">`, mask);
|
|
108
|
+
}
|
|
109
|
+
const set = (k) => !!find(k);
|
|
110
|
+
const add = (tag) => { if (!set(key(tag)))
|
|
111
|
+
head += tag; };
|
|
112
|
+
const image = content(find('meta:property:og:image')?.text) || options.site.image || '';
|
|
113
|
+
const description = content(find('meta:name:description')?.text);
|
|
114
|
+
add(`<link rel="canonical" href="${escape(url)}">`);
|
|
115
|
+
add(`<meta property="og:title" content="${escape(decode(title))}">`);
|
|
116
|
+
if (description)
|
|
117
|
+
add(`<meta property="og:description" content="${escape(description)}">`);
|
|
118
|
+
add(`<meta property="og:url" content="${escape(url)}">`);
|
|
119
|
+
add('<meta property="og:type" content="website">');
|
|
120
|
+
if (options.site.name)
|
|
121
|
+
add(`<meta property="og:site_name" content="${escape(options.site.name)}">`);
|
|
122
|
+
if (image)
|
|
123
|
+
add(`<meta property="og:image" content="${escape(relative(image) ? absolute(image) : image)}">`);
|
|
124
|
+
add(`<meta name="twitter:card" content="${image ? 'summary_large_image' : 'summary'}">`);
|
|
125
|
+
return head;
|
|
126
|
+
}
|
|
127
|
+
export function basePath(base = '/') {
|
|
128
|
+
return /^https?:\/\//i.test(base) ? new URL(base).pathname : base;
|
|
129
|
+
}
|
package/dist/server/manifest.js
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
// Read the route manifest while pages are prerendered. Server only (Node): a page that calls readManifest() during
|
|
2
|
-
// `vite build` is rendered again once the manifest is written, so it can show what the built site ships.
|
|
3
1
|
import { readFileSync } from 'node:fs';
|
|
4
|
-
/** The built site's manifest, or null outside `vite build` (in dev) and on the first prerender pass. */
|
|
5
2
|
export function readManifest() {
|
|
6
3
|
;
|
|
7
4
|
globalThis.__clManifestRead = true;
|
package/dist/server/modes.js
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
// Per-route rendering modes: when each route renders. 'static' at build (the default), 'server' per request,
|
|
2
|
-
// 'client' in the browser (the server sends a shell; the router renders the page from its data).
|
|
3
1
|
const MODES = ['static', 'server', 'client'];
|
|
4
|
-
/** Throws on an unknown mode or a malformed pattern, naming it. */
|
|
5
2
|
export function checkModes(table) {
|
|
6
3
|
for (const [pattern, mode] of Object.entries(table)) {
|
|
7
4
|
if (!pattern.startsWith('/'))
|
|
@@ -13,13 +10,11 @@ export function checkModes(table) {
|
|
|
13
10
|
throw new Error(`clarusjs: routes['${pattern}'] is "${mode}"; use 'static', 'server' or 'client'`);
|
|
14
11
|
}
|
|
15
12
|
}
|
|
16
|
-
/** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
|
|
17
13
|
export function modeFor(route, table) {
|
|
18
14
|
let best;
|
|
19
15
|
for (const [pattern, mode] of Object.entries(table)) {
|
|
20
16
|
const folder = pattern.endsWith('/*') ? pattern.slice(0, -2) : undefined;
|
|
21
17
|
const hit = folder !== undefined ? route === (folder || '/') || route.startsWith(`${folder}/`) : route === pattern;
|
|
22
|
-
// An exact pattern beats a folder of the same length.
|
|
23
18
|
const length = folder !== undefined ? folder.length : pattern.length + 0.5;
|
|
24
19
|
if (hit && (!best || length > best.length))
|
|
25
20
|
best = { length, mode: mode };
|
package/dist/server/views.js
CHANGED
|
@@ -1,17 +1,10 @@
|
|
|
1
|
-
// render(name, props): any view under src/ rendered to HTML from server code (a loader, an endpoint, a script that
|
|
2
|
-
// imports the built server). The server entry registers the views; `clarusjs check` writes .clarusjs/views.d.ts,
|
|
3
|
-
// which types each name with that view's inputs.
|
|
4
|
-
/** '/src/components/pill.tscl' → 'components/pill' */
|
|
5
1
|
export function viewName(file) {
|
|
6
2
|
return file.replace(/^.*?\/src\//, '').replace(/\.[^./]+$/, '');
|
|
7
3
|
}
|
|
8
|
-
// On globalThis: the bundled server and an app's own `import 'clarusjs/views'` may be two copies of this module.
|
|
9
4
|
const store = globalThis;
|
|
10
|
-
/** Called by the server entry with import.meta.glob('/src/**\/*.tscl'). */
|
|
11
5
|
export function registerViews(files) {
|
|
12
6
|
store.__clViews = new Map(Object.entries(files).map(([file, load]) => [viewName(file), load]));
|
|
13
7
|
}
|
|
14
|
-
/** Render a view to HTML. Its props are checked against its inputs once `clarusjs check` has generated the registry. */
|
|
15
8
|
export async function render(name, props) {
|
|
16
9
|
const views = store.__clViews;
|
|
17
10
|
if (!views)
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -20,3 +20,11 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
|
|
|
20
20
|
loader: boolean;
|
|
21
21
|
}[];
|
|
22
22
|
}>;
|
|
23
|
+
/** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). */
|
|
24
|
+
export declare function packageOf(file: string): string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Component files reachable from `start` through @import lines: relative paths, root-relative ('/src/…') and package
|
|
27
|
+
* specifiers ('@clarusjs/theme-docs/layout.tscl', resolved as Node would from the app). Real paths, so a workspace
|
|
28
|
+
* package linked into node_modules is one file, not two.
|
|
29
|
+
*/
|
|
30
|
+
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[]): string[];
|
package/dist/vite/build.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
// Build-time helpers for the Vite plugin: find components, and prerender every route to static HTML.
|
|
2
1
|
import { spawnSync } from 'node:child_process';
|
|
3
|
-
import { readdirSync } from 'node:fs';
|
|
4
|
-
import {
|
|
5
|
-
|
|
2
|
+
import { readdirSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import { parse } from '../compiler/parse.js';
|
|
6
6
|
export function findClarusFiles(srcDir, extensions = ['.tscl']) {
|
|
7
7
|
let entries;
|
|
8
8
|
try {
|
|
@@ -13,11 +13,6 @@ export function findClarusFiles(srcDir, extensions = ['.tscl']) {
|
|
|
13
13
|
}
|
|
14
14
|
return entries.filter((f) => extensions.some((ext) => f.endsWith(ext))).map((f) => resolve(srcDir, f)).sort();
|
|
15
15
|
}
|
|
16
|
-
/**
|
|
17
|
-
* '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
|
|
18
|
-
* Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
|
|
19
|
-
* entries() values never contain '/' (and a page file's own name has none).
|
|
20
|
-
*/
|
|
21
16
|
export function routeToFile(route) {
|
|
22
17
|
const path = route.replace(/^\/+|\/+$/g, '').split('/').map((seg) => {
|
|
23
18
|
try {
|
|
@@ -25,21 +20,14 @@ export function routeToFile(route) {
|
|
|
25
20
|
}
|
|
26
21
|
catch {
|
|
27
22
|
return seg;
|
|
28
|
-
}
|
|
23
|
+
}
|
|
29
24
|
}).join('/');
|
|
30
|
-
// A client page's data file is written as itself, next to the page's shell.
|
|
31
25
|
if (path === '__data.json' || path.endsWith('/__data.json'))
|
|
32
26
|
return path;
|
|
33
|
-
// A page's fragment, likewise.
|
|
34
27
|
if (path === 'index.frag.html' || path.endsWith('/index.frag.html'))
|
|
35
28
|
return path;
|
|
36
29
|
return path ? `${path}/index.html` : 'index.html';
|
|
37
30
|
}
|
|
38
|
-
/**
|
|
39
|
-
* Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
|
|
40
|
-
* build. Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache. Returns the
|
|
41
|
-
* routes rendered and those that read the route manifest (readManifest() from `manifestFile`).
|
|
42
|
-
*/
|
|
43
31
|
export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
44
32
|
const script = `
|
|
45
33
|
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
@@ -93,3 +81,40 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
93
81
|
throw new Error(result.stderr.trim() || `prerender failed (exit ${result.status})`);
|
|
94
82
|
return JSON.parse(result.stdout);
|
|
95
83
|
}
|
|
84
|
+
export function packageOf(file) {
|
|
85
|
+
return /.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(file)?.[1].replace(/\\/g, '/');
|
|
86
|
+
}
|
|
87
|
+
export function reachableComponents(root, start, read, extensions) {
|
|
88
|
+
const require = createRequire(resolve(root, 'package.json'));
|
|
89
|
+
const seen = new Set();
|
|
90
|
+
const queue = start.map((f) => realpathSync(f));
|
|
91
|
+
while (queue.length) {
|
|
92
|
+
const file = queue.shift();
|
|
93
|
+
if (seen.has(file))
|
|
94
|
+
continue;
|
|
95
|
+
seen.add(file);
|
|
96
|
+
let imports;
|
|
97
|
+
try {
|
|
98
|
+
imports = parse(read(file), file).imports;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
for (const { from } of imports) {
|
|
104
|
+
const spec = from.replace(/\?.*$/, '');
|
|
105
|
+
if (!extensions.some((e) => spec.endsWith(e)))
|
|
106
|
+
continue;
|
|
107
|
+
let target;
|
|
108
|
+
try {
|
|
109
|
+
target = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : require.resolve(spec);
|
|
110
|
+
target = realpathSync(target);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (!seen.has(target))
|
|
116
|
+
queue.push(target);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return [...seen];
|
|
120
|
+
}
|
package/dist/vite/links.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ type Options = {
|
|
|
13
13
|
/** Client routes render in the browser: their pages exist, but their anchors can't be checked at build. */
|
|
14
14
|
clientRoutes: string[];
|
|
15
15
|
base: string;
|
|
16
|
+
/** site.url: absolute links to the site itself are checked like internal ones. */
|
|
17
|
+
site?: string;
|
|
16
18
|
};
|
|
17
19
|
export declare function checkLinks(options: Options): LinkIssue[];
|
|
18
20
|
export {};
|