clarusjs 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/check/generate.js +1 -21
  2. package/dist/cli/check.js +44 -11
  3. package/dist/cli/explain.js +0 -1
  4. package/dist/cli/index.js +0 -1
  5. package/dist/compiler/emit-client.js +1 -11
  6. package/dist/compiler/emit-server.js +1 -2
  7. package/dist/compiler/errors.js +0 -1
  8. package/dist/compiler/html-expr.js +2 -7
  9. package/dist/compiler/index.js +10 -8
  10. package/dist/compiler/ir.d.ts +1 -0
  11. package/dist/compiler/ir.js +9 -14
  12. package/dist/compiler/parse.d.ts +1 -0
  13. package/dist/compiler/parse.js +18 -19
  14. package/dist/compiler/script.js +2 -31
  15. package/dist/compiler/shared.js +0 -5
  16. package/dist/runtime/fragments.js +8 -3
  17. package/dist/runtime/html.d.ts +2 -0
  18. package/dist/runtime/html.js +4 -0
  19. package/dist/runtime/loader.js +39 -2
  20. package/dist/runtime/router.d.ts +1 -1
  21. package/dist/runtime/router.js +9 -8
  22. package/dist/runtime/server.d.ts +1 -1
  23. package/dist/runtime/server.js +1 -1
  24. package/dist/server/handler.d.ts +10 -0
  25. package/dist/server/handler.js +48 -48
  26. package/dist/server/head.d.ts +36 -0
  27. package/dist/server/head.js +129 -0
  28. package/dist/server/manifest.js +0 -3
  29. package/dist/server/modes.js +0 -5
  30. package/dist/server/views.js +0 -7
  31. package/dist/vite/build.d.ts +8 -0
  32. package/dist/vite/build.js +42 -17
  33. package/dist/vite/links.d.ts +2 -0
  34. package/dist/vite/links.js +11 -10
  35. package/dist/vite/manifest.js +2 -10
  36. package/dist/vite/netlify.js +1 -7
  37. package/dist/vite/plugin.d.ts +29 -0
  38. package/dist/vite/plugin.js +99 -73
  39. package/dist/vite/sitemap.d.ts +11 -0
  40. package/dist/vite/sitemap.js +31 -0
  41. package/package.json +4 -2
@@ -1,4 +1,3 @@
1
- // .tscl source → syntax tree. Pure: no file system, no JS parsing (expressions are kept as raw strings).
2
1
  import { ClarusError } from './errors.js';
3
2
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
4
3
  const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?\s*$/d;
@@ -27,7 +26,6 @@ export function parse(source, file) {
27
26
  out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
28
27
  }
