clarusjs 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +2 -0
  2. package/dist/check/generate.js +1 -21
  3. package/dist/cli/check.js +44 -11
  4. package/dist/cli/explain.js +0 -1
  5. package/dist/cli/index.js +0 -1
  6. package/dist/compiler/emit-client.js +1 -11
  7. package/dist/compiler/emit-server.js +1 -2
  8. package/dist/compiler/errors.js +0 -1
  9. package/dist/compiler/html-expr.js +2 -7
  10. package/dist/compiler/index.d.ts +6 -0
  11. package/dist/compiler/index.js +45 -4
  12. package/dist/compiler/ir.d.ts +1 -0
  13. package/dist/compiler/ir.js +9 -14
  14. package/dist/compiler/parse.d.ts +10 -0
  15. package/dist/compiler/parse.js +48 -20
  16. package/dist/compiler/script.js +2 -31
  17. package/dist/compiler/shared.js +0 -5
  18. package/dist/runtime/fragments.js +23 -3
  19. package/dist/runtime/html.d.ts +2 -0
  20. package/dist/runtime/html.js +4 -0
  21. package/dist/runtime/loader.js +46 -3
  22. package/dist/runtime/router.d.ts +1 -1
  23. package/dist/runtime/router.js +23 -15
  24. package/dist/runtime/server.d.ts +1 -1
  25. package/dist/runtime/server.js +1 -1
  26. package/dist/server/handler.d.ts +15 -1
  27. package/dist/server/handler.js +61 -52
  28. package/dist/server/head.d.ts +36 -0
  29. package/dist/server/head.js +129 -0
  30. package/dist/server/manifest.js +0 -3
  31. package/dist/server/modes.js +0 -5
  32. package/dist/server/views.js +1 -8
  33. package/dist/vite/build.d.ts +10 -2
  34. package/dist/vite/build.js +44 -19
  35. package/dist/vite/links.d.ts +20 -0
  36. package/dist/vite/links.js +94 -0
  37. package/dist/vite/manifest.js +2 -10
  38. package/dist/vite/netlify.js +1 -7
  39. package/dist/vite/plugin.d.ts +55 -0
  40. package/dist/vite/plugin.js +282 -82
  41. package/dist/vite/sitemap.d.ts +11 -0
  42. package/dist/vite/sitemap.js +31 -0
  43. package/package.json +5 -3
@@ -1,12 +1,12 @@
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;
5
4
  const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
6
5
  const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
7
6
  const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
7
+ const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
8
8
  export function parse(source, file) {
9
- const out = { inputs: [], imports: [], typeImports: [], dataImports: [], nodes: [] };
9
+ const out = { inputs: [], imports: [], typeImports: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
10
10
  let i = 0;
11
11
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
12
12
  const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
@@ -26,12 +26,16 @@ export function parse(source, file) {
26
26
  out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
27
27
  }
28
28
  else if ((m = line.match(IMPORT_RE))) {
29
- // A default import of a .tscl file is a component; of anything else, data.
30
29
  if (m[3].endsWith('.tscl'))
31
30
  out.imports.push({ name: m[1], from: m[3], start: i });
32
31
  else
33
32
  out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + line.indexOf(m[1], 7) });
34
33
  }
34
+ else if ((m = CSS_IMPORT_RE.exec(line))) {
35
+ if (!/\.css(\?|$)/.test(m[2]))
36
+ fail(`@import without a name only takes a stylesheet (.css): "${m[2]}"`, i);
37
+ out.cssImports.push({ from: m[2], start: i });
38
+ }
35
39
  else
36
40
  fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
37
41
  i = end;
@@ -70,7 +74,6 @@ export function parse(source, file) {
70
74
  }
71
75
  else {
72
76
  if (typeof value === 'string' && value.includes('{{')) {
73
- // Split into literal text and {{ expr }} parts; valueStart is the offset of the value's first character.
74
77
  const valueStart = start + name.length + 2;
75
78
  const parts = [];
76
79
  let at = 0;
@@ -96,8 +99,6 @@ export function parse(source, file) {
96
99
  }
97
100
  }
98
101
  }
