@shadow-js/core 1.0.1 → 1.0.3
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.
- package/CHANGELOG.md +23 -0
- package/dist/dev/action.js +11 -7
- package/dist/dev/action.js.map +1 -1
- package/dist/dev/cache.d.ts +2 -1
- package/dist/dev/cache.js +5 -3
- package/dist/dev/cache.js.map +1 -1
- package/dist/dev/effect.js +17 -33
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/extend/index.d.ts +7 -6
- package/dist/dev/extend/index.js +7 -7
- package/dist/dev/extend/index.js.map +1 -1
- package/dist/dev/external-store.js +8 -3
- package/dist/dev/external-store.js.map +1 -1
- package/dist/dev/internal/concurrency.js +56 -30
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/diagnostics.js +0 -2
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/dispose.js +1 -1
- package/dist/dev/internal/dispose.js.map +1 -1
- package/dist/dev/internal/flags.js +1 -3
- package/dist/dev/internal/flags.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +1 -2
- package/dist/dev/internal/graph.js +47 -69
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/owner.d.ts +9 -6
- package/dist/dev/internal/owner.js +22 -30
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/scheduler.js +44 -73
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/list.js +4 -12
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/memo.d.ts +2 -1
- package/dist/dev/memo.js +4 -4
- package/dist/dev/memo.js.map +1 -1
- package/dist/dev/ownership.d.ts +4 -2
- package/dist/dev/ownership.js +59 -3
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.js +18 -11
- package/dist/dev/props.js.map +1 -1
- package/dist/dev/reaction.d.ts +1 -1
- package/dist/dev/reaction.js +5 -1
- package/dist/dev/reaction.js.map +1 -1
- package/dist/dev/reducer.js +1 -1
- package/dist/dev/reducer.js.map +1 -1
- package/dist/dev/resource.js +24 -15
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/selector.js +1 -5
- package/dist/dev/selector.js.map +1 -1
- package/dist/dev/signal.d.ts +3 -2
- package/dist/dev/signal.js +3 -3
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +10 -4
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/use-store.d.ts +5 -0
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/transitions.js +1 -1
- package/dist/dev/transitions.js.map +1 -1
- package/dist/prod/action.js +1 -1
- package/dist/prod/action.js.map +1 -1
- package/dist/prod/cache.js +1 -1
- package/dist/prod/cache.js.map +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/extend/index.js +1 -1
- package/dist/prod/extend/index.js.map +1 -1
- package/dist/prod/external-store.js +1 -1
- package/dist/prod/external-store.js.map +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/dispose.js +1 -1
- package/dist/prod/internal/dispose.js.map +1 -1
- package/dist/prod/internal/flags.js +1 -1
- package/dist/prod/internal/flags.js.map +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/owner.js +1 -1
- package/dist/prod/internal/owner.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/list.js +1 -1
- package/dist/prod/list.js.map +1 -1
- package/dist/prod/memo.js +1 -1
- package/dist/prod/memo.js.map +1 -1
- package/dist/prod/ownership.js +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js.map +1 -1
- package/dist/prod/reaction.js +1 -1
- package/dist/prod/reaction.js.map +1 -1
- package/dist/prod/reducer.js +1 -1
- package/dist/prod/reducer.js.map +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/resource.js.map +1 -1
- package/dist/prod/selector.js +1 -1
- package/dist/prod/selector.js.map +1 -1
- package/dist/prod/signal.js +1 -1
- package/dist/prod/signal.js.map +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/transitions.js +1 -1
- package/dist/prod/transitions.js.map +1 -1
- package/dist/server/action.js +1 -1
- package/dist/server/action.js.map +1 -1
- package/dist/server/cache.js +1 -1
- package/dist/server/cache.js.map +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/extend/index.js +1 -1
- package/dist/server/extend/index.js.map +1 -1
- package/dist/server/external-store.js.map +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/dispose.js +1 -1
- package/dist/server/internal/dispose.js.map +1 -1
- package/dist/server/internal/flags.js +1 -1
- package/dist/server/internal/flags.js.map +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/owner.js +1 -1
- package/dist/server/internal/owner.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/list.js +1 -1
- package/dist/server/list.js.map +1 -1
- package/dist/server/memo.js +1 -1
- package/dist/server/memo.js.map +1 -1
- package/dist/server/ownership.js +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js.map +1 -1
- package/dist/server/reaction.js +1 -1
- package/dist/server/reaction.js.map +1 -1
- package/dist/server/reducer.js +1 -1
- package/dist/server/reducer.js.map +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/resource.js.map +1 -1
- package/dist/server/selector.js +1 -1
- package/dist/server/selector.js.map +1 -1
- package/dist/server/signal.js +1 -1
- package/dist/server/signal.js.map +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/transitions.js.map +1 -1
- package/dist/server-dev/action.js +11 -7
- package/dist/server-dev/action.js.map +1 -1
- package/dist/server-dev/cache.js +5 -3
- package/dist/server-dev/cache.js.map +1 -1
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/extend/index.js +7 -7
- package/dist/server-dev/extend/index.js.map +1 -1
- package/dist/server-dev/external-store.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +56 -30
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/diagnostics.js +0 -2
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +1 -1
- package/dist/server-dev/internal/dispose.js.map +1 -1
- package/dist/server-dev/internal/flags.js +1 -3
- package/dist/server-dev/internal/flags.js.map +1 -1
- package/dist/server-dev/internal/graph.js +47 -69
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/owner.js +22 -30
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +44 -73
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/list.js +4 -12
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/memo.js +4 -4
- package/dist/server-dev/memo.js.map +1 -1
- package/dist/server-dev/ownership.js +59 -3
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +18 -11
- package/dist/server-dev/props.js.map +1 -1
- package/dist/server-dev/reaction.js +5 -1
- package/dist/server-dev/reaction.js.map +1 -1
- package/dist/server-dev/reducer.js +1 -1
- package/dist/server-dev/reducer.js.map +1 -1
- package/dist/server-dev/resource.js +24 -15
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/selector.js +1 -5
- package/dist/server-dev/selector.js.map +1 -1
- package/dist/server-dev/signal.js +3 -3
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +10 -4
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/transitions.js.map +1 -1
- package/package.json +2 -1
|
@@ -4,7 +4,7 @@ import { FLAG_PARKED, FLAG_TRANSITION } from "./flags.js";
|
|
|
4
4
|
import { rt } from "./state.js";
|
|
5
5
|
import { handleError } from "./owner.js";
|
|
6
6
|
import { clearQueues, hasPending, renderQueue, userQueue } from "./queue.js";
|
|
7
|
-
import { recompute, updateIfNecessary } from "./graph.js";
|
|
7
|
+
import { recompute, refreshAncestors, updateIfNecessary } from "./graph.js";
|
|
8
8
|
// src/internal/scheduler.ts
|
|
9
9
|
/**
|
|
10
10
|
* Flush passes allowed before the loop guard aborts (R-CODE-12).
|
|
@@ -20,21 +20,23 @@ function byCreation(a, b) {
|
|
|
20
20
|
return a.depth - b.depth || a.seq - b.seq;
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
|
-
*
|
|
23
|
+
* Runs one queued effect. Its stale owners come first: an owner that is about to re-run disposes the
|
|
24
|
+
* effect, and running it before (a zombie, G-17) would read state that is already out of date.
|
|
24
25
|
* @internal
|
|
25
26
|
*/
|
|
26
|
-
function
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
function runQueued(effect) {
|
|
28
|
+
try {
|
|
29
|
+
if (!refreshAncestors(effect)) return;
|
|
30
|
+
if (effect.state === 2) recompute(effect);
|
|
31
|
+
else updateIfNecessary(effect);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
handleError(error, effect);
|
|
31
34
|
}
|
|
32
|
-
return true;
|
|
33
35
|
}
|
|
34
36
|
/** Runs every queued effect of one phase, parents before children, siblings by creation. */
|
|
35
37
|
function drain(queue) {
|
|
36
38
|
const batch = queue.splice(0, queue.length);
|
|
37
|
-
|
|
39
|
+
batch.sort(byCreation);
|
|
38
40
|
for (const effect of batch) {
|
|
39
41
|
effect.flags &= -3;
|
|
40
42
|
if ((effect.flags & 4) !== 0) continue;
|
|
@@ -42,12 +44,7 @@ function drain(queue) {
|
|
|
42
44
|
effect.flags = effect.flags & ~FLAG_TRANSITION | FLAG_PARKED;
|
|
43
45
|
continue;
|
|
44
46
|
}
|
|
45
|
-
|
|
46
|
-
if (effect.state === 2) recompute(effect);
|
|
47
|
-
else updateIfNecessary(effect);
|
|
48
|
-
} catch (error) {
|
|
49
|
-
handleError(error, effect);
|
|
50
|
-
}
|
|
47
|
+
runQueued(effect);
|
|
51
48
|
}
|
|
52
49
|
return batch.length;
|
|
53
50
|
}
|
|
@@ -86,25 +83,13 @@ function flush() {
|
|
|
86
83
|
report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);
|
|
87
84
|
try {
|
|
88
85
|
while (hasPending()) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
passes += 1;
|
|
92
|
-
if (passes > 1e3) {
|
|
93
|
-
aborted = true;
|
|
94
|
-
break;
|
|
95
|
-
}
|
|
96
|
-
runs += drain(renderQueue);
|
|
97
|
-
}
|
|
98
|
-
if (!aborted && userQueue.length > 0) {
|
|
99
|
-
passes += 1;
|
|
100
|
-
if (passes > 1e3) aborted = true;
|
|
101
|
-
else runs += drain(userQueue);
|
|
102
|
-
}
|
|
103
|
-
if (aborted) {
|
|
86
|
+
passes += 1;
|
|
87
|
+
if (passes > 1e3) {
|
|
104
88
|
clearQueues();
|
|
105
89
|
rt.uncaught.push(new ShadowError("INFINITE_LOOP"));
|
|
106
90
|
break;
|
|
107
91
|
}
|
|
92
|
+
runs += drain(renderQueue.length > 0 ? renderQueue : userQueue);
|
|
108
93
|
}
|
|
109
94
|
} finally {
|
|
110
95
|
rt.flushing = false;
|
|
@@ -185,8 +170,32 @@ function group(fn) {
|
|
|
185
170
|
if (rt.batchDepth === 0 && hasPending()) schedule();
|
|
186
171
|
}
|
|
187
172
|
}
|
|
188
|
-
|
|
189
|
-
|
|
173
|
+
/**
|
|
174
|
+
* The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when
|
|
175
|
+
* `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until
|
|
176
|
+
* the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.
|
|
177
|
+
*/
|
|
178
|
+
function runBatched(fn, sync) {
|
|
179
|
+
rt.batchDepth += 1;
|
|
180
|
+
let result;
|
|
181
|
+
let failure;
|
|
182
|
+
let failed = false;
|
|
183
|
+
try {
|
|
184
|
+
result = fn === void 0 ? void 0 : fn();
|
|
185
|
+
} catch (error) {
|
|
186
|
+
failed = true;
|
|
187
|
+
failure = error;
|
|
188
|
+
} finally {
|
|
189
|
+
rt.batchDepth -= 1;
|
|
190
|
+
}
|
|
191
|
+
if (sync || rt.batchDepth === 0 && !rt.flushing && hasPending()) try {
|
|
192
|
+
flush();
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (failed) throw new AggregateError([failure, error], "Both the callback and the flush threw.");
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
if (failed) throw failure;
|
|
198
|
+
return result;
|
|
190
199
|
}
|
|
191
200
|
/**
|
|
192
201
|
* Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so
|
|
@@ -211,26 +220,7 @@ function combine(primary, secondary) {
|
|
|
211
220
|
* @since 1.0.0
|
|
212
221
|
*/
|
|
213
222
|
function batch(fn) {
|
|
214
|
-
|
|
215
|
-
let result;
|
|
216
|
-
let failure;
|
|
217
|
-
let failed = false;
|
|
218
|
-
try {
|
|
219
|
-
result = fn();
|
|
220
|
-
} catch (error) {
|
|
221
|
-
failed = true;
|
|
222
|
-
failure = error;
|
|
223
|
-
} finally {
|
|
224
|
-
rt.batchDepth -= 1;
|
|
225
|
-
}
|
|
226
|
-
if (rt.batchDepth === 0 && !rt.flushing && hasPending()) try {
|
|
227
|
-
flush();
|
|
228
|
-
} catch (error) {
|
|
229
|
-
if (failed) throw combine(failure, error);
|
|
230
|
-
throw error;
|
|
231
|
-
}
|
|
232
|
-
if (failed) throw failure;
|
|
233
|
-
return result;
|
|
223
|
+
return runBatched(fn, false);
|
|
234
224
|
}
|
|
235
225
|
/**
|
|
236
226
|
* Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and
|
|
@@ -260,27 +250,8 @@ function flushSync(fn) {
|
|
|
260
250
|
warn("FLUSH_IN_EFFECT");
|
|
261
251
|
return fn === void 0 ? void 0 : fn();
|
|
262
252
|
}
|
|
263
|
-
|
|
264
|
-
let result;
|
|
265
|
-
let failure;
|
|
266
|
-
let failed = false;
|
|
267
|
-
try {
|
|
268
|
-
result = fn === void 0 ? void 0 : fn();
|
|
269
|
-
} catch (error) {
|
|
270
|
-
failed = true;
|
|
271
|
-
failure = error;
|
|
272
|
-
} finally {
|
|
273
|
-
rt.batchDepth -= 1;
|
|
274
|
-
}
|
|
275
|
-
try {
|
|
276
|
-
flush();
|
|
277
|
-
} catch (error) {
|
|
278
|
-
if (failed) throw combine(failure, error);
|
|
279
|
-
throw error;
|
|
280
|
-
}
|
|
281
|
-
if (failed) throw failure;
|
|
282
|
-
return result;
|
|
253
|
+
return runBatched(fn, true);
|
|
283
254
|
}
|
|
284
|
-
export { MAX_FLUSH_PASSES, batch, byCreation, flush, flushSync, group,
|
|
255
|
+
export { MAX_FLUSH_PASSES, batch, byCreation, flush, flushSync, group, reportUncaught, runQueued, schedule };
|
|
285
256
|
|
|
286
257
|
//# sourceMappingURL=scheduler.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.js","names":[],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Effects mostly arrive in creation order already; checking is O(n), sorting is not.\n * @internal\n */\nexport function isOrdered(list: readonly Computation[]): boolean {\n for (let i = 1; i < list.length; i += 1) {\n const previous = list[i - 1];\n const current = list[i];\n if (previous !== undefined && current !== undefined && byCreation(previous, current) > 0) {\n return false;\n }\n }\n return true;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n let aborted = false;\n // Render passes count too: a render effect that keeps writing its own source must abort.\n while (renderQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n aborted = true;\n break;\n }\n runs += drain(renderQueue);\n }\n if (!aborted && userQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) aborted = true;\n else runs += drain(userQueue);\n }\n if (aborted) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\nfunction combine(primary: unknown, secondary: unknown): unknown {\n return new AggregateError(\n [primary, secondary],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n if (failed) throw failure;\n return result as T;\n}\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,mBAAmB;AAEhC,IAAI,qBAAqB;;;;;AAMzB,SAAgB,WAAW,GAAgB,GAAwB;CACjE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE;AACxC;;;;;AAMA,SAAgB,UAAU,MAAuC;CAC/D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;EACvC,MAAM,WAAW,KAAK,IAAI;EAC1B,MAAM,UAAU,KAAK;EACrB,IAAI,aAAa,KAAA,KAAa,YAAY,KAAA,KAAa,WAAW,UAAU,OAAO,IAAI,GACrF,OAAO;CAEX;CACA,OAAO;AACT;;AAGA,SAAS,MAAM,OAA8B;CAC3C,MAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,MAAM;CAC1C,IAAI,CAAC,UAAU,KAAK,GAAG,MAAM,KAAK,UAAU;CAC5C,KAAK,MAAM,UAAU,OAAO;EAC1B,OAAO,SAAS;EAChB,KAAK,OAAO,QAAA,OAA2B,GAAG;EAC1C,IAAI,OAAO,SAAS,GAAG;GAErB,OAAO,QAAS,OAAO,QAAQ,CAAC,kBAAmB;GACnD;EACF;EACA,IAAI;GAEF,IAAI,OAAO,UAAA,GAAiB,UAAU,MAAM;QACvC,kBAAkB,MAAM;EAC/B,SAAS,OAAO;GACd,YAAY,OAAO,MAAM;EAC3B;CACF;CACA,OAAO,MAAM;AACf;AAEA,SAAS,MAAM,QAAyB;CACtC,MAAM,CAAC,SAAS;CAChB,IAAI,OAAO,WAAW,GAAG,MAAM;CAC/B,MAAM,IAAI,eACR,QACU,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G;CACZ,UAAU;EACR,GAAG,cAAc;EACjB,IAAI,GAAG,eAAe,KAAK,WAAW,GAAG,SAAS;CACpD;AACF;AAEA,SAAS,QAAQ,SAAkB,WAA6B;CAC9D,OAAO,IAAI,eACT,CAAC,SAAS,SAAS,GACT,wCACZ;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,MAAS,IAAgB;CACvC,GAAG,cAAc;CACjB,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS;CACb,IAAI;EACF,SAAS,GAAG;CACd,SAAS,OAAO;EACd,SAAS;EACT,UAAU;CACZ,UAAU;EACR,GAAG,cAAc;CACnB;CACA,IAAI,GAAG,eAAe,KAAK,CAAC,GAAG,YAAY,WAAW,GACpD,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,IAAI,QAAQ,MAAM,QAAQ,SAAS,KAAK;EACxC,MAAM;CACR;CAEF,IAAI,QAAQ,MAAM;CAClB,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,UAAoB,IAAiB;CACnD,IAAI,GAAG,UAAU;EACf,KAAK,iBAAiB;EACtB,OAAQ,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC5C;CACA,GAAG,cAAc;CACjB,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS;CACb,IAAI;EACF,SAAS,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC7C,SAAS,OAAO;EACd,SAAS;EACT,UAAU;CACZ,UAAU;EACR,GAAG,cAAc;CACnB;CACA,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,IAAI,QAAQ,MAAM,QAAQ,SAAS,KAAK;EACxC,MAAM;CACR;CACA,IAAI,QAAQ,MAAM;CAClB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"scheduler.js","names":[],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, refreshAncestors, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Runs one queued effect. Its stale owners come first: an owner that is about to re-run disposes the\n * effect, and running it before (a zombie, G-17) would read state that is already out of date.\n * @internal\n */\nexport function runQueued(effect: Computation): void {\n try {\n if (!refreshAncestors(effect)) return;\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n // Effects mostly arrive in creation order already: the sort then finds one ascending run and is O(n).\n batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n runs += drain(renderQueue.length > 0 ? renderQueue : userQueue);\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (sync || (rt.batchDepth === 0 && !rt.flushing && hasPending())) {\n try {\n flush();\n } catch (error) {\n if (failed) {\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n }\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n return runBatched(fn, true);\n}\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,mBAAmB;AAEhC,IAAI,qBAAqB;;;;;AAMzB,SAAgB,WAAW,GAAgB,GAAwB;CACjE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE;AACxC;;;;;;AAOA,SAAgB,UAAU,QAA2B;CACnD,IAAI;EACF,IAAI,CAAC,iBAAiB,MAAM,GAAG;EAE/B,IAAI,OAAO,UAAA,GAAiB,UAAU,MAAM;OACvC,kBAAkB,MAAM;CAC/B,SAAS,OAAO;EACd,YAAY,OAAO,MAAM;CAC3B;AACF;;AAGA,SAAS,MAAM,OAA8B;CAC3C,MAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,MAAM;CAE1C,MAAM,KAAK,UAAU;CACrB,KAAK,MAAM,UAAU,OAAO;EAC1B,OAAO,SAAS;EAChB,KAAK,OAAO,QAAA,OAA2B,GAAG;EAC1C,IAAI,OAAO,SAAS,GAAG;GAErB,OAAO,QAAS,OAAO,QAAQ,CAAC,kBAAmB;GACnD;EACF;EACA,UAAU,MAAM;CAClB;CACA,OAAO,MAAM;AACf;AAEA,SAAS,MAAM,QAAyB;CACtC,MAAM,CAAC,SAAS;CAChB,IAAI,OAAO,WAAW,GAAG,MAAM;CAC/B,MAAM,IAAI,eACR,QACU,oDACZ;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,QAAc;CAC5B,IAAI,GAAG,UAAU;CACjB,GAAG,WAAW;CACd,IAAI,SAAS;CACb,IAAI,OAAO;CACE,OAAO,eAAe,aAAa,YAAY,QAAQ,UAAU,MAAM;CACpF,IAAI;EACF,OAAO,WAAW,GAAG;GAGnB,UAAU;GACV,IAAI,SAAA,KAA2B;IAC7B,YA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,eACR,CAAC,SAAS,KAAK,GACL,wCACZ;EAEF,MAAM;CACR;CAEF,IAAI,QAAQ,MAAM;CAClB,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,MAAS,IAAgB;CACvC,OAAO,WAAW,IAAI,KAAK;AAC7B;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,UAAoB,IAAiB;CACnD,IAAI,GAAG,UAAU;EACf,KAAK,iBAAiB;EACtB,OAAQ,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC5C;CACA,OAAO,WAAW,IAAI,IAAI;AAC5B"}
|
package/dist/server-dev/list.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { warn } from "./internal/diagnostics.js";
|
|
2
2
|
import { Owner } from "./internal/owner.js";
|
|
3
|
-
import { readSignal } from "./internal/graph.js";
|
|
3
|
+
import { Signal, readSignal } from "./internal/graph.js";
|
|
4
4
|
import { createRoot, getOwner, onCleanup, runWithOwner, untrack } from "./ownership.js";
|
|
5
5
|
import { disposeTree } from "./internal/dispose.js";
|
|
6
|
-
import {
|
|
6
|
+
import { writeSignal } from "./extend/index.js";
|
|
7
7
|
import { useMemo } from "./memo.js";
|
|
8
8
|
// src/list.ts
|
|
9
9
|
/**
|
|
@@ -11,14 +11,6 @@ import { useMemo } from "./memo.js";
|
|
|
11
11
|
* by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.
|
|
12
12
|
*/
|
|
13
13
|
var Row = class {
|
|
14
|
-
/** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */
|
|
15
|
-
key;
|
|
16
|
-
/** False for a later copy of a key in a keyed list. Such a row is never reused. */
|
|
17
|
-
first;
|
|
18
|
-
/** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */
|
|
19
|
-
item;
|
|
20
|
-
/** Index last written to the row. */
|
|
21
|
-
index;
|
|
22
14
|
value = void 0;
|
|
23
15
|
dispose = noop;
|
|
24
16
|
/** Created by the first `item()` read; null until then. */
|
|
@@ -32,11 +24,11 @@ var Row = class {
|
|
|
32
24
|
this.index = index;
|
|
33
25
|
}
|
|
34
26
|
readItem() {
|
|
35
|
-
this.itemNode ??=
|
|
27
|
+
this.itemNode ??= new Signal(this.item, Object.is);
|
|
36
28
|
return readSignal(this.itemNode);
|
|
37
29
|
}
|
|
38
30
|
readIndex() {
|
|
39
|
-
this.indexNode ??=
|
|
31
|
+
this.indexNode ??= new Signal(this.index, Object.is);
|
|
40
32
|
return readSignal(this.indexNode);
|
|
41
33
|
}
|
|
42
34
|
/** List bookkeeping, not a user write: allowed while the list memo computes. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list.js","names":[],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n item: T;\n /** Index last written to the row. */\n index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were th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AM,QAAQ,KAAK;EACnB,IAAI,UAAU,KAAA,KAAa,CAAC,MAAM,OAAO;EACzC,MAAM,OAAO,MAAM,IAAI,MAAM,GAAG;EAChC,IAAI,SAAS,KAAA,KAAa,SAAS,IAAI;EACvC,MAAM,KAAK;EACX,MAAM,IAAI,MAAM,KAAK,MAAM,SAAS,EAAE;CACxC;CACA,OAAO;AACT;;;;;AAMA,SAAS,QACP,QACA,KACA,OACA,MACA,OACA,OACW;CACX,MAAM,MAAM,IAAI,IAAU,KAAK,OAAO,MAAM,KAAK;CACjD,MAAM,iBAAoB,IAAI,SAAS;CACvC,MAAM,kBAA0B,IAAI,UAAU;CAC9C,aAAa,cACX,YAAY,YAAY;EACtB,IAAI,UAAU;EACd,IAAI,QAAQ,cAAc,MAAM,MAAM,UAAU,SAAS,CAAC;CAC5D,CAAC,CACH;CACA,OAAO;AACT;;AAGA,SAAS,aAAgB,QAAe,UAAgC;CACtE,OAAO,aAAa,cAClB,YAAY,aAAa;EAAE,OAAO,QAAQ,QAAQ;EAAG;CAAQ,EAAE,CACjE;AACF;;AAGA,SAAS,kBAAkB,SAAqB,UAA2B;CACzE,IAAI;EACF,QAAQ;CACV,SAAS,OAAO;EACd,SAAS,KAAK,KAAK;CACrB;AACF;AAEA,SAAS,gBAAgB,SAAkB,UAAuC;CAChF,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,OAAO,IAAI,eACT,CAAC,SAAS,GAAG,QAAQ,GACX,kDACZ;AACF;;AAGA,SAAS,cAAc,UAAoC;CACzD,IAAI,SAAS,WAAW,GAAG;CAC3B,IAAI,SAAS,WAAW,GAAG,MAAM,SAAS;CAC1C,MAAM,IAAI,eACR,UAEI,uDAEN;AACF"}
|
|
1
|
+
{"version":3,"file":"list.js","names":["SignalNode"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n disposeOwner,\n Owner,\n readSignal,\n SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n declare readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n declare readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n declare item: T;\n /** Index last written to the row. */\n declare index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= new SignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= new SignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,IAAM,MAAN,MAAgB;CASd,QAAW,KAAA;CACX,UAAsB;;CAEtB,WAAyC;;CAEzC,YAA+C;CAE/C,YAAY,KAAc,OAAgB,MAAS,OAAe;EAChE,KAAK,MAAM;EACX,KAAK,QAAQ;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;CAEA,WAAc;EACZ,KAAK,aAAa,IAAIA,OAAW,KAAK,MAAM,OAAO,EAAE;EACrD,OAAO,WAAW,KAAK,QAAQ;CACjC;CAEA,YAAoB;EAClB,KAAK,cAAc,IAAIA,OAAW,KAAK,OAAO,OAAO,EAAE;EACvD,OAAO,WAAW,KAAK,SAAS;CAClC;;CAGA,QAAQ,MAAe;EACrB,KAAK,OAAO;EACZ,IAAI,KAAK,aAAa,MAAM,YAAY,KAAK,UAAU,MAAM,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AAa;EAAE,OAAO,QAAQ,QAAQ;EAAG;CAAQ,EAAE,CACjE;AACF;;AAGA,SAAS,kBAAkB,SAAqB,UAA2B;CACzE,IAAI;EACF,QAAQ;CACV,SAAS,OAAO;EACd,SAAS,KAAK,KAAK;CACrB;AACF;AAEA,SAAS,gBAAgB,SAAkB,UAAuC;CAChF,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,OAAO,IAAI,eACT,CAAC,SAAS,GAAG,QAAQ,GACX,kDACZ;AACF;;AAGA,SAAS,cAAc,UAAoC;CACzD,IAAI,SAAS,WAAW,GAAG;CAC3B,IAAI,SAAS,WAAW,GAAG,MAAM,SAAS;CAC1C,MAAM,IAAI,eACR,UAEI,uDAEN;AACF"}
|
package/dist/server-dev/memo.js
CHANGED
|
@@ -28,10 +28,10 @@ function useMemo(fn, options) {
|
|
|
28
28
|
const node = createComputation({
|
|
29
29
|
kind: "memo",
|
|
30
30
|
fn,
|
|
31
|
-
equals: options?.equals
|
|
32
|
-
lazy: options?.lazy
|
|
33
|
-
allowWrites: options?.allowWrites
|
|
34
|
-
|
|
31
|
+
equals: options?.equals,
|
|
32
|
+
lazy: options?.lazy,
|
|
33
|
+
allowWrites: options?.allowWrites,
|
|
34
|
+
name: options?.name
|
|
35
35
|
});
|
|
36
36
|
return () => readComputation(node);
|
|
37
37
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memo.js","names":[],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals:
|
|
1
|
+
{"version":3,"file":"memo.js","names":[],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates. It runs untracked: a signal it reads is not a dependency of\n * the memo or of the reader that pulled it.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals: options?.equals as Equals<unknown> | undefined,\n lazy: options?.lazy,\n allowWrites: options?.allowWrites,\n name: options?.name,\n });\n return () => readComputation<T>(node);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,QACd,IACA,SACa;CACb,MAAM,OAAO,kBAAkB;EAC7B,MAAM;EACF;EACJ,QAAQ,SAAS;EACjB,MAAM,SAAS;EACf,aAAa,SAAS;EACtB,MAAM,SAAS;CACjB,CAAC;CACD,aAAa,gBAAmB,IAAI;AACtC"}
|
|
@@ -3,6 +3,55 @@ import { Owner, addCleanup, handleError } from "./internal/owner.js";
|
|
|
3
3
|
import { disposeTree } from "./internal/dispose.js";
|
|
4
4
|
import { currentOwner, runInScope } from "./extend/index.js";
|
|
5
5
|
// src/ownership.ts
|
|
6
|
+
/** Where the copies of core list themselves; `Symbol.for` makes the key the same in every copy. */
|
|
7
|
+
const REGISTRY_KEY = "shadow-js.core.instances";
|
|
8
|
+
/**
|
|
9
|
+
* The most copies the registry lists. Real programs have one, a misconfigured one two or three; the
|
|
10
|
+
* limit keeps a program that loads core in a loop (a hot-reload bug) from growing the shared map.
|
|
11
|
+
*/
|
|
12
|
+
const MAX_LISTED_COPIES = 8;
|
|
13
|
+
/**
|
|
14
|
+
* The identity of this copy of the module (every evaluation of the module makes its own) and the build it is:
|
|
15
|
+
* the server build and the client build are different files by design, and tests that render on the server
|
|
16
|
+
* and hydrate in one process load one of each, so only copies of the same build count as duplicates.
|
|
17
|
+
*/
|
|
18
|
+
const COPY = { server: true };
|
|
19
|
+
/** The registry of the copies of core and how many roots each has alive, or undefined before any root exists. */
|
|
20
|
+
function copyRegistry() {
|
|
21
|
+
const found = globalThis[Symbol.for(REGISTRY_KEY)];
|
|
22
|
+
return found instanceof Map ? found : void 0;
|
|
23
|
+
}
|
|
24
|
+
/** Development only. Counts a disposed root out of this copy's entry; the entry goes with its last root. */
|
|
25
|
+
function releaseRoot() {
|
|
26
|
+
const registry = copyRegistry();
|
|
27
|
+
const live = registry?.get(COPY);
|
|
28
|
+
if (registry === void 0 || live === void 0) return;
|
|
29
|
+
if (live > 1) registry.set(COPY, live - 1);
|
|
30
|
+
else registry.delete(COPY);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Development only. Lists a new root under this copy of core in a registry on `globalThis`, which counts the
|
|
34
|
+
* live roots of every copy, and warns `DUPLICATE_CORE` (once per copy) when another copy of the same build has
|
|
35
|
+
* live roots: two copies cannot see each other's signals. A copy leaves the registry when its last root is disposed, so copies
|
|
36
|
+
* that never run at the same time (separate test files, a reload) do not warn. Called from `createRoot` only
|
|
37
|
+
* behind `__DEV__`, and only when a root is created, never when the module is imported. The release is one
|
|
38
|
+
* shared function, so a root costs no closure: rows of a list make a root each.
|
|
39
|
+
*/
|
|
40
|
+
function listRoot(root) {
|
|
41
|
+
let registry = copyRegistry();
|
|
42
|
+
if (registry === void 0) {
|
|
43
|
+
registry = /* @__PURE__ */ new Map();
|
|
44
|
+
globalThis[Symbol.for(REGISTRY_KEY)] = registry;
|
|
45
|
+
}
|
|
46
|
+
const listed = registry.has(COPY);
|
|
47
|
+
for (const copy of registry.keys()) if (copy !== COPY && copy.server === COPY.server) {
|
|
48
|
+
warn("DUPLICATE_CORE");
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
if (!listed && registry.size >= MAX_LISTED_COPIES) return;
|
|
52
|
+
registry.set(COPY, (registry.get(COPY) ?? 0) + 1);
|
|
53
|
+
addCleanup(root, releaseRoot);
|
|
54
|
+
}
|
|
6
55
|
/**
|
|
7
56
|
* Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an
|
|
8
57
|
* effect or a memo to read a value without re-running when that value changes. The current owner
|
|
@@ -30,14 +79,16 @@ function untrack(fn) {
|
|
|
30
79
|
* Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is
|
|
31
80
|
* disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use
|
|
32
81
|
* it for code that runs outside a component, such as an app entry point, a test or a module that
|
|
33
|
-
* owns long-lived effects.
|
|
82
|
+
* owns long-lived effects. Development builds also use the root to find a second copy of core: a root
|
|
83
|
+
* created while a root of another copy is alive warns `DUPLICATE_CORE` once.
|
|
34
84
|
*
|
|
35
85
|
* @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.
|
|
36
86
|
* @param options `detached` keeps the root out of the current owner. Undefined uses the default
|
|
37
87
|
* (attached).
|
|
38
88
|
* @returns Whatever `fn` returns.
|
|
39
89
|
* @throws Rethrows any error thrown by `fn`, after the root and everything created in it are
|
|
40
|
-
* disposed.
|
|
90
|
+
* disposed. When a cleanup of the root throws as well, both errors are thrown together as an
|
|
91
|
+
* `AggregateError` (the body's first), so the body's error is never replaced.
|
|
41
92
|
* @example
|
|
42
93
|
* import { createRoot, useEffect, useSignal } from "@shadow-js/core";
|
|
43
94
|
*
|
|
@@ -56,13 +107,18 @@ function createRoot(fn, options) {
|
|
|
56
107
|
const current = currentOwner();
|
|
57
108
|
const root = new Owner(detached ? null : current);
|
|
58
109
|
if (detached) root.context = current === null ? null : current.context;
|
|
110
|
+
listRoot(root);
|
|
59
111
|
try {
|
|
60
112
|
return runInScope({
|
|
61
113
|
owner: root,
|
|
62
114
|
listener: null
|
|
63
115
|
}, () => fn(() => disposeTree(root)));
|
|
64
116
|
} catch (error) {
|
|
65
|
-
|
|
117
|
+
try {
|
|
118
|
+
disposeTree(root);
|
|
119
|
+
} catch (cleanupError) {
|
|
120
|
+
throw new AggregateError([error, cleanupError], "The root body threw and so did its disposal.");
|
|
121
|
+
}
|
|
66
122
|
throw error;
|
|
67
123
|
}
|
|
68
124
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownership.js","names":["disposeOwner"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n disposeOwner(root);\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,QAAW,IAAgB;CACzC,OAAO,WAAW,EAAE,UAAU,KAAK,GAAG,EAAE;AAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,WAAc,IAAgC,SAA0B;CACtF,MAAM,WAAW,SAAS,aAAa;CACvC,MAAM,UAAU,aAAa;CAC7B,MAAM,OAAO,IAAI,MAAM,WAAW,OAAO,OAAO;CAChD,IAAI,UAAU,KAAK,UAAU,YAAY,OAAO,OAAO,QAAQ;CAC/D,IAAI;EACF,OAAO,WAAW;GAAE,OAAO;GAAM,UAAU;EAAK,SAAS,SAASA,YAAa,IAAI,CAAC,CAAC;CACvF,SAAS,OAAO;EACd,YAAa,IAAI;EACjB,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,WAAyB;CACvC,OAA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M,OAAO,KAAK,QAAQ,KAAK,KAAK,KAAK,KAAK;CAC5F,KAAK,QAAQ;CACb,MAAM,WAAW,MAAM;CACvB,MAAM,WAAW;CACjB,OAAO,IAAI,KAAK,KAAK,GAAG,EAAE,GAAG;AAC/B"}
|
|
1
|
+
{"version":3,"file":"ownership.js","names":["disposeOwner"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/** Where the copies of core list themselves; `Symbol.for` makes the key the same in every copy. */\nconst REGISTRY_KEY = \"shadow-js.core.instances\";\n\n/**\n * The most copies the registry lists. Real programs have one, a misconfigured one two or three; the\n * limit keeps a program that loads core in a loop (a hot-reload bug) from growing the shared map.\n */\nconst MAX_LISTED_COPIES = 8;\n\n/**\n * The identity of this copy of the module (every evaluation of the module makes its own) and the build it is:\n * the server build and the client build are different files by design, and tests that render on the server\n * and hydrate in one process load one of each, so only copies of the same build count as duplicates.\n */\nconst COPY: { readonly server: boolean } = { server: __SERVER__ };\n\n/** The registry of the copies of core and how many roots each has alive, or undefined before any root exists. */\nfunction copyRegistry(): Map<{ readonly server: boolean }, number> | undefined {\n const found = (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)];\n return found instanceof Map ? found : undefined;\n}\n\n/** Development only. Counts a disposed root out of this copy's entry; the entry goes with its last root. */\nfunction releaseRoot(): void {\n const registry = copyRegistry();\n const live = registry?.get(COPY);\n if (registry === undefined || live === undefined) return;\n if (live > 1) registry.set(COPY, live - 1);\n else registry.delete(COPY);\n}\n\n/**\n * Development only. Lists a new root under this copy of core in a registry on `globalThis`, which counts the\n * live roots of every copy, and warns `DUPLICATE_CORE` (once per copy) when another copy of the same build has\n * live roots: two copies cannot see each other's signals. A copy leaves the registry when its last root is disposed, so copies\n * that never run at the same time (separate test files, a reload) do not warn. Called from `createRoot` only\n * behind `__DEV__`, and only when a root is created, never when the module is imported. The release is one\n * shared function, so a root costs no closure: rows of a list make a root each.\n */\nfunction listRoot(root: Owner): void {\n let registry = copyRegistry();\n if (registry === undefined) {\n registry = new Map();\n (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)] = registry;\n }\n const listed = registry.has(COPY);\n for (const copy of registry.keys()) {\n if (copy !== COPY && copy.server === COPY.server) {\n warn(\"DUPLICATE_CORE\");\n break;\n }\n }\n // A copy past the limit is not listed; the warning above has been given by then.\n if (!listed && registry.size >= MAX_LISTED_COPIES) return;\n registry.set(COPY, (registry.get(COPY) ?? 0) + 1);\n addCleanup(root, releaseRoot);\n}\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects. Development builds also use the root to find a second copy of core: a root\n * created while a root of another copy is alive warns `DUPLICATE_CORE` once.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed. When a cleanup of the root throws as well, both errors are thrown together as an\n * `AggregateError` (the body's first), so the body's error is never replaced.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n if (__DEV__) listRoot(root);\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n try {\n disposeOwner(root);\n } catch (cleanupError) {\n // The body's error says what went wrong; a cleanup error must not replace it.\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"The root body threw and so did its disposal.\" : \"SHADOW_ROOT_ERRORS\",\n );\n }\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":";;;;;;AAgBA,MAAM,eAAe;;;;;AAMrB,MAAM,oBAAoB;;;;;;AAO1B,MAAM,OAAqC,EAAE,QAAA,KAAmB;;AAGhE,SAAS,eAAsE;CAC7E,MAAM,QAAS,WAA0C,OAAO,IAAI,YAAY;CAChF,OAAO,iBAAiB,MAAM,QAAQ,KAAA;AACxC;;AAGA,SAAS,cAAoB;CAC3B,MAAM,WAAW,aAAa;CAC9B,MAAM,OAAO,UAAU,IAAI,IAAI;CAC/B,IAAI,aAAa,KAAA,KAAa,SAAS,KAAA,GAAW;CAClD,IAAI,OAAO,GAAG,SAAS,IAAI,MAAM,OAAO,CAAC;MACpC,SAAS,OAAO,IAAI;AAC3B;;;;;;;;;AAUA,SAAS,SAAS,MAAmB;CACnC,IAAI,WAAW,aAAa;CAC5B,IAAI,aAAa,KAAA,GAAW;EAC1B,2BAAW,IAAI,IAAI;EACnB,WAA2C,OAAO,IAAI,YAAY,KAAK;CACzE;CACA,MAAM,SAAS,SAAS,IAAI,IAAI;CAChC,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