clarusjs 0.13.0 → 0.15.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 (53) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +148 -13
  3. package/dist/cli/check.d.ts +4 -0
  4. package/dist/cli/check.js +3 -1
  5. package/dist/cli/mapper.js +19 -1
  6. package/dist/cli/project.d.ts +4 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/class-style.d.ts +1 -1
  9. package/dist/compiler/class-style.js +6 -2
  10. package/dist/compiler/components.d.ts +32 -0
  11. package/dist/compiler/components.js +63 -0
  12. package/dist/compiler/emit-client.js +33 -4
  13. package/dist/compiler/emit-server.js +21 -11
  14. package/dist/compiler/html-expr.d.ts +11 -2
  15. package/dist/compiler/html-expr.js +38 -20
  16. package/dist/compiler/icon.d.ts +1 -1
  17. package/dist/compiler/icon.js +4 -0
  18. package/dist/compiler/index.d.ts +13 -1
  19. package/dist/compiler/index.js +64 -2
  20. package/dist/compiler/ir.d.ts +39 -0
  21. package/dist/compiler/ir.js +104 -11
  22. package/dist/compiler/lint.js +12 -1
  23. package/dist/compiler/parse.d.ts +44 -0
  24. package/dist/compiler/parse.js +93 -10
  25. package/dist/compiler/script.d.ts +21 -1
  26. package/dist/compiler/script.js +58 -3
  27. package/dist/compiler/shared.d.ts +6 -0
  28. package/dist/compiler/shared.js +14 -0
  29. package/dist/fetch/index.d.ts +157 -3
  30. package/dist/fetch/index.js +135 -14
  31. package/dist/forms/index.js +15 -3
  32. package/dist/runtime/attrs.d.ts +6 -0
  33. package/dist/runtime/attrs.js +16 -0
  34. package/dist/runtime/dom.d.ts +42 -1
  35. package/dist/runtime/dom.js +152 -23
  36. package/dist/runtime/html.d.ts +6 -0
  37. package/dist/runtime/html.js +12 -0
  38. package/dist/runtime/index.d.ts +1 -1
  39. package/dist/runtime/index.js +1 -1
  40. package/dist/runtime/loader.js +32 -6
  41. package/dist/runtime/router.d.ts +6 -1
  42. package/dist/runtime/router.js +1 -1
  43. package/dist/runtime/server.d.ts +20 -2
  44. package/dist/runtime/server.js +48 -8
  45. package/dist/server/handler.d.ts +28 -1
  46. package/dist/server/handler.js +48 -2
  47. package/dist/server/modes.d.ts +2 -0
  48. package/dist/server/modes.js +5 -1
  49. package/dist/server/views.d.ts +1 -1
  50. package/dist/server/views.js +1 -1
  51. package/dist/vite/plugin.d.ts +19 -0
  52. package/dist/vite/plugin.js +61 -14
  53. package/package.json +1 -1
@@ -28,6 +28,17 @@ export type Ctx = Element | {
28
28
  start: Comment;
29
29
  end: Comment;
30
30
  };
31
+ /**
32
+ * The island that owns `node` (#465): its nearest <cl-island>, except that each slot range (`<!--[s-->…<!--]s-->`) it
33
+ * sits inside moves ownership one island outward, so content an island passes to another stays its own. Null when
34
+ * no island owns it. An [s the parser left without its ]s runs to the end of its parent.
35
+ * @internal
36
+ */
37
+ export declare function owner(node: Node): Element | null;
38
+ /** @internal An island's provide()s, for content another island re-renders inside it. */
39
+ export declare function provideOn(root: Element, cx: object): void;
40
+ /** Slot ranges still open at `n`, among the siblings before it (#465). @internal */
41
+ export declare function openSlots(n: Node): number;
31
42
  /** Hole markers in `ctx`, by index. @internal */
32
43
  export declare function holes(ctx: Ctx): Hole[];
33
44
  /** @if block markers in `ctx`, by index. @internal */
@@ -41,8 +52,17 @@ export declare function block(ctx: Ctx, index: number, which: () => number, bran
41
52
  html: () => string;
42
53
  wire: () => void;
43
54
  }[]): void;
55
+ /**
56
+ * An @await's promise in an island (#430): `k()` is 0 while it's pending, 1 once it resolved, 2 once it rejected
57
+ * (tracked, so a block follows it); `v()` is the value or error. When the expression's signals change, a new
58
+ * promise starts (back to pending) and only the newest one's answer counts. @internal
59
+ */
60
+ export declare function awaited(fn: () => unknown): {
61
+ k(): number;
62
+ v(): unknown;
63
+ };
44
64
  /** @internal Compiled components call this; apps don't. */
