@torpor/view 1.3.2 → 1.4.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 (60) hide show
  1. package/dist/{Effect-99HYQdzZ.d.mts → Effect-Bi_nt6cx.d.cts} +31 -3
  2. package/dist/Effect-Bi_nt6cx.d.cts.map +1 -0
  3. package/dist/{Effect-Bf8fz_zC.d.cts → Effect-Bi_nt6cx.d.mts} +31 -3
  4. package/dist/Effect-Bi_nt6cx.d.mts.map +1 -0
  5. package/dist/ListItemSpec-DFkYr2TE.d.cts +28 -0
  6. package/dist/ListItemSpec-DFkYr2TE.d.cts.map +1 -0
  7. package/dist/ListItemSpec-DFkYr2TE.d.mts +28 -0
  8. package/dist/ListItemSpec-DFkYr2TE.d.mts.map +1 -0
  9. package/dist/{AsyncOptions-BDtArmeL.d.mts → WatchOptions--xq-Gn4e.d.cts} +77 -4
  10. package/dist/WatchOptions--xq-Gn4e.d.cts.map +1 -0
  11. package/dist/{AsyncOptions-C_7mWR6F.d.cts → WatchOptions-DWF4EqB6.d.mts} +77 -4
  12. package/dist/WatchOptions-DWF4EqB6.d.mts.map +1 -0
  13. package/dist/compile.cjs +1316 -400
  14. package/dist/compile.d.cts +16 -12
  15. package/dist/compile.d.cts.map +1 -1
  16. package/dist/compile.d.mts +16 -12
  17. package/dist/compile.d.mts.map +1 -1
  18. package/dist/compile.mjs +1316 -400
  19. package/dist/compile.mjs.map +1 -1
  20. package/dist/dev.cjs +101 -51
  21. package/dist/dev.d.cts +33 -2
  22. package/dist/dev.d.cts.map +1 -1
  23. package/dist/dev.d.mts +33 -2
  24. package/dist/dev.d.mts.map +1 -1
  25. package/dist/dev.mjs +51 -2
  26. package/dist/dev.mjs.map +1 -1
  27. package/dist/{fromWebSocket-ERhd9KZR.mjs → fromWebSocket-B22DIys7.mjs} +11 -2
  28. package/dist/fromWebSocket-B22DIys7.mjs.map +1 -0
  29. package/dist/{fromWebSocket-Cdoghvmh.cjs → fromWebSocket-C56rkQpZ.cjs} +15 -0
  30. package/dist/index.cjs +621 -269
  31. package/dist/index.d.cts +36 -129
  32. package/dist/index.d.cts.map +1 -1
  33. package/dist/index.d.mts +36 -129
  34. package/dist/index.d.mts.map +1 -1
  35. package/dist/index.mjs +609 -258
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/runtime.iife.js +1 -1
  38. package/dist/ssr.cjs +122 -22
  39. package/dist/ssr.d.cts +46 -12
  40. package/dist/ssr.d.cts.map +1 -1
  41. package/dist/ssr.d.mts +46 -12
  42. package/dist/ssr.d.mts.map +1 -1
  43. package/dist/ssr.mjs +121 -23
  44. package/dist/ssr.mjs.map +1 -1
  45. package/dist/titleWarning-BMjLAXpn.mjs +72 -0
  46. package/dist/titleWarning-BMjLAXpn.mjs.map +1 -0
  47. package/dist/titleWarning-DXp4fK7q.cjs +87 -0
  48. package/package.json +2 -1
  49. package/dist/AsyncOptions-BDtArmeL.d.mts.map +0 -1
  50. package/dist/AsyncOptions-C_7mWR6F.d.cts.map +0 -1
  51. package/dist/Cleanup-D0wvGW5d.d.cts +0 -9
  52. package/dist/Cleanup-D0wvGW5d.d.cts.map +0 -1
  53. package/dist/Cleanup-D0wvGW5d.d.mts +0 -9
  54. package/dist/Cleanup-D0wvGW5d.d.mts.map +0 -1
  55. package/dist/Effect-99HYQdzZ.d.mts.map +0 -1
  56. package/dist/Effect-Bf8fz_zC.d.cts.map +0 -1
  57. package/dist/devContext-BulTn3U5.cjs +0 -27
  58. package/dist/devContext-ZNsPyOgB.mjs +0 -24
  59. package/dist/devContext-ZNsPyOgB.mjs.map +0 -1
  60. package/dist/fromWebSocket-ERhd9KZR.mjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_devContext = require("./devContext-BulTn3U5.cjs");
3
- const require_fromWebSocket = require("./fromWebSocket-Cdoghvmh.cjs");
2
+ const require_titleWarning = require("./titleWarning-DXp4fK7q.cjs");
3
+ const require_fromWebSocket = require("./fromWebSocket-C56rkQpZ.cjs");
4
4
  //#region src/render/context.ts
5
5
  const CONTEXT_SYMBOL = Symbol.for("torp.Context");
