svelte 5.58.0 → 5.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/compiler/index.js +1 -1
  2. package/package.json +19 -1
  3. package/renderer.d.ts +1 -0
  4. package/src/compiler/errors.js +19 -0
  5. package/src/compiler/index.js +37 -2
  6. package/src/compiler/migrate/index.js +2 -1
  7. package/src/compiler/phases/1-parse/read/options.js +20 -0
  8. package/src/compiler/phases/2-analyze/index.js +21 -2
  9. package/src/compiler/phases/2-analyze/visitors/AnimateDirective.js +5 -0
  10. package/src/compiler/phases/2-analyze/visitors/Attribute.js +6 -2
  11. package/src/compiler/phases/2-analyze/visitors/BindDirective.js +4 -0
  12. package/src/compiler/phases/2-analyze/visitors/ExpressionTag.js +2 -1
  13. package/src/compiler/phases/2-analyze/visitors/HtmlTag.js +5 -0
  14. package/src/compiler/phases/2-analyze/visitors/OnDirective.js +6 -0
  15. package/src/compiler/phases/2-analyze/visitors/RegularElement.js +13 -6
  16. package/src/compiler/phases/2-analyze/visitors/SvelteBody.js +5 -0
  17. package/src/compiler/phases/2-analyze/visitors/SvelteDocument.js +5 -0
  18. package/src/compiler/phases/2-analyze/visitors/SvelteElement.js +5 -1
  19. package/src/compiler/phases/2-analyze/visitors/SvelteHead.js +5 -0
  20. package/src/compiler/phases/2-analyze/visitors/SvelteWindow.js +5 -0
  21. package/src/compiler/phases/2-analyze/visitors/Text.js +3 -1
  22. package/src/compiler/phases/2-analyze/visitors/TransitionDirective.js +6 -0
  23. package/src/compiler/phases/2-analyze/visitors/shared/element.js +3 -2
  24. package/src/compiler/phases/3-transform/client/transform-client.js +68 -1
  25. package/src/compiler/phases/3-transform/client/transform-template/index.js +4 -3
  26. package/src/compiler/phases/3-transform/client/transform-template/template.js +1 -1
  27. package/src/compiler/phases/3-transform/client/utils.js +3 -2
  28. package/src/compiler/phases/3-transform/client/visitors/RegularElement.js +23 -13
  29. package/src/compiler/phases/3-transform/client/visitors/RenderTag.js +13 -1
  30. package/src/compiler/phases/3-transform/client/visitors/SnippetBlock.js +11 -1
  31. package/src/compiler/phases/3-transform/client/visitors/SvelteBoundary.js +8 -5
  32. package/src/compiler/phases/3-transform/client/visitors/shared/component.js +17 -8
  33. package/src/compiler/phases/3-transform/client/visitors/shared/element.js +4 -3
  34. package/src/compiler/phases/3-transform/client/visitors/shared/fragment.js +7 -1
  35. package/src/compiler/phases/3-transform/server/transform-server.js +14 -1
  36. package/src/compiler/phases/3-transform/server/visitors/ExpressionStatement.js +8 -0
  37. package/src/compiler/phases/3-transform/server/visitors/RegularElement.js +8 -4
  38. package/src/compiler/print/index.js +45 -57
  39. package/src/compiler/state.js +12 -0
  40. package/src/compiler/utils/builders.js +2 -2
  41. package/src/compiler/validate-options.js +47 -1
  42. package/src/index-client.js +3 -3
  43. package/src/internal/client/constants.js +15 -1
  44. package/src/internal/client/custom-renderer/containers.js +213 -0
  45. package/src/internal/client/custom-renderer/cross.js +145 -0
  46. package/src/internal/client/custom-renderer/index.js +28 -0
  47. package/src/internal/client/custom-renderer/state.js +59 -0
  48. package/src/internal/client/dev/css.js +3 -1
  49. package/src/internal/client/dev/debug.js +6 -6
  50. package/src/internal/client/dev/elements.js +9 -7
  51. package/src/internal/client/dev/tracing.js +67 -11
  52. package/src/internal/client/dev/validation.js +2 -1
  53. package/src/internal/client/dom/blocks/async.js +2 -1
  54. package/src/internal/client/dom/blocks/await.js +110 -19
  55. package/src/internal/client/dom/blocks/boundary.js +142 -88
  56. package/src/internal/client/dom/blocks/branches.js +94 -75
  57. package/src/internal/client/dom/blocks/css-props.js +31 -3
  58. package/src/internal/client/dom/blocks/each.js +166 -45
  59. package/src/internal/client/dom/blocks/html.js +19 -13
  60. package/src/internal/client/dom/blocks/slot.js +3 -3
  61. package/src/internal/client/dom/blocks/snippet.js +52 -3
  62. package/src/internal/client/dom/blocks/svelte-element.js +17 -6
  63. package/src/internal/client/dom/blocks/svelte-head.js +13 -4
  64. package/src/internal/client/dom/css.js +4 -4
  65. package/src/internal/client/dom/elements/attributes.js +91 -51
  66. package/src/internal/client/dom/elements/bindings/input.js +19 -10
  67. package/src/internal/client/dom/elements/bindings/select.js +13 -9
  68. package/src/internal/client/dom/elements/class.js +16 -5
  69. package/src/internal/client/dom/elements/events.js +153 -21
  70. package/src/internal/client/dom/elements/misc.js +3 -2
  71. package/src/internal/client/dom/elements/style.js +17 -6
  72. package/src/internal/client/dom/hydration.js +6 -6
  73. package/src/internal/client/dom/operations.js +435 -14
  74. package/src/internal/client/dom/reconciler.js +2 -2
  75. package/src/internal/client/dom/template.js +94 -66
  76. package/src/internal/client/error-handling.js +4 -12
  77. package/src/internal/client/errors.js +85 -2
  78. package/src/internal/client/index.js +9 -2
  79. package/src/internal/client/reactivity/async.js +257 -122
  80. package/src/internal/client/reactivity/batch.js +1124 -531
  81. package/src/internal/client/reactivity/deriveds.js +281 -177
  82. package/src/internal/client/reactivity/effects.js +87 -54
  83. package/src/internal/client/reactivity/sources.js +30 -124
  84. package/src/internal/client/reactivity/status.js +1 -1
  85. package/src/internal/client/render.js +60 -87
  86. package/src/internal/client/runtime.js +931 -153
  87. package/src/internal/client/validate.js +2 -2
  88. package/src/internal/disclose-version.js +1 -1
  89. package/src/internal/flags/custom-renderer-server.js +10 -0
  90. package/src/internal/flags/custom-renderer.js +3 -0
  91. package/src/internal/flags/index.js +6 -0
  92. package/src/internal/init-operations.js +3 -0
  93. package/src/internal/shared/errors.js +20 -0
  94. package/src/legacy/legacy-client.js +6 -2
  95. package/src/renderer/index-server.js +18 -0
  96. package/src/renderer/index.js +2 -0
  97. package/src/version.js +1 -1
  98. package/types/index.d.ts +245 -25
  99. package/types/index.d.ts.map +10 -1
  100. package/src/internal/client/reactivity/utils.js +0 -18
@@ -1,5 +1,6 @@
1
1
  /** @import { Fork } from 'svelte' */
