clarusjs 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/check/generate.d.ts +6 -0
  2. package/dist/check/generate.js +12 -22
  3. package/dist/cli/check.js +58 -15
  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.js +10 -8
  11. package/dist/compiler/ir.d.ts +1 -0
  12. package/dist/compiler/ir.js +9 -14
  13. package/dist/compiler/parse.d.ts +1 -0
  14. package/dist/compiler/parse.js +18 -19
  15. package/dist/compiler/script.js +2 -31
  16. package/dist/compiler/shared.js +0 -5
  17. package/dist/runtime/dom.js +4 -1
  18. package/dist/runtime/fragments.d.ts +1 -1
  19. package/dist/runtime/fragments.js +10 -30
  20. package/dist/runtime/html.d.ts +2 -0
  21. package/dist/runtime/html.js +4 -0
  22. package/dist/runtime/loader.js +41 -2
  23. package/dist/runtime/navigate.d.ts +38 -0
  24. package/dist/runtime/navigate.js +88 -0
  25. package/dist/runtime/navigation.d.ts +88 -0
  26. package/dist/runtime/navigation.js +165 -0
  27. package/dist/runtime/router.d.ts +8 -1
  28. package/dist/runtime/router.js +32 -42
  29. package/dist/runtime/server.d.ts +1 -1
  30. package/dist/runtime/server.js +1 -1
  31. package/dist/server/handler.d.ts +18 -0
  32. package/dist/server/handler.js +80 -53
  33. package/dist/server/head.d.ts +36 -0
  34. package/dist/server/head.js +129 -0
  35. package/dist/server/manifest.js +0 -3
  36. package/dist/server/modes.js +0 -5
  37. package/dist/server/views.js +0 -7
  38. package/dist/vite/aliases.d.ts +10 -0
  39. package/dist/vite/aliases.js +42 -0
  40. package/dist/vite/build.d.ts +9 -0
  41. package/dist/vite/build.js +43 -17
  42. package/dist/vite/links.d.ts +2 -0
  43. package/dist/vite/links.js +11 -10
  44. package/dist/vite/manifest.js +2 -10
  45. package/dist/vite/netlify.js +1 -7
  46. package/dist/vite/plugin.d.ts +35 -0
  47. package/dist/vite/plugin.js +162 -88
  48. package/dist/vite/redirects.d.ts +10 -0
  49. package/dist/vite/redirects.js +41 -0
  50. package/dist/vite/sitemap.d.ts +11 -0
  51. package/dist/vite/sitemap.js +31 -0
  52. package/package.json +18 -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, '$');