45
- export declare function region(ctx: Ctx, index: number, html: () => string, wire: () => void): void;
65
+ export declare function region(ctx: Ctx, index: number, html: (cx?: object) => string, wire: () => void, cx?: object): void;
46
66
  /**
47
67
  * A @for list. Rows the server rendered are adopted in place. When the list changes, rows are matched by key:
48
68
  * kept rows keep their DOM nodes (moved only when out of order) and get the new item and index through their
@@ -67,6 +87,12 @@ export declare function text(hole: Hole, fn: () => unknown): void;
67
87
  * @internal Compiled components call this; apps don't.
68
88
  */
69
89
  export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event) => void): void;
90
+ /**
91
+ * [use]="behaviour" (#464): call each behaviour (one, or a list) with the element marked data-cl-u="index", once; a
92
+ * function it returns runs when the branch, row or island goes.
93
+ * @internal Compiled components call this.
94
+ */
95
+ export declare function use(ctx: Ctx, index: number, get: () => unknown): void;
70
96
  /** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
71
97
  export declare function marked(ctx: Ctx, selector: string): Element | undefined;
72
98
  /**
@@ -86,6 +112,21 @@ export declare function attr(ctx: Ctx, index: number, name: string, fn: () => un
86
112
  export declare function modelInput<T>(root: Element, name: string, initial: T): Signal<T> & {
87
113
  own(value: T): void;
88
114
  };
115
+ /**
116
+ * emit() in a component that declares @event (#442): a cancelable cl:event from the island to its parent's listener.
117
+ * False when the parent cancelled it ($info.cancel()).
118
+ * @internal Compiled components call this; apps don't.
119
+ */
120
+ export declare function emit(root: Element, name: string, value: unknown, info?: {
121
+ reason?: string;
122
+ event?: Event;
123
+ }): boolean;
124
+ /** (name)="…" on a child island in region `index` (#442): its emit('name', …) arrives here, and goes no further. @internal */
125
+ export declare function listen(ctx: Ctx, index: number, name: string, handler: (value: unknown, info: {
126
+ reason?: string;
127
+ event?: Event;
128
+ cancel(): void;
129
+ }) => void): void;
89
130
  /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
90
131
  export declare function model(ctx: Ctx, index: number, name: string, set: (value: unknown) => void): void;
91
132
  export {};
@@ -10,6 +10,57 @@ function inside(ctx, node) {
10
10
  return !!(ctx.start.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING) &&
11
11
  !!(ctx.end.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_PRECEDING);
12
12
  }
