@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
@@ -0,0 +1,901 @@
1
+ /**
2
+ * Suspense, use(), lazy hydration and async transitions.
3
+ *
4
+ * Krate components run once and update through signals, so React's
5
+ * "throw a promise and re-render" model is mapped onto three pieces:
6
+ *
7
+ * - Boundaries. A Suspense boundary is a counter of outstanding work. It shows
8
+ * its fallback while any descendant is suspended and reveals its content
9
+ * once everything inside settled, so siblings reveal together and the
10
+ * innermost boundary wins (each suspension is attributed to the nearest
11
+ * boundary only). Compiled pages emit the boundary as a conditional slot
12
+ * (content and fallback, one of them in a hoisted template) and the
13
+ * boundary shows one of them between the slot markers (see boundaryDOM).
14
+ * - Runs. The hydration code of a component inside a boundary runs through
15
+ * `__krateBoundary(id, fn)`. When `use(promise)` meets a pending promise
16
+ * during that first run, the run throws a {@link SuspenseSignal}; the runner
17
+ * holds the boundary and runs the component again when the promise settles.
18
+ * As in React, `use()` calls on the retry reuse the promise seen at the same
19
+ * position in the previous attempt, so an uncached `use(fetch(...))` does
20
+ * not loop.
21
+ * - Transitions. `startTransition` marks the updates it makes (and the effect
22
+ * flush they cause) as a transition. A boundary that is already showing
23
+ * content keeps showing it when a transition update suspends it, and the
24
+ * transition stays pending until that work and any async action settle.
25
+ */
26
+ import { createSignal, createEffect, onCleanup, krateGetOwner, krateSetOwner } from './signal.js';
27
+ const tracked = new WeakSet();
28
+ export function isThenable(value) {
29
+ return (value != null &&
30
+ (typeof value === 'object' || typeof value === 'function') &&
31
+ typeof value.then === 'function');
32
+ }
33
+ /**
34
+ * Starts tracking a thenable's settlement by writing `status`/`value`/`reason`
35
+ * onto it (the same fields React uses, so libraries that pre-resolve promises
36
+ * for React interoperate). The same object is cached by identity: once it is
37
+ * fulfilled, reading it never suspends again.
38
+ */
39
+ export function trackThenable(t) {
40
+ if (tracked.has(t))
41
+ return t;
42
+ tracked.add(t);
43
+ if (t.status === 'fulfilled' || t.status === 'rejected')
44
+ return t;
45
+ t.status = 'pending';
46
+ t.then((value) => {
47
+ if (t.status === 'pending') {
48
+ t.status = 'fulfilled';
49
+ t.value = value;
50
+ }
51
+ }, (reason) => {
52
+ if (t.status === 'pending') {
53
+ t.status = 'rejected';
54
+ t.reason = reason;
55
+ }
56
+ });
57
+ return t;
58
+ }
59
+ /** Thrown (internally) when a pending thenable is read. */
60
+ export class SuspenseSignal {
61
+ constructor(thenable) {
62
+ this.thenable = thenable;
63
+ }
64
+ }
65
+ export function isSuspenseSignal(value) {
66
+ return value instanceof SuspenseSignal;
67
+ }
68
+ function noop() { }
69
+ const CONTEXT_MARKER = Symbol.for('krate.context');
70
+ let readScope = null;
71
+ function withReadScope(scope, fn) {
72
+ const prev = readScope;
73
+ readScope = scope;
74
+ try {
75
+ return fn();
76
+ }
77
+ finally {
78
+ readScope = prev;
79
+ }
80
+ }
81
+ /**
82
+ * Runs one attempt of a computation that may be replayed after suspending:
83
+ * reads restart at position 0 and reuse the thenables of earlier attempts.
84
+ */
85
+ export function withReplayScope(scope, fn) {
86
+ scope.i = 0;
87
+ return withReadScope(scope, fn);
88
+ }
89
+ /**
90
+ * Unwraps a value the way React's `use()` does: a context yields its current
91
+ * value, a fulfilled thenable its value, a rejected thenable throws its reason
92
+ * and a pending one throws a {@link SuspenseSignal}. Other values pass
93
+ * through unchanged.
94
+ */
95
+ export function readValue(value) {
96
+ const ctx = value;
97
+ // Krate contexts carry a marker; objects with a useContext() method (other
98
+ // context shapes) count as contexts unless they are thenables.
99
+ // Contexts are callable (React 19 `<Ctx value>`), so functions count too.
100
+ if (ctx && (typeof ctx === 'object' || typeof ctx === 'function') && typeof ctx.useContext === 'function') {
101
+ if (ctx.$$typeof === CONTEXT_MARKER || !isThenable(value))
102
+ return ctx.useContext();
103
+ }
104
+ if (!isThenable(value))
105
+ return value;
106
+ let t = value;
107
+ const scope = readScope;
108
+ if (scope) {
109
+ const idx = scope.i++;
110
+ const prev = scope.list[idx];
111
+ if (prev !== undefined && prev !== t) {
112
+ // An uncached promise created again on replay: keep the first one.
113
+ t.then(noop, noop);
114
+ t = prev;
115
+ }
116
+ else {
117
+ scope.list[idx] = t;
118
+ }
119
+ }
120
+ trackThenable(t);
121
+ if (t.status === 'fulfilled')
122
+ return t.value;
123
+ if (t.status === 'rejected')
124
+ throw t.reason;
125
+ throw new SuspenseSignal(t);
126
+ }
127
+ let errorHandler = null;
128
+ /**
129
+ * Installs the handler for errors raised inside Suspense work. An error
130
+ * boundary implementation registers here (or defines a global
131
+ * `__krateReportError(error, anchor)`); returning `true` marks the error as
132
+ * handled. Unhandled errors are logged with `console.error`.
133
+ */
134
+ export function setSuspenseErrorHandler(handler) {
135
+ errorHandler = handler;
136
+ }
137
+ let ownerApi = null;
138
+ /** Connects error boundaries explicitly (tests, the compat runtime). */
139
+ export function connectErrorBoundaries(api) {
140
+ ownerApi = api;
141
+ }
142
+ function owners() {
143
+ if (ownerApi)
144
+ return ownerApi;
145
+ const g = globalThis;
146
+ return typeof g.getOwner === 'function' && typeof g.handleError === 'function'
147
+ ? { getOwner: g.getOwner, handleError: g.handleError }
148
+ : null;
149
+ }
150
+ /** The error-boundary owner of the code running now, if any. */
151
+ function errorOwner() {
152
+ const api = owners();
153
+ return api ? api.getOwner() : null;
154
+ }
155
+ export function reportSuspenseError(error, boundary, owner) {
156
+ if (errorHandler && errorHandler(error, boundary) === true)
157
+ return;
158
+ const api = owner ? owners() : null;
159
+ if (api) {
160
+ api.handleError(error, owner);
161
+ return;
162
+ }
163
+ const g = globalThis;
164
+ if (typeof g.__krateReportError === 'function' && g.__krateReportError(error, boundary ? boundary.anchor : null) === true) {
165
+ return;
166
+ }
167
+ console.error('[krate] uncaught error in suspended work:', error);
168
+ }
169
+ class TransitionState {
170
+ constructor() {
171
+ this.count = 0;
172
+ this.error = undefined;
173
+ this.failed = false;
174
+ this.settled = false;
175
+ // Created on first read: a transition nobody observes writes no signal
176
+ // (an extra write would only schedule another flush).
177
+ this.signal = null;
178
+ this.pending = () => {
179
+ if (!this.signal)
180
+ this.signal = createSignal(!this.settled);
181
+ return this.signal[0]();
182
+ };
183
+ this.promise = new Promise((res, rej) => {
184
+ this.resolve = res;
185
+ this.reject = rej;
186
+ });
187
+ // A transition nobody awaits must not surface as an unhandled rejection;
188
+ // the error is reported through reportSuspenseError instead.
189
+ this.promise.catch(noop);
190
+ }
191
+ add() {
192
+ this.count++;
193
+ }
194
+ release() {
195
+ if (--this.count > 0)
196
+ return;
197
+ this.settled = true;
198
+ this.signal?.[1](false);
199
+ if (this.failed)
200
+ this.reject(this.error);
201
+ else
202
+ this.resolve();
203
+ }
204
+ wait(t) {
205
+ this.add();
206
+ const done = () => this.release();
207
+ t.then(done, done);
208
+ }
209
+ }
210
+ // The transition whose synchronous scope (or the effect flush that scope
211
+ // scheduled) is currently running.
212
+ let activeTransition = null;
213
+ /** Reports whether the code running now was started by startTransition. */
214
+ export function isInTransition() {
215
+ return currentLane() !== null;
216
+ }
217
+ /**
218
+ * Runs `fn` as a transition and returns its pending state. This is the
219
+ * shared primitive behind `startTransition`, `useTransition` and the React 19
220
+ * action hooks:
221
+ *
222
+ * - updates made synchronously by `fn`, and the effect flush they schedule,
223
+ * are transition updates;
224
+ * - if `fn` returns a promise (an async action) the transition stays pending
225
+ * until it settles, including the awaited work;
226
+ * - a boundary that is already revealed and suspends during the transition
227
+ * keeps its content, and the transition stays pending until it resolves.
228
+ *
229
+ * Updates made after an `await` inside `fn` are ordinary updates, as in
230
+ * React 19; wrap them in another `startTransition` to mark them.
231
+ */
232
+ export function runAsyncTransition(fn, options) {
233
+ const report = options?.report !== false;
234
+ const tr = new TransitionState();
235
+ // Join the action scope (actions.ts) so optimistic updates stay applied
236
+ // and form/action status stays pending for the whole transition.
237
+ const endAction = beginActionScope();
238
+ tr.promise.then(endAction, endAction);
239
+ tr.add();
240
+ const prev = activeTransition;
241
+ activeTransition = tr;
242
+ let result;
243
+ try {
244
+ result = fn();
245
+ }
246
+ catch (error) {
247
+ tr.failed = true;
248
+ tr.error = error;
249
+ activeTransition = prev;
250
+ tr.release();
251
+ if (report)
252
+ reportSuspenseError(error, null);
253
+ return tr;
254
+ }
255
+ activeTransition = prev;
256
+ if (isThenable(result)) {
257
+ tr.add();
258
+ result.then(() => tr.release(), (error) => {
259
+ tr.failed = true;
260
+ tr.error = error;
261
+ tr.release();
262
+ if (report)
263
+ reportSuspenseError(error, null);
264
+ });
265
+ }
266
+ // Effects scheduled by the synchronous part run in a microtask queued
267
+ // before this one; keep the transition lane open until they ran so a
268
+ // suspension they cause is attributed to this transition.
269
+ laneTransition = tr;
270
+ queueMicrotask(() => {
271
+ if (laneTransition === tr)
272
+ laneTransition = null;
273
+ tr.release();
274
+ });
275
+ return tr;
276
+ }
277
+ let actionScope = null;
278
+ // beginActionScope opens a scope in the action runtime (the hydration
279
+ // bundle's __krateBeginAction global, or one connected explicitly).
280
+ function beginActionScope() {
281
+ const begin = actionScope ?? globalThis.__krateBeginAction;
282
+ return typeof begin === 'function' ? begin() : noop;
283
+ }
284
+ /**
285
+ * Makes this module the single transition scope for React 19 actions: form
286
+ * actions and useActionState dispatches run through runAsyncTransition, so
287
+ * they share pending state, transition lanes and Suspense behavior with
288
+ * useTransition. Errors are left to the action runtime, which reports them.
289
+ */
290
+ export function connectActionTransitions(api) {
291
+ const target = (api ?? globalThis);
292
+ if (api?.__krateBeginAction)
293
+ actionScope = api.__krateBeginAction;
294
+ if (typeof target.setActionTransitionRunner !== 'function')
295
+ return;
296
+ target.setActionTransitionRunner((fn) => {
297
+ let result;
298
+ let threw = false;
299
+ let thrown;
300
+ const tr = runAsyncTransition(() => {
301
+ try {
302
+ result = fn();
303
+ }
304
+ catch (error) {
305
+ threw = true;
306
+ thrown = error;
307
+ throw error;
308
+ }
309
+ return result;
310
+ }, { report: false });
311
+ if (threw)
312
+ return Promise.reject(thrown);
313
+ // Resolve with the action's value once the transition (including any
314
+ // suspension it caused) settled; reject with the action's error.
315
+ return Promise.resolve(result).then((value) => tr.promise.then(() => value));
316
+ });
317
+ }
318
+ // The transition whose effect flush is still queued.
319
+ let laneTransition = null;
320
+ function currentLane() {
321
+ return activeTransition ?? laneTransition;
322
+ }
323
+ /** React's top-level `startTransition`. Async functions are supported. */
324
+ export function startTransition(fn) {
325
+ runAsyncTransition(fn);
326
+ }
327
+ /**
328
+ * Returns a `startTransition` bound to a pending setter: the setter is set to
329
+ * true when a transition starts and back to false once every transition
330
+ * started through it has settled (overlapping transitions keep it pending).
331
+ * Compiled `useTransition()` calls lower to this.
332
+ */
333
+ export function __krateTransitionStarter(setPending) {
334
+ let outstanding = 0;
335
+ return (fn) => {
336
+ outstanding++;
337
+ setPending(true);
338
+ const tr = runAsyncTransition(fn);
339
+ const done = () => {
340
+ if (--outstanding === 0)
341
+ setPending(false);
342
+ };
343
+ tr.promise.then(done, done);
344
+ };
345
+ }
346
+ /** `const [isPending, startTransition] = useTransition()`; isPending is a getter. */
347
+ export function useTransition() {
348
+ const [pending, setPending] = createSignal(false);
349
+ return [pending, __krateTransitionStarter(setPending)];
350
+ }
351
+ // React throttles reveals: content replacing a fallback is committed no
352
+ // sooner than FALLBACK_THROTTLE_MS after the most recent fallback appeared,
353
+ // so nested and sequential reveals do not flash. Krate uses React 19's value.
354
+ let fallbackThrottleMs = 300;
355
+ let lastFallbackAt = -Infinity;
356
+ function now() {
357
+ return typeof performance !== 'undefined' ? performance.now() : Date.now();
358
+ }
359
+ /** Records that a fallback became visible (starts the reveal throttle). */
360
+ export function noteFallbackShown() {
361
+ lastFallbackAt = now();
362
+ }
363
+ /** Sets the reveal throttle (React's FALLBACK_THROTTLE_MS); 0 disables it. */
364
+ export function setFallbackThrottle(ms) {
365
+ fallbackThrottleMs = ms;
366
+ }
367
+ class BoundaryController {
368
+ constructor(id, anchor, initialContent, apply) {
369
+ this.pending = new Set();
370
+ this.holds = 0;
371
+ this.scheduled = false;
372
+ this.throttle = null;
373
+ this.id = id;
374
+ this.anchor = anchor;
375
+ this.content = initialContent;
376
+ this.apply = apply;
377
+ }
378
+ get pendingCount() {
379
+ return this.pending.size;
380
+ }
381
+ showingContent() {
382
+ return this.content;
383
+ }
384
+ suspend(t, inTransition = false) {
385
+ if (inTransition && this.content) {
386
+ // Already revealed content stays visible during a transition; the
387
+ // transition waits for the work instead.
388
+ currentLane()?.wait(t);
389
+ return;
390
+ }
391
+ if (this.pending.has(t))
392
+ return;
393
+ this.pending.add(t);
394
+ this.update();
395
+ const done = () => {
396
+ this.pending.delete(t);
397
+ this.schedule();
398
+ };
399
+ t.then(done, done);
400
+ }
401
+ hold() {
402
+ this.holds++;
403
+ }
404
+ release() {
405
+ if (this.holds > 0)
406
+ this.holds--;
407
+ this.schedule();
408
+ }
409
+ schedule() {
410
+ if (this.scheduled)
411
+ return;
412
+ this.scheduled = true;
413
+ // Reveal after the current microtask batch: sibling retries and the
414
+ // effect flush of resolved values land first, so content appears filled.
415
+ queueMicrotask(() => {
416
+ queueMicrotask(() => {
417
+ this.scheduled = false;
418
+ this.update();
419
+ });
420
+ });
421
+ }
422
+ update() {
423
+ const want = this.pending.size === 0 && this.holds === 0;
424
+ if (want === this.content)
425
+ return;
426
+ if (want) {
427
+ const wait = lastFallbackAt + fallbackThrottleMs - now();
428
+ if (wait > 0) {
429
+ if (this.throttle === null) {
430
+ this.throttle = setTimeout(() => {
431
+ this.throttle = null;
432
+ this.update();
433
+ }, wait);
434
+ }
435
+ return;
436
+ }
437
+ }
438
+ else {
439
+ noteFallbackShown();
440
+ }
441
+ this.content = want;
442
+ this.apply(want);
443
+ // A reveal can expose a nested boundary that still shows its fallback.
444
+ if (want && onReveal)
445
+ onReveal(this);
446
+ }
447
+ }
448
+ let onReveal = null;
449
+ /**
450
+ * Creates a boundary controller over an arbitrary show/hide function. Used by
451
+ * the compiled boundary markers and the compat `<Suspense>` component, and
452
+ * exported for tests and custom integrations.
453
+ */
454
+ export function createBoundary(id, apply, options) {
455
+ return new BoundaryController(id, options?.anchor ?? null, options?.initialContent ?? true, apply);
456
+ }
457
+ const boundaries = new Map();
458
+ /** The template/marker id of a compiled boundary's conditional slot. */
459
+ export function boundarySlotId(id) {
460
+ return 's' + id;
461
+ }
462
+ /**
463
+ * Returns the boundary for a compiled `<!--suspense:ID-->` marker. The
464
+ * compiler emits the boundary's two states as a conditional slot: the active
465
+ * one between `<!--k:sID-->` markers and the other in a hoisted
466
+ * `<template data-kc="sID" data-kb="c|a">` (c = content, a = fallback).
467
+ */
468
+ export function getBoundary(id) {
469
+ const slot = boundarySlotId(id);
470
+ const g = globalThis;
471
+ const start = typeof g.findSlot === 'function' ? g.findSlot(slot) : null;
472
+ const existing = boundaries.get(id);
473
+ // After an SPA navigation the same id can name a boundary of the new page.
474
+ if (existing && (start === null || existing.anchor === start))
475
+ return existing;
476
+ const tpl = typeof document !== 'undefined'
477
+ ? document.querySelector('template[data-kc="' + slot + '"]')
478
+ : null;
479
+ // A template holding the content means the build rendered the fallback.
480
+ const initialContent = !tpl || tpl.getAttribute('data-kb') !== 'c';
481
+ // The boundary is a conditional slot: report its branch to the effect
482
+ // scheduler (when loaded) so effects of the content run in the commit after
483
+ // it is revealed and are cleaned up while it is hidden again.
484
+ const activity = globalThis.krateCondActivity;
485
+ const swap = start && start.nodeType === 8 ? boundaryDOM(start, tpl, initialContent) : null;
486
+ const apply = (show) => {
487
+ if (!swap)
488
+ return;
489
+ if (activity && !show)
490
+ activity(slot, 'a');
491
+ swap(show);
492
+ if (activity && show)
493
+ activity(slot, 'c');
494
+ };
495
+ const b = createBoundary(id, apply, { anchor: start, initialContent });
496
+ if (!initialContent && start && start.isConnected)
497
+ noteFallbackShown();
498
+ boundaries.set(id, b);
499
+ return b;
500
+ }
501
+ onReveal = (revealed) => {
502
+ for (const b of boundaries.values()) {
503
+ if (b !== revealed && !b.showingContent() && b.anchor && b.anchor.isConnected) {
504
+ noteFallbackShown();
505
+ return;
506
+ }
507
+ }
508
+ };
509
+ /**
510
+ * Shows the content or the fallback between a boundary's slot markers, the
511
+ * way React does: the first reveal takes the content out of its template;
512
+ * suspending revealed content again hides it in place (elements get
513
+ * `display: none !important`, text is emptied) and shows the fallback after
514
+ * it, so content state and DOM identity survive; revealing again restores it.
515
+ */
516
+ function boundaryDOM(start, tpl, initialContent) {
517
+ const endValue = '/' + (start.nodeValue || '');
518
+ const end = () => {
519
+ for (let n = start.nextSibling; n; n = n.nextSibling) {
520
+ if (n.nodeType === 8 && n.nodeValue === endValue)
521
+ return n;
522
+ }
523
+ return null;
524
+ };
525
+ const between = () => {
526
+ const out = [];
527
+ const stop = end();
528
+ for (let n = start.nextSibling; n && n !== stop; n = n.nextSibling)
529
+ out.push(n);
530
+ return out;
531
+ };
532
+ let content = initialContent ? between() : [];
533
+ let fallback = initialContent ? [] : between();
534
+ let tplTaken = false;
535
+ const fromTemplate = () => {
536
+ if (!tpl || tplTaken)
537
+ return [];
538
+ tplTaken = true;
539
+ return Array.from(tpl.content.childNodes);
540
+ };
541
+ const hidden = new Map();
542
+ const insert = (nodes) => {
543
+ const parent = start.parentNode;
544
+ if (!parent)
545
+ return;
546
+ const before = end();
547
+ for (const n of nodes)
548
+ parent.insertBefore(n, before);
549
+ };
550
+ const detach = (nodes) => {
551
+ for (const n of nodes)
552
+ n.parentNode?.removeChild(n);
553
+ };
554
+ return (show) => {
555
+ if (show) {
556
+ detach(fallback);
557
+ if (content.length === 0) {
558
+ content = fromTemplate();
559
+ insert(content);
560
+ refsEnter();
561
+ return;
562
+ }
563
+ for (const n of content) {
564
+ const saved = hidden.get(n);
565
+ if (saved === undefined)
566
+ continue;
567
+ if (typeof saved === 'string')
568
+ n.nodeValue = saved;
569
+ else if (saved[0] === '')
570
+ n.style.removeProperty('display');
571
+ else
572
+ n.style.setProperty('display', saved[0], saved[1]);
573
+ }
574
+ hidden.clear();
575
+ return;
576
+ }
577
+ for (const n of content) {
578
+ if (hidden.has(n))
579
+ continue;
580
+ if (n.nodeType === 1 && n.style) {
581
+ const style = n.style;
582
+ hidden.set(n, [style.getPropertyValue('display'), style.getPropertyPriority('display')]);
583
+ style.setProperty('display', 'none', 'important');
584
+ }
585
+ else if (n.nodeType === 3) {
586
+ hidden.set(n, n.nodeValue || '');
587
+ n.nodeValue = '';
588
+ }
589
+ }
590
+ if (fallback.length === 0)
591
+ fallback = fromTemplate();
592
+ insert(fallback);
593
+ refsEnter();
594
+ };
595
+ }
596
+ // refsEnter attaches the refs of elements that just entered the document
597
+ // (refs.ts holds refs of detached nodes until then), so a form action or ref
598
+ // in content revealed from its template is bound.
599
+ function refsEnter() {
600
+ const enter = globalThis.krateRefsEnter;
601
+ if (typeof enter === 'function')
602
+ enter();
603
+ }
604
+ /** Registers a boundary under its id so compiled runs can find it. */
605
+ export function registerBoundary(boundary) {
606
+ boundaries.set(boundary.id, boundary);
607
+ }
608
+ /** Forgets compiled boundaries (SPA navigation re-hydrates a new page). */
609
+ export function resetBoundaries() {
610
+ boundaries.clear();
611
+ }
612
+ /**
613
+ * Suspends `boundary` on `t`. Inside a transition an already revealed
614
+ * boundary keeps its content and the transition waits instead; with no
615
+ * boundary the work only extends the active transition.
616
+ */
617
+ export function suspendOn(boundary, t) {
618
+ const inTransition = currentLane() !== null;
619
+ if (boundary)
620
+ boundary.suspend(t, inTransition);
621
+ else if (inTransition)
622
+ currentLane()?.wait(t);
623
+ }
624
+ let currentRun = null;
625
+ /** The boundary of the component whose hydration is running, if any. */
626
+ export function currentBoundary() {
627
+ return currentRun ? currentRun.boundary : null;
628
+ }
629
+ /**
630
+ * Runs a component's hydration code inside the boundary `id` (or none). A
631
+ * pending `use()` during the run throws; the run is disposed and repeated
632
+ * when the promise settles, with earlier promises reused by position. Other
633
+ * errors go to the error handler (see {@link setSuspenseErrorHandler}).
634
+ */
635
+ export function __krateBoundary(id, fn) {
636
+ const boundary = id ? getBoundary(id) : null;
637
+ const state = { boundary, scope: { list: [], i: 0 }, disposers: [] };
638
+ const errOwner = errorOwner();
639
+ boundary?.hold();
640
+ const attempt = () => {
641
+ state.scope.i = 0;
642
+ const prev = currentRun;
643
+ currentRun = state;
644
+ // A retry runs later, outside the hydration script: keep the effect
645
+ // owner it declares from leaking into unrelated code.
646
+ const owner = krateGetOwner();
647
+ try {
648
+ // Reads made directly in the body (not through __krateUse) replay too.
649
+ withReadScope(state.scope, fn);
650
+ currentRun = prev;
651
+ krateSetOwner(owner);
652
+ boundary?.release();
653
+ }
654
+ catch (error) {
655
+ currentRun = prev;
656
+ krateSetOwner(owner);
657
+ for (const dispose of state.disposers.splice(0))
658
+ dispose();
659
+ if (isSuspenseSignal(error)) {
660
+ error.thenable.then(attempt, attempt);
661
+ return;
662
+ }
663
+ boundary?.release();
664
+ reportSuspenseError(error, boundary, errOwner);
665
+ }
666
+ };
667
+ attempt();
668
+ }
669
+ /**
670
+ * The compiled form of `const value = use(...)`: `__krateUse(() => expr)`
671
+ * where every `use(x)` inside `expr` became `__krateRead(x)`. Returns a
672
+ * getter.
673
+ *
674
+ * The first evaluation runs synchronously: a pending promise suspends the
675
+ * whole component run (see {@link __krateBoundary}). Later re-evaluations (a
676
+ * signal read by `expr` changed, for example a new promise in state) keep the
677
+ * previous value while the new promise is pending and suspend the boundary:
678
+ * outside a transition it shows the fallback again, inside a transition it
679
+ * keeps the old content.
680
+ */
681
+ export function __krateUse(compute) {
682
+ const run = currentRun;
683
+ const boundary = run ? run.boundary : null;
684
+ const errOwner = errorOwner();
685
+ const scope = run ? run.scope : { list: [], i: 0 };
686
+ const start = scope.i;
687
+ const initial = withReadScope(scope, compute);
688
+ const own = scope.list.slice(start, scope.i);
689
+ const [get, set] = createSignal(initial);
690
+ const [version, setVersion] = createSignal(0);
691
+ const bump = () => setVersion((v) => v + 1);
692
+ let first = true;
693
+ const dispose = createEffect(() => {
694
+ version();
695
+ const replay = first ? { list: own, i: 0 } : null;
696
+ first = false;
697
+ try {
698
+ const next = withReadScope(replay, compute);
699
+ set(() => next);
700
+ }
701
+ catch (error) {
702
+ if (isSuspenseSignal(error)) {
703
+ error.thenable.then(bump, bump);
704
+ suspendOn(boundary, error.thenable);
705
+ return;
706
+ }
707
+ reportSuspenseError(error, boundary, errOwner);
708
+ }
709
+ });
710
+ if (run)
711
+ run.disposers.push(dispose);
712
+ return get;
713
+ }
714
+ /** `use(x)` inside a `__krateUse` computation. */
715
+ export function __krateRead(value) {
716
+ return readValue(value);
717
+ }
718
+ // Lazy hydration chunks
719
+ const lazyLoads = new Map();
720
+ /**
721
+ * Loads the hydration chunk of a `lazy()` component. The component's HTML was
722
+ * rendered at build time, so the content stays visible while its code loads
723
+ * (as with React hydrating server-rendered lazy content); the boundary is
724
+ * held so a boundary that is still showing its fallback reveals together with
725
+ * the lazy content. Loading starts when the page hydrates, the first point the
726
+ * component is rendered on the client. A failed load is reported to the
727
+ * nearest error boundary.
728
+ */
729
+ export function __krateLazy(url, boundaryId) {
730
+ const boundary = boundaryId ? getBoundary(boundaryId) : null;
731
+ const errOwner = errorOwner();
732
+ boundary?.hold();
733
+ let load = lazyLoads.get(url);
734
+ if (!load) {
735
+ // React starts loading a lazy component when it first renders: a boundary
736
+ // inside a hidden branch waits until the branch is shown.
737
+ const anchor = boundary ? boundary.anchor : null;
738
+ load =
739
+ anchor && !anchor.isConnected
740
+ ? whenConnected(anchor).then(() => {
741
+ // The fallback just became visible.
742
+ noteFallbackShown();
743
+ return importChunk(url);
744
+ })
745
+ : importChunk(url);
746
+ lazyLoads.set(url, load);
747
+ }
748
+ load.then(() => boundary?.release(), (error) => {
749
+ boundary?.release();
750
+ reportSuspenseError(error, boundary, errOwner);
751
+ });
752
+ return load;
753
+ }
754
+ // whenConnected resolves once node is attached to the document.
755
+ function whenConnected(node) {
756
+ if (node.isConnected || typeof MutationObserver === 'undefined')
757
+ return Promise.resolve();
758
+ return new Promise((resolve) => {
759
+ const observer = new MutationObserver(() => {
760
+ if (!node.isConnected)
761
+ return;
762
+ observer.disconnect();
763
+ resolve();
764
+ });
765
+ observer.observe(document.documentElement, { childList: true, subtree: true });
766
+ });
767
+ }
768
+ const lazyPayloads = new WeakMap();
769
+ /**
770
+ * The module promise of a lazy() whose loader is not a static import. The
771
+ * loader is called once, when the component first hydrates; it must resolve
772
+ * to a module whose default export is a component.
773
+ */
774
+ export function __krateLazyPayload(loader) {
775
+ let payload = lazyPayloads.get(loader);
776
+ if (!payload) {
777
+ payload = Promise.resolve()
778
+ .then(() => loader())
779
+ .then((mod) => {
780
+ const impl = mod && typeof mod === 'object' ? mod.default : undefined;
781
+ if (typeof impl !== 'function') {
782
+ throw new Error('lazy: the loader did not resolve to a module with a component as its default export (resolve to { default: Component })');
783
+ }
784
+ return mod;
785
+ });
786
+ trackThenable(payload);
787
+ lazyPayloads.set(loader, payload);
788
+ }
789
+ return payload;
790
+ }
791
+ let chunkImporter = (url) => import(/* @vite-ignore */ url);
792
+ /** Overrides how lazy chunks are fetched (tests, custom loaders). */
793
+ export function setLazyChunkImporter(fn) {
794
+ chunkImporter = fn;
795
+ }
796
+ function importChunk(url) {
797
+ try {
798
+ return Promise.resolve(chunkImporter(url));
799
+ }
800
+ catch (error) {
801
+ return Promise.reject(error);
802
+ }
803
+ }
804
+ /** Entry point of a lazy hydration chunk: runs the chunk's component code. */
805
+ export function __krateLazyRun(fn) {
806
+ fn();
807
+ }
808
+ // Deferred values and external stores
809
+ function scheduleDeferred(fn) {
810
+ setTimeout(fn, 0);
811
+ }
812
+ /**
813
+ * React's `useDeferredValue(value, initialValue?)` as a getter. During an
814
+ * urgent update the getter keeps returning the previous value and catches up
815
+ * in a later task (a `setTimeout(0)` after the update), so urgent DOM work
816
+ * lands first. With `initialValue` the first value is `initialValue` and the
817
+ * real value follows the same way (React 19). Updates made inside a
818
+ * transition are not deferred again.
819
+ */
820
+ export function createDeferredValue(get, ...initial) {
821
+ const hasInitial = initial.length > 0;
822
+ let latest;
823
+ let current;
824
+ let timer = false;
825
+ const [deferred, setDeferred] = createSignal(undefined);
826
+ const flush = () => {
827
+ timer = false;
828
+ if (!Object.is(latest, current)) {
829
+ current = latest;
830
+ setDeferred(() => latest);
831
+ }
832
+ };
833
+ let first = true;
834
+ createEffect(() => {
835
+ latest = get();
836
+ if (first) {
837
+ first = false;
838
+ current = hasInitial ? initial[0] : latest;
839
+ setDeferred(() => current);
840
+ if (!hasInitial || Object.is(current, latest))
841
+ return;
842
+ }
843
+ if (Object.is(latest, current))
844
+ return;
845
+ if (isInTransition()) {
846
+ flush();
847
+ return;
848
+ }
849
+ if (!timer) {
850
+ timer = true;
851
+ scheduleDeferred(flush);
852
+ }
853
+ });
854
+ return deferred;
855
+ }
856
+ /** React's `useDeferredValue` for compat callers: wraps a getter or a value. */
857
+ export function useDeferredValue(value, ...initial) {
858
+ if (typeof value === 'function')
859
+ return createDeferredValue(value, ...initial);
860
+ return value;
861
+ }
862
+ /**
863
+ * React's `useSyncExternalStore` as a getter. Subscribes once, re-reads the
864
+ * snapshot on every store notification (and once right after subscribing, to
865
+ * catch changes between the first read and the subscription), stores the
866
+ * snapshot only when it changed by `Object.is`, and unsubscribes when the
867
+ * component is torn down. `getServerSnapshot` is what the build renders;
868
+ * the client hydrates from `getSnapshot`.
869
+ */
870
+ export function createExternalStore(subscribe, getSnapshot, _getServerSnapshot) {
871
+ let value = getSnapshot();
872
+ if (!Object.is(value, getSnapshot())) {
873
+ console.error('[krate] The result of getSnapshot should be cached to avoid an infinite loop');
874
+ }
875
+ const [get, set] = createSignal(value);
876
+ const check = () => {
877
+ const next = getSnapshot();
878
+ if (!Object.is(next, value)) {
879
+ value = next;
880
+ set(() => next);
881
+ }
882
+ };
883
+ const unsubscribe = subscribe(check);
884
+ check();
885
+ onCleanup(() => {
886
+ if (typeof unsubscribe === 'function')
887
+ unsubscribe();
888
+ });
889
+ return get;
890
+ }
891
+ /** React's `useSyncExternalStore` (getter result). */
892
+ export function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
893
+ return createExternalStore(subscribe, getSnapshot, getServerSnapshot);
894
+ }
895
+ connectActionTransitions();
896
+ // Lets createResource (in the core bundle) suspend the creating component's
897
+ // boundary without importing this module.
898
+ globalThis.__krateSuspenseHook = {
899
+ current: currentBoundary,
900
+ suspend: (boundary, promise) => suspendOn(boundary, promise),
901
+ };