99
- // Find the `}}` that closes a hole, skipping strings, template literals and nested brackets.
100
- // ponytail: regex literals containing quotes or braces are not recognised; tokenise with acorn if that ever bites
101
102
  function holeEnd(from) {
102
103
  const stack = [];
103
104
  for (let j = from; j < source.length; j++) {
@@ -133,8 +134,6 @@ export function parse(source, file) {
133
134
  }
134
135
  return -1;
135
136
  }
136
- // Parse children until `</parent>` (or end of input at top level).
137
- // A parenthesised JS condition after `@if` / `@else if`, skipping strings and nested parentheses.
138
137
  function condition(keyword) {
139
138
  while (/\s/.test(source[i] ?? ''))
140
139
  i++;
@@ -158,7 +157,6 @@ export function parse(source, file) {
158
157
  }
159
158
  return fail(`unclosed ( after ${keyword}`, open);
160
159
  }
161
- // @if (a) { … } @else if (b) { … } @else { … }
162
160
  function ifBlock() {
163
161
  const start = i;
164
162
  i += 3;
@@ -172,7 +170,7 @@ export function parse(source, file) {
172
170
  i++;
173
171
  branches.push({ ...next, children: children({ tag: '@if', start, block: true }) });
174
172
  if (next.cond === null)
175
- break; // @else is last
173
+ break;
176
174
  const save = i;
177
175
  while (/\s/.test(source[i] ?? ''))
178
176
  i++;
@@ -192,8 +190,6 @@ export function parse(source, file) {
192
190
  }
193
191
  return { type: 'if', branches, start };
194
192
  }
195
- // Split at top-level ';' (outside strings and brackets).
196
- /** Top-level `;` clauses, trimmed, each with its offset in `text`. */
197
193
  function splitClauses(text) {
198
194
  const parts = [];
199
195
  const push = (from, to) => {
@@ -222,12 +218,10 @@ export function parse(source, file) {
222
218
  push(from, text.length);
223
219
  return parts;
224
220
  }
225
- // @for (item of list; track key) { … } @empty { … }
226
221
  function forBlock() {
227
222
  const start = i;
228
223
  i += 4;
229
224
  const { cond: head, condStart: headStart } = condition('@for');
230
- // Where `head` (trimmed) starts in the source, so every part below gets its exact offset.
231
225
  let at = headStart;
232
226
  while (/\s/.test(source[at] ?? ''))
233
227
  at++;
@@ -271,7 +265,6 @@ export function parse(source, file) {
271
265
  i = save;
272
266
  return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, children: body, empty, start };
273
267
  }
274
- // @slot('name') { … }: content for a component's named slot.
275
268
  function fillBlock() {
276
269
  const start = i;
277
270
  i += 5;
@@ -308,7 +301,7 @@ export function parse(source, file) {
308
301
  const end = source.indexOf('-->', i + 4);
309
302
  if (end === -1)
310
303
  fail('unclosed <!-- comment', i);
311
- text += source.slice(i, end + 3); // kept verbatim as static text: no tags, no holes inside
304
+ text += source.slice(i, end + 3);
312
305
  i = end + 3;
313
306
  }
314
307
  else if (/^@if[\s(]/.test(source.slice(i, i + 4))) {
@@ -367,9 +360,36 @@ export function parse(source, file) {
367
360
  fail(`unclosed <${tag}>`, start);
368
361
  const selfClosing = source.startsWith('/>', i);
369
362
  i += selfClosing ? 2 : 1;
370
- if (tag === 'script') {
363
+ if (tag === 'script' && list.some((a) => a.name === 'inline')) {
364
+ const bound = list.find((a) => a.kind !== 'static');
365
+ if (bound)
366
+ fail('an inline script takes static attributes only', bound.start);
367
+ const end = source.indexOf('</script>', i);
368
+ if (end === -1)
369
+ fail('unclosed <script inline>', start);
370
+ const kids = selfClosing ? [] : [{ type: 'text', value: source.slice(i, end), start: i }];
371
+ nodes.push({ type: 'element', tag, attrs: list.filter((a) => a.name !== 'inline'), children: kids, start });
372
+ i = selfClosing ? i : end + '</script>'.length;
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
+ }
390
+ else if (tag === 'script') {
371
391
  if (parent)
372
- fail('<script> must be at the top level', start);
392
+ fail('<script> must be at the top level (a component script); add `inline` for a script that runs where it stands', start);
373
393
  if (out.script)
374
394
  fail('only one <script> block is allowed', start);
375
395
  const end = source.indexOf('</script>', i);
@@ -378,8 +398,17 @@ export function parse(source, file) {
378
398
  out.script = { code: source.slice(i, end), start: i };
379
399
  i = end + '</script>'.length;
380
400
  }
401
+ else if (tag === 'style' && !parent) {
402
+ const end = source.indexOf('</style>', i);
403
+ if (end === -1)
404
+ fail('unclosed <style>', start);
405
+ const hole = source.slice(i, end).indexOf('{{');
406
+ if (hole !== -1)
407
+ fail('{{ }} holes are not supported in a component <style>: set a CSS custom property from the template instead (style="--x: {{ x }}")', i + hole);
408
+ out.styles.push({ css: source.slice(i, end), global: list.some((a) => a.name === 'global'), start: i });
409
+ i = end + '</style>'.length;
410
+ }
381
411
  else if (list.some((a) => a.name === 'verbatim')) {
382
- // Everything up to </tag> is text: no holes, tags or directives.
383
412
  const attr = list.find((a) => a.name === 'verbatim');
384
413
  if (attr.kind !== 'static' || attr.value !== true)
385
414
  fail('verbatim takes no value', attr.start);
@@ -413,7 +442,6 @@ export function parse(source, file) {
413
442
  out.nodes = children();
414
443
  return out;
415
444
  }
416
- /** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
417
445
  export function importNames(clause) {
418
446
  if (!clause.startsWith('{'))
419
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, '$');
@@ -25,30 +25,50 @@ isCurrent = () => true) {
25
25
  throw new Error('different swap regions');
26
26
  for (const title of next.querySelectorAll('title'))
27
27
  title.remove(); // some parsers leave the leading <title> in the body
28
+ // The page's stylesheets: add the ones not loaded yet to <head>, and wait for them, so nothing shows unstyled.
29
+ const loading = [];
30
+ for (const link of doc.querySelectorAll('link[rel="stylesheet"]')) {
31
+ link.remove();
32
+ if (document.head.querySelector(`link[rel="stylesheet"][href="${CSS.escape(link.getAttribute('href'))}"]`))
33
+ continue;
34
+ const added = document.createElement('link');
35
+ added.rel = 'stylesheet';
36
+ added.href = link.getAttribute('href');
37
+ loading.push(new Promise((done) => { added.onload = added.onerror = done; }));
38
+ document.head.append(added);
39
+ }
40
+ await Promise.all(loading);
41
+ if (!isCurrent())
42
+ return;
28
43
  // Persisted elements move into the new page as they are, with their state and attached islands.
29
44
  for (const old of document.querySelectorAll('[data-cl-persist]')) {
30
45
  next.querySelector(`[data-cl-persist="${CSS.escape(old.getAttribute('data-cl-persist'))}"]`)?.replaceWith(old);
31
46
  }
32
47
  document.title = doc.title;
33
48
  old.replaceWith(next);
34
- globalThis.__clAttach?.(next);
49
+ globalThis.__clAttach?.(next, 1); // 1: navigated (bytes)
35
50
  }
36
51
  const navigation = typeof document !== 'undefined' ? globalThis.navigation : undefined;
37
52
  // Only the latest navigation may change the document; a URL that failed loads normally, never intercepted again
38
53
  // (the reload of a failed URL is itself a navigation to it, which the fallback check lets through).
39
54
  let latest = 0;
40
55
  let fallback = '';
56
+ let swapping = false;
41
57
  navigation?.addEventListener('navigate', (event) => {
42
58
  const e = event;
43
- 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)
44
62
  return;
45
63
  const url = new URL(e.destination.url);
46
64
  if (url.href === fallback)
47
65
  return;
48
66
  const id = ++latest;
49
67
  const isCurrent = () => latest === id && !e.signal.aborted;
68
+ swapping = true;
50
69
  e.intercept({
51
- handler: () => swap(url, fetch, isCurrent).catch(() => {
70
+ handler: () => swap(url, fetch, isCurrent).finally(() => { if (latest === id)
71
+ swapping = false; }).catch(() => {
52
72
  if (!isCurrent())
53
73
  return;
54
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,8 +143,51 @@ 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);
149
- if (typeof document !== 'undefined')
181
+ globalThis.__clAttach = (root, navigated) => {
182
+ void attachAll(root);
183
+ if (navigated)
184
+ arrive();
185
+ };
186
+ if (typeof document !== 'undefined') {
187
+ // Islands never affect layout. Installed on the document (not in <head>), so it survives head swaps by the client
188
+ // router; the server also writes it as a <style> for the first paint.
189
+ const sheet = new CSSStyleSheet();
190
+ sheet.replaceSync('cl-island{display:contents}');
191
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
150
192
  attachAll();
193
+ }
@@ -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;
@@ -45,36 +45,44 @@ isCurrent = () => true) {
45
45
  load(found.r),
46
46
  get(data).then(async (res) => {
47
47
  if (!res.ok)
48
- throw new Error(`${res.status === 404 ? 'not found' : res.status}: ${data}`);
48
+ throw new Error(`${res.status} ${data}`);
49
49
  return parse(await res.text());
50
50
  }),
51
51
  ]);
52
52
  if (!isCurrent())
53
53
  return false;
54
54
  const doc = new DOMParser().parseFromString(page.render(props), 'text/html');
55
- const style = doc.createElement('style');
56
- style.textContent = 'cl-island{display:contents}'; // islands never affect layout
57
- doc.head.append(style);
58
- // The page's <title> comes with its head; its own <html> attributes (lang, dir, …) replace the previous page's.
55
+ // The head stays (its stylesheets are every client page's, linked by the shell); the title and the page's own
56
+ // <html> attributes (lang, dir, …) are the new page's.
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);
59
59
  const root = document.documentElement;
60
60
  for (const { name } of [...root.attributes])
61
61
  root.removeAttribute(name);
62
62
  for (const { name, value } of [...doc.documentElement.attributes])
63
63
  root.setAttribute(name, value);
64
- document.head.replaceWith(doc.head);
65
64
  document.body.replaceWith(doc.body);
66
- globalThis.__clAttach?.(document.body);
65
+ // The page's inline head scripts (such as setting the theme before paint) run once, as on a normal load.
66
+ for (const old of doc.head.querySelectorAll('script:not([src])')) {
67
+ const script = document.createElement('script');
68
+ script.textContent = old.textContent;
69
+ document.head.append(script);
70
+ script.remove();
71
+ }
72
+ // Attaches the new page's islands; the loader also releases the old page's.
73
+ ;
74
+ globalThis.__clAttach?.(document.body, 1); // 1: navigated (bytes)
67
75
  return true;
68
76
  }
69
- const routes = typeof document !== 'undefined' ? document.getElementById('cl-routes') : null;
77
+ const routes = globalThis.document?.getElementById('cl-routes');
70
78
  if (routes) {
71
- const table = JSON.parse(routes.textContent ?? '[]');
79
+ const table = JSON.parse(routes.textContent);
72
80
  // Each navigation gets a number; only the latest may change the document or fall back.
73
81
  let latest = 1; // the first render is navigation 1
74
- show(new URL(location.href), table, undefined, undefined, () => latest === 1).catch((err) => {
82
+ show(new URL(location.href), table, () => latest === 1).catch((err) => {
75
83
  if (latest !== 1)
76
84
  return;
77
- document.body.textContent = err.message.startsWith('not found') ? 'Page not found.' : 'Could not load this page.';
85
+ document.body.textContent = err.message.startsWith('404') ? 'Page not found.' : 'Could not load page.';
78
86
  });
79
87
  // A URL that failed to render is loaded normally, never intercepted again (no retry loop). canIntercept is
80
88
  // only true for same-origin navigations, so no origin check is needed.
@@ -82,7 +90,7 @@ if (routes) {
82
90
  const navigation = globalThis.navigation;
83
91
  navigation?.addEventListener('navigate', (event) => {
84
92
  const e = event;
85
- if (!e.canIntercept || e.hashChange || e.downloadRequest !== null || e.formData)
93
+ if (!e.canIntercept || e.hashChange || e.downloadRequest != null || e.formData)
86
94
  return;
87
95
  const url = new URL(e.destination.url);
88
96
  if (url.href === fallback || !matchRoute(table, url.pathname))
@@ -90,7 +98,7 @@ if (routes) {
90
98
  const id = ++latest;
91
99
  const isCurrent = () => latest === id && !e.signal.aborted;
92
100
  e.intercept({
93
- handler: () => show(url, table, undefined, undefined, isCurrent).then(() => { }, () => {
101
+ handler: () => show(url, table, isCurrent).then(() => { }, () => {
94
102
  if (!isCurrent())
95
103
  return;
96
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
  };
@@ -14,7 +15,7 @@ type DataModule = {
14
15
  request: Request;
15
16
  }): object | Promise<object>;
16
17
  };
17
- /** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
18
+ /** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
18
19
  export declare function routeFromFile(file: string): string;
19
20
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
20
21
  loaderUrl?: string;
@@ -29,6 +30,14 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
29
30
  fragments?: boolean;
30
31
  /** URL of the fragment navigation script (with fragments on, every static and server page loads it). */
31
32
  navUrl?: string;
33
+ /** URL of the stylesheet with every component's <style>, linked from every page. */
34
+ stylesUrl?: string;
35
+ /** Stylesheets each page imports (directly or through its components), by route as its file names it. */
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;
32
41
  }): {
33
42
  fetch(request: Request): Promise<Response>;
34
43
  routes: string[];
@@ -42,4 +51,9 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
42
51
  * its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
43
52
  */
44
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;
45
59
  export {};