29
28
  else if ((m = line.match(IMPORT_RE))) {
30
- // A default import of a .tscl file is a component; of anything else, data.
31
29
  if (m[3].endsWith('.tscl'))
32
30
  out.imports.push({ name: m[1], from: m[3], start: i });
33
31
  else
@@ -76,7 +74,6 @@ export function parse(source, file) {
76
74
  }
77
75
  else {
78
76
  if (typeof value === 'string' && value.includes('{{')) {
79
- // Split into literal text and {{ expr }} parts; valueStart is the offset of the value's first character.
80
77
  const valueStart = start + name.length + 2;
81
78
  const parts = [];
82
79
  let at = 0;
@@ -102,8 +99,6 @@ export function parse(source, file) {
102
99
  }
103
100
  }
104
101
  }
105
- // Find the `}}` that closes a hole, skipping strings, template literals and nested brackets.
106
- // ponytail: regex literals containing quotes or braces are not recognised; tokenise with acorn if that ever bites
107
102
  function holeEnd(from) {
108
103
  const stack = [];
109
104
  for (let j = from; j < source.length; j++) {
@@ -139,8 +134,6 @@ export function parse(source, file) {
139
134
  }
140
135
  return -1;
141
136
  }
142
- // Parse children until `</parent>` (or end of input at top level).
143
- // A parenthesised JS condition after `@if` / `@else if`, skipping strings and nested parentheses.
144
137
  function condition(keyword) {
145
138
  while (/\s/.test(source[i] ?? ''))
146
139
  i++;
@@ -164,7 +157,6 @@ export function parse(source, file) {
164
157
  }
165
158
  return fail(`unclosed ( after ${keyword}`, open);
166
159
  }
167
- // @if (a) { … } @else if (b) { … } @else { … }
168
160
  function ifBlock() {
169
161
  const start = i;
170
162
  i += 3;
@@ -178,7 +170,7 @@ export function parse(source, file) {
178
170
  i++;
179
171
  branches.push({ ...next, children: children({ tag: '@if', start, block: true }) });
180
172
  if (next.cond === null)
181
- break; // @else is last
173
+ break;
182
174
  const save = i;
183
175
  while (/\s/.test(source[i] ?? ''))
184
176
  i++;
@@ -198,8 +190,6 @@ export function parse(source, file) {
198
190
  }
199
191
  return { type: 'if', branches, start };
200
192
  }
201
- // Split at top-level ';' (outside strings and brackets).
202
- /** Top-level `;` clauses, trimmed, each with its offset in `text`. */
203
193
  function splitClauses(text) {
204
194
  const parts = [];
205
195
  const push = (from, to) => {
@@ -228,12 +218,10 @@ export function parse(source, file) {
228
218
  push(from, text.length);
229
219
  return parts;
230
220
  }
231
- // @for (item of list; track key) { … } @empty { … }
232
221
  function forBlock() {
233
222
  const start = i;
234
223
  i += 4;
235
224
  const { cond: head, condStart: headStart } = condition('@for');
236
- // Where `head` (trimmed) starts in the source, so every part below gets its exact offset.
237
225
  let at = headStart;
238
226
  while (/\s/.test(source[at] ?? ''))
239
227
  at++;
@@ -277,7 +265,6 @@ export function parse(source, file) {
277
265
  i = save;
278
266
  return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, children: body, empty, start };
279
267
  }
280
- // @slot('name') { … }: content for a component's named slot.
281
268
  function fillBlock() {
282
269
  const start = i;
283
270
  i += 5;
@@ -314,7 +301,7 @@ export function parse(source, file) {
314
301
  const end = source.indexOf('-->', i + 4);
315
302
  if (end === -1)
316
303
  fail('unclosed <!-- comment', i);
317
- text += source.slice(i, end + 3); // kept verbatim as static text: no tags, no holes inside
304
+ text += source.slice(i, end + 3);
318
305
  i = end + 3;
319
306
  }
320
307
  else if (/^@if[\s(]/.test(source.slice(i, i + 4))) {
@@ -374,7 +361,6 @@ export function parse(source, file) {
374
361
  const selfClosing = source.startsWith('/>', i);
375
362
  i += selfClosing ? 2 : 1;
376
363
  if (tag === 'script' && list.some((a) => a.name === 'inline')) {
377
- // <script inline>: written out as is and run where it stands (e.g. in <head>, before the first paint).
378
364
  const bound = list.find((a) => a.kind !== 'static');
379
365
  if (bound)
380
366
  fail('an inline script takes static attributes only', bound.start);
@@ -385,6 +371,22 @@ export function parse(source, file) {
385
371
  nodes.push({ type: 'element', tag, attrs: list.filter((a) => a.name !== 'inline'), children: kids, start });
386
372
  i = selfClosing ? i : end + '</script>'.length;
387
373
  }
374
+ else if (tag === 'script' && list.some((a) => a.kind === 'static' && a.name === 'type' && a.value === 'application/ld+json')) {
375
+ const bound = list.find((a) => a.kind !== 'static');
376
+ if (bound)
377
+ fail('a JSON-LD script takes static attributes only', bound.start);
378
+ const end = source.indexOf('</script>', i);
379
+ if (end === -1)
380
+ fail('unclosed <script type="application/ld+json">', start);
381
+ const body = selfClosing ? '' : source.slice(i, end);
382
+ const hole = /^\s*\{\{([\s\S]*)\}\}\s*$/.exec(body);
383
+ const at = i + body.indexOf('{{');
384
+ if (!hole && body.includes('{{'))
385
+ fail('JSON-LD takes static JSON, or one {{ }} hole holding the whole value ({{ { "@type": "Article", headline: title } }})', at);
386
+ const kids = hole ? [{ type: 'expr', expr: hole[1].trim(), start: at, json: true }] : body ? [{ type: 'text', value: body, start: i }] : [];
387
+ nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
388
+ i = selfClosing ? i : end + '</script>'.length;
389
+ }
388
390
  else if (tag === 'script') {
389
391
  if (parent)
390
392
  fail('<script> must be at the top level (a component script); add `inline` for a script that runs where it stands', start);
@@ -397,7 +399,6 @@ export function parse(source, file) {
397
399
  i = end + '</script>'.length;
398
400
  }
399
401
  else if (tag === 'style' && !parent) {
400
- // A top-level <style> is the component's stylesheet. One inside markup (a layout's <head>) stays HTML.
401
402
  const end = source.indexOf('</style>', i);
402
403
  if (end === -1)
403
404
  fail('unclosed <style>', start);
@@ -408,7 +409,6 @@ export function parse(source, file) {
408
409
  i = end + '</style>'.length;
409
410
  }
410
411
  else if (list.some((a) => a.name === 'verbatim')) {
411
- // Everything up to </tag> is text: no holes, tags or directives.
412
412
  const attr = list.find((a) => a.name === 'verbatim');
413
413
  if (attr.kind !== 'static' || attr.value !== true)
414
414
  fail('verbatim takes no value', attr.start);
@@ -442,7 +442,6 @@ export function parse(source, file) {
442
442
  out.nodes = children();
443
443
  return out;
444
444
  }
445
- /** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
446
445
  export function importNames(clause) {
447
446
  if (!clause.startsWith('{'))
448
447
  return [clause];
@@ -1,11 +1,9 @@
1
- // <script> analysis and signal rewrites. Reads `count` → `count.get()`, writes `count++` → `count.set(count.get() + 1)`.
2
1
  import { parse as acornParse, parseExpressionAt } from 'acorn';
3
2
  import { ClarusError } from './errors.js';
4
3
  const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
5
4
  function isNode(v) {
6
5
  return !!v && typeof v.type === 'string' && typeof v.start === 'number';
7
6
  }
8
- // Child slots that hold names, not reads.
9
7
  function isBinding(parent, key) {
10
8
  if (!parent)
11
9
  return false;
@@ -27,7 +25,6 @@ function isBinding(parent, key) {
27
25
  }
28
26
  return false;
29
27
  }
30
- // Print `node` from `code`, replacing any subtree for which `hook` returns a string.
31
28
  function print(node, code, hook, parent = null, key = '') {
32
29
  const replaced = hook(node, parent, key);
33
30
  if (replaced !== undefined)
@@ -47,7 +44,7 @@ function print(node, code, hook, parent = null, key = '') {
47
44
  let pos = node.start;
48
45
  for (const kid of kids) {
49
46
  if (kid.node.start < pos)
50
- continue; // shorthand property: key and value share a range
47
+ continue;
51
48
  out += code.slice(pos, kid.node.start) + print(kid.node, code, hook, node, kid.key);
52
49
  pos = kid.node.end;
53
50
  }
@@ -64,7 +61,6 @@ function parseScript(code, file = '<script>', source = code, offset = 0) {
64
61
  }
65
62
  function parseExpr(expr) {
66
63
  const ast = parseExpressionAt(expr, 0, OPTS);
67
- // acorn drops wrapping parens from the node range: `({ a })` gives a node ending before `)`. Allow exactly those.
68
64
  const open = (expr.slice(0, ast.start).match(/\(/g) ?? []).length;
69
65
  if (!/^[\s(]*$/.test(expr.slice(0, ast.start)) || expr.slice(ast.end).replace(/\s/g, '') !== ')'.repeat(open)) {
70
66
  throw Object.assign(new SyntaxError('expected a single expression'), { pos: ast.end });
@@ -81,18 +77,15 @@ function located(fn, what, file, source, offset) {
81
77
  throw new ClarusError(`${what}: ${e.message.replace(/ \(\d+:\d+\)$/, '')}`, file, source, offset);
82
78
  }
83
79
  }
84
- /** Throw a located ClarusError unless `expr` is exactly one JS expression. */
85
80
  export function checkExpr(expr, file, source, offset) {
86
81
  located(() => parseExpr(expr), 'invalid expression', file, source, offset);
87
82
  }
88
- /** Throw a located ClarusError unless `code` parses as statements (event handlers may hold several). */
89
83
  export function checkHandler(code, file, source, offset) {
90
84
  const ast = located(() => acornParse(code, OPTS), 'invalid event handler', file, source, offset);
91
85
  if (ast.body.some((n) => n.type === 'ImportDeclaration' || n.type.startsWith('Export'))) {
92
86
  throw new ClarusError('imports and exports in event handlers are not supported', file, source, offset);
93
87
  }
94
88
  }
95
- /** Every name bound by a declaration pattern: `a`, `{ a, b: [c] }`, `...rest`, `x = 1`. */
96
89
  function patternNames(p, out = new Set()) {
97
90
  if (!p)
98
91
  return out;
@@ -117,7 +110,6 @@ function patternNames(p, out = new Set()) {
117
110
  }
118
111
  return out;
119
112
  }
120
- /** Names a scope node declares for its own body (params, block-level declarations, loop heads, catch params). */
121
113
  function scopeNames(node) {
122
114
  const names = new Set();
123
115
  const declare = (stmt) => {
@@ -155,7 +147,6 @@ function scopeNames(node) {
155
147
  }
156
148
  return names;
157
149
  }
158
- /** [start, end] ranges of template literals in `code`, so formatting never touches their contents. */
159
150
  export function templateRanges(code) {
160
151
  const ranges = [];
161
152
  print(parseScript(code), code, (node) => {
@@ -165,12 +156,10 @@ export function templateRanges(code) {
165
156
  });
166
157
  return ranges;
167
158
  }
168
- /** Parenthesize expressions whose meaning changes when inlined as an argument or arrow body (`a, b`, `{ … }`). */
169
159
  export function wrapExpr(expr) {
170
160
  const t = parseExpr(expr).type;
171
161
  return t === 'SequenceExpression' || t === 'ObjectExpression' ? `(${expr})` : expr;
172
162
  }
173
- /** Names declared at the top level of <script>: variables, functions, classes. */
174
163
  export function scriptNames(code) {
175
164
  const names = new Set();
176
165
  for (const stmt of parseScript(code).body) {
@@ -194,12 +183,6 @@ function signalCall(init) {
194
183
  const name = init.callee.name;
195
184
  return name === 'state' || name === 'derived' || name === 'shared' ? name : undefined;
196
185
  }
197
- /**
198
- * Take the `import` statements out of a <script> so they can go at the top of the compiled modules. Their text is
199
- * blanked in the body (same length, newlines kept), so positions in the rest of the script don't move.
200
- * Island scripts are bundled for the browser, so `node:` imports are a build error.
201
- */
202
- /** Import statements (text and offset in `code`), and the body with them blanked out. */
203
186
  export function splitImports(code, file, source, offset) {
204
187
  const imports = [];
205
188
  let body = code;
@@ -215,8 +198,6 @@ export function splitImports(code, file, source, offset) {
215
198
  }
216
199
  return { imports, body };
217
200
  }
218
- // Globals that only exist on a server runtime. An island's script also runs in the browser and its state() values
219
- // are written into the page, so reading these would leak server data (or simply fail in the browser).
220
201
  const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
221
202
  export function analyzeScript(code, file, source, offset) {
222
203
  const signals = new Map();
@@ -242,8 +223,6 @@ export function analyzeScript(code, file, source, offset) {
242
223
  }
243
224
  return signals;
244
225
  }
245
- // Scope-aware: a parameter or local that shadows a signal name turns the rewrite off inside that scope.
246
- // ponytail: `var` declared in nested blocks is not hoisted to the function scope here; add if it ever matters
247
226
  function clientHook(code, signals, entered = new WeakSet()) {
248
227
  const hook = (node, parent, key) => {
249
228
  const rec = (n) => print(n, code, hook, node, '');
@@ -263,7 +242,7 @@ function clientHook(code, signals, entered = new WeakSet()) {
263
242
  const name = node.argument.name;
264
243
  const op = node.operator[0];
265
244
  if (parent?.type === 'ExpressionStatement')
266
- return `${name}.set(${name}.get() ${op} 1)`; // value unused
245
+ return `${name}.set(${name}.get() ${op} 1)`;
267
246
  return node.prefix
268
247
  ? `(${name}.set(${name}.get() ${op} 1), ${name}.get())`
269
248
  : `((__cl_v) => (${name}.set(__cl_v ${op} 1), __cl_v))(${name}.get())`;
@@ -284,10 +263,6 @@ function clientHook(code, signals, entered = new WeakSet()) {
284
263
  };
285
264
  return hook;
286
265
  }
287
- /**
288
- * Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
289
- * starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
290
- */
291
266
  export function rewriteClient(code, signals, options = {}) {
292
267
  const ast = parseScript(code);
293
268
  const hook = clientHook(code, signals);
@@ -295,7 +270,6 @@ export function rewriteClient(code, signals, options = {}) {
295
270
  return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
296
271
  const topLevel = new Set(ast.body.filter((n) => n.type === 'VariableDeclaration').flatMap((n) => n.declarations));
297
272
  const withState = (node, parent, key) => {
298
- // `let x = state()` becomes `const x = …`; re-print with this hook so the declarators below still see it.
299
273
  if (node.type === 'VariableDeclaration' && node.kind === 'let' && node.declarations.every((d) => signalCall(d.init))) {
300
274
  return 'const' + print({ ...node, kind: 'const', start: node.start + 3 }, code, withState, parent, key);
301
275
  }
@@ -323,8 +297,6 @@ export function rewriteServer(code) {
323
297
  return `(${inner})`;
324
298
  if (node.callee.name === 'derived')
325
299
  return `(${inner})()`;
326
- // A store's current value lives across requests on the server; render from its initial value instead, and from
327
- // a copy, so a render that mutates it can't change what the next request sees.
328
300
  if (node.callee.name === 'shared')
329
301
  return `structuredClone((${inner}).initial)`;
330
302
  return undefined;
@@ -334,7 +306,6 @@ export function rewriteServer(code) {
334
306
  export function referencesSignal(expr, signals) {
335
307
  return referencesNames(expr, new Set(signals.keys()));
336
308
  }
337
- /** Does `expr` read any of `names`? */
338
309
  export function referencesNames(expr, names) {
339
310
  let found = false;
340
311
  print(parseExpr(expr), expr, (node, parent, key) => {
@@ -1,12 +1,10 @@
1
1
  import { templateRanges } from './script.js';
2
- /** `const { start = 0, name } = props`, or '' when the component has no inputs. */
3
2
  export function inputsLine(ir) {
4
3
  if (!ir.inputs.length)
5
4
  return '';
6
5
  const parts = ir.inputs.map((i) => (i.default !== undefined ? `${i.name} = ${i.default}` : i.name));
7
6
  return ` const { ${parts.join(', ')} } = __cl_props\n`;
8
7
  }
9
- /** Dedent a script block and indent it by two spaces, one statement line per line. */
10
8
  export function indentScript(code) {
11
9
  const body = code.replace(/^\s*\n/, '').replace(/\s+$/, '');
12
10
  const ranges = templateRanges(body);
@@ -14,13 +12,10 @@ export function indentScript(code) {
14
12
  const lines = body.split('\n').map((text) => {
15
13
  const start = offset;
16
14
  offset += text.length + 1;
17
- // A line that starts inside a template literal is string content: never re-indent it.
18
15
  return { text, literal: ranges.some(([a, b]) => start > a && start < b) };
19
16
  });
20
17
  const code_ = lines.filter((l) => !l.literal && l.text.trim());
21
18
  const indent = Math.min(...code_.map((l) => l.text.match(/^\s*/)[0].length));
22
19
  return lines.map((l) => (l.literal ? l.text : ' ' + l.text.slice(indent))).join('\n') + '\n';
23
20
  }
24
- // Generated names carry a __cl_ prefix so they can't collide with names in the author's <script>.
25
- // `-` maps to `$`, which import names cannot contain after the first character, so the mapping is one-to-one.
26
21
  export const renderName = (name) => '__cl_render_' + name.replace(/-/g, '$');
@@ -46,24 +46,29 @@ isCurrent = () => true) {
46
46
  }
47
47
  document.title = doc.title;
48
48
  old.replaceWith(next);
49
- globalThis.__clAttach?.(next);
49
+ globalThis.__clAttach?.(next, 1); // 1: navigated (bytes)
50
50
  }
51
51
  const navigation = typeof document !== 'undefined' ? globalThis.navigation : undefined;
52
52
  // Only the latest navigation may change the document; a URL that failed loads normally, never intercepted again
53
53
  // (the reload of a failed URL is itself a navigation to it, which the fallback check lets through).
54
54
  let latest = 0;
55
55
  let fallback = '';
56
+ let swapping = false;
56
57
  navigation?.addEventListener('navigate', (event) => {
57
58
  const e = event;
58
- if (!e.canIntercept || e.hashChange || e.downloadRequest !== null || e.formData)
59
+ // A #hash, and the page's own history.pushState/replaceState (same-document, not back/forward), are never a page
60
+ // load, except while a swap is still loading: they abort it, so this navigation has to show the new page instead.
61
+ if (!e.canIntercept || e.hashChange || (e.destination.sameDocument && e.navigationType !== 'traverse' && !swapping) || e.downloadRequest !== null || e.formData)
59
62
  return;
60
63
  const url = new URL(e.destination.url);
61
64
  if (url.href === fallback)
62
65
  return;
63
66
  const id = ++latest;
64
67
  const isCurrent = () => latest === id && !e.signal.aborted;
68
+ swapping = true;
65
69
  e.intercept({
66
- handler: () => swap(url, fetch, isCurrent).catch(() => {
70
+ handler: () => swap(url, fetch, isCurrent).finally(() => { if (latest === id)
71
+ swapping = false; }).catch(() => {
67
72
  if (!isCurrent())
68
73
  return;
69
74
  fallback = url.href;
@@ -1,5 +1,7 @@
1
1
  /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
2
2
  export declare function escape(value: unknown): string;
3
+ /** A value as JSON for a <script> (JSON-LD): <, >, & and line separators escaped, so it can't end the script. */
4
+ export declare function json(value: unknown): string;
3
5
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
4
6
  export declare function attrHtml(name: string, value: unknown, tag?: string): string;
5
7
  /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. */
@@ -7,6 +7,10 @@ export function escape(value) {
7
7
  return '';
8
8
  return String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
9
9
  }
10
+ /** A value as JSON for a <script> (JSON-LD): <, >, & and line separators escaped, so it can't end the script. */
11
+ export function json(value) {
12
+ return (JSON.stringify(value) ?? 'null').replace(/[<>&\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);
13
+ }
10
14
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
11
15
  export function attrHtml(name, value, tag) {
12
16
  const v = attrValue(name, value, tag);
@@ -143,9 +143,46 @@ export async function attachAll(root = document, load = lastLoad) {
143
143
  }
144
144
  await Promise.all(now);
145
145
  }
146
- // Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook.
146
+ /**
147
+ * After a navigation (fragment swap or client render): focus moves to the new content, the #hash target, else the
148
+ * page's <h1>, else <main>, so keyboard and screen reader users start there; and the new title is announced in a
149
+ * polite live region. Done here rather than in the router and navigation scripts, which stay within 1 KB.
150
+ */
151
+ function arrive() {
152
+ let id = '';
153
+ try {
154
+ id = decodeURIComponent(location.hash.slice(1));
155
+ }
156
+ catch { }
157
+ // In this order: a selector list would return the first match in the document, such as a heading in the header.
158
+ const target = (id && document.getElementById(id)) || document.querySelector('main h1') || document.querySelector('h1') || document.querySelector('main');
159
+ if (target instanceof HTMLElement) {
160
+ // Not natively focusable (a heading, <main>, an <a> without href, whose tabIndex still reads 0): tabindex -1.
161
+ if (!target.matches('a[href],area[href],button,input,select,textarea,iframe,summary,[tabindex],[contenteditable]'))
162
+ target.setAttribute('tabindex', '-1');
163
+ target.focus();
164
+ }
165
+ let live = document.getElementById('cl-live');
166
+ if (!live) {
167
+ live = document.createElement('p');
168
+ live.id = 'cl-live';
169
+ live.setAttribute('aria-live', 'polite');
170
+ live.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap';
171
+ document.body.append(live);
172
+ }
173
+ // Set after a moment: a region that was just created (the router replaces <body>) must exist before it changes.
174
+ const region = live;
175
+ region.textContent = '';
176
+ setTimeout(() => { region.textContent = document.title; }, 50);
177
+ }
178
+ // Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook. The router
179
+ // and fragment navigation pass navigated = true after replacing the page.
147
180
  ;
148
- globalThis.__clAttach = (root) => void attachAll(root);
181
+ globalThis.__clAttach = (root, navigated) => {
182
+ void attachAll(root);
183
+ if (navigated)
184
+ arrive();
185
+ };
149
186
  if (typeof document !== 'undefined') {
150
187
  // Islands never affect layout. Installed on the document (not in <head>), so it survives head swaps by the client
151
188
  // router; the server also writes it as a <style> for the first paint.
@@ -11,5 +11,5 @@ export declare function matchRoute(table: Entry[], pathname: string): {
11
11
  params: Record<string, string>;
12
12
  } | null;
13
13
  /** Render the client route at `url` into the document. False when `url` is not a client route. */
14
- export declare function show(url: URL, table: Entry[], load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>, isCurrent?: () => boolean): Promise<boolean>;
14
+ export declare function show(url: URL, table: Entry[], isCurrent?: () => boolean, load?: (src: string) => Promise<Page>, get?: (url: string) => Promise<Response>): Promise<boolean>;
15
15
  export {};
@@ -34,9 +34,9 @@ export function matchRoute(table, pathname) {
34
34
  return null;
35
35
  }
36
36
  /** Render the client route at `url` into the document. False when `url` is not a client route. */
37
- export async function show(url, table, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src)), get = fetch,
37
+ export async function show(url, table,
38
38
  // False once a newer navigation has started: then this one must not touch the document.
39
- isCurrent = () => true) {
39
+ isCurrent = () => true, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src)), get = fetch) {
40
40
  const found = matchRoute(table, url.pathname);
41
41
  if (!found)
42
42
  return false;
@@ -54,7 +54,8 @@ isCurrent = () => true) {
54
54
  const doc = new DOMParser().parseFromString(page.render(props), 'text/html');
55
55
  // The head stays (its stylesheets are every client page's, linked by the shell); the title and the page's own
56
56
  // <html> attributes (lang, dir, …) are the new page's.
57
- document.title = doc.title;
57
+ // The site's titleTemplate, from the shell (always set: '%s' without one).
58
+ document.title = document.getElementById('cl-routes').dataset.title.replace('%s', () => doc.title);
58
59
  const root = document.documentElement;
59
60
  for (const { name } of [...root.attributes])
60
61
  root.removeAttribute(name);
@@ -70,15 +71,15 @@ isCurrent = () => true) {
70
71
  }
71
72
  // Attaches the new page's islands; the loader also releases the old page's.
72
73
  ;
73
- globalThis.__clAttach?.(document.body);
74
+ globalThis.__clAttach?.(document.body, 1); // 1: navigated (bytes)
74
75
  return true;
75
76
  }
76
- const routes = typeof document !== 'undefined' ? document.getElementById('cl-routes') : null;
77
+ const routes = globalThis.document?.getElementById('cl-routes');
77
78
  if (routes) {
78
- const table = JSON.parse(routes.textContent ?? '[]');
79
+ const table = JSON.parse(routes.textContent);
79
80
  // Each navigation gets a number; only the latest may change the document or fall back.
80
81
  let latest = 1; // the first render is navigation 1
81
- show(new URL(location.href), table, undefined, undefined, () => latest === 1).catch((err) => {
82
+ show(new URL(location.href), table, () => latest === 1).catch((err) => {
82
83
  if (latest !== 1)
83
84
  return;
84
85
  document.body.textContent = err.message.startsWith('404') ? 'Page not found.' : 'Could not load page.';
@@ -97,7 +98,7 @@ if (routes) {
97
98
  const id = ++latest;
98
99
  const isCurrent = () => latest === id && !e.signal.aborted;
99
100
  e.intercept({
100
- handler: () => show(url, table, undefined, undefined, isCurrent).then(() => { }, () => {
101
+ handler: () => show(url, table, isCurrent).then(() => { }, () => {
101
102
  if (!isCurrent())
102
103
  return;
103
104
  fallback = url.href;
@@ -1,5 +1,5 @@
1
1
  import { attrHtml } from './html.ts';
2
- export { escape, blockHtml, forHtml, regionHtml } from './html.ts';
2
+ export { escape, json, blockHtml, forHtml, regionHtml } from './html.ts';
3
3
  /**
4
4
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
5
5
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
@@ -1,7 +1,7 @@
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 } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
- export { escape, blockHtml, forHtml, regionHtml } from './html.js';
4
+ export { escape, json, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  /**
6
6
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
7
7
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
@@ -1,4 +1,5 @@
1
1
  import { type ModeTable } from './modes.ts';
2
+ import { type HeadOptions, type SiteOptions } from './head.ts';
2
3
  type PageModule = {
3
4
  render(props?: object): string;
4
5
  };
@@ -33,6 +34,10 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
33
34
  stylesUrl?: string;
34
35
  /** Stylesheets each page imports (directly or through its components), by route as its file names it. */
35
36
  css?: Record<string, string[]>;
37
+ /** Title template, site-wide head tags and a transform (see head.ts). */
38
+ head?: HeadOptions;
39
+ /** The site's public address: canonical URLs and social cards (see head.ts). */
40
+ site?: SiteOptions;
36
41
  }): {
37
42
  fetch(request: Request): Promise<Response>;
38
43
  routes: string[];
@@ -46,4 +51,9 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
46
51
  * its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
47
52
  */
48
53
  export declare function toFragment(html: string): string;
54
+ /**
55
+ * The 404 page is served at any depth (/a/b/c), so its relative links (href, src) are resolved from the site root:
56
+ * 'guide' means <base>guide wherever the visitor is.
57
+ */
58
+ export declare function rootLinks(html: string, base: string): string;
49
59
  export {};