@shadow-js/core 1.0.0 → 1.0.2
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 +19 -0
- package/dist/dev/action.d.ts +0 -2
- package/dist/dev/action.js +1 -2
- package/dist/dev/cache.d.ts +2 -3
- package/dist/dev/cache.js +6 -5
- package/dist/dev/cache.js.map +1 -1
- package/dist/dev/context.d.ts +0 -2
- package/dist/dev/context.js +1 -2
- package/dist/dev/effect.d.ts +0 -2
- package/dist/dev/effect.js +18 -35
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/env.d.ts +0 -2
- package/dist/dev/env.js +1 -2
- package/dist/dev/events.d.ts +0 -2
- package/dist/dev/events.js +1 -2
- package/dist/dev/extend/index.d.ts +7 -8
- package/dist/dev/extend/index.js +8 -9
- package/dist/dev/extend/index.js.map +1 -1
- package/dist/dev/external-store.d.ts +0 -2
- package/dist/dev/external-store.js +9 -5
- package/dist/dev/external-store.js.map +1 -1
- package/dist/dev/internal/concurrency.d.ts +0 -2
- package/dist/dev/internal/concurrency.js +43 -22
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/devtools.d.ts +0 -2
- package/dist/dev/internal/devtools.js +1 -2
- package/dist/dev/internal/diagnostics.d.ts +0 -2
- package/dist/dev/internal/diagnostics.js +1 -4
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/dispose.d.ts +0 -2
- package/dist/dev/internal/dispose.js +1 -2
- package/dist/dev/internal/flags.js +2 -5
- package/dist/dev/internal/flags.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +0 -3
- package/dist/dev/internal/graph.js +21 -39
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/hydration-flag.d.ts +0 -2
- package/dist/dev/internal/hydration-flag.js +1 -2
- package/dist/dev/internal/messages.d.ts +0 -2
- package/dist/dev/internal/messages.js +1 -2
- package/dist/dev/internal/owner.d.ts +7 -7
- package/dist/dev/internal/owner.js +13 -24
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/queue.js +1 -2
- package/dist/dev/internal/scheduler.d.ts +0 -2
- package/dist/dev/internal/scheduler.js +34 -73
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/internal/state.d.ts +0 -2
- package/dist/dev/internal/state.js +1 -2
- package/dist/dev/internal/suspension.d.ts +0 -2
- package/dist/dev/internal/suspension.js +1 -2
- package/dist/dev/internal/types.d.ts +0 -2
- package/dist/dev/list.d.ts +0 -2
- package/dist/dev/list.js +1 -10
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/memo.d.ts +2 -3
- package/dist/dev/memo.js +5 -6
- package/dist/dev/memo.js.map +1 -1
- package/dist/dev/optimistic.d.ts +0 -2
- package/dist/dev/optimistic.js +1 -2
- package/dist/dev/ownership.d.ts +4 -4
- package/dist/dev/ownership.js +60 -5
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.d.ts +0 -2
- package/dist/dev/props.js +19 -13
- package/dist/dev/props.js.map +1 -1
- package/dist/dev/reaction.d.ts +1 -3
- package/dist/dev/reaction.js +6 -3
- package/dist/dev/reaction.js.map +1 -1
- package/dist/dev/reducer.d.ts +0 -2
- package/dist/dev/reducer.js +2 -3
- package/dist/dev/reducer.js.map +1 -1
- package/dist/dev/refs.d.ts +0 -2
- package/dist/dev/refs.js +1 -2
- package/dist/dev/resource.d.ts +0 -2
- package/dist/dev/resource.js +22 -14
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/selector.d.ts +0 -2
- package/dist/dev/selector.js +2 -7
- package/dist/dev/selector.js.map +1 -1
- package/dist/dev/signal.d.ts +3 -4
- package/dist/dev/signal.js +1 -2
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +7 -2
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/proxies.js +1 -2
- package/dist/dev/store/read.d.ts +0 -2
- package/dist/dev/store/read.js +1 -2
- package/dist/dev/store/reconcile.d.ts +0 -2
- package/dist/dev/store/reconcile.js +1 -2
- package/dist/dev/store/types.d.ts +0 -2
- package/dist/dev/store/use-store.d.ts +5 -2
- package/dist/dev/store/use-store.js +1 -2
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/suspense.d.ts +0 -2
- package/dist/dev/suspense.js +1 -2
- package/dist/dev/transitions.d.ts +0 -2
- package/dist/dev/transitions.js +2 -3
- package/dist/dev/transitions.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/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.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/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/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.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 +1 -2
- package/dist/server-dev/cache.js +6 -5
- package/dist/server-dev/cache.js.map +1 -1
- package/dist/server-dev/context.js +1 -2
- package/dist/server-dev/effect.js +1 -2
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/env.js +1 -2
- package/dist/server-dev/events.js +1 -2
- package/dist/server-dev/extend/index.js +8 -9
- package/dist/server-dev/extend/index.js.map +1 -1
- package/dist/server-dev/external-store.js +1 -2
- package/dist/server-dev/external-store.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +43 -22
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/devtools.js +1 -2
- package/dist/server-dev/internal/diagnostics.js +1 -4
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +1 -2
- package/dist/server-dev/internal/flags.js +2 -5
- package/dist/server-dev/internal/flags.js.map +1 -1
- package/dist/server-dev/internal/graph.js +21 -39
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/hydration-flag.js +1 -2
- package/dist/server-dev/internal/messages.js +1 -2
- package/dist/server-dev/internal/owner.js +13 -24
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/queue.js +1 -2
- package/dist/server-dev/internal/scheduler.js +34 -73
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/internal/state.js +1 -2
- package/dist/server-dev/internal/suspension.js +1 -2
- package/dist/server-dev/list.js +1 -10
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/memo.js +5 -6
- package/dist/server-dev/memo.js.map +1 -1
- package/dist/server-dev/optimistic.js +1 -2
- package/dist/server-dev/ownership.js +60 -5
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +19 -13
- package/dist/server-dev/props.js.map +1 -1
- package/dist/server-dev/reaction.js +6 -3
- package/dist/server-dev/reaction.js.map +1 -1
- package/dist/server-dev/reducer.js +2 -3
- package/dist/server-dev/reducer.js.map +1 -1
- package/dist/server-dev/refs.js +1 -2
- package/dist/server-dev/resource.js +22 -14
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/selector.js +2 -7
- package/dist/server-dev/selector.js.map +1 -1
- package/dist/server-dev/signal.js +1 -2
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +7 -2
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/proxies.js +1 -2
- package/dist/server-dev/store/read.js +1 -2
- package/dist/server-dev/store/reconcile.js +1 -2
- package/dist/server-dev/store/use-store.js +1 -2
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/suspense.js +1 -2
- package/dist/server-dev/transitions.js +1 -2
- package/dist/server-dev/transitions.js.map +1 -1
- package/package.json +2 -1
|
@@ -4,14 +4,14 @@ import { ShadowError, resetWarningDedupe, setWarningListener, warn } from "../in
|
|
|
4
4
|
import { rt } from "../internal/state.js";
|
|
5
5
|
import { Owner, addCleanup, handleError } from "../internal/owner.js";
|
|
6
6
|
import { enqueue } from "../internal/queue.js";
|
|
7
|
-
import { Computation, Signal, hasObservers, markObservers, observersOf, readMemo, readSignal, recompute, sourcesOf, track, updateIfNecessary } from "../internal/graph.js";
|
|
7
|
+
import { Computation, Signal, hasObservers, isEqual, markObservers, observersOf, readMemo, readSignal, recompute, sourcesOf, track, updateIfNecessary } from "../internal/graph.js";
|
|
8
8
|
import { batch, flush, flushSync, group, schedule } from "../internal/scheduler.js";
|
|
9
9
|
import { runWithContext } from "../context.js";
|
|
10
10
|
import { disposeTree } from "../internal/dispose.js";
|
|
11
11
|
import { SUSPENSION, isSuspension } from "../internal/suspension.js";
|
|
12
12
|
import { beginHold, createTransitionHold, endHold, holdReader, inTransition, pauseOwner, registerTransitionLane, resumeOwner, startTransition, transitionHooks, wakeSuspended } from "../internal/concurrency.js";
|
|
13
13
|
import { isHydrating, withHydration } from "../internal/hydration-flag.js";
|
|
14
|
-
|
|
14
|
+
// src/extend.ts
|
|
15
15
|
/**
|
|
16
16
|
* The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,
|
|
17
17
|
* `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import
|
|
@@ -141,7 +141,8 @@ function runInScope(scope, fn) {
|
|
|
141
141
|
*
|
|
142
142
|
* @param value Initial value.
|
|
143
143
|
* @param equals Decides whether a write is a change: readers are notified only when it returns
|
|
144
|
-
* `false`. `false` notifies on every write.
|
|
144
|
+
* `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's
|
|
145
|
+
* own `equals`), so what it reads is not a dependency of the writer or the reader.
|
|
145
146
|
* @param name Label shown by devtools. Undefined leaves the signal unnamed.
|
|
146
147
|
* @returns The signal node. It has no owner: it lives as long as something references it.
|
|
147
148
|
* @example
|
|
@@ -181,7 +182,7 @@ function createSignalNode(value, equals, name) {
|
|
|
181
182
|
function writeSignal(signal, next, options) {
|
|
182
183
|
if (options?.allowInMemo !== true && isComputingMemo()) throw new ShadowError("WRITE_IN_MEMO");
|
|
183
184
|
const equals = signal.equals;
|
|
184
|
-
if (equals !== false && equals
|
|
185
|
+
if (equals !== false && isEqual(equals, signal.value, next)) return false;
|
|
185
186
|
signal.value = next;
|
|
186
187
|
report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));
|
|
187
188
|
notify(signal);
|
|
@@ -233,13 +234,12 @@ function notify(source) {
|
|
|
233
234
|
*/
|
|
234
235
|
function createComputation(options) {
|
|
235
236
|
const owner = options.owner === void 0 ? rt.owner : options.owner;
|
|
236
|
-
|
|
237
|
-
|
|
237
|
+
const memo = options.kind === "memo";
|
|
238
|
+
const node = new Computation(owner, memo ? 1 : 2, memo ? 32 | (options.allowWrites === true ? 256 : 0) : (options.render === true ? 16 : 0) | (options.defer === true ? 64 : 0) | (options.lane === true ? 512 : 0), options.fn, memo ? options.equals ?? Object.is : false, options.name);
|
|
239
|
+
if (memo) {
|
|
238
240
|
if (options.lazy !== true) updateIfNecessary(node);
|
|
239
241
|
return node;
|
|
240
242
|
}
|
|
241
|
-
const flags = (options.render === true ? 16 : 0) | (options.defer === true ? 64 : 0) | (options.lane === true ? 512 : 0);
|
|
242
|
-
const node = new Computation(owner, 2, flags, options.fn, false, options.name);
|
|
243
243
|
node.apply = options.apply ?? null;
|
|
244
244
|
if (options.render === true) recompute(node);
|
|
245
245
|
else {
|
|
@@ -311,7 +311,6 @@ function refresh(node) {
|
|
|
311
311
|
function createOwner(parent) {
|
|
312
312
|
return new Owner(parent === void 0 ? rt.owner : parent);
|
|
313
313
|
}
|
|
314
|
-
//#endregion
|
|
315
314
|
export { Computation as ComputationNode, DEVTOOLS_EVENT, MESSAGES, Owner, SUSPENSION, ShadowError, Signal as SignalNode, addCleanup, batch, beginHold, createComputation, createOwner, createSignalNode, createTransitionHold, currentListener, currentOwner, report as devtoolsReport, disposeTree as disposeOwner, endHold, flush, flushSync, formatMessage, group, handleError, holdReader, inTransition, isComputingMemo, isHydrating, isSuspension, isTracking, markObservers, notify, observersOf, pauseOwner, readComputation, readSignal, refresh, registerTransitionLane, resetWarningDedupe, resumeOwner, runInScope, runWithContext, schedule, setWarningListener, sourcesOf, startTransition, track, transitionHooks, wakeSuspended, warn, withHydration, writeSignal };
|
|
316
315
|
|
|
317
316
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["OwnerClass"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && equals(signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: (value: never, previous: never) => unknown;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n if (options.kind === \"memo\") {\n const node = new Computation(\n owner,\n KIND_MEMO,\n FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0),\n options.fn,\n options.equals ?? Object.is,\n options.name,\n );\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n const flags =\n (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0);\n const node = new Computation(owner, KIND_EFFECT, flags, options.fn, false, options.name);\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}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AC3C,IAAI,CAAC,aAAa,MAAM,GAAG;CAC3B,cAAc,MAAM;CACpB,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBAAkB,SAA0C;CAC1E,MAAM,QAAQ,QAAQ,UAAU,KAAA,IAAY,GAAG,QAAQ,QAAQ;CAC/D,IAAI,QAAQ,SAAS,QAAQ;EAC3B,MAAM,OAAO,IAAI,YACf,OAAA,GAAA,MAEe,QAAQ,gBAAgB,OAAA,MAA2B,IAClE,QAAQ,IACR,QAAQ,UAAU,OAAO,IACzB,QAAQ,IACV;EACA,IAAI,QAAQ,SAAS,MAAM,kBAAkB,IAAI;EACjD,OAAO;CACT;CACA,MAAM,SACH,QAAQ,WAAW,OAAA,KAAqB,MACxC,QAAQ,UAAU,OAAA,KAAoB,MACtC,QAAQ,SAAS,OAAA,MAAmB;CACvC,MAAM,OAAO,IAAI,YAAY,OAAA,GAAoB,OAAO,QAAQ,IAAI,OAAO,QAAQ,IAAI;CACvF,KAAK,QAAQ,QAAQ,SAAS;CAC9B,IAAI,QAAQ,WAAW,MAGrB,UAAU,IAAI;MACT;EACL,QAAQ,IAAI;EACZ,SAAS;CACX;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAmB,MAAsB;CACvD,OAAO,SAAY,IAAI;AACzB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,MAAyB;CAC/C,kBAAkB,IAAI;AACxB;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,QAA8B;CACxD,OAAO,IAAIA,MAAW,WAAW,KAAA,IAAY,GAAG,QAAQ,MAAM;AAChE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["OwnerClass"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n isEqual,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's\n * own `equals`), so what it reads is not a dependency of the writer or the reader.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && isEqual(equals, signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown> | undefined;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string | undefined;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean | undefined;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean | undefined;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: ((value: never, previous: never) => unknown) | undefined;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n const memo = options.kind === \"memo\";\n const node = new Computation(\n owner,\n memo ? KIND_MEMO : KIND_EFFECT,\n memo\n ? FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0)\n : (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0),\n options.fn,\n memo ? (options.equals ?? Object.is) : false,\n options.name,\n );\n if (memo) {\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,SAAgB,eAA6B;CAC3C,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAsC;CACpD,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;AAiBA,SAAgB,aAAsB;CACpC,OAAO,GAAG,aAAa;AACzB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAA2B;CACzC,OACE,GAAG,cAAc,KACjB,GAAG,YAAY,QACf,GAAG,QAAQ,SAAA,MACV,GAAG,QAAQ,QAAA,SAA+B;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,WACd,OACA,IACG;CACH,MAAM,QAAQ,GAAG;CACjB,MAAM,WAAW,GAAG;CACpB,IAAI;EACF,MAAM,YAAY,MAAM;EACxB,IAAI,cAAc,KAAA,GAAW,GAAG,QAAQ;EACxC,MAAM,eAAe,MAAM;EAC3B,IAAI,iBAAiB,KAAA,GAAW,GAAG,WAAW;EAC9C,OAAO,GAAG;CACZ,UAAU;EACR,GAAG,QAAQ;EACX,GAAG,WAAW;CAChB;AACF;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAoB,OAAU,QAAmB,MAA0B;CACzF,OAAO,IAAI,OAAU,OAAO,QAAQ,IAAI;AAC1C;;;;;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AC/C,kBAAkB,IAAI;AACxB;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,QAA8B;CACxD,OAAO,IAAIA,MAAW,WAAW,KAAA,IAAY,GAAG,QAAQ,MAAM;AAChE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { untrack } from "./ownership.js";
|
|
2
|
-
|
|
2
|
+
// src/external-store.ts
|
|
3
3
|
/**
|
|
4
4
|
* Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive
|
|
5
5
|
* accessor. The one bridge for every external source, and the ShadowJS form of React's
|
|
@@ -40,7 +40,6 @@ function useExternalStore(subscribe, getSnapshot, options) {
|
|
|
40
40
|
return () => snapshot;
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
|
-
//#endregion
|
|
44
43
|
export { useExternalStore };
|
|
45
44
|
|
|
46
45
|
//# sourceMappingURL=external-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store.js","names":[],"sources":["../../src/external-store.ts"],"sourcesContent":["import { useEffect } from \"./effect\";\nimport type { Accessor, Equals } from \"./extend\";\nimport { isHydrating } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useExternalStore}. @since 1.0.0 */\nexport interface ExternalStoreOptions<T> {\n /**\n * The snapshot the server renders (there is no subscription there). Without it the server reads\n * `getSnapshot` once. Keep it equal to what the browser reads on its first render: a difference is\n * corrected only after subscribing, and no hydration test covers that case yet. While hydrating,\n * the browser's first render also uses it.\n * @default undefined (the server, and hydration, read `getSnapshot`)\n */\n getServerSnapshot?: () => T;\n /**\n * Decides whether a new snapshot is a change: the accessor updates only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\n/**\n * Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive\n * accessor. The one bridge for every external source, and the ShadowJS form of React's\n * `useSyncExternalStore` and Solid's `from`.\n *\n * `subscribe(notify)` is called in an effect after the owner is created and returns the\n * unsubscribe function, which runs when the owner is disposed. `getSnapshot()` is read untracked\n * at creation, on every notification, and once after subscribing (so a change made between the\n * first read and the subscription is not lost). The accessor updates only when the snapshot differs\n * by `equals`. On the server nothing is subscribed: the accessor returns `getServerSnapshot()`.\n *\n * @param subscribe Registers `notify`; returns the unsubscribe function.\n * @param getSnapshot Returns the current value. Reads inside it are not tracked.\n * @param options Server snapshot, equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the current snapshot.\n * @example\n * import { useExternalStore } from \"@shadow-js/core\";\n *\n * function subscribe(notify: () => void): () => void {\n * window.addEventListener(\"online\", notify);\n * window.addEventListener(\"offline\", notify);\n * return () => {\n * window.removeEventListener(\"online\", notify);\n * window.removeEventListener(\"offline\", notify);\n * };\n * }\n *\n * function OnlineBadge() {\n * const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });\n * return <span>{online() ? \"online\" : \"offline\"}</span>;\n * }\n * @see useSignal\n * @since 1.0.0\n */\nexport function useExternalStore<T>(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => T,\n options?: ExternalStoreOptions<T>,\n): Accessor<T> {\n if (__SERVER__) {\n const snapshot = untrack(options?.getServerSnapshot ?? getSnapshot);\n return () => snapshot;\n }\n // While hydrating, the first render must equal the server markup: the server snapshot, when given.\n // The browser's snapshot is applied by the subscription below.\n const first =\n isHydrating() && options?.getServerSnapshot !== undefined\n ? options.getServerSnapshot\n : getSnapshot;\n const [value, setValue] = useSignal<T>(untrack(first), {\n equals: options?.equals ?? Object.is,\n
|
|
1
|
+
{"version":3,"file":"external-store.js","names":[],"sources":["../../src/external-store.ts"],"sourcesContent":["import { useEffect } from \"./effect\";\nimport type { Accessor, Equals } from \"./extend\";\nimport { isHydrating } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useExternalStore}. @since 1.0.0 */\nexport interface ExternalStoreOptions<T> {\n /**\n * The snapshot the server renders (there is no subscription there). Without it the server reads\n * `getSnapshot` once. Keep it equal to what the browser reads on its first render: a difference is\n * corrected only after subscribing, and no hydration test covers that case yet. While hydrating,\n * the browser's first render also uses it.\n * @default undefined (the server, and hydration, read `getSnapshot`)\n */\n getServerSnapshot?: () => T;\n /**\n * Decides whether a new snapshot is a change: the accessor updates only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\n/**\n * Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive\n * accessor. The one bridge for every external source, and the ShadowJS form of React's\n * `useSyncExternalStore` and Solid's `from`.\n *\n * `subscribe(notify)` is called in an effect after the owner is created and returns the\n * unsubscribe function, which runs when the owner is disposed. `getSnapshot()` is read untracked\n * at creation, on every notification, and once after subscribing (so a change made between the\n * first read and the subscription is not lost). The accessor updates only when the snapshot differs\n * by `equals`. On the server nothing is subscribed: the accessor returns `getServerSnapshot()`.\n *\n * @param subscribe Registers `notify`; returns the unsubscribe function.\n * @param getSnapshot Returns the current value. Reads inside it are not tracked.\n * @param options Server snapshot, equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the current snapshot.\n * @example\n * import { useExternalStore } from \"@shadow-js/core\";\n *\n * function subscribe(notify: () => void): () => void {\n * window.addEventListener(\"online\", notify);\n * window.addEventListener(\"offline\", notify);\n * return () => {\n * window.removeEventListener(\"online\", notify);\n * window.removeEventListener(\"offline\", notify);\n * };\n * }\n *\n * function OnlineBadge() {\n * const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });\n * return <span>{online() ? \"online\" : \"offline\"}</span>;\n * }\n * @see useSignal\n * @since 1.0.0\n */\nexport function useExternalStore<T>(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => T,\n options?: ExternalStoreOptions<T>,\n): Accessor<T> {\n if (__SERVER__) {\n const snapshot = untrack(options?.getServerSnapshot ?? getSnapshot);\n return () => snapshot;\n }\n // While hydrating, the first render must equal the server markup: the server snapshot, when given.\n // The browser's snapshot is applied by the subscription below.\n const first =\n isHydrating() && options?.getServerSnapshot !== undefined\n ? options.getServerSnapshot\n : getSnapshot;\n const [value, setValue] = useSignal<T>(untrack(first), {\n equals: options?.equals ?? Object.is,\n name: options?.name,\n });\n const sync = (): void => {\n const next = untrack(getSnapshot);\n setValue(() => next);\n };\n useEffect(() => {\n // `subscribe` is a user callback: what it reads must not re-run (and re-subscribe) this effect.\n const unsubscribe = untrack(() => subscribe(sync));\n try {\n // Catch up with changes made between the first read and the subscription.\n sync();\n } catch (error) {\n // The effect fails, so no cleanup is registered: release the subscription here.\n unsubscribe();\n throw error;\n }\n return unsubscribe;\n });\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,SAAgB,iBACd,WACA,aACA,SACa;CACG;EACd,MAAM,WAAW,QAAQ,SAAS,qBAAqB,WAAW;EAClE,aAAa;CACf;AA6BF"}
|
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
import { DEVTOOLS_EVENT, report } from "./devtools.js";
|
|
2
2
|
import { ShadowError } from "./diagnostics.js";
|
|
3
|
-
import { FLAG_PARKED,
|
|
3
|
+
import { FLAG_PARKED, FLAG_TRANSITION } from "./flags.js";
|
|
4
4
|
import { rt } from "./state.js";
|
|
5
5
|
import { Owner, addCleanup, handleError } from "./owner.js";
|
|
6
6
|
import { clearQueues, hasPending, place, renderQueue, userQueue } from "./queue.js";
|
|
7
7
|
import { Computation, Signal, hasObservers, markObservers, readSignal, recompute, updateIfNecessary } from "./graph.js";
|
|
8
|
-
import { byCreation,
|
|
8
|
+
import { byCreation, reportUncaught, schedule } from "./scheduler.js";
|
|
9
9
|
import { runWithContext } from "../context.js";
|
|
10
10
|
import { SuspenseContext } from "../suspense.js";
|
|
11
11
|
import { disposeTree } from "./dispose.js";
|
|
12
12
|
import { SUSPENSION, isSuspension } from "./suspension.js";
|
|
13
|
-
|
|
13
|
+
// src/internal/concurrency.ts
|
|
14
14
|
/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */
|
|
15
15
|
const LANE_CHUNK = 64;
|
|
16
|
+
/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */
|
|
17
|
+
const SUSPENDED_SWEEP_AT = 64;
|
|
16
18
|
/** Visits `root` and every node below it. Iterative: the depth is user controlled. */
|
|
17
19
|
function walk(root, visit) {
|
|
18
20
|
const stack = [root];
|
|
@@ -27,10 +29,21 @@ function walk(root, visit) {
|
|
|
27
29
|
function createHooks() {
|
|
28
30
|
const laneRender = [];
|
|
29
31
|
const laneUser = [];
|
|
30
|
-
/**
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
/**
|
|
33
|
+
* The promise every transition that waits for the lane shares (`waiting` counts the callers, for
|
|
34
|
+
* devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew
|
|
35
|
+
* with every `startTransition`, and all of them resolve at the same moment anyway.
|
|
36
|
+
*/
|
|
37
|
+
let applied = null;
|
|
38
|
+
let resolveApplied = null;
|
|
39
|
+
let waiting = 0;
|
|
40
|
+
/**
|
|
41
|
+
* Memos and effects that caught a suspension; woken all at once when a boundary releases them. A
|
|
42
|
+
* node is listed once (it is a set), and the disposed ones are dropped each time the list
|
|
43
|
+
* length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,
|
|
44
|
+
* grow with the number of nodes that came and went.
|
|
45
|
+
*/
|
|
46
|
+
const suspended = /* @__PURE__ */ new Set();
|
|
34
47
|
/** Suspense boundaries currently holding a transition (the lane is busy while any holds). */
|
|
35
48
|
let holds = 0;
|
|
36
49
|
let scheduled = false;
|
|
@@ -42,7 +55,7 @@ function createHooks() {
|
|
|
42
55
|
*/
|
|
43
56
|
const drainLane = (queue, limit) => {
|
|
44
57
|
const batch = queue.splice(0, limit);
|
|
45
|
-
|
|
58
|
+
batch.sort(byCreation);
|
|
46
59
|
for (const effect of batch) {
|
|
47
60
|
if ((effect.flags & 1024) === 0) continue;
|
|
48
61
|
effect.flags &= ~(2 | FLAG_TRANSITION);
|
|
@@ -62,10 +75,12 @@ function createHooks() {
|
|
|
62
75
|
};
|
|
63
76
|
/** Resolves the transitions that wait for the lane, once the lane is idle. */
|
|
64
77
|
const settleLane = () => {
|
|
65
|
-
if (laneBusy() ||
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
78
|
+
if (laneBusy() || resolveApplied === null) return;
|
|
79
|
+
const resolve = resolveApplied;
|
|
80
|
+
applied = resolveApplied = null;
|
|
81
|
+
report(DEVTOOLS_EVENT.TRANSITION_END, waiting);
|
|
82
|
+
waiting = 0;
|
|
83
|
+
resolve();
|
|
69
84
|
};
|
|
70
85
|
/** Asks for one lane macrotask (the timer lets the browser paint and take input first). */
|
|
71
86
|
const scheduleLane = () => {
|
|
@@ -122,11 +137,13 @@ function createHooks() {
|
|
|
122
137
|
rt.listener = listener;
|
|
123
138
|
}
|
|
124
139
|
report(DEVTOOLS_EVENT.TRANSITION_START);
|
|
125
|
-
|
|
126
|
-
|
|
140
|
+
waiting += 1;
|
|
141
|
+
applied ??= new Promise((resolve) => {
|
|
142
|
+
resolveApplied = resolve;
|
|
127
143
|
});
|
|
144
|
+
const shared = applied;
|
|
128
145
|
settleLane();
|
|
129
|
-
return
|
|
146
|
+
return shared;
|
|
130
147
|
};
|
|
131
148
|
/** The hook's `place`: parks a paused effect or queues a lane effect. */
|
|
132
149
|
const parkOrLane = (effect, inLane) => {
|
|
@@ -162,8 +179,13 @@ function createHooks() {
|
|
|
162
179
|
};
|
|
163
180
|
const suspend = (node, error) => {
|
|
164
181
|
if (error !== SUSPENSION) return false;
|
|
165
|
-
node
|
|
166
|
-
|
|
182
|
+
if (!suspended.has(node)) {
|
|
183
|
+
const size = suspended.size;
|
|
184
|
+
if (size >= SUSPENDED_SWEEP_AT && (size & size - 1) === 0) {
|
|
185
|
+
for (const entry of suspended) if (entry.disposed) suspended.delete(entry);
|
|
186
|
+
}
|
|
187
|
+
suspended.add(node);
|
|
188
|
+
}
|
|
167
189
|
return true;
|
|
168
190
|
};
|
|
169
191
|
const holdReader = (tracker) => {
|
|
@@ -178,13 +200,13 @@ function createHooks() {
|
|
|
178
200
|
settleLane();
|
|
179
201
|
};
|
|
180
202
|
const wakeSuspended = () => {
|
|
181
|
-
const
|
|
203
|
+
const woken = Array.from(suspended);
|
|
204
|
+
suspended.clear();
|
|
182
205
|
const previous = rt.inTransition;
|
|
183
206
|
rt.inTransition = true;
|
|
184
207
|
try {
|
|
185
|
-
for (const node of
|
|
186
|
-
if (
|
|
187
|
-
node.flags &= ~FLAG_SUSPENDED;
|
|
208
|
+
for (const node of woken) {
|
|
209
|
+
if (node.disposed) continue;
|
|
188
210
|
node.state = 2;
|
|
189
211
|
if (node.kind === 2) place(node, true);
|
|
190
212
|
else markObservers(node);
|
|
@@ -627,7 +649,6 @@ function pauseOwner(owner) {
|
|
|
627
649
|
function resumeOwner(owner) {
|
|
628
650
|
rt.hooks?.resume(owner);
|
|
629
651
|
}
|
|
630
|
-
//#endregion
|
|
631
652
|
export { beginHold, createTransitionHold, endHold, holdReader, inTransition, pauseOwner, registerTransitionLane, resumeOwner, startTransition, transitionHooks, wakeSuspended };
|
|
632
653
|
|
|
633
654
|
//# sourceMappingURL=concurrency.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"concurrency.js","names":[],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_SUSPENDED,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n readSignal,\n recompute,\n Signal,\n updateIfNecessary,\n} from \"./graph\";\nimport { addCleanup, handleError, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, isOrdered, MAX_FLUSH_PASSES, reportUncaught, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) break;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /** Resolvers of the transitions waiting for the lane to go idle. */\n const waiters: Array<() => void> = [];\n /** Memos and effects that caught a suspension; woken all at once when a boundary releases them. */\n const suspended: Computation[] = [];\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n try {\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\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || waiters.length === 0) return;\n const resolved = waiters.splice(0, waiters.length);\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_END, resolved.length);\n for (const resolve of resolved) resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n const applied = new Promise<void>((resolve) => {\n waiters.push(resolve);\n });\n settleLane();\n return applied;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n node.flags |= FLAG_SUSPENDED;\n suspended.push(node);\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const waiting = suspended.splice(0, suspended.length);\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of waiting) {\n if ((node.flags & FLAG_SUSPENDED) === 0 || node.disposed) continue;\n node.flags &= ~FLAG_SUSPENDED;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n walk(owner, (node) => {\n node.pauses += 1;\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n });\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":";;;;;;;;;;;;;;AAmDA,MAAM,aAAa;;AAGnB,S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,SAAgB,UAAgB;CAC9B,GAAG,OAAO,QAAQ;AACpB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,gBAAsB;CACpC,GAAG,OAAO,cAAc;AAC1B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,WAAW,SAAqC;CAC9D,GAAG,OAAO,WAAW,OAAO;AAC9B;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,eAAwB;CACtC,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBAAqB,WAA8C;CACjF,MAAM,QAAQ,GAAG;CACjB,OAAO,UAAU,OAAO,OAAO,MAAM,WAAW,SAAS;AAC3D;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAgC;CAC9C,OAAO,GAAG,eAAe,GAAG,QAAQ;AACtC;;;;;;;;;;;;;;;;;AAkBA,SAAgB,WAAW,OAAoB;CAC7C,YAAY,CAAC,CAAC,MAAM,KAAK;AAC3B;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YAAY,OAAoB;CAC9C,GAAG,OAAO,OAAO,KAAK;AACxB"}
|
|
1
|
+
{"version":3,"file":"concurrency.js","names":[],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n readSignal,\n recompute,\n Signal,\n updateIfNecessary,\n} from \"./graph\";\nimport { addCleanup, handleError, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */\nconst SUSPENDED_SWEEP_AT = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) break;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /**\n * The promise every transition that waits for the lane shares (`waiting` counts the callers, for\n * devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew\n * with every `startTransition`, and all of them resolve at the same moment anyway.\n */\n let applied: Promise<void> | null = null;\n let resolveApplied: (() => void) | null = null;\n let waiting = 0;\n /**\n * Memos and effects that caught a suspension; woken all at once when a boundary releases them. A\n * node is listed once (it is a set), and the disposed ones are dropped each time the list\n * length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,\n * grow with the number of nodes that came and went.\n */\n const suspended = new Set<Computation>();\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n try {\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\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || resolveApplied === null) return;\n const resolve = resolveApplied;\n applied = resolveApplied = null;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.TRANSITION_END, waiting);\n waiting = 0;\n }\n resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n if (__DEV__) waiting += 1;\n applied ??= new Promise<void>((resolve) => {\n resolveApplied = resolve;\n });\n const shared = applied;\n settleLane();\n return shared;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n // Listed once: a node that suspends again before the wake-up is already in the set.\n if (!suspended.has(node)) {\n const size = suspended.size;\n if (size >= SUSPENDED_SWEEP_AT && (size & (size - 1)) === 0) {\n // A disposed node never wakes, so keeping it would leak it for as long as the hold lasts.\n for (const entry of suspended) {\n if (entry.disposed) suspended.delete(entry);\n }\n }\n suspended.add(node);\n }\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const woken = Array.from(suspended);\n suspended.clear();\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of woken) {\n if (node.disposed) continue;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n walk(owner, (node) => {\n node.pauses += 1;\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n });\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":";;;;;;;;;;;;;;AAkDA,MAAM,aAAa;;AAGnB,MAAM,qBAAqB;;AAG3B,SAAS,KAAK,MAAa,OAAoC;CAC7D,MAAM,QAAiB,CAAC,IAAI;CAC5B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,OAAO,MAAM,IAAI;EACvB,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,IAAI;EACV,KAAK,IAAI,QAAQ,KAAK,WAAW,UAAU,MAAM,QAAQ,MAAM,aAAa,MAAM,KAAK,KAAK;CAC9F;AACF;;AAGA,SAAS,cAAqB;CAC5B,MAAM,aAA4B,CAAC;CACnC,MAAM,WAA0B,CAAC;;;;;;CAMjC,IAAI,UAAgC;CACpC,IAAI,iBAAsC;CAC1C,IAAI,UAAU;;;;;;;CAOd,MAAM,4BAAY,IAAI,IAAiB;;CAEvC,IAAI,QAAQ;CACZ,IAAI,YAAY;CAEhB,MAAM,uBAAgC,WAAW,SAAS,KAAK,SAAS,SAAS;CACjF,MAAM,iBAA0B,eAAe,KAAK,QAAQ;;;;;CAM5D,MAAM,aAAa,OAAsB,UAA0B;EACjE,MAAM,QAAQ,MAAM,OAAO,GAAG,KAAK;EACnC,MAAM,KAAK,UAAU;EACrB,KAAK,MAAM,UAAU,OAAO;GAC1B,KAAK,OAAO,QAAA,UAA6B,GAAG;GAC5C,OAAO,SAAS,EAAA,IAAgB;GAChC,KAAK,OAAO,QAAA,OAA2B,GAAG;GAC1C,IAAI,OAAO,SAAS,GAAG;IACrB,OAAO,SAAS,cAAc;IAC9B;GACF;GACA,IAAI;IACF,IAAI,OAAO,UAAA,GAAiB,UAAU,MAAM;SACvC,kBAAkB,MAAM;GAC/B,SAAS,OAAO;IACd,YAA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AC5B,MAAM,WAAW,GAAG;CACpB,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,UAAU,YAAY;CAC5B,GAAG,QAAQ;CACX,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA+B;CAC7C,YAAY;AACd;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,gBAAgB,IAA+B;CAE3D,GAAG;CACH,OAAO,QAAQ,QAAQ;AAG3B;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,YAAkB;CAChC,GAAG,OAAO,UAAU;AACtB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,UAAgB;CAC9B,GAAG,OAAO,QAAQ;AACpB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,gBAAsB;CACpC,GAAG,OAAO,cAAc;AAC1B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,WAAW,SAAqC;CAC9D,GAAG,OAAO,WAAW,OAAO;AAC9B;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,eAAwB;CACtC,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBAAqB,WAA8C;CACjF,MAAM,QAAQ,GAAG;CACjB,OAAO,UAAU,OAAO,OAAO,MAAM,WAAW,SAAS;AAC3D;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAgC;CAC9C,OAAO,GAAG,eAAe,GAAG,QAAQ;AACtC;;;;;;;;;;;;;;;;;AAkBA,SAAgB,WAAW,OAAoB;CAC7C,YAAY,CAAC,CAAC,MAAM,KAAK;AAC3B;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YAAY,OAAoB;CAC9C,GAAG,OAAO,OAAO,KAAK;AACxB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/internal/devtools.ts
|
|
2
2
|
/**
|
|
3
3
|
* The runtime's side of the devtools protocol (version 1, see `@shadow-js/devtools`). The runtime
|
|
4
4
|
* does not import that package: it looks up a global hook, in development builds only, and every
|
|
@@ -71,7 +71,6 @@ function report(kind, a, b, c, d, e) {
|
|
|
71
71
|
const hook = Reflect.get(globalThis, KEY);
|
|
72
72
|
if (hook !== void 0 && hook.version === 1) hook.report(kind, a, b, c, d, e);
|
|
73
73
|
}
|
|
74
|
-
//#endregion
|
|
75
74
|
export { DEVTOOLS_EVENT, report };
|
|
76
75
|
|
|
77
76
|
//# sourceMappingURL=devtools.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { formatMessage } from "./messages.js";
|
|
2
|
-
|
|
2
|
+
// src/internal/diagnostics.ts
|
|
3
3
|
/**
|
|
4
4
|
* The error class of every diagnostic the runtime throws, carrying a stable code next to the
|
|
5
5
|
* message. Match on `code` rather than the message: the message is the full text in development
|
|
@@ -16,8 +16,6 @@ import { formatMessage } from "./messages.js";
|
|
|
16
16
|
* @since 1.0.0
|
|
17
17
|
*/
|
|
18
18
|
var ShadowError = class extends Error {
|
|
19
|
-
/** The diagnostic code, a key of {@link MESSAGES}; the same in development and production builds. */
|
|
20
|
-
code;
|
|
21
19
|
/**
|
|
22
20
|
* Creates the error with the text of {@link formatMessage} for `code` and the name `"ShadowError"`.
|
|
23
21
|
* @param code The diagnostic code.
|
|
@@ -96,7 +94,6 @@ function warn(code) {
|
|
|
96
94
|
if (listener !== void 0) listener(code, message);
|
|
97
95
|
else console.warn(message);
|
|
98
96
|
}
|
|
99
|
-
//#endregion
|
|
100
97
|
export { ShadowError, resetWarningDedupe, setWarningListener, warn };
|
|
101
98
|
|
|
102
99
|
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","names":[],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["import { formatMessage, type MessageCode } from \"./messages\";\n\n/**\n * The error class of every diagnostic the runtime throws, carrying a stable code next to the\n * message. Match on `code` rather than the message: the message is the full text in development\n * builds and only `SHADOW_<CODE>` in production builds. Throw it from a custom primitive to report a\n * core diagnostic the same way the built-in hooks do.\n *\n * @example\n * import { ShadowError } from \"@shadow-js/core/extend\";\n *\n * function isCycle(error: unknown): boolean {\n * return error instanceof ShadowError && error.code === \"CYCLE_DETECTED\";\n * }\n * @see MESSAGES\n * @since 1.0.0\n */\nexport class ShadowError extends Error {\n /** The diagnostic code, a key of {@link MESSAGES}; the same in development and production builds. */\n readonly code: MessageCode;\n /**\n * Creates the error with the text of {@link formatMessage} for `code` and the name `\"ShadowError\"`.\n * @param code The diagnostic code.\n */\n constructor(code: MessageCode) {\n super(formatMessage(code));\n this.name = \"ShadowError\";\n this.code = code;\n }\n}\n\n/**\n * A function that receives the warnings of {@link warn} instead of `console.warn`. Install one with\n * {@link setWarningListener}.\n * @param code The diagnostic code of the warning.\n * @param message The text of {@link formatMessage} for that code.\n * @since 1.0.0\n */\nexport type WarningListener = (code: MessageCode, message: string) => void;\n\nconst seen = new Set<MessageCode>();\nlet listener: WarningListener | undefined;\n\n/**\n * Sends every later warning to `next` instead of `console.warn`, for devtools and test helpers\n * (`@shadow-js/testing`) that collect warnings. Deduplication still applies: the listener receives\n * the first warning of each code only. Warnings exist in development builds only.\n *\n * @param next The listener to install. Undefined restores the default, `console.warn`.\n * @returns The listener that was installed before, or undefined when it was the default, so the\n * caller can restore it.\n * @example\n * import { type MessageCode, setWarningListener } from \"@shadow-js/core/extend\";\n *\n * const codes: MessageCode[] = [];\n * const previous = setWarningListener((code) => {\n * codes.push(code);\n * });\n * // ... run the code under test, then:\n * setWarningListener(previous);\n * @see warn\n * @see resetWarningDedupe\n * @since 1.0.0\n */\nexport function setWarningListener(next: WarningListener | undefined): WarningListener | undefined {\n const previous = listener;\n listener = next;\n return previous;\n}\n\n/**\n * Forgets which codes {@link warn} has already reported, so the next warning of each code is\n * reported again. Use it between test cases and after a hot reload.\n *\n * @example\n * import { resetWarningDedupe } from \"@shadow-js/core/extend\";\n *\n * function startTestCase(): void {\n * resetWarningDedupe(); // each case sees its own first warnings\n * }\n * @see warn\n * @since 1.0.0\n */\nexport function resetWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Reports a development-only diagnostic. Only the first warning of each code is reported, for the\n * whole program, until {@link resetWarningDedupe}; it goes to the listener of\n * {@link setWarningListener}, or to `console.warn` with the text of {@link formatMessage}. Does\n * nothing in production builds. Use it for a mistake that should not stop the app; throw\n * {@link ShadowError} for one that must.\n *\n * @param code The diagnostic code to report.\n * @example\n * import { currentOwner, warn } from \"@shadow-js/core/extend\";\n *\n * export function useTicker(): void {\n * if (currentOwner() === null) warn(\"NO_OWNER_CLEANUP\");\n * }\n * @see setWarningListener\n * @since 1.0.0\n */\nexport function warn(code: MessageCode): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n const message = formatMessage(code);\n if (listener !== undefined) listener(code, message);\n else console.warn(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,IAAa,cAAb,cAAiC,MAAM
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":[],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["import { formatMessage, type MessageCode } from \"./messages\";\n\n/**\n * The error class of every diagnostic the runtime throws, carrying a stable code next to the\n * message. Match on `code` rather than the message: the message is the full text in development\n * builds and only `SHADOW_<CODE>` in production builds. Throw it from a custom primitive to report a\n * core diagnostic the same way the built-in hooks do.\n *\n * @example\n * import { ShadowError } from \"@shadow-js/core/extend\";\n *\n * function isCycle(error: unknown): boolean {\n * return error instanceof ShadowError && error.code === \"CYCLE_DETECTED\";\n * }\n * @see MESSAGES\n * @since 1.0.0\n */\nexport class ShadowError extends Error {\n /** The diagnostic code, a key of {@link MESSAGES}; the same in development and production builds. */\n declare readonly code: MessageCode;\n /**\n * Creates the error with the text of {@link formatMessage} for `code` and the name `\"ShadowError\"`.\n * @param code The diagnostic code.\n */\n constructor(code: MessageCode) {\n super(formatMessage(code));\n this.name = \"ShadowError\";\n this.code = code;\n }\n}\n\n/**\n * A function that receives the warnings of {@link warn} instead of `console.warn`. Install one with\n * {@link setWarningListener}.\n * @param code The diagnostic code of the warning.\n * @param message The text of {@link formatMessage} for that code.\n * @since 1.0.0\n */\nexport type WarningListener = (code: MessageCode, message: string) => void;\n\nconst seen = new Set<MessageCode>();\nlet listener: WarningListener | undefined;\n\n/**\n * Sends every later warning to `next` instead of `console.warn`, for devtools and test helpers\n * (`@shadow-js/testing`) that collect warnings. Deduplication still applies: the listener receives\n * the first warning of each code only. Warnings exist in development builds only.\n *\n * @param next The listener to install. Undefined restores the default, `console.warn`.\n * @returns The listener that was installed before, or undefined when it was the default, so the\n * caller can restore it.\n * @example\n * import { type MessageCode, setWarningListener } from \"@shadow-js/core/extend\";\n *\n * const codes: MessageCode[] = [];\n * const previous = setWarningListener((code) => {\n * codes.push(code);\n * });\n * // ... run the code under test, then:\n * setWarningListener(previous);\n * @see warn\n * @see resetWarningDedupe\n * @since 1.0.0\n */\nexport function setWarningListener(next: WarningListener | undefined): WarningListener | undefined {\n const previous = listener;\n listener = next;\n return previous;\n}\n\n/**\n * Forgets which codes {@link warn} has already reported, so the next warning of each code is\n * reported again. Use it between test cases and after a hot reload.\n *\n * @example\n * import { resetWarningDedupe } from \"@shadow-js/core/extend\";\n *\n * function startTestCase(): void {\n * resetWarningDedupe(); // each case sees its own first warnings\n * }\n * @see warn\n * @since 1.0.0\n */\nexport function resetWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Reports a development-only diagnostic. Only the first warning of each code is reported, for the\n * whole program, until {@link resetWarningDedupe}; it goes to the listener of\n * {@link setWarningListener}, or to `console.warn` with the text of {@link formatMessage}. Does\n * nothing in production builds. Use it for a mistake that should not stop the app; throw\n * {@link ShadowError} for one that must.\n *\n * @param code The diagnostic code to report.\n * @example\n * import { currentOwner, warn } from \"@shadow-js/core/extend\";\n *\n * export function useTicker(): void {\n * if (currentOwner() === null) warn(\"NO_OWNER_CLEANUP\");\n * }\n * @see setWarningListener\n * @since 1.0.0\n */\nexport function warn(code: MessageCode): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n const message = formatMessage(code);\n if (listener !== undefined) listener(code, message);\n else console.warn(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,IAAa,cAAb,cAAiC,MAAM;;;;;CAOrC,YAAY,MAAmB;EAC7B,MAAM,cAAc,IAAI,CAAC;EACzB,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAWA,MAAM,uBAAO,IAAI,IAAiB;AAClC,IAAI;;;;;;;;;;;;;;;;;;;;;;AAuBJ,SAAgB,mBAAmB,MAAgE;CACjG,MAAM,WAAW;CACjB,WAAW;CACX,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,qBAA2B;CACzC,KAAK,MAAM;AACb;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,KAAK,MAAyB;CAE5C,IAAI,KAAK,IAAI,IAAI,GAAG;CACpB,KAAK,IAAI,IAAI;CACb,MAAM,UAAU,cAAc,IAAI;CAClC,IAAI,aAAa,KAAA,GAAW,SAAS,MAAM,OAAO;MAC7C,QAAQ,KAAK,OAAO;AAC3B"}
|
|
@@ -2,7 +2,7 @@ import { rt } from "./state.js";
|
|
|
2
2
|
import { disposeTree as disposeTree$1 } from "./owner.js";
|
|
3
3
|
import { hasPending } from "./queue.js";
|
|
4
4
|
import { flush } from "./scheduler.js";
|
|
5
|
-
|
|
5
|
+
// src/internal/dispose.ts
|
|
6
6
|
/**
|
|
7
7
|
* Disposes an owner and everything below it: children first, newest first, then each node's
|
|
8
8
|
* cleanups, newest first. Use it to end an owner made with `createOwner`; disposing an owner that is
|
|
@@ -43,7 +43,6 @@ function disposeTree(root) {
|
|
|
43
43
|
}
|
|
44
44
|
if (failed) throw failure;
|
|
45
45
|
}
|
|
46
|
-
//#endregion
|
|
47
46
|
export { disposeTree };
|
|
48
47
|
|
|
49
48
|
//# sourceMappingURL=dispose.js.map
|
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
// src/internal/flags.ts
|
|
2
2
|
/** Effect is queued in (or parked from) the transition lane, not the urgent queues. */
|
|
3
3
|
const FLAG_TRANSITION = 1024;
|
|
4
4
|
/** Effect was due while its owner was paused: it waits, unqueued, until the owner resumes. */
|
|
5
5
|
const FLAG_PARKED = 2048;
|
|
6
|
-
|
|
7
|
-
const FLAG_SUSPENDED = 4096;
|
|
8
|
-
//#endregion
|
|
9
|
-
export { FLAG_PARKED, FLAG_SUSPENDED, FLAG_TRANSITION };
|
|
6
|
+
export { FLAG_PARKED, FLAG_TRANSITION };
|
|
10
7
|
|
|
11
8
|
//# sourceMappingURL=flags.js.map
|