clarusjs 0.6.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.
Files changed (43) hide show
  1. package/README.md +2 -0
  2. package/dist/check/generate.js +1 -21
  3. package/dist/cli/check.js +44 -11
  4. package/dist/cli/explain.js +0 -1
  5. package/dist/cli/index.js +0 -1
  6. package/dist/compiler/emit-client.js +1 -11
  7. package/dist/compiler/emit-server.js +1 -2
  8. package/dist/compiler/errors.js +0 -1
  9. package/dist/compiler/html-expr.js +2 -7
  10. package/dist/compiler/index.d.ts +6 -0
  11. package/dist/compiler/index.js +45 -4
  12. package/dist/compiler/ir.d.ts +1 -0
  13. package/dist/compiler/ir.js +9 -14
  14. package/dist/compiler/parse.d.ts +10 -0
  15. package/dist/compiler/parse.js +48 -20
  16. package/dist/compiler/script.js +2 -31
  17. package/dist/compiler/shared.js +0 -5
  18. package/dist/runtime/fragments.js +23 -3
  19. package/dist/runtime/html.d.ts +2 -0
  20. package/dist/runtime/html.js +4 -0
  21. package/dist/runtime/loader.js +46 -3
  22. package/dist/runtime/router.d.ts +1 -1
  23. package/dist/runtime/router.js +23 -15
  24. package/dist/runtime/server.d.ts +1 -1
  25. package/dist/runtime/server.js +1 -1
  26. package/dist/server/handler.d.ts +15 -1
  27. package/dist/server/handler.js +61 -52
  28. package/dist/server/head.d.ts +36 -0
  29. package/dist/server/head.js +129 -0
  30. package/dist/server/manifest.js +0 -3
  31. package/dist/server/modes.js +0 -5
  32. package/dist/server/views.js +1 -8
  33. package/dist/vite/build.d.ts +10 -2
  34. package/dist/vite/build.js +44 -19
  35. package/dist/vite/links.d.ts +20 -0
  36. package/dist/vite/links.js +94 -0
  37. package/dist/vite/manifest.js +2 -10
  38. package/dist/vite/netlify.js +1 -7
  39. package/dist/vite/plugin.d.ts +55 -0
  40. package/dist/vite/plugin.js +282 -82
  41. package/dist/vite/sitemap.d.ts +11 -0
  42. package/dist/vite/sitemap.js +31 -0
  43. package/package.json +5 -3
@@ -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.tscl' → '/about' */
22
20
  export function routeFromFile(file) {
23
- const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.tscl$/, '').replace(/\/index$/, '');
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,17 +38,18 @@ 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; // a malformed %-escape names no page
41
+ return null;
45
42
  }
46
43
  return { route, params };
47
44
  }
48
45
  return null;
49
46
  }
50
- // entries() per route, asked once: prerendering and requests see the same list. null when there is none.
47
+ const links = (urls) => [...new Set([...urls, ...(options.stylesUrl ? [options.stylesUrl] : [])])].map((u) => `<link rel="stylesheet" href="${u}">`).join('');
48
+ const pageLinks = (route) => links(options.css?.[route.path] ?? []);
51
49
  const entriesCache = new Map();
