@krate/runtime 0.5.0-alpha.2 → 0.5.0-alpha.4

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 (105) hide show
  1. package/dist/action-context.d.ts +56 -0
  2. package/dist/action-context.js +73 -0
  3. package/dist/action-context.test.d.ts +1 -0
  4. package/dist/action-context.test.js +47 -0
  5. package/dist/actions.d.ts +120 -0
  6. package/dist/actions.js +550 -0
  7. package/dist/actions.test.d.ts +1 -0
  8. package/dist/actions.test.js +417 -0
  9. package/dist/boundary.d.ts +121 -0
  10. package/dist/boundary.js +429 -0
  11. package/dist/cache-scope.d.ts +118 -0
  12. package/dist/cache-scope.js +311 -0
  13. package/dist/cache.d.ts +55 -0
  14. package/dist/cache.js +155 -0
  15. package/dist/cache.test.d.ts +1 -0
  16. package/dist/cache.test.js +217 -0
  17. package/dist/class-component.d.ts +66 -0
  18. package/dist/class-component.js +633 -0
  19. package/dist/class-component.test.d.ts +1 -0
  20. package/dist/class-component.test.js +411 -0
  21. package/dist/context.d.ts +13 -0
  22. package/dist/context.js +58 -32
  23. package/dist/context.test.d.ts +1 -0
  24. package/dist/context.test.js +57 -0
  25. package/dist/derived.test.d.ts +1 -0
  26. package/dist/derived.test.js +140 -0
  27. package/dist/discrete.test.d.ts +1 -0
  28. package/dist/discrete.test.js +100 -0
  29. package/dist/dom.d.ts +55 -0
  30. package/dist/dom.js +414 -63
  31. package/dist/effects.d.ts +88 -0
  32. package/dist/effects.js +790 -0
  33. package/dist/effects.test.d.ts +1 -0
  34. package/dist/effects.test.js +485 -0
  35. package/dist/events.d.ts +58 -0
  36. package/dist/events.js +503 -0
  37. package/dist/events.test.d.ts +1 -0
  38. package/dist/events.test.js +447 -0
  39. package/dist/index.d.ts +14 -4
  40. package/dist/index.js +9 -3
  41. package/dist/jsx-types.d.ts +2 -0
  42. package/dist/krate-hydrate-lite.js +7 -1
  43. package/dist/krate-hydrate.js +7 -1
  44. package/dist/krate-runtime.js +7 -1
  45. package/dist/krate-suspense.js +2 -0
  46. package/dist/lanes.test.d.ts +1 -0
  47. package/dist/lanes.test.js +59 -0
  48. package/dist/list.d.ts +20 -0
  49. package/dist/list.js +466 -0
  50. package/dist/list.test.d.ts +1 -0
  51. package/dist/list.test.js +344 -0
  52. package/dist/optimistic-lanes.test.d.ts +1 -0
  53. package/dist/optimistic-lanes.test.js +45 -0
  54. package/dist/portal.d.ts +47 -0
  55. package/dist/portal.js +189 -0
  56. package/dist/portal.test.d.ts +1 -0
  57. package/dist/portal.test.js +99 -0
  58. package/dist/react-effects.test.d.ts +1 -0
  59. package/dist/react-effects.test.js +96 -0
  60. package/dist/react-suspense.test.d.ts +1 -0
  61. package/dist/react-suspense.test.js +194 -0
  62. package/dist/react.d.ts +132 -32
  63. package/dist/react.js +335 -81
  64. package/dist/react.test.js +12 -2
  65. package/dist/reconcile.js +13 -0
  66. package/dist/refs.d.ts +33 -0
  67. package/dist/refs.js +142 -0
  68. package/dist/refs.test.d.ts +1 -0
  69. package/dist/refs.test.js +257 -0
  70. package/dist/request-context.d.ts +62 -0
  71. package/dist/request-context.js +107 -0
  72. package/dist/resource.js +20 -1
  73. package/dist/router-layout.test.d.ts +1 -0
  74. package/dist/router-layout.test.js +179 -0
  75. package/dist/router-lite.d.ts +25 -0
  76. package/dist/router-lite.js +73 -0
  77. package/dist/router-nav.test.d.ts +1 -0
  78. package/dist/router-nav.test.js +399 -0
  79. package/dist/router-slots.test.d.ts +1 -0
  80. package/dist/router-slots.test.js +144 -0
  81. package/dist/router.d.ts +66 -2
  82. package/dist/router.js +1535 -650
  83. package/dist/server-async.test.d.ts +1 -0
  84. package/dist/server-async.test.js +174 -0
  85. package/dist/server-renderer.js +494 -119
  86. package/dist/server.d.ts +27 -1
  87. package/dist/server.js +187 -1
  88. package/dist/server.test.js +20 -0
  89. package/dist/signal-lanes.test.d.ts +1 -0
  90. package/dist/signal-lanes.test.js +32 -0
  91. package/dist/signal.d.ts +186 -1
  92. package/dist/signal.js +896 -66
  93. package/dist/slots.d.ts +22 -0
  94. package/dist/slots.js +134 -0
  95. package/dist/slots.test.d.ts +1 -0
  96. package/dist/slots.test.js +169 -0
  97. package/dist/snapshots.test.d.ts +1 -0
  98. package/dist/snapshots.test.js +208 -0
  99. package/dist/suspense-actions.test.d.ts +1 -0
  100. package/dist/suspense-actions.test.js +72 -0
  101. package/dist/suspense.d.ts +220 -0
  102. package/dist/suspense.js +901 -0
  103. package/dist/suspense.test.d.ts +1 -0
  104. package/dist/suspense.test.js +518 -0
  105. package/package.json +5 -1
package/dist/signal.js CHANGED
@@ -1,25 +1,351 @@
1
1
  import { resetContexts } from './context.js';
2
2
  import { resolvePersist, readDurableState, readPersisted, writePersisted, subscribePersist, } from './storage.js';
3
+ /** Signal options that give a signal React state semantics. */
4
+ export const krateHookState = { react: true };
5
+ // A null entry is an untracked scope (see untrack): reads inside it subscribe
6
+ // nothing.
3
7
  const context = [];
