clarusjs 0.7.0 → 0.8.1
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 +6 -0
- package/dist/check/generate.js +12 -22
- package/dist/cli/check.js +58 -15
- 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/dom.js +4 -1
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -30
- package/dist/runtime/html.d.ts +2 -0
- package/dist/runtime/html.js +4 -0
- package/dist/runtime/loader.js +41 -2
- 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 +32 -42
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +1 -1
- package/dist/server/handler.d.ts +18 -0
- package/dist/server/handler.js +80 -53
- 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/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +9 -0
- package/dist/vite/build.js +43 -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 +35 -0
- package/dist/vite/plugin.js +162 -88
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/dist/vite/sitemap.d.ts +11 -0
- package/dist/vite/sitemap.js +31 -0
- package/package.json +18 -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,14 @@ function compile(path) {
|
|
|
18
17
|
}).join('/');
|
|
19
18
|
return { keys, regex: new RegExp(`^${source}$`) };
|
|
20
19
|
}
|
|
21
|
-
|
|
20
|
+
export function redirect(to, status = 302) {
|
|
21
|
+
return new Response(null, { status, headers: { location: to } });
|
|
22
|
+
}
|
|
22
23
|
export function routeFromFile(file) {
|
|
23
24
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
|
|
24
25
|
return path || '/';
|
|
25
26
|
}
|
|
26
27
|
export function createHandler(pages, options = {}) {
|
|
27
|
-
// Static routes first, then dynamic ones with more fixed segments first: /users/new beats /users/[id].
|
|
28
28
|
const routes = Object.entries(pages)
|
|
29
29
|
.map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
|
|
30
30
|
.sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
|
|
@@ -41,16 +41,14 @@ export function createHandler(pages, options = {}) {
|
|
|
41
41
|
route.keys.forEach((key, i) => { params[key] = decodeURIComponent(m[i + 1]); });
|
|
42
42
|
}
|
|
43
43
|
catch {
|
|
44
|
-
return null;
|
|
44
|
+
return null;
|
|
45
45
|
}
|
|
46
46
|
return { route, params };
|
|
47
47
|
}
|
|
48
48
|
return null;
|
|
49
49
|
}
|
|
50
|
-
// A page's stylesheet links: what it imports, then the component styles (so components can build on the base).
|
|
51
50
|
const links = (urls) => [...new Set([...urls, ...(options.stylesUrl ? [options.stylesUrl] : [])])].map((u) => `<link rel="stylesheet" href="${u}">`).join('');
|
|
52
51
|
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
52
|
const entriesCache = new Map();
|
|
55
53
|
function entriesOf(route) {
|
|
56
54
|
if (!entriesCache.has(route)) {
|
|
@@ -62,30 +60,24 @@ export function createHandler(pages, options = {}) {
|
|
|
62
60
|
}
|
|
63
61
|
return entriesCache.get(route);
|
|
64
62
|
}
|
|
65
|
-
// Without entries() a route isn't restricted here (the build reports it).
|
|
66
63
|
async function listed(route, params) {
|
|
67
64
|
const list = await entriesOf(route);
|
|
68
65
|
return !list || list.some((entry) => route.keys.every((key) => entry[key] === params[key]));
|
|
69
66
|
}
|
|
70
|
-
|
|
67
|
+
const handler = {
|
|
71
68
|
routes: routes.map((r) => r.path).sort(),
|
|
72
|
-
/** Routes rendered per request ('server' mode), as their files name them. */
|
|
73
69
|
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
70
|
isServerPath(pathname) {
|
|
76
71
|
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
72
|
const owner = options.fragments && pathname.endsWith(`/${FRAG}`) ? match(trim(pathname.slice(0, -FRAG.length - 1) || '/')) : null;
|
|
79
73
|
const found = owner ?? match(trim(pathname));
|
|
80
74
|
return Boolean(found && modeFor(found.route.path, modes) === 'server');
|
|
81
75
|
},
|
|
82
|
-
/** Whether a route (as its file names it) has a load(). */
|
|
83
76
|
async hasLoader(path) {
|
|
84
77
|
const route = routes.find((r) => r.path === path);
|
|
85
78
|
const file = route && `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
|
|
86
79
|
return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
|
|
87
80
|
},
|
|
88
|
-
/** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
|
|
89
81
|
async paths() {
|
|
90
82
|
const out = [];
|
|
91
83
|
for (const route of routes) {
|
|
@@ -94,10 +86,8 @@ export function createHandler(pages, options = {}) {
|
|
|
94
86
|
continue;
|
|
95
87
|
const add = (path) => {
|
|
96
88
|
out.push(path);
|
|
97
|
-
// A client page's data, fetched by the router: written next to its shell.
|
|
98
89
|
if (mode === 'client')
|
|
99
90
|
out.push(path === '/' ? `/${DATA}` : `${path}/${DATA}`);
|
|
100
|
-
// A static page's fragment, for fragment navigation.
|
|
101
91
|
else if (options.fragments)
|
|
102
92
|
out.push(path === '/' ? `/${FRAG}` : `${path}/${FRAG}`);
|
|
103
93
|
};
|
|
@@ -115,9 +105,6 @@ export function createHandler(pages, options = {}) {
|
|
|
115
105
|
if (key === undefined)
|
|
116
106
|
return seg;
|
|
117
107
|
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
108
|
if (typeof value !== 'string' || value === '' || value === '.' || value === '..' || value === DATA || value === FRAG || /[/\\\0]/.test(value)) {
|
|
122
109
|
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
110
|
}
|
|
@@ -131,10 +118,7 @@ export function createHandler(pages, options = {}) {
|
|
|
131
118
|
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
132
119
|
return new Response('Method Not Allowed', { status: 405 });
|
|
133
120
|
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
121
|
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
122
|
let found = match(trim(pathname));
|
|
139
123
|
let wantsData = false;
|
|
140
124
|
if (pathname.endsWith(`/${DATA}`)) {
|
|
@@ -144,7 +128,6 @@ export function createHandler(pages, options = {}) {
|
|
|
144
128
|
wantsData = true;
|
|
145
129
|
}
|
|
146
130
|
}
|
|
147
|
-
// <static or server route>/index.frag.html: that page's fragment, for fragment navigation.
|
|
148
131
|
let wantsFrag = false;
|
|
149
132
|
if (options.fragments && !wantsData && pathname.endsWith(`/${FRAG}`)) {
|
|
150
133
|
const owner = match(trim(pathname.slice(0, -FRAG.length - 1) || '/'));
|
|
@@ -154,27 +137,56 @@ export function createHandler(pages, options = {}) {
|
|
|
154
137
|
}
|
|
155
138
|
}
|
|
156
139
|
const head = request.method === 'HEAD';
|
|
157
|
-
const
|
|
140
|
+
const plain = () => new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
141
|
+
const notFound = async () => {
|
|
142
|
+
if (pathname.endsWith(`/${DATA}`) || pathname.endsWith(`/${FRAG}`) || trim(pathname) === '/404' || !routes.some((r) => r.path === '/404'))
|
|
143
|
+
return plain();
|
|
144
|
+
const page = await handler.fetch(new Request(new URL('/404', request.url), { method: request.method }));
|
|
145
|
+
if (page.status !== 200)
|
|
146
|
+
return plain();
|
|
147
|
+
return new Response(head ? null : rootLinks(await page.text(), options.base ?? '/'), { status: 404, headers: page.headers });
|
|
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
|
+
};
|
|
158
165
|
const mode = found && modeFor(found.route.path, modes);
|
|
159
166
|
if (!found)
|
|
160
167
|
return notFound();
|
|
161
|
-
// A prerendered dynamic route only has the pages its entries() lists, as on a static host.
|
|
162
168
|
if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
|
|
163
169
|
return notFound();
|
|
164
170
|
if (mode === 'client' && !wantsData) {
|
|
165
|
-
// In matching order (static before dynamic, as on the server): the router takes the first match.
|
|
166
171
|
const client = options.client ?? {};
|
|
167
172
|
const prefix = (options.base ?? '/').replace(/\/$/, '');
|
|
168
173
|
const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
|
|
169
174
|
const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
`<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${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>` +
|
|
173
177
|
`<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
|
|
174
178
|
'</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
|
|
175
|
-
|
|
179
|
+
const { titleTemplate: _, ...siteHead } = options.head ?? {};
|
|
180
|
+
let page;
|
|
181
|
+
try {
|
|
182
|
+
page = completeHead(shell, maskComments, { ...siteHead, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, false) });
|
|
183
|
+
}
|
|
184
|
+
catch (err) {
|
|
185
|
+
return fail(`${found.route.file}: ${err.message}`, err);
|
|
186
|
+
}
|
|
187
|
+
return new Response(head ? null : page, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
176
188
|
}
|
|
177
|
-
let props = found.params;
|
|
189
|
+
let props = found.route.path === '/500' ? { status: 500, ...found.params } : found.params;
|
|
178
190
|
const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
|
|
179
191
|
const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
|
|
180
192
|
if (mod?.load) {
|
|
@@ -183,56 +195,65 @@ export function createHandler(pages, options = {}) {
|
|
|
183
195
|
loaded = await mod.load({ params: found.params, request });
|
|
184
196
|
}
|
|
185
197
|
catch (err) {
|
|
186
|
-
return
|
|
198
|
+
return fail(`${dataFile}: load() failed: ${err?.message ?? err}`, err);
|
|
187
199
|
}
|
|
200
|
+
if (loaded instanceof Response)
|
|
201
|
+
return loaded;
|
|
188
202
|
if (loaded === null || typeof loaded !== 'object' || Array.isArray(loaded)) {
|
|
189
|
-
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}`);
|
|
190
204
|
}
|
|
191
205
|
;
|
|
192
|
-
globalThis.__clLoaderRan = true;
|
|
193
|
-
props = { ...
|
|
206
|
+
globalThis.__clLoaderRan = true;
|
|
207
|
+
props = { ...props, ...loaded };
|
|
194
208
|
}
|
|
195
209
|
if (wantsData) {
|
|
196
210
|
return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
197
211
|
}
|
|
198
|
-
|
|
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
|
+
}
|
|
219
|
+
if (!/<html[\s>]/i.test(maskComments(html)))
|
|
220
|
+
html = `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title></head><body>${html}</body></html>`;
|
|
221
|
+
try {
|
|
222
|
+
html = completeHead(html, maskComments, { ...options.head, site: options.site, base: options.base }, { route: found.route.path, path: pagePath(pathname, wantsFrag) });
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
return fail(`${found.route.file}: ${err.message}`, err);
|
|
226
|
+
}
|
|
199
227
|
if (wantsFrag) {
|
|
200
|
-
// The page's stylesheet links go right after its title, so fragment navigation can load any that are missing.
|
|
201
228
|
const fragment = toFragment(html).replace(/^(<title\b[^>]*>[\s\S]*?<\/title\s*>)/i, (t) => t + pageLinks(found.route));
|
|
202
229
|
return new Response(head ? null : fragment, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
203
230
|
}
|
|
204
231
|
const visible = maskComments(html);
|
|
205
232
|
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
233
|
const nav = options.fragments === true;
|
|
209
234
|
const sheet = pageLinks(found.route);
|
|
210
|
-
const style = sheet + (hasIslands || nav ? '<style>cl-island{display:contents}</style>' : '');
|
|
235
|
+
const style = sheet + (hasIslands || nav ? '<style>cl-island{display:contents}</style>' : '');
|
|
211
236
|
const script = nav
|
|
212
237
|
? `<script type="module" src="${options.navUrl ?? '/cl-nav.js'}"></script>`
|
|
213
238
|
: 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>`;
|
|
239
|
+
const body = fullDocument(html, style, script);
|
|
217
240
|
return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
218
241
|
},
|
|
219
242
|
};
|
|
243
|
+
return handler;
|
|
244
|
+
}
|
|
245
|
+
function pagePath(pathname, fragment) {
|
|
246
|
+
const path = fragment ? pathname.slice(0, -FRAG.length) : pathname;
|
|
247
|
+
return path.replace(/(.)\/+$/, '$1') || '/';
|
|
220
248
|
}
|
|
221
|
-
/** A 500 that tells the visitor nothing internal; the details go to the server log (and the build's output). */
|
|
222
249
|
function failure(message) {
|
|
223
250
|
console.error(`[clarusjs] ${message}`);
|
|
224
251
|
return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
225
252
|
}
|
|
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
253
|
export function toFragment(html) {
|
|
231
|
-
// Comments and raw-text contents (scripts, styles, textareas, the title) can hold tag-shaped text: blank them out.
|
|
232
254
|
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
255
|
const title = /<title\b[^>]*>[\s\S]*?<\/title\s*>/i.exec(masked);
|
|
234
256
|
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
257
|
const tags = /<([a-zA-Z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
|
|
237
258
|
let marked = null;
|
|
238
259
|
for (let m = tags.exec(masked); m; m = tags.exec(masked)) {
|
|
@@ -259,11 +280,9 @@ export function toFragment(html) {
|
|
|
259
280
|
return `${titleHtml}<body>${html}</body>`;
|
|
260
281
|
return titleHtml + html.slice(open.index, close) + '</body>';
|
|
261
282
|
}
|
|
262
|
-
/** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
|
|
263
283
|
function maskComments(html) {
|
|
264
284
|
return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
|
|
265
285
|
}
|
|
266
|
-
/** A page whose layout renders the whole document: add the doctype if missing, and put style/script in place. */
|
|
267
286
|
function fullDocument(html, style, script) {
|
|
268
287
|
let out = /^\s*<!doctype/i.test(html) ? html : `<!doctype html>${html}`;
|
|
269
288
|
if (style) {
|
|
@@ -277,3 +296,11 @@ function fullDocument(html, style, script) {
|
|
|
277
296
|
}
|
|
278
297
|
return out;
|
|
279
298
|
}
|
|
299
|
+
export function rootLinks(html, base) {
|
|
300
|
+
return html.replace(/(\s(?:href|src)=")([^"]*)"/gi, (all, attr, url) => {
|
|
301
|
+
if (/^(?:[a-z][\w+.-]*:|\/|#|\?)/i.test(url))
|
|
302
|
+
return all;
|
|
303
|
+
const resolved = new URL(url.replace(/&/g, '&'), `http://x${base}`);
|
|
304
|
+
return `${attr}${(resolved.pathname + resolved.search + resolved.hash).replace(/&/g, '&')}"`;
|
|
305
|
+
});
|
|
306
|
+
}
|
|
@@ -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)
|
|
@@ -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
|
/**
|
|
@@ -20,3 +21,11 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
|
|
|
20
21
|
loader: boolean;
|
|
21
22
|
}[];
|
|
22
23
|
}>;
|
|
24
|
+
/** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). */
|
|
25
|
+
export declare function packageOf(file: string): string | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Component files reachable from `start` through @import lines: relative paths, root-relative ('/src/…') and package
|
|
28
|
+
* specifiers ('@clarusjs/theme-docs/layout.tscl', resolved as Node would from the app). Real paths, so a workspace
|
|
29
|
+
* package linked into node_modules is one file, not two.
|
|
30
|
+
*/
|
|
31
|
+
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[]): string[];
|