clarusjs 0.12.0 → 0.13.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/icons.js ADDED
@@ -0,0 +1,112 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join } from 'node:path';
4
+ const sets = new Map();
5
+ function packageDir(file) {
6
+ for (let dir = dirname(file);; dir = dirname(dir)) {
7
+ if (existsSync(join(dir, 'package.json')))
8
+ return dir;
9
+ if (dirname(dir) === dir)
10
+ return dirname(file);
11
+ }
12
+ }
13
+ function loadSet(set, fromFile) {
14
+ const dir = packageDir(fromFile);
15
+ let path;
16
+ try {
17
+ path = createRequire(join(dir, 'package.json')).resolve(`@iconify-json/${set}/icons.json`);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ const mtime = statSync(path).mtimeMs;
23
+ const cached = sets.get(path);
24
+ if (cached?.mtime === mtime)
25
+ return cached.data;
26
+ const data = JSON.parse(readFileSync(path, 'utf8'));
27
+ sets.set(path, { mtime, data });
28
+ return data;
29
+ }
30
+ function distance(a, b) {
31
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
32
+ for (let i = 1; i <= a.length; i++) {
33
+ const next = [i];
34
+ for (let j = 1; j <= b.length; j++)
35
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
36
+ row = next;
37
+ }
38
+ return row[b.length];
39
+ }
40
+ export function resolveIcon(name, fromFile) {
41
+ const colon = name.indexOf(':');
42
+ const set = colon === -1 ? name : name.slice(0, colon);
43
+ const icon = colon === -1 ? '' : name.slice(colon + 1);
44
+ const data = loadSet(set, fromFile);
45
+ if (!data)
46
+ return { missing: 'set', set };
47
+ const all = Object.assign(Object.create(null), data.aliases, data.icons);
48
+ const own = (n) => (Object.hasOwn(all, n) ? all[n] : undefined);
49
+ const first = own(icon);
50
+ if (!first) {
51
+ const suggestions = Object.keys(all)
52
+ .map((n) => [n, distance(icon, n)])
53
+ .filter(([n, d]) => d <= Math.max(2, Math.floor(n.length / 3)))
54
+ .sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]))
55
+ .slice(0, 3)
56
+ .map(([n]) => n);
57
+ return { missing: 'icon', set, suggestions };
58
+ }
59
+ let found = first;
60
+ let merged = { ...found };
61
+ for (let depth = 0; found.parent && depth < 10; depth++) {
62
+ const parent = own(found.parent);
63
+ if (!parent)
64
+ break;
65
+ merged = { ...parent, ...merged, parent: parent.parent };
66
+ found = parent;
67
+ }
68
+ for (const key of ['hFlip', 'vFlip', 'rotate']) {
69
+ if (merged[key])
70
+ throw new Error(`the icon ${name} uses ${key}, which <icon> doesn't support yet`);
71
+ }
72
+ return {
73
+ data: {
74
+ body: merged.body ?? '',
75
+ width: merged.width ?? data.width ?? 16,
76
+ height: merged.height ?? data.height ?? 16,
77
+ left: merged.left ?? data.left ?? 0,
78
+ top: merged.top ?? data.top ?? 0,
79
+ },
80
+ };
81
+ }
82
+ export function iconSets(fromFile) {
83
+ const dir = packageDir(fromFile);
84
+ const names = new Set();
85
+ try {
86
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
87
+ for (const deps of [pkg.dependencies, pkg.devDependencies])
88
+ for (const d of Object.keys(deps ?? {}))
89
+ if (d.startsWith('@iconify-json/'))
90
+ names.add(d.slice(14));
91
+ }
92
+ catch { }
93
+ try {
94
+ for (const d of readdirSync(join(dir, 'node_modules/@iconify-json')))
95
+ names.add(d);
96
+ }
97
+ catch { }
98
+ const out = [];
99
+ for (const prefix of [...names].sort()) {
100
+ const data = loadSet(prefix, fromFile);
101
+ if (data)
102
+ out.push({ prefix, name: data.info?.name ?? prefix, total: data.info?.total ?? Object.keys(data.icons).length });
103
+ }
104
+ return out;
105
+ }
106
+ export function iconNames(set, fromFile) {
107
+ const data = loadSet(set, fromFile);
108
+ return data ? Object.keys({ ...data.icons, ...data.aliases }).sort() : [];
109
+ }
110
+ export function iconSvg(data, attrs = '') {
111
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${data.left} ${data.top} ${data.width} ${data.height}"${attrs ? ' ' + attrs : ''}>${data.body}</svg>`;
112
+ }
@@ -1,5 +1,32 @@
1
1
  export declare const UNSAFE_URL = "about:invalid#unsafe";