8
+ // Each queued mount callback remembers the owner (effect or root) that was
9
+ // current when it was registered, so an onCleanup inside the callback belongs
10
+ // to that owner instead of the page root, and the error-boundary owner its
11
+ // errors are routed to.
4
12
  const mountQueue = [];
5
13
  let mountScheduled = false;
14
+ let ownerHooks = null;
15
+ /** Installs (or with null removes) the owner integration hooks. */
16
+ export function setOwnerHooks(hooks) {
17
+ ownerHooks = hooks;
18
+ }
19
+ // Callbacks that run once the effect queue has fully drained (see afterFlush).
20
+ const afterQueue = [];
6
21
  const allEffects = new Set();
7
22
  // Top-level onCleanup registrations (called outside an effect body) are scoped
8
23
  // to the page/root and run when disposeAll() executes on route change. This
9
24
  // gives component-level cleanup semantics: a component's top-level onCleanup
10
25
  // registers once when its hydration IIFE runs and is invoked on unmount.
11
26
  const rootCleanups = [];
27
+ // Route scopes (SPA layout persistence). Hydration code of a layout runs
28
+ // between krateEnterScope(id) and krateLeaveScope(), so every effect, cleanup
29
+ // and component owner it creates is tagged with the layout's id. On a soft
30
+ // navigation that keeps the layout mounted, the router disposes everything
31
+ // except the kept scopes (krateDisposeExcept) and the new page's hydration
32
+ // script skips the kept layouts' code (krateEnterScope returns false).
33
+ let routeScope = null;
34
+ let keptScopes = new Set();
35
+ // Scope of each owner key used by ownerEffects/ownerCleanups.
36
+ const ownerScopes = new Map();
37
+ /**
38
+ * Enters the route scope `id` for the hydration code that follows. Returns
39
+ * false when the SPA router kept that layout mounted: its bindings and
40
+ * effects are still live and must not be created twice.
41
+ */
42
+ export function krateEnterScope(id) {
43
+ if (keptScopes.has(id))
44
+ return false;
45
+ routeScope = id;
46
+ currentOwner = null;
47
+ return true;
48
+ }
49
+ /** Leaves the current route scope (see krateEnterScope). */
50
+ export function krateLeaveScope() {
51
+ routeScope = null;
52
+ currentOwner = null;
53
+ }
54
+ /**
55
+ * The route scope new effects and owners are tagged with (internal): the
56
+ * running effect's scope, else the scope whose hydration code is running,
57
+ * else the current component owner's scope (code running later, e.g. an
58
+ * event handler of a layout component).
59
+ */
60
+ export function krateCurrentScope() {
61
+ const top = context[context.length - 1];
62
+ if (top)
63
+ return top.scope;
64
+ if (routeScope !== null)
65
+ return routeScope;
66
+ if (currentOwner !== null && ownerScopes.has(currentOwner))
67
+ return ownerScopes.get(currentOwner) ?? null;
68
+ return null;
69
+ }
70
+ /** Sets the layout scopes the router kept mounted for the next hydration (internal). */
71
+ export function krateKeepScopes(ids) {
72
+ keptScopes = new Set(ids);
73
+ }
74
+ /** Records the route scope of an owner key (internal; see effects.ts). */
75
+ export function krateTagOwner(owner, scope) {
76
+ if (owner !== null && !ownerScopes.has(owner))
77
+ ownerScopes.set(owner, scope);
78
+ }
12
79
  // Pending effects scheduled to re-run in the next microtask. Writes batch
13
80
  // subscriber re-runs into a single flush so N writes in a loop (or one write
14
81
  // fanning out) produce one pass instead of N synchronous effect runs.
15
82
  const pending = [];
16
83
  let flushScheduled = false;
