rosetack 0.1.3 → 0.1.5

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.
@@ -6,6 +6,8 @@ type SignalEntry = { value: unknown; subs: Set<Subscriber> };
6
6
 
7
7
  let currentEffect: (() => void) | null = null;
8
8
 
9
+ let trackingDeps: Set<SignalEntry> | null = null;
10
+
9
11
  let signalMap: Map<string, SignalEntry> =
10
12
  (globalThis as any).__rosetack_signalMap ?? new Map();
11
13
  (globalThis as any).__rosetack_signalMap = signalMap;
@@ -21,13 +23,24 @@ export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
21
23
  const e = entry(key, initial);
22
24
 
23
25
  const getter = () => {
24
- if (currentEffect) e.subs.add(currentEffect);
26
+ if (currentEffect) {
27
+ e.subs.add(currentEffect);
28
+ if (trackingDeps) trackingDeps.add(e);
29
+ }
25
30
  return e.value as T;
26
31
  };
27
32
 
28
33
  const setter = (v: T) => {
29
- e.value = v;
34
+ const next = (typeof v === 'function' ? (v as (cur: T) => T)(e.value) : v) as T;
35
+ e.value = next;
36
+ const prevEffect = currentEffect;
37
+ const prevTracking = trackingDeps;
38
+ currentEffect = null;
39
+ trackingDeps = null;
30
40
  e.subs.forEach((fn: Subscriber) => fn());
41
+ currentEffect = prevEffect;
42
+ trackingDeps = prevTracking;
43
+ if (persistedKeys.has(key)) writeStorage(key, next);
31
44
  };
32
45
 
33
46
  return [getter, setter];
@@ -37,10 +50,62 @@ export function hasState(key: string): boolean {
37
50
  return signalMap.has(key);
38
51
  }
39
52
 
53
+ let seededKeys = new Set<string>();
54
+
55
+ export function isSeeded(key: string): boolean {
56
+ return seededKeys.has(key);
57
+ }
58
+
59
+ export function markSeeded(key: string): void {
60
+ seededKeys.add(key);
61
+ }
62
+
40
63
  export function setState<T>(key: string, value: T): void {
41
64
  const e = entry(key, value);
42
65
  e.value = value;
66
+ const prevEffect = currentEffect;
67
+ const prevTracking = trackingDeps;
68
+ currentEffect = null;
69
+ trackingDeps = null;
43
70
  e.subs.forEach((fn: Subscriber) => fn());
71
+ currentEffect = prevEffect;
72
+ trackingDeps = prevTracking;
73
+ if (persistedKeys.has(key)) writeStorage(key, value);
74
+ }
75
+
76
+ const persistedKeys = new Set<string>();
77
+
78
+ function writeStorage(key: string, v: unknown): void {
79
+ try {
80
+ (globalThis as { localStorage?: Storage }).localStorage?.setItem('rosetack:' + key, JSON.stringify(v));
81
+ } catch { /* no storage / private mode / quota: persistence is best-effort */ }
82
+ }
83
+
84
+ // F9 ($persist): `let theme = $persist('dark')` — like $state, but the value survives reloads.
85
+ export function persistState<T>(key: string, initial: T): [() => T, (v: T) => void] {
86
+ persistedKeys.add(key);
87
+ let seeded = initial;
88
+ let hasStored = false;
89
+ try {
90
+ const raw = (globalThis as { localStorage?: Storage }).localStorage?.getItem('rosetack:' + key);
91
+ if (raw != null) {
92
+ seeded = JSON.parse(raw) as T;
93
+ hasStored = true;
94
+ }
95
+ } catch { }
96
+ const [get, set] = state(key, seeded);
97
+ if (hasStored) set(seeded);
98
+ return [get, set];
99
+ }
100
+
101
+ let lastBoundaryError: Error | null = null;
102
+
103
+ export function $setBoundaryError(e: unknown): void {
104
+ lastBoundaryError = e instanceof Error ? e : new Error(String(e));
105
+ }
106
+
107
+ export function $boundaryError(): Error | null {
108
+ return lastBoundaryError;
44
109
  }
45
110
 
46
111
  const cleanups = new Set<Cleanup>();
@@ -78,7 +143,7 @@ export function resetContainerFx(container: object): void {
78
143
  keys.forEach((k: string) => signalMap.delete(k));
79
144
  keysByOwner.delete(container);
80
145
  }
81
- dataCache.clear();
146
+ renderMaps().data.clear();
82
147
  pendingDeltas.clear();
83
148
  }
84
149
 
@@ -102,6 +167,55 @@ export function effect(fn: () => void): Cleanup {
102
167
  return cleanup;
103
168
  }
104
169
 
170
+ // F43: `$effect(fn)` - the reactive effect rune. Client-only (SSR: a no-op, fn never fires).
171
+ export function $effect(fn: () => void | (() => void)): Cleanup {
172
+ if (typeof document === 'undefined') return () => {};
173
+ const deps = new Set<SignalEntry>();
174
+ let cleanup: (() => void) | undefined;
175
+ let scheduled = false;
176
+ let disposed = false;
177
+ const detach = () => {
178
+ deps.forEach((e: SignalEntry) => e.subs.delete(wrapped));
179
+ deps.clear();
180
+ };
181
+ const run = () => {
182
+ if (disposed) return;
183
+ scheduled = true;
184
+ detach();
185
+ if (typeof cleanup === 'function') {
186
+ try { (cleanup as () => void)(); } catch { /* a stale cleanup must not kill the route */ }
187
+ }
188
+ const prevEffect = currentEffect;
189
+ const prevTracking = trackingDeps;
190
+ currentEffect = wrapped;
191
+ trackingDeps = deps;
192
+ try {
193
+ const ret = fn();
194
+ cleanup = typeof ret === 'function' ? (ret as () => void) : undefined;
195
+ } catch { /* a throwing effect must not kill the route */ }
196
+ currentEffect = prevEffect;
197
+ trackingDeps = prevTracking;
198
+ scheduled = false;
199
+ };
200
+ const wrapped: Subscriber = () => {
201
+ if (scheduled || disposed) return;
202
+ scheduled = true;
203
+ queueMicrotask(run);
204
+ };
205
+ const owner = fxSet();
206
+ const dispose: Cleanup = () => {
207
+ disposed = true;
208
+ detach();
209
+ if (typeof cleanup === 'function') {
210
+ try { (cleanup as () => void)(); } catch { }
211
+ }
212
+ owner.delete(dispose);
213
+ };
214
+ owner.add(dispose);
215
+ queueMicrotask(run);
216
+ return dispose;
217
+ }
218
+
105
219
  const ESC_MAP: Record<string, string> = {
106
220
  '&': '&amp;',
107
221
  '<': '&lt;',
@@ -121,9 +235,39 @@ export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unkno
121
235
  return `<!--\u27e6m:${i}\u27e7-->` + esc(fn(arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
122
236
  }
123
237
 
238
+ export function attrValueString(name: string, v: unknown): string {
239
+ if (v == null) return '';
240
+ if (typeof v === 'object') {
241
+ if (name === 'class') {
242
+ return Object.entries(v).filter(([, x]) => x).map(([k]) => k).join(' ');
243
+ }
244
+ if (name === 'style') {
245
+ return Object.entries(v)
246
+ .filter(([, x]) => x != null && x !== false && x !== '')
247
+ .map(([k, x]) => `${k}: ${x}`)
248
+ .join('; ');
249
+ }
250
+ return JSON.stringify(v);
251
+ }
252
+ return String(v);
253
+ }
254
+
124
255
  export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
125
256
  const i = closes.push(fn) - 1;
126
- return `${name}="${esc(fn(arg))}" data-b="${i}:${name}"`;
257
+ return `${name}="${esc(attrValueString(name, fn(arg)))}" data-b${i}="${name}"`;
258
+ }
259
+
260
+ /**
261
+ * Boolean attributes (F1): presence IS the value - `checked="false"` still
262
+ * checks the box, so a reactive boolean attr can never ride attrMark. The
263
+ * SSR side emits the bare attribute only when truthy, plus an index-suffixed
264
+ * marker either way; wire()'s boolean branch flips the PROPERTY (the one
265
+ * thing a live DOM obeys after user interaction) and mirrors the attribute
266
+ * for no-JS parity.
267
+ */
268
+ export function boolAttrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
269
+ const i = closes.push(fn) - 1;
270
+ return (fn(arg) ? ` ${name}=""` : '') + ` data-b${i}="!${name}"`;
127
271
  }