13
+ /**
14
+ * The island that owns `node` (#465): its nearest <cl-island>, except that each slot range (`<!--[s-->…<!--]s-->`) it
15
+ * sits inside moves ownership one island outward, so content an island passes to another stays its own. Null when
16
+ * no island owns it. An [s the parser left without its ]s runs to the end of its parent.
17
+ * @internal
18
+ */
19
+ export function owner(node) {
20
+ let out = 0;
21
+ for (let n = node; n; n = n.parentNode) {
22
+ if (n !== node && n.localName === 'cl-island') {
23
+ if (!out)
24
+ return n;
25
+ out--;
26
+ }
27
+ out += openSlots(n);
28
+ }
29
+ return null;
30
+ }
31
+ // What each island provides (#465), for the components it holds that another island re-renders.
32
+ const provided = new WeakMap();
33
+ /** @internal An island's provide()s, for content another island re-renders inside it. */
34
+ export function provideOn(root, cx) { provided.set(root, cx); }
35
+ /**
36
+ * The context a region renders with: its island's own, plus what each island holding the region (it sits in their
37
+ * slot ranges, between them and `root`) provides, inner ones first. Spreading (Object.assign drops a __proto__ key)
38
+ * reads the getters now, so the region follows the values it read.
39
+ */
40
+ function contextAt(node, root, own) {
41
+ let cx;
42
+ for (let n = node.parentNode; n && n !== root; n = n.parentNode)
43
+ if (n.localName === 'cl-island')
44
+ cx = { ...provided.get(n), ...cx };
45
+ return cx ? { ...own, ...cx } : own;
46
+ }
47
+ /** Slot ranges still open at `n`, among the siblings before it (#465). @internal */
48
+ export function openSlots(n) {
49
+ let open = 0;
50
+ let closed = 0;
51
+ for (let s = n.previousSibling; s; s = s.previousSibling) {
52
+ if (s.nodeType !== 8)
53
+ continue;
54
+ const d = s.data;
55
+ if (d === ']s')
56
+ closed++;
57
+ else if (d === '[s')
58
+ closed ? closed-- : open++;
59
+ }
60
+ return open;
61
+ }
62
+ /** The island a context's root stands for: itself when it is one, else the island it is in (null: none). */
63
+ const islandOf = (root) => (root.localName === 'cl-island' ? root : owner(root));
13
64
  /**
14
65
  * Find every marker in `ctx`, skipping nested islands:
15
66
  * holes `<!--[N-->`, @if blocks `<!--[bN:K-->`, @for lists `<!--[fN-->` with rows `<!--[r-->` and `<!--[e-->`,
@@ -22,15 +73,7 @@ function scan(ctx) {
22
73
  const fors = [];
23
74
  const regions = [];
24
75
  const open = [];
25
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT, {
26
- acceptNode: (n) => n.nodeType === 8 ? NodeFilter.FILTER_ACCEPT
27
- : n !== root && n.localName === 'cl-island' ? NodeFilter.FILTER_REJECT
28
- : NodeFilter.FILTER_SKIP,
29
- });
30
- for (let n = walker.nextNode(); n; n = walker.nextNode()) {
31
- if (!inside(ctx, n))
32
- continue;
33
- const c = n;
76
+ const take = (c) => {
34
77
  const data = c.data;
35
78
  let m;
36
79
  const push = (kind, index = 0, k = 0) => open.push({ kind, index, k, start: c, rows: [], empty: null });
@@ -64,7 +107,31 @@ function scan(ctx) {
64
107
  parent.empty = { start: o.start, end: c };
65
108
  }
66
109
  }
67
- }
110
+ };
111
+ // One pass (#465): `level` counts the islands entered below this one, minus the slot ranges entered (each moves its
112
+ // content one island out), so the island's own comments are at 0 and nothing below 0 is (as owner() says, linearly).
113
+ const visit = (parent, level) => {
114
+ let ranges = 0;
115
+ for (let n = parent.firstChild; n; n = n.nextSibling) {
116
+ if (n.nodeType === 1)
117
+ level < 0 || visit(n, level + (n.localName === 'cl-island' ? 1 : 0));
118
+ else if (n.nodeType !== 8)
119
+ continue;
120
+ else if (n.data === '[s') {
121
+ ranges++;
122
+ level--;
123
+ }
124
+ else if (n.data === ']s') {
125
+ if (ranges) {
126
+ ranges--;
127
+ level++;
128
+ }
129
+ }
130
+ else if (!level && inside(ctx, n))
131
+ take(n);
132
+ }
133
+ };
134
+ visit(root, 0);
68
135
  return { holes, blocks, fors, regions };
69
136
  }
70
137
  /** Hole markers in `ctx`, by index. @internal */
@@ -139,8 +206,32 @@ const onlyIsland = (nodes) => {
139
206
  const kept = nodes.filter((n) => n.nodeType !== 3 || n.textContent.trim());
140
207
  return kept.length === 1 && kept[0].localName === 'cl-island' ? kept[0] : null;
141
208
  };
209
+ /**
210
+ * An @await's promise in an island (#430): `k()` is 0 while it's pending, 1 once it resolved, 2 once it rejected
211
+ * (tracked, so a block follows it); `v()` is the value or error. When the expression's signals change, a new
212
+ * promise starts (back to pending) and only the newest one's answer counts. @internal
213
+ */
214
+ export function awaited(fn) {
215
+ const k = state(0);
216
+ let v;
217
+ let run = 0;
218
+ onDispose(() => { run++; }); // an answer after the island is gone changes nothing
219
+ effect(() => {
220
+ const p = fn();
221
+ const id = ++run;
222
+ untrack(() => k.set(0));
223
+ Promise.resolve(p).then((x) => { if (id === run) {
224
+ v = x;
225
+ k.set(1);
226
+ } }, (e) => { if (id === run) {
227
+ v = e;
228
+ k.set(2);
229
+ } });
230
+ });
231
+ return { k: () => k.get(), v: () => v };
232
+ }
142
233
  /** @internal Compiled components call this; apps don't. */