17
84
  function newEffectState(fn) {
18
- return { fn, cleanups: [], disposed: false, sources: new Set(), running: false, rerun: false, queued: false };
85
+ const scope = krateCurrentScope();
86
+ const effect = { fn, cleanups: [], disposed: false, sources: new Set(), running: false, rerun: false, queued: false, owner: currentOwner, boundaryOwner: ownerHooks ? ownerHooks.current() : null, scope };
87
+ if (currentOwner !== null) {
88
+ krateTagOwner(currentOwner, scope);
89
+ let set = ownerEffects.get(currentOwner);
90
+ if (!set)
91
+ ownerEffects.set(currentOwner, (set = new Set()));
92
+ set.add(effect);
93
+ }
94
+ return effect;
95
+ }
96
+ // Effects and top-level cleanups created while an owner was current, so the
97
+ // owner can be unmounted on its own (a component removed by a conditional).
98
+ const ownerEffects = new Map();
99
+ const ownerCleanups = new Map();
100
+ /**
101
+ * Disposes every effect created under `owner` and runs its top-level
102
+ * onCleanup callbacks (internal, used when a component unmounts).
103
+ */
104
+ export function krateDisposeOwner(owner) {
105
+ const effects = ownerEffects.get(owner);
106
+ ownerEffects.delete(owner);
107
+ if (effects) {
108
+ for (const effect of effects) {
109
+ disposeEffect(effect);
110
+ allEffects.delete(effect);
111
+ }
112
+ }
113
+ const cleanups = ownerCleanups.get(owner);
114
+ ownerCleanups.delete(owner);
115
+ ownerScopes.delete(owner);
116
+ if (cleanups) {
117
+ for (const c of cleanups) {
118
+ try {
119
+ c();
120
+ }
121
+ catch {
122
+ // One failing cleanup must not keep the rest from running.
123
+ }
124
+ }
125
+ }
126
+ }
127
+ // Render snapshots for React state (see SignalOptions.react).
128
+ //
129
+ // Krate's render phase is any tracked effect run (DOM bindings, dependency
130
+ // trackers, memo computations read by them): reads there see the latest
131
+ // value. Everywhere else a React state read returns the value as of the last
132
+ // commit, or as of `snapshotEpoch` while an effect setup/cleanup runs for the
133
+ // commit it belongs to.
134
+ let renderDepth = 0;
135
+ let snapshotEpoch = null;
136
+ let epoch = 0;
137
+ const changedCells = new Set();
138
+ const historyCells = new Set();
139
+ /**
140
+ * Runs fn as render work: React state reads see the latest values rather than
141
+ * the last commit's (internal; the class component render phase).
142
+ */
143
+ export function krateRenderPhase(fn) {
144
+ renderDepth++;
145
+ const prevEpoch = snapshotEpoch;
146
+ snapshotEpoch = null;
147
+ try {
148
+ return fn();
149
+ }
150
+ finally {
151
+ snapshotEpoch = prevEpoch;
152
+ renderDepth--;
153
+ }
154
+ }
155
+ /** Records the current React state values as commit `epoch` (internal). */
156
+ export function krateCommitSnapshot() {
157
+ epoch++;
158
+ for (const cell of changedCells)
159
+ cell.commit(epoch);
160
+ changedCells.clear();
161
+ return epoch;
162
+ }
163
+ /** The epoch of the last commit snapshot (internal). */
164
+ export function krateEpoch() {
165
+ return epoch;
166
+ }
167
+ /** Runs fn reading React state as of commit `at` (internal). */
168
+ export function krateReadAt(at, fn) {
169
+ const prev = snapshotEpoch;
170
+ snapshotEpoch = at;
171
+ try {
172
+ return fn();
173
+ }
174
+ finally {
175
+ snapshotEpoch = prev;
176
+ }
177
+ }
178
+ /** Drops snapshot history older than commit `min` (internal). */
179
+ export function kratePruneSnapshots(min) {
180
+ for (const cell of historyCells) {
181
+ if (!cell.prune(min))
182
+ historyCells.delete(cell);
183
+ }
184
+ }
185
+ // Update lanes. A write during a discrete event (click, key, input...) or a
186
+ // commit flushes in a microtask, and a discrete update also runs its passive
187
+ // effects at the end of its commit, like React's SyncLane. A React state
188
+ // write anywhere else (timeouts, promises) flushes in a later task, after
189
+ // the microtasks that code queued, like React's DefaultLane.
190
+ const DISCRETE = new Set(('auxclick beforeinput blur cancel change click close compositionend compositionstart compositionupdate ' +
191
+ 'contextmenu copy cut dblclick dragend dragstart drop focusin focusout input invalid keydown keypress keyup ' +
192
+ 'mousedown mouseup paste pause play pointercancel pointerdown pointerup ratechange reset resize seeked ' +
193
+ 'select submit touchcancel touchend touchstart volumechange focus').split(' '));
194
+ let committing = 0;
195
+ let syncLane = false;
196
+ // Set while the event runtime dispatches a discrete native event.
197
+ let discreteDispatch = 0;
198
+ function inDiscreteEvent() {
199
+ if (discreteDispatch > 0)
200
+ return true;
201
+ const ev = typeof window !== 'undefined' ? window.event : undefined;
202
+ return !!ev && DISCRETE.has(ev.type);
203
+ }
204
+ let transitionWrites = 0;
205
+ /**
206
+ * Runs fn with its signal writes in the transition lane: they commit in a
207
+ * later task, like React's transition and default updates, even for plain
208
+ * signals. Used for the updates an async action makes when it settles
209
+ * (pending flags, results), so the pending render stays on screen for at
210
+ * least one task, as it does in React.
211
+ */
212
+ export function krateTransitionWrites(fn) {
213
+ transitionWrites++;
214
+ try {
215
+ return fn();
216
+ }
217
+ finally {
218
+ transitionWrites--;
219
+ }
220
+ }
221
+ /** Reports whether a native event type is discrete (React's SyncLane). */
222
+ export function krateIsDiscrete(type) {
223
+ return DISCRETE.has(type);
224
+ }
225
+ /**
226
+ * Runs the handlers of one native event dispatch. For a discrete event
227
+ * (click, input, keydown, submit, change, focus, ...) the updates they made
228
+ * are flushed synchronously when `flush` is set, as React does at the end of
229
+ * a discrete event: render, commit, layout and passive effects all run before
230
+ * the browser event returns. Continuous events keep the normal batching.
231
+ */
232
+ export function krateRunEvent(type, flush, fn) {
233
+ const discrete = DISCRETE.has(type);
234
+ if (!discrete) {
235
+ fn();
236
+ return;
237
+ }
238
+ discreteDispatch++;
239
+ try {
240
+ fn();
241
+ }
242
+ finally {
243
+ discreteDispatch--;
244
+ // An event dispatched by the flush itself (a blur fired by removing the
245
+ // focused node) joins the running flush instead of committing on its own.
246
+ if (flush && discreteDispatch === 0 && flushDepth === 0 && committing === 0 && (pending.length > 0 || syncLane)) {
247
+ krateFlushSync();
248
+ }
249
+ }
250
+ }
251
+ /** Marks a commit in progress (internal): writes there flush in a microtask. */
252
+ export function krateCommitting(on) {
253
+ committing += on ? 1 : -1;
254
+ }
255
+ /** Reports and clears whether the pending commit came from a discrete event. */
256
+ export function krateTakeSyncLane() {
257
+ const v = syncLane;
258
+ syncLane = false;
259
+ return v;
260
+ }
261
+ /** The effect currently collecting dependencies, ignoring untracked frames. */
262
+ function currentEffect() {
263
+ return context[context.length - 1] || null;
264
+ }
265
+ // The component owner whose body (or binding effect) is currently running.
266
+ // Opaque here; effects.ts gives it meaning (effect ordering and unmounting).
267
+ // Effects capture it at creation and restore it while they re-run, so
268
+ // components created by a binding re-run are parented correctly.
269
+ let currentOwner = null;
270
+ /** Returns the current component owner (internal, used by effects.ts). */
271
+ export function krateGetOwner() {
272
+ return currentOwner;
273
+ }
274
+ /** Sets the current component owner and returns the previous one (internal). */
275
+ export function krateSetOwner(owner) {
276
+ const prev = currentOwner;
277
+ currentOwner = owner;
278
+ return prev;
279
+ }
280
+ // Hooks run after a flush settles (no pending effects) and when the page is
281
+ // torn down. effects.ts registers its commit and unmount here; the API is
282
+ // additive so other schedulers can hook in too.
283
+ const beforeFlushHooks = [];
284
+ const afterFlushHooks = [];
285
+ const disposeHooks = [];
286
+ /** Registers fn to run before every effect flush starts (internal). */
287
+ export function krateOnBeforeFlush(fn) {
288
+ beforeFlushHooks.push(fn);
289
+ }
290
+ /** Registers fn to run after every settled effect flush (internal). */
291
+ export function krateOnAfterFlush(fn) {
292
+ afterFlushHooks.push(fn);
293
+ }
294
+ /**
295
+ * Registers fn to run at the start of disposeAll (internal). For a partial
296
+ * teardown (krateDisposeExcept / krateDisposeScopes) `gone` reports which
297
+ * route scopes are torn down; it is null for a full teardown.
298
+ */
299
+ export function krateOnDispose(fn) {
300
+ disposeHooks.push(fn);
301
+ }
302
+ /** Reports whether signal writes are waiting for the next flush. */
303
+ export function kratePendingFlush() {
304
+ return pending.length > 0;
305
+ }
306
+ /**
307
+ * Runs fn without subscribing the surrounding effect to the signals it reads.
308
+ */
309
+ export function untrack(fn) {
310
+ context.push(null);
311
+ try {
312
+ return fn();
313
+ }
314
+ finally {
315
+ context.pop();
316
+ }
317
+ }
318
+ /**
319
+ * Runs fn once after the pending effect queue has fully drained (including
320
+ * effects scheduled while it drained) and the after-flush hooks ran, so the
321
+ * DOM reflects every write made so far. Schedules a flush when none is
322
+ * pending. Used by the class component commit phase.
323
+ */
324
+ export function afterFlush(fn) {
325
+ afterQueue.push(fn);
326
+ scheduleFlush();
327
+ }
328
+ function drainAfterQueue() {
329
+ if (afterQueue.length === 0)
330
+ return;
331
+ const after = afterQueue.splice(0);
332
+ for (const fn of after) {
333
+ fn();
334
+ }
335
+ }
336
+ /**
337
+ * Same-value equality used for every React-facing comparison (state
338
+ * bail-out, dependency arrays): Object.is, so NaN equals NaN and +0 differs
339
+ * from -0.
340
+ */
341
+ export function sameValue(a, b) {
342
+ return Object.is(a, b);
19
343
  }