2
+ /**
3
+ * A class from a string (as written), an object (its truthy keys) or an array (flattened, falsy entries dropped), like
4
+ * clsx. Templates use it for `[class]` values and `[class.name]` toggles.
5
+ * @example
6
+ * classValue(['a', on && 'b', { c: true, d: false }]) // 'a b c' when on
7
+ * @see https://clarusjs.com/guide/attributes
8
+ */
9
+ export declare function classValue(value: unknown): string;
10
+ /**
11
+ * A style from a string (as written), an object (camelCase keys to kebab-case, custom properties as they are; null,
12
+ * undefined, false and '' left out; no units added) or an array of those. Templates use it for `[style]` values and
13
+ * `[style.prop]` bindings.
14
+ * @example
15
+ * styleValue({ fontSize: '2em', '--accent': c, color: null }) // 'font-size: 2em; --accent: …;'
16
+ * @see https://clarusjs.com/guide/attributes
17
+ */
18
+ export declare function styleValue(value: unknown): string;
2
19
  /**
3
20
  * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
4
21
  */
5
22
  export declare function attrValue(name: string, value: unknown, tag?: string): string | true | null;
23
+ /**
24
+ * A spread's attributes (#405): each key with its value as attrValue gives it, except the names written on the element
25
+ * (`skip`, lowercase), class and style (merged with the element's own), and what a spread may never set, listed in
26
+ * `dropped` with why: event handlers, srcdoc, invalid names, JSX names and objects or functions.
27
+ * @internal the runtimes call this; apps write [...]="attrs".
28
+ */
29
+ export declare function spreadAttrs(obj: unknown, skip: readonly string[], tag?: string): {
30
+ set: [string, string | true | null][];
31
+ dropped: [string, string][];
32
+ };
@@ -29,6 +29,33 @@ function safeUrl(url, image) {
29
29
  // ARIA states whose absence means "doesn't apply" (no aria-expanded: nothing expands). Other aria-* (aria-current:
30
30
  // `active ? 'page' : false`) keep false = removed.
31
31
  const ENUMERATED = new Set(['contenteditable', 'draggable', 'spellcheck', 'translate', 'aria-expanded', 'aria-pressed', 'aria-checked', 'aria-selected']);
32
+ /**
33
+ * A class from a string (as written), an object (its truthy keys) or an array (flattened, falsy entries dropped), like
34
+ * clsx. Templates use it for `[class]` values and `[class.name]` toggles.
35
+ * @example
36
+ * classValue(['a', on && 'b', { c: true, d: false }]) // 'a b c' when on
37
+ * @see https://clarusjs.com/guide/attributes
38
+ */
39
+ export function classValue(value) {
40
+ const names = (v) => (!v ? [] : typeof v === 'string' ? v.split(/\s+/) : Array.isArray(v) ? v.flatMap(names) : typeof v === 'object' ? Object.keys(v).filter((k) => v[k]) : [String(v)]);
41
+ // Each class once, single spaces: a written class="star" and a bound 'star on' make "star on".
42
+ return [...new Set(names(value).filter(Boolean))].join(' ');
43
+ }
44
+ /**
45
+ * A style from a string (as written), an object (camelCase keys to kebab-case, custom properties as they are; null,
46
+ * undefined, false and '' left out; no units added) or an array of those. Templates use it for `[style]` values and
47
+ * `[style.prop]` bindings.
48
+ * @example
49
+ * styleValue({ fontSize: '2em', '--accent': c, color: null }) // 'font-size: 2em; --accent: …;'
50
+ * @see https://clarusjs.com/guide/attributes
51
+ */
52
+ export function styleValue(value) {
53
+ // A string stays whole (a url(data:…;base64,…) holds a ';'); only a trailing ';' is dropped before joining.
54
+ const decls = (v) => !v ? [] : typeof v === 'string' ? [v.trim().replace(/;\s*$/, '')].filter(Boolean) : Array.isArray(v) ? v.flatMap(decls) : typeof v === 'object'
55
+ ? Object.entries(v).filter(([, x]) => x != null && x !== false && x !== '').map(([k, x]) => `${k.startsWith('--') ? k : k.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase())}: ${x}`)
56
+ : [];
57
+ return decls(value).map((d) => d + ';').join(' ');
58
+ }
32
59
  /**
33
60
  * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
34
61
  */
@@ -36,6 +63,14 @@ export function attrValue(name, value, tag) {
36
63
  if (value == null)
37
64
  return null;
38
65
  const n = name.toLowerCase();
66
+ // A class from an object or an array (a spread's class, or one bound directly): its classes, never [object Object].
67
+ if (n === 'class' && typeof value === 'object')
68
+ return classValue(value) || null;
69
+ if (n === 'style' && typeof value === 'object')
70
+ return styleValue(value) || null;
71
+ // An empty class or style adds nothing (a spread without one, a class whose toggles are all off).
72
+ if ((n === 'class' || n === 'style') && value === '')
73
+ return null;
39
74
  if (typeof value === 'boolean' && ENUMERATED.has(n))
40
75
  return n === 'translate' ? (value ? 'yes' : 'no') : String(value); // translate: yes/no
41
76
  if (value === false)
@@ -62,3 +97,34 @@ export function attrValue(name, value, tag) {
62
97
  return UNSAFE_URL;
63
98
  return s;
64
99
  }
100
+ const ATTR_NAME = /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/;
101
+ /**
102
+ * A spread's attributes (#405): each key with its value as attrValue gives it, except the names written on the element
103
+ * (`skip`, lowercase), class and style (merged with the element's own), and what a spread may never set, listed in
104
+ * `dropped` with why: event handlers, srcdoc, invalid names, JSX names and objects or functions.
105
+ * @internal the runtimes call this; apps write [...]="attrs".
106
+ */
107
+ export function spreadAttrs(obj, skip, tag) {
108
+ const set = [];
109
+ const dropped = [];
110
+ if (!obj || typeof obj !== 'object')
111
+ return { set, dropped };
112
+ for (const [key, value] of Object.entries(obj)) {
113
+ const n = key.toLowerCase();
114
+ if (skip.includes(n) || n === 'class' || n === 'style')
115
+ continue;
116
+ const why = !ATTR_NAME.test(key) ? 'not an attribute name'
117
+ // clarusjs's own markers (data-cl-e, data-cl-a, data-cl-path…): data must not spoof the runtime's wiring.
118
+ : n.startsWith('data-cl-') || n.startsWith('cl-') ? 'reserved for clarusjs'
119
+ : n.startsWith('on') ? 'an event handler: use (event)="…" in an island'
120
+ : n === 'srcdoc' ? 'srcdoc is static only'
121
+ : key === 'className' ? 'a JSX name: use class' : key === 'htmlFor' ? 'a JSX name: use for'
122
+ : value !== null && (typeof value === 'object' || typeof value === 'function') ? 'not a value for an attribute (an object or a function)'
123
+ : '';
124
+ if (why)
125
+ dropped.push([key, why]);
126
+ else
127
+ set.push([key, attrValue(key, value, tag)]);
128
+ }
129
+ return { set, dropped };
130
+ }
@@ -69,6 +69,12 @@ export declare function text(hole: Hole, fn: () => unknown): void;
69
69
  export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event) => void): void;