6
6
  const context = globalThis[CONTEXT_SYMBOL] ??= {
@@ -8,7 +8,6 @@ const context = globalThis[CONTEXT_SYMBOL] ??= {
8
8
  previousEffect: null,
9
9
  extent: 0,
10
10
  batch: 0,
11
- batchOperation: 0,
12
11
  registerComputed: null,
13
12
  effectsToRun: [],
14
13
  firstSignalToUpdate: null,
@@ -24,98 +23,11 @@ const context = globalThis[CONTEXT_SYMBOL] ??= {
24
23
  mountEffects: [],
25
24
  stashedEvents: [],
26
25
  stashedAnimations: [],
26
+ runAnimations: null,
27
27
  hydrationNode: null,
28
28
  serverValues: null
29
29
  };
30
30
  //#endregion
31
- //#region src/render/addAnimation.ts
32
- function addAnimation(el, entry, exit) {
33
- context.stashedAnimations.push({
34
- region: context.activeRegion,
35
- el,
36
- in: entry,
37
- out: exit
38
- });
39
- }
40
- //#endregion
41
- //#region src/render/addEvent.ts
42
- function addEvent(el, type, listener) {
43
- if (listener !== void 0 && listener !== null) context.stashedEvents.push({
44
- el,
45
- type,
46
- listener
47
- });
48
- }
49
- //#endregion
50
- //#region src/render/isTextNode.ts
51
- function isTextNode(node) {
52
- return node.nodeType === 3;
53
- }
54
- const HYDRATION_BREAK_REGEX = /^\^(?:\d+)?$/;
55
- /**
56
- * Whether a comment node's data is a branch-break marker (`^`, or `^<index>`
57
- * when the server recorded the branch it rendered).
58
- */
59
- function isHydrationBreak(data) {
60
- return HYDRATION_BREAK_REGEX.test(data);
61
- }
62
- /**
63
- * The branch index encoded in a `^<index>` branch-break marker, or `undefined`
64
- * for a plain `^` marker (e.g. from `@for`, which has no branch index).
65
- */
66
- function hydrationBreakIndex(data) {
67
- if (!data.startsWith("^") || data.length === 1) return;
68
- const index = Number(data.slice(1));
69
- return Number.isNaN(index) ? void 0 : index;
70
- }
71
- //#endregion
72
- //#region src/render/isCommentNode.ts
73
- function isCommentNode(node) {
74
- return node.nodeType === 8;
75
- }
76
- //#endregion
77
- //#region src/render/nodeCheckHydrationBreak.ts
78
- /**
79
- * When hydrating, removes and skips hydration comments that are inserted at the
80
- * start of branches and used to split up text nodes that would otherwise be
81
- * joined in HTML.
82
- *
83
- * @param node The node to check and maybe skip.
84
- * @returns The next node.
85
- */
86
- function nodeCheckHydrationBreak(node) {
87
- if (node !== null && isCommentNode(node) && isHydrationBreak(node.data)) {
88
- let comment = node;
89
- node = node.nextSibling;
90
- comment.remove();
91
- }
92
- context.hydrationNode = node;
93
- return node;
94
- }
95
- //#endregion
96
- //#region src/render/nodeNext.ts
97
- /**
98
- * Gets the next sibling of a node.
99
- *
100
- * When hydrating, sets the hydration node.
101
- *
102
- * @param node The node.
103
- * @param text Whether we require a text node.
104
- */
105
- function nodeNext(node, text = false) {
106
- if (context.hydrationNode !== null) {
107
- if (text && isTextNode(node)) return node;
108
- let next = nodeCheckHydrationBreak(node.nextSibling);
109
- while (!text && next !== null && isTextNode(next) && next.textContent?.trim() === "") next = nodeCheckHydrationBreak(next.nextSibling);
110
- if (!text && next !== null && next.nodeName === "TBODY" && next.firstChild && isTextNode(node)) {
111
- next = next.firstChild;
112
- context.hydrationNode = next;
113
- }
114
- return next;
115
- }
116
- return node.nextSibling;
117
- }
118
- //#endregion
119
31
  //#region src/dev/devAssert.ts
120
32
  /**
121
33
  * Throws when `condition` is false — but only when dev mode is enabled (the
@@ -130,7 +42,7 @@ function nodeNext(node, text = false) {
130
42
  * @param message What the violation means — the thrown error's message.
131
43
  */
132
44
  function devAssert(condition, message) {
133
- if (require_devContext.devContext.enabled && !condition) throw new Error(message);
45
+ if (require_titleWarning.devContext.enabled && !condition) throw new Error(message);
134
46
  }
135
47
  //#endregion
136
48
  //#region src/watch/clearSources.ts
@@ -363,15 +275,30 @@ function resubscribeSuspendSources(effect) {
363
275
  context.activeTarget = oldActive;
364
276
  }
365
277
  /**
278
+ * How many times a single effect may run in one flush before it's treated as
279
+ * a cycle. Deliberately generous: the limit is per effect, so a large flush
280
+ * (hundreds of effects reacting to one change) is fine — only an effect that
281
+ * keeps re-queuing itself hits it.
282
+ */
283
+ const MAX_EFFECT_RUNS_PER_FLUSH = 100;
284
+ /**
366
285
  * Runs the effects that have been collected during the batch.
367
286
  */
368
287
  function triggerEffects() {
369
288
  let unhandledError = null;
289
+ let cycle = false;
370
290
  const queue = context.effectsToRun;
291
+ queue.sort((a, b) => a.seq - b.seq);
371
292
  for (let i = 0; i < queue.length; i++) {
372
293
  const effect = queue[i];
373
- context.batchOperation++;
374
294
  effect.queued = false;
295
+ if (effect.destroyed) continue;
296
+ const runs = (effect.flushRuns ?? 0) + 1;
297
+ effect.flushRuns = runs;
298
+ if (runs > MAX_EFFECT_RUNS_PER_FLUSH) {
299
+ cycle = true;
300
+ break;
301
+ }
375
302
  try {
376
303
  checkEffect(effect);
377
304
  } catch (err) {
@@ -387,7 +314,10 @@ function triggerEffects() {
387
314
  }
388
315
  }
389
316
  }
390
- for (let effect of queue) effect.queued = false;
317
+ for (let effect of queue) {
318
+ effect.queued = false;
319
+ effect.flushRuns = 0;
320
+ }
391
321
  context.effectsToRun = [];
392
322
  let signal = context.firstSignalToUpdate;
393
323
  context.firstSignalToUpdate = null;
@@ -397,6 +327,7 @@ function triggerEffects() {
397
327
  signal.nextSignalToUpdate = null;
398
328
  signal = nextSignal;
399
329
  }
330
+ if (cycle) throw new Error("Cycle detected");
400
331
  if (unhandledError !== null) throw unhandledError.error;
401
332
  }
402
333
  //#endregion
@@ -411,7 +342,6 @@ function batchEnd() {
411
342
  triggerEffects();
412
343
  } finally {
413
344
  context.batch = 0;
414
- context.batchOperation = 0;
415
345
  context.previousEffect = null;
416
346
  }
417
347
  }
@@ -423,7 +353,7 @@ function batchStart() {
423
353
  //#endregion
424
354
  //#region src/watch/runEffect.ts
425
355
  function runEffect(effect) {
426
- require_devContext.devContext.effectRun(effect);
356
+ require_titleWarning.devContext.effectRun(effect);
427
357
  const oldActiveTarget = context.activeTarget;
428
358
  const oldExtent = context.extent;
429
359
  effect.didError = false;
@@ -453,6 +383,7 @@ function runEffect(effect) {
453
383
  }
454
384
  //#endregion
455
385
  //#region src/watch/$run.ts
386
+ let effectSeq = 0;
456
387
  /**
457
388
  * Runs and re-runs a function that depends on a watched object
458
389
  *
@@ -468,6 +399,7 @@ function $run(fn, name, options) {
468
399
  firstSource: null,
469
400
  nextEffect: null,
470
401
  extent: 0,
402
+ seq: ++effectSeq,
471
403
  queued: false,
472
404
  didError: false,
473
405
  didSuspend: false,
@@ -482,64 +414,11 @@ function $run(fn, name, options) {
482
414
  region.effects.push(effect);
483
415
  effect.region = region;
484
416
  }
485
- require_devContext.devContext.onRun(effect);
417
+ require_titleWarning.devContext.onRun(effect);
486
418
  runEffect(effect);
487
419
  return effect;
488
420
  }
489
421
  //#endregion
490
- //#region src/watch/$peek.ts
491
- /**
492
- * Runs a function without tracking the reactive values it reads: `$watch`'d
493
- * state accessed inside `fn` does not become a dependency of the currently
494
- * running effect or computed. Useful for reading state inside an effect
495
- * without re-running it when that state changes.
496
- *
497
- * @param fn The function to run untracked.
498
- */
499
- function $peek(fn) {
500
- const oldActiveTarget = context.activeTarget;
501
- context.activeTarget = null;
502
- const result = fn();
503
- context.activeTarget = oldActiveTarget;
504
- return result;
505
- }
506
- //#endregion
507
- //#region src/watch/flushMountEffects.ts
508
- /**
509
- * Runs the collected `$onmount`/`onmount` callbacks — once, after the
510
- * component's markup has been added to the DOM (or, when hydrating, after
511
- * hydration is complete). Multiple callbacks run in the order they were
512
- * added.
513
- *
514
- * Each callback becomes an effect with `isMountEffect` set, so the keyed-list
515
- * reconciler's force-rerun path (`rerunRegionEffects`) skips it. Its body
516
- * also runs untracked: mount callbacks are once-only, so reactive reads
517
- * inside them do not subscribe. In dev builds a tracked pass warns when a
518
- * callback reads reactive state, since that is almost always a mistake — the
519
- * reactive part should be wrapped in `$run`.
520
- */
521
- function flushMountEffects() {
522
- if (context.mountEffects.length === 0) return;
523
- const activeRegion = context.activeRegion;
524
- for (let effect of context.mountEffects) {
525
- context.activeRegion = effect.region;
526
- $run(() => runMountCallback(effect.fn), void 0, { isMountEffect: true });
527
- }
528
- context.activeRegion = activeRegion;
529
- context.mountEffects.length = 0;
530
- }
531
- function runMountCallback(fn) {
532
- if (!require_devContext.devContext.enabled) return $peek(fn);
533
- const result = fn();
534
- const effect = context.activeTarget;
535
- if (effect !== null && effect.type === 2 && effect.firstSource !== null) {
536
- console.warn("[torpor] A $onmount/onmount callback read reactive state, but mount callbacks run only once and will not re-run. Wrap the reactive part in $run(), e.g. $onmount(() => { $run(() => ...); });");
537
- deactivateSources(effect);
538
- clearSources(effect);
539
- }
540
- return result;
541
- }
542
- //#endregion
543
422
  //#region src/render/animate.ts
544
423
  /**
545
424
  * Parses a transform function argument as a number, returning null for
@@ -694,13 +573,183 @@ async function animate(el, enter, keyframes, options) {
694
573
  await animation.finished;
695
574
  }
696
575
  //#endregion
576
+ //#region src/render/runAnimations.ts
577
+ /**
578
+ * Runs the animations stashed by `addAnimation` (`context.stashedAnimations`)
579
+ * when their element has been added to the DOM.
580
+ *
581
+ * Kept in its own module (imported only by `addAnimation`) rather than in
582
+ * `runMountSideEffects`: this way a component that never uses a
583
+ * `transition`/`transition-in`/`transition-out` attribute never imports
584
+ * `t_animate`, so this module — and `animate.ts` with it — is tree-shaken
585
+ * out of the bundle. `runMountSideEffects` reaches the runner through
586
+ * `context.runAnimations`, which stays null until `addAnimation` installs it.
587
+ */
588
+ function runAnimations() {
589
+ for (let animation of context.stashedAnimations) {
590
+ context.activeRegion = animation.region;
591
+ $run(function runMountSideEffectsAnimation() {
592
+ if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
593
+ if (animation.out !== void 0) return () => {
594
+ animate(animation.el, false, animation.out.keyframes, animation.out.options);
595
+ };
596
+ });
597
+ }
598
+ context.stashedAnimations.length = 0;
599
+ }
600
+ //#endregion
601
+ //#region src/render/addAnimation.ts
602
+ function addAnimation(el, entry, exit) {
603
+ context.runAnimations ??= runAnimations;
604
+ context.stashedAnimations.push({
605
+ region: context.activeRegion,
606
+ el,
607
+ in: entry,
608
+ out: exit
609
+ });
610
+ }
611
+ //#endregion
612
+ //#region src/render/addEvent.ts
613
+ function addEvent(el, type, listener) {
614
+ if (listener !== void 0 && listener !== null) context.stashedEvents.push({
615
+ el,
616
+ type,
617
+ listener
618
+ });
619
+ }
620
+ //#endregion
621
+ //#region src/render/isTextNode.ts
622
+ function isTextNode(node) {
623
+ return node.nodeType === 3;
624
+ }
625
+ const HYDRATION_BREAK_REGEX = /^\^(?:\d+)?$/;
626
+ /**
627
+ * Whether a comment node's data is a branch-break marker (`^`, or `^<index>`
628
+ * when the server recorded the branch it rendered).
629
+ */
630
+ function isHydrationBreak(data) {
631
+ return HYDRATION_BREAK_REGEX.test(data);
632
+ }
633
+ /**
634
+ * The branch index encoded in a `^<index>` branch-break marker, or `undefined`
635
+ * for a plain `^` marker (e.g. from `@for`, which has no branch index).
636
+ */
637
+ function hydrationBreakIndex(data) {
638
+ if (!data.startsWith("^") || data.length === 1) return;
639
+ const index = Number(data.slice(1));
640
+ return Number.isNaN(index) ? void 0 : index;
641
+ }
642
+ //#endregion
643
+ //#region src/render/isCommentNode.ts
644
+ function isCommentNode(node) {
645
+ return node.nodeType === 8;
646
+ }
647
+ //#endregion
648
+ //#region src/render/nodeCheckHydrationBreak.ts
649
+ /**
650
+ * When hydrating, removes and skips hydration comments that are inserted at the
651
+ * start of branches and used to split up text nodes that would otherwise be
652
+ * joined in HTML.
653
+ *
654
+ * @param node The node to check and maybe skip.
655
+ * @returns The next node.
656
+ */
657
+ function nodeCheckHydrationBreak(node) {
658
+ if (node !== null && isCommentNode(node) && isHydrationBreak(node.data)) {
659
+ let comment = node;
660
+ node = node.nextSibling;
661
+ comment.remove();
662
+ }
663
+ context.hydrationNode = node;
664
+ return node;
665
+ }
666
+ //#endregion
667
+ //#region src/render/nodeNext.ts
668
+ /**
669
+ * Gets the next sibling of a node.
670
+ *
671
+ * When hydrating, sets the hydration node.
672
+ *
673
+ * @param node The node.
674
+ * @param text Whether we require a text node.
675
+ */
676
+ function nodeNext(node, text = false) {
677
+ if (context.hydrationNode !== null) {
678
+ if (text && isTextNode(node)) return node;
679
+ let next = nodeCheckHydrationBreak(node.nextSibling);
680
+ while (!text && next !== null && isTextNode(next) && next.textContent?.trim() === "") next = nodeCheckHydrationBreak(next.nextSibling);
681
+ if (!text && next !== null && next.nodeName === "TBODY" && next.firstChild && isTextNode(node)) {
682
+ next = next.firstChild;
683
+ context.hydrationNode = next;
684
+ }
685
+ return next;
686
+ }
687
+ return node.nextSibling;
688
+ }
689
+ //#endregion
690
+ //#region src/watch/$peek.ts
691
+ /**
692
+ * Runs a function without tracking the reactive values it reads: `$watch`'d
693
+ * state accessed inside `fn` does not become a dependency of the currently
694
+ * running effect or computed. Useful for reading state inside an effect
695
+ * without re-running it when that state changes.
696
+ *
697
+ * @param fn The function to run untracked.
698
+ */
699
+ function $peek(fn) {
700
+ const oldActiveTarget = context.activeTarget;
701
+ context.activeTarget = null;
702
+ try {
703
+ return fn();
704
+ } finally {
705
+ context.activeTarget = oldActiveTarget;
706
+ }
707
+ }
708
+ //#endregion
709
+ //#region src/watch/flushMountEffects.ts
710
+ /**
711
+ * Runs the collected `$onmount`/`onmount` callbacks — once, after the
712
+ * component's markup has been added to the DOM (or, when hydrating, after
713
+ * hydration is complete). Multiple callbacks run in the order they were
714
+ * added.
715
+ *
716
+ * Each callback becomes an effect with `isMountEffect` set, so the keyed-list
717
+ * reconciler's force-rerun path (`rerunRegionEffects`) skips it. Its body
718
+ * also runs untracked: mount callbacks are once-only, so reactive reads
719
+ * inside them do not subscribe. In dev builds a tracked pass warns when a
720
+ * callback reads reactive state, since that is almost always a mistake — the
721
+ * reactive part should be wrapped in `$run`.
722
+ */
723
+ function flushMountEffects() {
724
+ if (context.mountEffects.length === 0) return;
725
+ const activeRegion = context.activeRegion;
726
+ for (let effect of context.mountEffects) {
727
+ context.activeRegion = effect.region;
728
+ $run(() => runMountCallback(effect.fn), void 0, { isMountEffect: true });
729
+ }
730
+ context.activeRegion = activeRegion;
731
+ context.mountEffects.length = 0;
732
+ }
733
+ function runMountCallback(fn) {
734
+ if (!require_titleWarning.devContext.enabled) return $peek(fn);
735
+ const result = fn();
736
+ const effect = context.activeTarget;
737
+ if (effect !== null && effect.type === 2 && effect.firstSource !== null) {
738
+ console.warn("[torpor] A $onmount/onmount callback read reactive state, but mount callbacks run only once and will not re-run. Wrap the reactive part in $run(), e.g. $onmount(() => { $run(() => ...); });");
739
+ deactivateSources(effect);
740
+ clearSources(effect);
741
+ }
742
+ return result;
743
+ }
744
+ //#endregion
697
745
  //#region src/render/delegatedEvents.ts
698
746
  /**
699
747
  * Event delegation.
700
748
  *
701
749
  * For event types in `DELEGATED_EVENT_TYPES` (all natively bubbling), we
702
- * register a single listener on `document` per type and dispatch by walking
703
- * up from `event.target` to find the closest ancestor with a stashed handler.
750
+ * register a single listener on each element's `ownerDocument` per type and
751
+ * dispatch by walking up from the event target, running each ancestor's
752
+ * stashed handler in turn until one calls `stopPropagation()`.
704
753
  * This replaces per-element `addEventListener` for delegated types.
705
754
  *
706
755
  * Why: in the js-framework-bench row template, every `<tr>` clones two `<a>`
@@ -720,6 +769,22 @@ async function animate(el, enter, keyframes, options) {
720
769
  * Non-bubbling events (`focus`, `blur`, `scroll`, `load`, `error`, `abort`,
721
770
  * `unload`, `resize`, etc.) bypass delegation and use direct
722
771
  * `addEventListener` on the element, preserving native semantics.
772
+ *
773
+ * Limitations (inherent to delegating to the document, same trade-off as
774
+ * React and Solid):
775
+ *
776
+ * - A native `stopPropagation()` — third-party code, or a listener added in
777
+ * `$onmount` — stops the event before it reaches the document, so the
778
+ * delegated handlers won't run. Torpor handlers can still call
779
+ * `stopPropagation()` among themselves (that's what ends the walk below).
780
+ * - `stopPropagation()` in a delegated handler runs after the native event
781
+ * has finished bubbling, so it only affects other delegated handlers, not
782
+ * native listeners.
783
+ *
784
+ * Shadow DOM and multiple documents are supported: the listener lives on the
785
+ * element's `ownerDocument` (so components mounted into an iframe or popup
786
+ * document work), and the path comes from `composedPath()` (so the listener
787
+ * sees the real target inside a shadow root, not the retargeted host).
723
788
  */
724
789
  const DELEGATED_EVENT_TYPES = /* @__PURE__ */ new Set([
725
790
  "auxclick",
@@ -767,10 +832,12 @@ function isDelegatedEventType(type) {
767
832
  const DELEGATE_PREFIX = "torp.$$";
768
833
  const DELEGATE_REGISTERED = Symbol.for("torp.delegated.registered");
769
834
  function delegatedHandler(event) {
770
- let node = event.target;
771
835
  const stopAt = event.currentTarget;
772
836
  const key = DELEGATE_PREFIX + event.type;
773
- while (node != null && node !== stopAt) {
837
+ const path = event.composedPath();
838
+ for (let i = 0; i < path.length; i++) {
839
+ const node = path[i];
840
+ if (node === stopAt) break;
774
841
  const handler = node[key];
775
842
  if (handler !== void 0) {
776
843
  Object.defineProperty(event, "currentTarget", {
@@ -783,29 +850,28 @@ function delegatedHandler(event) {
783
850
  } finally {
784
851
  delete event.currentTarget;
785
852
  }
786
- return;
853
+ if (event.cancelBubble) return;
787
854
  }
788
- node = node.parentNode;
789
855
  }
790
856
  }
791
- function ensureDelegatedListener(type) {
792
- if (typeof document === "undefined") return;
793
- let registered = document[DELEGATE_REGISTERED];
857
+ function ensureDelegatedListener(doc, type) {
858
+ let registered = doc[DELEGATE_REGISTERED];
794
859
  if (!registered) {
795
860
  registered = /* @__PURE__ */ new Set();
796
- document[DELEGATE_REGISTERED] = registered;
861
+ doc[DELEGATE_REGISTERED] = registered;
797
862
  }
798
863
  if (registered.has(type)) return;
799
864
  registered.add(type);
800
- document.addEventListener(type, delegatedHandler);
865
+ doc.addEventListener(type, delegatedHandler);
801
866
  }
802
867
  /**
803
868
  * Attach a delegated event handler to an element.
804
869
  *
805
870
  * Stores the handler as a property on the element and ensures a single
806
- * document-level listener exists for the type. Idempotent for the
807
- * document-level listener: the first call for a given type registers it,
808
- * subsequent calls are a Set-has check.
871
+ * listener exists for the type on the element's own document (so components
872
+ * mounted into another document — an iframe or popup — get delegated events
873
+ * too). Idempotent for the document-level listener: the first call for a
874
+ * given type registers it, subsequent calls are a Set-has check.
809
875
  *
810
876
  * Passing `null` or `undefined` as the listener clears any previously-set
811
877
  * handler for that type on the element (mirroring `addEvent`'s existing
@@ -817,7 +883,9 @@ function attachDelegatedEvent(el, type, listener) {
817
883
  el[key] = void 0;
818
884
  return;
819
885
  }
820
- ensureDelegatedListener(type);
886
+ const doc = el.ownerDocument;
887
+ if (doc === null || typeof doc.addEventListener !== "function") return;
888
+ ensureDelegatedListener(doc, type);
821
889
  el[key] = listener;
822
890
  }
823
891
  const DIRECT_LISTENERS = "torp.$directListeners";
@@ -859,8 +927,19 @@ function copyEventListeners(from, to) {
859
927
  }
860
928
  //#endregion
861
929
  //#region src/render/isFragmentNode.ts
930
+ /**
931
+ * Whether the node is a detached template/document fragment — i.e. a tree
932
+ * we're still building, where mount-time side effects (`$onmount`, event
933
+ * hookup, animations) must wait until the outer tree is inserted.
934
+ *
935
+ * A `ShadowRoot` is also `nodeType 11`, but it's a live tree root (its host
936
+ * may already be connected), so side effects must run when content is added
937
+ * to it. `host` distinguishes a shadow root without relying on
938
+ * `instanceof ShadowRoot`, which fails across realms (e.g. an iframe's
939
+ * shadow root).
940
+ */
862
941
  function isFragmentNode(node) {
863
- return node.nodeType === 11;
942
+ return node.nodeType === 11 && node.host === void 0;
864
943
  }
865
944
  //#endregion
866
945
  //#region src/render/runMountSideEffects.ts
@@ -886,16 +965,7 @@ function runMountSideEffects(parent, activeRegion, hydrationNode) {
886
965
  }
887
966
  context.stashedEvents.length = 0;
888
967
  }
889
- for (let animation of context.stashedAnimations) {
890
- context.activeRegion = animation.region;
891
- $run(function runMountSideEffectsAnimation() {
892
- if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
893
- if (animation.out !== void 0) return () => {
894
- animate(animation.el, false, animation.out.keyframes, animation.out.options);
895
- };
896
- });
897
- }
898
- context.stashedAnimations.length = 0;
968
+ if (context.stashedAnimations.length > 0) context.runAnimations?.();
899
969
  context.activeRegion = activeRegion;
900
970
  }
901
971
  //#endregion
@@ -947,6 +1017,47 @@ function addFragment(fragment, parent, before, endNode, startNode) {
947
1017
  if (hydrationNode !== null && endNode !== void 0) nodeNext(endNode);
948
1018
  }
949
1019
  //#endregion
1020
+ //#region src/render/urlAttributes.ts
1021
+ /**
1022
+ * A function that rewrites the URLs in `href`, `src` and `action` attributes
1023
+ * as the client sets them, registered by a host framework with
1024
+ * `setUrlRewriter` (e.g. `@torpor/build` adds a site's base path, so markup
1025
+ * can be written base-free). Undefined when no rewriting is needed.
1026
+ */
1027
+ let rewriteUrl;
1028
+ /**
1029
+ * Registers a function that rewrites the URLs in `href`, `src` and `action`
1030
+ * attributes the client sets -- from dynamic attributes, spread props and
1031
+ * client-rendered markup -- or clears it with `undefined`. Fragments already
1032
+ * cached are not rewritten again, so register it before the first render.
1033
+ */
1034
+ function setUrlRewriter(rewriter) {
1035
+ rewriteUrl = rewriter;
1036
+ }
1037
+ const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
1038
+ "href",
1039
+ "src",
1040
+ "action"
1041
+ ]);
1042
+ /** An attribute value, with its URL rewritten if it's a URL attribute. */
1043
+ function urlAttributeValue(name, value) {
1044
+ if (rewriteUrl === void 0 || typeof value !== "string") return value;
1045
+ return URL_ATTRIBUTES.has(name.toLowerCase()) ? rewriteUrl(value) : value;
1046
+ }
1047
+ /** Rewrites the URL attributes of the elements in a freshly parsed template. */
1048
+ function rewriteUrlsIn(root) {
1049
+ if (rewriteUrl === void 0) return;
1050
+ const elements = [...root.querySelectorAll("[href], [src], [action]")];
1051
+ if (root instanceof Element && root.matches("[href], [src], [action]")) elements.push(root);
1052
+ for (const el of elements) for (const name of URL_ATTRIBUTES) {
1053
+ const value = el.getAttribute(name);
1054
+ if (value !== null) {
1055
+ const rewritten = rewriteUrl(value);
1056
+ if (rewritten !== value) el.setAttribute(name, rewritten);
1057
+ }
1058
+ }
1059
+ }
1060
+ //#endregion
950
1061
  //#region src/render/applyProps.ts
951
1062
  function applyProps(el, props, propNamesUsed) {
952
1063
  if (props !== void 0) {
@@ -956,7 +1067,7 @@ function applyProps(el, props, propNamesUsed) {
956
1067
  if (isDelegatedEventType(eventName)) attachDelegatedEvent(el, eventName, value);
957
1068
  else el.addEventListener(eventName, value);
958
1069
  } else $run(function setAttribute() {
959
- el.setAttribute(name, value);
1070
+ el.setAttribute(name, urlAttributeValue(name, value));
960
1071
  });
961
1072
  }
962
1073
  }
@@ -964,7 +1075,7 @@ function applyProps(el, props, propNamesUsed) {
964
1075
  //#endregion
965
1076
  //#region src/render/clearRegion.ts
966
1077
  function clearRegion(region) {
967
- require_devContext.devContext.onRegionCleared(region);
1078
+ require_titleWarning.devContext.onRegionCleared(region);
968
1079
  let animations = region.animations !== null ? Array.from(region.animations) : void 0;
969
1080
  let childRegion = region.nextRegion;
970
1081
  while (childRegion !== null && childRegion.depth > region.depth) {
@@ -1032,6 +1143,7 @@ function releaseRegion(region) {
1032
1143
  region.animations = null;
1033
1144
  region.errorBoundary = void 0;
1034
1145
  for (const effect of region.effects) {
1146
+ effect.destroyed = true;
1035
1147
  if (typeof effect.cleanup === "function") {
1036
1148
  effect.cleanup();
1037
1149
  effect.cleanup = void 0;
@@ -1072,7 +1184,7 @@ function newRegion(name) {
1072
1184
  //#region src/render/popRegion.ts
1073
1185
  function popRegion(oldRegion) {
1074
1186
  context.activeRegion = oldRegion;
1075
- require_devContext.devContext.onRegionPopped();
1187
+ require_titleWarning.devContext.onRegionPopped();
1076
1188
  }
1077
1189
  //#endregion
1078
1190
  //#region src/render/pushRegion.ts
@@ -1089,7 +1201,7 @@ function pushRegion(region, toParent = false) {
1089
1201
  }
1090
1202
  context.activeRegion = region;
1091
1203
  context.previousRegion = region;
1092
- require_devContext.devContext.onRegionPushed(region, toParent);
1204
+ require_titleWarning.devContext.onRegionPushed(region, toParent);
1093
1205
  return activeRegion;
1094
1206
  }
1095
1207
  //#endregion
@@ -1121,14 +1233,16 @@ function rememberSlotRefillDepth(parent, depth) {
1121
1233
  * @param $context Optional context to pass to the component
1122
1234
  */
1123
1235
  function fillLayoutSlot(component, slot, parent, anchor, $props, $context) {
1124
- const region = newRegion(require_devContext.devContext.enabled ? "Layout slot" : void 0);
1236
+ const region = newRegion(require_titleWarning.devContext.enabled ? "Layout slot" : void 0);
1125
1237
  const oldRegion = pushRegion(region, true);
1126
1238
  const refillDepth = refillDepths.get(parent);
1127
1239
  if (refillDepth !== void 0) {
1128
1240
  region.depth = refillDepth;
1129
1241
  refillDepths.delete(parent);
1130
1242
  }
1243
+ const previousSlotDepth = require_titleWarning.devContext.enabled ? require_titleWarning.setDevSlotDepth(region.depth) : -1;
1131
1244
  component(parent, anchor, $props, $context, { _: slot });
1245
+ if (require_titleWarning.devContext.enabled) require_titleWarning.setDevSlotDepth(previousSlotDepth);
1132
1246
  popRegion(oldRegion);
1133
1247
  return region;
1134
1248
  }
@@ -1184,8 +1298,9 @@ function getFragment(document, array, index, html, ns) {
1184
1298
  template.innerHTML = html;
1185
1299
  array[index] = template.content;
1186
1300
  }
1301
+ rewriteUrlsIn(array[index]);
1187
1302
  }
1188
- return array[index].cloneNode(true);
1303
+ return document.importNode(array[index], true);
1189
1304
  }
1190
1305
  //#endregion
1191
1306
  //#region src/render/getElementFragment.ts
@@ -1224,8 +1339,9 @@ function getElementFragment(document, array, index, html, ns) {
1224
1339
  template.innerHTML = html;
1225
1340
  array[index] = template.content.firstElementChild;
1226
1341
  }
1342
+ rewriteUrlsIn(array[index]);
1227
1343
  }
1228
- return array[index].cloneNode(true);
1344
+ return document.importNode(array[index], true);
1229
1345
  }
1230
1346
  //#endregion
1231
1347
  //#region src/render/isServerComponent.ts
@@ -1288,8 +1404,12 @@ function containedTrees(parent) {
1288
1404
  * @param parent The parent node
1289
1405
  * @param component The component to mount
1290
1406
  * @param props An object containing component props
1407
+ * @param slots Slot render functions for the component
1408
+ * @param rootContext The root `$context`, which the component and all of its
1409
+ * descendants inherit (e.g. app-wide state that a framework provides to
1410
+ * every page)
1291
1411
  */
1292
- function hydrate(parent, component, props, slots) {
1412
+ function hydrate(parent, component, props, slots, rootContext) {
1293
1413
  if (isServerComponent(component)) throw new Error("The component was compiled for SSR (it renders to an HTML string) and cannot be hydrated in the browser. Import the client build instead, e.g. with the '?client' import query");
1294
1414
  const saved = context.rootRegion !== null ? {
1295
1415
  activeRegion: context.activeRegion,
@@ -1298,11 +1418,11 @@ function hydrate(parent, component, props, slots) {
1298
1418
  rootRegion: context.rootRegion
1299
1419
  } : null;
1300
1420
  context.hydrationNode = parent.firstChild;
1301
- const root = newRegion(require_devContext.devContext.enabled ? "Root" : void 0);
1421
+ const root = newRegion(require_titleWarning.devContext.enabled ? "Root" : void 0);
1302
1422
  context.rootRegion = root;
1303
1423
  context.previousRegion = root;
1304
1424
  pushRegion(root);
1305
- component(parent, null, props, void 0, slots);
1425
+ component(parent, null, props, rootContext, slots);
1306
1426
  context.hydrationNode = null;
1307
1427
  flushMountEffects();
1308
1428
  if (saved === null) {
@@ -1335,8 +1455,12 @@ function hydrate(parent, component, props, slots) {
1335
1455
  * child elements
1336
1456
  * @param component The component to mount
1337
1457
  * @param props An object containing component props
1458
+ * @param slots Slot render functions for the component
1459
+ * @param rootContext The root `$context`, which the component and all of its
1460
+ * descendants inherit (e.g. app-wide state that a framework provides to
1461
+ * every page)
1338
1462
  */
1339
- function mount(parent, component, props, slots) {
1463
+ function mount(parent, component, props, slots, rootContext) {
1340
1464
  if (isServerComponent(component)) throw new Error("The component was compiled for SSR (it renders to an HTML string) and cannot be mounted in the browser. Import the client build instead, e.g. with the '?client' import query");
1341
1465
  if (parent.childElementCount > 0) throw new Error("The parent node must have no child elements");
1342
1466
  while (parent.firstChild !== null) parent.firstChild.remove();
@@ -1345,17 +1469,32 @@ function mount(parent, component, props, slots) {
1345
1469
  previousRegion: context.previousRegion,
1346
1470
  rootRegion: context.rootRegion
1347
1471
  } : null;
1348
- const root = newRegion(require_devContext.devContext.enabled ? "Root" : void 0);
1472
+ const root = newRegion(require_titleWarning.devContext.enabled ? "Root" : void 0);
1349
1473
  context.rootRegion = root;
1350
1474
  context.previousRegion = root;
1351
1475
  pushRegion(root);
1352
- component(parent, null, props, void 0, slots);
1353
- if (saved !== null) {
1354
- context.rootRegion = saved.rootRegion;
1355
- context.previousRegion = saved.previousRegion;
1356
- context.activeRegion = saved.activeRegion;
1476
+ let mounted = false;
1477
+ try {
1478
+ component(parent, null, props, rootContext, slots);
1479
+ mounted = true;
1480
+ } finally {
1481
+ if (mounted) {
1482
+ if (saved !== null) {
1483
+ context.rootRegion = saved.rootRegion;
1484
+ context.previousRegion = saved.previousRegion;
1485
+ context.activeRegion = saved.activeRegion;
1486
+ }
1487
+ } else {
1488
+ unregisterRegionTree(parent);
1489
+ try {
1490
+ clearRegion(root);
1491
+ } catch {}
1492
+ context.rootRegion = saved !== null ? saved.rootRegion : null;
1493
+ context.previousRegion = saved !== null ? saved.previousRegion : null;
1494
+ context.activeRegion = saved !== null ? saved.activeRegion : null;
1495
+ }
1357
1496
  }
1358
- registerRegionTree(parent, root);
1497
+ if (mounted) registerRegionTree(parent, root);
1359
1498
  }
1360
1499
  //#endregion
1361
1500
  //#region src/render/unmount.ts
@@ -1369,6 +1508,10 @@ function mount(parent, component, props, slots) {
1369
1508
  * embed is disposed and the host's render context is left untouched. Any
1370
1509
  * embeds living inside a root container are disposed along with it.
1371
1510
  *
1511
+ * When no tree was mounted into `parent`, this is a no-op apart from
1512
+ * disposing any embeds living inside it and removing `parent`'s own child
1513
+ * nodes — it never touches the running app's root context.
1514
+ *
1372
1515
  * Call this before `mount`ing a fresh component tree into the same container
1373
1516
  * (e.g. when client-side navigating to a route whose layout chain differs
1374
1517
  * from the previous one). `mount` refuses to mount into a non-empty parent
@@ -1382,17 +1525,17 @@ function unmount(parent) {
1382
1525
  clearRegion(nestedTree);
1383
1526
  unregisterRegionTree(nestedParent);
1384
1527
  }
1385
- if (owned !== void 0 && owned !== context.rootRegion) {
1386
- clearRegion(owned);
1387
- unregisterRegionTree(parent);
1388
- } else {
1389
- if (context.rootRegion !== null) {
1390
- clearRegion(context.rootRegion);
1528
+ if (owned !== void 0) {
1529
+ if (owned !== context.rootRegion) {
1530
+ clearRegion(owned);
1531
+ unregisterRegionTree(parent);
1532
+ } else {
1533
+ clearRegion(owned);
1391
1534
  context.rootRegion = null;
1392
1535
  context.previousRegion = null;
1393
1536
  context.activeRegion = null;
1537
+ unregisterRegionTree(parent);
1394
1538
  }
1395
- if (owned !== void 0) unregisterRegionTree(parent);
1396
1539
  }
1397
1540
  while (parent.firstChild !== null) parent.firstChild.remove();
1398
1541
  }
@@ -1821,7 +1964,7 @@ function runControlBranch(region, oldIndex, index, name) {
1821
1964
  */
1822
1965
  function pushBranchRegion(region, name) {
1823
1966
  context.previousRegion = region;
1824
- return pushRegion(newRegion(require_devContext.devContext.enabled ? name : void 0), true);
1967
+ return pushRegion(newRegion(require_titleWarning.devContext.enabled ? name : void 0), true);
1825
1968
  }
1826
1969
  /**
1827
1970
  * Clears a server-rendered control branch that the client didn't pick, so the
@@ -1856,50 +1999,23 @@ function clearServerBranch(region, removedFirst, anchor) {
1856
1999
  }
1857
2000
  }
1858
2001
  //#endregion
1859
- //#region src/render/checkListKeys.ts
1860
- const warnedByRegion = /* @__PURE__ */ new WeakMap();
2002
+ //#region src/watch/isWrappable.ts
1861
2003
  /**
1862
- * DEV-ONLY: warns when a keyed `@for` list contains duplicate `@key` values.
2004
+ * Whether `$watch`/`deepWrap` can proxy this value.
1863
2005
  *
1864
- * `runListItems` matches old and new rows by key (first match wins), so
1865
- * duplicate keys make updates and removals hit the wrong rows, desyncing the
1866
- * DOM from the data. Called from `runList` only when `devContext.enabled`, so
1867
- * it never runs in a production build.
1868
- *
1869
- * `undefined`/`null` keys are the "unkeyed" case (rows are matched
1870
- * positionally) and are ignored.
1871
- *
1872
- * @param region The `@for` list's region, used to dedupe warnings per list.
1873
- * @param specs The new row specs, in order.
2006
+ * Only plain objects, plain arrays, and exact Date/Map/Set/URL/
2007
+ * URLSearchParams instances are deep-watched. Everything else -- class
2008
+ * instances, array/collection subclasses, RegExp, typed arrays, promises, DOM
2009
+ * nodes, weak collections, and any frozen/non-extensible object -- is treated
2010
+ * as an opaque value: it is returned unchanged, and only replacing the
2011
+ * property that holds it is reactive.
1874
2012
  */
1875
- function checkListKeys(region, specs) {
1876
- let seen;
1877
- for (let i = 0; i < specs.length; i++) {
1878
- const key = specs[i].key;
1879
- if (key === void 0 || key === null) continue;
1880
- if (seen === void 0) seen = /* @__PURE__ */ new Set();
1881
- if (!seen.has(key)) {
1882
- seen.add(key);
1883
- continue;
1884
- }
1885
- let warned = warnedByRegion.get(region);
1886
- if (warned === void 0) {
1887
- warned = /* @__PURE__ */ new Set();
1888
- warnedByRegion.set(region, warned);
1889
- }
1890
- if (!warned.has(key)) {
1891
- warned.add(key);
1892
- console.warn(`[torpor] Duplicate @key value ${formatKey(key)} in a keyed @for list. Keys must be unique, or updates and removals will affect the wrong rows.`);
1893
- }
1894
- }
1895
- }
1896
- function formatKey(key) {
1897
- try {
1898
- const json = JSON.stringify(key);
1899
- return json === void 0 ? String(key) : json;
1900
- } catch {
1901
- return String(key);
1902
- }
2013
+ function isWrappable(value) {
2014
+ if (value === null || typeof value !== "object") return false;
2015
+ if (!Object.isExtensible(value)) return false;
2016
+ const proto = Object.getPrototypeOf(value);
2017
+ if (proto === Date.prototype || proto === Map.prototype || proto === Set.prototype || typeof URL !== "undefined" && proto === URL.prototype || typeof URLSearchParams !== "undefined" && proto === URLSearchParams.prototype) return true;
2018
+ return proto === Object.prototype || proto === null || proto === Array.prototype;
1903
2019
  }
1904
2020
  //#endregion
1905
2021
  //#region src/watch/propagateSignal.ts
@@ -1995,29 +2111,49 @@ var AwaitSuspend = class extends Error {
1995
2111
  //#endregion
1996
2112
  //#region src/watch/deepWrap.ts
1997
2113
  /**
1998
- * Wraps a value with `$watch` if it is a plain object (or Date/Map/Set) that
1999
- * is not already watched and is not a promise. Returns the value unchanged
2000
- * otherwise.
2114
+ * Wraps a value with `$watch` if it is a plain object, plain array, or exact
2115
+ * Date/Map/Set instance that is not already watched. Returns the value
2116
+ * unchanged otherwise (class instances, subclasses, RegExp, typed arrays,
2117
+ * frozen objects, promises, DOM nodes, ... stay opaque).
2001
2118
  *
2002
2119
  * Used by the `get` trap (wrap values on read) and the `set` trap (wrap
2003
2120
  * values on write), so a value stored in watched state is reactive whether
2004
2121
  * it's been read yet or not.
2005
2122
  */
2006
2123
  const proxyCache = /* @__PURE__ */ new WeakMap();
2124
+ const wrappedProxies = /* @__PURE__ */ new WeakSet();
2125
+ /**
2126
+ * Whether `value` is a proxy created by `deepWrap` — checked without going
2127
+ * through the proxy's `get` trap.
2128
+ */
2129
+ function isWrappedProxy(value) {
2130
+ return value !== null && typeof value === "object" && wrappedProxies.has(value);
2131
+ }
2007
2132
  function deepWrap(value) {
2008
2133
  if (value === void 0 || value === null || typeof value !== "object") return value;
2134
+ if (wrappedProxies.has(value)) return value;
2009
2135
  if (value[require_fromWebSocket.proxyDataSymbol] !== void 0) return proxyCache.get(value) ?? value;
2136
+ if (!isWrappable(value)) return value;
2010
2137
  if (value.then !== void 0) return value;
2011
- if (value.nodeType !== void 0) return value;
2012
2138
  const cached = proxyCache.get(value);
2013
2139
  if (cached !== void 0) return cached;
2014
2140
  const proxy = $watch(value);
2015
2141
  proxyCache.set(value, proxy);
2142
+ wrappedProxies.add(proxy);
2016
2143
  return proxy;
2017
2144
  }
2018
2145
  //#endregion
2019
2146
  //#region src/watch/trackProxySignal.ts
2020
2147
  function trackProxySignal(data, key) {
2148
+ trackSignal(ensureProxySignal(data, key));
2149
+ }
2150
+ /**
2151
+ * Creates or gets the signal for a proxy key, without subscribing the active
2152
+ * effect to it. Used where a signal must exist for later reads (e.g. the
2153
+ * array iterator creating per-index signals) but the current reader
2154
+ * shouldn't re-run when that key changes.
2155
+ */
2156
+ function ensureProxySignal(data, key) {
2021
2157
  let signal = data.signals.get(key);
2022
2158
  if (signal === void 0) {
2023
2159
  signal = {
@@ -2027,7 +2163,115 @@ function trackProxySignal(data, key) {
2027
2163
  };
2028
2164
  data.signals.set(key, signal);
2029
2165
  }
2030
- trackSignal(signal);
2166
+ return signal;
2167
+ }
2168
+ //#endregion
2169
+ //#region src/watch/urlHandlers.ts
2170
+ const URL_KEY = Symbol("torp.url");
2171
+ const URL_PARAMS_KEY = Symbol("torp.urlParams");
2172
+ const URL_PROPERTIES = /* @__PURE__ */ new Set([
2173
+ "href",
2174
+ "origin",
2175
+ "protocol",
2176
+ "username",
2177
+ "password",
2178
+ "host",
2179
+ "hostname",
2180
+ "port",
2181
+ "pathname",
2182
+ "search",
2183
+ "searchParams",
2184
+ "hash"
2185
+ ]);
2186
+ const URL_METHODS = /* @__PURE__ */ new Set(["toString", "toJSON"]);
2187
+ const URL_MEMBERS = /* @__PURE__ */ new Set([...URL_PROPERTIES, ...URL_METHODS]);
2188
+ const URL_PARAMS_METHODS = /* @__PURE__ */ new Set([
2189
+ "append",
2190
+ "delete",
2191
+ "get",
2192
+ "getAll",
2193
+ "has",
2194
+ "set",
2195
+ "sort",
2196
+ "entries",
2197
+ "forEach",
2198
+ "keys",
2199
+ "values",
2200
+ "toString"
2201
+ ]);
2202
+ const URL_PARAMS_MUTATORS = /* @__PURE__ */ new Set([
2203
+ "append",
2204
+ "delete",
2205
+ "set",
2206
+ "sort"
2207
+ ]);
2208
+ function urlGet(data, target, key, wrap) {
2209
+ trackProxySignal(data, URL_KEY);
2210
+ if (key === "searchParams") {
2211
+ const params = target.searchParams;
2212
+ if (data.shallow === true) return params;
2213
+ const proxy = wrap(params);
2214
+ const paramsData = params[require_fromWebSocket.proxyDataSymbol];
2215
+ if (paramsData !== void 0) {
2216
+ paramsData.linkedUrlData = data;
2217
+ data.urlParamsData = paramsData;
2218
+ }
2219
+ return proxy;
2220
+ }
2221
+ if (URL_METHODS.has(key)) return function(...args) {
2222
+ return target[key](...args);
2223
+ };
2224
+ return target[key];
2225
+ }
2226
+ function urlSet(data, target, key, value) {
2227
+ const before = target.href;
2228
+ const descriptor = typeof key === "string" ? Object.getOwnPropertyDescriptor(URL.prototype, key) : void 0;
2229
+ if (descriptor?.set !== void 0) descriptor.set.call(target, value);
2230
+ else if (!Reflect.set(target, key, value, target)) return false;
2231
+ if (target.href !== before) {
2232
+ batchStart();
2233
+ try {
2234
+ propagateSignal(data, URL_KEY);
2235
+ if (data.urlParamsData !== void 0) propagateSignal(data.urlParamsData, URL_PARAMS_KEY);
2236
+ } finally {
2237
+ batchEnd();
2238
+ }
2239
+ }
2240
+ return true;
2241
+ }
2242
+ function trackUrlParams(data) {
2243
+ trackProxySignal(data, URL_PARAMS_KEY);
2244
+ if (data.linkedUrlData !== void 0) trackProxySignal(data.linkedUrlData, URL_KEY);
2245
+ }
2246
+ function propagateUrlParams(data) {
2247
+ batchStart();
2248
+ try {
2249
+ propagateSignal(data, URL_PARAMS_KEY);
2250
+ if (data.linkedUrlData !== void 0) propagateSignal(data.linkedUrlData, URL_KEY);
2251
+ } finally {
2252
+ batchEnd();
2253
+ }
2254
+ }
2255
+ function urlParamsGet(data, target, key) {
2256
+ if (key === "size") {
2257
+ trackUrlParams(data);
2258
+ return target.size;
2259
+ }
2260
+ if (key === Symbol.iterator) {
2261
+ trackUrlParams(data);
2262
+ return target[Symbol.iterator].bind(target);
2263
+ }
2264
+ return function(...args) {
2265
+ const method = key;
2266
+ if (URL_PARAMS_MUTATORS.has(method)) {
2267
+ const before = target.toString();
2268
+ const result = target[method](...args);
2269
+ if (target.toString() !== before) propagateUrlParams(data);
2270
+ return result;
2271
+ }
2272
+ trackUrlParams(data);
2273
+ return target[method](...args);
2274
+ };
2031
2275
  }
2032
2276
  //#endregion
2033
2277
  //#region src/watch/proxyGet.ts
@@ -2080,6 +2324,8 @@ function proxyGet(target, key, receiver) {
2080
2324
  let data = target[require_fromWebSocket.proxyDataSymbol];
2081
2325
  if (key === require_fromWebSocket.proxyDataSymbol) return data;
2082
2326
  if ((data.isDate || data.isMap || data.isSet) && !Object.prototype.hasOwnProperty.call(target, key)) return collectionGet(data, target, key, receiver);
2327
+ if (data.isUrl && typeof key === "string" && URL_MEMBERS.has(key) && !Object.prototype.hasOwnProperty.call(target, key)) return urlGet(data, target, key, deepWrap);
2328
+ if (data.isUrlParams && (key === "size" || key === Symbol.iterator || typeof key === "string" && URL_PARAMS_METHODS.has(key)) && !Object.prototype.hasOwnProperty.call(target, key)) return urlParamsGet(data, target, key);
2083
2329
  let signal = data.signals.get(key);
2084
2330
  if (signal === void 0) {
2085
2331
  const propDescriptor = Object.getOwnPropertyDescriptor(target, key);
@@ -2143,8 +2389,7 @@ function proxyGet(target, key, receiver) {
2143
2389
  }
2144
2390
  const arrayWrapper = {
2145
2391
  [Symbol.iterator]: function(data, target, _key) {
2146
- trackProxySignal(data, "length");
2147
- context.activeTarget = null;
2392
+ trackArrayReads(data);
2148
2393
  return function arrayIterator() {
2149
2394
  let index = 0;
2150
2395
  return {
@@ -2161,7 +2406,7 @@ const arrayWrapper = {
2161
2406
  target[index] = value;
2162
2407
  }
2163
2408
  }
2164
- trackProxySignal(data, String(index));
2409
+ ensureProxySignal(data, String(index));
2165
2410
  index++;
2166
2411
  return {
2167
2412
  value,
@@ -2188,29 +2433,112 @@ const arrayWrapper = {
2188
2433
  toReversed: readHandle,
2189
2434
  toSorted: readHandle,
2190
2435
  toSpliced: readHandle,
2191
- indexOf: readHandle,
2192
- lastIndexOf: readHandle,
2193
- includes: readHandle,
2436
+ indexOf: searchHandle,
2437
+ lastIndexOf: searchHandle,
2438
+ includes: searchHandle,
2194
2439
  find: readHandle,
2195
2440
  findIndex: readHandle,
2196
2441
  some: readHandle,
2197
2442
  every: readHandle,
2198
- join: readHandle,
2443
+ join: joinHandle,
2199
2444
  forEach: readHandle,
2200
2445
  reduce: readHandle,
2201
2446
  reduceRight: readHandle,
2202
2447
  flat: readHandle,
2203
2448
  flatMap: readHandle,
2204
- at: readHandle
2449
+ at: atHandle
2205
2450
  };
2451
+ /**
2452
+ * Wraps (and writes back) every object element of a raw array, so callback
2453
+ * parameters and returned values are reactive proxies — the same lazy wrapping
2454
+ * the iterator does. Skipped entirely once every element is wrapped (the
2455
+ * `elementsWrapped` flag, reset by mutations that can insert raw elements);
2456
+ * `isWrappedProxy` skips elements that are already proxies without reading
2457
+ * through their `get` trap. Shallow arrays are left unwrapped to match the
2458
+ * `get` trap's deep-only behaviour.
2459
+ */
2460
+ function wrapArrayElements(data, target) {
2461
+ if (data.shallow === true || data.elementsWrapped === true) return;
2462
+ const length = target.length;
2463
+ for (let i = 0; i < length; i++) {
2464
+ const value = target[i];
2465
+ if (value !== null && typeof value === "object" && !isWrappedProxy(value)) {
2466
+ const wrapped = deepWrap(value);
2467
+ if (wrapped !== value) target[i] = wrapped;
2468
+ }
2469
+ }
2470
+ data.elementsWrapped = true;
2471
+ }
2472
+ /**
2473
+ * Subscribes the active effect to everything a read of the array's contents
2474
+ * depends on: `length` (rows added/removed) and the content signal (an
2475
+ * element replaced at an existing index, which keeps the length). When no
2476
+ * effect is active both are cheap no-ops.
2477
+ */
2478
+ function trackArrayReads(data) {
2479
+ trackProxySignal(data, "length");
2480
+ trackProxySignal(data, require_fromWebSocket.proxyArrayContentSymbol);
2481
+ }
2206
2482
  function readHandle(data, target, key) {
2207
2483
  return function(...args) {
2208
- trackProxySignal(data, "length");
2484
+ trackArrayReads(data);
2485
+ wrapArrayElements(data, target);
2486
+ return target[key].apply(target, args);
2487
+ };
2488
+ }
2489
+ function joinHandle(data, target, key) {
2490
+ return function(...args) {
2491
+ trackArrayReads(data);
2209
2492
  return target[key].apply(target, args);
2210
2493
  };
2211
2494
  }
2495
+ /**
2496
+ * `indexOf` / `lastIndexOf` / `includes`.
2497
+ *
2498
+ * Elements are wrapped lazily, so the array can hold raw objects or their
2499
+ * proxies — and a raw search value can miss the proxy that replaced it (or a
2500
+ * proxy can miss the raw object it wraps). On a miss with an object argument,
2501
+ * retry with the unwrapped and wrapped forms.
2502
+ */
2503
+ function searchHandle(data, target, key) {
2504
+ return function(...args) {
2505
+ trackArrayReads(data);
2506
+ const search = args[0];
2507
+ const func = target[key];
2508
+ const found = func.apply(target, args);
2509
+ if ((found === -1 || found === false) && search !== null && typeof search === "object") for (const candidate of [require_fromWebSocket.$unwrap(search), deepWrap(search)]) {
2510
+ if (candidate === search) continue;
2511
+ const result = func.apply(target, [candidate, ...args.slice(1)]);
2512
+ if (result !== -1 && result !== false) return result;
2513
+ }
2514
+ return found;
2515
+ };
2516
+ }
2517
+ /**
2518
+ * `at`: like a direct `arr[i]` read, but it wraps just the element it returns
2519
+ * (a whole-array wrap would turn the O(1) lookup into O(n)).
2520
+ */
2521
+ function atHandle(data, target, _key) {
2522
+ return function(index) {
2523
+ trackArrayReads(data);
2524
+ const length = target.length;
2525
+ let i = Math.trunc(Number(index ?? 0)) || 0;
2526
+ if (i < 0) i += length;
2527
+ if (i < 0 || i >= length) return void 0;
2528
+ let value = target[i];
2529
+ if (data.shallow !== true) {
2530
+ const wrapped = deepWrap(value);
2531
+ if (wrapped !== value) {
2532
+ value = wrapped;
2533
+ target[i] = value;
2534
+ }
2535
+ }
2536
+ return value;
2537
+ };
2538
+ }
2212
2539
  function arrayHandle(data, target, key) {
2213
2540
  return function(...args) {
2541
+ if (key === "push" || key === "unshift" || key === "splice") data.elementsWrapped = false;
2214
2542
  const result = target[key].apply(target, args);
2215
2543
  propagateSignal(data, "length");
2216
2544
  if (key !== "sort" && key !== "reverse") propagateSignal(data, require_fromWebSocket.proxyKeysSymbol);
@@ -2315,7 +2643,7 @@ const mapWrapper = {
2315
2643
  return function(key) {
2316
2644
  key = require_fromWebSocket.$unwrap(key);
2317
2645
  const result = target.delete(key);
2318
- propagateCollection(data, collectionKey(key));
2646
+ if (result) propagateCollection(data, collectionKey(key));
2319
2647
  return result;
2320
2648
  };
2321
2649
  },
@@ -2389,7 +2717,7 @@ const setWrapper = {
2389
2717
  return function(value) {
2390
2718
  value = require_fromWebSocket.$unwrap(value);
2391
2719
  const result = target.delete(value);
2392
- propagateCollection(data, collectionKey(value));
2720
+ if (result) propagateCollection(data, collectionKey(value));
2393
2721
  return result;
2394
2722
  };
2395
2723
  },
@@ -2442,16 +2770,21 @@ function setEntries(data, target) {
2442
2770
  //#region src/watch/proxySet.ts
2443
2771
  function proxySet(target, key, value, receiver) {
2444
2772
  const oldValue = target[key];
2445
- if (value !== oldValue) {
2446
- if (context.batchOperation > 100) throw new Error("Cycle detected");
2773
+ if (!Object.is(value, oldValue)) {
2447
2774
  let data = target[require_fromWebSocket.proxyDataSymbol];
2448
- require_devContext.devContext.signalSet(data, key);
2775
+ require_titleWarning.devContext.signalSet(data, key);
2776
+ if (data.isUrl && !Object.prototype.hasOwnProperty.call(target, key)) return urlSet(data, target, key, value);
2449
2777
  if (data.shallow !== true) value = deepWrap(value);
2450
2778
  const isNewKey = !Object.prototype.hasOwnProperty.call(target, key);
2779
+ const isArrayIndex = data.isArray && typeof key !== "symbol" && !isNaN(+key);
2780
+ const oldLength = isArrayIndex ? target.length : 0;
2451
2781
  Reflect.set(target, key, value, receiver);
2452
2782
  propagateSignal(data, key);
2453
2783
  if (isNewKey) propagateSignal(data, require_fromWebSocket.proxyKeysSymbol);
2454
- if (data.isArray && typeof key !== "symbol" && !isNaN(+key)) propagateSignal(data, "length");
2784
+ if (isArrayIndex) {
2785
+ propagateSignal(data, require_fromWebSocket.proxyArrayContentSymbol);
2786
+ if (target.length !== oldLength) propagateSignal(data, "length");
2787
+ }
2455
2788
  }
2456
2789
  return true;
2457
2790
  }
@@ -2465,6 +2798,11 @@ const sharedHandler = {
2465
2798
  if (data !== void 0) trackProxySignal(data, require_fromWebSocket.proxyKeysSymbol);
2466
2799
  return Reflect.ownKeys(target);
2467
2800
  },
2801
+ has: (target, key) => {
2802
+ const data = target[require_fromWebSocket.proxyDataSymbol];
2803
+ if (data !== void 0) trackProxySignal(data, require_fromWebSocket.proxyKeysSymbol);
2804
+ return Reflect.has(target, key);
2805
+ },
2468
2806
  deleteProperty: (target, key) => {
2469
2807
  const deleted = Reflect.deleteProperty(target, key);
2470
2808
  const data = target[require_fromWebSocket.proxyDataSymbol];
@@ -2478,20 +2816,33 @@ const sharedHandler = {
2478
2816
  /**
2479
2817
  * Watches an object and runs effects when its properties are changed.
2480
2818
  *
2481
- * Dates, Maps and Sets are supported too: their methods are reactive (reads
2482
- * track, writes notify), so `new Date()`, `new Map()` and `new Set()` can be
2483
- * used in watched state directly.
2819
+ * Only plain objects, plain arrays, and exact Date/Map/Set/URL/
2820
+ * URLSearchParams instances are deep-watched. Other values -- class instances,
2821
+ * subclasses, RegExp, typed arrays, frozen/non-extensible objects, promises,
2822
+ * DOM nodes, ... -- are returned unchanged. Effects still track the property
2823
+ * that holds them, so replacing the value is reactive even though mutating it
2824
+ * in place isn't.
2825
+ *
2826
+ * Dates, Maps, Sets, URLs and URLSearchParams are supported: their methods are
2827
+ * reactive (reads track, writes notify), so they can be used in watched state
2828
+ * directly.
2484
2829
  *
2485
2830
  * @param object The object to watch
2486
2831
  */
2487
2832
  function $watch(object, options) {
2488
2833
  if (object === void 0 || object === null || object[require_fromWebSocket.proxyDataSymbol] !== void 0) return object;
2834
+ if (!isWrappable(object)) {
2835
+ if (require_titleWarning.devContext.enabled) console.warn("$watch() only deep-watches plain objects, arrays and exact Date/Map/Set/URL/URLSearchParams instances; returning this value unchanged.");
2836
+ return object;
2837
+ }
2489
2838
  const data = {
2490
2839
  target: object,
2491
2840
  isArray: Array.isArray(object),
2492
2841
  isDate: object instanceof Date,
2493
2842
  isMap: object instanceof Map,
2494
2843
  isSet: object instanceof Set,
2844
+ isUrl: typeof URL !== "undefined" && object instanceof URL,
2845
+ isUrlParams: typeof URLSearchParams !== "undefined" && object instanceof URLSearchParams,
2495
2846
  shallow: options?.shallow === true,
2496
2847
  signals: /* @__PURE__ */ new Map()
2497
2848
  };
@@ -2502,7 +2853,7 @@ function $watch(object, options) {
2502
2853
  configurable: true
2503
2854
  });
2504
2855
  const proxy = new Proxy(object, sharedHandler);
2505
- require_devContext.devContext.onWatch(data);
2856
+ require_titleWarning.devContext.onWatch(data);
2506
2857
  return proxy;
2507
2858
  }
2508
2859
  //#endregion
@@ -2764,7 +3115,7 @@ function runList(region, parent, anchor, buildItems, create, update, noWatch) {
2764
3115
  const oldRegion = pushRegion(region, first);
2765
3116
  first = false;
2766
3117
  const newSpecs = buildItems();
2767
- if (require_devContext.devContext.enabled) checkListKeys(region, newSpecs);
3118
+ if (require_titleWarning.devContext.enabled) require_titleWarning.devContext.checkListKeys(region, newSpecs);
2768
3119
  context.activeTarget = null;
2769
3120
  listItems = runListItems(region, parent, anchor, listItems, newSpecs, create, update, noWatch);
2770
3121
  popRegion(oldRegion);
@@ -3048,7 +3399,7 @@ function setAttribute(el, name, value) {
3048
3399
  if (name === "value") {
3049
3400
  if (setValueProperty(el, String(value))) return;
3050
3401
  }
3051
- el.setAttribute(name, value);
3402
+ el.setAttribute(name, urlAttributeValue(name, value));
3052
3403
  }
3053
3404
  /** Sets the `value` property on a form control; returns false for other elements. */
3054
3405
  function setValueProperty(el, value) {
@@ -3500,6 +3851,7 @@ exports.fromServer = require_fromWebSocket.fromServer;
3500
3851
  exports.fromWebSocket = require_fromWebSocket.fromWebSocket;
3501
3852
  exports.hydrate = hydrate;
3502
3853
  exports.mount = mount;
3854
+ exports.setUrlRewriter = setUrlRewriter;
3503
3855
  exports.t_add_element = addElement;
3504
3856
  exports.t_add_fragment = addFragment;
3505
3857
  exports.t_anchor = nodeAnchor;