what-core 0.13.11 → 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/hooks.js CHANGED
@@ -3,10 +3,13 @@
3
3
  // Components run ONCE. Hooks return signal accessors (functions) so the
4
4
  // fine-grained runtime handles reactive updates automatically via effects.
5
5
 
6
- import { signal, computed, effect, batch, untrack, __DEV__ } from './reactive.js';
7
- import { getCurrentComponent } from './dom.js';
6
+ import { signal, computed, effect, untrack, getOwner, onCleanup as onOwnerCleanup, _userEffect, _currentComponent, _contextOf, _devAsyncWork, _devCallSite, _devStackLoc, _asyncComputed, _asyncStatus, _asyncError, _refresh, _setAsyncValue, _installSeedOps, __DEV__ } from './reactive.js';
8
7
  import { getServerContext, isServerRender } from './server-context.js';
9
- import { getLoaderData as _getLoaderData, getResource as _getResource } from './hydration-data.js';
8
+ import { getLoaderData as _getLoaderData, getResource as _getResource, getResourceError as _getResourceError, _seedFor, _errorFromRecord } from './hydration-data.js';
9
+ import { computed as asyncComputed } from './async.js';
10
+ import { _enableSuspense } from './render.js';
11
+ import { _isLiveProp } from './dom.js';
12
+ import { report, _thrownMessage } from './diagnostics.js';
10
13
 
11
14
  // --- useLoaderData ---
12
15
  // Returns the current page's server loader data. Works during SSR (reads the
@@ -33,19 +36,22 @@ export function useLoaderData() {
33
36
  return _getLoaderData();
34
37
  }
35
38
 
39
+ // The component a hook belongs to: the nearest component owner above the
40
+ // current owner (reactive.js _componentOwner).
36
41
  function getCtx(hookName) {
37
- const ctx = getCurrentComponent();
42
+ const ctx = _currentComponent();
38
43
  if (!ctx) {
39
- throw new Error(
40
- `[what] ${hookName || 'Hook'}() can only be called inside a component function. ` +
41
- `Did you call it outside of a component or in an async callback? ` +
42
- `If you need reactive state outside a component, use signal() directly.`
43
- );
44
+ // The production tier keeps the code and the first sentence; the
45
+ // catalogue (ERR_HOOK_OUTSIDE_COMPONENT) has the rest.
46
+ throw Object.assign(new Error(__DEV__
47
+ ? _thrownMessage('ERR_HOOK_OUTSIDE_COMPONENT', `${hookName || 'Hook'}() can only be called inside a component function. Did you call it outside of a component or in an async callback? If you need reactive state outside a component, use signal() directly.`)
48
+ : `[what] ${hookName || 'Hook'}() can only be called inside a component function.`), { code: 'ERR_HOOK_OUTSIDE_COMPONENT' });
44
49
  }
45
50
  return ctx;
46
51
  }
47
52
 
48
53
  function getHook(ctx) {
54
+ if (ctx.hooks === null) ctx.hooks = [];
49
55
  const index = ctx.hookIndex++;
50
56
  return { index, exists: index < ctx.hooks.length };
51
57
  }
