@torpor/view 0.4.18 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +41 -16
  2. package/dist/Cleanup-D0wvGW5d.d.cts +9 -0
  3. package/dist/Cleanup-D0wvGW5d.d.cts.map +1 -0
  4. package/dist/Cleanup-D0wvGW5d.d.mts +9 -0
  5. package/dist/Cleanup-D0wvGW5d.d.mts.map +1 -0
  6. package/dist/Component-0MH0zd-m.d.cts +11 -0
  7. package/dist/Component-0MH0zd-m.d.cts.map +1 -0
  8. package/dist/Component-0MH0zd-m.d.mts +11 -0
  9. package/dist/Component-0MH0zd-m.d.mts.map +1 -0
  10. package/dist/Effect-BTKurOpr.d.mts +381 -0
  11. package/dist/Effect-BTKurOpr.d.mts.map +1 -0
  12. package/dist/Effect-COl3aRJV.d.cts +381 -0
  13. package/dist/Effect-COl3aRJV.d.cts.map +1 -0
  14. package/dist/compile.cjs +1734 -739
  15. package/dist/compile.d.cts +85 -50
  16. package/dist/compile.d.cts.map +1 -1
  17. package/dist/compile.d.mts +85 -50
  18. package/dist/compile.d.mts.map +1 -1
  19. package/dist/compile.mjs +1737 -741
  20. package/dist/compile.mjs.map +1 -1
  21. package/dist/dev.cjs +62 -63
  22. package/dist/dev.d.cts +4 -3
  23. package/dist/dev.d.cts.map +1 -1
  24. package/dist/dev.d.mts +4 -3
  25. package/dist/dev.d.mts.map +1 -1
  26. package/dist/dev.mjs +61 -62
  27. package/dist/dev.mjs.map +1 -1
  28. package/dist/{devContext-B3yskfhA.cjs → devContext-BulTn3U5.cjs} +6 -9
  29. package/dist/{devContext-CQ8RhBX-.mjs → devContext-ZNsPyOgB.mjs} +3 -4
  30. package/dist/devContext-ZNsPyOgB.mjs.map +1 -0
  31. package/dist/fromWebSocket-1QOjcrHE.cjs +182 -0
  32. package/dist/fromWebSocket-B52kN3-W.d.mts +91 -0
  33. package/dist/fromWebSocket-B52kN3-W.d.mts.map +1 -0
  34. package/dist/fromWebSocket-DeB35Q4w.d.cts +91 -0
  35. package/dist/fromWebSocket-DeB35Q4w.d.cts.map +1 -0
  36. package/dist/fromWebSocket-Dxc_uwm1.mjs +137 -0
  37. package/dist/fromWebSocket-Dxc_uwm1.mjs.map +1 -0
  38. package/dist/index.cjs +2109 -494
  39. package/dist/index.d.cts +608 -112
  40. package/dist/index.d.cts.map +1 -1
  41. package/dist/index.d.mts +608 -112
  42. package/dist/index.d.mts.map +1 -1
  43. package/dist/index.mjs +2088 -490
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/ssr.cjs +78 -17
  46. package/dist/ssr.d.cts +64 -11
  47. package/dist/ssr.d.cts.map +1 -1
  48. package/dist/ssr.d.mts +64 -11
  49. package/dist/ssr.d.mts.map +1 -1
  50. package/dist/ssr.mjs +67 -14
  51. package/dist/ssr.mjs.map +1 -1
  52. package/package.json +21 -19
  53. package/dist/Cleanup-CYsytTEc.d.cts +0 -9
  54. package/dist/Cleanup-CYsytTEc.d.cts.map +0 -1
  55. package/dist/Cleanup-CgjyN0lW.d.mts +0 -9
  56. package/dist/Cleanup-CgjyN0lW.d.mts.map +0 -1
  57. package/dist/Component-DmWGMgak.d.mts +0 -11
  58. package/dist/Component-DmWGMgak.d.mts.map +0 -1
  59. package/dist/Component-kGLRFYg2.d.cts +0 -11
  60. package/dist/Component-kGLRFYg2.d.cts.map +0 -1
  61. package/dist/Region-Bb6HAb-F.d.cts +0 -201
  62. package/dist/Region-Bb6HAb-F.d.cts.map +0 -1
  63. package/dist/Region-CTchywkr.d.mts +0 -201
  64. package/dist/Region-CTchywkr.d.mts.map +0 -1
  65. package/dist/devContext-CQ8RhBX-.mjs.map +0 -1
  66. package/dist/formatText-BNP3P38F.d.cts +0 -17
  67. package/dist/formatText-BNP3P38F.d.cts.map +0 -1
  68. package/dist/formatText-D6Ov8Ub0.d.mts +0 -17
  69. package/dist/formatText-D6Ov8Ub0.d.mts.map +0 -1
  70. package/dist/formatText-DTIRmc3X.mjs +0 -61
  71. package/dist/formatText-DTIRmc3X.mjs.map +0 -1
  72. package/dist/formatText-Dhl2O0Ee.cjs +0 -96
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- const require_devContext = require('./devContext-B3yskfhA.cjs');
2
- const require_formatText = require('./formatText-Dhl2O0Ee.cjs');
3
-
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_devContext = require("./devContext-BulTn3U5.cjs");
3
+ const require_fromWebSocket = require("./fromWebSocket-1QOjcrHE.cjs");
4
4
  //#region src/render/context.ts
5
5
  const CONTEXT_SYMBOL = Symbol.for("torp.Context");