128
272
 
129
273
  export function ifMark(
@@ -147,9 +291,23 @@ export function ifMark(
147
291
  return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
148
292
  }
149
293
 
150
- export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
151
- const i = closes.push(() => (items() as unknown[]).map((v) => {
152
- return { html: String(fn(v, closes)), closes, scope: v };
294
+ interface EachRow {
295
+ html: string;
296
+ closes: unknown[];
297
+ scope?: unknown;
298
+ keyed?: boolean;
299
+ key?: string;
300
+ nodes?: Node[];
301
+ disp?: Cleanup;
302
+ norm?: string;
303
+ }
304
+ const EACH_REUSE_FORBID = /data-(?:on|use|bind-this|transition|animate)|data-rosetack-c|data-rv-island/;
305
+ const EACH_HTML_NORM = (h: string): string => h.replace(/\u27e6\/?[a-z]+:\d+\u27e7/g, '').replace(/data-b\d+/g, 'data-b');
306
+ const normHtml = (row: EachRow): string => (row.norm ??= EACH_HTML_NORM(row.html));
307
+
308
+ export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown, key?: (s: unknown, vi: number) => unknown): string {
309
+ const i = closes.push(() => (items() as unknown[]).map((v, vi) => {
310
+ return { html: String(fn(v, closes, vi)), closes, scope: v, keyed: !!key, key: key ? String(key(v, vi)) : undefined };
153
311
  })) - 1;
154
312
  let h = `<!--\u27e6l:${i}\u27e7-->`;
155
313
  for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
@@ -211,6 +369,8 @@ const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
211
369
 
212
370
  const wired = new WeakSet<Node>();
213
371
 
372
+ const pendingIslandObservers = new Set<IntersectionObserver>();
373
+
214
374
  /** Parse an html string into a DocumentFragment. */
215
375
  export function tpl(html: string): DocumentFragment {
216
376
  const t = document.createElement('template');
@@ -223,6 +383,28 @@ const HEAD_ATTR = 'data-rosetack-head';
223
383
  export const handlers: Record<string, (e: Event) => void> =
224
384
  (globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
225
385
 
386
+ let actionDispatch: ((name: string, e: Event) => void) | null = null;
387
+ export function setActionDispatcher(fn: (name: string, e: Event) => void): void {
388
+ actionDispatch = fn;
389
+ }
390
+
391
+ const directBound = new WeakMap<Element, Set<string>>();
392
+
393
+ /**
394
+ * F5: `use:NAME` element actions - the plugin point for DOM behaviors
395
+ * (tooltips, dropdowns, canvas glue) that themes and plugins register once
396
+ * per module: directives.tooltip = (el) => { ...; return cleanup? }. wire()
397
+ * invokes each action for its element when the route adopts; the returned
398
+ * cleanup (if any) rides the same disposal set as every other effect.
399
+ * Parameters travel as data-* attributes the action reads - keeping them out
400
+ * of the reactive graph keeps the action contract one argument.
401
+ */
402
+ export const directives: Record<string, (el: Element, param?: unknown) => void | (() => void) | { update?: (p: unknown) => void; destroy?: () => void }> =
403
+ (globalThis as { __rosetack_directives?: Record<string, (el: Element, param?: unknown) => void | (() => void) | { update?: (p: unknown) => void; destroy?: () => void }> })
404
+ .__rosetack_directives ??= {};
405
+
406
+ const actionRecords = new WeakMap<Element, { update?: (p: unknown) => void; destroy?: () => void }>();
407
+
226
408
  /**
227
409
  * Apply one route's whole <head> (every block of its chain, page first) to the
228
410
  * document: <title> replaces the title, <meta>/<link>/<base> are matched by
@@ -281,6 +463,35 @@ export function clearHead(): void {
281
463
  * Works on the live SSR DOM (adoption) and on freshly parsed fragments.
282
464
  * Returns a disposer for every effect it created.
283
465
  */
466
+ const TRANSITION_POSES: Record<string, { transform?: string; filter?: string; opacity: string }> = {
467
+ fade: { opacity: '0' },
468
+ slide: { transform: 'translateY(20px)', opacity: '0' },
469
+ fly: { transform: 'translateX(-30px) rotate(-5deg)', opacity: '0' },
470
+ zoom: { transform: 'scale(0.8)', opacity: '0' },
471
+ 'slide-up': { transform: 'translateY(30px)', opacity: '0' },
472
+ 'slide-down': { transform: 'translateY(-30px)', opacity: '0' },
473
+ 'slide-left': { transform: 'translateX(30px)', opacity: '0' },
474
+ 'slide-right': { transform: 'translateX(-30px)', opacity: '0' },
475
+ scale: { transform: 'scale(0.7)', opacity: '0' },
476
+ spin: { transform: 'rotate(-90deg)', opacity: '0' },
477
+ blur: { filter: 'blur(8px)', opacity: '0' },
478
+ stagger: { transform: 'translateY(10px)', opacity: '0' },
479
+ };
480
+
481
+ function parseTransitionParams(pstr: string): { duration?: number; delay?: number; easing?: string } {
482
+ const out: { duration?: number; delay?: number; easing?: string } = {};
483
+ if (!pstr) return out;
484
+ const trimmed = pstr.trim();
485
+ if (/^\d+$/.test(trimmed)) { out.duration = Number(trimmed); return out; }
486
+ const dM = /duration\s*:\s*(\d+)/.exec(pstr);
487
+ if (dM) out.duration = Number(dM[1]);
488
+ const dlM = /delay\s*:\s*(\d+)/.exec(pstr);
489
+ if (dlM) out.delay = Number(dlM[1]);
490
+ const eM = /easing\s*:\s*(['"])(.*?)\1/.exec(pstr);
491
+ if (eM) out.easing = eM[2];
492
+ return out;
493
+ }
494
+
284
495
  export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Cleanup {
285
496
  let holder: Node = root;
286
497
  if (root.nodeType === 11) {
@@ -335,6 +546,33 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
335
546
 
336
547
  const ownsHead = root === document.getElementById('app');
337
548
 
549
+ let islandSkip = false;
550
+ if (ownsHead) {
551
+ const islandEls = Array.from(
552
+ (holder as Element).querySelectorAll('[data-rv-island]')
553
+ ).filter((el) => !(el.parentElement && el.parentElement.closest('[data-rv-island]')));
554
+ islandSkip = islandEls.length > 0;
555
+ for (const isl of islandEls) {
556
+ const fire = () => wire(isl, closes, scope);
557
+ const mode = isl.getAttribute('data-rv-island-hydrate');
558
+ if (mode === 'visible' && typeof IntersectionObserver !== 'undefined') {
559
+ const io = new IntersectionObserver((entries) => {
560
+ if (entries.some((en) => en.isIntersecting)) {
561
+ io.disconnect();
562
+ pendingIslandObservers.delete(io);
563
+ fire();
564
+ }
565
+ });
566
+ io.observe(isl);
567
+ pendingIslandObservers.add(io);
568
+ } else if (mode === 'idle' && typeof (globalThis as { requestIdleCallback?: unknown }).requestIdleCallback === 'function') {
569
+ (globalThis as { requestIdleCallback: (cb: () => void) => void }).requestIdleCallback(() => fire());
570
+ } else {
571
+ fire();
572
+ }
573
+ }
574
+ }
575
+
338
576
  for (const c of comments) {
339
577
  if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
340
578
  const m = (c.nodeValue ?? '').match(MARK_RE);
@@ -342,6 +580,8 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
342
580
  const kind = m[1];
343
581
  const idx = +m[2];
344
582
 
583
+ if (islandSkip && kind !== 'h' && (c.parentNode as Element).closest?.('[data-rv-island]')) continue;
584
+
345
585
  if (kind === 'h' && !ownsHead) continue;
346
586
  wired.add(c);
347
587
 
@@ -414,20 +654,68 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
414
654
  const start = c;
415
655
  const end = ends.get(idx);
416
656
  if (!end) continue;
417
- const st = start as unknown as { __disp?: Cleanup };
657
+ const st = start as unknown as { __disp?: Cleanup; __kmap?: Map<string, EachRow> };
418
658
  weff(() => {
419
659
  if (st.__disp) {
420
660
  st.__disp();
421
661
  st.__disp = undefined;
422
662
  }
423
- const items = (closes[idx] as (s?: unknown) => unknown)(scope) as Array<{ html: string; closes: unknown[]; scope?: unknown }>;
663
+ const items = (closes[idx] as (s?: unknown) => unknown)(scope) as EachRow[];
664
+ const parent = start.parentNode!;
665
+ const keyed = items.length > 0 && items.every((r) => r.keyed);
666
+ if (keyed) {
667
+ const prev = st.__kmap ?? new Map<string, EachRow>();
668
+ const counts = new Map<string, number>();
669
+ for (const r of items) counts.set(r.key!, (counts.get(r.key!) ?? 0) + 1);
670
+ const keep = new Set<Node>();
671
+ const nextMap = new Map<string, EachRow>();
672
+ const used = new Set<string>();
673
+ const decisions: Array<{ row: EachRow; keepRow?: EachRow }> = [];
674
+ for (const r of items) {
675
+ const k = r.key!;
676
+ let keepRow: EachRow | undefined;
677
+ if (counts.get(k) === 1 && !used.has(k)) {
678
+ const cand = prev.get(k);
679
+ if (cand && normHtml(cand) === normHtml(r) && !EACH_REUSE_FORBID.test(r.html)) {
680
+ keepRow = cand;
681
+ used.add(k);
682
+ }
683
+ }
684
+ decisions.push({ row: r, keepRow });
685
+ if (keepRow) for (const nd of keepRow.nodes ?? []) keep.add(nd);
686
+ }
687
+ let n = start.nextSibling;
688
+ while (n && n !== end) {
689
+ const nx = n.nextSibling;
690
+ if (!keep.has(n)) n.remove();
691
+ n = nx;
692
+ }
693
+ const disps: Cleanup[] = [];
694
+ for (const d of decisions) {
695
+ if (d.keepRow) {
696
+ disps.push(d.keepRow.disp!);
697
+ nextMap.set(d.row.key!, d.keepRow);
698
+ for (const nd of d.keepRow.nodes ?? []) parent.insertBefore(nd, end);
699
+ } else {
700
+ const frag = tpl(d.row.html);
701
+ const disp = wire(frag, d.row.closes, d.row.scope);
702
+ disps.push(disp);
703
+ const nodes = Array.from(frag.childNodes);
704
+ for (const nd of nodes) parent.insertBefore(nd, end);
705
+ if (counts.get(d.row.key!) === 1) nextMap.set(d.row.key!, { ...d.row, nodes, disp });
706
+ }
707
+ }
708
+ st.__kmap = nextMap;
709
+ st.__disp = () => disps.forEach((d) => d());
710
+ return;
711
+ }
712
+ st.__kmap = undefined;
424
713
  let n = start.nextSibling;
425
714
  while (n && n !== end) {
426
715
  const nx = n.nextSibling;
427
716
  n.remove();
428
717
  n = nx;
429
718
  }
430
- const parent = start.parentNode!;
431
719
  const disps: Cleanup[] = [];
432
720
  for (const r of items) {
433
721
  const frag = tpl(r.html);
@@ -455,18 +743,557 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
455
743
  } else if (root.nodeType !== 11) clearHead();
456
744
  }
457
745
 
458
- const els = (holder as Element).querySelectorAll('[data-b]');
459
- els.forEach((el) => {
460
- const spec = el.getAttribute('data-b')!;
461
- const sep = spec.indexOf(':');
462
- const idx = +spec.slice(0, sep);
463
- const attr = spec.slice(sep + 1);
464
- el.removeAttribute('data-b');
465
- weff(() => {
466
- el.setAttribute(attr, String((closes[idx] as (s?: unknown) => unknown)(scope)));
467
- });
746
+ const all = (holder as Element).querySelectorAll('*');
747
+ all.forEach((el) => {
748
+ if (islandSkip && el.closest('[data-rv-island]')) return;
749
+ for (const an of el.getAttributeNames()) {
750
+ if (!an.startsWith('data-b')) continue;
751
+ const idx = Number(an.slice(6));
752
+ if (!Number.isFinite(idx)) continue;
753
+ const attr = el.getAttribute(an)!;
754
+ el.removeAttribute(an);
755
+ const effect = () => String((closes[idx] as (s?: unknown) => unknown)(scope));
756
+ if (attr === 'data-use-param') {
757
+ weff(() => {
758
+ const raw = effect();
759
+ let p: unknown = raw;
760
+ try { p = JSON.parse(raw); } catch { /* string param */ }
761
+ actionRecords.get(el)?.update?.(p);
762
+ });
763
+ continue;
764
+ }
765
+ if (attr === 'value') {
766
+ weff(() => {
767
+ const v = effect();
768
+ const out = v == null ? '' : v;
769
+ const inp = el as unknown as HTMLInputElement;
770
+ if (inp.value !== out) inp.value = out;
771
+ });
772
+ } else if (attr === 'data-selmulti') {
773
+ weff(() => {
774
+ const vals = effect().split(',');
775
+ for (const o of Array.from((el as unknown as HTMLSelectElement).options)) {
776
+ o.selected = vals.includes(o.value);
777
+ }
778
+ });
779
+ } else if (attr.startsWith('!')) {
780
+ const name = attr.slice(1);
781
+ weff(() => {
782
+ const v = (closes[idx] as (s?: unknown) => unknown)(scope);
783
+ const live = !(v === false || v == null || v === '' || v === 'false' || v === 0);
784
+ const target = el as unknown as Record<string, unknown>;
785
+ if (target[name] !== live) target[name] = live;
786
+ if (live) el.setAttribute(name, '');
787
+ else el.removeAttribute(name);
788
+ });
789
+ } else {
790
+ weff(() => {
791
+ const out = attrValueString(attr, (closes[idx] as (s?: unknown) => unknown)(scope));
792
+ if (el.getAttribute(attr) !== out) el.setAttribute(attr, out);
793
+ });
794
+ }
795
+ }
796
+ });
797
+
798
+ const uses = (holder as Element).querySelectorAll('[data-use]');
799
+ uses.forEach((el) => {
800
+ if (islandSkip && el.closest('[data-rv-island]')) return;
801
+ const name = el.getAttribute('data-use')!;
802
+ const fn = directives[name];
803
+ if (!fn) return;
804
+ const rawParam = el.getAttribute('data-use-param');
805
+ let initial: unknown = rawParam ?? undefined;
806
+ if (typeof initial === 'string') {
807
+ try { initial = JSON.parse(initial); } catch { /* plain string param */ }
808
+ }
809
+ const ret = fn(el, initial);
810
+ if (typeof ret === 'function') created.push(ret);
811
+ else if (ret && typeof ret === 'object') {
812
+ actionRecords.set(el, { update: ret.update, destroy: ret.destroy });
813
+ if (ret.destroy) created.push(ret.destroy);
814
+ }
815
+ });
816
+
817
+ const refs = (holder as Element).querySelectorAll('[data-bind-this]');
818
+ refs.forEach((el) => {
819
+ if (islandSkip && el.closest('[data-rv-island]')) return;
820
+ const key = el.getAttribute('data-bind-this')!;
821
+ setState(key, el);
822
+ created.push(() => setState(key, null));
468
823
  });
469
824
 
825
+ if ((holder as Element).querySelectorAll('[data-transition]').length > 0) {
826
+ const trans = (holder as Element).querySelectorAll('[data-transition]');
827
+ trans.forEach((el) => {
828
+ if (islandSkip && el.closest('[data-rv-island]')) return;
829
+ const transAttr = el.getAttribute('data-transition')!;
830
+ const parts = transAttr.split('|');
831
+ for (const part of parts) {
832
+ const segs = part.split(':');
833
+ const dir = segs[0] === 'in' || segs[0] === 'out' ? segs[0]! : '';
834
+ const name = (dir ? segs[1] : segs[0]) ?? '';
835
+ const pstr = (dir ? segs.slice(2) : segs.slice(1)).join(':');
836
+ const params = parseTransitionParams(pstr);
837
+ const duration = params.duration != null ? Number(params.duration) : 300;
838
+ if (dir === 'out') {
839
+ const pose = TRANSITION_POSES[name];
840
+ if (pose) {
841
+ const parent = el.parentElement;
842
+ const idx = parent ? Math.max(0, Array.from(parent.children).indexOf(el)) : 0;
843
+ const vDelay = params.delay != null ? Number(params.delay) : null;
844
+ const delay = name === 'stagger'
845
+ ? (vDelay != null ? Math.max(0, vDelay) : idx * (duration / 10))
846
+ : (vDelay != null ? vDelay : 0);
847
+ const easing = params.easing || 'ease';
848
+ created.push(() => {
849
+ const parts = [pose.transform ? `transform ${duration}ms ${easing} ${delay}ms` : '', pose.filter ? `filter ${duration}ms ${easing} ${delay}ms` : '', `opacity ${duration}ms ${easing} ${delay}ms`].filter(Boolean);
850
+ el.style.transition = parts.join(', ');
851
+ if (pose.transform) el.style.transform = pose.transform;
852
+ if (pose.filter) el.style.filter = pose.filter;
853
+ el.style.opacity = pose.opacity;
854
+ setTimeout(() => {
855
+ el.style.transform = '';
856
+ el.style.filter = '';
857
+ el.style.opacity = '';
858
+ el.style.transition = '';
859
+ }, duration + delay);
860
+ });
861
+ } else {
862
+ const custom = (globalThis as any).__rosetackTransitions?.[name];
863
+ if (custom) {
864
+ const ret = custom(el, duration, 'out');
865
+ if (typeof ret === 'function') created.push(ret);
866
+ }
867
+ }
868
+ continue;
869
+ }
870
+ const exitStart = created.length;
871
+ const pose = TRANSITION_POSES[name];
872
+ if (pose) {
873
+ const parent = el.parentElement;
874
+ const idx = parent ? Math.max(0, Array.from(parent.children).indexOf(el)) : 0;
875
+ const vDelay = params.delay != null ? Number(params.delay) : null;
876
+ const delay = name === 'stagger'
877
+ ? (vDelay != null ? Math.max(0, vDelay) : idx * (duration / 10))
878
+ : (vDelay != null ? vDelay : 0);
879
+ const easing = params.easing || 'ease';
880
+ const cssParts: string[] = [];
881
+ if (pose.transform) cssParts.push(`transform ${duration}ms ${easing} ${delay}ms`);
882
+ if (pose.filter) cssParts.push(`filter ${duration}ms ${easing} ${delay}ms`);
883
+ cssParts.push(`opacity ${duration}ms ${easing} ${delay}ms`);
884
+ const tcss = cssParts.join(', ');
885
+ el.style.opacity = '0';
886
+ if (pose.transform) el.style.transform = pose.transform;
887
+ if (pose.filter) el.style.filter = pose.filter;
888
+ el.style.transition = tcss;
889
+ requestAnimationFrame(() => {
890
+ requestAnimationFrame(() => {
891
+ el.style.transform = '';
892
+ el.style.filter = '';
893
+ el.style.opacity = '1';
894
+ });
895
+ });
896
+ created.push(() => {
897
+ el.style.opacity = '0';
898
+ if (pose.transform) el.style.transform = pose.transform;
899
+ if (pose.filter) el.style.filter = pose.filter;
900
+ setTimeout(() => {
901
+ el.style.opacity = '';
902
+ el.style.transform = '';
903
+ el.style.filter = '';
904
+ el.style.transition = '';
905
+ }, duration + delay);
906
+ });
907
+ } else {
908
+ const custom = (globalThis as any).__rosetackTransitions?.[name];
909
+ if (custom) {
910
+ const ret = custom(el, duration, dir || 'both');
911
+ if (typeof ret === 'function') created.push(ret);
912
+ }
913
+ }
914
+ if (dir === 'in') created.length = exitStart;
915
+ }
916
+ });
917
+ }
918
+
919
+ if ((holder as Element).querySelectorAll('[data-animate]').length > 0) {
920
+ const anim = (holder as Element).querySelectorAll('[data-animate]');
921
+ anim.forEach((el) => {
922
+ if (islandSkip && el.closest('[data-rv-island]')) return;
923
+ const animAttr = el.getAttribute('data-animate')!;
924
+ const parts = animAttr.split('|');
925
+ for (const part of parts) {
926
+ const [name] = part.split(':');
927
+ const rest = part.slice(name.length + 1);
928
+ const duration = Number((/(\d+)\s*\}?\s*$/.exec(rest) ?? [])[1]) || 300;
929
+ if (name === 'flip') {
930
+ const firstRect = el.getBoundingClientRect();
931
+ const firstTop = firstRect.top;
932
+ const firstLeft = firstRect.left;
933
+ requestAnimationFrame(() => {
934
+ requestAnimationFrame(() => {
935
+ const lastRect = el.getBoundingClientRect();
936
+ const deltaTop = lastRect.top - firstTop;
937
+ const deltaLeft = lastRect.left - firstLeft;
938
+ if (Math.abs(deltaTop) < 0.5 && Math.abs(deltaLeft) < 0.5) return;
939
+ el.style.transform = `translate(${-deltaLeft}px, ${-deltaTop}px)`;
940
+ el.style.transition = 'none';
941
+ requestAnimationFrame(() => {
942
+ requestAnimationFrame(() => {
943
+ el.style.transition = `transform ${duration}ms ease`;
944
+ el.style.transform = '';
945
+ });
946
+ });
947
+ });
948
+ });
949
+ } else if (name === 'pulse') {
950
+ el.style.transform = 'scale(1)';
951
+ el.style.transition = `transform ${duration}ms ease`;
952
+ requestAnimationFrame(() => {
953
+ requestAnimationFrame(() => {
954
+ el.style.transform = 'scale(1.1)';
955
+ setTimeout(() => {
956
+ el.style.transform = 'scale(1)';
957
+ }, duration);
958
+ });
959
+ });
960
+ } else if (name === 'bounce') {
961
+ el.style.transform = 'translateY(0)';
962
+ el.style.transition = `transform ${duration}ms ease`;
963
+ requestAnimationFrame(() => {
964
+ requestAnimationFrame(() => {
965
+ el.style.transform = 'translateY(-15px)';
966
+ setTimeout(() => {
967
+ el.style.transform = 'translateY(0)';
968
+ }, duration);
969
+ });
970
+ });
971
+ } else if (name === 'shake') {
972
+ el.style.transform = 'translateX(0)';
973
+ el.style.transition = `transform ${duration / 4}ms ease-in-out`;
974
+ requestAnimationFrame(() => {
975
+ requestAnimationFrame(() => {
976
+ el.style.transform = 'translateX(-8px)';
977
+ setTimeout(() => {
978
+ el.style.transform = 'translateX(8px)';
979
+ setTimeout(() => {
980
+ el.style.transform = 'translateX(-8px)';
981
+ setTimeout(() => {
982
+ el.style.transform = 'translateX(8px)';
983
+ setTimeout(() => {
984
+ el.style.transform = 'translateX(0)';
985
+ el.style.transition = '';
986
+ }, duration / 4);
987
+ }, duration / 4);
988
+ }, duration / 4);
989
+ }, duration / 4);
990
+ }, duration / 4);
991
+ });
992
+ } else if (name === 'scale') {
993
+ el.style.transform = 'scale(0.5)';
994
+ el.style.opacity = '0';
995
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
996
+ requestAnimationFrame(() => {
997
+ requestAnimationFrame(() => {
998
+ el.style.transform = '';
999
+ el.style.opacity = '1';
1000
+ });
1001
+ });
1002
+ created.push(() => {
1003
+ el.style.transform = 'scale(0.5)';
1004
+ el.style.opacity = '0';
1005
+ setTimeout(() => {
1006
+ el.style.transform = '';
1007
+ el.style.opacity = '';
1008
+ el.style.transition = '';
1009
+ }, duration);
1010
+ });
1011
+ } else if (name === 'rotate') {
1012
+ el.style.transform = 'rotate(-180deg)';
1013
+ el.style.opacity = '0';
1014
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1015
+ requestAnimationFrame(() => {
1016
+ requestAnimationFrame(() => {
1017
+ el.style.transform = '';
1018
+ el.style.opacity = '1';
1019
+ });
1020
+ });
1021
+ created.push(() => {
1022
+ el.style.transform = 'rotate(-180deg)';
1023
+ el.style.opacity = '0';
1024
+ setTimeout(() => {
1025
+ el.style.transform = '';
1026
+ el.style.opacity = '';
1027
+ el.style.transition = '';
1028
+ }, duration);
1029
+ });
1030
+ } else if (name === 'fade-in') {
1031
+ el.style.opacity = '0';
1032
+ el.style.transition = `opacity ${duration}ms ease`;
1033
+ requestAnimationFrame(() => {
1034
+ requestAnimationFrame(() => {
1035
+ el.style.opacity = '1';
1036
+ });
1037
+ });
1038
+ created.push(() => {
1039
+ el.style.opacity = '0';
1040
+ setTimeout(() => {
1041
+ el.style.opacity = '';
1042
+ el.style.transition = '';
1043
+ }, duration);
1044
+ });
1045
+ } else if (name === 'fade-out') {
1046
+ el.style.opacity = '1';
1047
+ el.style.transition = `opacity ${duration}ms ease`;
1048
+ requestAnimationFrame(() => {
1049
+ requestAnimationFrame(() => {
1050
+ el.style.opacity = '0';
1051
+ });
1052
+ });
1053
+ created.push(() => {
1054
+ el.style.opacity = '1';
1055
+ setTimeout(() => {
1056
+ el.style.opacity = '';
1057
+ el.style.transition = '';
1058
+ }, duration);
1059
+ });
1060
+ } else if (name === 'stagger') {
1061
+ const parent = el.parentElement;
1062
+ if (parent) {
1063
+ const siblings = Array.from(parent.children);
1064
+ const index = siblings.indexOf(el);
1065
+ const delay = index * (duration / 10);
1066
+ el.style.opacity = '0';
1067
+ el.style.transform = 'translateY(10px)';
1068
+ el.style.transition = `opacity ${duration}ms ease ${delay}ms, transform ${duration}ms ease ${delay}ms`;
1069
+ requestAnimationFrame(() => {
1070
+ requestAnimationFrame(() => {
1071
+ el.style.opacity = '1';
1072
+ el.style.transform = '';
1073
+ });
1074
+ });
1075
+ created.push(() => {
1076
+ el.style.opacity = '0';
1077
+ el.style.transform = 'translateY(10px)';
1078
+ setTimeout(() => {
1079
+ el.style.opacity = '';
1080
+ el.style.transform = '';
1081
+ el.style.transition = '';
1082
+ }, duration + delay);
1083
+ });
1084
+ }
1085
+ } else if (name === 'zoom-in') {
1086
+ el.style.transform = 'scale(0)';
1087
+ el.style.opacity = '0';
1088
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1089
+ requestAnimationFrame(() => {
1090
+ requestAnimationFrame(() => {
1091
+ el.style.transform = '';
1092
+ el.style.opacity = '1';
1093
+ });
1094
+ });
1095
+ created.push(() => {
1096
+ el.style.transform = 'scale(0)';
1097
+ el.style.opacity = '0';
1098
+ setTimeout(() => {
1099
+ el.style.transform = '';
1100
+ el.style.opacity = '';
1101
+ el.style.transition = '';
1102
+ }, duration);
1103
+ });
1104
+ } else if (name === 'zoom-out') {
1105
+ el.style.transform = 'scale(1)';
1106
+ el.style.opacity = '1';
1107
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1108
+ requestAnimationFrame(() => {
1109
+ requestAnimationFrame(() => {
1110
+ el.style.transform = 'scale(0)';
1111
+ el.style.opacity = '0';
1112
+ });
1113
+ });
1114
+ created.push(() => {
1115
+ el.style.transform = 'scale(1)';
1116
+ el.style.opacity = '1';
1117
+ setTimeout(() => {
1118
+ el.style.transform = '';
1119
+ el.style.opacity = '';
1120
+ el.style.transition = '';
1121
+ }, duration);
1122
+ });
1123
+ } else if (name === 'slide-up-fade') {
1124
+ el.style.transform = 'translateY(30px)';
1125
+ el.style.opacity = '0';
1126
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1127
+ requestAnimationFrame(() => {
1128
+ requestAnimationFrame(() => {
1129
+ el.style.transform = '';
1130
+ el.style.opacity = '1';
1131
+ });
1132
+ });
1133
+ created.push(() => {
1134
+ el.style.transform = 'translateY(30px)';
1135
+ el.style.opacity = '0';
1136
+ setTimeout(() => {
1137
+ el.style.transform = '';
1138
+ el.style.opacity = '';
1139
+ el.style.transition = '';
1140
+ }, duration);
1141
+ });
1142
+ } else if (name === 'slide-down-fade') {
1143
+ el.style.transform = 'translateY(-30px)';
1144
+ el.style.opacity = '0';
1145
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1146
+ requestAnimationFrame(() => {
1147
+ requestAnimationFrame(() => {
1148
+ el.style.transform = '';
1149
+ el.style.opacity = '1';
1150
+ });
1151
+ });
1152
+ created.push(() => {
1153
+ el.style.transform = 'translateY(-30px)';
1154
+ el.style.opacity = '0';
1155
+ setTimeout(() => {
1156
+ el.style.transform = '';
1157
+ el.style.opacity = '';
1158
+ el.style.transition = '';
1159
+ }, duration);
1160
+ });
1161
+ } else if (name === 'flip-x') {
1162
+ el.style.transform = 'rotateX(90deg)';
1163
+ el.style.opacity = '0';
1164
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1165
+ requestAnimationFrame(() => {
1166
+ requestAnimationFrame(() => {
1167
+ el.style.transform = '';
1168
+ el.style.opacity = '1';
1169
+ });
1170
+ });
1171
+ created.push(() => {
1172
+ el.style.transform = 'rotateX(90deg)';
1173
+ el.style.opacity = '0';
1174
+ setTimeout(() => {
1175
+ el.style.transform = '';
1176
+ el.style.opacity = '';
1177
+ el.style.transition = '';
1178
+ }, duration);
1179
+ });
1180
+ } else if (name === 'flip-y') {
1181
+ el.style.transform = 'rotateY(90deg)';
1182
+ el.style.opacity = '0';
1183
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1184
+ requestAnimationFrame(() => {
1185
+ requestAnimationFrame(() => {
1186
+ el.style.transform = '';
1187
+ el.style.opacity = '1';
1188
+ });
1189
+ });
1190
+ created.push(() => {
1191
+ el.style.transform = 'rotateY(90deg)';
1192
+ el.style.opacity = '0';
1193
+ setTimeout(() => {
1194
+ el.style.transform = '';
1195
+ el.style.opacity = '';
1196
+ el.style.transition = '';
1197
+ }, duration);
1198
+ });
1199
+ } else if (name === 'spin') {
1200
+ el.style.transform = 'rotate(-360deg)';
1201
+ el.style.opacity = '0';
1202
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1203
+ requestAnimationFrame(() => {
1204
+ requestAnimationFrame(() => {
1205
+ el.style.transform = '';
1206
+ el.style.opacity = '1';
1207
+ });
1208
+ });
1209
+ created.push(() => {
1210
+ el.style.transform = 'rotate(-360deg)';
1211
+ el.style.opacity = '0';
1212
+ setTimeout(() => {
1213
+ el.style.transform = '';
1214
+ el.style.opacity = '';
1215
+ el.style.transition = '';
1216
+ }, duration);
1217
+ });
1218
+ } else if (name === 'pop') {
1219
+ el.style.transform = 'scale(0.3)';
1220
+ el.style.opacity = '0';
1221
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1222
+ requestAnimationFrame(() => {
1223
+ requestAnimationFrame(() => {
1224
+ el.style.transform = 'scale(1.1)';
1225
+ setTimeout(() => {
1226
+ el.style.transform = '';
1227
+ }, duration / 3);
1228
+ });
1229
+ });
1230
+ created.push(() => {
1231
+ el.style.transform = 'scale(0.3)';
1232
+ el.style.opacity = '0';
1233
+ setTimeout(() => {
1234
+ el.style.transform = '';
1235
+ el.style.opacity = '';
1236
+ el.style.transition = '';
1237
+ }, duration);
1238
+ });
1239
+ } else if (name === 'blink') {
1240
+ el.style.opacity = '0';
1241
+ el.style.transition = `opacity ${duration}ms ease`;
1242
+ requestAnimationFrame(() => {
1243
+ requestAnimationFrame(() => {
1244
+ el.style.opacity = '1';
1245
+ });
1246
+ });
1247
+ created.push(() => {
1248
+ el.style.opacity = '0';
1249
+ setTimeout(() => {
1250
+ el.style.opacity = '';
1251
+ el.style.transition = '';
1252
+ }, duration);
1253
+ });
1254
+ }
1255
+ }
1256
+ });
1257
+ }
1258
+
1259
+ const DELEGATED_SET = new Set(['click', 'input', 'change', 'submit']);
1260
+ const evRoot = holder as Element;
1261
+ const evTargets = [evRoot, ...Array.from(evRoot.querySelectorAll('*'))];
1262
+ for (const el of evTargets) {
1263
+ if (!el.getAttributeNames) continue;
1264
+ if (islandSkip && el.closest && el.closest('[data-rv-island]')) continue;
1265
+ for (const an of el.getAttributeNames()) {
1266
+ const mm = /^data-on(w|d)?-(.+)$/.exec(an);
1267
+ if (!mm) continue;
1268
+ const ev = mm[2];
1269
+ if (!mm[1] && DELEGATED_SET.has(ev)) continue;
1270
+ const g = globalThis as { window?: EventTarget; document?: { defaultView?: EventTarget } & EventTarget };
1271
+ const win = g.window ?? g.document?.defaultView;
1272
+ const target: EventTarget | undefined = mm[1] === 'w' ? win : mm[1] === 'd' ? (g.document as EventTarget) : el;
1273
+ if (!target) continue;
1274
+ let seen = directBound.get(el);
1275
+ if (!seen) directBound.set(el, (seen = new Set()));
1276
+ if (seen.has(ev)) continue;
1277
+ seen.add(ev);
1278
+ const spec = el.getAttribute(an)!;
1279
+ const listener = (e: Event) => {
1280
+ if (!el.hasAttribute(an)) return;
1281
+ if (spec.startsWith('$action:')) {
1282
+ if (actionDispatch) actionDispatch(spec.slice('$action:'.length), e);
1283
+ return;
1284
+ }
1285
+ const h = handlers[spec];
1286
+ if (h) h(e);
1287
+ };
1288
+ target.addEventListener(ev, listener, ev === 'scroll' ? { passive: true } : undefined);
1289
+ created.push(() => {
1290
+ target.removeEventListener(ev, listener);
1291
+ const s = directBound.get(el);
1292
+ if (s) s.delete(ev);
1293
+ });
1294
+ }
1295
+ }
1296
+
470
1297
  if (holder !== root) {
471
1298
  while (holder.firstChild) root.appendChild(holder.firstChild);
472
1299
  }
@@ -477,24 +1304,60 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
477
1304
  export function resetEffects(): void {
478
1305
  cleanups.forEach((fn) => fn());
479
1306
  cleanups.clear();
1307
+ pendingIslandObservers.forEach((io) => io.disconnect());
1308
+ pendingIslandObservers.clear();
480
1309
  }
481
1310
 
482
- let dataCache = new Map<string, Promise<unknown>>();
483
-
484
1311
  export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
1312
+ const cache = renderMaps().data;
485
1313
  const key = fn.toString();
486
- let p = dataCache.get(key);
1314
+ let p = cache.get(key);
487
1315
  if (!p) {
488
1316
  p = Promise.resolve(fn());
489
- dataCache.set(key, p);
1317
+ cache.set(key, p);
490
1318
  }
491
1319
  return p as Promise<T>;
492
1320
  }
493
1321
 
494
1322
  export function clearRequestState(): void {
495
1323
  signalMap.clear();
496
- dataCache.clear();
1324
+ renderMaps().data.clear();
497
1325
  pendingDeltas.clear();
1326
+ seededKeys = new Set();
1327
+ }
1328
+
1329
+ /**
1330
+ * Run `fn` with request state no other in-flight render can observe or
1331
+ * destroy, then restore the caller's state.
1332
+ *
1333
+ * signalMap is a process-wide singleton (deliberate - every inlined module
1334
+ * shares one map), which is only safe while renders never overlap. They
1335
+ * DO overlap: prod-server warms every route in the background at startup, and
1336
+ * renderPageCached revalidates a stale cache entry in the background while the
1337
+ * foreground request is still streaming. Each of those renders used to open
1338
+ * with clearRequestState(), wiping whichever render was in flight; the
1339
+ * survivor then saw hasState()===true for a key it never seeded and
1340
+ * dereferenced the other render's null - "Cannot read properties of null
1341
+ * (reading 'bodyFix')", a 500 that hits a cold route and clears on refresh.
1342
+ *
1343
+ * Isolating here makes concurrent renders correct rather than merely unlikely.
1344
+ * Two different mechanisms, because they fail differently: signalMap is
1345
+ * swapped and restored (it is synchronous to read, and its entries are keyed
1346
+ * per state key), while dataCache rides the async chain instead - see
1347
+ * renderMaps() for why a swap there was not isolation at all.
1348
+ */
1349
+ export async function isolateRender<T>(fn: () => Promise<T>): Promise<T> {
1350
+ const savedSignals = signalMap;
1351
+ const savedSeeded = seededKeys;
1352
+ signalMap = new Map();
1353
+ seededKeys = new Set();
1354
+ renderMaps().data.clear();
1355
+ try {
1356
+ return await fn();
1357
+ } finally {
1358
+ signalMap = savedSignals;
1359
+ seededKeys = savedSeeded;
1360
+ }
498
1361
  }
499
1362
 
500
1363
  let requestQuery: Record<string, string> = {};
@@ -520,13 +1383,97 @@ export function setPrefetchOverride(q: Record<string, string> | null): void {
520
1383
 
521
1384
  let requestContext: Record<string, unknown> = {};
522
1385
 
1386
+ /** Pluggable per-async-chain store; see the comment above. */
1387
+ type ContextStore = {
1388
+ getStore(): Record<string, unknown> | undefined;
1389
+ run<T>(store: Record<string, unknown>, fn: () => T): T;
1390
+ };
1391
+ let contextStore: ContextStore | null = null;
1392
+
1393
+ /**
1394
+ * The render-local maps for the CURRENT async chain.
1395
+ *
1396
+ * isolateRender() used to swap module-level `dataCache` / `signalMap` and
1397
+ * restore them in a finally. That is not isolation, it is a rename: `await`
1398
+ * yields, so two overlapping renders interleave and the second one saves the
1399
+ * FIRST one's fresh map as its "saved" value. Concretely, with A and B running:
1400
+ *
1401
+ * A: saved = D0; dataCache = DA
1402
+ * B: saved = DA; dataCache = DB <- A's writes now land in DB
1403
+ * A: restore dataCache = D0
1404
+ * B: restore dataCache = DA <- and A's map is live again
1405
+ *
1406
+ * So A and B shared one $data map, and $data is keyed on the thunk SOURCE
1407
+ * ALONE (the payload is not part of the key). Two renders of different paths
1408
+ * therefore shared one `chrome()` promise, and the second one was served the
1409
+ * first one's header - which is how the home page could come back with no menu
1410
+ * item highlighted, on roughly two cold starts out of three, while a warm
1411
+ * process was always correct.
1412
+ *
1413
+ * The fix is the same shape as the request context bag: keep the maps on the
1414
+ * async chain. Under a context store each request gets its own; without one
1415
+ * (edge, client) this is the single-render fallback and the old behaviour is
1416
+ * correct anyway.
1417
+ */
1418
+ const RENDER_MAPS = Symbol('renderMaps');
1419
+ type RenderMaps = { data: Map<string, Promise<unknown>>; signals: Map<string, unknown>; seeded: Set<string> };
1420
+ let fallbackRenderMaps: RenderMaps = { data: new Map(), signals: new Map(), seeded: new Set() };
1421
+
1422
+ function renderMaps(): RenderMaps {
1423
+ const scoped = contextStore?.getStore();
1424
+ if (!scoped) return fallbackRenderMaps;
1425
+ let m = scoped[RENDER_MAPS] as RenderMaps | undefined;
1426
+ if (!m) {
1427
+ m = { data: new Map(), signals: new Map(), seeded: new Set() };
1428
+ scoped[RENDER_MAPS] = m;
1429
+ }
1430
+ return m;
1431
+ }
1432
+
1433
+ /**
1434
+ * Install the async-local context store (Node passes an AsyncLocalStorage
1435
+ * adapter). Pass null to return to the module-level bag.
1436
+ */
1437
+ export function installContextStore(store: ContextStore | null): void {
1438
+ contextStore = store;
1439
+ }
1440
+
523
1441
  export function getContext(): Record<string, unknown> {
524
- return requestContext;
1442
+ const scoped = contextStore?.getStore();
1443
+ return scoped ?? requestContext;
525
1444
  }
526
1445
 
527
- /** Fresh bag for a new request - runMiddleware() calls this before the middleware. */
1446
+ /**
1447
+ * Fresh bag for a new request - runMiddleware() calls this before the
1448
+ * middleware. Under a context store it must NOT assign the module-level
1449
+ * variable (that is the shared-state bug); it clears the current scope's bag
1450
+ * in place so the object identity the store handed out stays valid.
1451
+ */
528
1452
  export function resetRequestContext(): void {
1453
+ if (contextStore) {
1454
+ const scoped = contextStore.getStore();
1455
+ if (scoped) {
1456
+ for (const k of Object.keys(scoped)) delete scoped[k];
1457
+ return;
1458
+ }
1459
+ }
1460
+ requestContext = {};
1461
+ }
1462
+
1463
+ /**
1464
+ * Run `fn` inside its own context bag. A Node host calls this around each
1465
+ * request; without a store this degrades to a save/restore of the module-level
1466
+ * bag, which is what the pre-AsyncLocalStorage code did.
1467
+ */
1468
+ export function runWithContext<T>(fn: () => T): T {
1469
+ if (contextStore) return contextStore.run({}, fn);
1470
+ const saved = requestContext;
529
1471
  requestContext = {};
1472
+ try {
1473
+ return fn();
1474
+ } finally {
1475
+ requestContext = saved;
1476
+ }
530
1477
  }
531
1478
 
532
1479
  /**
@@ -550,14 +1497,13 @@ export async function isolateStateAsync<T>(
550
1497
  fn: () => Promise<T>
551
1498
  ): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
552
1499
  const savedSignals = signalMap;
553
- const savedData = dataCache;
554
1500
  const savedDeltas = new Map(pendingDeltas);
555
1501
  pendingDeltas.clear();
556
1502
  const savedMounts = mountQueue.splice(0, mountQueue.length);
557
1503
  const savedCleanups = new Set(cleanups);
558
1504
  cleanups.clear();
559
1505
  signalMap = new Map();
560
- dataCache = new Map();
1506
+ renderMaps().data.clear();
561
1507
  try {
562
1508
  const result = await fn();
563
1509
  return {
@@ -568,7 +1514,6 @@ export async function isolateStateAsync<T>(
568
1514
  };
569
1515
  } finally {
570
1516
  signalMap = savedSignals;
571
- dataCache = savedData;
572
1517
  pendingDeltas.clear();
573
1518
  savedDeltas.forEach((d, k) => pendingDeltas.set(k, d));
574
1519
  mountQueue.splice(0, 0, ...savedMounts);
@@ -594,6 +1539,7 @@ export function resumeState(json: string): void {
594
1539
  const obj = JSON.parse(json);
595
1540
  Object.entries(obj).forEach(([k, v]) => {
596
1541
  entry(k, v).value = v;
1542
+ seededKeys.add(k);
597
1543
  });
598
1544
  } catch {
599
1545
  // ignore corrupt state
@@ -872,10 +1818,18 @@ export type ActionErrorInfo = { action: string; message: string; code: number; f
872
1818
  * Read it as data (`{#if $actionError()}<p>{$actionError().message}</p>{/if}`)
873
1819
  * or let a {#boundary} contain it ($actionErrorOrThrow below).
874
1820
  */
1821
+ export function $actionPending(): boolean {
1822
+ const entry = signalMap.get('actionPending');
1823
+ return entry ? entry.value === true : false;
1824
+ }
1825
+
875
1826
  export function $actionError(): ActionErrorInfo | null {
876
1827
  const e = signalMap.get('actionError');
877
1828
  if (!e) return null;
878
- if (currentEffect) e.subs.add(currentEffect);
1829
+ if (currentEffect) {
1830
+ e.subs.add(currentEffect);
1831
+ if (trackingDeps) trackingDeps.add(e);
1832
+ }
879
1833
  return (e.value as ActionErrorInfo | null) ?? null;
880
1834
  }
881
1835
 
@@ -903,10 +1857,10 @@ export class StateDelta {
903
1857
  }
904
1858
 
905
1859
  /** Append (or prepend) items to a list-valued state key. */
906
- export const $append = (value: unknown): StateDelta => new StateDelta('append', value);
907
- export const $prepend = (value: unknown): StateDelta => new StateDelta('prepend', value);
1860
+ export const $append = (value: unknown): StateDelta => new StateDelta('a', value);
1861
+ export const $prepend = (value: unknown): StateDelta => new StateDelta('p', value);
908
1862
  /** Shallow-merge an object into an object-valued state key. */
909
- export const $merge = (value: Record<string, unknown>): StateDelta => new StateDelta('merge', value);
1863
+ export const $merge = (value: Record<string, unknown>): StateDelta => new StateDelta('m', value);
910
1864
 
911
1865
  const pendingDeltas = new Map<string, StateDelta>();
912
1866
 
@@ -915,15 +1869,7 @@ export function setStateDelta(key: string, delta: StateDelta): void {
915
1869
  pendingDeltas.set(key, delta);
916
1870
  }
917
1871
 
918
- /**
919
- * Apply every pending delta to the live state and clear them. The generated
920
- * render calls this once, right after its state declarations - and only the
921
- * SSR side ever emits the call: a delta is recorded by a server dispatch, so
922
- * on the client (post-adopt re-render, client-side navigation, refresh) the
923
- * map is empty and this is a no-op. That is also why a delta can never apply
924
- * twice: the value it produced is what the state script carried, and the
925
- * client resumes THAT instead of recomputing it.
926
- */
1872
+ /** Apply every pending delta to the live state and clear them. */
927
1873
  export function applyStateDeltas(): void {
928
1874
  if (pendingDeltas.size === 0) return;
929
1875
  for (const [key, delta] of [...pendingDeltas]) {
@@ -935,13 +1881,12 @@ export function applyStateDeltas(): void {
935
1881
  /** Apply one delta to the live state. */
936
1882
  export function applyStateDelta(key: string, delta: StateDelta): void {
937
1883
  const cur = signalMap.get(key)?.value;
938
- if (delta.op === 'merge') {
1884
+ if (delta.op === 'm') {
939
1885
  setState(key, { ...(cur as Record<string, unknown> | undefined), ...(delta.value as Record<string, unknown>) });
940
1886
  return;
941
1887
  }
942
1888
  const list = (v: unknown): unknown[] => (v == null ? [] : Array.isArray(v) ? v : [v]);
943
- const merged =
944
- delta.op === 'append' ? [...list(cur), ...list(delta.value)] : [...list(delta.value), ...list(cur)];
1889
+ const merged = delta.op === 'a' ? [...list(cur), ...list(delta.value)] : [...list(delta.value), ...list(cur)];
945
1890
  setState(key, merged);
946
1891
  }
947
1892