what-core 0.14.0 → 0.15.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 (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -38
  3. package/a11y.d.ts +128 -0
  4. package/data.d.ts +294 -0
  5. package/dist/a11y.js +510 -0
  6. package/dist/a11y.min.js +413 -0
  7. package/dist/actions.js +158 -0
  8. package/dist/actions.min.js +112 -0
  9. package/dist/animation.js +481 -0
  10. package/dist/animation.min.js +295 -0
  11. package/dist/async.js +180 -0
  12. package/dist/async.min.js +134 -0
  13. package/dist/components.js +577 -0
  14. package/dist/components.min.js +413 -0
  15. package/dist/data.js +1212 -0
  16. package/dist/data.min.js +918 -0
  17. package/dist/diagnostics.js +187 -0
  18. package/dist/diagnostics.min.js +134 -0
  19. package/dist/dom.js +796 -0
  20. package/dist/dom.min.js +603 -0
  21. package/dist/entries/a11y.js +43 -0
  22. package/dist/entries/a11y.min.js +43 -0
  23. package/dist/entries/data.js +29 -0
  24. package/dist/entries/data.min.js +29 -0
  25. package/dist/entries/dom.js +45 -0
  26. package/dist/entries/dom.min.js +45 -0
  27. package/dist/entries/form.js +31 -0
  28. package/dist/entries/form.min.js +31 -0
  29. package/dist/entries/internal.js +123 -0
  30. package/dist/entries/internal.min.js +123 -0
  31. package/dist/entries/motion.js +23 -0
  32. package/dist/entries/motion.min.js +23 -0
  33. package/dist/entries/ui.js +25 -0
  34. package/dist/entries/ui.min.js +25 -0
  35. package/dist/env.js +5 -0
  36. package/dist/env.min.js +5 -0
  37. package/dist/errors.js +1518 -0
  38. package/dist/errors.min.js +548 -0
  39. package/dist/form.js +936 -0
  40. package/dist/form.min.js +703 -0
  41. package/dist/guardrails.js +84 -0
  42. package/dist/guardrails.min.js +55 -0
  43. package/dist/h.js +232 -0
  44. package/dist/h.min.js +171 -0
  45. package/dist/head.js +241 -0
  46. package/dist/head.min.js +207 -0
  47. package/dist/helpers.js +126 -0
  48. package/dist/helpers.min.js +98 -0
  49. package/dist/hooks.js +255 -0
  50. package/dist/hooks.min.js +153 -0
  51. package/dist/hot.js +215 -0
  52. package/dist/hot.min.js +24 -0
  53. package/dist/hydration-data.js +495 -0
  54. package/dist/hydration-data.min.js +371 -0
  55. package/dist/import-changes.js +273 -0
  56. package/dist/import-changes.min.js +272 -0
  57. package/dist/index.js +95 -0
  58. package/dist/index.min.js +95 -227
  59. package/dist/jsx-dev-runtime.js +10 -0
  60. package/dist/jsx-dev-runtime.min.js +10 -1
  61. package/dist/jsx-runtime.js +27 -0
  62. package/dist/jsx-runtime.min.js +15 -1
  63. package/dist/live.js +54 -0
  64. package/dist/live.min.js +49 -0
  65. package/dist/markup-rules.js +250 -0
  66. package/dist/markup-rules.min.js +213 -0
  67. package/dist/reactive.js +3334 -0
  68. package/dist/reactive.min.js +2033 -0
  69. package/dist/render.js +4746 -0
  70. package/dist/render.min.js +2797 -1
  71. package/dist/scheduler.js +225 -0
  72. package/dist/scheduler.min.js +162 -0
  73. package/dist/selector.js +11 -0
  74. package/dist/selector.min.js +10 -0
  75. package/dist/server-context.js +148 -0
  76. package/dist/server-context.min.js +121 -0
  77. package/dist/skeleton.js +342 -0
  78. package/dist/skeleton.min.js +310 -0
  79. package/dist/store.js +72 -0
  80. package/dist/store.min.js +50 -0
  81. package/dist/testing.js +720 -0
  82. package/dist/testing.min.js +458 -1
  83. package/dist/vnode-adoption.js +19 -0
  84. package/dist/vnode-adoption.min.js +19 -0
  85. package/dist/vnode-renderer.js +61 -0
  86. package/dist/vnode-renderer.min.js +47 -0
  87. package/dom.d.ts +44 -0
  88. package/form.d.ts +218 -0
  89. package/hot.d.ts +35 -0
  90. package/index.d.ts +421 -736
  91. package/internal.d.ts +284 -0
  92. package/jsx-runtime.d.ts +160 -137
  93. package/markup-rules.d.ts +83 -0
  94. package/motion.d.ts +156 -0
  95. package/package.json +117 -3
  96. package/render.d.ts +278 -29
  97. package/src/a11y.js +64 -59
  98. package/src/actions.js +226 -0
  99. package/src/animation.js +105 -57
  100. package/src/async.js +259 -0
  101. package/src/components.js +495 -144
  102. package/src/data.js +1410 -1159
  103. package/src/diagnostics.js +263 -0
  104. package/src/dom.js +1159 -872
  105. package/src/entries/a11y.js +24 -0
  106. package/src/entries/data.js +17 -0
  107. package/src/entries/dom.js +29 -0
  108. package/src/entries/form.js +16 -0
  109. package/src/entries/internal.js +63 -0
  110. package/src/entries/motion.js +13 -0
  111. package/src/entries/ui.js +13 -0
  112. package/src/env-development.js +12 -0
  113. package/src/env.js +33 -0
  114. package/src/errors.js +1144 -168
  115. package/src/form.js +723 -225
  116. package/src/guardrails.js +38 -126
  117. package/src/h.js +227 -152
  118. package/src/head.js +189 -19
  119. package/src/helpers.js +47 -75
  120. package/src/hooks.js +233 -248
  121. package/src/hot.js +316 -0
  122. package/src/hydration-data.js +859 -16
  123. package/src/import-changes.js +156 -0
  124. package/src/index.js +38 -188
  125. package/src/jsx-dev-runtime.js +7 -14
  126. package/src/jsx-runtime.js +25 -9
  127. package/src/live.js +80 -0
  128. package/src/markup-rules.js +387 -0
  129. package/src/reactive.js +4400 -862
  130. package/src/render.js +6502 -2570
  131. package/src/scheduler.js +56 -21
  132. package/src/selector.js +31 -0
  133. package/src/server-context.js +252 -22
  134. package/src/skeleton.js +22 -12
  135. package/src/store.js +17 -31
  136. package/src/testing.js +389 -63
  137. package/src/vnode-adoption.js +48 -0
  138. package/src/vnode-renderer.js +114 -0
  139. package/testing.d.ts +81 -1
  140. package/ui.d.ts +20 -0
  141. package/dist/chunk-6YOUZ6T4.min.js +0 -1
  142. package/dist/chunk-FN6HXME3.min.js +0 -11
  143. package/dist/chunk-VKZY7JPN.min.js +0 -1
  144. package/src/agent-context.js +0 -127
  145. package/src/warnings.js +0 -193
package/src/components.js CHANGED
@@ -1,74 +1,107 @@
1
1
  // What Framework - Component Utilities
2
2
  // memo, lazy, Suspense, ErrorBoundary
3
3
 
4
- import { h } from './h.js';
5
- import { signal, __DEV__ } from './reactive.js';
4
+ import { h, _vnode, lowered } from './h.js';
5
+ import {
6
+ signal, effect, untrack, getOwner, runWithOwner, createRoot, onCleanup, _handleError, _isDisposed, HANDLED,
7
+ _trackWork, _beginWork, _retryErrors, _errorSource, _setUserEffectGate, _releaseUserEffect,
8
+ _committingTransition, __DEV__, __devtools,
9
+ } from './reactive.js';
10
+ import { report, recordObservation } from './diagnostics.js';
6
11
  import { isServerRender } from './server-context.js';
7
-
8
- // Legacy errorBoundaryStack removed — tree-based resolution via _parentCtx._errorBoundary
9
- // is now the only mechanism. See reportError() below.
12
+ import { hydrate, insert, _enableSuspense, _hydrationErrorHook, _toFunctionComponent, _withCursor } from './render.js';
13
+ import { createDOM, _handleNavigationSignal, _place } from './dom.js';
14
+ import { _islandHost } from './hydration-data.js';
10
15
 
11
16
  // --- memo ---
12
17
  // In the run-once model, components execute exactly once and never re-render.
13
18
  // Signals update the DOM directly via fine-grained effects. Therefore, memo()
14
19
  // is a no-op identity wrapper — there is no re-render to skip.
15
- // Kept for API compatibility with React-style code.
20
+ // Kept for API compatibility with React-style code. A class component is run
21
+ // through the bridge compiled JSX and h() run one through
22
+ // (render.js _toFunctionComponent): called as a function it would throw.
16
23
 
17
24
  export function memo(Component, _areEqual) {
25
+ const render = _toFunctionComponent(Component);
18
26
  // No-op in run-once model — just return the component as-is
19
27
  const MemoWrapper = function MemoWrapper(props) {
20
- return Component(props);
28
+ return render(props);
21
29
  };
22
30
  MemoWrapper.displayName = `Memo(${Component.name || 'Anonymous'})`;
23
31
  return MemoWrapper;
24
32
  }
25
33
 
26
- // Injected by dom.js
27
- /** @type {(() => any) | null} */
28
- let _getCurrentComponent = null;
29
- export function _injectGetCurrentComponent(fn) { _getCurrentComponent = fn; }
30
-
31
- export function shallowEqual(a, b) {
32
- if (a === b) return true;
33
- const keysA = Object.keys(a);
34
- const keysB = Object.keys(b);
35
- if (keysA.length !== keysB.length) return false;
36
- for (const key of keysA) {
37
- if (!Object.is(a[key], b[key])) return false;
38
- }
39
- return true;
40
- }
41
-
42
34
  // --- lazy ---
43
- // Code-split a component. Returns a wrapper that loads on first render.
35
+ // Code-split a component. Returns a wrapper that loads on first render, and
36
+ // keeps what it loaded for good. A download that failed is shown to the
37
+ // renders that waited on it (the nearest error boundary gets its error), and
38
+ // then forgotten: the next render (an error boundary's reset, the component
39
+ // rendered again) downloads again, as does the next navigation to its route
40
+ // (`_load`, which what-router's navigation waits on, and its prefetch
41
+ // starts). A navigation waits on behalf of the page it renders, which shows
42
+ // the failure; a download only a prefetch started is no render's, so its
43
+ // failure is forgotten at once and the first render after it downloads
44
+ // again. React's lazy keeps the error until the page is reloaded.
44
45
 
45
46
  export function lazy(loader) {
47
+ _enableSuspense();
46
48
  let Component = null;
47
- let loadPromise = null;
48
- let loadError = null;
49
+ // The download in flight, or the last one; `failed` holds the error of the
50
+ // last one until it has been shown. `awaited`: a render or a navigation
51
+ // waits on the download in flight, and shows its failure.
52
+ /** @type {Promise<void> | null} */
53
+ let loading = null;
54
+ /** @type {{ error: any } | null} */
55
+ let failed = null;
56
+ let awaited = false;
49
57
  const listeners = new Set();
50
58
 
59
+ // A download, which settles once the module has loaded or the download has
60
+ // failed (a loader that throws included): never with the failure, which a
61
+ // render shows.
62
+ function load() {
63
+ failed = null;
64
+ awaited = false;
65
+ const download = loading = new Promise((resolve) => resolve(loader())).then((mod) => {
66
+ Component = mod.default || mod;
67
+ // Notify all waiting instances
68
+ listeners.forEach(fn => fn());
69
+ listeners.clear();
70
+ }, (error) => {
71
+ if (awaited) failed = { error };
72
+ else if (loading === download) loading = null;
73
+ });
74
+ return download;
75
+ }
76
+
51
77
  function LazyWrapper(props) {
52
- if (loadError) throw loadError;
53
78
  if (Component) return h(Component, props);
54
-
55
- if (!loadPromise) {
56
- loadPromise = loader()
57
- .then(mod => {
58
- Component = mod.default || mod;
59
- // Notify all waiting instances
60
- listeners.forEach(fn => fn());
61
- listeners.clear();
62
- })
63
- .catch(err => { loadError = err; });
79
+ if (failed !== null) {
80
+ // Every render that waited on the download is rendered again in the
81
+ // same turn and shows its error; after that turn it is forgotten.
82
+ const shown = failed;
83
+ queueMicrotask(() => {
84
+ if (failed === shown) failed = loading = null;
85
+ });
86
+ throw shown.error;
64
87
  }
65
-
66
88
  // Throw promise for Suspense to catch
67
- throw loadPromise;
89
+ if (loading === null) load();
90
+ awaited = true;
91
+ throw loading;
68
92
  }
69
93
 
70
94
  LazyWrapper.displayName = 'Lazy';
71
95
  LazyWrapper._lazy = true;
96
+ // What a navigation to it waits for: the download in flight, or a new one
97
+ // (none yet, or the last one failed); null once loaded. A prefetch's
98
+ // download (`prefetch` true) is not waited on.
99
+ LazyWrapper._load = (prefetch) => {
100
+ if (Component) return null;
101
+ if (loading === null || failed !== null) load();
102
+ if (!prefetch) awaited = true;
103
+ return loading;
104
+ };
72
105
  LazyWrapper._onLoad = (fn) => {
73
106
  if (Component) fn();
74
107
  else listeners.add(fn);
@@ -76,62 +109,283 @@ export function lazy(loader) {
76
109
  return LazyWrapper;
77
110
  }
78
111
 
112
+ // A boundary's context only exists once the vnode renderer builds it
113
+ // (createSuspenseBoundary / createErrorBoundary), so compiled children must
114
+ // not be built while the boundary function runs: it receives the children
115
+ // factory instead. See _installLazyChildren. Marked through a call rather than
116
+ // a top-level statement so a bundle that never uses the boundary drops it, and
117
+ // the vnode renderer with it.
118
+ function deferChildren(Component) {
119
+ Component._deferChildren = true;
120
+ return Component;
121
+ }
122
+
79
123
  // --- Suspense ---
80
- // Show fallback while children are loading (lazy components).
81
- // Works with lazy() and async components.
82
-
83
- export function Suspense({ fallback, children }) {
84
- const loading = signal(false);
85
- const pendingPromises = new Set();
86
- let failed = false;
87
-
88
- // Suspense boundary marker
89
- const boundary = {
90
- _suspense: true,
91
- onSuspend(promise) {
92
- if (failed) return;
93
- loading.set(true);
94
- pendingPromises.add(promise);
95
- // Rejection is handled separately from fulfilment. Clearing the fallback
96
- // on a rejection re-renders the child, which suspends on the same
97
- // rejected thenable again, forever. Latch the failure and stay put.
98
- promise.then(
99
- () => {
100
- pendingPromises.delete(promise);
101
- if (pendingPromises.size === 0) {
102
- loading.set(false);
103
- }
104
- },
105
- (err) => {
106
- failed = true;
107
- pendingPromises.delete(promise);
108
- console.error('[what] Suspense: a suspended child rejected:', err);
109
- },
110
- );
111
- },
124
+ // <Suspense fallback>: shows `fallback` until its children have first shown.
125
+ // The children are built once, out of the document, under an owner whose
126
+ // `_onPending` handler hears of every binding or effect held on a value that
127
+ // has not landed, and every component that suspended (threw a promise: lazy(),
128
+ // use(), a not-ready read in its body, which render.js renders again in place
129
+ // once it settles). A held binding counts until a run of it completes (a
130
+ // value computed from another async value keeps it waiting through that
131
+ // value's own fetch), fails, or it is disposed; a suspended component until it
132
+ // has rendered again, or its place is gone. While any of them waits, the
133
+ // fallback stands in; when none does, after the flush that let the last one
134
+ // go, the children's DOM is moved in and the boundary is revealed. settled()
135
+ // counts that reveal as work, so it resolves after the effects it releases
136
+ // have run.
137
+ //
138
+ // After that, async values never bring the fallback back: a refresh keeps the
139
+ // children mounted, their bindings hold what they show until the new value
140
+ // lands, and a binding or component that waits on a value later renders
141
+ // nothing in the meantime. A component that suspends on any other promise (a
142
+ // lazy() chunk, use(promise)) does, as in React: the children's DOM is moved
143
+ // out, still mounted, while the fallback shows, and back once what the
144
+ // boundary waits for has settled. onMount and useEffect under a boundary that
145
+ // is not showing its children first run when it does.
146
+ //
147
+ // The vnode carries the boundary, and the boundary its client renderer
148
+ // (`mount`), so a bundle that never uses Suspense does not carry it. A
149
+ // renderer sets `show` and `conceal`, which move the children in and out;
150
+ // hydration (render.js hydrateSuspense) sets them too, and tells the boundary
151
+ // when the walk of its children is over (`walked`).
152
+
153
+ // `fallback` is read where it is shown, never while Suspense runs: JSX passed
154
+ // as the fallback is built there (dom.js _installLazyChildren), so while
155
+ // hydrating it claims the server's fallback.
156
+ export const Suspense = /* @__PURE__ */ deferChildren(function Suspense(props) {
157
+ const b = createSuspense(props);
158
+ const children = props.children;
159
+ return _vnode('__suspense', { get fallback() { return b.fallback; }, boundary: b }, Array.isArray(children) ? children : [children]);
160
+ });
161
+
162
+ // Boundaries built and not revealed yet; the user-effect gate looks only while
163
+ // there is one.
164
+ let unrevealed = 0;
165
+
166
+ // A user-phase effect created under a boundary that has not revealed waits for
167
+ // it: the outermost such boundary, which hands it on to the next one that
168
+ // still has not, if any, when it reveals.
169
+ function gateUserEffect(e) {
170
+ if (unrevealed === 0) return false;
171
+ /** @type {any} */
172
+ let target = null;
173
+ for (let o = e.owner; o != null; o = o.owner) {
174
+ const b = o._suspense;
175
+ if (b !== undefined && !b.revealed) target = b;
176
+ }
177
+ if (target === null) return false;
178
+ target.deferred.push(e);
179
+ return true;
180
+ }
181
+
182
+ // A promise a component suspended on is the app's: it reaches the boundary
183
+ // through `link`, which the boundary empties when it goes, so one that never
184
+ // settles keeps nothing of it. Its own scope, so the callbacks hold `link` and
185
+ // nothing else.
186
+ function awaitSuspended(waiting, link) {
187
+ const done = () => {
188
+ const b = link.b;
189
+ if (b === null) return;
190
+ b.links.delete(link);
191
+ b.thenables--;
192
+ b.check();
112
193
  };
194
+ waiting.then(done, done);
195
+ }
113
196
 
114
- return {
115
- tag: '__suspense',
116
- props: { boundary, fallback, loading },
117
- children: Array.isArray(children) ? children : [children],
118
- _vnode: true,
197
+ function createSuspense(props) {
198
+ _enableSuspense();
199
+ const b = {
200
+ get fallback() { return _place(props, 'fallback'); },
201
+ revealed: false,
202
+ hydrating: false,
203
+ /** @type {Set<any>} held effects and bindings that have not completed a run since */
204
+ waiting: new Set(),
205
+ /** promises of suspended components not settled yet */
206
+ thenables: 0,
207
+ /** @type {Set<{ b: any }>} what each of those promises reaches the boundary through */
208
+ links: new Set(),
209
+ /** @type {any[]} user-phase effects waiting for the reveal */
210
+ deferred: [],
211
+ /** @type {(() => void) | null} */
212
+ show: null,
213
+ /** @type {(() => void) | null} */
214
+ conceal: null,
215
+ attached: false,
216
+ queued: false,
217
+ // `waiting` is a promise a component suspended on, or an effect or
218
+ // binding held on a value that is not ready. For an effect it counts,
219
+ // it returns the function the engine calls when the effect stops waiting.
220
+ onPending(waiting) {
221
+ if (b.revealed) {
222
+ if (waiting.showsFallback !== true) return null;
223
+ if (__DEV__ && _committingTransition()) report('ERR_SUSPEND_IN_TRANSITION', { data: { component: waiting.component } });
224
+ b.revealed = false;
225
+ unrevealed++;
226
+ // The component is being built inside a region that is running; the
227
+ // fallback goes in once that run is over, unless the boundary has
228
+ // shown its children again, or gone, by then.
229
+ queueMicrotask(() => {
230
+ if (!b.revealed && b.conceal !== null) b.conceal();
231
+ });
232
+ }
233
+ if (__DEV__) recordObservation(__devtools, 'suspense:waiting', b, /** @type {any} */ (b).devOwner);
234
+ if (typeof waiting.then !== 'function') {
235
+ b.waiting.add(waiting);
236
+ return b.release;
237
+ }
238
+ // It settles once the component has rendered again (or its place is
239
+ // gone): that render's own waits are counted by now.
240
+ b.thenables++;
241
+ _trackWork(waiting);
242
+ const link = { b };
243
+ b.links.add(link);
244
+ awaitSuspended(waiting, link);
245
+ return null;
246
+ },
247
+ // A counted effect completed a run, failed, or was disposed. Look again
248
+ // after the flush that is running (or the current task), when every
249
+ // binding that runs in it has run, and count the look as work settled()
250
+ // waits for.
251
+ release(e) {
252
+ b.waiting.delete(e);
253
+ b.schedule();
254
+ },
255
+ schedule() {
256
+ if (b.queued || b.revealed) return;
257
+ b.queued = true;
258
+ const done = _beginWork();
259
+ queueMicrotask(() => {
260
+ b.queued = false;
261
+ b.check();
262
+ done();
263
+ });
264
+ },
265
+ check() {
266
+ if (b.revealed || b.hydrating) return;
267
+ for (const e of b.waiting) if (_isDisposed(e)) b.waiting.delete(e);
268
+ if (b.waiting.size === 0 && b.thenables === 0) b.reveal();
269
+ },
270
+ reveal() {
271
+ b.revealed = true;
272
+ if (__DEV__) recordObservation(__devtools, 'suspense:revealed', b, /** @type {any} */ (b).devOwner);
273
+ unrevealed--;
274
+ if (b.show !== null) b.show();
275
+ const deferred = b.deferred;
276
+ b.deferred = [];
277
+ for (const e of deferred) if (!gateUserEffect(e)) _releaseUserEffect(e);
278
+ },
279
+ // Start counting: the children are about to be built under `root`.
280
+ attach(root, hydrating) {
281
+ root._onPending = b.onPending;
282
+ root._suspense = b;
283
+ if (b.revealed || b.attached) return;
284
+ b.attached = true;
285
+ b.hydrating = hydrating;
286
+ unrevealed++;
287
+ _setUserEffectGate(gateUserEffect);
288
+ // Until the boundary itself goes: hydration replaces the arm `root` holds.
289
+ runWithOwner(root.owner, () => onCleanup(() => {
290
+ for (const link of b.links) link.b = null;
291
+ b.links.clear();
292
+ if (!b.revealed) {
293
+ b.revealed = true;
294
+ if (__DEV__) recordObservation(__devtools, 'suspense:disposed', b);
295
+ unrevealed--;
296
+ }
297
+ }));
298
+ },
299
+ // Hydration: the children have been walked. The server's content is on
300
+ // screen unless a component suspended, so that is the reveal; a binding
301
+ // waiting for a value only the client fetches keeps the server's content
302
+ // up meanwhile.
303
+ walked() {
304
+ b.hydrating = false;
305
+ if (b.thenables === 0) {
306
+ b.waiting.clear();
307
+ if (!b.revealed) b.reveal();
308
+ }
309
+ },
310
+ mount: mountSuspense,
119
311
  };
312
+ if (__DEV__) /** @type {any} */ (b).devOwner = getOwner();
313
+ return b;
120
314
  }
121
315
 
122
- // The boundary context only exists once createSuspenseBoundary runs, so
123
- // compiled children must not be built during this call. See createComponent.
124
- Suspense._deferChildren = true;
316
+ // Build `vnodes` before `end` in a root of their own; returns its disposer.
317
+ function buildArm(vnodes, end) {
318
+ return createRoot((dispose) => {
319
+ for (const v of Array.isArray(vnodes) ? vnodes : [vnodes]) {
320
+ const node = createDOM(v, end.parentNode);
321
+ if (node) end.parentNode.insertBefore(node, end);
322
+ }
323
+ return dispose;
324
+ });
325
+ }
125
326
 
126
- // --- ErrorBoundary ---
127
- // Catch errors in children and show fallback.
128
- // Uses a signal to track error state so it works with reactive rendering.
327
+ // The client render of a boundary: <!--sb:start--> fallback or children <!--sb:end-->.
328
+ function mountSuspense(vnode, parent) {
329
+ const b = vnode.props.boundary;
330
+ const owner = getOwner();
331
+ const start = document.createComment('sb:start');
332
+ const end = document.createComment('sb:end');
333
+ // The boundary swaps the fallback and the children between its markers
334
+ // after it is placed, so a region that embeds it removes the live range
335
+ // (dom.js _liveRegionNodes).
336
+ /** @type {any} */ (start)._rangeEnd = end;
337
+ const container = document.createDocumentFragment();
338
+ container.appendChild(start);
339
+ container.appendChild(end);
340
+ const holder = document.createDocumentFragment();
341
+ createRoot(() => {
342
+ b.attach(getOwner(), false);
343
+ for (const v of vnode.children) {
344
+ const node = createDOM(v, parent);
345
+ if (node) holder.appendChild(node);
346
+ }
347
+ });
348
+ /** @type {(() => void) | null} */
349
+ let fallbackArm = null;
350
+ b.show = () => {
351
+ if (fallbackArm !== null) {
352
+ fallbackArm();
353
+ fallbackArm = null;
354
+ for (let n = start.nextSibling; n !== null && n !== end; n = start.nextSibling) n.remove();
355
+ }
356
+ /** @type {Node} */ (end.parentNode).insertBefore(holder, end);
357
+ };
358
+ b.conceal = () => {
359
+ for (let n = start.nextSibling; n !== null && n !== end; n = start.nextSibling) holder.appendChild(n);
360
+ fallbackArm = runWithOwner(owner, () => buildArm(b.fallback, end));
361
+ };
362
+ b.check();
363
+ if (!b.revealed) fallbackArm = buildArm(b.fallback, end);
364
+ onCleanup(() => { if (fallbackArm !== null) fallbackArm(); });
365
+ return container;
366
+ }
129
367
 
130
- export function ErrorBoundary({ fallback, children, onError }) {
368
+ // --- ErrorBoundary ---
369
+ // Catch errors in children and show fallback. The renderers install
370
+ // `handleError` on the owner its children are built under
371
+ // (createErrorBoundary below, render.js hydrateErrorBoundary), so an error thrown while the
372
+ // children are built, or later by an effect, a binding, a cleanup, a list row,
373
+ // a component created inside them or an async value they read, reaches it.
374
+ // `reset` fetches again the async values whose errors it caught, disposes the
375
+ // fallback and builds the children again.
376
+
377
+ // `fallback` is read when it is shown, as Suspense's is.
378
+ export const ErrorBoundary = /* @__PURE__ */ deferChildren(function ErrorBoundary(props) {
379
+ const { children, onError } = props;
131
380
  const errorState = signal(null);
381
+ // The async computed runs that failed with the errors it caught.
382
+ /** @type {Array<{ node: any, run: number }>} */
383
+ const caught = [];
132
384
 
133
385
  // Error handler that will be registered with the component tree
134
386
  const handleError = (error) => {
387
+ const source = _errorSource(error);
388
+ if (source !== null) caught.push(source);
135
389
  errorState.set(error);
136
390
  if (onError) {
137
391
  try {
@@ -143,36 +397,77 @@ export function ErrorBoundary({ fallback, children, onError }) {
143
397
  };
144
398
 
145
399
  // Reset function to recover from error
146
- const reset = () => errorState.set(null);
147
-
148
- return {
149
- tag: '__errorBoundary',
150
- props: { errorState, handleError, fallback, reset },
151
- children: Array.isArray(children) ? children : [children],
152
- _vnode: true,
400
+ const reset = () => {
401
+ _retryErrors(caught.splice(0));
402
+ errorState.set(null);
153
403
  };
404
+ // Development: a hot update resets a boundary that took an error thrown in
405
+ // code it can replace (render.js hotSlot), so the save that fixes it shows.
406
+ if (__DEV__) /** @type {any} */ (handleError)._reset = reset;
407
+
408
+ return _vnode('__errorBoundary', {
409
+ errorState, handleError, reset, mount: createErrorBoundary,
410
+ get fallback() { return _place(props, 'fallback'); },
411
+ }, Array.isArray(children) ? children : [children]);
412
+ });
413
+
414
+ // The client render of a boundary, which its vnode carries (`mount`) as
415
+ // Suspense's does: <!--eb:start--> arm <!--eb:end-->. An effect shows the arm
416
+ // `errorState` names and rebuilds it when the state changes. Each arm is built
417
+ // in a root owned by the run that builds it, so the next run, or the
418
+ // boundary's disposal, disposes the arm before another takes its place.
419
+ // `handleError` goes on the root of the children's arm (`_onError`), which is
420
+ // how an error anywhere under the children finds it, and why one in the
421
+ // fallback goes past it to the boundary above.
422
+ function createErrorBoundary(vnode, parent) {
423
+ const { errorState, handleError, reset } = vnode.props;
424
+ const children = vnode.children;
425
+ const start = document.createComment('eb:start');
426
+ const end = document.createComment('eb:end');
427
+ // The arm between the markers is rebuilt after the boundary is placed, so a
428
+ // region that embeds it removes the live range (dom.js _liveRegionNodes).
429
+ /** @type {any} */ (start)._rangeEnd = end;
430
+ const container = document.createDocumentFragment();
431
+ container.appendChild(start);
432
+ container.appendChild(end);
433
+ effect(() => {
434
+ const error = errorState();
435
+ for (let n = start.nextSibling; n !== null && n !== end; n = start.nextSibling) n.remove();
436
+ untrack(() => {
437
+ if (error) {
438
+ const fallback = vnode.props.fallback;
439
+ // A function is called with them; a class component is rendered with them.
440
+ buildErrorArm(typeof fallback === 'function' ? _toFunctionComponent(fallback)({ error, reset }) : fallback, parent, end, null);
441
+ return;
442
+ }
443
+ try {
444
+ _withCursor(buildErrorArm, children, parent, end, handleError);
445
+ } catch (err) {
446
+ if (_handleNavigationSignal(err)) return;
447
+ handleError(err);
448
+ }
449
+ });
450
+ });
451
+ return container;
154
452
  }
155
453
 
156
- // The boundary context only exists once createErrorBoundary runs, so compiled
157
- // children must not be built during this call. See createComponent.
158
- ErrorBoundary._deferChildren = true;
159
-
160
- // Helper to report error to nearest boundary
161
- // Walks the component context tree (not a runtime stack) so async errors are caught
162
- export function reportError(error, startCtx) {
163
- // Walk up the _parentCtx chain to find the nearest _errorBoundary
164
- let ctx = startCtx || _getCurrentComponent?.();
165
- while (ctx) {
166
- if (ctx._errorBoundary) {
167
- ctx._errorBoundary(error);
168
- return true;
454
+ // Build `vnodes` before `end` in a root of their own, with `onError` (when
455
+ // given) as the root's error handler.
456
+ function buildErrorArm(vnodes, parent, end, onError) {
457
+ createRoot(() => {
458
+ if (onError !== null) /** @type {any} */ (getOwner())._onError = onError;
459
+ for (const v of Array.isArray(vnodes) ? vnodes : [vnodes]) {
460
+ const node = createDOM(v, parent);
461
+ if (node) end.parentNode.insertBefore(node, end);
169
462
  }
170
- ctx = ctx._parentCtx;
171
- }
172
- return false;
463
+ });
173
464
  }
174
465
 
175
- // _getCurrentComponent is already declared above and injected via _injectGetCurrentComponent
466
+ // Hand an error to the nearest error boundary above `owner` (the current owner
467
+ // by default). Returns true when a boundary took it.
468
+ export function reportError(error, owner) {
469
+ return _handleError(owner === undefined ? getOwner() : owner, error) === HANDLED;
470
+ }
176
471
 
177
472
  // --- Show ---
178
473
  // Conditional rendering component. Cleaner than ternaries.
@@ -187,13 +482,13 @@ export function reportError(error, startCtx) {
187
482
  // pipelines (the babel plugin lowers inline; the automatic `jsxImportSource`
188
483
  // runtime / h() route here via _$createComponent).
189
484
 
190
- export function Show({ when, fallback = null, children }) {
485
+ export const Show = /* @__PURE__ */ lowered(function Show({ when, fallback = null, children }) {
191
486
  return () => {
192
487
  // `when` can be a signal getter, a plain thunk, or a static value.
193
488
  const condition = typeof when === 'function' ? when() : when;
194
489
  return condition ? children : fallback;
195
490
  };
196
- }
491
+ });
197
492
 
198
493
  // --- For ---
199
494
  // List rendering. Returns a reactive thunk (see Show above) so the list
@@ -201,9 +496,11 @@ export function Show({ when, fallback = null, children }) {
201
496
  // framework's fn-child effect, tracking it. The preferred, keyed-efficient
202
497
  // pattern is `.map()` with a `key` prop (auto-lowered to _$mapArray by the
203
498
  // compiler) or `<For>` compiled by the fine-grained plugin; this runtime form
204
- // is the fallback for the automatic JSX runtime / h() path.
499
+ // is the fallback for the automatic JSX runtime / h() path. With `key`, it
500
+ // gives each row its item as an accessor, as the compiled <For> does: a row
501
+ // is built once per key, and follows an item replaced under that key.
205
502
 
206
- export function For({ each, fallback = null, children }) {
503
+ export const For = /* @__PURE__ */ lowered(function For({ each, key, fallback = null, children }) {
207
504
  // children should be a function (item, index) => vnode. Resolve/validate it
208
505
  // once at creation — it does not change across list updates.
209
506
  const renderFn = Array.isArray(children) ? children[0] : children;
@@ -211,6 +508,7 @@ export function For({ each, fallback = null, children }) {
211
508
  console.warn('[what] For: children must be a render function, e.g. <For each={items}>{(item) => ...}</For>');
212
509
  return fallback;
213
510
  }
511
+ if (typeof key === 'function') return keyedFor(each, key, fallback, renderFn);
214
512
 
215
513
  return () => {
216
514
  const list = typeof each === 'function' ? each() : each;
@@ -225,19 +523,53 @@ export function For({ each, fallback = null, children }) {
225
523
  if (item.id != null) vnode.key = item.id;
226
524
  else if (item.key != null) vnode.key = item.key;
227
525
  } else if (typeof item === 'string' || typeof item === 'number') {
228
- // Primitive items can be their own key
526
+ // Primitive items can be their own key. Like the items of an unkeyed
527
+ // list they may repeat, which is not a duplicate-key mistake.
229
528
  vnode.key = item;
529
+ vnode._itemKey = true;
230
530
  }
231
531
  }
232
532
  return vnode;
233
533
  });
234
534
  };
535
+ });
536
+
537
+ // <For key>: the vnode of each key is made once, from an accessor of the
538
+ // item, and handed back on every run, so the keyed rows keep it (and its DOM)
539
+ // while the accessor follows the item.
540
+ function keyedFor(each, key, fallback, renderFn) {
541
+ /** @type {Map<any, { item: any, vnode: any }>} */
542
+ let rows = new Map();
543
+ return () => {
544
+ const list = typeof each === 'function' ? each() : each;
545
+ /** @type {Map<any, { item: any, vnode: any }>} */
546
+ const next = new Map();
547
+ if (!list || list.length === 0) {
548
+ rows = next;
549
+ return fallback;
550
+ }
551
+ const out = list.map((item, index) => {
552
+ const k = key(item);
553
+ let row = rows.get(k);
554
+ if (row === undefined || next.has(k)) {
555
+ const cell = signal(item);
556
+ row = { item: cell, vnode: untrack(() => renderFn(() => cell(), index)) };
557
+ if (row.vnode && typeof row.vnode === 'object') row.vnode.key = k;
558
+ } else {
559
+ row.item(item);
560
+ }
561
+ next.set(k, row);
562
+ return row.vnode;
563
+ });
564
+ rows = next;
565
+ return out;
566
+ };
235
567
  }
236
568
 
237
569
  // --- Switch / Match ---
238
570
  // Multi-condition rendering (like switch statement).
239
571
 
240
- export function Switch({ fallback = null, children }) {
572
+ export const Switch = /* @__PURE__ */ lowered(function Switch({ fallback = null, children }) {
241
573
  // The Match children are static, so resolve them once. The match loop, which
242
574
  // reads each Match's reactive `when`, must run inside a reactive thunk (see
243
575
  // Show/For above): components run once, so evaluating `when()` in the body
@@ -259,9 +591,9 @@ export function Switch({ fallback = null, children }) {
259
591
  }
260
592
  return fallback;
261
593
  };
262
- }
594
+ });
263
595
 
264
- export function Match(props) {
596
+ export const Match = /* @__PURE__ */ lowered(function Match(props) {
265
597
  // Executed rather than left as a marker, which is what a lone compiled
266
598
  // <Match> does. Returning a `{ tag: Match }` vnode here would send createDOM
267
599
  // straight back into Match forever, so return a reactive thunk that renders
@@ -270,28 +602,22 @@ export function Match(props) {
270
602
  const condition = typeof props.when === 'function' ? props.when() : props.when;
271
603
  return condition ? props.children : null;
272
604
  };
273
- }
605
+ });
274
606
 
275
- // --- Island ---
607
+ // --- _$Island ---
276
608
  // Islands architecture: the content ships as server-rendered HTML and only the
277
609
  // *interactivity* is deferred to a client trigger. The babel plugin compiles
278
- // `<Counter client:idle />` into h(Island, { component: Counter, mode: 'idle' }).
279
- //
280
- // This used to render an empty marker div on every path, on the server AND the
281
- // client, in every mode: the SSR branch never rendered the component, and the
282
- // client branch read `hydrated()` once in a run-once component so the swap-in
283
- // never happened. Every `client:*` directive silently deleted its component.
284
-
285
- // Late-bound renderers, injected by render.js. components.js cannot import
286
- // render.js directly (render -> dom -> components is already a cycle), so the
287
- // same injection precedent as _injectGetCurrentComponent applies here.
288
- /** @type {{ hydrate?: Function, insert?: Function } | null} */
289
- let _islandRuntime = null;
290
-
291
- /** @internal */
292
- export function _injectIslandRuntime(runtime) {
293
- _islandRuntime = runtime;
294
- }
610
+ // `<Counter client:idle start={1} />` into
611
+ // h(_$Island, { component: Counter, name: 'Counter', mode: 'idle', props: { start: 1 } }),
612
+ // importing it from what-framework/render: the island's options and the
613
+ // component's props are two objects, so a prop called `name`, `mode`,
614
+ // `mediaQuery` or `component` reaches the component, and the name is the tag
615
+ // as written, which a minifier leaves alone (the function's own name is the
616
+ // fallback). Called without `props`, every key that is not an option is a
617
+ // prop. The public island component, which hydrates through the island
618
+ // registry, is what-framework/server's Island. An island written by hand
619
+ // without `name` is reported in development (ERR_ISLAND_WITHOUT_NAME): a
620
+ // minifier renames its function in one bundle and not the other.
295
621
 
296
622
  // Island props cross the server/client boundary as JSON, so anything that is not
297
623
  // representable is dropped rather than throwing mid-render. Functions in
@@ -311,7 +637,12 @@ function serializeIslandProps(props) {
311
637
  }
312
638
  }
313
639
 
314
- export function Island({ component: Component, mode, mediaQuery, name, children, ...props }) {
640
+ export const _$Island = /* @__PURE__ */ deferChildren(function Island({ component: Component, mode, mediaQuery, name, props: own, children, ...rest }) {
641
+ const props = own === undefined ? rest : own;
642
+ if (__DEV__ && !name) {
643
+ const component = Component?.name || 'anonymous';
644
+ report('ERR_ISLAND_WITHOUT_NAME', { data: { component }, subject: { kind: 'component', name: component } });
645
+ }
315
646
  const islandName = name || Component?.name || 'Island';
316
647
  const resolvedMode = mode || 'idle';
317
648
 
@@ -334,6 +665,9 @@ export function Island({ component: Component, mode, mediaQuery, name, children,
334
665
  const childList = children == null ? [] : (Array.isArray(children) ? children : [children]);
335
666
 
336
667
  if (isServerRender()) {
668
+ // The client hydrates the content as a root of its own, under this
669
+ // component's owner: it takes that root's place among the keyed rows.
670
+ _islandHost();
337
671
  return h(
338
672
  'div',
339
673
  { ...marker, 'data-island-props': serializeIslandProps(props) },
@@ -342,20 +676,27 @@ export function Island({ component: Component, mode, mediaQuery, name, children,
342
676
  }
343
677
 
344
678
  let hydrated = false;
679
+ // The island's content hydrates long after this body ran, under the island's
680
+ // owner, so it is disposed with the island and finds its context, and its
681
+ // mismatches go where those of the hydrate() that ran this body go.
682
+ const owner = getOwner();
683
+ const onHydrationError = _hydrationErrorHook();
345
684
 
346
685
  function hydrateInto(el) {
347
- if (hydrated) return;
686
+ if (hydrated || (owner !== null && _isDisposed(owner))) return;
348
687
  hydrated = true;
349
688
 
350
689
  const vnode = h(Component, props, ...childList);
351
690
 
352
691
  // Server-rendered children present => hydrate in place, reusing the DOM.
353
692
  // Nothing there => a client-only render, so build it from scratch.
354
- if (el.childNodes.length > 0 && _islandRuntime?.hydrate) {
355
- _islandRuntime.hydrate(vnode, el);
356
- } else if (_islandRuntime?.insert) {
357
- _islandRuntime.insert(el, vnode, null);
358
- }
693
+ runWithOwner(owner, () => {
694
+ if (el.childNodes.length > 0) {
695
+ hydrate(vnode, el, onHydrationError === null ? undefined : { onHydrationError });
696
+ } else {
697
+ insert(el, vnode, null);
698
+ }
699
+ });
359
700
 
360
701
  el.removeAttribute('data-hydrate');
361
702
  el.removeAttribute('data-island-self');
@@ -399,12 +740,22 @@ export function Island({ component: Component, mode, mediaQuery, name, children,
399
740
 
400
741
  case 'interaction':
401
742
  case 'action': {
743
+ // Built in the browser (a client navigation, a key that changed),
744
+ // the island has no server HTML: nothing on the page could be
745
+ // interacted with, so it renders at once.
746
+ if (el.childNodes.length === 0) {
747
+ queueMicrotask(trigger);
748
+ break;
749
+ }
750
+ // In the capture phase: focus does not bubble, and the island
751
+ // hydrates before the event reaches its target, so the handler the
752
+ // island sets on the target runs for the interaction that woke it.
402
753
  const events = ['click', 'focus', 'mouseenter', 'touchstart'];
403
754
  const onInteract = () => {
404
- for (const type of events) el.removeEventListener(type, onInteract);
755
+ for (const type of events) el.removeEventListener(type, onInteract, true);
405
756
  trigger();
406
757
  };
407
- for (const type of events) el.addEventListener(type, onInteract, { once: true });
758
+ for (const type of events) el.addEventListener(type, onInteract, { capture: true, once: true });
408
759
  break;
409
760
  }
410
761
 
@@ -431,4 +782,4 @@ export function Island({ component: Component, mode, mediaQuery, name, children,
431
782
  }
432
783
 
433
784
  return h('div', { ...marker, ref: (el) => { if (el) scheduleHydration(el); } });
434
- }
785
+ });