6
6
  const context = globalThis[CONTEXT_SYMBOL] ??= {
@@ -10,55 +10,41 @@ const context = globalThis[CONTEXT_SYMBOL] ??= {
10
10
  batch: 0,
11
11
  batchOperation: 0,
12
12
  registerComputed: null,
13
- firstEffectToRun: null,
13
+ effectsToRun: [],
14
14
  firstSignalToUpdate: null,
15
+ lastSignalToUpdate: null,
15
16
  activeRegion: null,
16
17
  previousRegion: null,
17
18
  rootRegion: null,
19
+ awaitBoundary: null,
20
+ suspendPeek: false,
21
+ suspendPeekHit: false,
22
+ refreshSignals: null,
23
+ refreshInitialized: null,
18
24
  mountEffects: [],
19
25
  stashedEvents: [],
20
26
  stashedAnimations: [],
21
27
  hydrationNode: null
22
28
  };
23
- var context_default = context;
24
-
25
29
  //#endregion
26
30
  //#region src/render/addAnimation.ts
27
31
  function addAnimation(el, entry, exit) {
28
- context_default.stashedAnimations.push({
29
- region: context_default.activeRegion,
32
+ context.stashedAnimations.push({
33
+ region: context.activeRegion,
30
34
  el,
31
35
  in: entry,
32
36
  out: exit
33
37
  });
34
38
  }
35
-
36
39
  //#endregion
37
40
  //#region src/render/addEvent.ts
38
41
  function addEvent(el, type, listener) {
39
- if (listener !== void 0 && listener !== null) context_default.stashedEvents.push({
40
- region: context_default.activeRegion,
42
+ if (listener !== void 0 && listener !== null) context.stashedEvents.push({
41
43
  el,
42
44
  type,
43
45
  listener
44
46
  });
45
47
  }
46
-
47
- //#endregion
48
- //#region src/types/constants.ts
49
- /**
50
- * The type of a Signal object.
51
- */
52
- const SIGNAL_TYPE = 0;
53
- /**
54
- * The type of a Computed object.
55
- */
56
- const COMPUTED_TYPE = 1;
57
- /**
58
- * The type of an Effect object.
59
- */
60
- const EFFECT_TYPE = 2;
61
-
62
48
  //#endregion
63
49
  //#region src/watch/clearSources.ts
64
50
  /**
@@ -77,7 +63,6 @@ function clearSources(target) {
77
63
  previousSub = clearSub;
78
64
  }
79
65
  }
80
-
81
66
  //#endregion
82
67
  //#region src/watch/deactivateSources.ts
83
68
  /**
@@ -86,7 +71,6 @@ function clearSources(target) {
86
71
  function deactivateSources(target) {
87
72
  for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) sourceSub.active = false;
88
73
  }
89
-
90
74
  //#endregion
91
75
  //#region src/watch/trackSignal.ts
92
76
  /**
@@ -94,60 +78,48 @@ function deactivateSources(target) {
94
78
  * run when the signal changes.
95
79
  */
96
80
  function trackSignal(signal) {
97
- const target = context_default.activeTarget;
81
+ const target = context.activeTarget;
98
82
  if (target !== null) {
99
- let sub = null;
100
- let lastSub = null;
101
- for (let nextSub = signal.firstTarget; nextSub !== null; nextSub = nextSub.nextTarget) {
102
- lastSub = nextSub;
103
- if (nextSub.target === target) {
104
- sub = nextSub;
105
- break;
106
- }
83
+ for (let existingSub = target.firstSource; existingSub !== null; existingSub = existingSub.nextSource) if (existingSub.source === signal) {
84
+ existingSub.active = true;
85
+ return;
107
86
  }
108
- if (sub === null) {
109
- sub = {
110
- source: signal,
111
- target,
112
- previousTarget: lastSub,
113
- nextTarget: null,
114
- nextSource: null,
115
- active: true,
116
- recalc: false
117
- };
118
- if (lastSub === null) signal.firstTarget = sub;
119
- else lastSub.nextTarget = sub;
120
- if (target.firstSource === null) target.firstSource = sub;
121
- else {
122
- let lastEffectSub = target.firstSource;
123
- for (let nextSub = lastEffectSub.nextSource; nextSub !== null; nextSub = nextSub.nextSource) lastEffectSub = nextSub;
124
- lastEffectSub.nextSource = sub;
125
- }
126
- } else sub.active = true;
87
+ const oldFirstTarget = signal.firstTarget;
88
+ const sub = {
89
+ source: signal,
90
+ target,
91
+ previousTarget: null,
92
+ nextTarget: oldFirstTarget,
93
+ nextSource: target.firstSource,
94
+ active: true,
95
+ recalc: false
96
+ };
97
+ if (oldFirstTarget !== null) oldFirstTarget.previousTarget = sub;
98
+ signal.firstTarget = sub;
99
+ target.firstSource = sub;
127
100
  }
128
101
  }
129
-
130
102
  //#endregion
131
103
  //#region src/watch/runComputed.ts
132
104
  function runComputed(computed) {
133
- const oldActiveTarget = context_default.activeTarget;
105
+ const oldActiveTarget = context.activeTarget;
134
106
  computed.running = true;
135
107
  computed.didError = false;
108
+ computed.didSuspend = false;
136
109
  try {
137
- context_default.activeTarget = computed;
110
+ context.activeTarget = computed;
138
111
  computed.value = computed.run();
139
112
  } catch (err) {
140
113
  computed.didError = true;
141
114
  computed.value = err;
142
115
  throw err;
143
116
  } finally {
144
- context_default.activeTarget = oldActiveTarget;
117
+ context.activeTarget = oldActiveTarget;
145
118
  computed.running = false;
146
119
  }
147
120
  trackSignal(computed);
148
121
  return computed.value;
149
122
  }
150
-
151
123
  //#endregion
152
124
  //#region src/watch/checkComputed.ts
153
125
  /**
@@ -171,7 +143,6 @@ function checkComputed(computed) {
171
143
  }
172
144
  return changed;
173
145
  }
174
-
175
146
  //#endregion
176
147
  //#region src/watch/checkSources.ts
177
148
  /**
@@ -180,21 +151,20 @@ function checkComputed(computed) {
180
151
  */
181
152
  function checkSources(target) {
182
153
  let haveComputed = false;
183
- for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc) if (sourceSub.source.type === SIGNAL_TYPE) return true;
154
+ for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc) if (sourceSub.source.type === 0) return true;
184
155
  else if (sourceSub.source.recalc) haveComputed = true;
185
156
  else return true;
186
157
  if (haveComputed) {
187
- for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc && sourceSub.source.type === COMPUTED_TYPE && sourceSub.source.recalc) {
188
- const oldActiveTarget = context_default.activeTarget;
189
- context_default.activeTarget = target;
158
+ for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc && sourceSub.source.type === 1 && sourceSub.source.recalc) {
159
+ const oldActiveTarget = context.activeTarget;
160
+ context.activeTarget = target;
190
161
  const recalc = checkComputed(sourceSub.source);
191
- context_default.activeTarget = oldActiveTarget;
162
+ context.activeTarget = oldActiveTarget;
192
163
  if (recalc) return true;
193
164
  }
194
165
  }
195
166
  return false;
196
167
  }
197
-
198
168
  //#endregion
199
169
  //#region src/watch/runCleanups.ts
200
170
  /**
@@ -203,9 +173,10 @@ function checkSources(target) {
203
173
  function runCleanups(effect) {
204
174
  let effectToClean = effect;
205
175
  for (let i = 0; i < effect.extent; i++) {
176
+ if (effectToClean === null) break;
206
177
  if (typeof effectToClean.cleanup === "function") {
207
- const oldActiveTarget = context_default.activeTarget;
208
- context_default.activeTarget = null;
178
+ const oldActiveTarget = context.activeTarget;
179
+ context.activeTarget = null;
209
180
  try {
210
181
  effectToClean.cleanup();
211
182
  } catch (err) {
@@ -214,18 +185,12 @@ function runCleanups(effect) {
214
185
  throw err;
215
186
  } finally {
216
187
  effectToClean.cleanup = void 0;
217
- context_default.activeTarget = oldActiveTarget;
188
+ context.activeTarget = oldActiveTarget;
218
189
  }
219
190
  }
220
- const nextEffect = effectToClean.nextEffect;
221
- if (i !== 0 && effect.nextEffectToRun === effectToClean) {
222
- effect.nextEffectToRun = effectToClean.nextEffectToRun;
223
- effectToClean.nextEffect = effectToClean.nextEffectToRun = null;
224
- }
225
- effectToClean = nextEffect;
191
+ effectToClean = effectToClean.nextEffect;
226
192
  }
227
193
  }
228
-
229
194
  //#endregion
230
195
  //#region src/watch/checkEffect.ts
231
196
  /**
@@ -240,130 +205,250 @@ function checkEffect(effect) {
240
205
  clearSources(effect);
241
206
  }
242
207
  }
243
-
244
208
  //#endregion
245
- //#region src/watch/clearTargets.ts
209
+ //#region src/watch/routeEffectError.ts
246
210
  /**
247
- * Clear unused target subscriptions after all Effects have been run.
211
+ * Routes an error thrown by an effect re-run to the nearest enclosing error
212
+ * boundary (`@try`/`@catch` or top-level `@error`), and forces the boundary's
213
+ * control effect to re-run so it renders its catch branch. Returns true if a
214
+ * boundary handled the error.
215
+ *
216
+ * The boundary is found by walking the flattened region chain from the
217
+ * effect's owning region (`Effect.region`, set by `$run`) through its
218
+ * ancestors (regions with strictly decreasing depth on the `previousRegion`
219
+ * chain — the same shape `clearRegion` walks).
220
+ *
221
+ * For recovery, the boundary holds the failing effect's source signals
222
+ * (captured by `runEffect` before it cleared them, `Effect.errorSources`)
223
+ * together with the boundary effect's own sources: reads wrapped in nested
224
+ * `$run` effects (text/attribute interpolation) are tracked by those
225
+ * effects, not the boundary, so without holding them the catch branch would
226
+ * never re-attempt the try branch. `runTry` re-subscribes the boundary
227
+ * effect to the held signals on every run that shows the catch branch.
228
+ *
229
+ * Called from `triggerEffects`' per-effect catch. If forcing the boundary
230
+ * re-run itself throws (e.g. the catch branch content errors), the error
231
+ * propagates to the caller, which reports it as unhandled — matching the
232
+ * compiled form, where a throwing catch branch escapes the boundary.
248
233
  */
249
- function clearTargets(source) {
250
- let previousSub = null;
251
- for (let clearSub = source.firstTarget; clearSub !== null; clearSub = clearSub.nextTarget) if (!clearSub.active) if (previousSub === null) source.firstTarget = clearSub.nextTarget;
252
- else previousSub.nextTarget = clearSub.nextTarget;
253
- else previousSub = clearSub;
234
+ function routeEffectError(effect, error) {
235
+ let region = effect.region ?? null;
236
+ while (region !== null) {
237
+ const boundary = region.errorBoundary;
238
+ if (boundary !== void 0 && boundary.effect !== null) {
239
+ const boundaryEffect = boundary.effect;
240
+ const held = [];
241
+ for (let sub = boundaryEffect.firstSource; sub !== null; sub = sub.nextSource) held.push(sub.source);
242
+ for (const signal of effect.errorSources ?? []) if (!held.includes(signal)) held.push(signal);
243
+ boundary.error = error;
244
+ boundary.hasError = true;
245
+ boundary.heldSignals = held;
246
+ runCleanups(boundaryEffect);
247
+ deactivateSources(boundaryEffect);
248
+ runEffect(boundaryEffect);
249
+ clearSources(boundaryEffect);
250
+ return true;
251
+ }
252
+ const depth = region.depth;
253
+ let previous = region.previousRegion;
254
+ while (previous !== null && previous.depth >= depth) previous = previous.previousRegion;
255
+ region = previous;
256
+ }
257
+ return false;
254
258
  }
255
-
256
259
  //#endregion
257
260
  //#region src/watch/triggerEffects.ts
258
261
  /**
262
+ * Re-subscribes a failed effect to the suspended computeds its run had read,
263
+ * after `runEffect`'s catch detached them via `clearSources`. Called when no
264
+ * error boundary handled the crash: the error still surfaces (see below),
265
+ * but the promise's resolve re-runs the effect, so a crash caused by a
266
+ * pending read's `undefined` heals instead of leaving a dead effect.
267
+ */
268
+ function resubscribeSuspendSources(effect) {
269
+ const sources = effect.suspendSources;
270
+ if (!sources || sources.size === 0) return;
271
+ const oldActive = context.activeTarget;
272
+ context.activeTarget = effect;
273
+ for (const signal of sources) trackSignal(signal);
274
+ context.activeTarget = oldActive;
275
+ }
276
+ /**
259
277
  * Runs the effects that have been collected during the batch.
260
278
  */
261
279
  function triggerEffects() {
262
- let didError = false;
263
- let error;
264
- let effect = context_default.firstEffectToRun;
265
- while (effect !== null) {
266
- context_default.batchOperation++;
280
+ let unhandledError = null;
281
+ const queue = context.effectsToRun;
282
+ for (let i = 0; i < queue.length; i++) {
283
+ const effect = queue[i];
284
+ context.batchOperation++;
285
+ effect.queued = false;
267
286
  try {
268
287
  checkEffect(effect);
269
288
  } catch (err) {
270
- if (!didError) {
271
- didError = true;
272
- error = err;
289
+ let handled = false;
290
+ try {
291
+ handled = routeEffectError(effect, err);
292
+ } catch (routingError) {
293
+ if (unhandledError === null) unhandledError = { error: routingError };
294
+ }
295
+ if (!handled) {
296
+ resubscribeSuspendSources(effect);
297
+ if (unhandledError === null) unhandledError = { error: err };
273
298
  }
274
299
  }
275
- effect = effect.nextEffectToRun;
276
- }
277
- effect = context_default.firstEffectToRun;
278
- context_default.firstEffectToRun = null;
279
- while (effect !== null) {
280
- let nextEffect = effect.nextEffectToRun;
281
- effect.nextEffectToRun = null;
282
- effect = nextEffect;
283
300
  }
284
- let signal = context_default.firstSignalToUpdate;
285
- context_default.firstSignalToUpdate = null;
301
+ for (let effect of queue) effect.queued = false;
302
+ context.effectsToRun = [];
303
+ let signal = context.firstSignalToUpdate;
304
+ context.firstSignalToUpdate = null;
305
+ context.lastSignalToUpdate = null;
286
306
  while (signal !== null) {
287
- clearTargets(signal);
288
307
  const nextSignal = signal.nextSignalToUpdate;
289
308
  signal.nextSignalToUpdate = null;
290
309
  signal = nextSignal;
291
310
  }
292
- if (didError) throw error;
311
+ if (unhandledError !== null) throw unhandledError.error;
293
312
  }
294
-
295
313
  //#endregion
296
314
  //#region src/watch/batchEnd.ts
297
315
  function batchEnd() {
298
- if (context_default.batch > 1) {
299
- context_default.batch--;
316
+ if (context.batch > 1) {
317
+ context.batch--;
300
318
  return;
301
319
  }
302
320
  try {
303
321
  triggerEffects();
304
322
  } finally {
305
- context_default.batch = 0;
306
- context_default.batchOperation = 0;
307
- context_default.previousEffect = null;
323
+ context.batch = 0;
324
+ context.batchOperation = 0;
325
+ context.previousEffect = null;
308
326
  }
309
327
  }
310
-
311
328
  //#endregion
312
329
  //#region src/watch/batchStart.ts
313
330
  function batchStart() {
314
- context_default.batch++;
331
+ context.batch++;
315
332
  }
316
-
317
333
  //#endregion
318
334
  //#region src/watch/runEffect.ts
319
335
  function runEffect(effect) {
320
- require_devContext.devContext_default.effectRun(effect);
321
- const oldActiveTarget = context_default.activeTarget;
322
- const oldExtent = context_default.extent;
336
+ require_devContext.devContext.effectRun(effect);
337
+ const oldActiveTarget = context.activeTarget;
338
+ const oldExtent = context.extent;
323
339
  effect.didError = false;
340
+ effect.errorSources = null;
341
+ effect.didSuspend = false;
342
+ effect.suspendSources = null;
324
343
  batchStart();
325
344
  try {
326
- if (context_default.previousEffect !== null) context_default.previousEffect.nextEffect = effect;
327
- context_default.activeTarget = effect;
328
- context_default.previousEffect = effect;
329
- context_default.extent = 1;
345
+ if (context.previousEffect !== null) context.previousEffect.nextEffect = effect;
346
+ context.activeTarget = effect;
347
+ context.previousEffect = effect;
348
+ context.extent = 1;
330
349
  effect.cleanup = effect.run();
331
- effect.extent = context_default.extent;
350
+ effect.extent = context.extent;
332
351
  } catch (err) {
333
352
  effect.didError = true;
353
+ let sources = null;
354
+ for (let sub = effect.firstSource; sub !== null; sub = sub.nextSource) (sources ??= []).push(sub.source);
355
+ effect.errorSources = sources;
334
356
  clearSources(effect);
335
357
  throw err;
336
358
  } finally {
337
- context_default.activeTarget = oldActiveTarget;
338
- context_default.extent += oldExtent - 1;
359
+ context.activeTarget = oldActiveTarget;
360
+ context.extent += oldExtent - 1;
339
361
  batchEnd();
340
362
  }
341
363
  }
342
-
343
364
  //#endregion
344
365
  //#region src/watch/$run.ts
345
366
  /**
346
367
  * Runs and re-runs a function that depends on a watched object
347
368
  *
348
369
  * @param fn The function to run, which may return a cleanup function.
370
+ * @param options Internal fields to set on the constructed Effect (e.g.
371
+ * `isMountEffect`, `forVarDeps`). Not part of the public API.
349
372
  */
350
- function $run(fn, name) {
373
+ function $run(fn, name, options) {
351
374
  let effect = {
352
- type: EFFECT_TYPE,
375
+ type: 2,
353
376
  run: fn,
354
377
  cleanup: void 0,
355
378
  firstSource: null,
356
379
  nextEffect: null,
357
380
  extent: 0,
358
- nextEffectToRun: null,
381
+ queued: false,
359
382
  didError: false,
360
- name
383
+ didSuspend: false,
384
+ region: null,
385
+ errorSources: null,
386
+ name,
387
+ isMountEffect: options?.isMountEffect,
388
+ forVarMask: options?.forVarMask
361
389
  };
362
- require_devContext.devContext_default.onRun(effect);
390
+ const region = context.activeRegion;
391
+ if (region !== null) {
392
+ region.effects.push(effect);
393
+ effect.region = region;
394
+ }
395
+ require_devContext.devContext.onRun(effect);
363
396
  runEffect(effect);
364
397
  return effect;
365
398
  }
366
-
399
+ //#endregion
400
+ //#region src/watch/$peek.ts
401
+ /**
402
+ * Runs a function without tracking the reactive values it reads: `$watch`'d
403
+ * state accessed inside `fn` does not become a dependency of the currently
404
+ * running effect or computed. Useful for reading state inside an effect
405
+ * without re-running it when that state changes.
406
+ *
407
+ * @param fn The function to run untracked.
408
+ */
409
+ function $peek(fn) {
410
+ const oldActiveTarget = context.activeTarget;
411
+ context.activeTarget = null;
412
+ const result = fn();
413
+ context.activeTarget = oldActiveTarget;
414
+ return result;
415
+ }
416
+ //#endregion
417
+ //#region src/watch/flushMountEffects.ts
418
+ /**
419
+ * Runs the collected `$onmount`/`onmount` callbacks — once, after the
420
+ * component's markup has been added to the DOM (or, when hydrating, after
421
+ * hydration is complete). Multiple callbacks run in the order they were
422
+ * added.
423
+ *
424
+ * Each callback becomes an effect with `isMountEffect` set, so the keyed-list
425
+ * reconciler's force-rerun path (`rerunRegionEffects`) skips it. Its body
426
+ * also runs untracked: mount callbacks are once-only, so reactive reads
427
+ * inside them do not subscribe. In dev builds a tracked pass warns when a
428
+ * callback reads reactive state, since that is almost always a mistake — the
429
+ * reactive part should be wrapped in `$run`.
430
+ */
431
+ function flushMountEffects() {
432
+ if (context.mountEffects.length === 0) return;
433
+ const activeRegion = context.activeRegion;
434
+ for (let effect of context.mountEffects) {
435
+ context.activeRegion = effect.region;
436
+ $run(() => runMountCallback(effect.fn), void 0, { isMountEffect: true });
437
+ }
438
+ context.activeRegion = activeRegion;
439
+ context.mountEffects.length = 0;
440
+ }
441
+ function runMountCallback(fn) {
442
+ if (!require_devContext.devContext.enabled) return $peek(fn);
443
+ const result = fn();
444
+ const effect = context.activeTarget;
445
+ if (effect !== null && effect.type === 2 && effect.firstSource !== null) {
446
+ 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(() => ...); });");
447
+ deactivateSources(effect);
448
+ clearSources(effect);
449
+ }
450
+ return result;
451
+ }
367
452
  //#endregion
368
453
  //#region src/render/animate.ts
369
454
  /**
@@ -384,76 +469,279 @@ async function animate(el, enter, keyframes, options) {
384
469
  setTimeout(() => {
385
470
  animation.timeline = el.ownerDocument.timeline;
386
471
  }, 1);
387
- const activeRegion = context_default.activeRegion;
472
+ const activeRegion = context.activeRegion;
388
473
  activeRegion.animations ??= /* @__PURE__ */ new Set();
389
474
  activeRegion.animations.add(animation);
390
475
  await animation.finished;
391
476
  }
392
-
477
+ //#endregion
478
+ //#region src/render/delegatedEvents.ts
479
+ /**
480
+ * Event delegation.
481
+ *
482
+ * For event types in `DELEGATED_EVENT_TYPES` (all natively bubbling), we
483
+ * register a single listener on `document` per type and dispatch by walking
484
+ * up from `event.target` to find the closest ancestor with a stashed handler.
485
+ * This replaces per-element `addEventListener` for delegated types.
486
+ *
487
+ * Why: in the js-framework-bench row template, every `<tr>` clones two `<a>`
488
+ * elements each with a `click` handler. With per-element `addEventListener`,
489
+ * `runlots` (10k rows) issues 20000 `addEventListener` calls and the browser
490
+ * allocates 20000 `Listener` objects. With delegation it's 2 calls total
491
+ * (one per delegated type, registered lazily on first use) and zero
492
+ * per-element `Listener` allocations — the handler is stored as a property
493
+ * on the element.
494
+ *
495
+ * Model: last-write-wins per element per type (same as Solid's
496
+ * `delegateEvents`). Repeated `t_event(el, "click", h)` calls with the same
497
+ * element reassign the property; calling with `null`/`undefined` clears it.
498
+ * Torpor's compiler emits `t_event(el, type, h)` exactly once per element
499
+ * lifetime (outside any tracked effect), so this is the natural shape.
500
+ *
501
+ * Non-bubbling events (`focus`, `blur`, `scroll`, `load`, `error`, `abort`,
502
+ * `unload`, `resize`, etc.) bypass delegation and use direct
503
+ * `addEventListener` on the element, preserving native semantics.
504
+ */
505
+ const DELEGATED_EVENT_TYPES = /* @__PURE__ */ new Set([
506
+ "auxclick",
507
+ "beforeinput",
508
+ "change",
509
+ "click",
510
+ "compositionend",
511
+ "compositionstart",
512
+ "compositionupdate",
513
+ "contextmenu",
514
+ "dblclick",
515
+ "drag",
516
+ "dragend",
517
+ "dragenter",
518
+ "dragleave",
519
+ "dragover",
520
+ "dragstart",
521
+ "drop",
522
+ "focusin",
523
+ "focusout",
524
+ "input",
525
+ "keydown",
526
+ "keypress",
527
+ "keyup",
528
+ "mousedown",
529
+ "mousemove",
530
+ "mouseout",
531
+ "mouseover",
532
+ "mouseup",
533
+ "pointerdown",
534
+ "pointermove",
535
+ "pointerout",
536
+ "pointerover",
537
+ "pointerup",
538
+ "reset",
539
+ "submit",
540
+ "touchend",
541
+ "touchmove",
542
+ "touchstart",
543
+ "wheel"
544
+ ]);
545
+ function isDelegatedEventType(type) {
546
+ return DELEGATED_EVENT_TYPES.has(type);
547
+ }
548
+ const DELEGATE_PREFIX = "torp.$$";
549
+ const DELEGATE_REGISTERED = Symbol.for("torp.delegated.registered");
550
+ function delegatedHandler(event) {
551
+ let node = event.target;
552
+ const stopAt = event.currentTarget;
553
+ const key = DELEGATE_PREFIX + event.type;
554
+ while (node != null && node !== stopAt) {
555
+ const handler = node[key];
556
+ if (handler !== void 0) {
557
+ Object.defineProperty(event, "currentTarget", {
558
+ configurable: true,
559
+ value: node,
560
+ writable: false
561
+ });
562
+ try {
563
+ handler.call(node, event);
564
+ } finally {
565
+ delete event.currentTarget;
566
+ }
567
+ return;
568
+ }
569
+ node = node.parentNode;
570
+ }
571
+ }
572
+ function ensureDelegatedListener(type) {
573
+ if (typeof document === "undefined") return;
574
+ let registered = document[DELEGATE_REGISTERED];
575
+ if (!registered) {
576
+ registered = /* @__PURE__ */ new Set();
577
+ document[DELEGATE_REGISTERED] = registered;
578
+ }
579
+ if (registered.has(type)) return;
580
+ registered.add(type);
581
+ document.addEventListener(type, delegatedHandler);
582
+ }
583
+ /**
584
+ * Attach a delegated event handler to an element.
585
+ *
586
+ * Stores the handler as a property on the element and ensures a single
587
+ * document-level listener exists for the type. Idempotent for the
588
+ * document-level listener: the first call for a given type registers it,
589
+ * subsequent calls are a Set-has check.
590
+ *
591
+ * Passing `null` or `undefined` as the listener clears any previously-set
592
+ * handler for that type on the element (mirroring `addEvent`'s existing
593
+ * null-skipping semantics, extended to support explicit removal).
594
+ */
595
+ function attachDelegatedEvent(el, type, listener) {
596
+ const key = DELEGATE_PREFIX + type;
597
+ if (listener === void 0 || listener === null) {
598
+ el[key] = void 0;
599
+ return;
600
+ }
601
+ ensureDelegatedListener(type);
602
+ el[key] = listener;
603
+ }
604
+ const DIRECT_LISTENERS = "torp.$directListeners";
605
+ /**
606
+ * Records a direct (non-delegated) listener on the element at attach time,
607
+ * so `copyEventListeners` can re-attach it after a dynamic-element tag
608
+ * swap. `addEventListener` listeners can't be discovered after the fact.
609
+ */
610
+ function recordDirectListener(el, type, listener) {
611
+ let list = el[DIRECT_LISTENERS];
612
+ if (!list) {
613
+ list = [];
614
+ el[DIRECT_LISTENERS] = list;
615
+ }
616
+ list.push({
617
+ type,
618
+ listener
619
+ });
620
+ }
621
+ /**
622
+ * Copies the event listeners attached to one element onto another — used by
623
+ * `t_dynamic` so a dynamic element keeps its listeners when its tag changes.
624
+ * Delegated handlers are `torp.$$<type>` properties, copied per known
625
+ * delegated type (swaps are rare, so the fixed set of checks is fine);
626
+ * direct listeners are re-registered from the list `recordDirectListener`
627
+ * built at attach time.
628
+ */
629
+ function copyEventListeners(from, to) {
630
+ for (const type of DELEGATED_EVENT_TYPES) {
631
+ const key = DELEGATE_PREFIX + type;
632
+ const handler = from[key];
633
+ if (handler !== void 0) to[key] = handler;
634
+ }
635
+ const direct = from[DIRECT_LISTENERS];
636
+ if (direct) {
637
+ to[DIRECT_LISTENERS] = direct;
638
+ for (const { type, listener } of direct) to.addEventListener(type, listener);
639
+ }
640
+ }
393
641
  //#endregion
394
642
  //#region src/render/isFragmentNode.ts
395
643
  function isFragmentNode(node) {
396
644
  return node.nodeType === 11;
397
645
  }
398
-
646
+ //#endregion
647
+ //#region src/render/runMountSideEffects.ts
648
+ /**
649
+ * Runs the mount-time side effects that both `addFragment` and `addElement`
650
+ * share: `$onmount` effects (only when not hydrating), stashed event
651
+ * listeners, and stashed animations. No-op when `parent` is itself a
652
+ * `DocumentFragment` (we're being inserted into a detached tree, so
653
+ * `$onmount` and event hookup would be premature — they'll run when the
654
+ * outer fragment attaches).
655
+ *
656
+ * Extracted so the `DocumentFragment` path (`addFragment`) and the
657
+ * single-element path (`addElement`) don't duplicate this logic.
658
+ */
659
+ function runMountSideEffects(parent, activeRegion, hydrationNode) {
660
+ if (isFragmentNode(parent)) return;
661
+ if (hydrationNode === null) flushMountEffects();
662
+ if (context.stashedEvents.length > 0) {
663
+ for (let event of context.stashedEvents) if (isDelegatedEventType(event.type)) attachDelegatedEvent(event.el, event.type, event.listener);
664
+ else {
665
+ event.el.addEventListener(event.type, event.listener);
666
+ recordDirectListener(event.el, event.type, event.listener);
667
+ }
668
+ context.stashedEvents.length = 0;
669
+ }
670
+ for (let animation of context.stashedAnimations) {
671
+ context.activeRegion = animation.region;
672
+ $run(function runMountSideEffectsAnimation() {
673
+ if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
674
+ if (animation.out !== void 0) return () => {
675
+ animate(animation.el, false, animation.out.keyframes, animation.out.options);
676
+ };
677
+ });
678
+ }
679
+ context.stashedAnimations.length = 0;
680
+ context.activeRegion = activeRegion;
681
+ }
682
+ //#endregion
683
+ //#region src/render/addElement.ts
684
+ /**
685
+ * Companion to `addFragment` for the single-root-element codegen path. Wires
686
+ * a cloned root element (produced by `getElementFragment`) into the live DOM
687
+ * tree, sets the active region's start/end nodes, and runs the same
688
+ * mount-time side effects as `addFragment` (`$onmount` effects, stashed event
689
+ * listeners, stashed animations).
690
+ *
691
+ * Differences from `addFragment`:
692
+ * - `node` is both the start and end of the region (no
693
+ * `fragment.firstChild`/`fragment.lastChild` indirection).
694
+ * - When hydrating, the existing DOM node is reused (the cloned `node` is
695
+ * discarded); `endNode` is still `node` because `nodeRootElement` returns
696
+ * the hydration cursor's node in that case, not the cloned one.
697
+ *
698
+ * @param node The root element (cloned by `getElementFragment`, or the
699
+ * hydration cursor's node when hydrating).
700
+ * @param parent The intended parent element.
701
+ * @param before The sibling to insert before (or `null` to append).
702
+ */
703
+ function addElement(node, parent, before) {
704
+ const activeRegion = context.activeRegion;
705
+ const hydrationNode = context.hydrationNode;
706
+ activeRegion.startNode = node;
707
+ activeRegion.endNode = node;
708
+ parent = before?.parentNode ?? parent;
709
+ if (hydrationNode === null) parent.insertBefore(node, before);
710
+ runMountSideEffects(parent, activeRegion, hydrationNode);
711
+ }
399
712
  //#endregion
400
713
  //#region src/render/addFragment.ts
401
- function addFragment(fragment, parent, before, endNode) {
402
- const activeRegion = context_default.activeRegion;
403
- const hydrationNode = context_default.hydrationNode;
404
- if (hydrationNode !== null) activeRegion.endNode = endNode ?? hydrationNode;
405
- else {
714
+ function addFragment(fragment, parent, before, endNode, startNode) {
715
+ const activeRegion = context.activeRegion;
716
+ const hydrationNode = context.hydrationNode;
717
+ if (hydrationNode !== null) {
718
+ if (startNode !== void 0 && startNode.parentNode !== null) activeRegion.startNode = startNode;
719
+ activeRegion.endNode = endNode ?? hydrationNode;
720
+ } else {
406
721
  activeRegion.startNode = fragment.firstChild;
407
722
  activeRegion.endNode = fragment.lastChild;
408
723
  }
409
724
  parent = before?.parentNode ?? parent;
410
725
  if (hydrationNode === null) parent.insertBefore(fragment, before);
411
- if (!isFragmentNode(parent)) {
412
- if (hydrationNode === null) {
413
- for (let effect of context_default.mountEffects) $run(effect);
414
- context_default.mountEffects.length = 0;
415
- }
416
- if (context_default.stashedEvents.length > 0) {
417
- const events = [...context_default.stashedEvents];
418
- $run(function addFragmentEvents() {
419
- for (let event of events) event.el.addEventListener(event.type, event.listener);
420
- return () => {
421
- for (let event of events) event.el.removeEventListener(event.type, event.listener);
422
- };
423
- });
424
- context_default.stashedEvents.length = 0;
425
- }
426
- for (let animation of context_default.stashedAnimations) {
427
- context_default.activeRegion = animation.region;
428
- $run(function addFragmentAnimation() {
429
- if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
430
- if (animation.out !== void 0) return () => {
431
- animate(animation.el, false, animation.out.keyframes, animation.out.options);
432
- };
433
- });
434
- }
435
- context_default.stashedAnimations.length = 0;
436
- context_default.activeRegion = activeRegion;
437
- }
726
+ runMountSideEffects(parent, activeRegion, hydrationNode);
438
727
  }
439
-
440
728
  //#endregion
441
729
  //#region src/render/applyProps.ts
442
730
  function applyProps(el, props, propNamesUsed) {
443
731
  if (props !== void 0) {
444
732
  for (let [name, value] of Object.entries(props)) if (!propNamesUsed.includes(name)) if (name.startsWith("on")) {
445
733
  const eventName = name.substring(2);
446
- el.addEventListener(eventName, value);
447
- } else $run(function setAttribute$1() {
734
+ if (isDelegatedEventType(eventName)) attachDelegatedEvent(el, eventName, value);
735
+ else el.addEventListener(eventName, value);
736
+ } else $run(function setAttribute() {
448
737
  el.setAttribute(name, value);
449
738
  });
450
739
  }
451
740
  }
452
-
453
741
  //#endregion
454
742
  //#region src/render/clearRegion.ts
455
743
  function clearRegion(region) {
456
- require_devContext.devContext_default.onRegionCleared(region);
744
+ require_devContext.devContext.onRegionCleared(region);
457
745
  let animations = region.animations !== null ? Array.from(region.animations) : void 0;
458
746
  let childRegion = region.nextRegion;
459
747
  while (childRegion !== null && childRegion.depth > region.depth) {
@@ -461,9 +749,10 @@ function clearRegion(region) {
461
749
  animations ??= [];
462
750
  animations.push(...childRegion.animations);
463
751
  }
752
+ const nextChild = childRegion.nextRegion;
464
753
  releaseRegion(childRegion);
465
754
  childRegion.depth = -2;
466
- childRegion = childRegion.nextRegion;
755
+ childRegion = nextChild;
467
756
  }
468
757
  region.nextRegion = childRegion;
469
758
  if (region.previousRegion !== null) region.previousRegion.nextRegion = region.nextRegion;
@@ -478,31 +767,83 @@ function clearRegion(region) {
478
767
  }
479
768
  function clearNodes(region) {
480
769
  if (region.startNode !== null && region.endNode !== null) {
770
+ const after = region.endNode.nextSibling;
771
+ let stop = region.startNode;
772
+ const startDetached = region.startNode.parentNode === null;
773
+ let fallback = false;
774
+ if (startDetached) {
775
+ let prev = region.previousRegion;
776
+ while (prev !== null && prev.depth > region.depth) prev = prev.previousRegion;
777
+ if (prev !== null && prev.endNode !== null && prev.endNode.parentNode !== null) {
778
+ stop = prev.endNode;
779
+ fallback = true;
780
+ }
781
+ }
481
782
  let currentNode = region.endNode;
482
- while (currentNode !== region.startNode) {
783
+ while (currentNode !== null && currentNode !== stop) {
483
784
  let previousNode = currentNode.previousSibling;
484
785
  currentNode.remove();
786
+ if (previousNode === null) break;
485
787
  currentNode = previousNode;
486
788
  }
487
- currentNode.remove();
789
+ if (!fallback && currentNode === region.startNode) currentNode.remove();
790
+ const firstRemaining = fallback ? stop : after;
791
+ if (firstRemaining !== null) {
792
+ let ancestor = region.previousRegion;
793
+ let ancestorDepth = region.depth;
794
+ while (ancestor !== null && ancestor.depth < ancestorDepth) {
795
+ if (ancestor.startNode !== null && ancestor.startNode.parentNode === null) ancestor.startNode = firstRemaining;
796
+ ancestorDepth = ancestor.depth;
797
+ ancestor = ancestor.previousRegion;
798
+ }
799
+ }
488
800
  }
489
801
  releaseRegion(region);
490
802
  }
491
803
  function releaseRegion(region) {
804
+ region.generation = -1;
492
805
  region.startNode = null;
493
806
  region.endNode = null;
494
807
  region.previousRegion = null;
495
808
  region.nextRegion = null;
496
809
  region.animations = null;
810
+ region.errorBoundary = void 0;
811
+ for (const effect of region.effects) {
812
+ if (typeof effect.cleanup === "function") {
813
+ effect.cleanup();
814
+ effect.cleanup = void 0;
815
+ }
816
+ let sub = effect.firstSource;
817
+ effect.firstSource = null;
818
+ while (sub !== null) {
819
+ const nextSource = sub.nextSource;
820
+ const prev = sub.previousTarget;
821
+ const next = sub.nextTarget;
822
+ if (prev === null) {
823
+ if (sub.source.firstTarget === sub) sub.source.firstTarget = next;
824
+ } else prev.nextTarget = next;
825
+ if (next !== null) next.previousTarget = prev;
826
+ sub.previousTarget = null;
827
+ sub.nextTarget = null;
828
+ sub.nextSource = null;
829
+ sub = nextSource;
830
+ }
831
+ }
832
+ region.effects.length = 0;
497
833
  }
498
-
499
834
  //#endregion
500
835
  //#region src/render/clearLayoutSlot.ts
836
+ /**
837
+ * Clears a region that was created by `fillLayoutSlot`: tears down the
838
+ * rendered content and its effects, leaving the surrounding layout intact
839
+ * so the slot can be refilled.
840
+ *
841
+ * @param region The region to clear
842
+ */
501
843
  function clearLayoutSlot(region) {
502
- context_default.previousRegion = region.previousRegion;
844
+ context.previousRegion = region.previousRegion;
503
845
  clearRegion(region);
504
846
  }
505
-
506
847
  //#endregion
507
848
  //#region src/render/newRegion.ts
508
849
  function newRegion(name) {
@@ -513,45 +854,80 @@ function newRegion(name) {
513
854
  nextRegion: null,
514
855
  depth: -1,
515
856
  animations: null,
516
- name
857
+ name,
858
+ effects: []
517
859
  };
518
860
  }
519
-
520
861
  //#endregion
521
862
  //#region src/render/popRegion.ts
522
863
  function popRegion(oldRegion) {
523
- context_default.activeRegion = oldRegion;
524
- require_devContext.devContext_default.onRegionPopped();
864
+ context.activeRegion = oldRegion;
865
+ require_devContext.devContext.onRegionPopped();
525
866
  }
526
-
527
867
  //#endregion
528
868
  //#region src/render/pushRegion.ts
529
869
  function pushRegion(region, toParent = false) {
530
- const activeRegion = context_default.activeRegion;
870
+ const activeRegion = context.activeRegion;
531
871
  if (toParent) {
532
- const previousRegion = context_default.previousRegion;
872
+ const previousRegion = context.previousRegion;
533
873
  region.previousRegion = previousRegion;
534
874
  const nextRegion = previousRegion.nextRegion;
535
875
  previousRegion.nextRegion = region;
536
876
  region.nextRegion = nextRegion;
877
+ if (nextRegion !== null) nextRegion.previousRegion = region;
537
878
  region.depth = activeRegion.depth + 1;
538
879
  }
539
- context_default.activeRegion = region;
540
- context_default.previousRegion = region;
541
- require_devContext.devContext_default.onRegionPushed(region, toParent);
880
+ context.activeRegion = region;
881
+ context.previousRegion = region;
882
+ require_devContext.devContext.onRegionPushed(region, toParent);
542
883
  return activeRegion;
543
884
  }
544
-
545
885
  //#endregion
546
886
  //#region src/render/fillLayoutSlot.ts
887
+ /**
888
+ * Renders a component into a persistent layout slot, and returns the region
889
+ * it was rendered into. Used by the layout engine during navigation: the
890
+ * component is created inside `parent` at `anchor`, with `slot` as its child
891
+ * slot render, and the returned region can later be passed to
892
+ * `clearLayoutSlot` to tear the page down — leaving the layout itself
893
+ * intact — before refilling the slot.
894
+ *
895
+ * @param component The component to render into the slot
896
+ * @param slot The slot render to pass to the component
897
+ * @param parent The parent node to render into
898
+ * @param anchor The node to insert content before, or null to append
899
+ * @param $props Optional props to pass to the component
900
+ * @param $context Optional context to pass to the component
901
+ */
547
902
  function fillLayoutSlot(component, slot, parent, anchor, $props, $context) {
548
- const region = newRegion(require_devContext.devContext_default.enabled ? "Layout slot" : void 0);
903
+ const region = newRegion(require_devContext.devContext.enabled ? "Layout slot" : void 0);
549
904
  const oldRegion = pushRegion(region, true);
550
905
  component(parent, anchor, $props, $context, { _: slot });
551
906
  popRegion(oldRegion);
552
907
  return region;
553
908
  }
554
-
909
+ //#endregion
910
+ //#region src/render/firstInsideNode.ts
911
+ /**
912
+ * During hydration, `nodeAnchor` finds the first node inside a hydration
913
+ * block and removes the start/end marker comments. Generated code for
914
+ * `@html` needs that first node later (to adopt the server-rendered nodes
915
+ * as the region's bounds), but by then the markers are gone — so the only
916
+ * reliable way to recover it is to stash it here, keyed by the anchor node
917
+ * that `nodeAnchor` returns.
918
+ */
919
+ const firstInsideNodes = /* @__PURE__ */ new WeakMap();
920
+ function setFirstInsideNode(anchor, node) {
921
+ firstInsideNodes.set(anchor, node);
922
+ }
923
+ /**
924
+ * Gets the first node that was inside the hydration block for the given
925
+ * anchor node, or `undefined` if the anchor wasn't hydrated through
926
+ * hydration markers.
927
+ */
928
+ function firstInsideNode(anchor) {
929
+ return firstInsideNodes.get(anchor);
930
+ }
555
931
  //#endregion
556
932
  //#region src/render/getFragment.ts
557
933
  function getFragment(document, array, index, html, ns) {
@@ -568,7 +944,44 @@ function getFragment(document, array, index, html, ns) {
568
944
  }
569
945
  return array[index].cloneNode(true);
570
946
  }
571
-
947
+ //#endregion
948
+ //#region src/render/getElementFragment.ts
949
+ /**
950
+ * Returns a clone of the cached template's single root element, bypassing the
951
+ * `DocumentFragment` wrapper that `getFragment` produces.
952
+ *
953
+ * Used by the compiler-emitted `createListItem` for `@for` bodies (and other
954
+ * fragments) whose template has exactly one rendering root child — e.g.
955
+ * `<tr><td>...</td>...</tr>`. Cloning `template.content.firstElementChild`
956
+ * directly saves the per-row `DocumentFragment` allocation that `getFragment`'s
957
+ * `cloneNode(true)` on the cached template's content would otherwise produce,
958
+ * which dominates the cost of bulk-row creates (`run`/`add`/`runlots`).
959
+ *
960
+ * Contract: the compiler only emits `t_fragment_el` for fragment indices whose
961
+ * template has exactly one rendering root, and that root is an `Element`. The
962
+ * cache array (`t_fragment_els`) is separate from `t_fragments` so each helper
963
+ * only ever sees its own cached type at a given index.
964
+ *
965
+ * @param document The owner document (used to build the cached `<template>`).
966
+ * @param array The per-component `t_fragment_els` cache.
967
+ * @param index The fragment's index in the cache.
968
+ * @param html The fragment's HTML source, with `#` placeholders for reactive
969
+ * text and `<!>` for anchor comments.
970
+ * @param ns When true, the template is created in the SVG namespace (its
971
+ * `firstElementChild` is then an SVG element).
972
+ */
973
+ function getElementFragment(document, array, index, html, ns) {
974
+ if (array[index] === void 0) if (ns === true) {
975
+ const template = document.createElementNS("http://www.w3.org/2000/svg", "template");
976
+ template.innerHTML = html;
977
+ array[index] = template.firstElementChild;
978
+ } else {
979
+ const template = document.createElement("template");
980
+ template.innerHTML = html;
981
+ array[index] = template.content.firstElementChild;
982
+ }
983
+ return array[index].cloneNode(true);
984
+ }
572
985
  //#endregion
573
986
  //#region src/render/hydrate.ts
574
987
  /**
@@ -578,16 +991,14 @@ function getFragment(document, array, index, html, ns) {
578
991
  * @param props An object containing component props
579
992
  */
580
993
  function hydrate(parent, component, props, slots) {
581
- context_default.hydrationNode = parent.firstChild;
582
- context_default.rootRegion = newRegion(require_devContext.devContext_default.enabled ? "Root" : void 0);
583
- context_default.previousRegion = context_default.rootRegion;
584
- pushRegion(context_default.rootRegion);
994
+ context.hydrationNode = parent.firstChild;
995
+ context.rootRegion = newRegion(require_devContext.devContext.enabled ? "Root" : void 0);
996
+ context.previousRegion = context.rootRegion;
997
+ pushRegion(context.rootRegion);
585
998
  component(parent, null, props, void 0, slots);
586
- context_default.hydrationNode = null;
587
- for (let effect of context_default.mountEffects) $run(effect);
588
- context_default.mountEffects.length = 0;
999
+ context.hydrationNode = null;
1000
+ flushMountEffects();
589
1001
  }
590
-
591
1002
  //#endregion
592
1003
  //#region src/render/mount.ts
593
1004
  /**
@@ -600,14 +1011,36 @@ function hydrate(parent, component, props, slots) {
600
1011
  function mount(parent, component, props, slots) {
601
1012
  if (parent.childElementCount > 0) throw new Error("The parent node must have no child elements");
602
1013
  while (parent.firstChild !== null) parent.firstChild.remove();
603
- if (context_default.rootRegion === null) {
604
- context_default.rootRegion = newRegion(require_devContext.devContext_default.enabled ? "Root" : void 0);
605
- context_default.previousRegion = context_default.rootRegion;
606
- pushRegion(context_default.rootRegion);
1014
+ if (context.rootRegion === null) {
1015
+ context.rootRegion = newRegion(require_devContext.devContext.enabled ? "Root" : void 0);
1016
+ context.previousRegion = context.rootRegion;
1017
+ pushRegion(context.rootRegion);
607
1018
  }
608
1019
  component(parent, null, props, void 0, slots);
609
1020
  }
610
-
1021
+ //#endregion
1022
+ //#region src/render/unmount.ts
1023
+ /**
1024
+ * Tears down the current UI: disposes the root region tree (running effect
1025
+ * cleanups and detaching subscriptions), resets the render context, and
1026
+ * removes any remaining child nodes from `parent`.
1027
+ *
1028
+ * Call this before `mount`ing a fresh component tree into the same container
1029
+ * (e.g. when client-side navigating to a route whose layout chain differs
1030
+ * from the previous one). `mount` refuses to mount into a non-empty parent
1031
+ * and reuses an existing root region, so both must be cleared first.
1032
+ *
1033
+ * @param parent The container that the previous UI was mounted into
1034
+ */
1035
+ function unmount(parent) {
1036
+ if (context.rootRegion !== null) {
1037
+ clearRegion(context.rootRegion);
1038
+ context.rootRegion = null;
1039
+ context.previousRegion = null;
1040
+ context.activeRegion = null;
1041
+ }
1042
+ while (parent.firstChild !== null) parent.firstChild.remove();
1043
+ }
611
1044
  //#endregion
612
1045
  //#region src/render/newListItem.ts
613
1046
  function newListItem(data, key, name) {
@@ -620,28 +1053,20 @@ function newListItem(data, key, name) {
620
1053
  animations: null,
621
1054
  name,
622
1055
  data,
623
- key
1056
+ key,
1057
+ effects: []
624
1058
  };
625
1059
  }
626
-
627
- //#endregion
628
- //#region src/render/hydrationMarkers.ts
629
- const HYDRATION_START = "[";
630
- const HYDRATION_END = "]";
631
- const HYDRATION_BREAK = "^";
632
-
633
1060
  //#endregion
634
1061
  //#region src/render/isCommentNode.ts
635
1062
  function isCommentNode(node) {
636
1063
  return node.nodeType === 8;
637
1064
  }
638
-
639
1065
  //#endregion
640
1066
  //#region src/render/isTextNode.ts
641
1067
  function isTextNode(node) {
642
1068
  return node.nodeType === 3;
643
1069
  }
644
-
645
1070
  //#endregion
646
1071
  //#region src/render/nodeCheckHydrationBreak.ts
647
1072
  /**
@@ -653,17 +1078,14 @@ function isTextNode(node) {
653
1078
  * @returns The next node.
654
1079
  */
655
1080
  function nodeCheckHydrationBreak(node) {
656
- if (context_default.hydrationNode !== null) {
657
- if (node !== null && isCommentNode(node) && node.data === HYDRATION_BREAK) {
658
- let comment = node;
659
- node = node.nextSibling;
660
- comment.remove();
661
- }
662
- context_default.hydrationNode = node;
1081
+ if (node !== null && isCommentNode(node) && node.data === "^") {
1082
+ let comment = node;
1083
+ node = node.nextSibling;
1084
+ comment.remove();
663
1085
  }
1086
+ context.hydrationNode = node;
664
1087
  return node;
665
1088
  }
666
-
667
1089
  //#endregion
668
1090
  //#region src/render/nodeNext.ts
669
1091
  /**
@@ -675,10 +1097,18 @@ function nodeCheckHydrationBreak(node) {
675
1097
  * @param text Whether we require a text node.
676
1098
  */
677
1099
  function nodeNext(node, text = false) {
678
- if (context_default.hydrationNode !== null && text && isTextNode(node)) return node;
679
- return nodeCheckHydrationBreak(node.nextSibling);
1100
+ if (context.hydrationNode !== null) {
1101
+ if (text && isTextNode(node)) return node;
1102
+ let next = nodeCheckHydrationBreak(node.nextSibling);
1103
+ while (!text && next !== null && isTextNode(next) && next.textContent?.trim() === "") next = nodeCheckHydrationBreak(next.nextSibling);
1104
+ if (!text && next !== null && next.nodeName === "TBODY" && next.firstChild && isTextNode(node)) {
1105
+ next = next.firstChild;
1106
+ context.hydrationNode = next;
1107
+ }
1108
+ return next;
1109
+ }
1110
+ return node.nextSibling;
680
1111
  }
681
-
682
1112
  //#endregion
683
1113
  //#region src/render/nodeAnchor.ts
684
1114
  /**
@@ -696,32 +1126,43 @@ function nodeNext(node, text = false) {
696
1126
  * @returns The anchor node.
697
1127
  */
698
1128
  function nodeAnchor(node) {
699
- if (context_default.hydrationNode !== null) {
700
- if (isCommentNode(node) && node.data === HYDRATION_START) {
1129
+ if (context.hydrationNode !== null) {
1130
+ if (isCommentNode(node) && node.data === "[") {
1131
+ const startParent = node.parentNode;
701
1132
  let currentNode = nodeNext(node);
1133
+ const firstInside = currentNode;
702
1134
  node.remove();
703
1135
  let level = 1;
704
1136
  while (currentNode !== null) {
705
1137
  if (isCommentNode(currentNode)) {
706
- if (currentNode.data === HYDRATION_START) level += 1;
707
- else if (currentNode.data === HYDRATION_END) {
1138
+ if (currentNode.data === "[") level += 1;
1139
+ else if (currentNode.data === "]") {
708
1140
  level -= 1;
709
1141
  if (level === 0) {
710
1142
  const endNode = currentNode.nextSibling;
711
1143
  currentNode.remove();
712
- if (context_default.hydrationNode === currentNode) context_default.hydrationNode = endNode;
1144
+ if (context.hydrationNode === currentNode) context.hydrationNode = endNode;
1145
+ const region = context.activeRegion;
1146
+ if (region.startNode === null && firstInside !== null) region.startNode = firstInside;
1147
+ setFirstInsideNode(endNode, firstInside);
713
1148
  return endNode;
714
1149
  }
715
1150
  }
716
1151
  }
717
- currentNode = currentNode.nextSibling;
1152
+ if (currentNode.firstChild) currentNode = currentNode.firstChild;
1153
+ else if (currentNode.nextSibling) currentNode = currentNode.nextSibling;
1154
+ else {
1155
+ let parent = currentNode.parentNode;
1156
+ while (parent !== null && parent.nextSibling === null && parent !== startParent) parent = parent.parentNode;
1157
+ if (parent === null || parent === startParent) currentNode = null;
1158
+ else currentNode = parent.nextSibling;
1159
+ }
718
1160
  }
719
1161
  if (currentNode === null) throw new Error("End hydration comment not found");
720
1162
  }
721
1163
  }
722
1164
  return node;
723
1165
  }
724
-
725
1166
  //#endregion
726
1167
  //#region src/render/nodeChild.ts
727
1168
  /**
@@ -733,40 +1174,104 @@ function nodeAnchor(node) {
733
1174
  */
734
1175
  function nodeChild(parent) {
735
1176
  let childNode = parent.firstChild;
736
- if (context_default.hydrationNode !== null) {
1177
+ if (context.hydrationNode !== null) {
737
1178
  if (childNode === null) childNode = parent.appendChild(parent.ownerDocument.createTextNode(""));
738
- context_default.hydrationNode = childNode;
1179
+ context.hydrationNode = childNode;
739
1180
  }
740
1181
  return childNode;
741
1182
  }
742
-
1183
+ //#endregion
1184
+ //#region src/render/walkHydrationRoot.ts
1185
+ /**
1186
+ * Walks the hydration cursor past skippable leading nodes (whitespace text,
1187
+ * branch-break markers, auto-inserted `<tbody>`) and lands on the first real
1188
+ * content node — the same walk `nodeRoot` performs for the non-text case.
1189
+ *
1190
+ * Sets `region.startNode` to the landed node (unless it's a control-start
1191
+ * marker, which `nodeAnchor` consumes next). Returns the landed node and
1192
+ * advances `context.hydrationNode` to it.
1193
+ *
1194
+ * Extracted so `nodeRoot` and `nodeRootElement` share one implementation of
1195
+ * the cursor walk.
1196
+ */
1197
+ function walkHydrationRoot() {
1198
+ let rootNode = context.hydrationNode;
1199
+ while (rootNode !== null && isSkippable(rootNode)) {
1200
+ const next = rootNode.nextSibling;
1201
+ if (isCommentNode(rootNode) && rootNode.data === "^") rootNode.remove();
1202
+ rootNode = next;
1203
+ context.hydrationNode = rootNode;
1204
+ }
1205
+ while (rootNode !== null && rootNode.nodeName === "TBODY" && rootNode.firstChild !== null) {
1206
+ rootNode = rootNode.firstChild;
1207
+ context.hydrationNode = rootNode;
1208
+ }
1209
+ const region = context.activeRegion;
1210
+ const isControlStart = rootNode !== null && isCommentNode(rootNode) && rootNode.data === "[";
1211
+ if (region.startNode === null && !isControlStart) region.startNode = rootNode;
1212
+ return rootNode;
1213
+ }
1214
+ function isSkippable(node) {
1215
+ if (isTextNode(node) && (node.textContent ?? "").trim() === "") return true;
1216
+ if (isCommentNode(node)) return node.data === "^" || node.data === "";
1217
+ return false;
1218
+ }
1219
+ //#endregion
1220
+ //#region src/render/nodeRootElement.ts
1221
+ /**
1222
+ * Gets the root element of a single-root fragment built via `getElementFragment`.
1223
+ *
1224
+ * Companion to `nodeRoot`, for the codegen path where the compiler has emitted
1225
+ * `t_fragment_el` (cloning the cached template's `firstElementChild` directly)
1226
+ * instead of `t_fragment` (cloning into a `DocumentFragment`). In the
1227
+ * non-hydrating case the cloned element is already the root, so this is a
1228
+ * no-op pass-through. In the hydrating case we perform the same cursor walk as
1229
+ * `nodeRoot`'s non-text branch so the region's `startNode` lands on the
1230
+ * existing DOM node and the hydration cursor advances past any leading
1231
+ * whitespace, branch-break markers, and auto-inserted `<tbody>` wrappers.
1232
+ *
1233
+ * @param node The cloned root element (ignored when hydrating).
1234
+ */
1235
+ function nodeRootElement(node) {
1236
+ if (context.hydrationNode !== null) return walkHydrationRoot();
1237
+ return node;
1238
+ }
743
1239
  //#endregion
744
1240
  //#region src/render/nodeRoot.ts
745
1241
  /**
746
1242
  * Gets the first child in a fragment.
747
1243
  *
748
- * When hydrating, also sets the active range's start node, while we have it.
1244
+ * When hydrating, also sets the active region's start node, while we have it.
1245
+ *
1246
+ * If the hydration cursor is on a control-start marker (`<![>`), the node is
1247
+ * left in place for `nodeAnchor` (called next as `t_anchor(t_root(...))`) to
1248
+ * walk — it consumes the matched `<![>...<!]>` pair, removes the markers and
1249
+ * sets the region's start node to the first node inside the block.
1250
+ *
1251
+ * For non-text fragments, leading branch-break markers (`<!^>`), empty anchor
1252
+ * comments left by preceding siblings, and residual whitespace-only text nodes
1253
+ * are skipped (break markers removed) so the region's start node lands on real
1254
+ * content. This replaces the per-sibling `t_next` calls that the codegen used
1255
+ * to emit when leading whitespace separated siblings; with whitespace trimmed
1256
+ * those calls are gone, so the advancement happens here.
749
1257
  *
750
1258
  * @param parent The parent of the fragment.
751
1259
  * @param text Whether we require a text node.
752
1260
  */
753
1261
  function nodeRoot(parent, text = false) {
754
- if (context_default.hydrationNode !== null) {
755
- let rootNode = context_default.hydrationNode;
1262
+ if (context.hydrationNode !== null) {
1263
+ let rootNode = context.hydrationNode;
756
1264
  if (text && !isTextNode(rootNode) && rootNode.previousSibling !== null && isTextNode(rootNode.previousSibling)) {
757
1265
  rootNode = rootNode.previousSibling;
758
- context_default.hydrationNode = rootNode;
1266
+ context.hydrationNode = rootNode;
759
1267
  }
760
- if (isCommentNode(rootNode) && rootNode.data === HYDRATION_START) {
761
- rootNode = rootNode.nextSibling;
762
- context_default.hydrationNode = rootNode;
763
- }
764
- const region = context_default.activeRegion;
765
- if (region.startNode === null) region.startNode = rootNode;
1268
+ if (!text) return walkHydrationRoot();
1269
+ const region = context.activeRegion;
1270
+ const isControlStart = rootNode !== null && isCommentNode(rootNode) && rootNode.data === "[";
1271
+ if (region.startNode === null && !isControlStart) region.startNode = rootNode;
766
1272
  return rootNode;
767
1273
  } else return parent.firstChild;
768
1274
  }
769
-
770
1275
  //#endregion
771
1276
  //#region src/render/nodeSkip.ts
772
1277
  /**
@@ -779,10 +1284,108 @@ function nodeRoot(parent, text = false) {
779
1284
  */
780
1285
  function nodeSkip(node, count) {
781
1286
  let nextNode = node;
782
- for (let i = 0; i < count; i++) nextNode = nodeCheckHydrationBreak(nextNode.nextSibling);
1287
+ if (context.hydrationNode !== null) for (let i = 0; i < count; i++) nextNode = nodeCheckHydrationBreak(nextNode.nextSibling);
1288
+ else for (let i = 0; i < count; i++) nextNode = nextNode.nextSibling;
783
1289
  return nextNode;
784
1290
  }
785
-
1291
+ //#endregion
1292
+ //#region src/render/rerunRegionEffects.ts
1293
+ /**
1294
+ * Force re-runs every effect owned by `region` and its descendant regions
1295
+ * that depends on at least one of the for-vars set in `changedMask`.
1296
+ *
1297
+ * Used by keyed-list `updateListItem` callbacks emitted by the compiler when
1298
+ * the `@for` body has been classified "no-proxy safe" — i.e. the per-item
1299
+ * data bag is *not* wrapped in a shallow `$watch` Proxy. Without that Proxy,
1300
+ * a write such as `t_old_item.data.row = newRow` doesn't propagate through a
1301
+ * signal, so any effects that read `data.row` must be re-run manually.
1302
+ *
1303
+ * `changedMask` is a bitmask of the for-var positions whose references
1304
+ * actually changed in this update. Each effect carries `forVarMask`
1305
+ * (computed at compile time) listing the for-vars its body reads; effects
1306
+ * whose `forVarMask & changedMask === 0` are skipped. Mount callbacks
1307
+ * (`isMountEffect` — `$onmount`/`onmount`) are always skipped: they run
1308
+ * once per DOM mount and their bodies are untracked.
1309
+ *
1310
+ * Equivalent to what `checkEffect` does when a signal has propagated, but
1311
+ * unconditional for the effects that do match: cleanup → deactivate sources
1312
+ * → run → clear unused sources, for every matching effect on the region and
1313
+ * on every descendant region (`depth > region.depth`, the same chain shape
1314
+ * `clearRegion` walks).
1315
+ */
1316
+ function rerunRegionEffects(region, changedMask) {
1317
+ rerunEffectsOnRegion(region, changedMask);
1318
+ let child = region.nextRegion;
1319
+ while (child !== null && child.depth > region.depth) {
1320
+ rerunEffectsOnRegion(child, changedMask);
1321
+ child = child.nextRegion;
1322
+ }
1323
+ }
1324
+ function rerunEffectsOnRegion(region, changedMask) {
1325
+ for (let effect of region.effects) {
1326
+ if (effect.isMountEffect) continue;
1327
+ if (effect.forVarMask !== void 0 && (effect.forVarMask & changedMask) === 0) continue;
1328
+ runCleanups(effect);
1329
+ deactivateSources(effect);
1330
+ runEffect(effect);
1331
+ clearSources(effect);
1332
+ }
1333
+ }
1334
+ //#endregion
1335
+ //#region src/render/restoreHydration.ts
1336
+ /**
1337
+ * Restores the hydration cursor to a previously-snapshotted node. Used by
1338
+ * `@try`/`@catch`: if the try branch throws partway through its hydration
1339
+ * walk, the catch branch must resume hydrating from where the try group
1340
+ * started, not from wherever the failed branch left the cursor.
1341
+ *
1342
+ * The cursor is set unconditionally: a failed try-branch build can walk the
1343
+ * cursor past the last node (setting it to `null` via `nodeNext`), and the
1344
+ * rewind must still restore it — otherwise the catch branch would think it
1345
+ * isn't hydrating and insert fresh nodes alongside the server's. When not
1346
+ * hydrating at all, the snapshot itself is `null`, so this is a no-op.
1347
+ *
1348
+ * @param node The snapshotted cursor node (from `saveHydration`).
1349
+ */
1350
+ function restoreHydration(node) {
1351
+ context.hydrationNode = node;
1352
+ }
1353
+ //#endregion
1354
+ //#region src/render/widenAncestorsAtAnchor.ts
1355
+ /**
1356
+ * Widens ancestor region node windows after a control re-run rendered
1357
+ * content at its anchor.
1358
+ *
1359
+ * A region that owns only a control's anchor comment captures
1360
+ * `startNode = endNode = anchor` when it mounts (e.g. a `@for` row whose
1361
+ * body is a single `@if`, or an outer `@if` whose body is a single control).
1362
+ * Content rendered by a LATER re-run of that control is inserted into the
1363
+ * live DOM just BEFORE the anchor — outside that window — so clearing the
1364
+ * owning region would remove only the anchor and orphan the branch content.
1365
+ * At mount time this can't happen (content is added to the region's detached
1366
+ * fragment first, so its `startNode` already covers it), which is why only
1367
+ * re-runs need this fix.
1368
+ *
1369
+ * The first node of the newly rendered content is the first DESCENDANT region
1370
+ * of the control that owns nodes (control regions themselves have null
1371
+ * `startNode`). Ancestors are the regions with strictly decreasing depth on
1372
+ * the `previousRegion` chain; only those whose window starts exactly at the
1373
+ * anchor are widened.
1374
+ */
1375
+ function widenAncestorsAtAnchor(region, anchor) {
1376
+ if (anchor === null) return;
1377
+ let child = region.nextRegion;
1378
+ while (child !== null && child.depth > region.depth && child.startNode === null) child = child.nextRegion;
1379
+ if (child === null || child.depth <= region.depth || child.startNode === anchor) return;
1380
+ const firstNode = child.startNode;
1381
+ let ancestor = region.previousRegion;
1382
+ let ancestorDepth = region.depth;
1383
+ while (ancestor !== null && ancestor.depth < ancestorDepth) {
1384
+ if (ancestor.startNode === anchor) ancestor.startNode = firstNode;
1385
+ ancestorDepth = ancestor.depth;
1386
+ ancestor = ancestor.previousRegion;
1387
+ }
1388
+ }
786
1389
  //#endregion
787
1390
  //#region src/render/runControl.ts
788
1391
  /**
@@ -791,27 +1394,106 @@ function nodeSkip(node, count) {
791
1394
  */
792
1395
  function runControl(region, anchor, create, name) {
793
1396
  let first = true;
794
- $run(function runControl$1() {
1397
+ const gen = region.generation = (region.generation ?? 0) + 1;
1398
+ $run(function runControl() {
1399
+ if (region.generation !== gen) return;
1400
+ if (region.depth === -2) region.recreate = true;
795
1401
  const oldRegion = pushRegion(region, first);
796
1402
  first = false;
797
1403
  create(anchor);
798
1404
  popRegion(oldRegion);
1405
+ widenAncestorsAtAnchor(region, anchor);
1406
+ if (context.hydrationNode !== null && anchor !== null) context.hydrationNode = anchor;
799
1407
  }, name);
800
- if (context_default.hydrationNode) anchor = context_default.hydrationNode.nextSibling;
801
1408
  }
802
-
803
1409
  //#endregion
804
1410
  //#region src/render/runControlBranch.ts
805
1411
  function runControlBranch(region, oldIndex, index) {
806
- if (oldIndex === index) return false;
807
- if (region.depth === -2) return false;
808
- if (region.nextRegion !== null && region.nextRegion.depth > region.depth) clearRegion(region.nextRegion);
1412
+ const recreate = region.recreate;
1413
+ if (recreate) region.recreate = false;
1414
+ const firstRender = region.hasRenderedBranch !== true;
1415
+ region.hasRenderedBranch = true;
1416
+ if (oldIndex === index) {
1417
+ if (recreate) {
1418
+ if (region.nextRegion !== null && region.nextRegion.depth > region.depth) clearRegion(region.nextRegion);
1419
+ return true;
1420
+ }
1421
+ return false;
1422
+ }
1423
+ if (!firstRender && region.nextRegion !== null && region.nextRegion.depth > region.depth) clearRegion(region.nextRegion);
809
1424
  return true;
810
1425
  }
811
-
1426
+ //#endregion
1427
+ //#region src/watch/deepWrap.ts
1428
+ /**
1429
+ * Wraps a value with `$watch` if it is a plain object (or Date/Map/Set) that
1430
+ * is not already watched and is not a promise. Returns the value unchanged
1431
+ * otherwise.
1432
+ *
1433
+ * Used by the `get` trap (wrap values on read) and the `set` trap (wrap
1434
+ * values on write), so a value stored in watched state is reactive whether
1435
+ * it's been read yet or not.
1436
+ */
1437
+ const proxyCache = /* @__PURE__ */ new WeakMap();
1438
+ function deepWrap(value) {
1439
+ if (value === void 0 || value === null || typeof value !== "object") return value;
1440
+ if (value[require_fromWebSocket.proxyDataSymbol] !== void 0) return proxyCache.get(value) ?? value;
1441
+ if (value.then !== void 0) return value;
1442
+ if (value.nodeType !== void 0) return value;
1443
+ const cached = proxyCache.get(value);
1444
+ if (cached !== void 0) return cached;
1445
+ const proxy = $watch(value);
1446
+ proxyCache.set(value, proxy);
1447
+ return proxy;
1448
+ }
812
1449
  //#endregion
813
1450
  //#region src/watch/propagateSignal.ts
814
1451
  /**
1452
+ * Walk the target graph from a signal source (ProxySignal or Computed),
1453
+ * marking each dependent as needing recalculation and queuing effects for
1454
+ * re-run. Shared between `propagateSignal` (for proxy writes) and `$async`'s
1455
+ * promise-resolve handler (for async value resolution).
1456
+ *
1457
+ * Must be called inside `batchStart`/`batchEnd` — callers own the batch.
1458
+ */
1459
+ function propagateFromSignal(signal) {
1460
+ const first = signal.firstTarget;
1461
+ if (first === null) return;
1462
+ let targetSub = first;
1463
+ let computed;
1464
+ outer: while (true) {
1465
+ targetSub.active = false;
1466
+ targetSub.recalc = true;
1467
+ const target = targetSub.target;
1468
+ if (target.type === 2) {
1469
+ if (!target.queued) {
1470
+ target.queued = true;
1471
+ context.effectsToRun.push(target);
1472
+ }
1473
+ } else if (!target.recalc) {
1474
+ target.recalc = true;
1475
+ if (target.firstTarget !== null) {
1476
+ computed = target;
1477
+ computed.rollback = targetSub;
1478
+ targetSub = target.firstTarget;
1479
+ continue;
1480
+ }
1481
+ }
1482
+ while (targetSub.nextTarget === null && computed !== void 0) {
1483
+ const rollback = computed.rollback;
1484
+ if (rollback === null) break;
1485
+ targetSub = rollback;
1486
+ if (targetSub.source.type !== 1) {
1487
+ computed = void 0;
1488
+ continue outer;
1489
+ }
1490
+ computed = targetSub.source;
1491
+ }
1492
+ if (targetSub.nextTarget === null) break;
1493
+ targetSub = targetSub.nextTarget;
1494
+ }
1495
+ }
1496
+ /**
815
1497
  * When a signal is changed, we need to
816
1498
  * - Set the signal's subscriptions to recalc
817
1499
  * - Set any dependent computed values to recalc
@@ -822,61 +1504,26 @@ function propagateSignal(proxy, key) {
822
1504
  if (signal !== void 0 && signal.firstTarget !== null) {
823
1505
  batchStart();
824
1506
  try {
825
- if (context_default.firstSignalToUpdate === null) context_default.firstSignalToUpdate = signal;
826
- else if (signal.nextSignalToUpdate === null) {
827
- let lastSignal = context_default.firstSignalToUpdate;
828
- while (lastSignal.nextSignalToUpdate !== null) lastSignal = lastSignal.nextSignalToUpdate;
829
- lastSignal.nextSignalToUpdate = signal;
830
- }
831
- let lastEffect = context_default.firstEffectToRun;
832
- if (lastEffect !== null) while (lastEffect.nextEffectToRun !== null) lastEffect = lastEffect.nextEffectToRun;
833
- let targetSub = signal.firstTarget;
834
- let computed;
835
- outer: while (true) {
836
- targetSub.active = false;
837
- targetSub.recalc = true;
838
- const target = targetSub.target;
839
- if (target.type === EFFECT_TYPE) {
840
- if (lastEffect === null) {
841
- context_default.firstEffectToRun = target;
842
- lastEffect = target;
843
- } else if (target.nextEffectToRun === null && lastEffect !== target) {
844
- lastEffect.nextEffectToRun = target;
845
- lastEffect = target;
846
- }
847
- } else if (!target.recalc) {
848
- target.recalc = true;
849
- if (target.firstTarget !== null) {
850
- computed = target;
851
- computed.rollback = targetSub;
852
- targetSub = target.firstTarget;
853
- continue;
854
- }
855
- }
856
- while (targetSub.nextTarget === null && computed !== void 0) {
857
- targetSub = computed.rollback;
858
- if (targetSub.source.type !== COMPUTED_TYPE) {
859
- computed = void 0;
860
- continue outer;
861
- }
862
- computed = targetSub.source;
863
- }
864
- if (targetSub.nextTarget === null) break;
865
- targetSub = targetSub.nextTarget;
1507
+ if (context.lastSignalToUpdate === null) {
1508
+ context.firstSignalToUpdate = signal;
1509
+ context.lastSignalToUpdate = signal;
1510
+ } else if (signal.nextSignalToUpdate === null) {
1511
+ context.lastSignalToUpdate.nextSignalToUpdate = signal;
1512
+ context.lastSignalToUpdate = signal;
866
1513
  }
1514
+ propagateFromSignal(signal);
867
1515
  } finally {
868
1516
  batchEnd();
869
1517
  }
870
1518
  }
871
1519
  }
872
-
873
1520
  //#endregion
874
1521
  //#region src/watch/trackProxySignal.ts
875
1522
  function trackProxySignal(data, key) {
876
1523
  let signal = data.signals.get(key);
877
1524
  if (signal === void 0) {
878
1525
  signal = {
879
- type: SIGNAL_TYPE,
1526
+ type: 0,
880
1527
  firstTarget: null,
881
1528
  nextSignalToUpdate: null
882
1529
  };
@@ -884,12 +1531,53 @@ function trackProxySignal(data, key) {
884
1531
  }
885
1532
  trackSignal(signal);
886
1533
  }
887
-
888
1534
  //#endregion
889
1535
  //#region src/watch/proxyGet.ts
1536
+ /**
1537
+ * Called when a read hits a `didSuspend` computed. Subscribes the reader (so
1538
+ * resolve re-runs it through the normal reactive graph), propagates the
1539
+ * suspend up the cache chain by tainting the active reader, and notifies the
1540
+ * nearest `@await` boundary.
1541
+ *
1542
+ * Return value (stale-while-revalidate, ASYNC.md §6.2): on a refresh suspend
1543
+ * (the computed has resolved before) returns the previously resolved value
1544
+ * held in `staleValue`, so readers keep displaying the old content instead of
1545
+ * a placeholder — an `@await` boundary thus keeps its content mounted
1546
+ * rather than flashing the `with` branch. On a first load (`staleValue` is
1547
+ * undefined) returns `undefined`, which the boundary replaces with its
1548
+ * `with` branch. In peek mode (used by `$pending`) always returns `undefined`
1549
+ * — the value isn't needed, only the subscription.
1550
+ */
1551
+ function suspendRead(signal) {
1552
+ trackSignal(signal);
1553
+ if (context.suspendPeek) {
1554
+ if (!signal.suspendQuiet) context.suspendPeekHit = true;
1555
+ return;
1556
+ }
1557
+ if (context.activeTarget !== null) {
1558
+ context.activeTarget.didSuspend = true;
1559
+ if (context.activeTarget.type === 2) {
1560
+ const effect = context.activeTarget;
1561
+ (effect.suspendSources ??= /* @__PURE__ */ new Set()).add(signal);
1562
+ }
1563
+ }
1564
+ if (context.awaitBoundary !== null) {
1565
+ context.awaitBoundary.suspended = true;
1566
+ context.awaitBoundary.pending.add(signal);
1567
+ const boundaryEffect = context.awaitBoundary.effect;
1568
+ if (boundaryEffect !== null && boundaryEffect !== context.activeTarget) {
1569
+ const oldActive = context.activeTarget;
1570
+ context.activeTarget = boundaryEffect;
1571
+ trackSignal(signal);
1572
+ context.activeTarget = oldActive;
1573
+ }
1574
+ }
1575
+ return signal.staleValue;
1576
+ }
890
1577
  function proxyGet(target, key, receiver) {
891
- let data = target[require_formatText.proxyDataSymbol];
892
- if (key === require_formatText.proxyDataSymbol) return data;
1578
+ let data = target[require_fromWebSocket.proxyDataSymbol];
1579
+ if (key === require_fromWebSocket.proxyDataSymbol) return data;
1580
+ if ((data.isDate || data.isMap || data.isSet) && !Object.prototype.hasOwnProperty.call(target, key)) return collectionGet(data, target, key, receiver);
893
1581
  let signal = data.signals.get(key);
894
1582
  if (signal === void 0) {
895
1583
  const propDescriptor = Object.getOwnPropertyDescriptor(target, key);
@@ -897,38 +1585,92 @@ function proxyGet(target, key, receiver) {
897
1585
  if (propDescriptor.writable) {
898
1586
  if (data.shallow !== true) {
899
1587
  const value = target[key];
900
- if (value !== void 0 && value !== null && typeof value === "object" && value[require_formatText.proxyDataSymbol] === void 0 && value.then === void 0) target[key] = $watch(value);
1588
+ const wrapped = deepWrap(value);
1589
+ if (wrapped !== value) target[key] = wrapped;
901
1590
  }
902
1591
  trackProxySignal(data, key);
903
1592
  } else if (propDescriptor.get) {
904
- const oldRegisterComputed = context_default.registerComputed;
1593
+ const oldRegisterComputed = context.registerComputed;
905
1594
  try {
906
- context_default.registerComputed = (computed) => {
1595
+ context.registerComputed = (computed) => {
907
1596
  data.signals.set(key, computed);
908
1597
  };
909
- return Reflect.get(target, key, receiver);
1598
+ const result = Reflect.get(target, key, receiver);
1599
+ const registered = data.signals.get(key);
1600
+ if (context.refreshSignals !== null && registered !== void 0 && registered.type === 1 && registered.isAsync) {
1601
+ context.refreshSignals.push(registered);
1602
+ context.refreshInitialized?.add(registered);
1603
+ }
1604
+ if (registered !== void 0 && registered.type === 1 && registered.didSuspend) return suspendRead(registered);
1605
+ return result;
910
1606
  } finally {
911
- context_default.registerComputed = oldRegisterComputed;
1607
+ context.registerComputed = oldRegisterComputed;
912
1608
  }
913
1609
  }
914
1610
  } else if (data.isArray) {
915
1611
  if (arrayWrapper[key] !== void 0) return arrayWrapper[key](data, target, key);
916
1612
  } else trackProxySignal(data, key);
917
- } else if (signal.type === SIGNAL_TYPE) trackProxySignal(data, key);
918
- else if (signal.type === COMPUTED_TYPE) {
1613
+ } else if (signal.type === 0) {
1614
+ if (data.shallow !== true) {
1615
+ const value = target[key];
1616
+ if (typeof value === "object" && value !== null) {
1617
+ const propDescriptor = Object.getOwnPropertyDescriptor(target, key);
1618
+ if (propDescriptor !== void 0 && propDescriptor.writable) {
1619
+ const wrapped = deepWrap(value);
1620
+ if (wrapped !== value) target[key] = wrapped;
1621
+ }
1622
+ }
1623
+ }
1624
+ trackProxySignal(data, key);
1625
+ } else if (signal.type === 1) {
1626
+ if (context.refreshSignals !== null && signal.isAsync) {
1627
+ context.refreshSignals.push(signal);
1628
+ return signal.value;
1629
+ }
919
1630
  if (signal.running) throw new Error("Cycle detected");
920
1631
  else if (signal.recalc) checkComputed(signal);
921
- else if (signal.didError) throw signal.value;
922
- else trackSignal(signal);
1632
+ if (signal.didError) {
1633
+ trackSignal(signal);
1634
+ throw signal.value;
1635
+ }
1636
+ if (signal.didSuspend) return suspendRead(signal);
1637
+ trackSignal(signal);
923
1638
  return signal.value;
924
1639
  }
925
- return Reflect.get(target, key, receiver);
1640
+ return target[key];
926
1641
  }
927
1642
  const arrayWrapper = {
928
- [Symbol.iterator]: function(data, target, key) {
1643
+ [Symbol.iterator]: function(data, target, _key) {
929
1644
  trackProxySignal(data, "length");
930
- context_default.activeTarget = null;
931
- return target[key];
1645
+ context.activeTarget = null;
1646
+ return function arrayIterator() {
1647
+ let index = 0;
1648
+ return {
1649
+ next() {
1650
+ if (index >= target.length) return {
1651
+ value: void 0,
1652
+ done: true
1653
+ };
1654
+ let value = target[index];
1655
+ if (data.shallow !== true) {
1656
+ const wrapped = deepWrap(value);
1657
+ if (wrapped !== value) {
1658
+ value = wrapped;
1659
+ target[index] = value;
1660
+ }
1661
+ }
1662
+ trackProxySignal(data, String(index));
1663
+ index++;
1664
+ return {
1665
+ value,
1666
+ done: false
1667
+ };
1668
+ },
1669
+ [Symbol.iterator]() {
1670
+ return this;
1671
+ }
1672
+ };
1673
+ };
932
1674
  },
933
1675
  pop: arrayHandle,
934
1676
  push: arrayHandle,
@@ -936,8 +1678,35 @@ const arrayWrapper = {
936
1678
  shift: arrayHandle,
937
1679
  sort: arrayHandle,
938
1680
  splice: arrayHandle,
939
- unshift: arrayHandle
1681
+ unshift: arrayHandle,
1682
+ slice: readHandle,
1683
+ concat: readHandle,
1684
+ filter: readHandle,
1685
+ map: readHandle,
1686
+ toReversed: readHandle,
1687
+ toSorted: readHandle,
1688
+ toSpliced: readHandle,
1689
+ indexOf: readHandle,
1690
+ lastIndexOf: readHandle,
1691
+ includes: readHandle,
1692
+ find: readHandle,
1693
+ findIndex: readHandle,
1694
+ some: readHandle,
1695
+ every: readHandle,
1696
+ join: readHandle,
1697
+ forEach: readHandle,
1698
+ reduce: readHandle,
1699
+ reduceRight: readHandle,
1700
+ flat: readHandle,
1701
+ flatMap: readHandle,
1702
+ at: readHandle
940
1703
  };
1704
+ function readHandle(data, target, key) {
1705
+ return function(...args) {
1706
+ trackProxySignal(data, "length");
1707
+ return target[key].apply(target, args);
1708
+ };
1709
+ }
941
1710
  function arrayHandle(data, target, key) {
942
1711
  return function(...args) {
943
1712
  const result = target[key].apply(target, args);
@@ -945,48 +1714,331 @@ function arrayHandle(data, target, key) {
945
1714
  return result;
946
1715
  };
947
1716
  }
948
-
1717
+ const COLLECTION_KEY = Symbol("torp.collection");
1718
+ const TIME_KEY = "#time";
1719
+ /**
1720
+ * Routes a `get` on a watched Date/Map/Set to the right wrapper handler.
1721
+ *
1722
+ * Note the two levels of indirection for methods: the handler runs at get-trap
1723
+ * time (returning the method to call), and the returned function runs when the
1724
+ * method is invoked. `size` is the exception -- it returns its value at
1725
+ * get-trap time, because it's a readonly property, not a method.
1726
+ */
1727
+ function collectionGet(data, target, key, receiver) {
1728
+ if (data.isDate) return dateGet(data, target, key);
1729
+ const handle = (data.isMap ? mapWrapper : setWrapper)[key];
1730
+ if (handle !== void 0) return handle(data, target, key, receiver);
1731
+ return target[key];
1732
+ }
1733
+ /**
1734
+ * Returns the signal key for a Map/Set operation: primitives get a per-key
1735
+ * signal, so reading one key doesn't re-run effects when an unrelated key
1736
+ * changes. Anything else shares the collection-wide signal.
1737
+ */
1738
+ function collectionKey(key) {
1739
+ const type = typeof key;
1740
+ return type === "string" || type === "number" || type === "symbol" ? key : COLLECTION_KEY;
1741
+ }
1742
+ /**
1743
+ * Propagates a Map/Set mutation: the per-key signal (when the key is a
1744
+ * primitive) plus the collection-wide signal. The collection signal is always
1745
+ * enough for object keys, and propagating the same signal twice would re-run
1746
+ * effects twice (they re-subscribe between flushes).
1747
+ */
1748
+ function propagateCollection(data, key) {
1749
+ if (key !== COLLECTION_KEY) propagateSignal(data, key);
1750
+ propagateSignal(data, COLLECTION_KEY);
1751
+ }
1752
+ function dateGet(data, target, key) {
1753
+ if (typeof key === "symbol") {
1754
+ if (key === Symbol.toPrimitive) return function(hint) {
1755
+ const result = target[Symbol.toPrimitive](hint);
1756
+ trackProxySignal(data, TIME_KEY);
1757
+ return result;
1758
+ };
1759
+ return target[key];
1760
+ }
1761
+ if (typeof key !== "string") return target[key];
1762
+ const value = target[key];
1763
+ if (typeof value !== "function") return value;
1764
+ if (key.startsWith("set")) return function(...args) {
1765
+ const before = target.getTime();
1766
+ const result = value.apply(target, args);
1767
+ if (target.getTime() !== before) propagateSignal(data, TIME_KEY);
1768
+ return result;
1769
+ };
1770
+ if (key.startsWith("get") || key.startsWith("to") || key === "valueOf") return function(...args) {
1771
+ const result = value.apply(target, args);
1772
+ trackProxySignal(data, TIME_KEY);
1773
+ return result;
1774
+ };
1775
+ return value;
1776
+ }
1777
+ const mapWrapper = {
1778
+ size: function(data, target) {
1779
+ trackProxySignal(data, COLLECTION_KEY);
1780
+ return target.size;
1781
+ },
1782
+ get: function(data, target) {
1783
+ return function(key) {
1784
+ key = require_fromWebSocket.$unwrap(key);
1785
+ trackProxySignal(data, collectionKey(key));
1786
+ const value = target.get(key);
1787
+ if (data.shallow !== true) {
1788
+ const wrapped = deepWrap(value);
1789
+ if (wrapped !== value) target.set(key, wrapped);
1790
+ return wrapped;
1791
+ }
1792
+ return value;
1793
+ };
1794
+ },
1795
+ has: function(data, target) {
1796
+ return function(key) {
1797
+ key = require_fromWebSocket.$unwrap(key);
1798
+ trackProxySignal(data, collectionKey(key));
1799
+ return target.has(key);
1800
+ };
1801
+ },
1802
+ set: function(data, target, _key, receiver) {
1803
+ return function(key, value) {
1804
+ key = require_fromWebSocket.$unwrap(key);
1805
+ if (target.has(key) && require_fromWebSocket.$unwrap(target.get(key)) === require_fromWebSocket.$unwrap(value)) return receiver ?? target;
1806
+ const result = target.set(key, value);
1807
+ propagateCollection(data, collectionKey(key));
1808
+ return receiver ?? result;
1809
+ };
1810
+ },
1811
+ delete: function(data, target) {
1812
+ return function(key) {
1813
+ key = require_fromWebSocket.$unwrap(key);
1814
+ const result = target.delete(key);
1815
+ propagateCollection(data, collectionKey(key));
1816
+ return result;
1817
+ };
1818
+ },
1819
+ clear: function(data, target) {
1820
+ return function() {
1821
+ const result = target.clear();
1822
+ batchStart();
1823
+ try {
1824
+ for (const key of data.signals.keys()) propagateSignal(data, key);
1825
+ } finally {
1826
+ batchEnd();
1827
+ }
1828
+ return result;
1829
+ };
1830
+ },
1831
+ keys: function(data, target) {
1832
+ return function() {
1833
+ trackProxySignal(data, COLLECTION_KEY);
1834
+ return [...target.keys()][Symbol.iterator]();
1835
+ };
1836
+ },
1837
+ values: function(data, target) {
1838
+ return function() {
1839
+ trackProxySignal(data, COLLECTION_KEY);
1840
+ let values = [...target.values()];
1841
+ if (data.shallow !== true) values = values.map(deepWrap);
1842
+ return values[Symbol.iterator]();
1843
+ };
1844
+ },
1845
+ entries: mapEntries,
1846
+ [Symbol.iterator]: mapEntries,
1847
+ forEach: function(data, target, _key, receiver) {
1848
+ return function(callback, thisArg) {
1849
+ trackProxySignal(data, COLLECTION_KEY);
1850
+ const wrap = data.shallow !== true;
1851
+ target.forEach((value, key) => {
1852
+ callback.call(thisArg, wrap ? deepWrap(value) : value, key, receiver ?? target);
1853
+ });
1854
+ };
1855
+ }
1856
+ };
1857
+ function mapEntries(data, target) {
1858
+ return function() {
1859
+ trackProxySignal(data, COLLECTION_KEY);
1860
+ const wrap = data.shallow !== true;
1861
+ return [...target.entries()].map((entry) => [entry[0], wrap ? deepWrap(entry[1]) : entry[1]])[Symbol.iterator]();
1862
+ };
1863
+ }
1864
+ const setWrapper = {
1865
+ size: function(data, target) {
1866
+ trackProxySignal(data, COLLECTION_KEY);
1867
+ return target.size;
1868
+ },
1869
+ has: function(data, target) {
1870
+ return function(value) {
1871
+ value = require_fromWebSocket.$unwrap(value);
1872
+ trackProxySignal(data, collectionKey(value));
1873
+ return target.has(value);
1874
+ };
1875
+ },
1876
+ add: function(data, target, _key, receiver) {
1877
+ return function(value) {
1878
+ value = require_fromWebSocket.$unwrap(value);
1879
+ if (target.has(value)) return receiver ?? target;
1880
+ const result = target.add(value);
1881
+ propagateCollection(data, collectionKey(value));
1882
+ return receiver ?? result;
1883
+ };
1884
+ },
1885
+ delete: function(data, target) {
1886
+ return function(value) {
1887
+ value = require_fromWebSocket.$unwrap(value);
1888
+ const result = target.delete(value);
1889
+ propagateCollection(data, collectionKey(value));
1890
+ return result;
1891
+ };
1892
+ },
1893
+ clear: function(data, target) {
1894
+ return function() {
1895
+ const result = target.clear();
1896
+ batchStart();
1897
+ try {
1898
+ for (const key of data.signals.keys()) propagateSignal(data, key);
1899
+ } finally {
1900
+ batchEnd();
1901
+ }
1902
+ return result;
1903
+ };
1904
+ },
1905
+ keys: setValues,
1906
+ values: setValues,
1907
+ [Symbol.iterator]: setValues,
1908
+ entries: setEntries,
1909
+ forEach: function(data, target, _key, receiver) {
1910
+ return function(callback, thisArg) {
1911
+ trackProxySignal(data, COLLECTION_KEY);
1912
+ const wrap = data.shallow !== true;
1913
+ target.forEach((value) => {
1914
+ const wrapped = wrap ? deepWrap(value) : value;
1915
+ callback.call(thisArg, wrapped, wrapped, receiver ?? target);
1916
+ });
1917
+ };
1918
+ }
1919
+ };
1920
+ function setValues(data, target) {
1921
+ return function() {
1922
+ trackProxySignal(data, COLLECTION_KEY);
1923
+ let values = [...target.values()];
1924
+ if (data.shallow !== true) values = values.map(deepWrap);
1925
+ return values[Symbol.iterator]();
1926
+ };
1927
+ }
1928
+ function setEntries(data, target) {
1929
+ return function() {
1930
+ trackProxySignal(data, COLLECTION_KEY);
1931
+ const wrap = data.shallow !== true;
1932
+ return [...target.values()].map((value) => {
1933
+ const wrapped = wrap ? deepWrap(value) : value;
1934
+ return [wrapped, wrapped];
1935
+ })[Symbol.iterator]();
1936
+ };
1937
+ }
949
1938
  //#endregion
950
1939
  //#region src/watch/proxySet.ts
951
1940
  function proxySet(target, key, value, receiver) {
952
1941
  const oldValue = target[key];
953
1942
  if (value !== oldValue) {
954
- if (context_default.batchOperation > 100) throw new Error("Cycle detected");
955
- let data = target[require_formatText.proxyDataSymbol];
956
- require_devContext.devContext_default.signalSet(data, key);
957
- if (oldValue && oldValue[require_formatText.proxyDataSymbol] !== void 0) value = $watch(value, { shallow: oldValue[require_formatText.proxyDataSymbol].shallow });
1943
+ if (context.batchOperation > 100) throw new Error("Cycle detected");
1944
+ let data = target[require_fromWebSocket.proxyDataSymbol];
1945
+ require_devContext.devContext.signalSet(data, key);
1946
+ if (data.shallow !== true) value = deepWrap(value);
958
1947
  Reflect.set(target, key, value, receiver);
959
1948
  propagateSignal(data, key);
960
- if (data.isArray && !isNaN(+String(key))) propagateSignal(data, "length");
1949
+ if (data.isArray && typeof key !== "symbol" && !isNaN(+key)) propagateSignal(data, "length");
961
1950
  }
962
1951
  return true;
963
1952
  }
964
-
965
1953
  //#endregion
966
1954
  //#region src/watch/$watch.ts
1955
+ const sharedHandler = {
1956
+ get: proxyGet,
1957
+ set: proxySet
1958
+ };
967
1959
  /**
968
- * Watches an object and runs effects when its properties are changed
1960
+ * Watches an object and runs effects when its properties are changed.
1961
+ *
1962
+ * Dates, Maps and Sets are supported too: their methods are reactive (reads
1963
+ * track, writes notify), so `new Date()`, `new Map()` and `new Set()` can be
1964
+ * used in watched state directly.
969
1965
  *
970
1966
  * @param object The object to watch
971
1967
  */
972
1968
  function $watch(object, options) {
973
- if (object === void 0 || object === null || object[require_formatText.proxyDataSymbol] !== void 0) return object;
1969
+ if (object === void 0 || object === null || object[require_fromWebSocket.proxyDataSymbol] !== void 0) return object;
974
1970
  const data = {
975
1971
  target: object,
976
1972
  isArray: Array.isArray(object),
1973
+ isDate: object instanceof Date,
1974
+ isMap: object instanceof Map,
1975
+ isSet: object instanceof Set,
977
1976
  shallow: options?.shallow === true,
978
1977
  signals: /* @__PURE__ */ new Map()
979
1978
  };
980
- object[require_formatText.proxyDataSymbol] = data;
981
- const handler = {
982
- get: proxyGet,
983
- set: proxySet
984
- };
985
- const proxy = new Proxy(object, handler);
986
- require_devContext.devContext_default.onWatch(data);
1979
+ Object.defineProperty(object, require_fromWebSocket.proxyDataSymbol, {
1980
+ value: data,
1981
+ writable: true,
1982
+ enumerable: false,
1983
+ configurable: true
1984
+ });
1985
+ const proxy = new Proxy(object, sharedHandler);
1986
+ require_devContext.devContext.onWatch(data);
987
1987
  return proxy;
988
1988
  }
989
-
1989
+ //#endregion
1990
+ //#region src/render/getSequence.ts
1991
+ /**
1992
+ * Computes the indices (into `arr`) of a longest strictly-increasing
1993
+ * subsequence, skipping zero entries. Adapted from Vue 3's `getSequence`.
1994
+ *
1995
+ * Used by the keyed-list reconciler (`runListItems`): `arr` is the
1996
+ * `newIndexToOldIndex` map where `arr[i] = oldIndex + 1` (so `0` marks a
1997
+ * new/unmounted slot, which is skipped). The returned indices identify the
1998
+ * items that are already in correct relative order and therefore don't need
1999
+ * to be moved — everything else is moved or mounted.
2000
+ *
2001
+ * Runs in O(n log n).
2002
+ */
2003
+ function getSequence(arr) {
2004
+ const p = arr.slice();
2005
+ const result = [0];
2006
+ let i;
2007
+ let j;
2008
+ let u;
2009
+ let v;
2010
+ let c;
2011
+ const len = arr.length;
2012
+ for (i = 0; i < len; i++) {
2013
+ const arrI = arr[i];
2014
+ if (arrI !== 0) {
2015
+ j = result[result.length - 1];
2016
+ if (arr[j] < arrI) {
2017
+ p[i] = j;
2018
+ result.push(i);
2019
+ continue;
2020
+ }
2021
+ u = 0;
2022
+ v = result.length - 1;
2023
+ while (u < v) {
2024
+ c = u + v >> 1;
2025
+ if (arr[result[c]] < arrI) u = c + 1;
2026
+ else v = c;
2027
+ }
2028
+ if (arrI < arr[result[u]]) {
2029
+ if (u > 0) p[i] = result[u - 1];
2030
+ result[u] = i;
2031
+ }
2032
+ }
2033
+ }
2034
+ u = result.length;
2035
+ v = result[u - 1];
2036
+ while (u-- > 0) {
2037
+ result[u] = v;
2038
+ v = p[v];
2039
+ }
2040
+ return result;
2041
+ }
990
2042
  //#endregion
991
2043
  //#region src/render/moveRegion.ts
992
2044
  function moveRegion(parent, region, before) {
@@ -1000,145 +2052,416 @@ function moveRegion(parent, region, before) {
1000
2052
  currentNode = nextNode;
1001
2053
  }
1002
2054
  }
1003
-
1004
2055
  //#endregion
1005
2056
  //#region src/render/runListItems.ts
2057
+ const SHALLOW_WATCH_OPTIONS = { shallow: true };
1006
2058
  /**
2059
+ * Mounts a new list item from a spec: allocates the ListItem, establishes it
2060
+ * as the active region (so the compiler-emitted `create` callback attaches
2061
+ * effects/events to the right region), sets its depth, optionally wraps its
2062
+ * data in a shallow watch, then runs `create`. Returns the mounted item so the
2063
+ * caller can slot it into the live list. The sibling chain is left for the
2064
+ * end-of-pass relink.
2065
+ */
2066
+ function mountSpec(spec, region, before, create, noWatch) {
2067
+ const item = newListItem(spec.data, spec.key);
2068
+ const savedActiveRegion = context.activeRegion;
2069
+ item.depth = region.depth + 1;
2070
+ context.activeRegion = item;
2071
+ if (noWatch !== true) item.data = $watch(item.data, SHALLOW_WATCH_OPTIONS);
2072
+ create(item, before);
2073
+ context.activeRegion = savedActiveRegion;
2074
+ return item;
2075
+ }
2076
+ /**
2077
+ * Reconciles an old keyed list against a new keyed list, reusing old
2078
+ * ListItems for survivors and producing the minimal set of DOM moves /
2079
+ * mounts / clears.
2080
+ *
2081
+ * @returns The new live list of ListItems (reused old items + freshly
2082
+ * mounted ones), which the caller keeps for the next reconciliation.
2083
+ *
1007
2084
  * @param region The list's region
1008
2085
  * @param parent The parent DOM element
1009
- * @param anchor The DOM element to create new items before
1010
- * @param oldItems The list of current items
1011
- * @param newItems The list of future items
2086
+ * @param anchor The DOM node to create new items before (the list's trailing anchor)
2087
+ * @param oldItems The list of current (live) items from the previous run
2088
+ * @param newSpecs The lightweight {key, data} specs for the new data
1012
2089
  * @param create A function that creates the DOM elements for a new item
2090
+ * @param update A function that syncs a matched item's data from its spec
2091
+ * (re-runs effects if a loop variable's reference actually changed)
2092
+ * @param noWatch When true, skip the per-item shallow `$watch` wrap. The
2093
+ * compiler guarantees the `@for` body never writes to its loop variables,
2094
+ * and emits an `update` callback that re-runs item effects manually when a
2095
+ * loop variable's reference actually changes (via `t_rerun_region_effects`).
1013
2096
  */
1014
- function runListItems(region, parent, anchor, oldItems, newItems, create, update) {
1015
- let oldStartIndex = 0;
1016
- let oldEndIndex = oldItems.length - 1;
1017
- let oldStartItem = oldItems[0];
1018
- let oldEndItem = oldItems[oldEndIndex];
1019
- let newStartIndex = 0;
1020
- let newEndIndex = newItems.length - 1;
1021
- let newStartItem = newItems[0];
1022
- let newEndItem = newItems[newEndIndex];
1023
- let oldKeyToIndex;
1024
- let newKeyToIndex;
1025
- while (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) if (oldStartItem === null) oldStartItem = oldItems[++oldStartIndex];
1026
- else if (oldEndItem === null) oldEndItem = oldItems[--oldEndIndex];
1027
- else if (newStartItem === null) newStartItem = newItems[++newStartIndex];
1028
- else if (newEndItem === null) newEndItem = newItems[--newEndIndex];
1029
- else if (oldStartItem.key === newStartItem.key) {
1030
- transferListItemData(oldStartItem, newStartItem, update);
1031
- oldStartItem = oldItems[++oldStartIndex];
1032
- newStartItem = newItems[++newStartIndex];
1033
- } else if (oldEndItem.key === newEndItem.key) {
1034
- transferListItemData(oldEndItem, newEndItem, update);
1035
- oldEndItem = oldItems[--oldEndIndex];
1036
- newEndItem = newItems[--newEndIndex];
1037
- } else if (oldStartItem.key === newEndItem.key) {
1038
- moveRegion(parent, oldStartItem, oldEndItem.endNode.nextSibling);
1039
- transferListItemData(oldStartItem, newEndItem, update);
1040
- oldStartItem = oldItems[++oldStartIndex];
1041
- newEndItem = newItems[--newEndIndex];
1042
- } else if (oldEndItem.key === newStartItem.key) {
1043
- moveRegion(parent, oldEndItem, oldStartItem.startNode);
1044
- transferListItemData(oldEndItem, newStartItem, update);
1045
- oldEndItem = oldItems[--oldEndIndex];
1046
- newStartItem = newItems[++newStartIndex];
1047
- } else {
1048
- if (oldKeyToIndex === void 0 || newKeyToIndex === void 0) {
1049
- oldKeyToIndex = /* @__PURE__ */ new Map();
1050
- for (let i = oldStartIndex; i < oldEndIndex; i++) oldKeyToIndex.set(oldItems[i].key, i);
1051
- newKeyToIndex = /* @__PURE__ */ new Map();
1052
- for (let i = newStartIndex; i < newEndIndex; i++) newKeyToIndex.set(newItems[i].key, i);
2097
+ function runListItems(region, parent, anchor, oldItems, newSpecs, create, update, noWatch) {
2098
+ const newItems = Array.from({ length: newSpecs.length });
2099
+ let nextSibling;
2100
+ if (oldItems.length > 0) {
2101
+ const lastOld = oldItems[oldItems.length - 1];
2102
+ nextSibling = lastOld.nextRegion;
2103
+ while (nextSibling !== null && nextSibling.depth > lastOld.depth) nextSibling = nextSibling.nextRegion;
2104
+ } else nextSibling = region.nextRegion;
2105
+ let oldStart = 0;
2106
+ let oldEnd = oldItems.length - 1;
2107
+ let newStart = 0;
2108
+ let newEnd = newSpecs.length - 1;
2109
+ let chainNeedsRelink = false;
2110
+ while (oldStart <= oldEnd && newStart <= newEnd) if (oldItems[oldStart].key === newSpecs[newStart].key) {
2111
+ const item = oldItems[oldStart];
2112
+ update(item, newSpecs[newStart]);
2113
+ newItems[newStart] = item;
2114
+ oldStart++;
2115
+ newStart++;
2116
+ } else if (oldItems[oldEnd].key === newSpecs[newEnd].key) {
2117
+ const item = oldItems[oldEnd];
2118
+ update(item, newSpecs[newEnd]);
2119
+ newItems[newEnd] = item;
2120
+ oldEnd--;
2121
+ newEnd--;
2122
+ } else if (oldItems[oldStart].key === newSpecs[newEnd].key) {
2123
+ const item = oldItems[oldStart];
2124
+ moveRegion(parent, item, oldItems[oldEnd].endNode?.nextSibling ?? anchor);
2125
+ chainNeedsRelink = true;
2126
+ update(item, newSpecs[newEnd]);
2127
+ newItems[newEnd] = item;
2128
+ oldStart++;
2129
+ newEnd--;
2130
+ } else if (oldItems[oldEnd].key === newSpecs[newStart].key) {
2131
+ const item = oldItems[oldEnd];
2132
+ moveRegion(parent, item, oldItems[oldStart].startNode);
2133
+ chainNeedsRelink = true;
2134
+ update(item, newSpecs[newStart]);
2135
+ newItems[newStart] = item;
2136
+ oldEnd--;
2137
+ newStart++;
2138
+ } else break;
2139
+ if (oldStart > oldEnd && newStart <= newEnd) {
2140
+ const before = newEnd + 1 < newSpecs.length ? newItems[newEnd + 1].startNode : anchor;
2141
+ for (let i = newStart; i <= newEnd; i++) newItems[i] = mountSpec(newSpecs[i], region, before, create, noWatch);
2142
+ chainNeedsRelink = true;
2143
+ } else if (newStart > newEnd) for (let i = oldStart; i <= oldEnd; i++) clearRegion(oldItems[i]);
2144
+ else {
2145
+ const newKeyToIndex = /* @__PURE__ */ new Map();
2146
+ for (let i = newStart; i <= newEnd; i++) newKeyToIndex.set(newSpecs[i].key, i);
2147
+ let anyOverlap = false;
2148
+ for (let i = oldStart; i <= oldEnd; i++) if (newKeyToIndex.has(oldItems[i].key)) {
2149
+ anyOverlap = true;
2150
+ break;
1053
2151
  }
1054
- let oldIndex = oldKeyToIndex.get(newStartItem.key);
1055
- let newIndex = newKeyToIndex.get(oldStartItem.key);
1056
- if (oldIndex === void 0 && newIndex === void 0) {
1057
- const oldRegion = pushRegion(newStartItem, true);
1058
- newStartItem.data = $watch(newStartItem.data, { shallow: true });
1059
- create(newStartItem, oldStartItem.startNode);
1060
- popRegion(oldRegion);
1061
- newStartItem.previousRegion = oldStartItem.previousRegion;
1062
- newStartItem.nextRegion = oldStartItem;
1063
- oldStartItem.previousRegion = newStartItem;
1064
- clearRegion(oldStartItem);
1065
- oldStartItem = oldItems[++oldStartIndex];
1066
- newStartItem = newItems[++newStartIndex];
1067
- } else if (oldIndex === void 0) {
1068
- const oldRegion = pushRegion(newStartItem, true);
1069
- newStartItem.data = $watch(newStartItem.data, { shallow: true });
1070
- create(newStartItem, oldStartItem.startNode);
1071
- popRegion(oldRegion);
1072
- newStartItem = newItems[++newStartIndex];
1073
- } else if (newIndex === void 0) {
1074
- clearRegion(oldStartItem);
1075
- oldStartItem = oldItems[++oldStartIndex];
2152
+ if (!anyOverlap) {
2153
+ let before = oldItems[oldEnd]?.endNode?.nextSibling ?? anchor;
2154
+ for (let i = oldEnd; i >= oldStart; i--) clearRegion(oldItems[i]);
2155
+ for (let i = newStart; i <= newEnd; i++) {
2156
+ newItems[i] = mountSpec(newSpecs[i], region, before, create, noWatch);
2157
+ before = newItems[i].endNode.nextSibling;
2158
+ }
2159
+ chainNeedsRelink = true;
1076
2160
  } else {
1077
- const oldData = oldItems[oldIndex];
1078
- moveRegion(parent, oldData, oldStartItem.startNode);
1079
- transferListItemData(oldData, newStartItem, update);
1080
- oldItems[oldIndex] = null;
1081
- newStartItem = newItems[++newStartIndex];
2161
+ const newMidLen = newEnd - newStart + 1;
2162
+ const newIndexToOld = Array.from({ length: newMidLen }).fill(0);
2163
+ for (let i = oldStart; i <= oldEnd; i++) {
2164
+ const oldItem = oldItems[i];
2165
+ const newIdx = newKeyToIndex.get(oldItem.key);
2166
+ if (newIdx !== void 0) {
2167
+ newIndexToOld[newIdx - newStart] = i + 1;
2168
+ update(oldItem, newSpecs[newIdx]);
2169
+ newItems[newIdx] = oldItem;
2170
+ } else clearRegion(oldItem);
2171
+ }
2172
+ const seq = getSequence(newIndexToOld);
2173
+ let j = seq.length - 1;
2174
+ for (let i = newMidLen - 1; i >= 0; i--) {
2175
+ const newIdx = newStart + i;
2176
+ const before = newIdx + 1 < newSpecs.length ? newItems[newIdx + 1].startNode : anchor;
2177
+ if (newIndexToOld[i] === 0) {
2178
+ newItems[newIdx] = mountSpec(newSpecs[newIdx], region, before, create, noWatch);
2179
+ chainNeedsRelink = true;
2180
+ } else if (j < 0 || i !== seq[j]) {
2181
+ moveRegion(parent, newItems[newIdx], before);
2182
+ chainNeedsRelink = true;
2183
+ } else j--;
2184
+ }
1082
2185
  }
1083
2186
  }
1084
- if (oldStartIndex <= oldEndIndex || newStartIndex <= newEndIndex) if (oldStartIndex > oldEndIndex) {
1085
- let before = oldStartItem?.startNode ?? oldItems[oldItems.length - 1]?.endNode?.nextSibling ?? anchor;
1086
- for (; newStartIndex <= newEndIndex; newStartItem = newItems[++newStartIndex]) {
1087
- const oldRegion = pushRegion(newStartItem, true);
1088
- newStartItem.data = $watch(newStartItem.data, { shallow: true });
1089
- create(newStartItem, before);
1090
- popRegion(oldRegion);
1091
- before = newStartItem.endNode.nextSibling;
2187
+ if (!chainNeedsRelink && newItems.length > 0) {
2188
+ let lastRegion = newItems[newItems.length - 1];
2189
+ let next = lastRegion.nextRegion;
2190
+ while (next !== null && next.depth > lastRegion.depth) {
2191
+ lastRegion = next;
2192
+ next = next.nextRegion;
1092
2193
  }
1093
- } else for (; oldEndIndex >= oldStartIndex; oldStartItem = oldItems[oldEndIndex--]) clearRegion(oldStartItem);
1094
- if (newItems.length > 0) region.nextRegion = newItems[0];
1095
- else if (oldItems.length > 0) region.nextRegion = oldItems[oldItems.length - 1].nextRegion;
1096
- }
1097
- function transferListItemData(oldItem, newItem, update) {
1098
- newItem.startNode = oldItem.startNode;
1099
- newItem.endNode = oldItem.endNode;
1100
- update(oldItem, newItem);
1101
- newItem.data = oldItem.data;
1102
- newItem.name = oldItem.name;
2194
+ context.previousRegion = lastRegion;
2195
+ return newItems;
2196
+ }
2197
+ if (newItems.length > 0) {
2198
+ let prevTail = region;
2199
+ for (let i = 0; i < newItems.length; i++) {
2200
+ const item = newItems[i];
2201
+ item.previousRegion = prevTail;
2202
+ prevTail.nextRegion = item;
2203
+ let last = item;
2204
+ let next = item.nextRegion;
2205
+ while (next !== null && next.depth > item.depth) {
2206
+ last = next;
2207
+ next = next.nextRegion;
2208
+ }
2209
+ prevTail = last;
2210
+ }
2211
+ prevTail.nextRegion = nextSibling;
2212
+ if (nextSibling !== null) nextSibling.previousRegion = prevTail;
2213
+ region.nextRegion = newItems[0];
2214
+ context.previousRegion = prevTail;
2215
+ } else {
2216
+ region.nextRegion = nextSibling;
2217
+ if (nextSibling !== null) nextSibling.previousRegion = region;
2218
+ context.previousRegion = region;
2219
+ }
2220
+ return newItems;
1103
2221
  }
1104
-
1105
2222
  //#endregion
1106
2223
  //#region src/render/runList.ts
1107
2224
  /**
1108
2225
  * Runs a `for` control statement
2226
+ * @param buildItems A function that returns the current list of lightweight
2227
+ * `{key, data}` specs (one per row of the source data)
1109
2228
  * @param create A function that creates the control statement's branches
2229
+ * @param noWatch When true, the compiler has determined the `@for` body never
2230
+ * writes to its loop variables, so each item's `data` bag can be left
2231
+ * unwrapped (skipping the per-item shallow `$watch` Proxy + ProxyData +
2232
+ * signals Map allocations). The compiler-emitted `update` callback is then
2233
+ * responsible for re-running item effects when a loop variable's reference
2234
+ * actually changes (via `t_rerun_region_effects`).
1110
2235
  */
1111
- function runList(region, parent, anchor, buildItems, create, update) {
2236
+ function runList(region, parent, anchor, buildItems, create, update, noWatch) {
1112
2237
  let first = true;
1113
2238
  let listItems = [];
1114
- $run(function runList$1() {
2239
+ $run(function runList() {
2240
+ if (region.depth === -2) return;
1115
2241
  const oldRegion = pushRegion(region, first);
1116
2242
  first = false;
1117
- const newItems = buildItems();
1118
- context_default.activeTarget = null;
1119
- runListItems(region, parent, anchor, listItems, newItems, create, update);
1120
- listItems = newItems;
2243
+ const newSpecs = buildItems();
2244
+ context.activeTarget = null;
2245
+ listItems = runListItems(region, parent, anchor, listItems, newSpecs, create, update, noWatch);
1121
2246
  popRegion(oldRegion);
1122
2247
  });
1123
- if (context_default.hydrationNode !== null) anchor = context_default.hydrationNode.nextSibling;
1124
2248
  }
1125
-
2249
+ //#endregion
2250
+ //#region src/render/runAwait.ts
2251
+ /**
2252
+ * Renders an `@await` boundary. On the first run, content is rendered
2253
+ * speculatively; if any read inside suspends (`didSuspend`), the boundary
2254
+ * discards the partial render and shows the `with` branch instead.
2255
+ *
2256
+ * Fine-grained updates: on subsequent runs the boundary only decides whether
2257
+ * to SWITCH branches. It does so from its `pending` set — the suspended
2258
+ * computeds recorded by `suspendRead` — dropping entries that resolved and
2259
+ * re-subscribing the still-suspended ones (a re-run deactivates all of the
2260
+ * effect's source subscriptions, so they must be re-tracked to survive
2261
+ * `clearSources`). That check is O(pending reads), not O(all sources), and
2262
+ * non-suspend dependency changes inside content are left to the child
2263
+ * effects that read them — the boundary isn't re-run by them at all.
2264
+ *
2265
+ * Stale-while-revalidate (ASYNC.md §6.2): once content has been produced
2266
+ * (`hasContent`), a subsequent suspend during a refresh does NOT switch to
2267
+ * the `with` branch — the boundary keeps the stale content mounted. `$async`
2268
+ * retains the previous resolved value (`Computed.staleValue`) and
2269
+ * `suspendRead` returns it, so child effects keep displaying the old value
2270
+ * until the new promise resolves and updates them in place. The `with` branch
2271
+ * is shown only on the first load, before content has ever rendered
2272
+ * successfully.
2273
+ *
2274
+ * @param renderContent Builds the content children (may read $async getters).
2275
+ * @param renderWith Builds the `with`-branch children, or null for empty.
2276
+ */
2277
+ function runAwait(region, anchor, renderContent, renderWith, name) {
2278
+ const boundary = {
2279
+ suspended: false,
2280
+ pending: /* @__PURE__ */ new Set(),
2281
+ effect: null
2282
+ };
2283
+ let index = -1;
2284
+ let first = true;
2285
+ let hasContent = false;
2286
+ let theEffect = null;
2287
+ const gen = region.generation = (region.generation ?? 0) + 1;
2288
+ $run(function runAwait() {
2289
+ if (region.generation !== gen) return;
2290
+ theEffect = context.activeTarget;
2291
+ boundary.effect = theEffect;
2292
+ const oldRegion = pushRegion(region, first);
2293
+ first = false;
2294
+ const renderBranch = (targetIndex, fn) => {
2295
+ runControlBranch(region, index, targetIndex);
2296
+ context.previousRegion = region;
2297
+ const oldR = pushRegion(newRegion(targetIndex === 0 ? "await_content" : "await_with"), true);
2298
+ fn(anchor);
2299
+ popRegion(oldR);
2300
+ index = targetIndex;
2301
+ };
2302
+ const attemptContent = () => {
2303
+ const oldBoundary = context.awaitBoundary;
2304
+ context.awaitBoundary = boundary;
2305
+ boundary.suspended = false;
2306
+ const savedHydration = context.hydrationNode;
2307
+ if (savedHydration !== null) context.hydrationNode = null;
2308
+ renderBranch(0, renderContent);
2309
+ if (savedHydration !== null) context.hydrationNode = savedHydration;
2310
+ context.awaitBoundary = oldBoundary;
2311
+ if (boundary.suspended && renderWith !== null) renderBranch(1, renderWith);
2312
+ else if (!boundary.suspended) hasContent = true;
2313
+ };
2314
+ if (theEffect === null) attemptContent();
2315
+ else {
2316
+ let suspended = false;
2317
+ for (const signal of boundary.pending) if (signal.didSuspend) {
2318
+ suspended = true;
2319
+ trackSignal(signal);
2320
+ } else boundary.pending.delete(signal);
2321
+ const targetIndex = suspended ? 1 : 0;
2322
+ if (targetIndex !== index) {
2323
+ if (targetIndex === 0) attemptContent();
2324
+ else if (!hasContent) if (renderWith !== null) renderBranch(1, renderWith);
2325
+ else {
2326
+ runControlBranch(region, index, 1);
2327
+ index = 1;
2328
+ }
2329
+ }
2330
+ }
2331
+ popRegion(oldRegion);
2332
+ widenAncestorsAtAnchor(region, anchor);
2333
+ }, name);
2334
+ }
2335
+ //#endregion
2336
+ //#region src/render/saveHydration.ts
2337
+ /**
2338
+ * Snapshots the hydration cursor so a `@try` branch's partial hydration walk
2339
+ * can be rewound if the branch throws and the `@catch` branch renders instead.
2340
+ *
2341
+ * @returns The current hydration cursor node, or `null` when not hydrating.
2342
+ */
2343
+ function saveHydration() {
2344
+ return context.hydrationNode;
2345
+ }
2346
+ //#endregion
2347
+ //#region src/render/runTry.ts
2348
+ /**
2349
+ * Renders a `@try`/`@catch` group, or a top-level `@error` block (which the
2350
+ * compiler wraps around the whole render).
2351
+ *
2352
+ * Like `runAwait`, the boundary is a control effect that renders one branch
2353
+ * at a time into a fresh child region (`runControlBranch` clears the old
2354
+ * branch on switch). Unlike the old compiled form, the try/catch lives in
2355
+ * this runtime, which gives it three capabilities the compiled form lacked:
2356
+ *
2357
+ * - **Effect-rerun error routing.** The boundary registers itself on its
2358
+ * region (`region.errorBoundary`); when an effect inside the try content
2359
+ * throws on a later re-run, `triggerEffects` → `routeEffectError` stores
2360
+ * the error here and force re-runs the boundary effect, which renders the
2361
+ * catch branch with it.
2362
+ * - **Recovery outside direct reads.** Reactive reads wrapped in nested
2363
+ * `$run` effects (text/attribute interpolation) are tracked by those
2364
+ * effects, not the boundary. When an error is routed, the boundary holds
2365
+ * the erroring effect's source signals (`heldSignals`) and re-subscribes
2366
+ * to them on every run that shows the catch branch, so a later change
2367
+ * re-attempts the try branch.
2368
+ * - **Top-level `@error` recovery.** Because the whole render is a
2369
+ * re-runnable branch, a later re-render error (from a nested control
2370
+ * re-running after a prop change) is caught by the same routing, and a
2371
+ * recovery re-render clears the error content and restores the normal
2372
+ * content.
2373
+ *
2374
+ * Semantics preserved from the compiled form:
2375
+ *
2376
+ * - Synchronous build errors in the try content render the catch branch
2377
+ * (rewinding the hydration cursor and restoring the control region, which
2378
+ * the failed partial build left active).
2379
+ * - While the try branch is showing, a boundary re-run with no routed error
2380
+ * does NOT rebuild it (`runControlBranch` same-index skip) — exactly like
2381
+ * `@if`/`@switch` branches.
2382
+ * - While the catch branch is showing, any boundary re-run re-attempts the
2383
+ * try branch (the recovery path for errors read directly by the boundary
2384
+ * effect, e.g. via `@const`).
2385
+ * - With no catch branch, errors propagate up to the nearest outer boundary
2386
+ * and no boundary is registered on the region.
2387
+ *
2388
+ * @param renderTry Builds the try content. May read reactive state.
2389
+ * @param renderCatch Builds the catch content, or null for `@try` without
2390
+ * `@catch`. Receives the error (the `@catch (err)` variable).
2391
+ */
2392
+ function runTry(region, anchor, renderTry, renderCatch, name) {
2393
+ const boundary = {
2394
+ error: void 0,
2395
+ hasError: false,
2396
+ effect: null,
2397
+ heldSignals: null
2398
+ };
2399
+ if (renderCatch !== null) region.errorBoundary = boundary;
2400
+ let index = -1;
2401
+ let first = true;
2402
+ const gen = region.generation = (region.generation ?? 0) + 1;
2403
+ $run(function runTry() {
2404
+ if (region.generation !== gen) return;
2405
+ const theEffect = context.activeTarget;
2406
+ boundary.effect = theEffect;
2407
+ const oldRegion = pushRegion(region, first);
2408
+ first = false;
2409
+ const renderBranch = (targetIndex, fn) => {
2410
+ runControlBranch(region, index, targetIndex);
2411
+ context.previousRegion = region;
2412
+ const oldR = pushRegion(newRegion(targetIndex === 0 ? "try" : "catch"), true);
2413
+ fn(anchor);
2414
+ popRegion(oldR);
2415
+ index = targetIndex;
2416
+ };
2417
+ const holdSignals = () => {
2418
+ if (boundary.heldSignals === null || theEffect === null) return;
2419
+ for (const signal of boundary.heldSignals) trackSignal(signal);
2420
+ };
2421
+ const hasRoutedError = boundary.hasError;
2422
+ const routedError = boundary.error;
2423
+ boundary.hasError = false;
2424
+ if (hasRoutedError && renderCatch !== null) {
2425
+ index = -1;
2426
+ renderBranch(1, (a) => renderCatch(a, routedError));
2427
+ holdSignals();
2428
+ } else if (index !== 0) {
2429
+ const snapshot = saveHydration();
2430
+ try {
2431
+ renderBranch(0, renderTry);
2432
+ boundary.heldSignals = null;
2433
+ } catch (err) {
2434
+ pushRegion(region);
2435
+ restoreHydration(snapshot);
2436
+ if (renderCatch !== null) {
2437
+ index = -1;
2438
+ renderBranch(1, (a) => renderCatch(a, err));
2439
+ holdSignals();
2440
+ } else throw err;
2441
+ }
2442
+ }
2443
+ popRegion(oldRegion);
2444
+ widenAncestorsAtAnchor(region, anchor);
2445
+ if (context.hydrationNode !== null && anchor !== null) context.hydrationNode = anchor;
2446
+ }, name);
2447
+ }
1126
2448
  //#endregion
1127
2449
  //#region src/render/setAttribute.ts
1128
2450
  function setAttribute(el, name, value) {
1129
2451
  if (value === false || value === void 0 || value === null) el.removeAttribute(name);
1130
2452
  else el.setAttribute(name, value);
1131
2453
  }
1132
-
1133
2454
  //#endregion
1134
2455
  //#region src/render/setDynamicElement.ts
1135
2456
  function setDynamicElement(el, tag) {
1136
- if (context_default.hydrationNode !== null) return el;
2457
+ if (context.hydrationNode !== null) return el;
1137
2458
  let newElement = el.ownerDocument.createElement(tag);
2459
+ for (const attr of el.attributes) newElement.setAttributeNS(null, attr.name, attr.value);
2460
+ copyEventListeners(el, newElement);
2461
+ newElement.replaceChildren(...el.childNodes.values());
1138
2462
  el.replaceWith(newElement);
1139
2463
  return newElement;
1140
2464
  }
1141
-
1142
2465
  //#endregion
1143
2466
  //#region src/watch/$batch.ts
1144
2467
  /**
@@ -1148,7 +2471,7 @@ function setDynamicElement(el, tag) {
1148
2471
  * @param fn The function containing the batched updates to run.
1149
2472
  */
1150
2473
  function $batch(fn) {
1151
- if (context_default.batch > 0) return fn();
2474
+ if (context.batch > 0) return fn();
1152
2475
  batchStart();
1153
2476
  try {
1154
2477
  return fn();
@@ -1156,7 +2479,127 @@ function $batch(fn) {
1156
2479
  batchEnd();
1157
2480
  }
1158
2481
  }
1159
-
2482
+ //#endregion
2483
+ //#region src/watch/$async.ts
2484
+ /**
2485
+ * Caches an async computed value from a thunk that returns a Promise. A peer
2486
+ * of `$cache` for async getters: the returned Computed carries a `didSuspend`
2487
+ * indicator that the proxy get trap reads to suspend callers until the promise
2488
+ * resolves.
2489
+ *
2490
+ * The thenable check and `.then` wiring live inside `computed.run` (a closure
2491
+ * over the computed object), so they fire on both the initial run and every
2492
+ * recalculation — `runComputed` and `checkComputed` are unchanged.
2493
+ *
2494
+ * @param fn A thunk returning the Promise to await. Signal reads inside `fn`
2495
+ * are tracked, so the fetch re-runs when dependencies change.
2496
+ */
2497
+ function $async(fn) {
2498
+ if (context.registerComputed === null) throw new Error("$async must be used in a getter");
2499
+ const computed = {
2500
+ type: 1,
2501
+ isAsync: true,
2502
+ value: null,
2503
+ run: null,
2504
+ firstSource: null,
2505
+ firstTarget: null,
2506
+ recalc: false,
2507
+ running: false,
2508
+ didError: false,
2509
+ didSuspend: false,
2510
+ generation: 0,
2511
+ hasResolved: false,
2512
+ lastErrored: false,
2513
+ suspendQuiet: false,
2514
+ staleValue: void 0,
2515
+ rollback: null
2516
+ };
2517
+ computed.run = () => {
2518
+ const value = fn();
2519
+ if (value !== null && value !== void 0 && typeof value.then === "function") {
2520
+ const gen = ++computed.generation;
2521
+ computed.didSuspend = true;
2522
+ computed.suspendQuiet = computed.hasResolved && !computed.recalc;
2523
+ value.then((v) => {
2524
+ if (computed.generation !== gen) return;
2525
+ computed.value = v;
2526
+ computed.didSuspend = false;
2527
+ computed.hasResolved = true;
2528
+ computed.lastErrored = false;
2529
+ computed.staleValue = v;
2530
+ batchStart();
2531
+ propagateFromSignal(computed);
2532
+ batchEnd();
2533
+ }, (e) => {
2534
+ if (computed.generation !== gen) return;
2535
+ computed.value = e;
2536
+ computed.didError = true;
2537
+ computed.didSuspend = false;
2538
+ computed.hasResolved = true;
2539
+ computed.lastErrored = true;
2540
+ computed.staleValue = void 0;
2541
+ batchStart();
2542
+ propagateFromSignal(computed);
2543
+ batchEnd();
2544
+ });
2545
+ }
2546
+ return value;
2547
+ };
2548
+ context.registerComputed(computed);
2549
+ runComputed(computed);
2550
+ return computed.value;
2551
+ }
2552
+ //#endregion
2553
+ //#region src/watch/$bind.ts
2554
+ /**
2555
+ * Establishes two-way reactive sync between matching keys on a state object
2556
+ * and a props object.
2557
+ *
2558
+ * For each key, `$bind` creates:
2559
+ * - **Forward sync** (`props → state`): when the parent pushes a new value via
2560
+ * `$props[key]`, it flows into `$state[key]`. Skips `undefined` values so
2561
+ * that defaults set in the initial `$watch(...)` are preserved when the
2562
+ * parent doesn't provide a value.
2563
+ * - **Backward sync** (`state → props`): when the component mutates
2564
+ * `$state[key]`, the new value is written back to `$props[key]`, which the
2565
+ * call site's `&key={...}` binding picks up and propagates to the parent.
2566
+ *
2567
+ * Same-value writes are no-ops (handled by the proxy layer), so two-way sync
2568
+ * stabilises without infinite loops.
2569
+ *
2570
+ * `$bind` syncs same-named keys, so the key must exist on the state object.
2571
+ * A state key named differently from the prop (e.g. `values` against a
2572
+ * `value` prop) would silently do nothing -- the binding reads and writes
2573
+ * keys that nothing else touches -- which is almost impossible to debug. The
2574
+ * key is therefore required to exist on the state object, and `$bind` throws
2575
+ * at setup otherwise.
2576
+ *
2577
+ * The prop does *not* need to exist on `props` yet: when the parent doesn't
2578
+ * pass an optional prop, the compiled props object has no key for it, and
2579
+ * the binding is simply inert (uncontrolled mode) until a value is pushed.
2580
+ *
2581
+ * @param state The component's reactive state (created via `$watch`).
2582
+ * @param props The component's `$props` proxy. When `undefined` (component
2583
+ * called with no props), `$bind` does nothing.
2584
+ * @param keys Keys to sync. Each key must exist on `state`.
2585
+ * @throws When a key does not exist on the state object.
2586
+ */
2587
+ function $bind(state, props, ...keys) {
2588
+ if (props === void 0) return;
2589
+ for (let key of keys.flat()) {
2590
+ if (!(key in state)) throw new Error(`$bind: the key "${key}" does not exist on the state object. $bind syncs same-named keys, so the state object must declare it (e.g. in the initial $watch).`);
2591
+ $run(() => {
2592
+ const v = props[key];
2593
+ if (v !== void 0) state[key] = v;
2594
+ }, `bind:forward:${key}`);
2595
+ let firstBackward = true;
2596
+ $run(() => {
2597
+ const value = state[key];
2598
+ if (!firstBackward) props[key] = value;
2599
+ firstBackward = false;
2600
+ }, `bind:backward:${key}`);
2601
+ }
2602
+ }
1160
2603
  //#endregion
1161
2604
  //#region src/watch/$cache.ts
1162
2605
  /**
@@ -1165,9 +2608,13 @@ function $batch(fn) {
1165
2608
  * @param fn The function containing the signals to compute and cache.
1166
2609
  */
1167
2610
  function $cache(fn) {
1168
- if (context_default.registerComputed === null) throw new Error("$cache must be used in a getter");
2611
+ if (context.registerComputed === null) {
2612
+ if (typeof window !== "undefined") throw new Error("$cache must be used in a getter");
2613
+ return fn();
2614
+ }
1169
2615
  let computed = {
1170
- type: COMPUTED_TYPE,
2616
+ type: 1,
2617
+ isAsync: false,
1171
2618
  value: null,
1172
2619
  run: fn,
1173
2620
  firstSource: null,
@@ -1175,106 +2622,274 @@ function $cache(fn) {
1175
2622
  recalc: false,
1176
2623
  running: false,
1177
2624
  didError: false,
2625
+ didSuspend: false,
2626
+ generation: 0,
2627
+ hasResolved: false,
2628
+ lastErrored: false,
2629
+ suspendQuiet: false,
2630
+ staleValue: void 0,
1178
2631
  rollback: null
1179
2632
  };
1180
- context_default.registerComputed(computed);
2633
+ context.registerComputed(computed);
1181
2634
  runComputed(computed);
2635
+ if (computed.value !== null && computed.value !== void 0 && typeof computed.value.then === "function") throw new Error("$cache returned a Promise — use $async for async getters");
1182
2636
  return computed.value;
1183
2637
  }
1184
-
1185
2638
  //#endregion
1186
- //#region src/watch/$mount.ts
2639
+ //#region src/watch/$onmount.ts
1187
2640
  /**
1188
- * Runs and re-runs a function on component mount
2641
+ * Runs `fn` once after the component is mounted to the DOM. May return a
2642
+ * cleanup function that runs on unmount / region clear.
2643
+ *
2644
+ * The callback is **not reactive**: it runs exactly once per mount, and
2645
+ * reactive values it reads are not tracked. To set up something that should
2646
+ * keep updating, wrap the reactive part in `$run`:
2647
+ *
2648
+ * ```ts
2649
+ * $onmount(() => {
2650
+ * $run(() => {
2651
+ * label.textContent = $state.count > 0 ? "+" : "";
2652
+ * });
2653
+ * });
2654
+ * ```
2655
+ *
2656
+ * The element-level equivalent is the `onmount` attribute:
2657
+ * `<input onmount={(el) => el.focus()} />`.
1189
2658
  *
1190
2659
  * @param fn The function to run, which may return a cleanup function
1191
2660
  */
1192
- function $mount(fn) {
1193
- context_default.mountEffects.push(fn);
2661
+ function $onmount(fn) {
2662
+ context.mountEffects.push({
2663
+ region: context.activeRegion,
2664
+ fn
2665
+ });
1194
2666
  }
1195
-
1196
2667
  //#endregion
1197
- //#region src/watch/$peek.ts
1198
- function $peek(fn) {
1199
- const oldActiveTarget = context_default.activeTarget;
1200
- context_default.activeTarget = null;
1201
- const result = fn();
1202
- context_default.activeTarget = oldActiveTarget;
1203
- return result;
2668
+ //#region src/watch/$pending.ts
2669
+ /**
2670
+ * Returns `true` if any value read inside `fn` is currently suspended in a
2671
+ * "loud" way — a `$async` getter whose promise hasn't resolved yet. A reactive
2672
+ * query for inline "loading…" indicators: the calling effect subscribes to the
2673
+ * same computeds, so `$pending` re-evaluates when they resolve.
2674
+ *
2675
+ * Uses a "peek mode" internally: reads during `fn` are tracked for
2676
+ * subscription but don't propagate taint or notify a `@await` boundary.
2677
+ * This lets `$pending` return a plain boolean without itself suspending.
2678
+ *
2679
+ * Quiet-on-refresh semantics (ASYNC.md §7.4): a suspend is *quiet* — and
2680
+ * therefore `$pending` returns `false` for it — when the computed has resolved
2681
+ * before and the re-fetch was a *silent* `$refresh(fn, { silent: true })` (a
2682
+ * bare refresh with no tracked dependency change, used for background
2683
+ * revalidation). This matches Solid's stale-while-revalidate default: quietly
2684
+ * re-asking the same question shouldn't ping the user. First loads and
2685
+ * dependency-change refreshes are loud (`true`), as is the default (loud)
2686
+ * `$refresh(fn)`. Quiet-ness is captured per computed at suspend time via
2687
+ * `suspendQuiet` (computed in `$async`'s run from `hasResolved` and `recalc`).
2688
+ *
2689
+ * @param fn A function that reads the reactive values to check.
2690
+ */
2691
+ function $pending(fn) {
2692
+ const oldPeek = context.suspendPeek;
2693
+ context.suspendPeek = true;
2694
+ context.suspendPeekHit = false;
2695
+ try {
2696
+ fn();
2697
+ return context.suspendPeekHit;
2698
+ } finally {
2699
+ context.suspendPeek = oldPeek;
2700
+ }
1204
2701
  }
1205
-
1206
2702
  //#endregion
1207
- //#region src/wrappers/ReactiveDate.ts
1208
- let initialized = false;
2703
+ //#region src/watch/$refresh.ts
1209
2704
  /**
1210
- * Wraps a Date object for $watching.
2705
+ * Re-fetches the `$async` getters read inside `fn` without changing a
2706
+ * dependency. A companion to `$pending` (ASYNC.md §6.2): pull-to-refresh,
2707
+ * refresh buttons, refetch-on-focus, polling, retry-after-error.
2708
+ *
2709
+ * `fn` is run in a tracking context that collects every `$async` computed it
2710
+ * reads (`$cache` computeds are ignored). Each collected computed is then
2711
+ * re-run with `recalc` left true — a "bare refresh" — so the suspend is
2712
+ * *loud*: `$pending(fn)` returns `true` while the re-fetch is in flight and
2713
+ * subscribers are notified at suspend *start*, so an inline "updating…"
2714
+ * indicator appears immediately. Readers keep displaying the previous
2715
+ * resolved value (`Computed.staleValue`) until the new promise resolves and
2716
+ * propagates through the reactive graph; an `@await` boundary keeps its
2717
+ * content mounted instead of flashing fallback.
2718
+ *
2719
+ * Pass `{ silent: true }` to re-fetch quietly (stale-while-revalidate):
2720
+ * `$pending(fn)` stays `false` and nothing re-runs until the new promise
2721
+ * resolves. For background revalidation where feedback would be noise —
2722
+ * polling, refetch-on-focus:
2723
+ *
2724
+ * ```torp
2725
+ * // poll quietly every 30s
2726
+ * $run(() => {
2727
+ * const id = setInterval(() => $refresh(() => $state.data, { silent: true }), 30_000);
2728
+ * return () => clearInterval(id);
2729
+ * });
2730
+ * ```
2731
+ *
2732
+ * A refresh is loud regardless of `silent` when the computed has never
2733
+ * resolved — e.g. retrying after an error that left `didError` set on a first
2734
+ * load — or when the re-fetch is triggered by a dependency change, which
2735
+ * flows through the normal `recalc` path instead of here.
2736
+ *
2737
+ * If `fn` reads a getter the UI has never read, the collection read
2738
+ * initializes it — and that fetch IS the refresh: the computed is not re-run
2739
+ * (a second fetch would be a duplicate whose resolve the generation guard
2740
+ * drops). Getters already read (pending, resolved, or errored) are re-run as
2741
+ * usual.
2742
+ *
2743
+ * The returned value of `fn` is ignored; use `fn` to reference the getters.
1211
2744
  */
1212
- var ReactiveDate = class ReactiveDate extends Date {
1213
- constructor(...params) {
1214
- super(...params);
1215
- if (!initialized) this.#init();
1216
- this[require_formatText.proxyHandledSymbol] = true;
1217
- this[require_formatText.proxyDataSymbol] = {
1218
- target: this,
1219
- isArray: false,
1220
- shallow: true,
1221
- signals: /* @__PURE__ */ new Map()
1222
- };
2745
+ function $refresh(fn, options) {
2746
+ const silent = options?.silent === true;
2747
+ const oldRefreshSignals = context.refreshSignals;
2748
+ const oldPeek = context.suspendPeek;
2749
+ const oldInitialized = context.refreshInitialized;
2750
+ context.refreshSignals = [];
2751
+ context.suspendPeek = true;
2752
+ context.refreshInitialized = /* @__PURE__ */ new Set();
2753
+ let unique;
2754
+ let initialized;
2755
+ try {
2756
+ fn();
2757
+ unique = new Set(context.refreshSignals ?? []);
2758
+ initialized = context.refreshInitialized;
2759
+ } finally {
2760
+ context.refreshSignals = oldRefreshSignals;
2761
+ context.suspendPeek = oldPeek;
2762
+ context.refreshInitialized = oldInitialized;
1223
2763
  }
1224
- #init() {
1225
- initialized = true;
1226
- let reactivePrototype = ReactiveDate.prototype;
1227
- let datePrototype = Date.prototype;
1228
- const methods = Object.getOwnPropertyNames(datePrototype);
1229
- for (const method of methods) {
1230
- if (method.startsWith("get") || method.startsWith("to") || method === "valueOf") reactivePrototype[method] = function(...args) {
1231
- const data = this[require_formatText.proxyDataSymbol];
1232
- const result = datePrototype[method].apply(this, args);
1233
- trackProxySignal(data, "#time");
1234
- return result;
1235
- };
1236
- if (method.startsWith("set")) reactivePrototype[method] = function(...args) {
1237
- const data = this[require_formatText.proxyDataSymbol];
1238
- const result = datePrototype[method].apply(this, args);
1239
- propagateSignal(data, "#time");
1240
- return result;
1241
- };
2764
+ for (const computed of unique) {
2765
+ if (initialized.has(computed)) continue;
2766
+ computed.recalc = !silent;
2767
+ deactivateSources(computed);
2768
+ const oldActiveTarget = context.activeTarget;
2769
+ context.activeTarget = null;
2770
+ try {
2771
+ runComputed(computed);
2772
+ } finally {
2773
+ context.activeTarget = oldActiveTarget;
2774
+ }
2775
+ computed.recalc = false;
2776
+ clearSources(computed);
2777
+ if (!silent) {
2778
+ batchStart();
2779
+ propagateFromSignal(computed);
2780
+ batchEnd();
1242
2781
  }
1243
2782
  }
1244
- };
1245
-
2783
+ }
2784
+ //#endregion
2785
+ //#region src/watch/$stream.ts
2786
+ /**
2787
+ * Subscribes to an external source of events — server-sent events,
2788
+ * WebSockets, DOM events, or any custom `StreamSource` — and calls
2789
+ * `handler` for each event it pushes. Events are typically written into
2790
+ * reactive state, which keeps templates, computeds and effects updating
2791
+ * through the normal reactivity model:
2792
+ *
2793
+ * ```torp
2794
+ * let $state = $watch({ messages: [] as string[] });
2795
+ *
2796
+ * $stream(fromServer(`/sse/${$props.id}`), (e) => {
2797
+ * $state.messages.push(e.data);
2798
+ * });
2799
+ * ```
2800
+ *
2801
+ * The subscription is managed by the framework:
2802
+ *
2803
+ * - It starts when the component is mounted to the DOM (so `&ref`-bound
2804
+ * elements are available), and is unsubscribed when the component
2805
+ * unmounts or its region is cleared.
2806
+ * - Reactive state read *inside* the source is tracked: when it changes,
2807
+ * the source is unsubscribed and re-subscribed with fresh values (e.g.
2808
+ * re-opening a connection when a user id changes). A pending debounced
2809
+ * call is dropped on re-subscribe.
2810
+ * - The source is never invoked during a server render, so browser-only
2811
+ * APIs are safe to use.
2812
+ *
2813
+ * Errors are values like any other: a source that can fail should push an
2814
+ * error-shaped value and own its own reconnection (e.g. `EventSource`
2815
+ * reconnects automatically).
2816
+ *
2817
+ * @param source The stream source to subscribe to
2818
+ * @param handler Called for each event the source pushes
2819
+ * @param options Timing options. `debounce` delays each handler call until
2820
+ * the source has been quiet for that many milliseconds, resetting on
2821
+ * every event (only the last event in a burst is handled).
2822
+ */
2823
+ function $stream(source, handler, options) {
2824
+ const fn = () => {
2825
+ let timer;
2826
+ $run(() => {
2827
+ const unsub = source((value) => {
2828
+ if (options?.debounce) {
2829
+ clearTimeout(timer);
2830
+ timer = setTimeout(() => handler(value), options.debounce);
2831
+ } else handler(value);
2832
+ });
2833
+ return () => {
2834
+ unsub?.();
2835
+ clearTimeout(timer);
2836
+ };
2837
+ });
2838
+ };
2839
+ context.mountEffects.push({
2840
+ region: context.activeRegion,
2841
+ fn
2842
+ });
2843
+ }
1246
2844
  //#endregion
2845
+ exports.$async = $async;
1247
2846
  exports.$batch = $batch;
2847
+ exports.$bind = $bind;
1248
2848
  exports.$cache = $cache;
1249
- exports.$mount = $mount;
2849
+ exports.$onmount = $onmount;
1250
2850
  exports.$peek = $peek;
2851
+ exports.$pending = $pending;
2852
+ exports.$refresh = $refresh;
1251
2853
  exports.$run = $run;
1252
- exports.$unwrap = require_formatText.$unwrap;
2854
+ exports.$stream = $stream;
2855
+ exports.$unwrap = require_fromWebSocket.$unwrap;
1253
2856
  exports.$watch = $watch;
1254
- exports.ReactiveDate = ReactiveDate;
1255
2857
  exports.clearLayoutSlot = clearLayoutSlot;
1256
2858
  exports.fillLayoutSlot = fillLayoutSlot;
2859
+ exports.fromElement = require_fromWebSocket.fromElement;
2860
+ exports.fromServer = require_fromWebSocket.fromServer;
2861
+ exports.fromWebSocket = require_fromWebSocket.fromWebSocket;
1257
2862
  exports.hydrate = hydrate;
1258
2863
  exports.mount = mount;
2864
+ exports.t_add_element = addElement;
1259
2865
  exports.t_add_fragment = addFragment;
1260
2866
  exports.t_anchor = nodeAnchor;
1261
2867
  exports.t_animate = addAnimation;
1262
2868
  exports.t_apply_props = applyProps;
1263
2869
  exports.t_attribute = setAttribute;
1264
2870
  exports.t_child = nodeChild;
1265
- exports.t_class = require_formatText.buildClasses;
2871
+ exports.t_class = require_fromWebSocket.buildClasses;
1266
2872
  exports.t_dynamic = setDynamicElement;
1267
2873
  exports.t_event = addEvent;
1268
- exports.t_fmt = require_formatText.formatText;
2874
+ exports.t_first_inside = firstInsideNode;
2875
+ exports.t_fmt = require_fromWebSocket.formatText;
1269
2876
  exports.t_fragment = getFragment;
2877
+ exports.t_fragment_el = getElementFragment;
1270
2878
  exports.t_list_item = newListItem;
1271
2879
  exports.t_next = nodeNext;
1272
2880
  exports.t_pop_region = popRegion;
1273
2881
  exports.t_push_region = pushRegion;
1274
2882
  exports.t_region = newRegion;
2883
+ exports.t_rerun_region_effects = rerunRegionEffects;
2884
+ exports.t_restore_hydration = restoreHydration;
1275
2885
  exports.t_root = nodeRoot;
2886
+ exports.t_root_el = nodeRootElement;
2887
+ exports.t_run_await = runAwait;
1276
2888
  exports.t_run_branch = runControlBranch;
1277
2889
  exports.t_run_control = runControl;
1278
2890
  exports.t_run_list = runList;
2891
+ exports.t_run_try = runTry;
2892
+ exports.t_save_hydration = saveHydration;
1279
2893
  exports.t_skip = nodeSkip;
1280
- exports.t_style = require_formatText.buildStyles;
2894
+ exports.t_style = require_fromWebSocket.buildStyles;
2895
+ exports.unmount = unmount;