70
70
  /** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
71
71
  export declare function marked(ctx: Ctx, selector: string): Element | undefined;
72
+ /**
73
+ * A reactive spread (#405): sets the attributes the object has, removes the ones it no longer has (only those it set:
74
+ * never one written on the element, which `skip` lists). Dropped keys are dropped silently here; the server warns.
75
+ * @internal
76
+ */
77
+ export declare function spread(ctx: Ctx, index: number, fn: () => unknown, skip: readonly string[], tag?: string): void;
72
78
  /** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. @internal */
73
79
  export declare function attr(ctx: Ctx, index: number, name: string, fn: () => unknown, tag?: string): void;
74
80
  /**
@@ -1,6 +1,6 @@
1
1
  // Attach helpers: find markers in server HTML and keep them updated. Browser only. Never re-renders existing HTML;
2
2
  // only @if branches and @for rows that did not exist on the server are rendered here.
3
- import { attrValue } from './attrs.js';
3
+ import { attrValue, spreadAttrs } from './attrs.js';
4
4
  import { batch, effect, onDispose, scope, state, untrack } from './signals.js';
5
5
  const rootOf = (ctx) => ('root' in ctx ? ctx.root : ctx);
6
6
  /** Is `node` inside `ctx` (always true for a whole island)? */
@@ -328,6 +328,31 @@ export function marked(ctx, selector) {
328
328
  const island = root.closest('cl-island');
329
329
  return [...root.querySelectorAll(selector)].find((e) => e.closest('cl-island') === island && inside(ctx, e));
330
330
  }