2
- /** @import { Derived, Effect, Reaction, Source, Value } from '#client' */
2
+ /** @import { BatchRecord, BatchValue, Derived, DerivedRecord, Effect, Reaction, Source, Value } from '#client' */
3
+ /** @import { Boundary } from '../dom/blocks/boundary.js' */
3
4
  import {
4
5
  BLOCK_EFFECT,
5
6
  BRANCH_EFFECT,
@@ -7,7 +8,6 @@ import {
7
8
  DESTROYED,
8
9
  DIRTY,
9
10
  EFFECT,
10
- ASYNC,
11
11
  INERT,
12
12
  RENDER_EFFECT,
13
13
  ROOT_EFFECT,
@@ -17,31 +17,51 @@ import {
17
17
  ERROR_VALUE,
18
18
  MANAGED_EFFECT,
19
19
  REACTION_RAN,
20
- DESTROYING
20
+ DESTROYING,
21
+ EFFECT_OFFSCREEN,
22
+ ASSIGNED,
23
+ ASYNC,
24
+ REACTION_IS_UPDATING,
25
+ BOUNDARY_EFFECT
21
26
  } from '#client/constants';
22
- import { async_mode_flag } from '../../flags/index.js';
23
- import { deferred, define_property, includes } from '../../shared/utils.js';
27
+ import { async_mode_flag, custom_renderers_flag } from '../../flags/index.js';
28
+ import { deferred, define_property } from '../../shared/utils.js';
24
29
  import {
30
+ active_effect,
25
31
  active_reaction,
26
32
  get,
27
33
  increment_write_version,
34
+ is_destroying_effect,
28
35
  is_dirty,
29
- update_effect
36
+ is_outdated,
37
+ promote_record,
38
+ prune_edges,
39
+ untrack,
40
+ update_effect,
41
+ write_version,
42
+ abort_record
30
43
  } from '../runtime.js';
31
44
  import * as e from '../errors.js';
32
45
  import { flush_tasks, queue_micro_task } from '../dom/task.js';
33
46
  import { DEV } from 'esm-env';
34
47
  import { invoke_error_boundary } from '../error-handling.js';
35
- import { flush_eager_effects, old_values, set_eager_effects, source, update } from './sources.js';
48
+ import {
49
+ eager_effects,
50
+ eager_effects_deferred,
51
+ flush_eager_effects,
52
+ source,
53
+ update
54
+ } from './sources.js';
36
55
  import { eager_effect, teardown, unlink_effect } from './effects.js';
37
- import { defer_effect } from './utils.js';
38
56
  import { UNINITIALIZED } from '../../../constants.js';
39
- import { set_signal_status } from './status.js';
57
+ import { set_signal_status, update_derived_status } from './status.js';
40
58
  import { invariant } from '../../shared/dev.js';
41
59
  import { OBSOLETE } from './deriveds.js';
60
+ import { is_runes } from '../context.js';
61
+ import { merge_target } from './async.js';
42
62
 
43
63
  /** @type {Batch | null} */
44
- let first_batch = null;
64
+ export let first_batch = null;
45
65
 
46
66
  /** @type {Batch | null} */
47
67
  let last_batch = null;
@@ -50,24 +70,99 @@ let last_batch = null;
50
70
  export let current_batch = null;
51
71
 
52
72
  /**
53
- * This is needed to avoid overwriting inputs
73
+ * The batch currently being processed (see `#process`)
54
74
  * @type {Batch | null}
55
75
  */
56
- export let previous_batch = null;
76
+ export let processing_batch = null;
77
+
78
+ /**
79
+ * @typedef {Object} TeardownContext
80
+ * @property {Map<Value, BatchValue>} reverted_values What teardowns see instead of the values sources hold: the values
81
+ * from before the writes that caused the teardowns (the `previous` of the batch being processed, see `flush`). For
82
+ * block effects that re-run right away because of a user effect's writes, also the writes of the effects that ran
83
+ * before it in the same commit, which apply (see `flush_queued_effects`)
84
+ * @property {Map<Derived, BatchValue>} derived_cache The values of deriveds in this view (see `runtime.js#teardown_view`),
85
+ * until it changes
86
+ * @property {TeardownContext | null} parent The context to restore after a nested flush or eager block
87
+ */
88
+
89
+ /**
90
+ * Effect teardowns revert the writes that caused them (see `runtime.js#teardown_view`).
91
+ * (A teardown outside of a flush reverts nothing, but gets a context to cache its deriveds in, for as long as it
92
+ * runs — see `execute_effect_teardown`)
93
+ * @type {TeardownContext | null}
94
+ */
95
+ export let teardown_context = null;
96
+
97
+ /** @param {TeardownContext | null} context */
98
+ export function set_teardown_context(context) {
99
+ teardown_context = context;
100
+ }
101
+
102
+ /** @param {Map<Value, BatchValue>} [values] */
103
+ export function push_teardown_context(values) {
104
+ var context = (teardown_context = {
105
+ reverted_values: new Map(teardown_context?.reverted_values),
106
+ derived_cache: new Map(),
107
+ parent: teardown_context
108
+ });
109
+
110
+ for (const [source, value] of values ?? []) context.reverted_values.set(source, value);
111
+
112
+ return context;
113
+ }
114
+
115
+ /**
116
+ * A write in a teardown remains visible after returning to an enclosing teardown view,
117
+ * and the deriveds that teardowns evaluated may depend on it
118
+ * @param {Value} source
119
+ */
120
+ export function teardown_write(source) {
121
+ for (var context = teardown_context; context !== null; context = context.parent) {
122
+ context.reverted_values.delete(source);
123
+ context.derived_cache.clear();
124
+ }
125
+ }
57
126
 
58
127
  /**
59
128
  * When time travelling (i.e. working in one batch, while other batches
60
129
  * still have ongoing work), we ignore the real values of affected
61
- * signals in favour of their values within the batch
62
- * @type {Map<Value, any> | null}
130
+ * signals in favour of their values within the batch — along with their
131
+ * versions: the batch's writes, and the values from before the writes of
132
+ * other batches, which its view of the world undoes (see `activate`).
133
+ * `null` means that the real world (i.e. the latest values) applies.
134
+ * Doesn't contain computed deriveds, these are in {@link view_cache}.
135
+ * @type {Map<Value, BatchValue> | null}
63
136
  */
64
137
  export let batch_values = null;
65
138
 
139
+ /**
140
+ * The values of deriveds in the active view of the world, for as long as it is active (see `get_view`):
141
+ * a record of a run (in which case `e` tells whether its value is an error), the derived itself if its
142
+ * global state applies, or the write to it that holds (an assignment). Exists whenever `batch_values` does
143
+ * @type {Map<Derived, Derived | DerivedRecord | BatchValue> | null}
144
+ */
145
+ export let view_cache = null;
146
+
147
+ /**
148
+ * The batch whose view of the world is active (see `activate`). Block and async
149
+ * effects that run while it is processed, and deriveds evaluated with values
150
+ * that are not the latest, are recorded in this batch
151
+ * @type {Batch | null}
152
+ */
153
+ export let view_batch = null;
154
+
66
155
  /** @type {Effect | null} */
67
156
  let last_scheduled_effect = null;
68
157
 
158
+ /**
159
+ * Batches whose view of the world changed because another batch committed, and that
160
+ * therefore need to be processed again once the current flush is done (see `#commit`)
161
+ * @type {Set<Batch>}
162
+ */
163
+ var rebases = new Set();
164
+
69
165
  export let is_flushing_sync = false;
70
- let is_processing = false;
71
166
 
72
167
  /**
73
168
  * During traversal, this is an array. Newly created effects are (if not immediately
@@ -91,8 +186,22 @@ var flush_count = 0;
91
186
  /** Sources whose DEV update counts and stack traces need resetting after the flush. @type {Set<Value>} */
92
187
  export const source_stacks = new Set();
93
188
 
189
+ /**
190
+ * A set of signals we have already seen while traversing in `batch.mark`.
191
+ * Not always set to balance the common case of sources only having a couple
192
+ * of (transitive) dependencies (where always creating a Set would be bad for perf)
193
+ * with the edge case of extremely deep or wide dependency arrays with cycles.
194
+ * @type {Set<any> | null}
195
+ */
196
+ var seen = null;
197
+ /** Number of transitive dependencies, see {@link seen} for more info */
198
+ var count_deps = 0;
199
+
94
200
  let uid = 1;
95
201
 
202
+ /** @type {number | null} */
203
+ let last_processed = null;
204
+
96
205
  export class Batch {
97
206
  id = uid++;
98
207
 
@@ -111,43 +220,60 @@ export class Batch {
111
220
  async_deriveds = new Map();
112
221
 
113
222
  /**
114
- * The current values of any signals that are updated in this batch.
115
- * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)
116
- * The keys of this map are identical to `this.previous`
117
- * @type {Map<Value, [any, boolean]>}
223
+ * The current values (and their versions) of any sources that are updated in this batch,
224
+ * including deriveds that were overridden via assignment — until it commits them (see `#commit`).
225
+ * Its keys are those of `this.previous`, plus the sources this batch gave their first value. `e` says whether
226
+ * the value is an error
227
+ * @type {Map<Value, BatchValue>}
118
228
  */
119
229
  current = new Map();
120
230
 
121
231
  /**
122
- * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place.
123
- * The keys of this map are identical to `this.current`
124
- * @type {Map<Value, any>}
232
+ * The values (and their versions) of any sources that are updated in this batch _before_ those updates took place.
233
+ * For a derived, `assigned` says whether its value before was assigned, too (otherwise it was computed).
234
+ * A source that this batch gave its first value (e.g. an async expression that resolved for the first time) has
235
+ * no entry: there's no value from before it, so other views can't undo the write, and teardowns don't revert it.
236
+ * @type {Map<Value, BatchValue>}
125
237
  */
126
238
  previous = new Map();
127
239
 
128
240
  /**
129
- * When the batch is committed (and the DOM is updated), we need to remove old branches
130
- * and append new ones by calling the functions added inside (if/each/key/etc) blocks
131
- * @type {Set<(batch: Batch) => void>}
241
+ * Results of reactions that belong to this batch rather than to the real world:
242
+ * deriveds evaluated in this batch's view of the world with values that are not the
243
+ * latest ones, and block/async effects that ran while this batch was processed.
244
+ * Effect records become global state when the batch commits (see `promote_record`)
245
+ * @type {Map<Reaction, BatchRecord> | null}
132
246
  */
133
- #commit_callbacks = new Set();
247
+ records = null;
134
248
 
135
249
  /**
136
- * If a fork is discarded, we need to destroy any effects that are no longer needed
137
- * @type {Set<(batch: Batch) => void>}
250
+ * Earlier batches whose changes are part of this batch's view of the world, because
251
+ * they intersect with it (this batch will be merged into them, see `#merge`)
252
+ * @type {Batch[]}
138
253
  */
139
- #discard_callbacks = new Set();
254
+ folded = [];
140
255
 
141
256
  /**
142
- * The number of async effects that are currently in flight
257
+ * When the batch is committed (and the DOM is updated), we need to remove old branches
258
+ * and append new ones by calling the functions added inside (if/each/key/etc) blocks.
259
+ * Each callback maps to the writes that apply in the teardowns it causes, if it was added
260
+ * while block effects re-ran eagerly (see `eager_block_writes`)
261
+ * @type {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>}
262
+ */
263
+ #commit_callbacks = new Map();
264
+
265
+ /**
266
+ * If a fork is discarded, we need to destroy any effects that are no longer needed
267
+ * (see `#commit_callbacks`)
268
+ * @type {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>}
143
269
  */
144
- #pending = 0;
270
+ #discard_callbacks = new Map();
145
271
 
146
272
  /**
147
- * Async effects that are currently in flight, _not_ inside a pending boundary
273
+ * Async effects that are currently in flight
148
274
  * @type {Map<Effect, number>}
149
275
  */
150
- #blocking_pending = new Map();
276
+ #pending = new Map();
151
277
 
152
278
  /**
153
279
  * A deferred that resolves when the batch is committed, used with `settled()`
@@ -156,6 +282,14 @@ export class Batch {
156
282
  */
157
283
  #deferred = null;
158
284
 
285
+ /**
286
+ * Effects to (re-)validate when this batch is processed next, and their status (DIRTY or MAYBE_DIRTY):
287
+ * those that were scheduled while it wasn't being processed (see {@link schedule}), and those whose run
288
+ * was deferred because it has pending work (see `#defer_effects`)
289
+ * @type {Map<Effect, number>}
290
+ */
291
+ #unprocessed = new Map();
292
+
159
293
  /**
160
294
  * Effects that were scheduled in this batch but not yet 'resolved' into the
161
295
  * root effects that need to be flushed. Resolving — the upwards traversal that
@@ -170,33 +304,35 @@ export class Batch {
170
304
  #scheduled = [];
171
305
 
172
306
  /**
173
- * Effects created while this batch was active.
174
- * @type {Effect[]}
307
+ * Branches that still exist, but will be destroyed when this batch
308
+ * is committed — we skip over these during `#process`
309
+ * @type {Set<Effect>}
175
310
  */
176
- #new_effects = [];
311
+ #skipped_branches = new Set();
177
312
 
178
313
  /**
179
- * Deferred effects (which run after async work has completed) and their status (DIRTY or MAYBE_DIRTY)
180
- * @type {Map<Effect, number>}
314
+ * Branches that this batch selected (see `unskip_effect`). A branch that is offscreen until
315
+ * it is committed (see `EFFECT_OFFSCREEN`) only exists in the views of the batches that selected it
316
+ * @type {Set<Effect>}
181
317
  */
182
- #dirty_reactions = new Map();
318
+ #unskipped_branches = new Set();
319
+
320
+ is_fork = false;
183
321
 
184
322
  /**
185
- * A map of branches that still exist, but will be destroyed when this batch
186
- * is committed — we skip over these during `process`.
187
- * The value contains child effects that were dirty/maybe_dirty before being reset,
188
- * so they can be rescheduled if the branch survives.
189
- * @type {Map<Effect, { d: Effect[], m: Effect[] }>}
323
+ * The batch that this one was merged into, if any (see `#merge`). Its async work that is still in flight
324
+ * continues as part of that one
325
+ * @type {Batch | null}
190
326
  */
191
- #skipped_branches = new Map();
327
+ merged = null;
192
328
 
193
329
  /**
194
- * Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing
195
- * @type {Set<Effect>}
330
+ * Batches whose runs this batch aborted. Merge into them before waiting for pending work.
331
+ * Requests belong to this batch because a synchronous derived can abort outside traversal,
332
+ * before an unrelated batch is processed (e.g. a fork being committed).
333
+ * @type {Set<Batch>}
196
334
  */
197
- #unskipped_branches = new Set();
198
-
199
- is_fork = false;
335
+ merge_requests = new Set();
200
336
 
201
337
  #decrement_queued = false;
202
338
 
@@ -214,9 +350,8 @@ export class Batch {
214
350
  #is_deferred() {
215
351
  if (this.is_fork) return true;
216
352
 
217
- for (const effect of this.#blocking_pending.keys()) {
218
- // pending work inside a skipped branch doesn't block, the branch is going to be destroyed
219
- if (!this.#is_skipped(effect)) {
353
+ for (const effect of this.#pending.keys()) {
354
+ if (this.is_blocked_by(effect)) {
220
355
  return true;
221
356
  }
222
357
  }
@@ -225,50 +360,107 @@ export class Batch {
225
360
  }
226
361
 
227
362
  /**
228
- * Whether `effect` is inside a branch that this batch skips
363
+ * Whether `effect` is a branch that this batch skips, or that only exists offscreen for other batches
229
364
  * @param {Effect} effect
230
365
  */
231
- #is_skipped(effect) {
366
+ #skips(effect) {
367
+ return (
368
+ this.#skipped_branches.has(effect) ||
369
+ ((effect.f & EFFECT_OFFSCREEN) !== 0 && !this.#unskipped_branches.has(effect))
370
+ );
371
+ }
372
+
373
+ /**
374
+ * Whether `effect` is inside a branch that this batch skips, i.e. doesn't exist in its view of the world
375
+ * @param {Effect} effect
376
+ */
377
+ is_skipped(effect) {
232
378
  for (var e = /** @type {Effect | null} */ (effect); e !== null; e = e.parent) {
233
- if (this.#skipped_branches.has(e)) return true;
379
+ if (this.#skips(e)) return true;
234
380
  }
235
381
 
236
382
  return false;
237
383
  }
238
384
 
239
385
  /**
240
- * Add an effect to the #skipped_branches map and reset its children
386
+ * Whether async work in `effect` holds up this batch — or, with `root`, the boundary whose content `root` is.
387
+ * It doesn't if the effect is inside a branch that this batch skips (the branch is going to be destroyed),
388
+ * or inside a boundary that is pending (which shows its pending snippet in the meantime).
389
+ * Unlike a skipped branch, the content of a pending boundary does exist in the view of the batch: its
390
+ * effects are still re-validated (see `#revalidate`), they just don't keep the batch from committing
241
391
  * @param {Effect} effect
392
+ * @param {Effect | null} [root]
242
393
  */
243
- skip_effect(effect) {
244
- if (!this.#skipped_branches.has(effect)) {
245
- this.#skipped_branches.set(effect, { d: [], m: [] });
394
+ is_blocked_by(effect, root = null) {
395
+ for (var e = /** @type {Effect | null} */ (effect); e !== null && e !== root; e = e.parent) {
396
+ if (this.#skips(e)) return false;
397
+
398
+ if (
399
+ (e.f & (BOUNDARY_EFFECT | DESTROYED)) === BOUNDARY_EFFECT &&
400
+ /** @type {Boundary} */ (e.b).is_pending
401
+ ) {
402
+ return false;
403
+ }
246
404
  }
405
+
406
+ return true;
407
+ }
408
+
409
+ /**
410
+ * @param {Effect} effect
411
+ */
412
+ skip_effect(effect) {
413
+ this.#skipped_branches.add(effect);
247
414
  this.#unskipped_branches.delete(effect);
248
415
  }
249
416
 
250
417
  /**
251
- * Remove an effect from the #skipped_branches map and reschedule
252
- * any tracked dirty/maybe_dirty child effects
253
418
  * @param {Effect} effect
254
- * @param {(e: Effect) => void} callback
255
419
  */
256
- unskip_effect(effect, callback = (e) => this.schedule(e)) {
257
- var tracked = this.#skipped_branches.get(effect);
258
- if (tracked) {
259
- this.#skipped_branches.delete(effect);
260
-
261
- for (var e of tracked.d) {
262
- set_signal_status(e, DIRTY);
263
- callback(e);
264
- }
420
+ unskip_effect(effect) {
421
+ if (
422
+ this.#skipped_branches.delete(effect) ||
423
+ (!this.#unskipped_branches.has(effect) &&
424
+ ((effect.f & EFFECT_OFFSCREEN) !== 0 ||
425
+ this.folded.some((batch) => batch.#skipped_branches.has(effect))))
426
+ ) {
427
+ // This batch adopts a branch that it skipped (whose effects may have been reset, see `reset_branch`),
428
+ // that so far only existed offscreen (possibly for another batch, whose view of the world its
429
+ // effects ran in), or that a batch whose writes are part of its view skips (and so didn't run the
430
+ // effects that its writes affect, or reset them) — re-validate its effects in this batch's view
431
+ this.revalidate_branch(effect);
432
+ }
433
+
434
+ this.#unskipped_branches.add(effect);
435
+ }
265
436
 
266
- for (e of tracked.m) {
267
- set_signal_status(e, MAYBE_DIRTY);
268
- callback(e);
437
+ /**
438
+ * Like `unskip_effect`, for a branch that was just created offscreen while this batch is processed.
439
+ * Its effects ran in this batch's view of the world when they were created, so there's nothing to re-validate
440
+ * TODO can we skip revalidation in `unskip_effect` in more cases, by detecting whether things changed
441
+ * inside a branch while it was skipped?
442
+ * @param {Effect} effect
443
+ */
444
+ unskip_new_effect(effect) {
445
+ this.#unskipped_branches.add(effect);
446
+ }
447
+
448
+ /**
449
+ * @param {Effect} effect
450
+ */
451
+ revalidate_branch(effect) {
452
+ for (var e = effect.first; e !== null; e = e.next) {
453
+ var flags = e.f;
454
+
455
+ // (branches nested inside that exist offscreen for other batches only are not adopted)
456
+ if ((flags & (DESTROYED | INERT)) === 0 && !this.#skips(e)) {
457
+ if ((flags & (BRANCH_EFFECT | ROOT_EFFECT | EAGER_EFFECT)) === 0 && e.fn !== null) {
458
+ this.schedule(e, MAYBE_DIRTY);
459
+ }
460
+
461
+ this.revalidate_branch(e);
269
462
  }
270
463
  }
271
- this.#unskipped_branches.add(effect);
272
464
  }
273
465
 
274
466
  /**
@@ -320,18 +512,38 @@ export class Batch {
320
512
  }
321
513
 
322
514
  #process() {
515
+ current_batch = processing_batch = this;
516
+
517
+ // A different batch view may apply, even when processing continues within the same flush.
518
+ teardown_context?.derived_cache.clear();
519
+
520
+ if (async_mode_flag && this.started && last_processed !== this.id) {
521
+ // Since this batch last ran, reactions may have come to depend on its writes without it
522
+ // knowing (e.g. effects created by other batches), or have run in the view of other batches.
523
+ // Re-validate them in this batch's view — this only re-runs those that are out of date
524
+ this.#revalidate(this.current.keys());
525
+ }
526
+
323
527
  this.started = true;
528
+ last_processed = this.id;
529
+
530
+ // Deferred effects are rescheduled even if the batch still has pending work, because traversing the
531
+ // tree could make an if block that contains the last blocking pending effect falsy, causing the batch
532
+ // to no longer be deferred. If it still is, they are deferred again
533
+ if (this.#unprocessed.size > 0) {
534
+ for (const [e, status] of this.#unprocessed) this.#add(e, status);
535
+ this.#unprocessed.clear();
536
+ }
324
537
 
325
- // We always reschedule previously-deferred effects, not just when
326
- // #is_deferred() is true, because traversing the tree could make
327
- // an if block that contains the last blocking pending effect falsy,
328
- // causing the block to no longer be deferred.
329
- for (const [e, status] of this.#dirty_reactions) {
330
- set_signal_status(e, status);
331
- this.schedule(e);
538
+ if (DEV) {
539
+ // track all the values that were updated during this flush,
540
+ // so that they can be reset afterwards
541
+ for (const value of this.current.keys()) {
542
+ source_stacks.add(value);
543
+ }
332
544
  }
333
545
 
334
- this.apply();
546
+ this.activate();
335
547
 
336
548
  /** @type {Effect[]} */
337
549
  var effects = (collected_effects = []);
@@ -339,6 +551,9 @@ export class Batch {
339
551
  /** @type {Effect[]} */
340
552
  var render_effects = [];
341
553
 
554
+ /** @type {Boundary[]} */
555
+ var revealed_boundaries = [];
556
+
342
557
  /**
343
558
  * @type {Effect[]}
344
559
  * @deprecated when we get rid of legacy mode and stores, we can get rid of this
@@ -351,14 +566,14 @@ export class Batch {
351
566
  while (this.#scheduled.length > 0) {
352
567
  if (flush_count++ > 1000) {
353
568
  this.#unlink();
354
- infinite_loop_guard(); // TODO try to reset_all() here?
569
+ infinite_loop_guard(); // TODO try to reset the tree here?
355
570
  }
356
571
 
357
572
  for (const root of this.#resolve()) {
358
573
  try {
359
- this.#traverse(root, effects, render_effects);
574
+ this.#traverse(root, effects, render_effects, revealed_boundaries);
360
575
  } catch (e) {
361
- reset_all(root);
576
+ reset_branch(root, true);
362
577
  // If there's no async work left, this branch is now dead and needs
363
578
  // to be discarded to not become a zombie that is never cleaned up.
364
579
  // See https://github.com/sveltejs/svelte/issues/18221#issuecomment-4497918414
@@ -386,20 +601,48 @@ export class Batch {
386
601
  if (updates.length > 0) {
387
602
  var batch = Batch.ensure();
388
603
  for (const e of updates) {
389
- batch.schedule(e);
604
+ // these were marked during traversal already (see `mark_reactions`), unless they ran since
605
+ if ((e.f & CLEAN) === 0) batch.schedule(e, MAYBE_DIRTY);
390
606
  }
391
607
  }
392
608
 
393
609
  collected_effects = null;
394
610
  legacy_updates = null;
395
611
 
612
+ if (this.merge_requests.size > 0) {
613
+ const sorted = Array.from(this.merge_requests, merge_target)
614
+ .filter((batch) => batch !== this && batch.linked && !batch.is_fork)
615
+ .sort((a, b) => a.id - b.id);
616
+ this.merge_requests.clear();
617
+
618
+ if (sorted.length > 0) {
619
+ this.#defer_effects(render_effects);
620
+ this.#defer_effects(effects);
621
+
622
+ /** @type {Batch} */
623
+ var target = this;
624
+ var i = sorted.length;
625
+
626
+ while (i--) {
627
+ var earlier = sorted[i];
628
+ if (earlier === target) continue;
629
+ earlier.#merge(target);
630
+ target = earlier;
631
+ }
632
+
633
+ // Revalidate once all the writes and pending work belong to the same batch.
634
+ target.#process();
635
+ return;
636
+ }
637
+ }
638
+
396
639
  // if the batch has outstanding pending work, stash effects and bail
397
640
  if (this.#is_deferred()) {
398
641
  this.#defer_effects(render_effects);
399
642
  this.#defer_effects(effects);
400
643
 
401
- for (const [e, t] of this.#skipped_branches) {
402
- reset_branch(e, t);
644
+ for (const e of this.#skipped_branches) {
645
+ reset_branch(e);
403
646
  }
404
647
 
405
648
  if (updates.length > 0) {
@@ -417,53 +660,117 @@ export class Batch {
417
660
  this.#defer_effects(render_effects);
418
661
  this.#defer_effects(effects);
419
662
  earlier_batch.#merge(this);
663
+ earlier_batch.#process();
664
+
420
665
  return;
421
666
  }
422
667
 
423
- // clear effects. Those that are still needed will be rescheduled through unskipping the skipped branches.
424
- this.#dirty_reactions.clear();
668
+ for (const boundary of revealed_boundaries) {
669
+ // A later traversal may have restored an unresolved branch since this boundary was queued.
670
+ if (boundary.is_pending && boundary.is_ready(this)) {
671
+ boundary.reveal(effects);
672
+ }
673
+ }
674
+
675
+ // The results of this batch are about to become the real-world state
676
+ this.#release_records(true);
425
677
 
426
678
  // append/remove branches
427
- for (const fn of this.#commit_callbacks) fn(this);
428
- this.#commit_callbacks.clear();
679
+ this.#run_callbacks(this.#commit_callbacks);
429
680
 
430
- previous_batch = this;
431
- flush_queued_effects(render_effects);
432
- flush_queued_effects(effects);
433
- previous_batch = null;
681
+ var earlier_writes = flush_queued_effects(render_effects);
682
+
683
+ // the content has been updated, and user effects are about to see it
684
+ if (custom_renderers_flag && before_effects !== null) {
685
+ before_effects();
686
+ }
687
+
688
+ flush_queued_effects(effects, earlier_writes);
434
689
 
435
690
  this.#deferred?.resolve();
436
691
 
437
692
  var next_batch = /** @type {Batch | null} */ (/** @type {unknown} */ (current_batch));
438
693
 
439
- if (this.#pending === 0 && (this.#scheduled.length === 0 || next_batch !== null)) {
694
+ if (this.#pending.size === 0 && (this.#scheduled.length === 0 || next_batch !== null)) {
440
695
  this.#unlink();
696
+ }
441
697
 
442
- // Order matters here - we need to commit and THEN continue flushing new batches, not the other way around,
443
- // else we could start flushing a new batch and then, if it has pending work, rebase it right afterwards, which is wrong.
444
- // In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode
445
- // TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed
446
- if (async_mode_flag) {
447
- this.#commit();
448
- // Rebases can activate other batches or null it out, therefore restore the new one here
449
- current_batch = next_batch;
450
- }
698
+ // Order matters here - we need to commit and THEN continue flushing new batches, not the other way around,
699
+ // else we could start flushing a new batch and then, if it has pending work, rebase it right afterwards, which is wrong.
700
+ // In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode
701
+ // TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed
702
+ if (async_mode_flag) {
703
+ this.commit_writes();
451
704
  }
452
705
 
453
706
  if (next_batch !== null) {
454
- old_values.clear();
707
+ // The next batch holds the writes made while this one committed, which cause the teardowns that run
708
+ // when it's processed. So teardowns now revert those, and no longer this batch's: of the reverted
709
+ // values, keep those that are the next batch's values from before its writes. (Writes made in teardowns
710
+ // aren't among them, see `teardown_write`, so they stay visible)
711
+ if (teardown_context !== null) {
712
+ for (const [source, snapshot] of teardown_context.reverted_values) {
713
+ if (next_batch.previous.get(source)?.wv !== snapshot.wv) {
714
+ teardown_context.reverted_values.delete(source);
715
+ }
716
+ }
717
+ }
718
+
455
719
  next_batch.#process();
456
720
  }
457
721
  }
458
722
 
723
+ /**
724
+ * Schedule the reactions that (transitively) depend on `sources` for re-validation in this batch.
725
+ * They are marked MAYBE_DIRTY, which means that they are only re-run if the exact versions
726
+ * of their dependencies differ from the ones they last saw (in this batch's view of the world)
727
+ * @param {Iterable<Source>} sources
728
+ */
729
+ #revalidate(sources) {
730
+ // deriveds added during iteration are visited too, so this doubles as a worklist
731
+ /** @type {Set<Value>} */
732
+ var values = new Set(sources);
733
+
734
+ /** @type {Set<Effect>} */
735
+ var effects = new Set();
736
+
737
+ for (const value of values) {
738
+ var reactions = value.reactions;
739
+ if (reactions === null) continue;
740
+
741
+ for (const reaction of reactions) {
742
+ var flags = reaction.f;
743
+
744
+ if ((flags & DERIVED) !== 0) {
745
+ if ((flags & CLEAN) !== 0) set_signal_status(reaction, MAYBE_DIRTY);
746
+ values.add(/** @type {Derived} */ (reaction));
747
+ continue;
748
+ }
749
+
750
+ var effect = /** @type {Effect} */ (reaction);
751
+ if (effects.has(effect)) continue;
752
+ effects.add(effect);
753
+
754
+ if (
755
+ (flags & (EAGER_EFFECT | INERT | DESTROYED)) === 0 &&
756
+ // branches that this batch skips don't exist in its view of the world
757
+ !this.is_skipped(effect)
758
+ ) {
759
+ this.schedule(effect, MAYBE_DIRTY);
760
+ }
761
+ }
762
+ }
763
+ }
764
+
459
765
  /**
460
766
  * Traverse the effect tree, executing effects or stashing
461
767
  * them for later execution as appropriate
462
768
  * @param {Effect} root
463
769
  * @param {Effect[]} effects
464
770
  * @param {Effect[]} render_effects
771
+ * @param {Boundary[]} revealed_boundaries
465
772
  */
466
- #traverse(root, effects, render_effects) {
773
+ #traverse(root, effects, render_effects, revealed_boundaries) {
467
774
  root.f ^= CLEAN;
468
775
 
469
776
  var effect = root.first;
@@ -473,7 +780,9 @@ export class Batch {
473
780
  var is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
474
781
  var is_skippable_branch = is_branch && (flags & CLEAN) !== 0;
475
782
 
476
- var skip = is_skippable_branch || (flags & INERT) !== 0 || this.#skipped_branches.has(effect);
783
+ // (eager effects run in the real world, see `flush_eager_effects`, not in the view of the batch)
784
+ var skip =
785
+ is_skippable_branch || (flags & (INERT | EAGER_EFFECT)) !== 0 || this.#skips(effect);
477
786
 
478
787
  if (!skip && effect.fn !== null) {
479
788
  if (is_branch) {
@@ -483,7 +792,6 @@ export class Batch {
483
792
  } else if (async_mode_flag && (flags & (RENDER_EFFECT | MANAGED_EFFECT)) !== 0) {
484
793
  render_effects.push(effect);
485
794
  } else if (is_dirty(effect)) {
486
- if ((flags & BLOCK_EFFECT) !== 0) this.add_dirty_reaction(effect, MAYBE_DIRTY);
487
795
  update_effect(effect);
488
796
  }
489
797
 
@@ -496,6 +804,15 @@ export class Batch {
496
804
  }
497
805
 
498
806
  while (effect !== null) {
807
+ // if a pending boundary is now resolved, reveal it
808
+ if ((effect.f & (BOUNDARY_EFFECT | DESTROYED)) === BOUNDARY_EFFECT) {
809
+ var boundary = /** @type {Boundary} */ (effect.b);
810
+
811
+ if (boundary.is_pending && boundary.is_ready(this)) {
812
+ revealed_boundaries.push(boundary);
813
+ }
814
+ }
815
+
499
816
  var next = effect.next;
500
817
 
501
818
  if (next !== null) {
@@ -518,8 +835,7 @@ export class Batch {
518
835
 
519
836
  /** @param {Batch} batch */
520
837
  #intersects(batch) {
521
- for (const [source, [, is_derived]] of this.current) {
522
- if (is_derived) continue;
838
+ for (const source of this.current.keys()) {
523
839
  if (batch.current.has(source)) return true;
524
840
  }
525
841
 
@@ -527,73 +843,86 @@ export class Batch {
527
843
  }
528
844
 
529
845
  /**
846
+ * Take over the writes of a later batch that depends on this one, because it finished first
847
+ * or aborted one of this batch's runs.
848
+ * Values it produced (async results, deriveds) remain valid; block effects select their
849
+ * branches again for this batch, if needed (their selections are keyed by batch)
530
850
  * @param {Batch} batch
531
851
  */
532
852
  #merge(batch) {
533
- for (const [source, value] of batch.current) {
534
- if (!this.previous.has(source) && batch.previous.has(source)) {
535
- this.previous.set(source, batch.previous.get(source));
853
+ for (const target of batch.merge_requests) this.merge_requests.add(target);
854
+ batch.merge_requests.clear();
855
+
856
+ for (const [source, entry] of batch.current) {
857
+ if (!this.previous.has(source)) {
858
+ const previous = batch.previous.get(source);
859
+ if (previous) this.previous.set(source, previous);
536
860
  }
537
861
 
538
- this.current.set(source, value);
862
+ this.current.set(source, entry);
539
863
  }
540
864
 
541
865
  for (const [effect, deferred] of batch.async_deriveds) {
542
866
  const d = this.async_deriveds.get(effect);
543
- if (d) deferred.promise.then(d.resolve).catch(d.reject);
867
+ if (d && d !== deferred) deferred.promise.then(d.resolve, d.reject);
868
+ // The incoming run can still be pending. A subsequent replacement must reach
869
+ // this deferred too, not just the older waiters to which it forwards its result.
870
+ this.async_deriveds.set(effect, deferred);
871
+ }
872
+
873
+ for (const [reaction, record] of batch.records ?? []) {
874
+ if ((reaction.f & BLOCK_EFFECT) === 0) {
875
+ var replaced = this.records?.get(reaction);
876
+ (this.records ??= new Map()).set(reaction, record);
877
+
878
+ // the run moves to this batch
879
+ batch.records?.delete(reaction);
880
+
881
+ // (once it's replaced, as both batches may hold the same record, see `keep_global_run`)
882
+ abort_record(reaction, replaced);
883
+ }
544
884
  }
545
885
 
546
886
  // Clear them or else those that are still pending might get rejected on discard (after merged-into batch is done).
547
887
  // This can happen when batch Y merged into X and Y has a pending boundary and therefore still-pending async deriveds inside.
548
888
  batch.async_deriveds.clear();
549
889
 
550
- // Mark is not guaranteed not touch these, so we transfer them
551
- this.transfer_reactions(batch.#dirty_reactions);
552
-
553
- /**
554
- * mark all effects that depend on `batch.current`, except the
555
- * async effects that we just resolved (TODO unless they depend
556
- * on values in this batch that are NOT in the later batch?).
557
- * Through this we also will populate the correct #skipped_branches,
558
- * oncommit callbacks etc, so we don't need to merge them separately.
559
- * @param {Value} value
560
- */
561
- const mark = (value) => {
562
- var reactions = value.reactions;
563
- if (reactions === null) return;
564
- // skip if value is derived and is neither dirty nor maybe dirty. transitive
565
- // deriveds (a derived depending on another derived) are only MAYBE_DIRTY, so
566
- // we must continue traversing them to reach the effects that depend on them
567
- if ((value.f & DERIVED) !== 0 && (value.f & (DIRTY | MAYBE_DIRTY)) === 0) {
568
- return;
890
+ // That pending work is this batch's from now on: it decrements this batch's counts (see `increment_pending`),
891
+ // so this batch stays linked until the work is done, and receives the effects that a boundary defers until then
892
+ if (batch.#pending.size > 0) {
893
+ for (const [effect, count] of batch.#pending) {
894
+ this.#pending.set(effect, (this.#pending.get(effect) ?? 0) + count);
569
895
  }
570
896
 
571
- for (const reaction of reactions) {
572
- var flags = reaction.f;
573
-
574
- if ((flags & DERIVED) !== 0) {
575
- mark(/** @type {Derived} */ (reaction));
576
- } else {
577
- var effect = /** @type {Effect} */ (reaction);
897
+ batch.#pending.clear();
898
+ }
578
899
 
579
- if (flags & (ASYNC | BLOCK_EFFECT) && !this.async_deriveds.has(effect)) {
580
- this.#dirty_reactions.delete(effect);
581
- set_signal_status(effect, DIRTY);
582
- this.schedule(effect);
583
- }
584
- }
900
+ if (batch.#unprocessed.size > 0) {
901
+ for (const [effect, status] of batch.#unprocessed) {
902
+ this.#add_dirty_effect(effect, status);
585
903
  }
586
- };
587
904
 
588
- for (const source of this.current.keys()) {
589
- mark(source);
905
+ batch.#unprocessed.clear();
590
906
  }
591
907
 
592
- this.oncommit(() => batch.discard());
908
+ // What the merged batch did on its own (e.g. branches it selected) is obsolete once this batch is
909
+ // done — whether it commits or is discarded (e.g. because of an error)
910
+ const discard = () => batch.discard();
911
+ this.oncommit(discard);
912
+ this.ondiscard(discard);
913
+ batch.merged = this;
593
914
  batch.#unlink();
915
+ }
594
916
 
595
- current_batch = this;
596
- this.#process();
917
+ /**
918
+ * Note that `effect` needs to be (re-)validated, without downgrading a DIRTY effect to MAYBE_DIRTY
919
+ * @param {Effect} effect
920
+ * @param {number} status DIRTY or MAYBE_DIRTY
921
+ */
922
+ #add_dirty_effect(effect, status) {
923
+ if (status === DIRTY || this.#unprocessed.get(effect) !== DIRTY) {
924
+ this.#unprocessed.set(effect, status);
925
+ }
597
926
  }
598
927
 
599
928
  /**
@@ -601,59 +930,133 @@ export class Batch {
601
930
  */
602
931
  #defer_effects(effects) {
603
932
  for (var i = 0; i < effects.length; i += 1) {
604
- defer_effect(effects[i], this.#dirty_reactions);
933
+ var effect = effects[i];
934
+ var status = effect.f & (DIRTY | MAYBE_DIRTY);
935
+
936
+ if (status !== 0) {
937
+ this.#add_dirty_effect(effect, effect.dv === null ? MAYBE_DIRTY : status);
938
+
939
+ // mark as clean so they get scheduled if they depend on pending async state
940
+ set_signal_status(effect, CLEAN);
941
+ }
605
942
  }
606
943
  }
607
944
 
608
945
  /**
609
946
  * Associate a change to a given source with the current
610
- * batch, noting its previous and current values
947
+ * batch, noting its previous and current values (and versions).
948
+ * The source itself is only updated if this is its latest value, i.e. unless this
949
+ * is a fork (whose writes only exist in its own view of the world) or a later batch
950
+ * already wrote to it (e.g. because an async expression resolved in an earlier batch).
611
951
  * @param {Value} source
612
952
  * @param {any} value
613
- * @param {boolean} [is_derived]
953
+ * @param {boolean} same whether the value equals the real one (it can, if this batch sees another one, see
954
+ * `internal_set`) — in which case the source isn't updated, and the value gets the same version
955
+ * @param {boolean} [error] whether the value is an error (thrown when read, see `runtime.js#get`)
956
+ * @param {Effect[] | null} [updated_during_traversal]
614
957
  */
615
- capture(source, value, is_derived = false) {
616
- if (source.v !== UNINITIALIZED && !this.previous.has(source)) {
617
- this.previous.set(source, source.v);
958
+ capture(source, value, same, error = false, updated_during_traversal = null) {
959
+ var previous = this.previous.get(source);
960
+ var later = later_writer(this, source);
961
+
962
+ if (previous === undefined) {
963
+ // the value before this batch's change is the one before the later batch's change, if any
964
+ previous = later?.previous.get(source);
965
+
966
+ // (A first value has no value from before it, see `previous`. If the later batch's write is the first value,
967
+ // the value before this batch's write is taken to be that one: in the views of other batches and in
968
+ // teardowns, undoing this write then gives the real value, just like not undoing it would)
969
+ if (previous === undefined && source.v !== UNINITIALIZED) {
970
+ previous = {
971
+ v: source.v,
972
+ wv: source.wv,
973
+ e: (source.f & ERROR_VALUE) !== 0,
974
+ assigned: (source.f & ASSIGNED) !== 0
975
+ };
976
+ }
977
+
978
+ if (previous !== undefined) this.previous.set(source, previous);
618
979
  }
619
980
 
620
- // Don't save errors in `batch_values`, or they won't be thrown in `runtime.js#get`
621
- if ((source.f & ERROR_VALUE) === 0) {
622
- this.current.set(source, [value, is_derived]);
623
- batch_values?.set(source, value);
981
+ if (is_destroying_effect) {
982
+ teardown_write(source);
983
+ } else if (previous !== undefined) {
984
+ teardown_context?.reverted_values.set(source, previous);
985
+ teardown_context?.derived_cache.clear();
624
986
  }
625
987
 
626
- if (!this.is_fork) {
627
- source.v = value;
988
+ /** @type {BatchValue} */
989
+ var entry = {
990
+ v: value,
991
+ wv: same ? source.wv : increment_write_version(),
992
+ e: error,
993
+ // a write to a derived is an assignment
994
+ assigned: (source.f & DERIVED) !== 0,
995
+ async: (source.f & ASYNC) !== 0
996
+ };
997
+
998
+ this.current.set(source, entry);
999
+
1000
+ // The active view of the world sees writes made while it's active, even if they don't belong to the batch whose
1001
+ // view it is — e.g. those of effects that run while a batch commits, which go to a new batch. (Async results
1002
+ // are only captured while no view is active, see `async_derived`)
1003
+ batch_values?.set(source, entry);
1004
+
1005
+ // an assignment replaces the value of a derived that the active view of the world holds
1006
+ view_cache?.delete(/** @type {Derived} */ (source));
1007
+
1008
+ // in order, this batch's change comes before that of the later batch, which replaces it (this happens when a
1009
+ // result arrives in a batch that committed while it was pending, see `#move_to_front`)
1010
+ if (!this.is_fork && later !== null) later.previous.set(source, entry);
1011
+
1012
+ if (!this.is_fork && !same && later === null) {
1013
+ apply(source, entry);
628
1014
  }
629
- }
630
1015
 
631
- activate() {
632
- current_batch = this;
1016
+ // A value that equals the real one, with the same version, changes nothing that reactions
1017
+ // could read outside this batch's view — which is revalidated when the batch is processed
1018
+ if (!same) {
1019
+ seen = null;
1020
+ count_deps = 0;
1021
+ this.mark(source, DIRTY, updated_during_traversal);
1022
+ seen = null;
1023
+
1024
+ if (eager_effects.size > 0 && !eager_effects_deferred) {
1025
+ flush_eager_effects();
1026
+ }
1027
+ }
633
1028
  }
634
1029
 
635
1030
  deactivate() {
636
- current_batch = null;
637
- batch_values = null;
1031
+ current_batch = processing_batch = batch_values = view_cache = view_batch = null;
638
1032
  }
639
1033
 
640
1034
  flush() {
641
- try {
642
- is_processing = true;
643
- current_batch = this;
1035
+ // flushes can be nested, e.g. if an effect calls `flushSync`
1036
+ var context = push_teardown_context(this.previous);
644
1037
 
1038
+ try {
645
1039
  this.#process();
1040
+
1041
+ // (the size check avoids allocating an iterator in the common case)
1042
+ if (rebases.size > 0) {
1043
+ for (const batch of rebases) {
1044
+ rebases.delete(batch);
1045
+
1046
+ // the batch is processed again anyway if a flush is queued
1047
+ if (batch.linked && !batch.#decrement_queued) {
1048
+ batch.#process();
1049
+ }
1050
+ }
1051
+ }
646
1052
  } finally {
647
1053
  flush_count = 0;
648
1054
  last_scheduled_effect = null;
649
1055
  collected_effects = null;
650
1056
  legacy_updates = null;
651
- is_processing = false;
652
1057
 
653
- current_batch = null;
654
- batch_values = null;
655
-
656
- old_values.clear();
1058
+ teardown_context = context.parent;
1059
+ this.deactivate();
657
1060
 
658
1061
  if (DEV) {
659
1062
  for (const source of source_stacks) {
@@ -666,8 +1069,7 @@ export class Batch {
666
1069
  }
667
1070
 
668
1071
  discard() {
669
- for (const fn of this.#discard_callbacks) fn(this);
670
- this.#discard_callbacks.clear();
1072
+ this.#run_callbacks(this.#discard_callbacks);
671
1073
 
672
1074
  for (const deferred of this.async_deriveds.values()) {
673
1075
  deferred.reject(OBSOLETE);
@@ -677,34 +1079,29 @@ export class Batch {
677
1079
  this.#deferred?.resolve();
678
1080
  }
679
1081
 
680
- /**
681
- * @param {Effect} effect
682
- */
683
- register_created_effect(effect) {
684
- this.#new_effects.push(effect);
685
- }
686
-
687
1082
  #commit() {
688
1083
  // If there are other pending batches, they now need to be 'rebased' —
689
- // in other words, we re-run block/async effects with the newly
690
- // committed state, unless the batch in question has a more
691
- // recent value for a given source
1084
+ // in other words, their view of the world now includes the newly committed
1085
+ // state (unless the batch in question has a more recent value for a given source),
1086
+ // so everything that depends on it needs to be re-validated in their view
692
1087
  for (let batch = first_batch; batch !== null; batch = batch.next) {
1088
+ if (batch === this) continue;
1089
+
693
1090
  var is_earlier = batch.id < this.id;
694
1091
 
695
1092
  /** @type {Source[]} */
696
1093
  var sources = [];
697
1094
 
698
- for (const [source, [value, is_derived]] of this.current) {
699
- if (batch.current.has(source)) {
700
- var batch_value = /** @type {[any, boolean]} */ (batch.current.get(source))[0]; // faster than destructuring
1095
+ for (const [source, entry] of this.current) {
1096
+ var own = batch.current.get(source);
701
1097
 
702
- if (is_earlier && value !== batch_value) {
1098
+ if (own !== undefined) {
1099
+ if (is_earlier && entry.v !== own.v && !own.async) {
703
1100
  // bring the value up to date
704
- batch.current.set(source, [value, is_derived]);
1101
+ batch.current.set(source, entry);
705
1102
  } else {
706
- // same value or later batch has more recent value,
707
- // no need to re-run these effects
1103
+ // same value, later batch has more recent value, or the batch's own result
1104
+ // of an async expression — no need to re-run these effects
708
1105
  continue;
709
1106
  }
710
1107
  }
@@ -712,30 +1109,21 @@ export class Batch {
712
1109
  sources.push(source);
713
1110
  }
714
1111
 
715
- if (is_earlier) {
716
- // TODO do we need to restart these in some cases, instead of
717
- // immediately resolving them? Likely not because of how this.apply() works.
718
- for (const [effect, deferred] of this.async_deriveds) {
719
- const d = batch.async_deriveds.get(effect);
720
- if (d) deferred.promise.then(d.resolve).catch(d.reject);
721
- }
722
- }
723
-
724
- var current = [...batch.current.keys()].filter(
725
- (source) => !(/** @type {[any, boolean]} */ (batch.current.get(source))[1])
726
- );
727
-
728
1112
  // If not started yet or no sources to update (which is e.g. possible for the very first batch) then bail
729
- if (!batch.started || current.length === 0) continue;
1113
+ if (!batch.started || batch.current.size === 0) continue;
730
1114
 
731
- // Re-run async/block effects that depend on distinct values changed in both batches (ignoring deriveds)
732
- var others = current.filter((source) => !this.current.has(source));
1115
+ var obsolete = true;
733
1116
 
734
- if (others.length === 0) {
735
- if (is_earlier) {
736
- // this batch is now obsolete and can be discarded
737
- batch.discard();
1117
+ for (const source of batch.current.keys()) {
1118
+ if (!this.current.has(source)) {
1119
+ obsolete = false;
1120
+ break;
738
1121
  }
1122
+ }
1123
+
1124
+ if (obsolete && is_earlier) {
1125
+ // this batch is now obsolete and can be discarded
1126
+ batch.discard();
739
1127
  } else if (sources.length > 0) {
740
1128
  // The microtask queue can contain the batch already scheduled to run right
741
1129
  // after this one is finished, so throwing the invariant would be wrong here.
@@ -743,100 +1131,49 @@ export class Batch {
743
1131
  invariant(batch.#scheduled.length === 0, 'Batch has scheduled effects');
744
1132
  }
745
1133
 
746
- // A batch was unskipped in a later batch -> tell prior batches to unskip it, too
747
- if (is_earlier) {
748
- for (const unskipped of this.#unskipped_branches) {
749
- batch.unskip_effect(unskipped, (e) => {
750
- if ((e.f & (BLOCK_EFFECT | ASYNC)) !== 0) {
751
- batch.schedule(e);
752
- } else {
753
- batch.#defer_effects([e]);
754
- }
755
- });
756
- }
757
- }
758
-
759
- batch.activate();
760
-
761
- /** @type {Set<Value>} */
762
- var marked = new Set();
763
-
764
- /** @type {Map<Reaction, boolean>} */
765
- var checked = new Map();
766
-
767
- for (var source of sources) {
768
- mark_effects(source, others, marked, checked);
769
- }
770
-
771
- checked = new Map();
772
- var current_unequal = [...batch.current]
773
- .filter(([c, v1]) => {
774
- const v2 = this.current.get(c);
775
- if (!v2) return true;
776
- // Either their values are different or one is a derived but not the other
777
- return v2[0] !== v1[0] || v2[1] !== v1[1];
778
- })
779
- .map(([c]) => c);
780
-
781
- if (current_unequal.length > 0) {
782
- for (const effect of this.#new_effects) {
783
- if (
784
- (effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 &&
785
- depends_on(effect, current_unequal, checked)
786
- ) {
787
- if ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) {
788
- set_signal_status(effect, DIRTY);
789
- batch.schedule(effect);
790
- } else {
791
- batch.add_dirty_reaction(effect, DIRTY);
792
- }
793
- }
794
- }
795
- }
796
-
797
- // Only apply and traverse when we know we triggered async work with marking the effects
798
- // and know this won't run anyway right afterwards
799
- if (batch.#scheduled.length > 0 && !batch.#decrement_queued) {
800
- batch.apply();
801
-
802
- for (var root of batch.#resolve()) {
803
- batch.#traverse(root, [], []);
804
- }
805
- }
806
-
807
- batch.deactivate();
1134
+ // Everything that depends on the committed values needs to be re-validated in the
1135
+ // batch's view. The batch is processed again once the current flush is done (which
1136
+ // also re-validates what depends on its own writes, as the committed batch may have
1137
+ // created reactions that read them), so that block effects select their branches
1138
+ // and async work restarts in the new view right away
1139
+ batch.#revalidate(sources);
1140
+ rebases.add(batch);
808
1141
  }
809
1142
  }
1143
+
1144
+ // The writes are part of the real world now. A batch that is still linked (because of pending work)
1145
+ // only has writes again once that work resolves, which it then commits
1146
+ this.current.clear();
1147
+ this.previous.clear();
810
1148
  }
811
1149
 
812
1150
  /**
813
- * @param {boolean} blocking
814
- * @param {Effect} effect
1151
+ * Make this batch's writes the real world, part of every other batch's view (see `#commit`).
1152
+ * If it has pending work it stays linked, coming first from now on (see `#move_to_front`)
815
1153
  */
816
- increment(blocking, effect) {
817
- this.#pending += 1;
818
-
819
- if (blocking) {
820
- let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;
821
- this.#blocking_pending.set(effect, blocking_pending_count + 1);
822
- }
1154
+ commit_writes() {
1155
+ this.#commit();
1156
+ if (this.linked && this.prev !== null) this.#move_to_front();
823
1157
  }
824
1158
 
825
1159
  /**
826
- * @param {boolean} blocking
827
1160
  * @param {Effect} effect
828
1161
  */
829
- decrement(blocking, effect) {
830
- this.#pending -= 1;
1162
+ increment(effect) {
1163
+ var count = this.#pending.get(effect) ?? 0;
1164
+ this.#pending.set(effect, count + 1);
1165
+ }
831
1166
 
832
- if (blocking) {
833
- let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;
1167
+ /**
1168
+ * @param {Effect} effect
1169
+ */
1170
+ decrement(effect) {
1171
+ var count = this.#pending.get(effect) ?? 0;
834
1172
 
835
- if (blocking_pending_count === 1) {
836
- this.#blocking_pending.delete(effect);
837
- } else {
838
- this.#blocking_pending.set(effect, blocking_pending_count - 1);
839
- }
1173
+ if (count === 1) {
1174
+ this.#pending.delete(effect);
1175
+ } else {
1176
+ this.#pending.set(effect, count - 1);
840
1177
  }
841
1178
 
842
1179
  if (this.#decrement_queued) return;
@@ -851,35 +1188,48 @@ export class Batch {
851
1188
  });
852
1189
  }
853
1190
 
854
- /**
855
- * @param {Map<Effect, number>} dirty_reactions
856
- */
857
- transfer_reactions(dirty_reactions) {
858
- for (const [effect, status] of dirty_reactions) {
859
- this.add_dirty_reaction(effect, status);
860
- }
1191
+ /** @param {(batch: Batch) => void} fn */
1192
+ oncommit(fn) {
1193
+ this.#commit_callbacks.set(fn, eager_block_writes?.size ? eager_block_writes : null);
1194
+ }
861
1195
 
862
- dirty_reactions.clear();
1196
+ /** @param {(batch: Batch) => void} fn */
1197
+ ondiscard(fn) {
1198
+ this.#discard_callbacks.set(fn, eager_block_writes?.size ? eager_block_writes : null);
863
1199
  }
864
1200
 
865
1201
  /**
866
- * @param {Effect} effect
867
- * @param {number} status
1202
+ * Runs the commit/discard callbacks.
1203
+ * A callback that was added while block effects re-ran eagerly detaches the branches that such a run
1204
+ * deselected (see `flush_queued_effects`). The teardowns it causes see the writes that applied in the
1205
+ * run's view, like they would have during the run: of the values that the current teardown context
1206
+ * reverts, the writes of the effects that ran before the one whose writes caused the run are restored.
1207
+ * Callbacks run untracked, because a batch can commit while an effect runs (e.g. one that calls `flushSync`)
1208
+ * @param {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>} callbacks
868
1209
  */
869
- add_dirty_reaction(effect, status) {
870
- if (status === DIRTY || this.#dirty_reactions.get(effect) !== DIRTY) {
871
- this.#dirty_reactions.set(effect, status);
872
- }
873
- }
1210
+ #run_callbacks(callbacks) {
1211
+ untrack(() => {
1212
+ for (const [fn, writes] of callbacks) {
1213
+ if (writes === null) {
1214
+ fn(this);
1215
+ continue;
1216
+ }
874
1217
 
875
- /** @param {(batch: Batch) => void} fn */
876
- oncommit(fn) {
877
- this.#commit_callbacks.add(fn);
878
- }
1218
+ var context = push_teardown_context();
879
1219
 
880
- /** @param {(batch: Batch) => void} fn */
881
- ondiscard(fn) {
882
- this.#discard_callbacks.add(fn);
1220
+ for (const [source, write] of writes) {
1221
+ if (context.reverted_values.has(source)) context.reverted_values.set(source, write);
1222
+ }
1223
+
1224
+ try {
1225
+ fn(this);
1226
+ } finally {
1227
+ teardown_context = context.parent;
1228
+ }
1229
+ }
1230
+ });
1231
+
1232
+ callbacks.clear();
883
1233
  }
884
1234
 
885
1235
  settled() {
@@ -890,7 +1240,7 @@ export class Batch {
890
1240
  if (current_batch === null) {
891
1241
  const batch = (current_batch = new Batch());
892
1242
 
893
- if (!is_processing && !is_flushing_sync) {
1243
+ if (processing_batch === null && !is_flushing_sync) {
894
1244
  queue_micro_task(() => {
895
1245
  if (!batch.started) {
896
1246
  batch.flush();
@@ -902,18 +1252,34 @@ export class Batch {
902
1252
  return current_batch;
903
1253
  }
904
1254
 
905
- apply() {
906
- if (!async_mode_flag || (!this.is_fork && this.prev === null && this.next === null)) {
907
- batch_values = null;
1255
+ /**
1256
+ * Make this the current batch, and its view of the world the active one
1257
+ */
1258
+ activate() {
1259
+ current_batch = this;
1260
+ view_batch = this;
1261
+
1262
+ // Async continuations can create or run reactions in another batch's view without
1263
+ // processing it. The next flush must re-validate those reactions in its own view.
1264
+ if (last_processed !== this.id) last_processed = null;
1265
+
1266
+ if (!async_mode_flag) {
1267
+ batch_values = view_cache = null;
1268
+ return;
1269
+ }
1270
+
1271
+ this.folded = [];
1272
+
1273
+ if (!this.is_fork && this.prev === null && this.next === null) {
1274
+ // this batch's view is the real world
1275
+ batch_values = view_cache = null;
908
1276
  return;
909
1277
  }
910
1278
 
911
1279
  // if there are multiple batches, we are 'time travelling' —
912
1280
  // we need to override values with the ones in this batch...
913
- batch_values = new Map();
914
- for (const [source, [value]] of this.current) {
915
- batch_values.set(source, value);
916
- }
1281
+ batch_values = new Map(this.current);
1282
+ view_cache = new Map();
917
1283
 
918
1284
  // ...and undo changes belonging to other batches unless they intersect
919
1285
  for (let batch = first_batch; batch !== null; batch = batch.next) {
@@ -924,9 +1290,16 @@ export class Batch {
924
1290
  // effects of the earlier batch in case they are merged.
925
1291
  // As a result you can think of batch_values as having the latest values of all intersecting
926
1292
  // batches up until this batch.
927
- if (batch.id >= this.id || !batch.#intersects(this)) {
1293
+ if (batch.id < this.id && batch.#intersects(this)) {
1294
+ this.folded.push(batch);
1295
+ } else {
928
1296
  for (const [source, previous] of batch.previous) {
929
- if (!batch_values.has(source)) {
1297
+ // (where the views agree on the value, the real one — and its version — applies. Not for an
1298
+ // assigned derived: its value before may have been computed in another view, see `get_view`)
1299
+ if (
1300
+ !batch_values.has(source) &&
1301
+ ((source.f & DERIVED) !== 0 || !source.equals(previous.v))
1302
+ ) {
930
1303
  batch_values.set(source, previous);
931
1304
  }
932
1305
  }
@@ -935,26 +1308,212 @@ export class Batch {
935
1308
  }
936
1309
 
937
1310
  /**
938
- *
1311
+ * The record of `reaction` in this batch's view of the world, i.e. that of this batch
1312
+ * or of the (earlier) batches whose changes it includes, if any
1313
+ * @param {Reaction} reaction
1314
+ * @returns {BatchRecord | undefined}
1315
+ */
1316
+ get_record(reaction) {
1317
+ var record = this.records?.get(reaction);
1318
+ var i = this.folded.length;
1319
+
1320
+ while (record === undefined && i--) {
1321
+ record = this.folded[i].records?.get(reaction);
1322
+ }
1323
+
1324
+ return record;
1325
+ }
1326
+
1327
+ /**
1328
+ * @param {Value} signal
1329
+ * @param {number} status should be DIRTY or MAYBE_DIRTY
1330
+ * @param {Effect[] | null} [updated_during_traversal]
1331
+ * @returns {void}
1332
+ */
1333
+ mark(signal, status, updated_during_traversal = null) {
1334
+ var reactions = signal.reactions;
1335
+ if (reactions === null) return;
1336
+
1337
+ var runes = is_runes();
1338
+ var length = reactions.length;
1339
+
1340
+ count_deps += length;
1341
+ // Activate the `seen` Set if we think from the unusually high number of deps that
1342
+ // there might be cycles in the graph, to avoid repeated lookups for reactions
1343
+ // Example: https://github.com/sveltejs/svelte/issues/16658 has a graph with one source
1344
+ // reaching ~10000 distinct deriveds/effects each, resulting in 65 million walks through repeated visits.
1345
+ if (count_deps > 100000 && seen === null) seen = new Set();
1346
+
1347
+ if (seen !== null) {
1348
+ if (seen.has(signal)) return;
1349
+ seen.add(signal);
1350
+ }
1351
+
1352
+ for (var i = 0; i < length; i++) {
1353
+ var reaction = reactions[i];
1354
+ var flags = reaction.f;
1355
+
1356
+ // In legacy mode, skip the current effect to prevent infinite loops
1357
+ if (!runes && reaction === active_effect) continue;
1358
+
1359
+ var not_dirty = (flags & DIRTY) === 0;
1360
+
1361
+ if ((flags & EAGER_EFFECT) !== 0) {
1362
+ if (!this.is_fork) {
1363
+ // don't set a DIRTY reaction to MAYBE_DIRTY
1364
+ if (not_dirty) {
1365
+ set_signal_status(reaction, status);
1366
+ }
1367
+
1368
+ // Eager effects need to run immediately:
1369
+ // - for $inspect so that the stack trace makes sense
1370
+ // - for $state.eager because they might be without an effect parent
1371
+ eager_effects.add(/** @type {Effect} */ (reaction));
1372
+ }
1373
+ } else if ((flags & DERIVED) !== 0) {
1374
+ // don't set a DIRTY reaction to MAYBE_DIRTY
1375
+ if (not_dirty) {
1376
+ set_signal_status(reaction, status);
1377
+ }
1378
+
1379
+ var derived = /** @type {Derived} */ (reaction);
1380
+
1381
+ view_cache?.delete(derived);
1382
+ this.mark(derived, MAYBE_DIRTY, updated_during_traversal);
1383
+ } else if (not_dirty) {
1384
+ var effect = /** @type {Effect} */ (reaction);
1385
+
1386
+ if ((flags & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {
1387
+ // these run right away to find out which branches the rest of the flush must skip
1388
+ // (see `flush_queued_effects`); the DOM changes when this batch commits
1389
+ set_signal_status(effect, status);
1390
+ eager_block_effects.add(effect);
1391
+ }
1392
+
1393
+ if (updated_during_traversal !== null) {
1394
+ set_signal_status(effect, status);
1395
+ updated_during_traversal.push(effect);
1396
+ } else {
1397
+ // the status is applied when the batch is processed
1398
+ this.schedule(effect, status);
1399
+ }
1400
+ }
1401
+ }
1402
+ }
1403
+
1404
+ /**
1405
+ * Schedule `effect` to be (re-)validated when this batch is processed. Its status only applies right
1406
+ * away if this is the batch that the current flush processes (next), or if a reaction is running (which
1407
+ * may have read what changed). Otherwise, whether an effect is dirty depends on this batch's view of the
1408
+ * world, so other batches (which may be processed first) mustn't see it: it is kept with this batch until
1409
+ * it is processed, and then checked against the exact versions of its dependencies (i.e. MAYBE_DIRTY)
939
1410
  * @param {Effect} effect
1411
+ * @param {number} status DIRTY or MAYBE_DIRTY
940
1412
  */
941
- schedule(effect) {
1413
+ schedule(effect, status) {
942
1414
  last_scheduled_effect = effect;
943
1415
 
944
- // defer render effects inside a pending boundary
945
- // TODO the `REACTION_RAN` check is only necessary because of legacy `$:` effects AFAICT — we can remove later
946
- if (
947
- effect.b?.is_pending &&
948
- (effect.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 &&
949
- (effect.f & REACTION_RAN) === 0
950
- ) {
951
- effect.b.defer_effect(effect);
1416
+ // While another batch is committed, effects that this batch's writes affect (other than the one
1417
+ // that is running, i.e. writing) wait for it to be processed, rather than running as part of that commit.
1418
+ // They may still run as part of it (for that batch's reasons) and see the write, so versions decide — unless
1419
+ // the effect is running, in which case it would record the version it didn't see (see `update_dependencies`)
1420
+ if (view_batch !== null && view_batch !== this && effect !== active_reaction) {
1421
+ this.#add_dirty_effect(
1422
+ effect,
1423
+ (effect.f & REACTION_IS_UPDATING) !== 0 ? status : MAYBE_DIRTY
1424
+ );
952
1425
  return;
953
1426
  }
954
1427
 
1428
+ if (processing_batch !== this && active_reaction === null) {
1429
+ if (this.prev !== null || this.next !== null || this.is_fork) {
1430
+ this.#add_dirty_effect(effect, MAYBE_DIRTY);
1431
+ return;
1432
+ }
1433
+
1434
+ status = MAYBE_DIRTY;
1435
+ }
1436
+
1437
+ this.#add(effect, status);
1438
+ }
1439
+
1440
+ /**
1441
+ * @param {Effect} effect
1442
+ * @param {number} status
1443
+ */
1444
+ #add(effect, status) {
1445
+ // don't set a DIRTY effect to MAYBE_DIRTY
1446
+ if ((effect.f & DIRTY) === 0) {
1447
+ set_signal_status(effect, status);
1448
+ }
1449
+
955
1450
  this.#scheduled.push(effect);
956
1451
  }
957
1452
 
1453
+ /** @param {boolean} commit whether the effects' runs become global state */
1454
+ #release_records(commit = false) {
1455
+ var records = this.records;
1456
+ if (records === null) return;
1457
+
1458
+ // Release ownership before pruning. Merged runs are retained by the receiving batch
1459
+ this.records = null;
1460
+ for (const [reaction, record] of records) {
1461
+ // A derived's record is a run in this batch's view: it is only the real-world value if its
1462
+ // dependencies still hold what it read, which is checked where a record is promoted on read
1463
+ // (see `update_derived`) and cannot be checked here. So it is dropped rather than promoted,
1464
+ // and its edges are left for its next global run to prune (see `prune_edges`). A destroyed
1465
+ // reaction has nothing left to update either
1466
+ if ((reaction.f & (DERIVED | DESTROYED)) === 0) {
1467
+ // Keep a newer committed async run instead of promoting an outdated record.
1468
+ // Otherwise, the effect would rerun and restart its async work in every batch.
1469
+ var replaced = (reaction.f & ASYNC) !== 0 && is_outdated(record) && !is_outdated(reaction);
1470
+
1471
+ if (commit && !replaced) {
1472
+ promote_record(reaction, record);
1473
+
1474
+ // The committed run is now what applies in the view of every batch without a run of the async
1475
+ // effect of its own (typically because the batch committed while its run was pending, inside a
1476
+ // pending boundary). Their in-flight runs are superseded: their results would overwrite this one
1477
+ // TODO feels pretty hacky and indication of an X-Y problem: This only works because !b.records?.has(reaction)
1478
+ // means "this would re-use the real world result, i.e. the one we just committed, so we can reject this old run".
1479
+ // This can reject runs too early in pending batches. The superseding batch eventually settles them,
1480
+ // but async/if blocks inside pending boundaries should be excluded.
1481
+ if ((reaction.f & ASYNC) !== 0) {
1482
+ for (let b = first_batch; b !== null; b = b.next) {
1483
+ if (b !== this && !b.records?.has(reaction)) {
1484
+ b.async_deriveds.get(/** @type {Effect} */ (reaction))?.reject(OBSOLETE);
1485
+ }
1486
+ }
1487
+ }
1488
+ }
1489
+
1490
+ prune_edges(reaction);
1491
+ }
1492
+
1493
+ // abort this run - if it was promoted to global, or another batch holds it, too, this is a noop
1494
+ abort_record(reaction, record);
1495
+ }
1496
+ }
1497
+
1498
+ /**
1499
+ * A batch that committed while work inside a pending boundary was in flight stays linked, so that the results
1500
+ * arrive in it. Its writes are the real world now, part of every other batch's view, so it comes first from now
1501
+ * on: This ensures logic about who sees what values in intersects/merge/etc work correctly.
1502
+ */
1503
+ #move_to_front() {
1504
+ var prev = /** @type {Batch} */ (this.prev);
1505
+ var first = /** @type {Batch} */ (first_batch);
1506
+
1507
+ prev.next = this.next;
1508
+ if (this.next === null) last_batch = prev;
1509
+ else this.next.prev = prev;
1510
+
1511
+ this.prev = null;
1512
+ this.next = first;
1513
+ first.prev = first_batch = this;
1514
+ this.id = first.id - 1;
1515
+ }
1516
+
958
1517
  #unlink() {
959
1518
  // #merge calls #unlink, discard later on does it again - prevent
960
1519
  // running it multiple times to not corrupt the linked list
@@ -976,10 +1535,26 @@ export class Batch {
976
1535
  }
977
1536
 
978
1537
  this.linked = false;
1538
+ this.#release_records();
979
1539
  }
980
1540
  }
981
1541
 
982
1542
  // TODO Svelte@6 think about removing the callback argument.
1543
+ /**
1544
+ * Called each time a batch has updated the content, before its user effects run, if set. Custom renderers
1545
+ * use this to keep the content of crossings that share a container in the order of their host nodes
1546
+ * (see `custom-renderer/containers.js`), so that effects never see them in a stale order
1547
+ * @type {(() => void) | null}
1548
+ */
1549
+ let before_effects = null;
1550
+
1551
+ /**
1552
+ * @param {(() => void) | null} fn
1553
+ */
1554
+ export function set_before_effects(fn) {
1555
+ before_effects = fn;
1556
+ }
1557
+
983
1558
  /**
984
1559
  * Synchronously flush any pending updates.
985
1560
  * Returns void if no callback is provided, otherwise returns the result of calling the callback.
@@ -989,8 +1564,8 @@ export class Batch {
989
1564
  */
990
1565
  export function flushSync(fn) {
991
1566
  var was_flushing_sync = is_flushing_sync;
992
- var prev_previous_batch = previous_batch;
993
- previous_batch = null;
1567
+ // e.g. flushSync during effect flushing phase - we gotta restore the view_batch afterwards in that case
1568
+ var previous_view_batch = view_batch !== current_batch ? view_batch : null;
994
1569
  is_flushing_sync = true;
995
1570
 
996
1571
  try {
@@ -1013,7 +1588,7 @@ export function flushSync(fn) {
1013
1588
  }
1014
1589
  } finally {
1015
1590
  is_flushing_sync = was_flushing_sync;
1016
- previous_batch = prev_previous_batch;
1591
+ view_batch = previous_view_batch;
1017
1592
  }
1018
1593
  }
1019
1594
 
@@ -1060,21 +1635,64 @@ function infinite_loop_guard() {
1060
1635
  export let eager_block_effects = null;
1061
1636
 
1062
1637
  /**
1638
+ * While block effects re-run eagerly (see `flush_queued_effects`), the writes of the effects that ran before the one
1639
+ * whose writes caused the re-runs, which apply in their view (possibly none). `null` otherwise. The branches that
1640
+ * these runs select/unskip are only appended (and those they skip detached) when the batch with the writes commits
1641
+ * (see `should_defer_append`), and the teardowns that this causes see these writes, too (see `#run_callbacks`)
1642
+ * @type {Map<Value, BatchValue> | null}
1643
+ */
1644
+ export let eager_block_writes = null;
1645
+
1646
+ /**
1647
+ * An effect (as opposed to a render effect, which keeps the offscreen content up to date) inside a boundary
1648
+ * that is still pending doesn't run when the batch commits. The boundary keeps it until it is revealed,
1649
+ * and hands it to the batch that reveals it (see `Boundary#reveal`)
1650
+ * TODO I feel like there's probably a less roundabout way to achieve this
1651
+ * @param {Effect} effect
1652
+ * @returns {boolean} whether the effect was deferred
1653
+ */
1654
+ function defer_if_pending(effect) {
1655
+ // A boundary is only pending while its content is new, so an effect that
1656
+ // has run before can't be inside one, and we can skip the lookup
1657
+ if ((effect.f & (EFFECT | REACTION_RAN)) !== EFFECT) return false;
1658
+
1659
+ for (var boundary = effect.b; boundary !== null; boundary = boundary.parent) {
1660
+ if (boundary.is_pending) {
1661
+ boundary.defer_effect(effect);
1662
+ return true;
1663
+ }
1664
+ }
1665
+
1666
+ return false;
1667
+ }
1668
+
1669
+ /**
1670
+ * `earlier_writes` includes writes from the pre-effect phase. Eager block teardowns
1671
+ * revert the running effect's writes, but not these earlier writes.
1063
1672
  * @param {Array<Effect>} effects
1064
- * @returns {void}
1673
+ * @param {Map<Value, BatchValue> | null} [earlier_writes]
1674
+ * @returns {Map<Value, BatchValue> | null}
1065
1675
  */
1066
- function flush_queued_effects(effects) {
1676
+ function flush_queued_effects(effects, earlier_writes = null) {
1067
1677
  var length = effects.length;
1068
- if (length === 0) return;
1678
+ if (length === 0) return earlier_writes;
1069
1679
 
1070
1680
  var i = 0;
1071
1681
 
1072
1682
  while (i < length) {
1073
1683
  var effect = effects[i++];
1074
1684
 
1075
- if ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) {
1685
+ if (
1686
+ (effect.f & (DESTROYED | INERT)) === 0 &&
1687
+ // don't run if already marked for destruction in the next batch
1688
+ // (this can happen if an effect writes a value which e.g. makes an if block falsy)
1689
+ !current_batch?.is_skipped(effect) &&
1690
+ !defer_if_pending(effect) &&
1691
+ is_dirty(effect)
1692
+ ) {
1076
1693
  eager_block_effects = new Set();
1077
1694
 
1695
+ var version = write_version;
1078
1696
  update_effect(effect);
1079
1697
 
1080
1698
  // Effects with no dependencies or teardown do not get added to the effect tree.
@@ -1083,7 +1701,7 @@ function flush_queued_effects(effects) {
1083
1701
  // here (rather than in `update_effect`) allows us to skip the work for
1084
1702
  // immediate effects.
1085
1703
  if (
1086
- effect.deps === null &&
1704
+ effect.edges === null &&
1087
1705
  effect.first === null &&
1088
1706
  effect.nodes === null &&
1089
1707
  effect.teardown === null &&
@@ -1096,126 +1714,96 @@ function flush_queued_effects(effects) {
1096
1714
  // If update_effect() has a flushSync() in it, we may have flushed another flush_queued_effects(),
1097
1715
  // which already handled this logic and did set eager_block_effects to null.
1098
1716
  if (eager_block_effects?.size > 0) {
1099
- old_values.clear();
1100
-
1101
- for (const e of eager_block_effects) {
1102
- // Skip eager effects that have already been unmounted
1103
- if ((e.f & (DESTROYED | INERT)) !== 0) continue;
1104
-
1105
- // Run effects in order from ancestor to descendant, else we could run into nullpointers
1106
- /** @type {Effect[]} */
1107
- const ordered_effects = [e];
1108
- let ancestor = e.parent;
1109
- while (ancestor !== null) {
1110
- if (eager_block_effects.has(ancestor)) {
1111
- eager_block_effects.delete(ancestor);
1112
- ordered_effects.push(ancestor);
1717
+ // these run because of the writes of the effect, so their teardowns revert those
1718
+ var previous_teardown_context = teardown_context;
1719
+
1720
+ // if state was written by an effect before the one that caused the eager
1721
+ // block rerun, its writes apply in this view. Deriveds must be evaluated
1722
+ // afresh rather than reusing results cached before those writes.
1723
+ if (earlier_writes !== null) push_teardown_context(earlier_writes);
1724
+
1725
+ // (a copy, as `earlier_writes` grows while the flush continues)
1726
+ var previous_eager_block_writes = eager_block_writes;
1727
+ eager_block_writes = new Map(earlier_writes);
1728
+
1729
+ try {
1730
+ for (const e of eager_block_effects) {
1731
+ // Skip eager effects that have already been unmounted, or that are inside a
1732
+ // branch that an earlier eager run (e.g. of an ancestor block) skips
1733
+ if ((e.f & (DESTROYED | INERT)) !== 0 || current_batch?.is_skipped(e)) continue;
1734
+
1735
+ // Run effects in order from ancestor to descendant, else we could run into nullpointers
1736
+ /** @type {Effect[]} */
1737
+ const ordered_effects = [e];
1738
+ let ancestor = e.parent;
1739
+ while (ancestor !== null) {
1740
+ if (eager_block_effects.has(ancestor)) {
1741
+ eager_block_effects.delete(ancestor);
1742
+ ordered_effects.push(ancestor);
1743
+ }
1744
+ ancestor = ancestor.parent;
1113
1745
  }
1114
- ancestor = ancestor.parent;
1115
- }
1116
1746
 
1117
- for (let j = ordered_effects.length - 1; j >= 0; j--) {
1118
- const e = ordered_effects[j];
1119
- // Skip eager effects that have already been unmounted
1120
- if ((e.f & (DESTROYED | INERT)) !== 0) continue;
1121
- update_effect(e);
1747
+ for (let j = ordered_effects.length - 1; j >= 0; j--) {
1748
+ const e = ordered_effects[j];
1749
+ // a block run may have skipped/destroyed the branch that a later one is in
1750
+ if ((e.f & (DESTROYED | INERT)) !== 0 || current_batch?.is_skipped(e)) continue;
1751
+ update_effect(e);
1752
+ }
1122
1753
  }
1754
+ } finally {
1755
+ eager_block_writes = previous_eager_block_writes;
1756
+ eager_block_effects?.clear();
1757
+ teardown_context = previous_teardown_context;
1123
1758
  }
1759
+ }
1124
1760
 
1125
- eager_block_effects.clear();
1761
+ // if the effect — or the block effects — wrote anything
1762
+ if (write_version !== version && current_batch !== null) {
1763
+ for (const [value, write] of current_batch.current) {
1764
+ if (write.wv > version) {
1765
+ (earlier_writes ??= new Map()).set(value, write);
1766
+ }
1767
+ }
1126
1768
  }
1127
1769
  }
1128
1770
  }
1129
1771
 
1130
1772
  eager_block_effects = null;
1773
+ return earlier_writes;
1131
1774
  }
1132
1775
 
1133
1776
  /**
1134
- * This is similar to `mark_reactions`, but it only marks async/block effects
1135
- * depending on `value` and at least one of the other `sources`, so that
1136
- * these effects can re-run after another batch has been committed
1137
- * @param {Value} value
1138
- * @param {Source[]} sources
1139
- * @param {Set<Value>} marked
1140
- * @param {Map<Reaction, boolean>} checked
1141
- */
1142
- function mark_effects(value, sources, marked, checked) {
1143
- if (marked.has(value)) return;
1144
- marked.add(value);
1145
-
1146
- if (value.reactions !== null) {
1147
- for (const reaction of value.reactions) {
1148
- const flags = reaction.f;
1149
-
1150
- if ((flags & DERIVED) !== 0) {
1151
- mark_effects(/** @type {Derived} */ (reaction), sources, marked, checked);
1152
- } else if (
1153
- (flags & (ASYNC | BLOCK_EFFECT)) !== 0 &&
1154
- (flags & DIRTY) === 0 &&
1155
- depends_on(reaction, sources, checked)
1156
- ) {
1157
- set_signal_status(reaction, DIRTY);
1158
- schedule_effect(/** @type {Effect} */ (reaction));
1159
- }
1160
- }
1161
- }
1162
- }
1163
-
1164
- /**
1165
- * When committing a fork, we need to trigger eager effects so that
1166
- * any `$state.eager(...)` expressions update immediately. This
1167
- * function allows us to discover them
1168
- * @param {Value} value
1169
- * @param {Set<Effect>} effects
1777
+ * The next batch after `batch` that wrote `source`, if any. Its write comes after one of `batch` in order, so
1778
+ * that one isn't the real-world value. Forks are skipped: their writes only exist in their own view of the world
1779
+ * @param {Batch} batch
1780
+ * @param {Value} source
1170
1781
  */
1171
- function mark_eager_effects(value, effects) {
1172
- if (value.reactions === null) return;
1173
-
1174
- for (const reaction of value.reactions) {
1175
- const flags = reaction.f;
1782
+ function later_writer(batch, source) {
1783
+ var later = batch.next;
1176
1784
 
1177
- if ((flags & DERIVED) !== 0) {
1178
- mark_eager_effects(/** @type {Derived} */ (reaction), effects);
1179
- } else if ((flags & EAGER_EFFECT) !== 0) {
1180
- set_signal_status(reaction, DIRTY);
1181
- effects.add(/** @type {Effect} */ (reaction));
1182
- }
1785
+ while (later !== null && (later.is_fork || !later.current.has(source))) {
1786
+ later = later.next;
1183
1787
  }
1184
- }
1185
-
1186
- /**
1187
- * @param {Reaction} reaction
1188
- * @param {Source[]} sources
1189
- * @param {Map<Reaction, boolean>} checked
1190
- */
1191
- function depends_on(reaction, sources, checked) {
1192
- const depends = checked.get(reaction);
1193
- if (depends !== undefined) return depends;
1194
1788
 
1195
- if (reaction.deps !== null) {
1196
- for (const dep of reaction.deps) {
1197
- if (includes.call(sources, dep)) {
1198
- return true;
1199
- }
1200
-
1201
- if ((dep.f & DERIVED) !== 0 && depends_on(/** @type {Derived} */ (dep), sources, checked)) {
1202
- checked.set(/** @type {Derived} */ (dep), true);
1203
- return true;
1204
- }
1205
- }
1206
- }
1207
-
1208
- checked.set(reaction, false);
1209
-
1210
- return false;
1789
+ return later;
1211
1790
  }
1212
1791
 
1213
1792
  /**
1214
- * @param {Effect} effect
1215
- * @returns {void}
1793
+ * Make a write the real-world value of `source`. A write to a derived is an assignment, whose
1794
+ * value holds until one of the derived's dependencies is written after it (see `changed_since`)
1795
+ * @param {Value} source
1796
+ * @param {BatchValue} entry
1216
1797
  */
1217
- export function schedule_effect(effect) {
1218
- /** @type {Batch} */ (current_batch).schedule(effect);
1798
+ function apply(source, entry) {
1799
+ source.v = entry.v;
1800
+ source.wv = entry.wv;
1801
+ source.f = entry.e ? source.f | ERROR_VALUE : source.f & ~ERROR_VALUE;
1802
+
1803
+ if ((source.f & DERIVED) !== 0) {
1804
+ source.f |= ASSIGNED;
1805
+ update_derived_status(/** @type {Derived} */ (source));
1806
+ }
1219
1807
  }
1220
1808
 
1221
1809
  /** @type {Source<number>[]} */
@@ -1263,30 +1851,26 @@ export function eager(fn) {
1263
1851
 
1264
1852
  get(version);
1265
1853
 
1266
- eager_effect(() => {
1267
- if (initial) {
1268
- // the first time this runs, we create an eager effect
1269
- // that will run eagerly whenever the expression changes
1270
- var previous_batch_values = batch_values;
1271
-
1272
- try {
1273
- batch_values = null;
1854
+ // evaluate in the real world — including recording the versions of the dependencies,
1855
+ // so that the eager effect is dirty-checked correctly later (see `flush_eager_effects`)
1856
+ in_real_world(() => {
1857
+ eager_effect(() => {
1858
+ if (initial) {
1859
+ // the first time this runs, we create an eager effect
1860
+ // that will run eagerly whenever the expression changes
1274
1861
  value = fn();
1275
- } finally {
1276
- batch_values = previous_batch_values;
1862
+ return;
1277
1863
  }
1278
1864
 
1279
- return;
1280
- }
1281
-
1282
- // the second time this effect runs, it's to schedule a
1283
- // `version` update. since this will recreate the effect,
1284
- // we don't need to evaluate the expression here
1285
- if (eager_versions.length === 0) {
1286
- queue_micro_task(eager_flush);
1287
- }
1865
+ // the second time this effect runs, it's to schedule a
1866
+ // `version` update. since this will recreate the effect,
1867
+ // we don't need to evaluate the expression here
1868
+ if (eager_versions.length === 0) {
1869
+ queue_micro_task(eager_flush);
1870
+ }
1288
1871
 
1289
- eager_versions.push(version);
1872
+ eager_versions.push(version);
1873
+ });
1290
1874
  });
1291
1875
 
1292
1876
  initial = false;
@@ -1295,43 +1879,43 @@ export function eager(fn) {
1295
1879
  }
1296
1880
 
1297
1881
  /**
1298
- * Mark all the effects inside a skipped branch CLEAN, so that
1299
- * they can be correctly rescheduled later. Tracks dirty and maybe_dirty
1300
- * effects so they can be rescheduled if the branch survives.
1301
- * @param {Effect} effect
1302
- * @param {{ d: Effect[], m: Effect[] }} tracked
1882
+ * Run `fn` with the real world (i.e. the latest values) as the active view, regardless of which batch is active
1883
+ * @param {() => void} fn
1303
1884
  */
1304
- function reset_branch(effect, tracked) {
1305
- // clean branch = nothing dirty inside, no need to traverse further
1306
- if ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {
1307
- return;
1308
- }
1309
-
1310
- if ((effect.f & DIRTY) !== 0) {
1311
- tracked.d.push(effect);
1312
- } else if ((effect.f & MAYBE_DIRTY) !== 0) {
1313
- tracked.m.push(effect);
1314
- }
1885
+ export function in_real_world(fn) {
1886
+ var previous_batch_values = batch_values;
1887
+ var previous_view_cache = view_cache;
1888
+ var previous_view_batch = view_batch;
1315
1889
 
1316
- set_signal_status(effect, CLEAN);
1890
+ // the real world doesn't belong to a batch, so what runs in it doesn't touch the active batch's records
1891
+ batch_values = view_cache = view_batch = null;
1317
1892
 
1318
- var e = effect.first;
1319
- while (e !== null) {
1320
- reset_branch(e, tracked);
1321
- e = e.next;
1893
+ try {
1894
+ fn();
1895
+ } finally {
1896
+ batch_values = previous_batch_values;
1897
+ view_cache = previous_view_cache;
1898
+ view_batch = previous_view_batch;
1322
1899
  }
1323
1900
  }
1324
1901
 
1325
1902
  /**
1326
- * Mark an entire effect tree clean following an error
1903
+ * Mark all the effects inside a skipped branch CLEAN, so that they can be correctly
1904
+ * rescheduled later (if the branch survives, its effects are re-validated, see `unskip_effect`)
1327
1905
  * @param {Effect} effect
1906
+ * @param {boolean} force reset even clean branches following an error
1328
1907
  */
1329
- function reset_all(effect) {
1908
+ function reset_branch(effect, force = false) {
1909
+ // clean branch = nothing dirty inside, no need to traverse further
1910
+ if (!force && (effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {
1911
+ return;
1912
+ }
1913
+
1330
1914
  set_signal_status(effect, CLEAN);
1331
1915
 
1332
1916
  var e = effect.first;
1333
1917
  while (e !== null) {
1334
- reset_all(e);
1918
+ reset_branch(e, force);
1335
1919
  e = e.next;
1336
1920
  }
1337
1921
  }
@@ -1360,21 +1944,34 @@ export function fork(fn) {
1360
1944
  e.experimental_async_required('fork');
1361
1945
  }
1362
1946
 
1363
- if (current_batch !== null) {
1947
+ if (active_effect !== null || current_batch?.is_fork) {
1364
1948
  e.fork_timing();
1365
1949
  }
1366
1950
 
1367
- flushSync();
1951
+ var batch = flushSync(() => {
1952
+ var batch = Batch.ensure();
1953
+ batch.is_fork = true;
1368
1954
 
1369
- var batch = Batch.ensure();
1370
- batch.is_fork = true;
1371
- batch_values = new Map();
1955
+ try {
1956
+ in_real_world(() => {
1957
+ batch_values = new Map();
1958
+ view_cache = new Map();
1959
+ view_batch = batch;
1372
1960
 
1373
- var committed = false;
1374
- var settled = batch.settled();
1961
+ fn();
1962
+ });
1963
+ } catch (error) {
1964
+ batch.discard();
1965
+ batch.deactivate();
1966
+ throw error;
1967
+ }
1375
1968
 
1376
- fn();
1377
- flushSync();
1969
+ return batch;
1970
+ });
1971
+
1972
+ var settled = batch.settled();
1973
+ var committed = false;
1974
+ var discarded = false;
1378
1975
 
1379
1976
  return {
1380
1977
  commit: async () => {
@@ -1383,51 +1980,47 @@ export function fork(fn) {
1383
1980
  return;
1384
1981
  }
1385
1982
 
1386
- if (!batch.linked) {
1983
+ if (discarded) {
1387
1984
  e.fork_discarded();
1388
1985
  }
1389
1986
 
1390
- committed = true;
1987
+ if (!batch.linked) {
1988
+ // batch was made obsolete by later changes
1989
+ committed = true;
1990
+ return;
1991
+ }
1391
1992
 
1993
+ committed = true;
1392
1994
  batch.is_fork = false;
1393
1995
 
1394
- // apply changes and update write versions so deriveds see the change
1395
- for (var [source, [value]] of batch.current) {
1396
- source.v = value;
1397
- source.wv = increment_write_version();
1398
- }
1996
+ // Apply the changes to the real world. They keep the versions they had in the fork,
1997
+ // so that everything the fork computed remains valid (processing the batch
1998
+ // re-validates everything that depends on them, see `#process`)
1999
+ for (const [source, entry] of batch.current) {
2000
+ const later = later_writer(batch, source);
1399
2001
 
1400
- // trigger any `$state.eager(...)` expressions with the new state.
1401
- // eager effects don't get scheduled like other effects, so we
1402
- // can't just encounter them during traversal, we need to
1403
- // proactively flush them
1404
- // TODO maybe there's a better implementation?
1405
- flushSync(() => {
1406
- /** @type {Set<Effect>} */
1407
- var eager_effects = new Set();
1408
-
1409
- for (var source of batch.current.keys()) {
1410
- mark_eager_effects(source, eager_effects);
2002
+ if (later !== null) {
2003
+ // in order, the fork's write comes before the later batch's, which replaces it
2004
+ later.previous.set(source, entry);
2005
+ } else {
2006
+ batch.mark(source, MAYBE_DIRTY);
2007
+ apply(source, entry);
1411
2008
  }
2009
+ }
1412
2010
 
1413
- set_eager_effects(eager_effects);
2011
+ if (eager_effects.size > 0) {
1414
2012
  flush_eager_effects();
1415
- });
2013
+ }
1416
2014
 
1417
2015
  batch.flush();
1418
2016
  await settled;
1419
2017
  },
1420
2018
  discard: () => {
1421
- // cause any MAYBE_DIRTY deriveds to update
1422
- // if they depend on things that changed
1423
- // inside the discarded fork
1424
- for (var source of batch.current.keys()) {
1425
- source.wv = increment_write_version();
1426
- }
1427
-
1428
2019
  if (!committed && batch.linked) {
1429
2020
  batch.discard();
1430
2021
  }
2022
+
2023
+ discarded = true;
1431
2024
  }
1432
2025
  };
1433
2026
  }