20
344
  function disposeEffect(effect) {
21
345
  if (!effect.disposed) {
22
346
  effect.disposed = true;
347
+ if (effect.owner !== null)
348
+ ownerEffects.get(effect.owner)?.delete(effect);
23
349
  // Detach from every signal subscriber Set so a long-lived signal never
24
350
  // retains a disposed effect (and its closure graph).
25
351
  for (const set of effect.sources) {
@@ -32,20 +358,120 @@ function disposeEffect(effect) {
32
358
  effect.cleanups.length = 0;
33
359
  }
34
360
  }
361
+ /**
362
+ * Partial teardown for a soft navigation that keeps some layouts mounted:
363
+ * disposes every effect, cleanup and component owner whose route scope is
364
+ * not in `keep`. With an empty `keep` this is disposeAll().
365
+ */
366
+ export function krateDisposeExcept(keep) {
367
+ if (keep.length === 0) {
368
+ disposeAll();
369
+ return;
370
+ }
371
+ const k = new Set(keep);
372
+ disposeMatching((scope) => !(scope != null && k.has(scope)), true);
373
+ }
374
+ /**
375
+ * Disposes only the effects, cleanups and component owners of the given
376
+ * route scopes (a parallel-route slot whose content is replaced).
377
+ */
378
+ export function krateDisposeScopes(ids) {
379
+ if (ids.length === 0)
380
+ return;
381
+ const k = new Set(ids);
382
+ disposeMatching((scope) => scope != null && k.has(scope), false);
383
+ }
384
+ /** The route scope encoded in a layout/slot id ("_lHASH_x" -> "_lHASH_"), else null. */
385
+ export function krateScopeOfId(id) {
386
+ if (id.charCodeAt(0) !== 95 /* _ */)
387
+ return null;
388
+ const end = id.indexOf('_', 1);
389
+ return end > 0 ? id.slice(0, end + 1) : null;
390
+ }
391
+ function disposeMatching(gone, pageTeardown) {
392
+ for (const hook of disposeHooks) {
393
+ try {
394
+ hook(gone);
395
+ }
396
+ catch {
397
+ // Unmount errors must not prevent the rest of the teardown.
398
+ }
399
+ }
400
+ for (const effect of Array.from(allEffects)) {
401
+ if (gone(effect.scope)) {
402
+ disposeEffect(effect);
403
+ allEffects.delete(effect);
404
+ }
405
+ }
406
+ const kept = [];
407
+ for (const cleanup of rootCleanups.splice(0)) {
408
+ if (!gone(cleanup.scope)) {
409
+ kept.push(cleanup);
410
+ continue;
411
+ }
412
+ try {
413
+ cleanup.fn();
414
+ }
415
+ catch {
416
+ // Cleanup errors must not prevent remaining cleanups or DOM swap.
417
+ }
418
+ }
419
+ rootCleanups.push(...kept);
420
+ const owners = new Set([...ownerCleanups.keys(), ...ownerEffects.keys()]);
421
+ for (const owner of owners) {
422
+ if (gone(ownerScopes.get(owner) ?? null))
423
+ krateDisposeOwner(owner);
424
+ }
425
+ if (!pageTeardown)
426
+ return;
427
+ // Islands are only mounted by page code (layouts with islands are never kept).
428
+ const g = globalThis;
429
+ const islands = g.__krate_island_cleanups;
430
+ if (Array.isArray(islands)) {
431
+ g.__krate_island_cleanups = [];
432
+ for (const cleanup of islands) {
433
+ try {
434
+ cleanup();
435
+ }
436
+ catch {
437
+ // Island unmount errors must not prevent the SPA swap.
438
+ }
439
+ }
440
+ }
441
+ routeScope = null;
442
+ resetContexts();
443
+ }
35
444
  export function disposeAll() {
445
+ routeScope = null;
446
+ for (const hook of disposeHooks) {
447
+ try {
448
+ hook(null);
449
+ }
450
+ catch {
451
+ // Unmount errors must not prevent the rest of the teardown.
452
+ }
453
+ }
36
454
  for (const effect of allEffects) {
37
455
  disposeEffect(effect);
38
456
  }
39
457
  allEffects.clear();
40
458
  for (const cleanup of rootCleanups) {
41
459
  try {
42
- cleanup();
460
+ cleanup.fn();
43
461
  }
44
462
  catch {
45
463
  // Cleanup errors must not prevent remaining cleanups or DOM swap.
46
464
  }
47
465
  }
48
466
  rootCleanups.length = 0;
467
+ for (const owner of Array.from(ownerCleanups.keys())) {
468
+ krateDisposeOwner(owner);
469
+ }
470
+ ownerEffects.clear();
471
+ ownerScopes.clear();
472
+ changedCells.clear();
473
+ historyCells.clear();
474
+ snapshotEpoch = null;
49
475
  // Unmount external Preact islands mounted by the page before the DOM swap.
50
476
  const g = globalThis;
51
477
  const islands = g.__krate_island_cleanups;
@@ -61,7 +487,11 @@ export function disposeAll() {
61
487
  }
62
488
  }
63
489
  pending.length = 0;
490
+ afterQueue.length = 0;
64
491
  flushScheduled = false;
492
+ flushMode = 0;
493
+ flushToken++;
494
+ syncLane = false;
65
495
  // Reset every context stack to its default so provider values from the page
66
496
  // being torn down cannot leak into the next SPA navigation.
67
497
  resetContexts();
@@ -165,44 +595,70 @@ export function createSignal(initial, options) {
165
595
  }
166
596
  }
167
597
  const subs = new Set();
598
+ // React state: the committed value and its per-commit history.
599
+ const react = !!options?.react;
600
+ let committed = value;
601
+ let history = null;
602
+ const cell = react
603
+ ? {
604
+ commit(e) {
605
+ if (Object.is(committed, value))
606
+ return;
607
+ if (!history)
608
+ history = [[0, committed]];
609
+ history.push([e, value]);
610
+ committed = value;
611
+ historyCells.add(cell);
612
+ },
613
+ prune(min) {
614
+ if (!history)
615
+ return false;
616
+ while (history.length > 1 && history[1][0] <= min)
617
+ history.shift();
618
+ if (history.length === 1) {
619
+ history = null;
620
+ return false;
621
+ }
622
+ return true;
623
+ },
624
+ }
625
+ : null;
626
+ const valueAt = (at) => {
627
+ if (!history)
628
+ return committed;
629
+ for (let i = history.length - 1; i >= 0; i--) {
630
+ if (history[i][0] <= at)
631
+ return history[i][1];
632
+ }
633
+ return history[0][1];
634
+ };
168
635
  const read = () => {
169
636
  const current = context[context.length - 1];
170
637
  if (current && !current.disposed) {
171
638
  subs.add(current);
172
639
  current.sources.add(subs);
173
640
  }
174
- return value;
175
- };
176
- const notify = () => {
177
- const list = Array.from(subs);
178
- for (const effect of list) {
179
- if (effect.disposed) {
180
- // Lazy cleanup for effects that were disposed without unsubscribing.
181
- subs.delete(effect);
182
- continue;
183
- }
184
- if (effect.running) {
185
- // A feedback loop that writes its own dependencies gets one
186
- // re-run after the current run; further iterations are dropped to
187
- // guarantee termination.
188
- effect.rerun = true;
189
- continue;
190
- }
191
- if (!effect.queued) {
192
- effect.queued = true;
193
- pending.push(effect);
194
- }
641
+ if (react) {
642
+ if (snapshotEpoch !== null)
643
+ return valueAt(snapshotEpoch);
644
+ if (renderDepth === 0)
645
+ return committed;
195
646
  }
196
- scheduleFlush();
647
+ return value;
197
648
  };
649
+ const notify = (reactWrite = false) => notifySubs(subs, reactWrite);
198
650
  const write = (next) => {
199
651
  const resolved = typeof next === 'function' ? next(value) : next;
200
- if (resolved !== value) {
652
+ // Object.is bail-out (React semantics): writing the same value notifies
653
+ // nothing, and NaN written over NaN is "the same value".
654
+ if (!Object.is(resolved, value)) {
201
655
  value = resolved;
202
656
  if (persist) {
203
657
  writePersisted(persist, value);
204
658
  }
205
- notify();
659
+ if (cell)
660
+ changedCells.add(cell);
661
+ notify(react);
206
662
  }
207
663
  };
208
664
  // Cross-tab synchronization: another tab changing the same key updates this
@@ -214,7 +670,7 @@ export function createSignal(initial, options) {
214
670
  return;
215
671
  try {
216
672
  const incoming = p.deserialize(raw);
217
- if (incoming !== value) {
673
+ if (!Object.is(incoming, value)) {
218
674
  value = incoming;
219
675
  notify();
220
676
  }
@@ -225,39 +681,294 @@ export function createSignal(initial, options) {
225
681
  });
226
682
  onCleanup(unsubscribe);
227
683
  }
684
+ signalGetters.add(read);
228
685
  return [read, write];
229
686
  }
230
- function scheduleFlush() {
231
- if (!flushScheduled) {
232
- flushScheduled = true;
233
- queueMicrotask(flushEffects);
687
+ // notifySubs schedules every subscriber of a changed source. Derived-value
688
+ // observers are marked stale synchronously (and forward the notification to
689
+ // their own subscribers), so anything that re-runs in the flush reads a
690
+ // recomputed value.
691
+ function notifySubs(subs, reactWrite = false) {
692
+ const list = Array.from(subs);
693
+ for (const effect of list) {
694
+ if (effect.disposed) {
695
+ // Lazy cleanup for effects that were disposed without unsubscribing.
696
+ subs.delete(effect);
697
+ continue;
698
+ }
699
+ if (effect.mark) {
700
+ effect.mark(reactWrite);
701
+ continue;
702
+ }
703
+ if (effect.running) {
704
+ // A feedback loop that writes its own dependencies gets one
705
+ // re-run after the current run; further iterations are dropped to
706
+ // guarantee termination.
707
+ effect.rerun = true;
708
+ continue;
709
+ }
710
+ if (!effect.queued) {
711
+ effect.queued = true;
712
+ pending.push(effect);
713
+ }
234
714
  }
715
+ scheduleFlush(reactWrite);
235
716
  }
717
+ const derivedGetters = new WeakSet();
718
+ /**
719
+ * A lazily evaluated derived value: the compile target of a React render-body
720
+ * value (`const total = rows.reduce(...)`). The getter recomputes on read when
721
+ * a signal (or another derived value) it read last time has changed since, so
722
+ * every reader in a flush sees the same current value. Nothing is computed
723
+ * until the first read, and a write only marks it stale. triggers, when
724
+ * given, is read for its subscriptions only: an object or array literal built
725
+ * in render gets a new identity whenever the component would re-render.
726
+ */
727
+ export function krateDerived(fn, triggers) {
728
+ let value;
729
+ let stale = true;
730
+ const subs = new Set();
731
+ const node = newEffectState(() => { });
732
+ node.mark = (reactWrite) => {
733
+ if (!stale) {
734
+ stale = true;
735
+ notifySubs(subs, reactWrite);
736
+ }
737
+ };
738
+ allEffects.add(node);
739
+ const read = () => {
740
+ const current = context[context.length - 1];
741
+ if (current && !current.disposed) {
742
+ subs.add(current);
743
+ current.sources.add(subs);
744
+ }
745
+ // Outside render (an event handler, an effect setup) React state reads
746
+ // see a committed snapshot. When that snapshot can differ from the latest
747
+ // values, compute from it without touching the cache, which always holds
748
+ // the latest render value.
749
+ if ((renderDepth === 0 || snapshotEpoch !== null) &&
750
+ (changedCells.size > 0 || (snapshotEpoch !== null && historyCells.size > 0))) {
751
+ return untrack(fn);
752
+ }
753
+ if (stale && !node.disposed) {
754
+ for (const set of node.sources) {
755
+ set.delete(node);
756
+ }
757
+ node.sources.clear();
758
+ // Cleared before computing so a source written during the computation
759
+ // marks it stale again instead of being lost.
760
+ stale = false;
761
+ context.push(node);
762
+ try {
763
+ // Extra sources (a render literal's state and props) only subscribe.
764
+ if (triggers)
765
+ triggers();
766
+ value = fn();
767
+ }
768
+ catch (err) {
769
+ stale = true;
770
+ throw err;
771
+ }
772
+ finally {
773
+ context.pop();
774
+ }
775
+ }
776
+ else if (node.disposed) {
777
+ return untrack(fn);
778
+ }
779
+ return value;
780
+ };
781
+ // Disposed with the binding (or component) that created it.
782
+ const parent = context[context.length - 1];
783
+ if (parent) {
784
+ parent.cleanups.push(() => {
785
+ disposeEffect(node);
786
+ allEffects.delete(node);
787
+ });
788
+ }
789
+ derivedGetters.add(read);
790
+ signalGetters.add(read);
791
+ return read;
792
+ }
793
+ /** Reports whether fn is a getter returned by krateDerived. */
794
+ export function isDerivedGetter(fn) {
795
+ return typeof fn === 'function' && derivedGetters.has(fn);
796
+ }
797
+ /**
798
+ * Normalizes a custom hook's return value to a getter. A hook compiled from
799
+ * React source returns a derived getter for a render-dependent result; any
800
+ * other value (a hook from a plain module, a constant) is wrapped so the call
801
+ * site can read every hook result the same way.
802
+ */
803
+ export function krateHook(value) {
804
+ if (isDerivedGetter(value))
805
+ return value;
806
+ return () => value;
807
+ }
808
+ // Getters returned by createSignal, so the React compatibility hooks can read
809
+ // a dependency that is a signal getter instead of comparing the function.
810
+ const signalGetters = new WeakSet();
811
+ /** Reports whether fn is a getter returned by createSignal. */
812
+ export function isSignalGetter(fn) {
813
+ return typeof fn === 'function' && signalGetters.has(fn);
814
+ }
815
+ // 0: none, 1: microtask, 2: later task.
816
+ let flushMode = 0;
817
+ let flushToken = 0;
818
+ function scheduleFlush(reactWrite = false) {
819
+ // Transition writes never take the sync lane, even when the microtask that
820
+ // makes them still sees the discrete event that started the action.
821
+ const discrete = transitionWrites === 0 && inDiscreteEvent();
822
+ if (discrete)
823
+ syncLane = true;
824
+ const later = reactWrite || transitionWrites > 0;
825
+ const micro = !later || discrete || committing > 0 || renderDepth > 0 || typeof setTimeout !== 'function';
826
+ if (flushMode === 1 || (!micro && flushMode === 2))
827
+ return;
828
+ flushScheduled = true;
829
+ const token = ++flushToken;
830
+ const run = () => {
831
+ if (token === flushToken)
832
+ flushEffects();
833
+ };
834
+ if (micro) {
835
+ flushMode = 1;
836
+ queueMicrotask(run);
837
+ }
838
+ else {
839
+ flushMode = 2;
840
+ setTimeout(run, 0);
841
+ }
842
+ }
843
+ let flushDepth = 0;
236
844
  function flushEffects() {
845
+ flushDepth++;
846
+ try {
847
+ flushEffectsInner();
848
+ }
849
+ finally {
850
+ flushDepth--;
851
+ }
852
+ }
853
+ function flushEffectsInner() {
237
854
  flushScheduled = false;
238
- const effects = pending.splice(0);
239
- for (const effect of effects) {
240
- if (effect.disposed) {
241
- continue;
242
- }
243
- effect.queued = false;
244
- effect.rerun = false;
245
- runEffect(effect);
246
- if (effect.rerun && !effect.disposed) {
855
+ flushMode = 0;
856
+ flushToken++;
857
+ for (const hook of beforeFlushHooks) {
858
+ hook();
859
+ }
860
+ // Effects re-queued by writes during a pass run in further passes of this
861
+ // same flush, so the cascade settles and commits before any other task or
862
+ // microtask can run. Otherwise code running between passes (an action's
863
+ // settle callback) would read React state that is written but not yet
864
+ // committed.
865
+ for (let pass = 0; pending.length > 0 && pass < 100; pass++) {
866
+ const effects = pending.splice(0);
867
+ for (const effect of effects) {
868
+ if (effect.disposed) {
869
+ continue;
870
+ }
871
+ effect.queued = false;
247
872
  effect.rerun = false;
248
873
  runEffect(effect);
874
+ if (effect.rerun && !effect.disposed) {
875
+ effect.rerun = false;
876
+ runEffect(effect);
877
+ }
878
+ }
879
+ }
880
+ if (pending.length === 0) {
881
+ // The cascade is done: a flush the passes scheduled has nothing to do.
882
+ flushMode = 0;
883
+ flushScheduled = false;
884
+ flushToken++;
885
+ }
886
+ // A cascade longer than the pass cap continues in the scheduled flush; the
887
+ // commit runs once it settles, so it sees the final DOM.
888
+ if (pending.length === 0) {
889
+ // Settle hooks (the class component render phase) may write signals;
890
+ // flush those in this same pass so the commit sees every DOM write.
891
+ for (const hook of settleHooks) {
892
+ hook();
893
+ }
894
+ if (pending.length > 0 && settleDepth < 50) {
895
+ settleDepth++;
896
+ try {
897
+ flushEffects();
898
+ }
899
+ finally {
900
+ settleDepth--;
901
+ }
902
+ return;
249
903
  }
904
+ runAfterFlush();
905
+ }
906
+ }
907
+ const settleHooks = [];
908
+ let settleDepth = 0;
909
+ /**
910
+ * Registers fn to run when a flush has no pending effects, before the
911
+ * after-flush hooks. Signal writes it makes are flushed first (internal).
912
+ */
913
+ export function krateOnSettle(fn) {
914
+ settleHooks.push(fn);
915
+ }
916
+ /** Ensures a flush runs soon even when no signal was written (internal). */
917
+ export function krateRequestFlush() {
918
+ scheduleFlush();
919
+ }
920
+ /**
921
+ * Runs the after-flush hooks now. Used when no signal flush is pending (for
922
+ * example, right after hydration registered effects).
923
+ */
924
+ export function runAfterFlush() {
925
+ // Every settled flush is a commit: record React state here, so committed
926
+ // values advance even when no effect scheduler is loaded.
927
+ if (changedCells.size > 0)
928
+ krateCommitSnapshot();
929
+ // React's commit reads document.activeElement (to restore focus and
930
+ // selection). In Firefox that read applies the focus fixup rule, so a
931
+ // focused button the commit disabled loses focus; reading it here gives
932
+ // each browser the same focus outcome as under React.
933
+ if (typeof document !== 'undefined')
934
+ void document.activeElement;
935
+ for (const hook of afterFlushHooks) {
936
+ hook();
937
+ }
938
+ drainAfterQueue();
939
+ }
940
+ /**
941
+ * Synchronously flushes pending signal effects and the commit that follows
942
+ * them (the building block for flushSync and tests).
943
+ */
944
+ export function krateFlushSync() {
945
+ if (pending.length === 0) {
946
+ runAfterFlush();
947
+ return;
948
+ }
949
+ // flushEffects runs the after-flush hooks itself once nothing is pending.
950
+ let guard = 0;
951
+ while (pending.length > 0 && guard++ < 100) {
952
+ flushEffects();
250
953
  }
251
954
  }
252
955
  function runEffect(effect) {
253
956
  effect.running = true;
254
- // Run cleanups from previous execution
255
- for (const cleanup of effect.cleanups) {
256
- cleanup();
257
- }
258
- effect.cleanups.length = 0;
259
- context.push(effect);
957
+ let pushed = false;
958
+ const prevOwner = currentOwner;
959
+ currentOwner = effect.owner;
960
+ renderDepth++;
961
+ // A tracked run is render work: it sees the latest values even when it is
962
+ // started from inside an effect setup or cleanup.
963
+ const prevEpoch = snapshotEpoch;
964
+ snapshotEpoch = null;
260
965
  try {
966
+ // Run cleanups from previous execution
967
+ for (const cleanup of effect.cleanups.splice(0)) {
968
+ cleanup();
969
+ }
970
+ context.push(effect);
971
+ pushed = true;
261
972
  // Support Solid-style `return () => {...}` cleanup functions. Many
262
973
  // components (Slider, Dropdown, Dialog, Tooltip) register their document
263
974
  // listeners in an effect and return a cleanup that removes them; without
@@ -268,33 +979,113 @@ function runEffect(effect) {
268
979
  effect.cleanups.push(ret);
269
980
  }
270
981
  }
982
+ catch (err) {
983
+ // An owned effect reports to its owner (error boundaries); unowned
984
+ // effects keep the previous behavior and throw.
985
+ if (!(effect.boundaryOwner && ownerHooks && ownerHooks.error(effect.boundaryOwner, err))) {
986
+ throw err;
987
+ }
988
+ }
271
989
  finally {
272
- context.pop();
990
+ snapshotEpoch = prevEpoch;
991
+ renderDepth--;
992
+ currentOwner = prevOwner;
993
+ if (pushed)
994
+ context.pop();
273
995
  effect.running = false;
274
996
  }
275
997
  }
276
998
  export function createEffect(fn) {
277
999
  const effect = newEffectState(fn);
278
1000
  allEffects.add(effect);
279
- runEffect(effect);
280
- return () => {
1001
+ // An effect created while an ownership root is current is disposed with it,
1002
+ // and an effect created under a component owner is disposed when that
1003
+ // component unmounts.
1004
+ const owner = context[context.length - 1];
1005
+ const dispose = () => {
281
1006
  disposeEffect(effect);
282
1007
  allEffects.delete(effect);
283
1008
  };
1009
+ if (effect.boundaryOwner && ownerHooks) {
1010
+ ownerHooks.cleanup(effect.boundaryOwner, dispose);
1011
+ }
1012
+ runEffect(effect);
1013
+ if (owner && owner.root)
1014
+ addOwnerCleanup(owner, dispose);
1015
+ return dispose;
284
1016
  }
285
1017
  export function onCleanup(fn) {
286
- const current = context[context.length - 1];
1018
+ const current = currentEffect();
287
1019
  if (current) {
288
- current.cleanups.push(fn);
1020
+ addOwnerCleanup(current, fn);
1021
+ return;
1022
+ }
1023
+ const owner = ownerHooks ? ownerHooks.current() : null;
1024
+ if (owner && ownerHooks) {
1025
+ // Component-level cleanup: runs when the owning component unmounts.
1026
+ ownerHooks.cleanup(owner, fn);
289
1027
  }
290
1028
  else {
291
- // No active effect: treat as a root/component-level cleanup, run on
292
- // disposeAll() (route change / page teardown).
293
- rootCleanups.push(fn);
1029
+ // No active effect: a component-level cleanup. It runs when its owner
1030
+ // unmounts, or on disposeAll() (route change / page teardown).
1031
+ if (currentOwner !== null) {
1032
+ krateTagOwner(currentOwner, krateCurrentScope());
1033
+ let list = ownerCleanups.get(currentOwner);
1034
+ if (!list)
1035
+ ownerCleanups.set(currentOwner, (list = []));
1036
+ list.push(fn);
1037
+ }
1038
+ else {
1039
+ rootCleanups.push({ fn, scope: krateCurrentScope() });
1040
+ }
1041
+ }
1042
+ }
1043
+ function addOwnerCleanup(owner, fn) {
1044
+ if (owner.dead) {
1045
+ // The root is already gone (a late mount callback): clean up at once.
1046
+ fn();
1047
+ return;
1048
+ }
1049
+ owner.cleanups.push(fn);
1050
+ }
1051
+ /**
1052
+ * Run `fn` in a new ownership root. Effects, memos, onCleanup callbacks and
1053
+ * onMount callbacks registered while it runs (and the cleanups those mount
1054
+ * callbacks register) belong to the root and are torn down, in registration
1055
+ * order, when the returned `dispose` is called. Signal reads inside `fn` are
1056
+ * not tracked by any enclosing effect. Keyed list rows and keyed remounts use
1057
+ * one root per row so a removed row runs its cleanups without touching its
1058
+ * siblings.
1059
+ */
1060
+ export function createRoot(fn) {
1061
+ const root = newEffectState(() => { });
1062
+ // `disposed` keeps signal reads inside the root untracked.
1063
+ root.disposed = true;
1064
+ root.root = true;
1065
+ const dispose = () => {
1066
+ if (root.dead)
1067
+ return;
1068
+ root.dead = true;
1069
+ const cleanups = root.cleanups.splice(0);
1070
+ for (const cleanup of cleanups) {
1071
+ try {
1072
+ cleanup();
1073
+ }
1074
+ catch (err) {
1075
+ console.error(err);
1076
+ }
1077
+ }
1078
+ };
1079
+ context.push(root);
1080
+ try {
1081
+ return fn(dispose);
1082
+ }
1083
+ finally {
1084
+ context.pop();
294
1085
  }
295
1086
  }
296
1087
  export function onMount(fn) {
297
- mountQueue.push(fn);
1088
+ mountQueue.push({ fn, owner: context[context.length - 1], boundary: ownerHooks ? ownerHooks.current() : null });
298
1089
  if (!mountScheduled) {
299
1090
  mountScheduled = true;
300
1091
  queueMicrotask(flushMounts);
@@ -303,8 +1094,33 @@ export function onMount(fn) {
303
1094
  function flushMounts() {
304
1095
  mountScheduled = false;
305
1096
  const queue = mountQueue.splice(0);
306
- for (const fn of queue) {
307
- fn();
1097
+ for (const { fn, owner, boundary } of queue) {
1098
+ const run = () => {
1099
+ if (!owner) {
1100
+ fn();
1101
+ return;
1102
+ }
1103
+ // The owner unmounted before its mount effects ran: skip them, as React
1104
+ // does for a component that never committed.
1105
+ if (owner.dead || (!owner.root && owner.disposed))
1106
+ return;
1107
+ // Collect cleanups registered by the callback without tracking its reads.
1108
+ const collector = newEffectState(() => { });
1109
+ collector.disposed = true;
1110
+ context.push(collector);
1111
+ try {
1112
+ fn();
1113
+ }
1114
+ finally {
1115
+ context.pop();
1116
+ }
1117
+ for (const cleanup of collector.cleanups)
1118
+ addOwnerCleanup(owner, cleanup);
1119
+ };
1120
+ if (boundary && ownerHooks)
1121
+ ownerHooks.run(boundary, run);
1122
+ else
1123
+ run();
308
1124
  }
309
1125
  }
310
1126
  // createMemo computes a derived value. Its computation effect is registered
@@ -322,14 +1138,18 @@ export function createMemo(fn) {
322
1138
  runEffect(effect);
323
1139
  // Register cleanup on the parent context so this memo effect is disposed
324
1140
  // when the parent re-runs or is disposed.
325
- const parent = context[context.length - 1];
1141
+ const parent = currentEffect();
1142
+ const disposeMemo = () => {
1143
+ if (!effect.disposed) {
1144
+ disposeEffect(effect);
1145
+ allEffects.delete(effect);
1146
+ }
1147
+ };
326
1148
  if (parent) {
327
- parent.cleanups.push(() => {
328
- if (!effect.disposed) {
329
- disposeEffect(effect);
330
- allEffects.delete(effect);
331
- }
332
- });
1149
+ parent.cleanups.push(disposeMemo);
1150
+ }
1151
+ else if (effect.boundaryOwner && ownerHooks) {
1152
+ ownerHooks.cleanup(effect.boundaryOwner, disposeMemo);
333
1153
  }
334
1154
  return get;
335
1155
  }
@@ -340,8 +1160,18 @@ export function createMemo(fn) {
340
1160
  * other signal. Used both directly and as the lowering target for React's
341
1161
  * `useReducer`.
342
1162
  */
343
- export function createReducer(reducer, initial) {
344
- const [get, set] = createSignal(initial);
1163
+ export function createReducer(reducer, initial, init, options) {
1164
+ // React's lazy initializer: useReducer(reducer, arg, init) starts at init(arg).
1165
+ // An options object may take init's place (createReducer(r, s, opts)).
1166
+ if (init && typeof init === 'object') {
1167
+ options = init;
1168
+ init = undefined;
1169
+ }
1170
+ const start = (typeof init === 'function' ? init(initial) : initial);
1171
+ const [get, set] = createSignal(start, options);
1172
+ // dispatch is created once, so its identity is stable for the component's
1173
+ // lifetime. The signal's Object.is bail-out skips updates when the reducer
1174
+ // returns the current state.
345
1175
  const dispatch = (action) => set((prev) => reducer(prev, action));
346
1176
  return [get, dispatch];
347
1177
  }