@@ -56,12 +62,13 @@ function getHook(ctx) {
56
62
  // via insert()'s effect wrapper. For interpolation, use count() explicitly.
57
63
  // This matches Solid's API and works with the run-once component model.
58
64
 
59
- export function useState(initial) {
65
+ // `debugName` is the development name what-compiler passes ("count@src/App.jsx:4:27").
66
+ export function useState(initial, debugName) {
60
67
  const ctx = getCtx('useState');
61
68
  const { index, exists } = getHook(ctx);
62
69
 
63
70
  if (!exists) {
64
- const s = signal(typeof initial === 'function' ? initial() : initial);
71
+ const s = signal(typeof initial === 'function' ? initial() : initial, debugName);
65
72
  ctx.hooks[index] = s;
66
73
  }
67
74
 
@@ -73,119 +80,126 @@ export function useState(initial) {
73
80
  // Returns the raw signal. More powerful: read with sig(), write with sig.set(v).
74
81
  // Avoids array destructuring overhead.
75
82
 
76
- export function useSignal(initial) {
83
+ export function useSignal(initial, debugName) {
77
84
  const ctx = getCtx('useSignal');
78
85
  const { index, exists } = getHook(ctx);
79
86
 
80
87
  if (!exists) {
81
- ctx.hooks[index] = signal(typeof initial === 'function' ? initial() : initial);
88
+ ctx.hooks[index] = signal(typeof initial === 'function' ? initial() : initial, debugName);
82
89
  }
83
90
 
84
91
  return ctx.hooks[index];
85
92
  }
86
93
 
87
94
  // --- useComputed ---
88
- // Derived value. Only recomputes when signal deps change.
95
+ // computed() as a hook: a derived value, which may be async (see async.js).
89
96
 
90
97
  export function useComputed(fn) {
91
98
  const ctx = getCtx('useComputed');
92
99
  const { index, exists } = getHook(ctx);
93
100
 
94
101
  if (!exists) {
95
- ctx.hooks[index] = computed(fn);
102
+ ctx.hooks[index] = asyncComputed(fn);
96
103
  }
97
104
 
98
105
  return ctx.hooks[index];
99
106
  }
100
107
 
101
108
  // --- useEffect ---
102
- // Side effect that runs after mount. In the run-once model, deps-based
103
- // re-running only works if deps are signal accessors. The implementation:
104
- // - No deps (undefined): wrap in effect() that auto-tracks signals
105
- // - Empty deps []: run once on mount, cleanup on unmount
106
- // - Deps [a, b]: create effect() that reads each dep (calling signal functions
107
- // to establish tracking), then runs the callback when any dep changes
108
-
109
- export function useEffect(fn, deps) {
110
- const ctx = getCtx('useEffect');
111
- const { index, exists } = getHook(ctx);
112
-
113
- if (!exists) {
114
- ctx.hooks[index] = { cleanup: null, dispose: null };
109
+ // Side effect that runs after mount, in the user phase: after the render-phase
110
+ // effects (the DOM bindings) of the same flush, so it sees settled DOM. The
111
+ // first run is on the microtask after the component body (or at the end of
112
+ // the batch, or in the flush, that builds the component). In the run-once
113
+ // model, deps-based re-running only works if deps are signal accessors:
114
+ // - No deps (undefined): re-runs whenever a signal it read changes
115
+ // - Empty deps []: runs once on mount, cleanup on unmount
116
+ // - Deps [a, b]: re-runs when a signal or computed among the deps changes;
117
+ // what the callback reads is untracked. Any other function in the array is
118
+ // not called (reportPlainDeps)
119
+ // A returned function is the cleanup, run before each re-run and on unmount.
120
+ // The effect belongs to the component: unmounting disposes it.
121
+
122
+ // Dev-mode: a value in the deps array (count() rather than count) is read once
123
+ // and never changes. Kept out of line: written inline after another statement,
124
+ // esbuild folds `if (seq, false) { loop }` without dropping the loop, which
125
+ // kept this report() call and the whole catalogue in production bundles.
126
+ //
127
+ // A function that is not a signal or a computed is not called for what it
128
+ // reads: a deps array written by React habit holds setters and callbacks
129
+ // (`[setCount]`, `[load]`, `[props.onClose]`), and calling those as getters
130
+ // would write state or start work on every run. One that takes no argument
131
+ // may have been meant as a getter (`[() => props.count]`), so it is reported:
132
+ // the effect never re-runs for it. One that takes arguments cannot be a
133
+ // getter, and listing it is harmless (a component runs once, so a callback
134
+ // never changes).
135
+ // The component is the report's subject, so the same mistake in two
136
+ // components is two reports, each with its own owner, and the rows of one
137
+ // component's list are one. The report is at the useEffect call: `at`, the
138
+ // location what-compiler gave it, else the caller's frame of the stack.
139
+ function reportPlainDeps(deps, ctx, at) {
140
+ const subject = { kind: 'component', name: ctx.Component?.displayName || ctx.Component?.name || 'anonymous' };
141
+ /** @type {string | null | undefined} */
142
+ let loc;
143
+ const where = () => (loc === undefined ? (loc = at ?? _devStackLoc(useEffect)) : loc);
144
+ for (let i = 0; i < deps.length; i++) {
145
+ const dep = deps[i];
146
+ if (dep == null) continue;
147
+ if (typeof dep !== 'function') report('ERR_EFFECT_DEP_NOT_FUNCTION', { data: { index: i }, subject: { ...subject, id: `${subject.name}#${i}` }, loc: where() });
148
+ else if (!dep._signal && dep.length === 0) report('ERR_EFFECT_DEP_NOT_SIGNAL', { data: { index: i }, subject: { ...subject, id: `${subject.name}#${i}` }, loc: where() });
115
149
  }
150
+ }
116
151
 
117
- // Dev-mode: warn when deps array contains non-function values that look like signals
118
- if (__DEV__ && Array.isArray(deps) && deps.length > 0) {
119
- for (let i = 0; i < deps.length; i++) {
120
- const dep = deps[i];
121
- if (dep != null && typeof dep !== 'function') {
122
- console.warn(
123
- `[what] useEffect dep at index ${i} is not a function. ` +
124
- `Did you mean to pass a signal? Use count instead of count()`
125
- );
126
- }
127
- }
128
- }
152
+ // "name@path:line:column" (what-compiler's development metadata) as its location.
153
+ function devLoc(meta) {
154
+ const at = typeof meta === 'string' ? meta.indexOf('@') : -1;
155
+ return at === -1 ? null : meta.slice(at + 1);
156
+ }
129
157
 
130
- const hook = ctx.hooks[index];
158
+ // A callback's result as an effect's: a function is the cleanup. In
159
+ // development, a thenable (an async callback) is work the component started,
160
+ // so an effect created after its `await`, under no owner, is reported; an
161
+ // async useEffect callback is reported itself, since its promise is not a
162
+ // cleanup and its runs can finish out of order (an async onMount, which runs
163
+ // once, passes `mounting`).
164
+ function cleanupOf(result, ctx, mounting) {
165
+ if (typeof result === 'function') return result;
166
+ if (__DEV__ && result != null && typeof result.then === 'function') {
167
+ _devAsyncWork(ctx, result);
168
+ if (!mounting) report('ERR_ASYNC_EFFECT', { data: { effectName: 'useEffect' } });
169
+ }
170
+ return undefined;
171
+ }
131
172
 
132
- // Only set up once — component runs once
133
- if (hook.dispose) return;
173
+ // `debugName` is what-compiler's development metadata for the call
174
+ // ("useEffect@src/App.jsx:10:3"), in development builds only.
175
+ export function useEffect(fn, deps, debugName) {
176
+ const ctx = getCtx('useEffect');
177
+ getHook(ctx);
178
+ const at = __DEV__ ? devLoc(debugName) : null;
179
+ if (__DEV__ && Array.isArray(deps)) reportPlainDeps(deps, ctx, at);
180
+ // A server render never mounts.
181
+ if (isServerRender()) return;
134
182
 
183
+ let run;
135
184
  if (deps === undefined) {
136
- // No deps array: wrap in effect() that auto-tracks signal reads inside fn
137
- queueMicrotask(() => {
138
- if (ctx.disposed) return;
139
- hook.dispose = effect(() => {
140
- if (hook.cleanup) {
141
- try { hook.cleanup(); } catch { /* cleanup error */ }
142
- hook.cleanup = null;
143
- }
144
- const result = fn();
145
- if (typeof result === 'function') hook.cleanup = result;
146
- });
147
- // Register disposal with component lifecycle
148
- ctx.effects = ctx.effects || [];
149
- ctx.effects.push(hook.dispose);
150
- });
185
+ run = () => cleanupOf(fn(), ctx);
151
186
  } else if (deps.length === 0) {
152
- // Empty deps []: run once on mount, cleanup on unmount
153
- queueMicrotask(() => {
154
- if (ctx.disposed) return;
155
- const result = fn();
156
- if (typeof result === 'function') hook.cleanup = result;
157
- });
158
- // Mark as set up so we don't re-run
159
- hook.dispose = true;
187
+ run = () => cleanupOf(untrack(fn), ctx);
160
188
  } else {
161
- // Deps array with values: create a reactive effect that reads each dep.
162
- // If a dep is a signal function, calling it establishes tracking.
163
- // When any tracked signal changes, the effect re-runs the callback.
164
- queueMicrotask(() => {
165
- if (ctx.disposed) return;
166
- hook.dispose = effect(() => {
167
- // Read all deps to establish signal tracking
168
- for (let i = 0; i < deps.length; i++) {
169
- const dep = deps[i];
170
- if (typeof dep === 'function' && dep._signal) {
171
- dep(); // Read signal to track it
172
- }
173
- }
174
-
175
- // Run cleanup from previous execution
176
- if (hook.cleanup) {
177
- try { hook.cleanup(); } catch { /* cleanup error */ }
178
- hook.cleanup = null;
179
- }
180
-
181
- // Run the effect callback
182
- const result = untrack(() => fn());
183
- if (typeof result === 'function') hook.cleanup = result;
184
- });
185
- // Register disposal with component lifecycle
186
- ctx.effects = ctx.effects || [];
187
- ctx.effects.push(hook.dispose);
188
- });
189
+ run = () => {
190
+ for (let i = 0; i < deps.length; i++) {
191
+ const dep = deps[i];
192
+ if (typeof dep === 'function' && dep._signal) dep();
193
+ }
194
+ return cleanupOf(untrack(fn), ctx);
195
+ };
196
+ }
197
+ if (__DEV__) {
198
+ /** @type {any} */ (run).inner = fn;
199
+ const name = fn.name || 'useEffect';
200
+ /** @type {any} */ (_userEffect)(run, at !== null ? `${name}@${at}` : _devCallSite(name, useEffect));
201
+ } else {
202
+ _userEffect(run);
189
203
  }
190
204
  }
191
205
 
@@ -200,12 +214,24 @@ export function useMemo(fn, _deps) {
200
214
  const { index, exists } = getHook(ctx);
201
215
 
202
216
  if (!exists) {
203
- ctx.hooks[index] = { computed: computed(fn) };
217
+ ctx.hooks[index] = { computed: computed(__DEV__ ? devMemo(fn) : fn) };
204
218
  }
205
219
 
206
220
  return ctx.hooks[index].computed;
207
221
  }
208
222
 
223
+ // Development: useMemo keeps a promise its function returns as the value, as
224
+ // React's does; one that does is almost always meant to be an async value.
225
+ function devMemo(fn) {
226
+ const memo = () => {
227
+ const value = fn();
228
+ if (value != null && typeof value.then === 'function') report('ERR_ASYNC_MEMO');
229
+ return value;
230
+ };
231
+ memo.inner = fn;
232
+ return memo;
233
+ }
234
+
209
235
  // --- useCallback ---
210
236
  // Memoized callback. In the run-once model, the component function only
211
237
  // executes once, so the callback reference is inherently stable.
@@ -238,67 +264,80 @@ export function useRef(initial) {
238
264
  }
239
265
 
240
266
  // --- useContext ---
241
- // Read from the nearest Provider in the component tree, or the default value.
242
- // Uses _parentCtx chain (persistent tree) instead of componentStack (runtime stack)
243
- // so context works correctly in effects and event handlers.
244
- // Returns the signal itself (not its value) so that consumers get reactive updates.
267
+ // Read from the nearest Provider above the current owner, or the default
268
+ // value. Providers keep their values on their component's owner, and the walk
269
+ // goes up the owner tree, so context resolves the same way in a component
270
+ // body, in an effect or region that re-runs long after it, and in a list row.
271
+ // A stored signal is read, so the reader subscribes to it.
245
272
 
246
273
  export function useContext(context) {
247
- // Walk up the _parentCtx chain to find the nearest provider
248
- let ctx = getCurrentComponent();
249
- if (__DEV__ && !ctx) {
250
- console.warn(
251
- `[what] useContext(${context?.displayName || 'Context'}) called outside of component render. ` +
252
- 'useContext must be called during component rendering, not inside effects or event handlers. ' +
253
- 'Store the context value in a variable during render and use that variable in your callback.'
254
- );
274
+ const map = _contextOf(context);
275
+ if (map !== null) {
276
+ const val = map.get(context);
277
+ return (val && val._signal) ? val() : val;
255
278
  }
256
- while (ctx) {
257
- if (ctx._contextValues && ctx._contextValues.has(context)) {
258
- const val = ctx._contextValues.get(context);
259
- // If the stored value is a signal, read it to subscribe
260
- return (val && val._signal) ? val() : val;
279
+ if (__DEV__) {
280
+ if (!_currentComponent()) {
281
+ report('ERR_HOOK_OUTSIDE_COMPONENT', { data: { hookName: 'useContext', context: context?.displayName || 'Context' } });
282
+ } else if (!context._hasDefault) {
283
+ // createContext() with no argument means the value must come from a provider.
284
+ report('ERR_CONTEXT_NOT_PROVIDED', { data: { context: context.displayName || 'Context' } });
261
285
  }
262
- ctx = ctx._parentCtx;
263
286
  }
264
287
  return context._defaultValue;
265
288
  }
266
289
 
267
290
  // --- createContext ---
268
- // Tree-scoped context: Provider sets value for its subtree only.
291
+ // Tree-scoped context: a provider sets the value for its subtree only.
269
292
  // Multiple providers can coexist — each subtree sees its own value.
270
293
  // Context values are wrapped in signals so consumers re-render when values change.
294
+ // The context is its own provider, as in React 19 and Solid 2: <Ctx value={v}>
295
+ // and <Ctx.Provider value={v}> render the same component.
296
+ //
297
+ // A provider follows its `value` prop as any component follows a prop:
298
+ // compiled JSX hands `value={theme()}` over as a live prop (a getter, dom.js
299
+ // _isLiveProp), which an effect of the provider reads, so the readers below
300
+ // see each new value. The value is read once per change, not once per reader,
301
+ // so `value={{ user: user(), setUser }}` is one object for all of them until
302
+ // `user` changes. A value that is not live (a signal handed over as it is,
303
+ // `value={theme}`; a constant; an h() call's argument) is stored as it is and
304
+ // costs no effect. A function is a value like any other: a signal handed
305
+ // over through a store (`value={store.theme}`, a live prop too) is what the
306
+ // readers get, and they call it; it is never called to make the value.
271
307
 
272
308
  export function createContext(defaultValue) {
273
- const context = {
274
- _defaultValue: defaultValue,
275
- Provider: ({ value, children }) => {
276
- const ctx = getCtx('Context.Provider');
277
- if (!ctx._contextValues) ctx._contextValues = new Map();
278
- if (!ctx._contextSignals) ctx._contextSignals = new Map();
279
-
280
- // Create or update the context signal
281
- if (!ctx._contextSignals.has(context)) {
282
- const s = signal(value);
283
- ctx._contextSignals.set(context, s);
284
- ctx._contextValues.set(context, s);
285
- } else {
286
- ctx._contextSignals.get(context).set(value);
287
- }
288
- return children;
289
- },
290
- // React-compatible Consumer: <Context.Consumer>{value => ...}</Context.Consumer>
291
- Consumer: ({ children }) => {
292
- const value = useContext(context);
293
- return typeof children === 'function' ? children(value) : children;
294
- },
309
+ function context(props) {
310
+ const ctx = getCtx('Context.Provider');
311
+ const values = ctx.context || (ctx.context = new Map());
312
+ const current = values.get(context);
313
+ if (current !== undefined) provide(current, props.value);
314
+ else {
315
+ const held = signal(props.value);
316
+ values.set(context, held);
317
+ if (_isLiveProp(props, 'value')) effect(() => provide(held, props.value), __DEV__ ? { name: 'context value' } : undefined);
318
+ }
319
+ return props.children;
320
+ }
321
+ context._defaultValue = defaultValue;
322
+ context._hasDefault = arguments.length > 0;
323
+ context.Provider = context;
324
+ // React-compatible Consumer: <Context.Consumer>{value => ...}</Context.Consumer>
325
+ context.Consumer = ({ children }) => {
326
+ const value = useContext(context);
327
+ return typeof children === 'function' ? children(value) : children;
295
328
  };
296
329
  // The context value is only published once the provider body runs, so
297
330
  // compiled children must not be built during this call. See createComponent.
298
- /** @type {any} */ (context.Provider)._deferChildren = true;
331
+ context._deferChildren = true;
299
332
  return context;
300
333
  }
301
334
 
335
+ // `set()` calls a function as an updater: a function value is stored as one
336
+ // that returns it.
337
+ function provide(held, value) {
338
+ held.set(typeof value === 'function' ? () => value : value);
339
+ }
340
+
302
341
  // --- useReducer ---
303
342
  // State management with a reducer function.
304
343
  // Returns [signalAccessor, dispatch] — accessor is a signal function.
@@ -321,135 +360,81 @@ export function useReducer(reducer, initialState, init) {
321
360
  }
322
361
 
323
362
  // --- onMount ---
324
- // Run callback once when component mounts. SolidJS-style lifecycle.
363
+ // Run callback once when the component mounts, in the user phase of the flush
364
+ // that follows its creation (see useEffect), so it sees settled DOM. Disposed
365
+ // with the component if that comes first.
325
366
 
326
367
  export function onMount(fn) {
327
368
  const ctx = getCtx('onMount');
328
- if (!ctx.mounted) {
329
- ctx._mountCallbacks = ctx._mountCallbacks || [];
330
- ctx._mountCallbacks.push(fn);
331
- }
369
+ if (isServerRender()) return;
370
+ _userEffect(() => { cleanupOf(untrack(fn), ctx, true); });
332
371
  }
333
372
 
334
373
  // --- onCleanup ---
335
- // Register cleanup function to run when component unmounts.
374
+ // Run `fn` when the current owner goes away: the component being rendered (on
375
+ // unmount), the effect whose run is executing (before it runs again, and when
376
+ // it is disposed), or the root, list row or region around the call.
336
377
 
337
378
  export function onCleanup(fn) {
338
- const ctx = getCtx('onCleanup');
339
- ctx._cleanupCallbacks = ctx._cleanupCallbacks || [];
340
- ctx._cleanupCallbacks.push(fn);
379
+ if (getOwner() !== null) onOwnerCleanup(fn);
380
+ else if (__DEV__) report('ERR_CLEANUP_WITHOUT_OWNER');
341
381
  }
342
382
 
343
383
  // --- createResource ---
344
- // Reactive data fetching primitive (SolidJS-style).
345
- // Returns [data, { loading, error, refetch, mutate }]
384
+ // createResource(fetcher, options) -> [data, { loading, error, refetch, mutate }].
385
+ // `data` is an async computed (async.js): reading it before the first value
386
+ // lands holds the reader, as any async value does, and a <Suspense> above it
387
+ // shows its fallback. `fetcher(source, { signal })` runs untracked: the
388
+ // resource fetches when it is created and on refetch(source), not when a
389
+ // signal the fetcher reads changes. On the server it takes part in the
390
+ // hydration data channel like any async value made in a component, under
391
+ // `options.key` when it has one: the client adopts the value (or the error)
392
+ // instead of fetching. `initialValue` starts it with a value and no fetch.
346
393
 
347
394
  export function createResource(fetcher, options = {}) {
348
- // --- Server branch: run the fetcher, cache by key on the render context, and
349
- // suspend (throw the promise) so the nearest Suspense shows its fallback until
350
- // the data resolves. On re-render the cached value is returned synchronously.
351
- //
352
- // Gated on the render scope for the same reason as useLoaderData above: under
353
- // a DOM shim a server render used to fall into the CLIENT branch, which starts
354
- // a browser-style fetch, returns null immediately and never suspends. The
355
- // server then emitted the empty state as final HTML and renderToStringAsync
356
- // had nothing pending to await, so the resolve loop exited after one pass.
357
- if (isServerRender()) {
358
- const ctx = getServerContext();
359
- if (ctx) {
360
- const key = options.key != null ? options.key : `__r${ctx.resourceCounter++}`;
361
- const cached = ctx.resources.get(key);
362
- if (cached && cached.status === 'ready') {
363
- const accessor = () => cached.value;
364
- return [accessor, { loading: () => false, error: () => null, refetch: () => {}, mutate: () => {} }];
365
- }
366
- if (cached && cached.status === 'error') {
367
- const accessor = () => undefined;
368
- return [accessor, { loading: () => false, error: () => cached.error, refetch: () => {}, mutate: () => {} }];
369
- }
370
- if (!cached) {
371
- const promise = Promise.resolve()
372
- .then(() => fetcher(options.source ?? true, {}))
373
- .then((v) => { ctx.resources.set(key, { status: 'ready', value: v }); })
374
- .catch((e) => { ctx.resources.set(key, { status: 'error', error: e }); });
375
- ctx.resources.set(key, { status: 'pending', promise });
376
- throw promise; // caught by the nearest Suspense boundary
377
- }
378
- // pending (shouldn't normally re-reach here within one pass)
379
- throw cached.promise;
380
- }
381
- // No active render context (bare synchronous renderToString): suspend so the
382
- // nearest Suspense boundary shows its fallback. There's no cache to resolve
383
- // into here — use renderToStringAsync / renderToStream for resolved data.
384
- if (options.initialValue != null) {
385
- const accessor = () => options.initialValue;
386
- return [accessor, { loading: () => false, error: () => null, refetch: () => {}, mutate: () => {} }];
387
- }
388
- throw Promise.resolve().then(() => fetcher(options.source ?? true, {}));
389
- }
390
-
391
- // --- Client branch: seed from the hydration payload so SSR'd resources don't
392
- // refetch on hydrate.
393
- let seeded = options.initialValue;
394
- if (seeded == null && options.key != null) {
395
- const fromPayload = _getResource(options.key);
396
- if (fromPayload !== undefined) seeded = fromPayload;
395
+ _enableSuspense();
396
+ _installSeedOps();
397
+ let source = options.source;
398
+ const ctx = isServerRender() ? getServerContext() : null;
399
+ const keyed = options.key != null;
400
+ /** @type {any} */
401
+ let seed;
402
+ if (ctx !== null) {
403
+ seed = _seedFor(options.key, false);
404
+ } else if (keyed) {
405
+ // A keyed value is adopted wherever it is read, not only while hydrating.
406
+ const value = options.initialValue != null ? options.initialValue : _getResource(options.key);
407
+ const record = value === undefined ? _getResourceError(options.key) : undefined;
408
+ seed = value !== undefined ? { value, track: false } : record ? { error: _errorFromRecord(record), track: false } : null;
409
+ } else {
410
+ // Asked even with an initialValue: every keyless value consumes its owner key.
411
+ seed = _seedFor(null, false);
412
+ if (options.initialValue != null) seed = { value: options.initialValue, track: false };
397
413
  }
398
-
399
- const data = signal(seeded ?? null);
400
- const loading = signal(seeded == null);
401
- const error = signal(null);
402
-
403
- /** @type {AbortController | null} */
404
- let controller = null;
405
-
406
- const refetch = async (source) => {
407
- // Abort previous request
408
- if (controller) controller.abort();
409
- controller = new AbortController();
410
- const { signal: abortSignal } = controller;
411
-
412
- loading.set(true);
413
- error.set(null);
414
-
415
- try {
416
- const result = await fetcher(source, { signal: abortSignal });
417
-
418
- // Only update if not aborted
419
- if (!abortSignal.aborted) {
420
- batch(() => {
421
- data.set(result);
422
- loading.set(false);
423
- });
424
- }
425
- } catch (e) {
426
- if (!abortSignal.aborted) {
427
- batch(() => {
428
- error.set(e);
429
- loading.set(false);
430
- });
431
- }
432
- }
414
+ const data = _asyncComputed(({ signal }) => untrack(() => (ctx !== null
415
+ ? fetcher(source ?? true, { signal: ctx.signal, request: ctx.request })
416
+ : fetcher(source, { signal }))), seed);
417
+ // A server render suspends the component that makes it until it settles,
418
+ // and finds it in the render's store when the component runs again.
419
+ if (ctx !== null && _asyncStatus(data) === 'unresolved') data();
420
+
421
+ const loading = () => {
422
+ const status = _asyncStatus(data);
423
+ return status === 'unresolved' || status === 'pending';
424
+ };
425
+ const error = () => {
426
+ _asyncStatus(data);
427
+ return _asyncError(data);
428
+ };
429
+ // Never rejects: a failed refetch shows in error().
430
+ const refetch = (next) => {
431
+ source = next;
432
+ return _refresh(data).then(() => undefined, () => undefined);
433
433
  };
434
-
435
434
  const mutate = (value) => {
436
- data.set(typeof value === 'function' ? value(data()) : value);
435
+ _setAsyncValue(data, typeof value === 'function' ? value(data.peek()) : value);
437
436
  };
438
437
 
439
- // Register cleanup with component lifecycle: abort on unmount
440
- const ctx = getCurrentComponent?.();
441
- if (ctx) {
442
- ctx._cleanupCallbacks = ctx._cleanupCallbacks || [];
443
- ctx._cleanupCallbacks.push(() => {
444
- if (controller) controller.abort();
445
- });
446
- }
447
-
448
- // Initial fetch only if we have no value (initial or hydrated from payload)
449
- if (seeded == null) {
450
- refetch(options.source);
451
- }
452
-
453
438
  return [data, { loading, error, refetch, mutate }];
454
439
  }
455
440