@@ -188,7 +188,10 @@ export function forBlock(ctx, index, list, keyOf, row, empty) {
188
188
  const keys = items.map((item, i) => {
189
189
  let key = keyOf(item, i);
190
190
  if (seen.has(key)) {
191
- console.warn(`[clarusjs] @for: duplicate key ${String(key)}; rows with repeated keys are matched by position`);
191
+ // Development only: Vite replaces import.meta.env.DEV, so a production build drops it (no ImportMeta
192
+ // declaration needed: consumers of this source typecheck without one).
193
+ if (import.meta.env?.DEV)
194
+ console.warn(`[clarusjs] @for: duplicate key ${String(key)}; rows with repeated keys are matched by position`);
192
195
  key = `${String(key)}\u0000${i}`;
193
196
  }
194
197
  seen.add(key);
@@ -2,4 +2,4 @@ import './loader.ts';
2
2
  /** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
3
3
  export declare function fragmentUrl(url: URL): string;
4
4
  /** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
5
- export declare function swap(url: URL, get?: (url: string) => Promise<Response>, isCurrent?: () => boolean): Promise<void>;
5
+ export declare function swap(url: URL, get?: (url: string) => Promise<Response>, isCurrent?: () => Promise<boolean> | boolean): Promise<void>;
@@ -2,6 +2,7 @@
2
2
  // instead of reloading. Browser only. Each page's fragment is <path>/index.frag.html; elements marked
3
3
  // data-cl-persist="key" are kept across swaps, and the island loader attaches whatever islands arrive.
4
4
  import './loader.js';
5
+ import { takeOver } from './navigate.js';
5
6
  /** '/guide/lists/' → '/guide/lists/index.frag.html', keeping the query. */
6
7
  export function fragmentUrl(url) {
7
8
  return `${url.pathname.replace(/\/+$/, '')}/index.frag.html${url.search}`;
@@ -9,15 +10,15 @@ export function fragmentUrl(url) {
9
10
  const region = (doc) => doc.querySelector('[data-cl-swap]') ?? doc.body;
10
11
  /** Fetch the page's fragment and swap it in. Throws when there is none (the caller then loads the page normally). */
11
12
  export async function swap(url, get = fetch,
12
- // False once a newer navigation has started: then this one must not touch the document.
13
+ // Awaited right before the swap (where the in-between hooks run): false once a newer navigation has started,
14
+ // then this one must not touch the document.
13
15
  isCurrent = () => true) {
14
16
  const src = fragmentUrl(url);
15
17
  const res = await get(src);
16
- if (!res.ok)
18
+ // Redirected: the page moved, and the address bar would keep the old URL. Failing loads the page normally.
19
+ if (!res.ok || res.redirected)
17
20
  throw new Error(`${res.status}: ${src}`);
18
21
  const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
19
- if (!isCurrent())
20
- return;
21
22
  const next = region(doc);
22
23
  const old = region(document);
23
24
  // A body can only replace a body, and a marked region a marked region: otherwise load the page normally.
@@ -38,7 +39,7 @@ isCurrent = () => true) {
38
39
  document.head.append(added);
39
40
  }
40
41
  await Promise.all(loading);
41
- if (!isCurrent())
42
+ if (!(await isCurrent()))
42
43
  return;
43
44
  // Persisted elements move into the new page as they are, with their state and attached islands.
44
45
  for (const old of document.querySelectorAll('[data-cl-persist]')) {
@@ -46,29 +47,8 @@ isCurrent = () => true) {
46
47
  }
47
48
  document.title = doc.title;
48
49
  old.replaceWith(next);
49
- globalThis.__clAttach?.(next);
50
+ // Attaches the new islands; the loader also releases those that left with the old region.
51
+ await globalThis.__clAttach?.(next, 1); // 1: navigated (bytes)
50
52
  }
51
- const navigation = typeof document !== 'undefined' ? globalThis.navigation : undefined;
52
- // Only the latest navigation may change the document; a URL that failed loads normally, never intercepted again
53
- // (the reload of a failed URL is itself a navigation to it, which the fallback check lets through).
54
- let latest = 0;
55
- let fallback = '';
56
- navigation?.addEventListener('navigate', (event) => {
57
- const e = event;
58
- if (!e.canIntercept || e.hashChange || e.downloadRequest !== null || e.formData)
59
- return;
60
- const url = new URL(e.destination.url);
61
- if (url.href === fallback)
62
- return;
63
- const id = ++latest;
64
- const isCurrent = () => latest === id && !e.signal.aborted;
65
- e.intercept({
66
- handler: () => swap(url, fetch, isCurrent).catch(() => {
67
- if (!isCurrent())
68
- return;
69
- fallback = url.href;
70
- // The URL is already committed: reload it (assign() would only move within the page when it has a #hash).
71
- location.reload();
72
- }),
73
- });
74
- });
53
+ // Every navigation the shared guard takes over.
54
+ takeOver(() => (url, isCurrent, signal) => swap(url, (src) => fetch(src, { signal }), isCurrent));
@@ -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,48 @@ 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, and wait for the returned promise: the
180
+ // islands that attach right away are attached before afterSwap and afterNavigate run.
147
181
  ;
148
- globalThis.__clAttach = (root) => void attachAll(root);
182
+ globalThis.__clAttach = (root, navigated) => {
183
+ const done = attachAll(root);
184
+ if (navigated)
185
+ arrive();
186
+ return done;
187
+ };
149
188
  if (typeof document !== 'undefined') {
150
189
  // Islands never affect layout. Installed on the document (not in <head>), so it survives head swaps by the client
151
190
  // router; the server also writes it as a <style> for the first paint.
@@ -0,0 +1,38 @@
1
+ /** `gate()` is awaited right before the page changes the document: false means stop (a newer navigation won). */
2
+ /** `signal`: aborts when the navigation does (pass it to the page's requests). */
3
+ export type Render = (url: URL, gate: () => Promise<boolean> | boolean, signal?: AbortSignal) => Promise<unknown>;
4
+ /** A navigation in progress, as the in-between hooks and the navigating store see it. */
5
+ export type Transition = {
6
+ from: URL;
7
+ to: URL;
8
+ type: string;
9
+ phase: 'loading' | 'swapping';
10
+ signal: AbortSignal;
11
+ };
12
+ type Pick = (url: URL) => Render | false | null | undefined;
13
+ type NavigateEvent = {
14
+ canIntercept: boolean;
15
+ hashChange: boolean;
16
+ downloadRequest: string | null;
17
+ formData: FormData | null;
18
+ destination: {
19
+ url: string;
20
+ sameDocument: boolean;
21
+ };
22
+ navigationType: string;
23
+ signal: AbortSignal;
24
+ intercept(options: {
25
+ handler(): Promise<void>;
26
+ precommitHandler?(): Promise<void>;
27
+ }): void;
28
+ };
29
+ /** The number of the latest navigation taken over (0 before any): only that one may change the document. */
30
+ export declare let latest: number;
31
+ /**
32
+ * Take over the navigations `pick` wants. A page loads one navigator (the router or fragments), so one picker.
33
+ * @see https://clarusjs.com/guide/client-routes
34
+ * @see https://clarusjs.com/guide/fragment-navigation
35
+ */
36
+ export declare function takeOver(pick: Pick): void;
37
+ export declare function onNavigate(e: NavigateEvent, pick: Pick): void;
38
+ export {};
@@ -0,0 +1,88 @@
1
+ // Which navigations clarusjs takes over, in one place for the fragment navigator and the client router. Browser
2
+ // only. Each passes a picker: given the URL, it returns how to render that page, or nothing to leave it alone.
3
+ /** The number of the latest navigation taken over (0 before any): only that one may change the document. */
4
+ export let latest = 0;
5
+ // A URL that failed to render loads normally, never taken over again (its reload is itself a navigation to it).
6
+ let fallback = '';
7
+ let swapping = false;
8
+ // The URL a held navigation is loading (not committed yet).
9
+ let held = '';
10
+ /**
11
+ * Take over the navigations `pick` wants. A page loads one navigator (the router or fragments), so one picker.
12
+ * @see https://clarusjs.com/guide/client-routes
13
+ * @see https://clarusjs.com/guide/fragment-navigation
14
+ */
15
+ export function takeOver(pick) {
16
+ ;
17
+ globalThis.navigation?.addEventListener('navigate', (e) => onNavigate(e, pick));
18
+ }
19
+ export function onNavigate(e, pick) {
20
+ // A #hash, and the page's own history.pushState/replaceState (same-document push or replace), are never a page
21
+ // load, except while a swap runs after its URL changed: they abort it, so this navigation shows the new page.
22
+ if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
23
+ return;
24
+ // Push and replace (same-document ones too: never reloads; back/forward is a traverse).
25
+ const hold = /^(p|rep)/.test(e.navigationType);
26
+ if (e.destination.sameDocument && hold && !swapping) {
27
+ // The page's own history change aborts a navigation whose URL is held: it goes on to its page right after.
28
+ if (held)
29
+ setTimeout(navigation.navigate.bind(navigation, held)); // it fired this event
30
+ return;
31
+ }
32
+ const url = new URL(e.destination.url);
33
+ const render = url.href != fallback && pick(url);
34
+ if (!render)
35
+ return;
36
+ const id = ++latest;
37
+ const isCurrent = () => latest == id && !e.signal.aborted;
38
+ const t = { from: new URL(location.href), to: url, type: e.navigationType, phase: 'loading', signal: e.signal };
39
+ const data = document.documentElement.dataset;
40
+ // Each step: on <html data-cl-navigating> (for CSS), then to clarusjs/navigation when an island loaded it.
41
+ const step = async (s) => {
42
+ if (s != 'swapped')
43
+ s ? (data.clNavigating = t.phase = s) : delete data.clNavigating;
44
+ await globalThis.__clNav?.(s, t);
45
+ };
46
+ step('loading');
47
+ // Push and replace hold the URL while the page loads, where the browser can (precommitHandler; others ignore it and
48
+ // only run handler): it changes once the page is ready to swap in, so an abort before that leaves page and URL as
49
+ // they were. Back/forward and reloads change it at once. Until its URL changes, a held navigation leaves the page's
50
+ // own history changes alone (see above).
51
+ swapping = !hold;
52
+ held = hold ? url.href : '';
53
+ let ready;
54
+ let commit;
55
+ const atGate = new Promise((r) => (ready = r));
56
+ const onCommit = new Promise((r) => (commit = () => { swapping = true; held = ''; r(); }));
57
+ let running;
58
+ // Ends this attempt (unless a newer one started): also when it is cancelled before its handlers ever run. `held`
59
+ // clears a task later: a page's own history change aborts this attempt just before its event reaches us, and still
60
+ // has to find it (see above).
61
+ const end = () => { if (latest == id) {
62
+ swapping = false;
63
+ step();
64
+ setTimeout(() => latest == id && (held = ''));
65
+ } };
66
+ e.signal.onabort = end;
67
+ const work = () => (running = render(url, async () => {
68
+ if (!isCurrent())
69
+ return false;
70
+ ready();
71
+ await onCommit;
72
+ await step('swapping');
73
+ return isCurrent();
74
+ }, e.signal).then(() => isCurrent() && step('swapped')).catch((err) => {
75
+ if (!isCurrent())
76
+ return;
77
+ fallback = url.href;
78
+ // Loaded normally: a reload once the URL changed (assign() would only move within the page with a #hash), else
79
+ // the new URL. After the failure is reported, so starting that load doesn't turn it into a cancellation.
80
+ setTimeout(() => (location.href == url.href ? location.reload() : location.assign(url.href)));
81
+ throw err; // reported as navigateerror (onNavigateError)
82
+ }).finally(end));
83
+ e.intercept({
84
+ // Resolves when the page is ready to swap in; rejects with a failure before that (reported, URL unchanged).
85
+ precommitHandler: hold ? () => Promise.race([atGate, work()]) : undefined,
86
+ handler: () => (commit(), running ?? work()),
87
+ });
88
+ }