331
+ /**
332
+ * A reactive spread (#405): sets the attributes the object has, removes the ones it no longer has (only those it set:
333
+ * never one written on the element, which `skip` lists). Dropped keys are dropped silently here; the server warns.
334
+ * @internal
335
+ */
336
+ export function spread(ctx, index, fn, skip, tag) {
337
+ const el = marked(ctx, `[data-cl-a="${index}"]`);
338
+ if (!el)
339
+ return;
340
+ let had = new Set();
341
+ effect(() => {
342
+ const now = new Set();
343
+ for (const [name, v] of spreadAttrs(fn(), skip, tag).set) {
344
+ now.add(name);
345
+ if (v === null)
346
+ el.removeAttribute(name);
347
+ else
348
+ el.setAttribute(name, v === true ? '' : v);
349
+ }
350
+ for (const name of had)
351
+ if (!now.has(name))
352
+ el.removeAttribute(name);
353
+ had = now;
354
+ });
355
+ }
331
356
  /** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. @internal */
332
357
  export function attr(ctx, index, name, fn, tag) {
333
358
  const el = marked(ctx, `[data-cl-a="${index}"]`);
@@ -4,6 +4,12 @@ export declare const HTML: unique symbol;
4
4
  export declare function escape(value: unknown): string;
5
5
  /** A value as JSON for a <script> (JSON-LD): <, >, & and line separators escaped, so it can't end the script. @internal */
6
6
  export declare function json(value: unknown): string;
7
+ /**
8
+ * A spread's attributes as HTML (#405); `where` (file:line:col, server code only) names the place in a warning for
9
+ * each key it drops, once.
10
+ * @internal
11
+ */
12
+ export declare function spreadHtml(obj: unknown, skip: readonly string[], tag?: string, where?: string): string;
7
13
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
8
14
  export declare function attrHtml(name: string, value: unknown, tag?: string): string;
9
15
  /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. @internal */
@@ -1,5 +1,5 @@
1
1
  // HTML-string helpers used by compiled code on the server (render) and in the browser (branch HTML for @if).
2
- import { attrValue } from './attrs.js';
2
+ import { attrValue, spreadAttrs } from './attrs.js';
3
3
  /** The mark of h()'s output (clarusjs/views). Symbol.for: two copies of the module agree. @internal */
4
4
  export const HTML = Symbol.for('clarusjs.html');
5
5
  const ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
@@ -16,6 +16,24 @@ export function escape(value) {
16
16
  export function json(value) {
17
17
  return (JSON.stringify(value) ?? 'null').replace(/[<>&\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);
18
18
  }
19
+ const warned = new Set();
20
+ /**
21
+ * A spread's attributes as HTML (#405); `where` (file:line:col, server code only) names the place in a warning for
22
+ * each key it drops, once.
23
+ * @internal
24
+ */
25
+ export function spreadHtml(obj, skip, tag, where) {
26
+ const { set, dropped } = spreadAttrs(obj, skip, tag);
27
+ // Once per place and reason, not per key: keys come from data, so a set of them could grow without end on a server.
28
+ if (where)
29
+ for (const [key, why] of dropped) {
30
+ if (warned.has(`${where} ${why}`))
31
+ continue;
32
+ warned.add(`${where} ${why}`);
33
+ console.warn(`[clarusjs] ${where}: [...] dropped ${JSON.stringify(key)} (${why})`);
34
+ }
35
+ return set.map(([name, v]) => (v === null ? '' : v === true ? ` ${name}` : ` ${name}="${escape(v)}"`)).join('');
36
+ }
19
37
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
20
38
  export function attrHtml(name, value, tag) {
21
39
  const v = attrValue(name, value, tag);
@@ -1,5 +1,6 @@
1
1
  export { state, derived, shared, effect, scope, onDispose, untrack, batch, type Signal, type ReadSignal } from './signals.ts';
2
- export { holes, blocks, text, on, attr, block, forBlock, region, model, modelInput, type Hole, type Block, type Ctx } from './dom.ts';
3
- export { escape, attrHtml, blockHtml, forHtml, regionHtml } from './html.ts';
2
+ export { holes, blocks, text, on, attr, spread, block, forBlock, region, model, modelInput, type Hole, type Block, type Ctx } from './dom.ts';
3
+ export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
+ export { classValue, styleValue } from './attrs.ts';
5
6
  export { browser } from './env.ts';
@@ -1,6 +1,7 @@
1
1
  // Browser runtime used by compiled attach() functions.
2
2
  export { state, derived, shared, effect, scope, onDispose, untrack, batch } from './signals.js';
3
- export { holes, blocks, text, on, attr, block, forBlock, region, model, modelInput } from './dom.js';
4
- export { escape, attrHtml, blockHtml, forHtml, regionHtml } from './html.js';
3
+ export { holes, blocks, text, on, attr, spread, block, forBlock, region, model, modelInput } from './dom.js';
4
+ export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
+ export { classValue, styleValue } from './attrs.js';
6
7
  export { browser } from './env.js';
@@ -1,5 +1,6 @@
1
1
  import { attrHtml } from './html.ts';
2
- export { escape, json, blockHtml, forHtml, regionHtml } from './html.ts';
2
+ export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml } from './html.ts';
3
+ export { classValue, styleValue } from './attrs.ts';
3
4
  /**
4
5
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
5
6
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
@@ -1,7 +1,8 @@
1
1
  // Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
2
2
  import { attrHtml, escape, HTML } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
- export { escape, json, blockHtml, forHtml, regionHtml } from './html.js';
4
+ export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml } from './html.js';
5
+ export { classValue, styleValue } from './attrs.js';
5
6
  /**
6
7
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
7
8
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
@@ -1,3 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  export declare function toRequest(req: IncomingMessage): Request;
3
3
  export declare function sendResponse(res: ServerResponse, response: Response): Promise<void>;
4
+ /** Whether an Accept-Encoding header allows `encoding`: named, or through `*`, and not with q=0. */
5
+ export declare function acceptsEncoding(header: string, encoding: string): boolean;
package/dist/vite/node.js CHANGED
@@ -16,3 +16,16 @@ export async function sendResponse(res, response) {
16
16
  response.headers.forEach((value, key) => res.setHeader(key, value));
17
17
  res.end(Buffer.from(await response.arrayBuffer()));
18
18
  }
19
+ export function acceptsEncoding(header, encoding) {
20
+ let star = false;
21
+ for (const part of header.toLowerCase().split(',')) {
22
+ const [name, ...params] = part.trim().split(';');
23
+ const q = params.map((p) => p.trim()).find((p) => p.startsWith('q='));
24
+ const allowed = !q || Number(q.slice(2)) > 0;
25
+ if (name === encoding)
26
+ return allowed;
27
+ if (name === '*')
28
+ star = allowed;
29
+ }
30
+ return star;
31
+ }
@@ -66,10 +66,15 @@ export type ClarusOptions = {
66
66
  /**
67
67
  * With site.url, vite build writes sitemap.xml (static pages, dated from git). false: no sitemap. `exclude`: paths
68
68
  * left out ('/legal', '/tags/*' one segment, '/drafts/**' any depth). A page opts out itself with
69
- * <cl-head><meta name="sitemap" content="false"></cl-head> (removed from the built page) or noindex.
69
+ * <cl-head><meta name="sitemap" content="false"></cl-head> (removed from the built page) or noindex, and sets its
70
+ * own date with <meta name="sitemap:lastmod" content="2026-11-01">. Each page's images (not alt="", not data:) are
71
+ * listed with Google's image extension; `images: false` leaves them out. `include`: paths the build can't list (server
72
+ * and client routes), or a function returning them (async, to read them from a database at build time).
70
73
  */
71
74
  sitemap?: boolean | {
72
75
  exclude?: string[];
76
+ images?: boolean;
77
+ include?: string[] | (() => string[] | Promise<string[]>);
73
78
  };
74
79
  /** With site.url, vite build writes robots.txt (allow all, and the sitemap), unless public/robots.txt exists. */
75
80
  robots?: boolean;
@@ -31,11 +31,13 @@ import { writeNetlifyFunction } from './netlify.js';
31
31
  import { checkLinks } from './links.js';
32
32
  import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
33
33
  import { projectAliases, resolveAlias } from './aliases.js';
34
- import { gitDates, sitemapXml } from './sitemap.js';
34
+ import { gitDates, sitemapFiles } from './sitemap.js';
35
35
  import { checkModes, modeFor } from '../server/modes.js';
36
36
  import { rootLinks, routeFromFile } from '../server/handler.js';
37
37
  import { basePath } from '../server/head.js';
38
- import { sendResponse, toRequest } from './node.js';
38
+ import { acceptsEncoding, sendResponse, toRequest } from './node.js';
39
+ import { resolveIcon } from '../icons.js';
40
+ const iconsFor = (file) => (name) => resolveIcon(name, file);
39
41
  const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
40
42
  const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
41
43
  const ENTRY = 'virtual:clarusjs/server-entry';
@@ -124,7 +126,7 @@ function writeStyles(root, files) {
124
126
  const outDir = resolve(root, '.clarusjs');
125
127
  for (const file of files.components(root)) {
126
128
  try {
127
- let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file) }).css;
129
+ let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file), icon: iconsFor(file) }).css;
128
130
  out = out.replace(/^(?:[ \t]*@(?:reference|import)\b[^;{]*;[ \t]*\n?)+/, (statements) => {
129
131
  for (const statement of statements.split(';').map((x) => x.trim()).filter(Boolean)) {
130
132
  head.add(statement.replace(/(["'])(\.{1,2}\/[^"']*)\1/, (_, q, spec) => {
@@ -158,6 +160,19 @@ function clientPages(appRoot, modes, files) {
158
160
  }
159
161
  return pages;
160
162
  }
163
+ function metaAttr(tag, name) {
164
+ return new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
165
+ }
166
+ function lastmodTime(value) {
167
+ const m = /^(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$/.exec(value);
168
+ if (!m)
169
+ return NaN;
170
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
171
+ const day = new Date(Date.UTC(y, mo - 1, d));
172
+ if (day.getUTCFullYear() !== y || day.getUTCMonth() !== mo - 1 || day.getUTCDate() !== d)
173
+ return NaN;
174
+ return Date.parse(m[4] ? value : `${value}T00:00:00Z`);
175
+ }
161
176
  function pluginsOf(list) {
162
177
  if (Array.isArray(list))
163
178
  return list.flatMap(pluginsOf);
@@ -261,7 +276,7 @@ export default function clarusjs(options = {}) {
261
276
  const input = { [LOADER_ENTRY]: here('../runtime/loader') };
262
277
  const components = files.components(appRoot);
263
278
  for (const file of components) {
264
- if (compile(files.read(file, appRoot), { file, target: 'client' }).stateful)
279
+ if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file) }).stateful)
265
280
  input[entryName(appRoot, file)] = file;
266
281
  }
267
282
  const client = clientPages(appRoot, modes, files);
@@ -337,6 +352,28 @@ export default function clarusjs(options = {}) {
337
352
  }
338
353
  const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
339
354
  const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
355
+ const markers = new Map();
356
+ for (const page of pageRoutes) {
357
+ const file = resolve(out, routeToFile(page));
358
+ let html = readFileSync(file, 'utf8');
359
+ const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
360
+ const optOut = tags.find((tag) => metaAttr(tag, 'name')?.toLowerCase() === 'sitemap' && metaAttr(tag, 'content') === 'false');
361
+ const dated = tags.find((tag) => metaAttr(tag, 'name')?.toLowerCase() === 'sitemap:lastmod');
362
+ let lastmod;
363
+ if (dated) {
364
+ const value = metaAttr(dated, 'content') ?? '';
365
+ const time = lastmodTime(value);
366
+ if (Number.isNaN(time))
367
+ throw new Error(`clarusjs: ${page}: sitemap:lastmod '${value}' isn't a date (YYYY-MM-DD)`);
368
+ lastmod = time / 1000;
369
+ }
370
+ for (const marker of [optOut, dated])
371
+ if (marker)
372
+ html = html.replace(marker, '');
373
+ if (optOut || dated)
374
+ writeFileSync(file, html);
375
+ markers.set(page, { out: !!optOut, ...(lastmod === undefined ? {} : { lastmod }) });
376
+ }
340
377
  if (pageRoutes.includes('/404') && !clientRoutes.includes('/404')) {
341
378
  const html = rootLinks(readFileSync(resolve(out, routeToFile('/404')), 'utf8'), basePath(builder.config.base));
342
379
  writeFileSync(resolve(out, routeToFile('/404')), html);
@@ -391,19 +428,41 @@ export default function clarusjs(options = {}) {
391
428
  const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
392
429
  const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
393
430
  .map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
394
- const optedOut = (page) => {
431
+ const images = typeof options.sitemap !== 'object' || options.sitemap.images !== false;
432
+ const sitemapMeta = (page) => {
395
433
  const file = resolve(out, routeToFile(page));
396
434
  const html = readFileSync(file, 'utf8');
397
435
  const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
398
- const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
399
- const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
400
- if (marker)
401
- writeFileSync(file, html.replace(marker, ''));
402
- return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
436
+ const attr = metaAttr;
437
+ const { out: optOut, lastmod } = markers.get(page) ?? { out: false };
438
+ const decode = (v) => v.replace(/&(amp|quot|#39|lt|gt);/g, (_, e) => ({ amp: '&', quot: '"', '#39': "'", lt: '<', gt: '>' })[e]);
439
+ const pics = images ? [...new Set([...html.matchAll(/<img\b[^>]*>/gi)].map(([tag]) => tag)
440
+ .filter((tag) => attr(tag, 'alt') !== '')
441
+ .map((tag) => decode(attr(tag, 'src') ?? ''))
442
+ .filter((src) => src && !/^data:/i.test(src)))].slice(0, 1000) : [];
443
+ const alternates = [...html.matchAll(/<link\b[^>]*>/gi)].map(([tag]) => tag)
444
+ .filter((tag) => /(^|\s)alternate(\s|$)/i.test(attr(tag, 'rel') ?? '') && attr(tag, 'hreflang') && attr(tag, 'href'))
445
+ .map((tag) => ({ hreflang: attr(tag, 'hreflang'), href: decode(attr(tag, 'href')) }));
446
+ return { out: optOut || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? '')), ...(lastmod === undefined ? {} : { lastmod }), images: pics, alternates };
403
447
  };
404
- const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
405
- .map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
406
- writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
448
+ const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page))
449
+ .map((path) => ({ path, meta: sitemapMeta(path) }));
450
+ const keptOut = new Set(pages.filter(({ path, meta }) => meta.out || exclude.some((re) => re.test(path))).map((p) => p.path));
451
+ const listedPages = pages.filter(({ path }) => !keptOut.has(path));
452
+ const entries = listedPages.map(({ path, meta }) => ({ path, lastmod: meta.lastmod ?? dates.get(fileOf(path) ?? '') ?? epoch, images: meta.images, alternates: meta.alternates }));
453
+ const include = typeof options.sitemap === 'object' ? options.sitemap.include : undefined;
454
+ const extra = typeof include === 'function' ? await include() : include ?? [];
455
+ const listed = new Set(entries.map((p) => p.path));
456
+ for (const path of extra) {
457
+ if (typeof path !== 'string' || !path.startsWith('/'))
458
+ throw new Error(`clarusjs: sitemap.include: '${String(path)}' isn't a path (start it with /)`);
459
+ if (listed.has(path) || keptOut.has(path) || exclude.some((re) => re.test(path)))
460
+ continue;
461
+ entries.push({ path, lastmod: undefined, images: [], alternates: [] });
462
+ listed.add(path);
463
+ }
464
+ for (const { file, xml } of sitemapFiles(options.site.url, builder.config.base, entries))
465
+ writeFileSync(resolve(out, file), xml);
407
466
  }
408
467
  if (options.site && options.robots !== false && !existsSync(resolve(out, 'robots.txt'))) {
409
468
  const sitemap = options.sitemap !== false ? `\nSitemap: ${new URL('sitemap.xml', new URL(builder.config.base, options.site.url.replace(/\/?$/, '/'))).href}\n` : '';
@@ -517,7 +576,7 @@ export default function clarusjs(options = {}) {
517
576
  const clientUrl = urls
518
577
  ? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/')) ?? urls.get(real(file))
519
578
  : command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
520
- if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
579
+ if (urls && !clientUrl && compile(code, { file, target: 'client', icon: iconsFor(file) }).stateful) {
521
580
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
522
581
  }
523
582
  let parsed;
@@ -541,7 +600,7 @@ export default function clarusjs(options = {}) {
541
600
  const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
542
601
  const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
543
602
  const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
544
- const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot });
603
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file) });
545
604
  if (consumer === 'server' && !renderQuery)
546
605
  for (const w of out.warnings)
547
606
  this.warn(w.message);
@@ -572,6 +631,7 @@ export default function clarusjs(options = {}) {
572
631
  const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
573
632
  if (file.startsWith(outDir + sep) && existsSync(file))
574
633
  req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
634
+ precompressed(req, res, outDir, base);
575
635
  }
576
636
  next();
577
637
  });
@@ -643,6 +703,30 @@ export default function clarusjs(options = {}) {
643
703
  },
644
704
  };
645
705
  }
706
+ function precompressed(req, res, outDir, base) {
707
+ if ((req.method !== 'GET' && req.method !== 'HEAD') || req.headers.range)
708
+ return;
709
+ const [path, query] = (req.url ?? '/').split('?');
710
+ if (!path.startsWith(base))
711
+ return;
712
+ let file;
713
+ try {
714
+ file = resolve(outDir, decodeURIComponent(path.slice(base.length)));
715
+ }
716
+ catch {
717
+ return;
718
+ }
719
+ if (!file.startsWith(outDir + sep) || !existsSync(file))
720
+ return;
721
+ const copies = ['br', 'gzip'].filter((enc) => existsSync(file + (enc === 'br' ? '.br' : '.gz')));
722
+ if (!copies.length)
723
+ return;
724
+ res.setHeader('Vary', 'Accept-Encoding');
725
+ const accept = String(req.headers['accept-encoding'] ?? '');
726
+ const pick = copies.find((enc) => acceptsEncoding(accept, enc));
727
+ if (pick)
728
+ req.url = `${path}${pick === 'br' ? '.br' : '.gz'}${query === undefined ? '' : `?${query}`}`;
729
+ }
646
730
  function precompress(dir) {
647
731
  for (const name of readdirSync(dir, { recursive: true })) {
648
732
  if (!/\.(html|js|css|svg|json|xml)$/.test(name))
@@ -5,8 +5,27 @@
5
5
  * @internal clarusjs's own build and server code call this; apps don't.
6
6
  */
7
7
  export declare function gitDates(root: string, dir: string): Map<string, number>;
8
- /** The sitemap: one <url> per page, under the site URL and base; lastmod (unix seconds) as a date when known. */
8
+ /**
9
+ * The sitemap: one <url> per page, under the site URL and base; lastmod (unix seconds) as a date when known; images
10
+ * (src as written, resolved against the page's URL) with Google's image extension; translations (hreflang alternates,
11
+ * href resolved the same way) as xhtml:link.
12
+ */
9
13
  export declare function sitemapXml(siteUrl: string, base: string, pages: {
10
14
  path: string;
11
15
  lastmod: number | undefined;
16
+ images?: string[];
17
+ alternates?: {
18
+ hreflang: string;
19
+ href: string;
20
+ }[];
12
21
  }[]): string;
22
+ /**
23
+ * The sitemap files to write: one sitemap.xml within the protocol's limits (50,000 URLs and 52,428,800 bytes
24
+ * uncompressed a file); past either, sitemap-1.xml, sitemap-2.xml… each within both, and sitemap.xml as their index,
25
+ * so robots.txt and search consoles keep one address. (A single page past the byte limit still gets a file alone.)
26
+ * @internal the build writes these; apps don't call it.
27
+ */
28
+ export declare function sitemapFiles(siteUrl: string, base: string, pages: Parameters<typeof sitemapXml>[2], max?: number, maxBytes?: number): {
29
+ file: string;
30
+ xml: string;
31
+ }[];