@shadow-js/core 1.0.4 → 1.0.6
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 +14 -0
- package/dist/dev/action.js +1 -1
- package/dist/dev/cache.js +1 -1
- package/dist/dev/context.js +2 -2
- package/dist/dev/effect.js +1 -1
- package/dist/dev/extend/index.d.ts +4 -4
- package/dist/dev/extend/index.js +5 -5
- package/dist/dev/external-store.js +2 -2
- package/dist/dev/index.d.ts +6 -6
- package/dist/dev/index.js +9 -9
- package/dist/dev/internal/concurrency.js +5 -5
- package/dist/dev/internal/dispose.js +1 -1
- package/dist/dev/internal/graph.d.ts +1 -1
- package/dist/dev/internal/graph.js +5 -1
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/scheduler.js +2 -2
- package/dist/dev/internal/state.d.ts +1 -1
- package/dist/dev/list.js +2 -2
- package/dist/dev/optimistic.js +1 -1
- package/dist/dev/ownership.js +6 -1
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.js +1 -1
- package/dist/dev/reaction.js +2 -2
- package/dist/dev/resource.js +4 -4
- package/dist/dev/selector.js +1 -1
- package/dist/dev/signal.js +1 -1
- package/dist/dev/store/index.d.ts +1 -1
- package/dist/dev/store/nodes.js +7 -3
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/reconcile.js +1 -1
- package/dist/dev/store/reconcile.js.map +1 -1
- package/dist/dev/store/use-store.js +9 -5
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/transitions.js +2 -2
- package/dist/prod/action.js +1 -1
- package/dist/prod/cache.js +1 -1
- package/dist/prod/context.js +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/extend/index.js +1 -1
- package/dist/prod/external-store.js +1 -1
- package/dist/prod/index.js +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/dispose.js +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.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/optimistic.js +1 -1
- package/dist/prod/ownership.js +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js +1 -1
- package/dist/prod/reaction.js +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/selector.js +1 -1
- package/dist/prod/signal.js +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/reconcile.js +1 -1
- package/dist/prod/store/reconcile.js.map +1 -1
- package/dist/prod/store/use-store.js +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/transitions.js +1 -1
- package/dist/server/action.js +1 -1
- package/dist/server/cache.js +1 -1
- package/dist/server/context.js +1 -1
- package/dist/server/extend/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/dispose.js +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.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/optimistic.js +1 -1
- package/dist/server/ownership.js +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js +1 -1
- package/dist/server/reaction.js +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/selector.js +1 -1
- package/dist/server/signal.js +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/reconcile.js +1 -1
- package/dist/server/store/reconcile.js.map +1 -1
- package/dist/server/store/use-store.js +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/transitions.js +1 -1
- package/dist/server-dev/action.js +1 -1
- package/dist/server-dev/cache.js +1 -1
- package/dist/server-dev/context.js +1 -1
- package/dist/server-dev/extend/index.js +5 -5
- package/dist/server-dev/index.js +9 -9
- package/dist/server-dev/internal/concurrency.js +5 -5
- package/dist/server-dev/internal/dispose.js +1 -1
- package/dist/server-dev/internal/graph.js +5 -1
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +2 -2
- package/dist/server-dev/list.js +2 -2
- package/dist/server-dev/optimistic.js +1 -1
- package/dist/server-dev/ownership.js +6 -1
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +1 -1
- package/dist/server-dev/reaction.js +2 -2
- package/dist/server-dev/resource.js +3 -3
- package/dist/server-dev/selector.js +1 -1
- package/dist/server-dev/signal.js +1 -1
- package/dist/server-dev/store/nodes.js +7 -3
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/reconcile.js +1 -1
- package/dist/server-dev/store/reconcile.js.map +1 -1
- package/dist/server-dev/store/use-store.js +9 -5
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/transitions.js +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","runQueued","settleLane","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","error","reportUncaught","hasPending","schedule","startTransition","listener","fn","shared","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","markObservers","pause","nodes","owner","i","Computation","finishDisposal","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"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 { Computation, hasObservers, markObservers, readSignal, Signal } from \"./graph\";\nimport { addCleanup, finishDisposal, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, runQueued, 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() as Owner;\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 runQueued(effect);\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 // Every node is paused before any cleanup runs: a cleanup that throws must not leave the rest\n // unpaused. Preorder reversed is the disposal order: children first, newest first.\n const nodes: Owner[] = [];\n walk(owner, (node) => {\n node.pauses += 1;\n nodes.push(node);\n });\n rt.disposing += 1;\n try {\n for (let i = nodes.length - 1; i >= 0; i -= 1) {\n const node = nodes[i];\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 } finally {\n finishDisposal();\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":"A,ysBAgDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvBG,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,C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AOoC,CAAK,CACxB,C"}
|
|
1
|
+
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","runQueued","settleLane","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","error","reportUncaught","hasPending","schedule","startTransition","listener","fn","shared","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","markObservers","pause","nodes","owner","i","Computation","finishDisposal","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"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 { Computation, hasObservers, markObservers, readSignal, Signal } from \"./graph\";\nimport { addCleanup, finishDisposal, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, runQueued, 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() as Owner;\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 runQueued(effect);\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 // Every node is paused before any cleanup runs: a cleanup that throws must not leave the rest\n // unpaused. Preorder reversed is the disposal order: children first, newest first.\n const nodes: Owner[] = [];\n walk(owner, (node) => {\n node.pauses += 1;\n nodes.push(node);\n });\n rt.disposing += 1;\n try {\n for (let i = nodes.length - 1; i >= 0; i -= 1) {\n const node = nodes[i];\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 } finally {\n finishDisposal();\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":"A,ysBAgDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvBG,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,CAAC,EAC7BC,EAA0B,CAAC,EAM7BC,EAAgC,KAChCC,EAAsC,KAQpCC,kBAAY,IAAI,IAElBC,EAAQ,EACRC,EAAY,GAEVC,MAAgCP,EAAW,OAAS,GAAKC,EAAS,OAAS,EAC3EO,MAA0BD,EAAe,GAAKF,EAAQ,EAMtDI,GAAa,EAAsB,IAA0B,CACjE,IAAMC,EAAQC,EAAM,OAAO,EAAGC,CAAK,EACnCF,EAAM,KAAKG,CAAU,EACrB,IAAK,IAAMC,KAAUJ,EACdI,EAAO,MAAA,OACZ,EAAO,OAAS,EAAA,EAAgBC,GAC3BD,EAAO,MAAA,IACRA,EAAO,OAAS,EAClB,EAAO,OAASE,EAAcD,EAGhCE,EAAUH,CAAM,IAElB,OAAOJ,EAAM,MACf,EAGMQ,MAAyB,CAC7B,GAAIV,EAAS,GAAKL,IAAmB,KAAM,OAC3C,IAAMgB,EAAUhB,EAChB,EAAU,EAAiB,KAK3BgB,EAAQ,CACV,EAGMC,MAA2B,CAC3Bd,IACJ,EAAY,GACZ,WAAWe,EAAW,CAAC,EACzB,EAOMA,MAAwB,CAE5B,GADA,EAAY,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,EAAG,OAAO,QAAQ,CACpB,CAkBA,SAAgB+B,GAAsB,CACpC/B,EAAG,OAAO,cAAc,CAC1B,CAuBA,SAAgB2B,EAAW,EAAqC,CAC9D3B,EAAG,OAAO,WAAW4B,CAAO,CAC9B,CAmBA,SAAgBqD,GAAwB,CACtC,OAAOjF,EAAG,YACZ,CAmBA,SAAgBkF,EAAqB,EAA8C,CACjF,IAAMC,EAAQnF,EAAG,MACjB,OAAOmF,IAAU,KAAO,KAAOA,EAAM,WAAWvC,CAAS,CAC3D,CAkBA,SAAgBwC,GAAgC,CAC9C,OAAOpF,EAAG,aAAeA,EAAG,MAAQ,IACtC,CAkBA,SAAgBqF,EAAW,EAAoB,CAC7CR,EAAY,CAAC,CAAC,MAAMzC,CAAK,CAC3B,CAmBA,SAAgBkD,EAAY,EAAoB,CAC9CtF,EAAG,OAAO,OAAOoC,CAAK,CACxB,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{disposeTree as e}from"./owner.js";import{hasPending as t}from"./queue.js";import{flushThenThrow as n}from"./scheduler.js";import{rt as r}from"./state.js";function i(i){let a,o=!1;try{e(i)}catch(e){o=!0,a=e}n(r.running===null&&r.batches===0&&r.disposing===0&&!r.flushing&&t(),o,a,`SHADOW_DISPOSE_FLUSH_ERRORS`)}export{i as disposeTree};
|
|
2
2
|
//# sourceMappingURL=dispose.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./diagnostics.js";import{
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{Owner as t,addCleanup as n,disposeChildren as r,finishDisposal as i,handleError as a,hasErrorHandler as o}from"./owner.js";import{enqueue as s}from"./queue.js";import{nextSequence as c,rt as l}from"./state.js";const u=Object.freeze([]);var d=class{kind=0;observers=null;stamp=0;constructor(e,t,n){this.value=e,this.equals=t,this.name=n}},f=class extends t{error=void 0;fn;apply=null;sources=u;observers=null;stamp=0;trackIndex=0;constructor(e,t,n,r,i,a){super(e),this.kind=t,this.flags=n,this.state=2,this.fn=r,this.equals=i,this.name=a,this.value=void 0,this.seq=c()}release(){this.flags|=4,m(this,0),this.fn=null,this.apply=null}};function p(e,t){let n=e.observers;if(n===null)return;let r=n.length-2;if(t!==r){let e=n[r],i=n[r+1];n[t]=e,n[t+1]=i,e.sources[i+1]=t}n.length=r}function m(e,t){let n=e.sources;if(!(n.length<=t)){for(let e=n.length-2;e>=t;e-=2)p(n[e],n[e+1]);n.length=t}}function h(e,t,n){let r=e.length;if(r>=16)return e.push(t,n),e;let i=Array(r+2);for(let t=0;t<r;t+=1)i[t]=e[t];return i[r]=t,i[r+1]=n,i}function g(e){let t=l.listener;if(t===null||e.stamp===t.stamp)return;e.stamp=t.stamp;let n=t.trackIndex;if(n<t.sources.length){if(t.sources[n]===e){t.trackIndex=n+2;return}m(t,n)}let r=e.observers,i=t.sources,a=r===null?0:r.length,o=i.length;e.observers=r===null?[t,o]:h(r,t,o),t.sources=h(i,e,a),t.trackIndex=o+2}function _(e){return b(e.sources)}function v(e){return e.observers===null?[]:b(e.observers)}function y(e){return e.observers!==null&&e.observers.length>0}function b(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(e[n]);return t}const x=[];function S(e,t){let n=e.state;e.kind===2?(n<t&&(e.state=t),n===0?s(e):l.inTransition||l.hooks?.promote(e)):n>=t||(e.state=t,n===0&&e.observers!==null&&e.observers.length>0&&x.push(e))}function C(e,t){return l.hooks?.suspend(e,t)===!0}function w(e){return e.pauses>0&&!(e.flags&32)}function T(e){for(E(e.observers,2);x.length>0;)E(x.pop().observers,1)}function E(e,t){if(e!==null)for(let n=0;n<e.length;n+=2)S(e[n],t)}const D=[],O=[];let k=0;function A(t,n=!1){if(t.state===0)return;let r=k;D[k]=t,O[k]=0,k+=1,t.flags|=128;try{for(;k>r;){let t=k-1,r=D[t];if(r.state===1||r.state===2&&n){let n=r.sources,i=O[t],a=!1;for(;i<n.length;){let r=n[i];if(i+=2,r.kind===0)continue;let o=r;if(j(o)){if(o.flags&1)throw new e(`CYCLE_DETECTED`);if(M(o)){O[t]=i,D[k]=o,O[k]=0,k+=1,o.flags|=128,a=!0;break}}}if(a)continue}r.state===2?F(r):r.state=0,r.flags&=-129,--k}}finally{for(let e=r;e<k;e+=1)D[e].flags&=-129;D.length=r,O.length=r,k=r}}function j(e){return e.state!==0&&!(e.flags&4)&&!w(e)}function M(e){if(!j(e))return!1;let t=[];for(let n=e.parent;n!==null;n=n.parent)n instanceof f&&n.state!==0&&!(n.flags&129)&&t.push(n);for(let e=t.length-1;e>=0;--e){let n=t[e];j(n)&&A(n)}return j(e)}function N(e){return l.listener!==null&&g(e),e.value}function P(t){if(t.flags&1)throw new e(`CYCLE_DETECTED`);if(t.state!==0&&M(t)&&A(t,l.nesting>=128),l.listener!==null&&g(t),t.flags&8)throw t.error;return t.value}function F(e){let t=e.fn;if(t===null)return;l.disposing+=1;try{r(e),e.runCleanups()}finally{--l.disposing}e.trackIndex=0,e.errorHandlers=null,e.idCount=0,e.childCount=0;let n=l.owner,a=l.listener,o=l.running;l.owner=e,l.listener=e,l.running=e,l.nesting+=1,e.state=0,e.flags|=1,e.stamp=c();let s,u=!1,d;try{s=t(e.value)}catch(e){u=!0,d=e}finally{l.owner=n,l.listener=a,l.running=o,--l.nesting,e.flags&=-2,m(e,e.flags&4?0:e.trackIndex)}e.kind===1?L(e,s,u,d):z(e,s,u,d),l.disposing+=1,e.flags&4&&(r(e),e.runCleanups()),i()}function I(e,t,n){let r=l.listener;l.listener=null;try{return e(t,n)}finally{l.listener=r}}function L(e,t,n,r){if(n&&C(e,r))return!1;let i=!!(e.flags&32);e.flags&=-33;let a=!!(e.flags&8),o;if(n&&R(e,r))return!1;if(n)e.flags|=8,e.error=r,o=!0;else{e.flags&=-9,e.error=void 0;let n=e.equals;try{o=i||a||n===!1||!I(n,e.value,t),o&&(e.value=t)}catch(t){e.flags|=8,e.error=t,o=!0}}if(!o||i)return o;let s=e.observers;if(s===null)return o;for(let e=0;e<s.length;e+=2){let t=s[e];t.state===1&&(t.state=2)}return o}function R(e,t){if(!o(e))return!1;e.flags&=-9,e.error=void 0;try{a(t,e)}catch(t){e.flags|=8,e.error=t}return!0}function z(e,t,r,i){if(r){C(e,i)||a(i,e);return}let o=e.apply,s;if(o===null)s=t;else{let n=!!(e.flags&64);e.flags&=-65;let r=e.value;if(e.value=t,n)return;let i=l.owner,c=l.listener,u=l.running;l.owner=e,l.listener=null,l.running=e;try{s=o(t,r)}catch(t){C(e,t)||a(t,e);return}finally{l.owner=i,l.listener=c,l.running=u}}typeof s==`function`&&(n(e,s),e.flags&4&&e.runCleanups())}export{f as Computation,d as Signal,y as hasObservers,I as isEqual,w as isFrozen,T as markObservers,v as observersOf,P as readMemo,N as readSignal,F as recompute,M as refreshAncestors,_ as sourcesOf,g as track,A as updateIfNecessary};
|
|
2
2
|
//# sourceMappingURL=graph.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","names":["NO_SOURCES","Signal","value","equals","name","Computation","Owner","parent","kind","flags","fn","nextSequence","unlinkFrom","removeObserver","observers","source","last","at","moved","movedAt","sources","node","from","i","withEdge","length","array","first","second","next","track","listener","rt","position","index","sourcesOf","everyOther","observersOf","hasObservers","out","edges","markStack","stale","previous","observer","enqueue","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","base","eagerSources","cursor","descended","dependency","needsUpdate","ShadowError","refreshAncestors","recompute","owner","ancestor","readSignal","signal","readMemo","memo","disposeChildren","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","finishDisposal","isEqual","prev","hadError","changed","routeToHandler","comparatorError","hasErrorHandler","handleError","unhandled","apply","cleanup","deferred","previousValue","addCleanup"],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport {\n addCleanup,\n disposeChildren,\n finishDisposal,\n handleError,\n hasErrorHandler,\n Owner,\n} from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n declare value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n declare equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name?: string) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /** 1 for a memo, 2 for an effect. */\n declare kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n declare state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n declare flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n declare value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n declare equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n declare seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkFrom(this, 0);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n staleObservers((markStack.pop() as Computation).observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at] as Computation;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] as number;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (!needsUpdate(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n if (!refreshAncestors(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n (frameNodes[i] as Computation).flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/** True when `node` is stale, alive and not frozen: running it now is both possible and needed. */\nfunction needsUpdate(node: Computation): boolean {\n return node.state !== CLEAN && (node.flags & FLAG_DISPOSED) === 0 && !isFrozen(node);\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n *\n * @returns Whether `node` still needs updating afterward (an owner's run may have cleaned or disposed it).\n */\nexport function refreshAncestors(node: Computation): boolean {\n if (!needsUpdate(node)) return false;\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (\n owner instanceof Computation &&\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_REFRESHING)) === 0\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i] as Computation;\n if (needsUpdate(ancestor)) updateIfNecessary(ancestor);\n }\n return needsUpdate(node);\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && refreshAncestors(memo)) {\n updateIfNecessary(memo, rt.nesting >= DEEP_LIMIT);\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n // One disposal for the children and the cleanups: all of them run even when one throws (the errors\n // are held in rt.uncaught), and the node still re-runs (it would stay dirty otherwise).\n rt.disposing += 1;\n try {\n disposeChildren(node);\n node.runCleanups();\n } finally {\n rt.disposing -= 1;\n }\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.nesting += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.nesting -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies. A node disposed while it ran\n // (it disposed its own owner) keeps none: reads after the disposal must not leave edges that\n // nothing will ever remove.\n unlinkFrom(node, (node.flags & FLAG_DISPOSED) !== 0 ? 0 : node.trackIndex);\n }\n\n let changed = true;\n if (node.kind === KIND_MEMO) changed = settleMemo(node, result, failed, failure);\n else settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n // The teardown's errors are thrown once the run is settled (unless a flush or an outer disposal collects them).\n rt.disposing += 1;\n finishDisposal();\n}\n\n/**\n * Calls a comparator untracked. It is a user callback: left tracked, the computation that writes (or the\n * reader that pulled the memo, the listener again once the run is over) would subscribe to whatever it\n * reads. Restored in `finally`, so a throwing comparator leaves the register as it found it.\n */\nexport function isEqual<T>(equals: (prev: T, next: T) => boolean, prev: T, next: T): boolean {\n const listener = rt.listener;\n rt.listener = null;\n try {\n return equals(prev, next);\n } finally {\n rt.listener = listener;\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !isEqual(equals, node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":"A,wQA+BA,MAAMA,EAA4B,OAAO,OAAO,CAAC,CAAC,EAkDlD,IAAaC,EAAb,KAAmD,CAEjD,KAAS,EAWT,UAAuC,KAEvC,MAAQ,EAaR,YAAY,EAAU,EAAmB,EAAe,CACtD,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,KAAOC,CAEd,CACF,EAiBaC,EAAb,cAAiCC,CAAwB,CAYvD,MAAiB,IAAA,GAIjB,GAKA,MAA6D,KAK7D,QAAyBN,EAEzB,UAAuC,KAEvC,MAAQ,EAER,WAAa,EAmBb,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAMO,CAAM,EACZ,KAAK,KAAOC,EACZ,KAAK,MAAQC,EACb,KAAK,MAAA,EACL,KAAK,GAAKC,EACV,KAAK,OAASP,EACd,KAAK,KAAOC,EACZ,KAAK,MAAQ,IAAA,GACb,KAAK,IAAMO,EAAa,CAW1B,CAEA,SAAmC,CACjC,KAAK,OAAA,EACLC,EAAW,KAAM,CAAC,EAClB,KAAK,GAAK,KACV,KAAK,MAAQ,IACf,CACF,EAMA,SAASC,EAAe,EAAgB,EAAkB,CACxD,IAAMC,EAAYC,EAAO,UACzB,GAAID,IAAc,KAAM,OACxB,IAAME,EAAOF,EAAU,OAAS,EAChC,GAAIG,IAAOD,EAAM,CACf,IAAME,EAAQJ,EAAUE,GAClBG,EAAUL,EAAUE,EAAO,GACjC,EAAUC,GAAMC,EAChB,EAAUD,EAAK,GAAKE,EACpB,EAAM,QAAQA,EAAU,GAAKF,CAC/B,CACA,EAAU,OAASD,CACrB,CAQA,SAASJ,EAAW,EAAmB,EAAoB,CACzD,IAAMQ,EAAUC,EAAK,QACrB,GAAI,IAAQ,QAAUC,GACtB,KAAK,IAAIC,EAAIH,EAAQ,OAAS,EAAGG,GAAKD,EAAM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AW9B,EAAUS,GACvBqB,EAAS,QAAA,IAAiB,EAAS,MAAA,EACzC,CACA,OAAOwC,CACT,CAYA,SAASC,EAAe,EAAmB,EAA2B,CACpE,GAAI,CAACE,EAAgBlE,CAAI,EAAG,MAAO,GACnC,EAAK,OAAS,GACd,EAAK,MAAQ,IAAA,GACb,GAAI,CACFmE,EAAYX,EAASxD,CAAI,CAC3B,OAASoE,EAAW,CAElB,EAAK,OAAA,EACL,EAAK,MAAQA,CACf,CACA,MAAO,EACT,CAEA,SAASV,EAAa,EAAmB,EAAiB,EAAiB,EAAwB,CACjG,GAAIH,EAAQ,CACL9B,EAAWzB,EAAMwD,CAAO,GAAGW,EAAYX,EAASxD,CAAI,EACzD,MACF,CACA,IAAMqE,EAAQrE,EAAK,MACfsE,EACJ,GAAID,IAAU,KACZ,EAAUf,MACL,CACL,IAAMiB,EAAA,GAAYvE,EAAK,MAAA,IACvB,EAAK,OAAS,IACd,IAAMwE,EAAgBxE,EAAK,MAE3B,GADA,EAAK,MAAQsD,EACTiB,EAAU,OACd,IAAMpB,EAAgBxC,EAAG,MACnByC,EAAmBzC,EAAG,SACtB0C,EAAkB1C,EAAG,QAC3B,EAAG,MAAQX,EACX,EAAG,SAAW,KAEd,EAAG,QAAUA,EACb,GAAI,CACF,EAAWqE,EAAyDf,EAAQkB,CAAa,CAC3F,OAAS9C,EAAO,CACTD,EAAWzB,EAAM0B,CAAK,GAAGyC,EAAYzC,EAAO1B,CAAI,EACrD,MACF,QAAU,CACR,EAAG,MAAQmD,EACX,EAAG,SAAWC,EACd,EAAG,QAAUC,CACf,CACF,CACI,OAAOiB,GAAY,aACrBG,EAAWzE,EAAMsE,CAAkB,EAE9BtE,EAAK,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
|
|
1
|
+
{"version":3,"file":"graph.js","names":["NO_SOURCES","Signal","value","equals","name","Computation","Owner","parent","kind","flags","fn","nextSequence","unlinkFrom","removeObserver","observers","source","last","at","moved","movedAt","sources","node","from","i","withEdge","length","array","first","second","next","track","listener","rt","position","index","sourcesOf","everyOther","observersOf","hasObservers","out","edges","markStack","stale","previous","observer","enqueue","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","base","eagerSources","cursor","descended","dependency","needsUpdate","ShadowError","refreshAncestors","recompute","owner","ancestor","readSignal","signal","readMemo","memo","disposeChildren","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","finishDisposal","isEqual","prev","hadError","changed","routeToHandler","comparatorError","hasErrorHandler","handleError","unhandled","apply","cleanup","deferred","previousValue","addCleanup"],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport {\n addCleanup,\n disposeChildren,\n finishDisposal,\n handleError,\n hasErrorHandler,\n Owner,\n} from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n declare value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n declare equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name?: string) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /** 1 for a memo, 2 for an effect. */\n declare kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n declare state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n declare flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n declare value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n declare equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n declare seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkFrom(this, 0);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n staleObservers((markStack.pop() as Computation).observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at] as Computation;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] as number;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (!needsUpdate(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n if (!refreshAncestors(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n (frameNodes[i] as Computation).flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/** True when `node` is stale, alive and not frozen: running it now is both possible and needed. */\nfunction needsUpdate(node: Computation): boolean {\n return node.state !== CLEAN && (node.flags & FLAG_DISPOSED) === 0 && !isFrozen(node);\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n *\n * @returns Whether `node` still needs updating afterward (an owner's run may have cleaned or disposed it).\n */\nexport function refreshAncestors(node: Computation): boolean {\n if (!needsUpdate(node)) return false;\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (\n owner instanceof Computation &&\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_REFRESHING)) === 0\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i] as Computation;\n if (needsUpdate(ancestor)) updateIfNecessary(ancestor);\n }\n return needsUpdate(node);\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && refreshAncestors(memo)) {\n updateIfNecessary(memo, rt.nesting >= DEEP_LIMIT);\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n // One disposal for the children and the cleanups: all of them run even when one throws (the errors\n // are held in rt.uncaught), and the node still re-runs (it would stay dirty otherwise).\n rt.disposing += 1;\n try {\n disposeChildren(node);\n node.runCleanups();\n } finally {\n rt.disposing -= 1;\n }\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.nesting += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.nesting -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies. A node disposed while it ran\n // (it disposed its own owner) keeps none: reads after the disposal must not leave edges that\n // nothing will ever remove.\n unlinkFrom(node, (node.flags & FLAG_DISPOSED) !== 0 ? 0 : node.trackIndex);\n }\n\n let changed = true;\n if (node.kind === KIND_MEMO) changed = settleMemo(node, result, failed, failure);\n else settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n // The teardown's errors are thrown once the run is settled (unless a flush or an outer disposal collects them).\n rt.disposing += 1;\n // The body disposed its own owner and kept going: what it created after that (child computations, cleanups) is\n // attached to a node nobody disposes again, so it would live and subscribe for good. It goes with the run.\n if ((node.flags & FLAG_DISPOSED) !== 0) {\n disposeChildren(node);\n node.runCleanups();\n }\n finishDisposal();\n}\n\n/**\n * Calls a comparator untracked. It is a user callback: left tracked, the computation that writes (or the\n * reader that pulled the memo, the listener again once the run is over) would subscribe to whatever it\n * reads. Restored in `finally`, so a throwing comparator leaves the register as it found it.\n */\nexport function isEqual<T>(equals: (prev: T, next: T) => boolean, prev: T, next: T): boolean {\n const listener = rt.listener;\n rt.listener = null;\n try {\n return equals(prev, next);\n } finally {\n rt.listener = listener;\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !isEqual(equals, node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":"A,wQA+BA,MAAMA,EAA4B,OAAO,OAAO,CAAC,CAAC,EAkDlD,IAAaC,EAAb,KAAmD,CAEjD,KAAS,EAWT,UAAuC,KAEvC,MAAQ,EAaR,YAAY,EAAU,EAAmB,EAAe,CACtD,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,KAAOC,CAEd,CACF,EAiBaC,EAAb,cAAiCC,CAAwB,CAYvD,MAAiB,IAAA,GAIjB,GAKA,MAA6D,KAK7D,QAAyBN,EAEzB,UAAuC,KAEvC,MAAQ,EAER,WAAa,EAmBb,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAMO,CAAM,EACZ,KAAK,KAAOC,EACZ,KAAK,MAAQC,EACb,KAAK,MAAA,EAC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EAAUf,MACL,CACL,IAAMiB,EAAA,GAAYvE,EAAK,MAAA,IACvB,EAAK,OAAS,IACd,IAAMwE,EAAgBxE,EAAK,MAE3B,GADA,EAAK,MAAQsD,EACTiB,EAAU,OACd,IAAMpB,EAAgBxC,EAAG,MACnByC,EAAmBzC,EAAG,SACtB0C,EAAkB1C,EAAG,QAC3B,EAAG,MAAQX,EACX,EAAG,SAAW,KAEd,EAAG,QAAUA,EACb,GAAI,CACF,EAAWqE,EAAyDf,EAAQkB,CAAa,CAC3F,OAAS9C,EAAO,CACTD,EAAWzB,EAAM0B,CAAK,GAAGyC,EAAYzC,EAAO1B,CAAI,EACrD,MACF,QAAU,CACR,EAAG,MAAQmD,EACX,EAAG,SAAWC,EACd,EAAG,QAAUC,CACf,CACF,CACI,OAAOiB,GAAY,aACrBG,EAAWzE,EAAMsE,CAAkB,EAE9BtE,EAAK,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{recompute as r,refreshAncestors as i,updateIfNecessary as a}from"./graph.js";import{handleError as o}from"./owner.js";import{clearQueues as s,hasPending as c,renderQueue as l,userQueue as u}from"./queue.js";import{rt as d}from"./state.js";const f=1e3;let p=!1;function m(e,t){return e.depth-t.depth||e.seq-t.seq}function h(e){try{if(!i(e))return;e.state===2?r(e):a(e)}catch(t){o(t,e)}}function g(e){let r=e.splice(0,e.length);r.sort(m);for(let e of r)e.flags&=-3,e.flags&4||(e.pauses>0?e.flags=e.flags&~n|t:h(e));return r.length}function _(e){let[t]=e;throw e.length===1?t:AggregateError(e,`SHADOW_FLUSH_ERRORS`)}function v(){if(d.flushing)return;d.flushing=!0;let t=0;try{for(;c();){if(t+=1,t>1e3){s(),d.uncaught.push(new e(`INFINITE_LOOP`));break}g(l.length>0?l:u)}}finally{d.flushing=!1}let n=d.uncaught;n.length>0&&(d.uncaught=[],_(n))}function y(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}function b(){if(p=!1,c())try{v()}catch(e){y(e)}}function x(){d.inTransition||d.batches>0||d.flushing||p||(p=!0,queueMicrotask(b))}function S(e){d.batches+=1;try{return e()}finally{--d.batches,d.batches===0&&c()&&x()}}function C(e,t,n,r){if(e)try{v()}catch(e){throw t?AggregateError([n,e],r):e}if(t)throw n}function w(e,t){d.batches+=1;let n,r,i=!1;try{n=e===void 0?void 0:e()}catch(e){i=!0,r=e}finally{--d.batches}return C(t||d.batches===0&&!d.flushing&&c(),i,r,`SHADOW_BATCH_ERRORS`),n}function T(e){return w(e,!1)}function E(e){return d.flushing?e===void 0?void 0:e():w(e,!0)}export{f as MAX_FLUSH_PASSES,T as batch,m as byCreation,v as flush,E as flushSync,C as flushThenThrow,S as group,y as reportUncaught,h as runQueued,x as schedule};
|
|
2
2
|
//# sourceMappingURL=scheduler.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","runQueued","refreshAncestors","effect","recompute","updateIfNecessary","error","handleError","drain","batch","queue","FLAG_TRANSITION","FLAG_PARKED","raise","first","errors","flush","rt","passes","hasPending","clearQueues","ShadowError","renderQueue","userQueue","reportUncaught","runScheduled","schedule","group","fn","flushThenThrow","wanted","failed","failure","message","runBatched","result","sync","flushSync"],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, refreshAncestors, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Runs one queued effect. Its stale owners come first: an owner that is about to re-run disposes the\n * effect, and running it before (a zombie, G-17) would read state that is already out of date.\n * @internal\n */\nexport function runQueued(effect: Computation): void {\n try {\n if (!refreshAncestors(effect)) return;\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n // Effects mostly arrive in creation order already: the sort then finds one ascending run and is O(n).\n batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const ran = drain(renderQueue.length > 0 ? renderQueue : userQueue);\n if (__DEV__) runs += ran;\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batches > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batches += 1;\n try {\n return fn();\n } finally {\n rt.batches -= 1;\n if (rt.batches === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * Flushes when `wanted`, then rethrows `failure` when `failed`. A failing flush is thrown on its own, or\n * together with `failure` (an `AggregateError` with `message`) when both threw.\n * @internal\n */\nexport function flushThenThrow(\n wanted: boolean,\n failed: boolean,\n failure: unknown,\n message: string,\n): void {\n if (wanted) {\n try {\n flush();\n } catch (error) {\n if (!failed) throw error;\n throw new AggregateError([failure, error], message);\n }\n }\n if (failed) throw failure;\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batches += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batches -= 1;\n }\n flushThenThrow(\n sync || (rt.batches === 0 && !rt.flushing && hasPending()),\n failed,\n failure,\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n return runBatched(fn, true);\n}\n"],"mappings":"A,mWAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAOA,SAAgBC,EAAU,EAA2B,CACnD,GAAI,CACF,GAAI,CAACC,EAAiBC,CAAM,EAAG,OAE3BA,EAAO,QAAA,EAAiBC,EAAUD,CAAM,EACvCE,EAAkBF,CAAM,CAC/B,OAASG,EAAO,CACdC,EAAYD,EAAOH,CAAM,CAC3B,CACF,CAGA,SAASK,EAAM,EAA8B,CAC3C,IAAMC,EAAQC,EAAM,OAAO,EAAGA,EAAM,MAAM,EAE1CD,EAAM,KAAKX,CAAU,EACrB,IAAK,IAAMK,KAAUM,EACnB,EAAO,OAAS,GACX,IAAO,MAAA,KACRN,EAAO,OAAS,EAElB,EAAO,MAASA,EAAO,MAAQ,CAACQ,EAAmBC,EAGrDX,EAAUE,CAAM,GAElB,OAAOM,EAAM,MACf,CAEA,SAASI,EAAM,EAAyB,CACtC,GAAM,CAACC,GAASC,EAEhB,MADIA,EAAO,SAAW,EAASD,EACrB,eACRC,EACiE,qBACnE,CACF,CAwBA,SAAgBC,GAAc,CAC5B,GAAIC,EAAG,SAAU,OACjB,EAAG,SAAW,GACd,IAAIC,EAAS,EAGb,GAAI,CACF,KAAOC,EAAW,GAAG,CAInB,GADA,GAAU,EACND,EAAA,IAA2B,CAC7BE,EAAY,EACZH,EAAG,SAAS,KAAK,IAAII,EAAY,eAAe,CAAC,EACjD,KACF,CACYb,EAAMc,EAAY,OAAS,EAAIA,EAAcC,CAAS,CAEp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,CAyBA,SAAgBS,EAAoB,EAAiB,CAKnD,OAJIpB,EAAG,SAEGW,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,EAErCM,EAAWN,EAAI,EAAI,CAC5B,C"}
|
|
1
|
+
{"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","runQueued","refreshAncestors","effect","recompute","updateIfNecessary","error","handleError","drain","batch","queue","FLAG_TRANSITION","FLAG_PARKED","raise","first","errors","flush","rt","passes","hasPending","clearQueues","ShadowError","renderQueue","userQueue","reportUncaught","runScheduled","schedule","group","fn","flushThenThrow","wanted","failed","failure","message","runBatched","result","sync","flushSync"],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, refreshAncestors, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Runs one queued effect. Its stale owners come first: an owner that is about to re-run disposes the\n * effect, and running it before (a zombie, G-17) would read state that is already out of date.\n * @internal\n */\nexport function runQueued(effect: Computation): void {\n try {\n if (!refreshAncestors(effect)) return;\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n // Effects mostly arrive in creation order already: the sort then finds one ascending run and is O(n).\n batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const ran = drain(renderQueue.length > 0 ? renderQueue : userQueue);\n if (__DEV__) runs += ran;\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batches > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batches += 1;\n try {\n return fn();\n } finally {\n rt.batches -= 1;\n if (rt.batches === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * Flushes when `wanted`, then rethrows `failure` when `failed`. A failing flush is thrown on its own, or\n * together with `failure` (an `AggregateError` with `message`) when both threw.\n * @internal\n */\nexport function flushThenThrow(\n wanted: boolean,\n failed: boolean,\n failure: unknown,\n message: string,\n): void {\n if (wanted) {\n try {\n flush();\n } catch (error) {\n if (!failed) throw error;\n throw new AggregateError([failure, error], message);\n }\n }\n if (failed) throw failure;\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batches += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batches -= 1;\n }\n flushThenThrow(\n sync || (rt.batches === 0 && !rt.flushing && hasPending()),\n failed,\n failure,\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n return runBatched(fn, true);\n}\n"],"mappings":"A,mWAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAOA,SAAgBC,EAAU,EAA2B,CACnD,GAAI,CACF,GAAI,CAACC,EAAiBC,CAAM,EAAG,OAE3BA,EAAO,QAAA,EAAiBC,EAAUD,CAAM,EACvCE,EAAkBF,CAAM,CAC/B,OAASG,EAAO,CACdC,EAAYD,EAAOH,CAAM,CAC3B,CACF,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AG,CACZ,QAAU,CACR,IAAG,QACCX,EAAG,UAAY,GAAKE,EAAW,GAAGO,EAAS,CACjD,CACF,CAOA,SAAgBG,EACd,EACA,EACA,EACA,EACM,CACN,GAAIC,EACF,GAAI,CACFd,EAAM,CACR,OAASV,EAAO,CAEd,MADKyB,EACK,eAAe,CAACC,EAAS1B,CAAK,EAAG2B,CAAO,EAD/B3B,CAErB,CAEF,GAAIyB,EAAQ,MAAMC,CACpB,CAOA,SAASE,EAAc,EAA2B,EAAkB,CAClE,EAAG,SAAW,EACd,IAAIC,EACAH,EACAD,EAAS,GACb,GAAI,CACF,EAASH,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,CAC7C,OAAStB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,OACL,CAOA,OANAuB,EACEO,GAASnB,EAAG,UAAY,GAAK,CAACA,EAAG,UAAYE,EAAW,EACxDY,EACAC,EACqD,qBACvD,EACOG,CACT,CAwBA,SAAgB1B,EAAS,EAAgB,CACvC,OAAOyB,EAAWN,EAAI,EAAK,CAC7B,CAyBA,SAAgBS,EAAoB,EAAiB,CAKnD,OAJIpB,EAAG,SAEGW,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,EAErCM,EAAWN,EAAI,EAAI,CAC5B,C"}
|
package/dist/server/list.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{Signal as t,readSignal as n}from"./internal/graph.js";import{
|
|
1
|
+
import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{Signal as t,readSignal as n}from"./internal/graph.js";import{writeSignal as r}from"./extend/index.js";import{disposeTree as i}from"./internal/dispose.js";import{useMemo as a}from"./memo.js";import{createRoot as o,getOwner as s,onCleanup as c,runWithOwner as l,untrack as u}from"./ownership.js";var d=class{value=void 0;dispose=f;itemNode=null;indexNode=null;constructor(e,t,n,r){this.key=e,this.first=t,this.item=n,this.index=r}readItem(){return this.itemNode??=new t(this.item,Object.is),n(this.itemNode)}readIndex(){return this.indexNode??=new t(this.index,Object.is),n(this.indexNode)}setItem(e){this.item=e,this.itemNode!==null&&r(this.itemNode,e,{allowInMemo:!0})}setIndex(e){this.index=e,this.indexNode!==null&&r(this.indexNode,e,{allowInMemo:!0})}};function f(){}function p(e,t,n){let r=n?.key;return h(e,r===void 0?{keyOf:e=>e,distinct:!1}:{keyOf:e=>r(e),distinct:!0},(e,n,i)=>t(r===void 0?e:n,i),n?.fallback)}function m(e,t,n){return h(e,{keyOf:(e,t)=>t,distinct:!1},(e,n,r)=>t(n,u(r)),n?.fallback)}function h(t,n,r,o){let l=new e(s());c(()=>{i(l)});let d=[],f;return a(()=>{let e=g(t()),i=Array.isArray(e)?Array.prototype.slice.call(e):e,a=u(()=>_(i,n)),s=b(d,a),c=[],p=[],m;try{a.forEach((e,t)=>{let n=s[t]??-1,i=n===-1?void 0:d[n];if(i!==void 0){p.push({row:i,item:e.item,position:t,fresh:!1});return}let a=x(l,e.key,e.first,e.item,t,r);c.push(a),p.push({row:a,item:e.item,position:t,fresh:!0})}),a.length===0&&o!==void 0&&(m=f??S(l,o))}catch(e){let t=[];for(let e of c)C(e.dispose,t);throw m!==void 0&&m!==f&&C(m.dispose,t),w(e,t)}let h=[],v=d,y=f;d=p.map(e=>e.row),f=m;let E=new Uint8Array(v.length);for(let e of s)e!==-1&&(E[e]=1);v.forEach((e,t)=>{E[t]!==1&&C(e.dispose,h)}),y!==void 0&&y!==m&&C(y.dispose,h);for(let e of p){if(e.fresh)continue;let t=e.row;t.index!==e.position&&t.setIndex(e.position),Object.is(t.item,e.item)||t.setItem(e.item)}return T(h),m===void 0?d.map(e=>e.value):[m.value]},{lazy:!0,allowWrites:!0})}function g(e){return e==null||e===!1?[]:e}function _(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let[i,a]of e.entries()){let e=t.keyOf(a,i),o=!0;t.distinct&&(r.has(e)?o=!1:r.add(e)),n.push({item:a,key:e,first:o})}return n}function v(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function y(e,t){return e!==void 0&&t!==void 0&&e.first&&t.first&&v(e.key,t.key)}function b(e,t){let n=e.length,r=t.length,i=new Int32Array(r).fill(-1),a=0;for(;a<n&&a<r&&y(e[a],t[a]);)i[a]=a,a+=1;let o=n-1,s=r-1;for(;o>=a&&s>=a&&y(e[o],t[s]);)i[s]=o,--o,--s;if(a>o||a>s)return i;let c=/* @__PURE__ */ new Map,l=new Int32Array(n).fill(-1);for(let t=o;t>=a;--t){let n=e[t];n!==void 0&&n.first&&(l[t]=c.get(n.key)??-1,c.set(n.key,t))}for(let e=a;e<=s;e+=1){let n=t[e];if(n===void 0||!n.first)continue;let r=c.get(n.key);r!==void 0&&r!==-1&&(i[e]=r,c.set(n.key,l[r]??-1))}return i}function x(e,t,n,r,i,a){let s=new d(t,n,r,i),c=()=>s.readItem(),f=()=>s.readIndex();return l(e,()=>o(e=>{s.dispose=e,s.value=u(()=>a(r,c,f))})),s}function S(e,t){return l(e,()=>o(e=>({value:u(t),dispose:e})))}function C(e,t){try{e()}catch(e){t.push(e)}}function w(e,t){return t.length===0?e:AggregateError([e,...t],`SHADOW_MAP_ERRORS`)}function T(e){if(e.length!==0)throw e.length===1?e[0]:AggregateError(e,`SHADOW_LIST_DISPOSE_ERRORS`)}export{m as indexArray,p as mapArray};
|
|
2
2
|
//# sourceMappingURL=list.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useMemo as e}from"./memo.js";import{useSignal as t}from"./signal.js";function n(n,r){let[i,a]=t([]);return[e(()=>{let e=n();for(let t of i())e=r(e,t.action);return e}),(e,t)=>{let n={action:e};a(e=>[...e,n]);let r=()=>{a(e=>e.filter(e=>e!==n))};t.then(r,r)}]}export{n as useOptimistic};
|
|
2
2
|
//# sourceMappingURL=optimistic.js.map
|
package/dist/server/ownership.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{
|
|
1
|
+
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{let t=o({owner:c,listener:null},()=>e(()=>i(c)));return c.disposed&&(i(c),c.runCleanups()),t}catch(e){try{i(c)}catch(t){throw AggregateError([e,t],`SHADOW_ROOT_ERRORS`)}throw e}}function l(){return a()}function u(e,t){let n=e;return n?.disposed&&(n=null),o({owner:n,listener:null},t)}function d(e){let t=a();t!==null&&n(t,e)}function f(e){let t=a();t!==null&&(t.errorHandlers===null?t.errorHandlers=[e]:t.errorHandlers.push(e))}function p(e,n){let i=new t(a());i.errorHandlers=[n];try{return u(i,e)}catch(e){r(e,i);return}}function m(){let t=a();if(t===null)throw new e(`NO_OWNER_ID`);for(let e=t;e!==null;e=e.parent){if(e.idPrefix===void 0)continue;let t=e.idCount;return e.idCount+=1,`s${e.idPrefix}${t}`}let n=[];for(let e=t;e!==null;e=e.parent)n.push(e.index);n.reverse();let r=t.idCount;return t.idCount+=1,`s${n.join(`-`)}_${r}`}export{p as catchError,c as createRoot,l as getOwner,d as onCleanup,f as onError,u as runWithOwner,s as untrack,m as useId};
|
|
2
2
|
//# sourceMappingURL=ownership.js.map
|