143
- export function region(ctx, index, html, wire) {
234
+ export function region(ctx, index, html, wire, cx) {
144
235
  const r = scan(ctx).regions[index];
145
236
  if (!r)
146
237
  return;
@@ -148,7 +239,7 @@ export function region(ctx, index, html, wire) {
148
239
  let first = true;
149
240
  onDispose(() => dispose?.());
150
241
  effect(() => {
151
- const next = html();
242
+ const next = html(contextAt(r.start, rootOf(ctx), cx));
152
243
  untrack(() => {
153
244
  if (!first) {
154
245
  // A nested island with new props is updated in place (DOM and state kept), not replaced.
@@ -304,7 +395,7 @@ export function on(ctx, index, type, fn) {
304
395
  // An event that doesn't bubble (mouseenter, focus) is its target's alone, not its ancestors'.
305
396
  for (let el = e.target; el && el !== root.parentElement; el = e.bubbles ? el.parentElement : null) {
306
397
  const i = el.getAttribute?.('data-cl-e');
307
- if (i === null || i === undefined || el.closest('cl-island') !== root)
398
+ if (i === null || i === undefined || owner(el) !== root)
308
399
  continue;
309
400
  for (const h of [...(own.get(Number(i)) ?? [])])
310
401
  if (inside(h.ctx, el))
@@ -322,11 +413,28 @@ export function on(ctx, index, type, fn) {
322
413
  onDispose(() => { const at = list.indexOf(handler); if (at !== -1)
323
414
  list.splice(at, 1); }); // a removed branch or row stops listening
324
415
  }
416
+ /**
417
+ * [use]="behaviour" (#464): call each behaviour (one, or a list) with the element marked data-cl-u="index", once; a
418
+ * function it returns runs when the branch, row or island goes.
419
+ * @internal Compiled components call this.
420
+ */
421
+ export function use(ctx, index, get) {
422
+ const el = marked(ctx, `[data-cl-u="${index}"]`);
423
+ if (!el)
424
+ return;
425
+ for (const fn of [untrack(get)].flat()) {
426
+ if (typeof fn !== 'function')
427
+ continue;
428
+ const dispose = fn(el);
429
+ if (typeof dispose === 'function')
430
+ onDispose(dispose);
431
+ }
432
+ }
325
433
  /** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
326
434
  export function marked(ctx, selector) {
327
435
  const root = rootOf(ctx);
328
- const island = root.closest('cl-island');
329
- return [...root.querySelectorAll(selector)].find((e) => e.closest('cl-island') === island && inside(ctx, e));
436
+ const island = islandOf(root);
437
+ return [...root.querySelectorAll(selector)].find((e) => owner(e) === island && inside(ctx, e));
330
438
  }
331
439
  /**
332
440
  * A reactive spread (#405): sets the attributes the object has, removes the ones it no longer has (only those it set:
@@ -402,8 +510,23 @@ export function modelInput(root, name, initial) {
402
510
  },
403
511
  };
404
512
  }
405
- /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
406
- export function model(ctx, index, name, set) {
513
+ /**
514
+ * emit() in a component that declares @event (#442): a cancelable cl:event from the island to its parent's listener.
515
+ * False when the parent cancelled it ($info.cancel()).
516
+ * @internal Compiled components call this; apps don't.
517
+ */
518
+ export function emit(root, name, value, info = {}) {
519
+ return root.dispatchEvent(new CustomEvent('cl:event', { detail: { name, value, ...info }, bubbles: true, cancelable: true }));
520
+ }
521
+ /** (name)="…" on a child island in region `index` (#442): its emit('name', …) arrives here, and goes no further. @internal */
522
+ export function listen(ctx, index, name, handler) {
523
+ fromChild(ctx, index, 'cl:event', name, (event, detail) => {
524
+ const { value, reason, event: cause } = detail;
525
+ handler(value, { reason, event: cause, cancel: () => event.preventDefault() });
526
+ });
527
+ }
528
+ /** Listen for `type` from the child island bound in region `index` only (not one nested in it), named `name`. */
529
+ function fromChild(ctx, index, type, name, take) {
407
530
  const r = scan(ctx).regions[index];
408
531
  if (!r)
409
532
  return;
@@ -414,13 +537,19 @@ export function model(ctx, index, name, set) {
414
537
  // Only from inside this region: 4 = the target follows the start marker, 2 = it precedes the end marker.
415
538
  if (detail.name !== name || !(r.start.compareDocumentPosition(from) & 4) || !(r.end.compareDocumentPosition(from) & 2))
416
539
  return;
417
- // Only the child island this region binds: an island nested in it, which nobody bound, keeps its own value.
418
- if (from.parentElement?.closest('cl-island') !== rootOf(ctx))
540
+ // Only the child island this region binds: an island nested in it, which nobody bound, keeps its own.
541
+ if (owner(from) !== rootOf(ctx))
419
542
  return;
420
- event.preventDefault();
421
543
  event.stopPropagation();
422
- set(detail.value);
544
+ take(event, detail);
423
545
  };
424
- host.addEventListener('cl:model', listen);
425
- onDispose(() => host.removeEventListener('cl:model', listen));
546
+ host.addEventListener(type, listen);
547
+ onDispose(() => host.removeEventListener(type, listen));
548
+ }
549
+ /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
550
+ export function model(ctx, index, name, set) {
551
+ fromChild(ctx, index, 'cl:model', name, (event, detail) => {
552
+ event.preventDefault(); // taken: the child's value follows the parent's state
553
+ set(detail.value);
554
+ });
426
555
  }
@@ -10,6 +10,12 @@ export declare function json(value: unknown): string;
10
10
  * @internal
11
11
  */
12
12
  export declare function spreadHtml(obj: unknown, skip: readonly string[], tag?: string, where?: string): string;
13
+ /**
14
+ * The attributes a parent passed to a component (#463), on its root: each through attrHtml, except the names the root
15
+ * writes itself (`skip`) and style (merged on its own). No spread checks needed: passed() keeps only attribute-like names.
16
+ * @internal
17
+ */
18
+ export declare function passedHtml(attrs: Record<string, unknown>, skip: readonly string[]): string;
13
19
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
14
20
  export declare function attrHtml(name: string, value: unknown, tag?: string): string;
15
21
  /** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. @internal */
@@ -34,6 +34,18 @@ export function spreadHtml(obj, skip, tag, where) {
34
34
  }
35
35
  return set.map(([name, v]) => (v === null ? '' : v === true ? ` ${name}` : ` ${name}="${escape(v)}"`)).join('');
36
36
  }
37
+ /**
38
+ * The attributes a parent passed to a component (#463), on its root: each through attrHtml, except the names the root
39
+ * writes itself (`skip`) and style (merged on its own). No spread checks needed: passed() keeps only attribute-like names.
40
+ * @internal
41
+ */
42
+ export function passedHtml(attrs, skip) {
43
+ let out = '';
44
+ for (const k in attrs)
45
+ if (k !== 'style' && !skip.includes(k.toLowerCase()))
46
+ out += attrHtml(k, attrs[k]);
47
+ return out;
48
+ }
37
49
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
38
50
  export function attrHtml(name, value, tag) {
39
51
  const v = attrValue(name, value, tag);
@@ -1,5 +1,5 @@
1
1
  export { state, derived, shared, effect, scope, onDispose, untrack, batch, type Signal, type ReadSignal } from './signals.ts';
2
- export { holes, blocks, text, on, attr, spread, block, forBlock, region, model, modelInput, type Hole, type Block, type Ctx } from './dom.ts';
2
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, use, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
3
3
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
5
  export { classValue, styleValue } from './attrs.ts';
@@ -1,6 +1,6 @@
1
1
  // Browser runtime used by compiled attach() functions.
2
2
  export { state, derived, shared, effect, scope, onDispose, untrack, batch } from './signals.js';
3
- export { holes, blocks, text, on, attr, spread, block, forBlock, region, model, modelInput } from './dom.js';
3
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, use, provideOn } from './dom.js';
4
4
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
6
  export { classValue, styleValue } from './attrs.js';
@@ -17,10 +17,21 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
17
17
  }
18
18
  return path;
19
19
  };
20
+ import { owner } from './dom.js';
20
21
  import { parse } from './serialize.js';
21
22
  import { scope } from './signals.js';
22
23
  // Islands scheduled or loading. `data-cl-ready` is set only after attach() succeeds.
23
24
  const loading = new WeakSet();
25
+ // Islands attaching now (attach="load"), so an island holding them waits for them (#465): content it re-renders
26
+ // inside them reads what they provide.
27
+ const pending = new WeakMap();
28
+ /** Does `inner` hold content of `el` in one of its slot ranges? */
29
+ function holds(inner, el) {
30
+ const walker = document.createTreeWalker(inner, 128); // comments
31
+ for (let n; (n = walker.nextNode());)
32
+ if (n.data === '[s' && owner(n.nextSibling) === el)
33
+ return true;
34
+ }
24
35
  const updates = new WeakMap();
25
36
  // Each attached island's disposer: everything its attach() wired (effects, listeners) is released by it.
26
37
  const attached = new Map();
@@ -36,7 +47,7 @@ function record(el) {
36
47
  const events = [];
37
48
  const listener = (e) => {
38
49
  const target = e.target;
39
- if (!target || target.closest?.('cl-island') !== el)
50
+ if (!target || owner(target) !== el)
40
51
  return;
41
52
  if (HOLD.has(e.type))
42
53
  e.preventDefault();
@@ -105,10 +116,20 @@ async function attachOne(el, load, recorded) {
105
116
  props = parse(el.getAttribute('p') ?? '{}');
106
117
  const s = el.getAttribute('s');
107
118
  state = s === null ? undefined : parse(s);
119
+ // Islands in it holding its content attach first (#465): content it re-renders there reads what they provide. One
120
+ // failing to load fails this one too (both retry). ponytail: later ones (idle, visible, interaction) aren't waited for.
121
+ for (const inner of el.querySelectorAll('cl-island')) {
122
+ if (!pending.has(inner) || !holds(inner, el))
123
+ continue;
124
+ await pending.get(inner);
125
+ if (!pending.has(inner))
126
+ throw 0;
127
+ }
108
128
  }
109
129
  catch (err) {
110
130
  recorded.stop();
111
131
  loading.delete(el); // network or parse failure: the next attachAll() retries
132
+ pending.delete(el);
112
133
  console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to load`, err);
113
134
  return;
114
135
  }
@@ -151,8 +172,11 @@ export async function attachAll(root = document, load = lastLoad) {
151
172
  for (const el of islands) {
152
173
  loading.add(el);
153
174
  const recorded = record(el);
154
- if ((el.getAttribute('a') ?? 'load') === 'load')
155
- now.push(attachOne(el, load, recorded));
175
+ if ((el.getAttribute('a') ?? 'load') === 'load') {
176
+ const p = attachOne(el, load, recorded);
177
+ pending.set(el, p);
178
+ now.push(p);
179
+ }
156
180
  else
157
181
  schedule(el, () => void attachOne(el, load, recorded));
158
182
  }
@@ -195,8 +219,10 @@ function arrive() {
195
219
  ;
196
220
  globalThis.__clUpdate = (el, next) => {
197
221
  const update = updates.get(el);
198
- // The same component: the same name and the same source (two panel.tscl files share a name).
199
- if (!update || el.getAttribute('c') !== next.getAttribute('c') || el.getAttribute('src') !== next.getAttribute('src'))
222
+ // The same component: the same name and the same source (two panel.tscl files share a name). An attached island
223
+ // without inputs has nothing to update (#465: re-rendered because the content it holds changed, which its parent
224
+ // wires in place).
225
+ if (!attached.has(el) || el.getAttribute('c') !== next.getAttribute('c') || el.getAttribute('src') !== next.getAttribute('src'))
200
226
  return false;
201
227
  const p = next.getAttribute('p') ?? '{}';
202
228
  el.setAttribute('p', p);
@@ -207,7 +233,7 @@ globalThis.__clUpdate = (el, next) => {
207
233
  for (const { name, value } of [...next.attributes])
208
234
  if (name.startsWith('data-cl-path-'))
209
235
  el.setAttribute(name, value);
210
- update(parse(p));
236
+ update?.(parse(p));
211
237
  return true;
212
238
  };
213
239
  globalThis.__clAttach = (root, navigated) => {
@@ -3,7 +3,12 @@ type Entry = {
3
3
  r: string;
4
4
  };
5
5
  type Page = {
6
- render(props: object): string;
6
+ render(props: object, slots?: undefined, opts?: {
7
+ route: {
8
+ path: string;
9
+ params: Record<string, string>;
10
+ };
11
+ }): string;
7
12
  };
8
13
  /** The route a path belongs to, with its decoded params. Same grammar as the server: whole [param] segments. */
9
14
  export declare function matchRoute(table: Entry[], pathname: string): {
@@ -64,7 +64,7 @@ isCurrent = () => true, load = (src) => import(__rewriteRelativeImportExtension(
64
64
  return false;
65
65
  // The head stays (its stylesheets are every client page's, linked by the shell); the title gets the site's
66
66
  // titleTemplate, from the shell (always set: '%s' without one).
67
- await swapIn(page.render(props), (title) => document.getElementById('cl-routes').dataset.title.replace('%s', () => title));
67
+ await swapIn(page.render(props, undefined, { route: { path: url.pathname, params: found.params } }), (title) => document.getElementById('cl-routes').dataset.title.replace('%s', () => title));
68
68
  return true;
69
69
  }
70
70
  /**
@@ -1,12 +1,30 @@
1
1
  import { attrHtml } from './html.ts';
2
- export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml } from './html.ts';
3
- export { classValue, styleValue } from './attrs.ts';
2
+ export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.ts';
3
+ export { classValue, styleValue, passed } from './attrs.ts';
4
4
  /**
5
5
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
6
6
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
7
7
  * @internal Compiled components call this; apps don't.
8
8
  */
9
9
  export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string, paths?: Record<string, unknown>): string;
10
+ export declare function island(name: string, src: string, props: Record<string, unknown>, html: string | Promise<string>, state?: Record<string, unknown>, attach?: string, paths?: Record<string, unknown>): string | Promise<string>;
11
+ /**
12
+ * The parts of a template level that calls components or places slots (#430): joined into a string, or into a
13
+ * promise of one when a part is a promise (a component that awaits in its <script server>). @internal
14
+ */
15
+ export declare function join(parts: unknown[]): string | Promise<string>;
16
+ /**
17
+ * An @await outside islands (#430): the server waits for the promise and renders @then with the value or @catch
18
+ * with the error; without @catch, a rejection fails the render. @internal
19
+ */
20
+ export declare function awaitHtml(promise: unknown, then: ((v: unknown) => string | Promise<string>) | null, caught: ((e: unknown) => string | Promise<string>) | null): Promise<string>;
21
+ /**
22
+ * A slot's HTML (#455): its fill, a function called with what the slot passes and the context at the slot (#465), or
23
+ * the fallback when nothing fills it. A string fill (hand-built slots) is used as is. @internal
24
+ */
25
+ export declare function slot(fill: unknown, data: object | undefined, fallback: () => string | Promise<string>, cx?: object): string | Promise<string>;
26
+ /** A child component's HTML inside an island: a promise (it awaits) is an error naming both. @internal */
27
+ export declare function sync(html: string | Promise<string>, child: string, island: string): string;
10
28
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
11
29
  export declare const attr: typeof attrHtml;
12
30
  /**
@@ -1,20 +1,57 @@
1
1
  // Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
2
2
  import { attrHtml, escape, HTML } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
- export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml } from './html.js';
5
- export { classValue, styleValue } from './attrs.js';
6
- /**
7
- * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
8
- * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
9
- * @internal Compiled components call this; apps don't.
10
- */
4
+ export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.js';
5
+ export { classValue, styleValue, passed } from './attrs.js';
11
6
  export function island(name, src, props, html, state, attach, paths) {
7
+ // Slot content that awaits (#430) makes the island's HTML a promise: wrap it once it's there.
8
+ if (html instanceof Promise)
9
+ return html.then((h) => island(name, src, props, h, state, attach, paths));
12
10
  const s = state === undefined ? '' : ` s="${escape(toBrowser(state))}"`;
13
11
  const a = attach && attach !== 'load' ? ` a="${escape(attach)}"` : ''; // when to attach: see runtime/loader.ts
14
12
  // A component bound two ways carries each binding's path for the forms engine (clarusjs/forms), given by its parent.
15
13
  const d = Object.entries(paths ?? {}).map(([model, path]) => ` data-cl-path-${escape(model)}="${escape(String(path))}"`).join('');
16
14
  return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(toBrowser(props))}"${s}${a}${d}>${html}</cl-island>`;
17
15
  }
16
+ /**
17
+ * The parts of a template level that calls components or places slots (#430): joined into a string, or into a
18
+ * promise of one when a part is a promise (a component that awaits in its <script server>). @internal
19
+ */
20
+ export function join(parts) {
21
+ return parts.some((p) => p instanceof Promise) ? Promise.all(parts).then((all) => all.join('')) : parts.join('');
22
+ }
23
+ /**
24
+ * An @await outside islands (#430): the server waits for the promise and renders @then with the value or @catch
25
+ * with the error; without @catch, a rejection fails the render. @internal
26
+ */
27
+ export async function awaitHtml(promise, then, caught) {
28
+ let value;
29
+ try {
30
+ value = await promise;
31
+ }
32
+ catch (err) {
33
+ if (!caught)
34
+ throw err;
35
+ return caught(err);
36
+ }
37
+ return then ? then(value) : '';
38
+ }
39
+ /**
40
+ * A slot's HTML (#455): its fill, a function called with what the slot passes and the context at the slot (#465), or
41
+ * the fallback when nothing fills it. A string fill (hand-built slots) is used as is. @internal
42
+ */
43
+ export function slot(fill, data, fallback, cx) {
44
+ if (fill === undefined || fill === null)
45
+ return fallback();
46
+ return typeof fill === 'function' ? fill(data ?? {}, cx) : fill;
47
+ }
48
+ /** A child component's HTML inside an island: a promise (it awaits) is an error naming both. @internal */
49
+ export function sync(html, child, island) {
50
+ if (typeof html === 'string')
51
+ return html;
52
+ html.catch(() => { }); // its own rejection isn't the error to report
53
+ throw new Error(`[clarusjs] <${child}> awaits in its <script server>, so it can't be inside the island <${island}>: an island re-renders its children in the browser, where it can't wait. Render <${child}> outside the island, or load its data in a parent and pass it in as props`);
54
+ }
18
55
  /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
19
56
  export const attr = attrHtml;
20
57
  /**
@@ -37,7 +74,10 @@ export function toBrowser(value, path = '', seen = new Set()) {
37
74
  * compiled components that have a loader. @internal
38
75
  */
39
76
  export function loaded(key) {
40
- return globalThis.__clLoaded?.get(key) ?? {};
77
+ // The server handler keeps each render's data in an AsyncLocalStorage (#430: a render may pause at an await);
78
+ // this module stays free of Node APIs (it also runs in the docs playground), so it only reads it.
79
+ const scope = globalThis;
80
+ return (scope.__clLoadedStore?.getStore() ?? scope.__clLoaded)?.get(key) ?? {};
41
81
  }
42
82
  /**
43
83
  * Render with component loaders' results available to `loaded()`. Rendering is synchronous, so one render's data never
@@ -1,7 +1,12 @@
1
1
  import { type ModeTable } from './modes.ts';
2
2
  import { type HeadOptions, type SiteOptions } from './head.ts';
3
3
  type PageModule = {
4
- render(props?: object): string;
4
+ render(props?: object, slots?: undefined, opts?: {
5
+ route: {
6
+ path: string;
7
+ params: Record<string, string>;
8
+ };
9
+ }): string | Promise<string>;
5
10
  };
6
11
  type Params = Record<string, string>;
7
12
  /**
@@ -67,6 +72,24 @@ export type LoadContext = {
67
72
  cookies: Cookies;
68
73
  locals: Locals;
69
74
  };
75
+ /**
76
+ * What a folder's `+guard.ts` gets (#457): the page's load() context plus the URL. Return a `Response` (such as
77
+ * `redirect()`) to answer instead of the page, or nothing to go on; it may set `locals` for what runs after it.
78
+ *
79
+ * ```ts
80
+ * // src/pages/admin/+guard.ts
81
+ * export function guard({ locals, url }: GuardContext) {
82
+ * if (!locals.user) return redirect('/sign-in?next=' + encodeURIComponent(url.pathname))
83
+ * }
84
+ * ```
85
+ * @see https://clarusjs.com/guide/auth
86
+ */
87
+ export type GuardContext = LoadContext & {
88
+ url: URL;
89
+ };
90
+ type GuardModule = {
91
+ guard?(context: GuardContext): Response | void | undefined | Promise<Response | void | undefined>;
92
+ };
70
93
  /**
71
94
  * `handle()` in src/server.ts: runs once per request before any page loads, to resolve the session into `locals`.
72
95
  * Returning a Response (such as `redirect('/login')`) answers the request instead.
@@ -118,11 +141,15 @@ export type EndpointModule = Partial<Record<'GET' | 'HEAD' | 'POST' | 'PUT' | 'P
118
141
  */
119
142
  export declare function redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
120
143
  /** @internal clarusjs's own build and server code call this; apps don't. */
144
+ export declare function isPageFile(file: string): boolean;
145
+ /** @internal clarusjs's own build and server code call this; apps don't. */
121
146
  export declare function routeFromFile(file: string): string;
122
147
  /** @internal clarusjs's own build and server code call this; apps don't. */
123
148
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
124
149
  loaderUrl?: string;
125
150
  data?: Record<string, () => Promise<DataModule>>;
151
+ /** Folder guards (#457): each src/pages folder's +guard.ts → its module. */
152
+ guards?: Record<string, () => Promise<GuardModule>>;
126
153
  modes?: ModeTable;
127
154
  /** Client routes (as their files name them) → URL of the page's browser render module. */
128
155
  client?: Record<string, string>;