52
50
  function entriesOf(route) {
53
51
  if (!entriesCache.has(route)) {
54
- const file = `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
52
+ const file = `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
55
53
  entriesCache.set(route, (async () => {
56
54
  const mod = data[file] ? await data[file]() : undefined;
57
55
  return mod?.entries ? await mod.entries() : null;
@@ -59,30 +57,24 @@ export function createHandler(pages, options = {}) {
59
57
  }
60
58
  return entriesCache.get(route);
61
59
  }
62
- // Without entries() a route isn't restricted here (the build reports it).
63
60
  async function listed(route, params) {
64
61
  const list = await entriesOf(route);
65
62
  return !list || list.some((entry) => route.keys.every((key) => entry[key] === params[key]));
66
63
  }
67
- return {
64
+ const handler = {
68
65
  routes: routes.map((r) => r.path).sort(),
69
- /** Routes rendered per request ('server' mode), as their files name them. */
70
66
  serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
71
- /** Whether a URL path belongs to a server route (what a host must send to this handler instead of a file). */
72
67
  isServerPath(pathname) {
73
68
  const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
74
- // <page>/index.frag.html belongs to that page when it exists; otherwise it is an ordinary path.
75
69
  const owner = options.fragments && pathname.endsWith(`/${FRAG}`) ? match(trim(pathname.slice(0, -FRAG.length - 1) || '/')) : null;
76
70
  const found = owner ?? match(trim(pathname));
77
71
  return Boolean(found && modeFor(found.route.path, modes) === 'server');
78
72
  },
79
- /** Whether a route (as its file names it) has a load(). */
80
73
  async hasLoader(path) {
81
74
  const route = routes.find((r) => r.path === path);
82
- const file = route && `/${route.file.replace(/\.tscl$/, '.load.ts')}`;
75
+ const file = route && `/${route.file.replace(/\.[^./]+$/, '.load.ts')}`;
83
76
  return Boolean(file && data[file] && typeof (await data[file]()).load === 'function');
84
77
  },
85
- /** Every concrete path to prerender: static routes as they are, dynamic ones from their entries(). */
86
78
  async paths() {
87
79
  const out = [];
88
80
  for (const route of routes) {
@@ -91,10 +83,8 @@ export function createHandler(pages, options = {}) {
91
83
  continue;
92
84
  const add = (path) => {
93
85
  out.push(path);
94
- // A client page's data, fetched by the router: written next to its shell.
95
86
  if (mode === 'client')
96
87
  out.push(path === '/' ? `/${DATA}` : `${path}/${DATA}`);
97
- // A static page's fragment, for fragment navigation.
98
88
  else if (options.fragments)
99
89
  out.push(path === '/' ? `/${FRAG}` : `${path}/${FRAG}`);
100
90
  };
@@ -102,7 +92,7 @@ export function createHandler(pages, options = {}) {
102
92
  add(route.path);
103
93
  continue;
104
94
  }
105
- const dataFile = route.file.replace(/\.tscl$/, '.load.ts');
95
+ const dataFile = route.file.replace(/\.[^./]+$/, '.load.ts');
106
96
  const list = await entriesOf(route);
107
97
  if (!list)
108
98
  throw new Error(`${route.path} is a dynamic route: export entries() from ${dataFile} to list the pages to prerender`);
@@ -112,9 +102,6 @@ export function createHandler(pages, options = {}) {
112
102
  if (key === undefined)
113
103
  return seg;
114
104
  const value = params[key];
115
- // Each value fills one path segment and names a folder in the build: never empty, '.' or '..'.
116
- // Path separators on any OS ('/', '\\') and NUL could step out of that folder once the segment is decoded.
117
- // __data.json and index.frag.html are a page's data and fragment files, so they can't also name a page.
118
105
  if (typeof value !== 'string' || value === '' || value === '.' || value === '..' || value === DATA || value === FRAG || /[/\\\0]/.test(value)) {
119
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}"`);
120
107
  }
@@ -128,10 +115,7 @@ export function createHandler(pages, options = {}) {
128
115
  if (request.method !== 'GET' && request.method !== 'HEAD')
129
116
  return new Response('Method Not Allowed', { status: 405 });
130
117
  const pathname = new URL(request.url).pathname;
131
- // '/guide/x/' is the same page as '/guide/x', in dev as on a static host.
132
118
  const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
133
- // <client route>/__data.json is that page's props, for the router. Only for a client route: anywhere else the
134
- // path is an ordinary page path (a server route may well have an [id] of "__data.json").
135
119
  let found = match(trim(pathname));
136
120
  let wantsData = false;
137
121
  if (pathname.endsWith(`/${DATA}`)) {
@@ -141,7 +125,6 @@ export function createHandler(pages, options = {}) {
141
125
  wantsData = true;
142
126
  }
143
127
  }
144
- // <static or server route>/index.frag.html: that page's fragment, for fragment navigation.
145
128
  let wantsFrag = false;
146
129
  if (options.fragments && !wantsData && pathname.endsWith(`/${FRAG}`)) {
147
130
  const owner = match(trim(pathname.slice(0, -FRAG.length - 1) || '/'));
@@ -151,26 +134,41 @@ export function createHandler(pages, options = {}) {
151
134
  }
152
135
  }
153
136
  const head = request.method === 'HEAD';
154
- const notFound = () => new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
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
+ };
155
146
  const mode = found && modeFor(found.route.path, modes);
156
147
  if (!found)
157
148
  return notFound();
158
- // A prerendered dynamic route only has the pages its entries() lists, as on a static host.
159
149
  if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
160
150
  return notFound();
161
151
  if (mode === 'client' && !wantsData) {
162
- // In matching order (static before dynamic, as on the server): the router takes the first match.
163
152
  const client = options.client ?? {};
164
153
  const prefix = (options.base ?? '/').replace(/\/$/, '');
165
154
  const table = routes.filter((r) => client[r.path]).map((r) => ({ p: (prefix + r.path).replace(/(.)\/$/, '$1'), r: client[r.path] }));
166
155
  const shell = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
167
- `<style>cl-island{display:contents}</style><script type="application/json" id="cl-routes">${safeJson(JSON.stringify(table))}</script>` +
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>` +
168
158
  `<script type="module" src="${loaderUrl}"></script><script type="module" src="${options.routerUrl ?? '/cl-router.js'}"></script>` +
169
159
  '</head><body><noscript>This page is rendered in the browser and needs JavaScript.</noscript></body></html>';
170
- return new Response(head ? null : shell, { headers: { 'content-type': 'text/html; charset=utf-8' } });
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' } });
171
169
  }
172
170
  let props = found.params;
173
- const dataFile = found.route.file.replace(/\.tscl$/, '.load.ts');
171
+ const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
174
172
  const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
175
173
  if (mod?.load) {
176
174
  let loaded;
@@ -184,46 +182,51 @@ export function createHandler(pages, options = {}) {
184
182
  return failure(`${dataFile}: load() must return an object of page inputs, got ${Array.isArray(loaded) ? 'an array' : loaded === null ? 'null' : typeof loaded}`);
185
183
  }
186
184
  ;
187
- globalThis.__clLoaderRan = true; // recorded by prerender for the manifest
185
+ globalThis.__clLoaderRan = true;
188
186
  props = { ...found.params, ...loaded };
189
187
  }
190
188
  if (wantsData) {
191
189
  return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
192
190
  }
193
- const html = (await found.route.load()).render(props);
194
- if (wantsFrag)
195
- return new Response(head ? null : toFragment(html), { headers: { 'content-type': 'text/html; charset=utf-8' } });
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
+ }
200
+ if (wantsFrag) {
201
+ const fragment = toFragment(html).replace(/^(<title\b[^>]*>[\s\S]*?<\/title\s*>)/i, (t) => t + pageLinks(found.route));
202
+ return new Response(head ? null : fragment, { headers: { 'content-type': 'text/html; charset=utf-8' } });
203
+ }
196
204
  const visible = maskComments(html);
197
205
  const hasIslands = visible.includes('<cl-island ');
198
- // Only pages with islands get a script, and only the loader; it fetches each island's own chunk. With fragment
199
- // navigation every page gets the navigation script instead, which brings the loader for islands that arrive.
200
206
  const nav = options.fragments === true;
201
- const style = hasIslands || nav ? '<style>cl-island{display:contents}</style>' : ''; // islands never affect layout
207
+ const sheet = pageLinks(found.route);
208
+ const style = sheet + (hasIslands || nav ? '<style>cl-island{display:contents}</style>' : '');
202
209
  const script = nav
203
210
  ? `<script type="module" src="${options.navUrl ?? '/cl-nav.js'}"></script>`
204
211
  : hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
205
- const body = /<html[\s>]/i.test(visible)
206
- ? fullDocument(html, style, script)
207
- : `<!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);
208
213
  return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
209
214
  },
210
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') || '/';
211
221
  }
212
- /** A 500 that tells the visitor nothing internal; the details go to the server log (and the build's output). */
213
222
  function failure(message) {
214
223
  console.error(`[clarusjs] ${message}`);
215
224
  return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } });
216
225
  }
217
- /**
218
- * A page's fragment: its <title>, then the element marked data-cl-swap (the region fragment navigation replaces), or
219
- * its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
220
- */
221
226
  export function toFragment(html) {
222
- // Comments and raw-text contents (scripts, styles, textareas, the title) can hold tag-shaped text: blank them out.
223
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);
224
228
  const title = /<title\b[^>]*>[\s\S]*?<\/title\s*>/i.exec(masked);
225
229
  const titleHtml = title ? html.slice(title.index, title.index + title[0].length) : '<title>clarusjs</title>';
226
- // The first start tag that carries a data-cl-swap attribute (boolean or with a value), attributes parsed properly.
227
230
  const tags = /<([a-zA-Z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
228
231
  let marked = null;
229
232
  for (let m = tags.exec(masked); m; m = tags.exec(masked)) {
@@ -250,11 +253,9 @@ export function toFragment(html) {
250
253
  return `${titleHtml}<body>${html}</body>`;
251
254
  return titleHtml + html.slice(open.index, close) + '</body>';
252
255
  }
253
- /** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
254
256
  function maskComments(html) {
255
257
  return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
256
258
  }
257
- /** A page whose layout renders the whole document: add the doctype if missing, and put style/script in place. */
258
259
  function fullDocument(html, style, script) {
259
260
  let out = /^\s*<!doctype/i.test(html) ? html : `<!doctype html>${html}`;
260
261
  if (style) {
@@ -268,3 +269,11 @@ function fullDocument(html, style, script) {
268
269
  }
269
270
  return out;
270
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(/&amp;/g, '&'), `http://x${base}`);
277
+ return `${attr}${(resolved.pathname + resolved.search + resolved.hash).replace(/&/g, '&amp;')}"`;
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
+ }
@@ -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;
@@ -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 };
@@ -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
- return file.replace(/^.*?\/src\//, '').replace(/\.tscl$/, '');
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)
@@ -1,5 +1,5 @@
1
- /** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
2
- export declare function findClarusFiles(srcDir: string): string[];
1
+ /** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
2
+ export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
3
3
  /**
4
4
  * '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
5
5
  * Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
@@ -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[];
@@ -1,9 +1,9 @@
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 { resolve } from 'node:path';
5
- /** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
6
- export function findClarusFiles(srcDir) {
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
+ export function findClarusFiles(srcDir, extensions = ['.tscl']) {
7
7
  let entries;
8
8
  try {
9
9
  entries = readdirSync(srcDir, { recursive: true });
@@ -11,13 +11,8 @@ export function findClarusFiles(srcDir) {
11
11
  catch {
12
12
  return [];
13
13
  }
14
- return entries.filter((f) => f.endsWith('.tscl')).map((f) => resolve(srcDir, f)).sort();
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
- } // '100%' is a name, not an escape
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
+ }
@@ -0,0 +1,20 @@
1
+ export type LinkIssue = {
2
+ kind: 'pages' | 'anchors';
3
+ page: string;
4
+ href: string;
5
+ message: string;
6
+ };
7
+ type Options = {
8
+ outDir: string;
9
+ /** Every built route (static pages and client shells), as URLs without the base. */
10
+ routes: string[];
11
+ /** Server routes as their files name them ('/account/[id]'): rendered per request, so any match counts. */
12
+ serverRoutes: string[];
13
+ /** Client routes render in the browser: their pages exist, but their anchors can't be checked at build. */
14
+ clientRoutes: string[];
15
+ base: string;
16
+ /** site.url: absolute links to the site itself are checked like internal ones. */
17
+ site?: string;
18
+ };
19
+ export declare function checkLinks(options: Options): LinkIssue[];
20
+ export {};