@shadow-js/core 1.0.2 → 1.0.4
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 +16 -0
- package/README.md +1 -2
- package/dist/dev/action.js +11 -7
- package/dist/dev/action.js.map +1 -1
- package/dist/dev/effect.js +8 -11
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/internal/concurrency.js +15 -11
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/dispose.js +2 -8
- package/dist/dev/internal/dispose.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +1 -1
- package/dist/dev/internal/graph.js +30 -35
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/owner.d.ts +2 -1
- package/dist/dev/internal/owner.js +10 -8
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/scheduler.js +40 -22
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/internal/state.js +11 -3
- package/dist/dev/internal/state.js.map +1 -1
- package/dist/dev/list.js +4 -4
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/resource.js +3 -3
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/signal.js +3 -3
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +4 -4
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/prod/action.js +1 -1
- package/dist/prod/action.js.map +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/dispose.js +1 -1
- package/dist/prod/internal/dispose.js.map +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/owner.js +1 -1
- package/dist/prod/internal/owner.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/internal/state.js +1 -1
- package/dist/prod/internal/state.js.map +1 -1
- package/dist/prod/list.js +1 -1
- package/dist/prod/list.js.map +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/resource.js.map +1 -1
- package/dist/prod/signal.js +1 -1
- package/dist/prod/signal.js.map +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/server/action.js +1 -1
- package/dist/server/action.js.map +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/dispose.js +1 -1
- package/dist/server/internal/dispose.js.map +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/owner.js +1 -1
- package/dist/server/internal/owner.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/internal/state.js +1 -1
- package/dist/server/internal/state.js.map +1 -1
- package/dist/server/list.js +1 -1
- package/dist/server/list.js.map +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/resource.js.map +1 -1
- package/dist/server/signal.js +1 -1
- package/dist/server/signal.js.map +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server-dev/action.js +11 -7
- package/dist/server-dev/action.js.map +1 -1
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +15 -11
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +2 -8
- package/dist/server-dev/internal/dispose.js.map +1 -1
- package/dist/server-dev/internal/graph.js +30 -35
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/owner.js +10 -8
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +40 -22
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/internal/state.js +11 -3
- package/dist/server-dev/internal/state.js.map +1 -1
- package/dist/server-dev/list.js +4 -4
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/resource.js +3 -3
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/signal.js +3 -3
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +4 -4
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","drain","batch","queue","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","raise","first","errors","flush","rt","passes","runs","hasPending","clearQueues","ShadowError","renderQueue","userQueue","reportUncaught","runScheduled","schedule","group","fn","runBatched","result","failure","failed","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, 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/** 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 try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n runs += drain(renderQueue.length > 0 ? renderQueue : userQueue);\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (sync || (rt.batchDepth === 0 && !rt.flushing && hasPending())) {\n try {\n flush();\n } catch (error) {\n if (failed) {\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n }\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n return runBatched(fn, true);\n}\n"],"mappings":"A,6UAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAGA,SAASC,EAAM,EAA8B,CAC3C,IAAMC,EAAQC,EAAM,OAAO,EAAGA,EAAM,MAAM,EAE1CD,EAAM,KAAKJ,CAAU,EACrB,IAAK,IAAMM,KAAUF,EAEnB,GADA,EAAO,OAAS,GACX,IAAO,MAAA,GACZ,IAAIE,EAAO,OAAS,EAElB,EAAO,MAASA,EAAO,MAAQ,CAACC,EAAmBC,OAGrD,GAAI,CAEEF,EAAO,QAAA,EAAiBG,EAAUH,CAAM,EACvCI,EAAkBJ,CAAM,CAC/B,OAASK,EAAO,CACdC,EAAYD,EAAOL,CAAM,CAC3B,CAPA,CASF,OAAOF,EAAM,MACf,CAEA,SAASS,EAAM,EAAyB,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R,IAAG,UACL,CACA,GAAIuB,GAASjB,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYG,EAAW,EAC7D,GAAI,CACFJ,EAAM,CACR,OAASL,EAAO,CAOd,MANIsB,EACQ,eACR,CAACD,EAASrB,CAAK,EACsC,qBACvD,EAEIA,CACR,CAEF,GAAIsB,EAAQ,MAAMD,EAClB,OAAOD,CACT,CAwBA,SAAgB3B,EAAS,EAAgB,CACvC,OAAO0B,EAAWD,EAAI,EAAK,CAC7B,CAyBA,SAAgBM,EAAoB,EAAiB,CAKnD,OAJIlB,EAAG,SAEGY,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,EAErCC,EAAWD,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,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AAqB,CAE5B,GADA,EAAqB,GAChBN,EAAW,EAChB,GAAI,CACFH,EAAM,CACR,OAASV,EAAO,CACdkB,EAAelB,CAAK,CACtB,CACF,CAmBA,SAAgBoB,GAAiB,CAE3BT,EAAG,cAAgBA,EAAG,QAAU,GAAKA,EAAG,UAAYpB,IACxD,EAAqB,GACrB,eAAe4B,CAAY,EAC7B,CAuBA,SAAgBE,EAAS,EAAgB,CACvC,EAAG,SAAW,EACd,GAAI,CACF,OAAOC,EAAG,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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={owner:null,listener:null,running:null,
|
|
1
|
+
const e={owner:null,listener:null,running:null,batches:0,flushing:!1,nesting:0,disposing:0,uncaught:[],inTransition:!1,hydrating:!1,hooks:null};let t=0;function n(){return t+=1,t}export{n as nextSequence,e as rt};
|
|
2
2
|
//# sourceMappingURL=state.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","names":["rt","counter","nextSequence"],"sources":["../../../src/internal/state.ts"],"sourcesContent":["import type { Computation } from \"./graph\";\nimport type { Owner } from \"./owner\";\n\n/**\n * A hold for a value a transition builds while its reads wait for data (a `Show` branch built during a\n * transition): the reads that wait count against this hold, not against the Suspense boundary around\n * the value, so the shown value stays until the hold settles. Created by `createTransitionHold`.\n * @since 1.0.0\n */\nexport interface TransitionHold {\n /** Runs `fn` with this hold as the Suspense boundary of the reads inside it. */\n run<T>(fn: () => T): T;\n /** Reads still waiting for data. */\n count(): number;\n /** True once a read in the hold was held (the value is then pending, not ready). */\n engaged(): boolean;\n /** Ends the hold without waking anything (the value is being dropped). */\n drop(): void;\n}\n\n/**\n * The choice a branch slot (Show, Switch) shows: its index, and what decides a rebuild. Renderers\n * extend it with what they need to build the branch.\n * @since 1.0.0\n */\nexport interface SlotChoice {\n /** Which branch is chosen: its position among the slot's branches, or the renderer's fallback index. */\n readonly index: number;\n /** True when the branch is rebuilt whenever `when` changes identity; false when only `index` counts. */\n readonly keyed: boolean;\n /** The condition value that selected the branch. */\n readonly when: unknown;\n}\n\n/**\n * The record of a branch's owner that its accessors read: the value and whether it is being torn down.\n * @since 1.0.0\n */\nexport interface SlotOwned {\n /** The index of the branch this record belongs to (see {@link SlotChoice.index}). */\n index: number;\n /** The latest condition value while the branch is shown; what its accessor returns during teardown. */\n value: unknown;\n /** True while the branch is torn down: its accessor then returns `value` instead of throwing. */\n disposing: boolean;\n}\n\n/**\n * A branch a slot shows, or builds during a transition. A branch without `dispose` is torn down by its memo.\n * @since 1.0.0\n */\nexport interface SlotBranch<C extends SlotChoice> {\n /** The choice the branch was built for. */\n readonly choice: C;\n /** The record its accessors read. */\n readonly owned: SlotOwned;\n /** What the branch produced: the value the slot's output returns while the branch is shown. */\n readonly result: unknown;\n /**\n * Tears the branch down. Set for the branches a transition built: they live under the holder, not\n * under the memo.\n * @default undefined (the slot's memo tears the branch down)\n */\n readonly dispose?: () => void;\n /**\n * The hold a transition built the branch under; null when none of its reads was held.\n * @default undefined (a memo-owned branch has no hold)\n */\n readonly hold?: TransitionHold | null;\n}\n\n/**\n * What a slot's output memo keeps: the branch on screen (its result is the value the output returns).\n * @since 1.0.0\n */\nexport interface SlotState<C extends SlotChoice> {\n /** The branch on screen, or undefined before the first build and while the memo rebuilds it. */\n live: SlotBranch<C> | undefined;\n}\n\n/**\n * The transition layer of one slot, from `transitionHooks()?.slotSwap(...)`: it keeps the shown\n * branch while a transition builds the next one (see `slotSwap` in concurrency.ts).\n * @since 1.0.0\n */\nexport interface SlotSwap<C extends SlotChoice> {\n /**\n * Runs one pass of the slot's memo for `choice`. True when a transition keeps the shown value. False\n * when the usual path follows: the branch on screen has been retired and `state.live` is cleared.\n */\n step(choice: C): boolean;\n}\n\n/**\n * The hold of one Suspense boundary: engaged by a transition read, released when its data arrived.\n * From `transitionHooks()?.boundaryHold()`.\n * @since 1.0.0\n */\nexport interface BoundaryHold {\n /** Engages the hold (a second call changes nothing) so the boundary keeps its content; returns true. */\n engage(): boolean;\n /** When engaged: wakes the readers that waited, then ends the hold. Otherwise does nothing. */\n release(): void;\n /** True while the hold is engaged. */\n holding(): boolean;\n}\n\n/**\n * The transition machinery the engine calls through `rt.hooks`: transition lanes, pauses (Activity)\n * and suspensions (Suspense holds). It is created by the first call of an API that needs it (see\n * concurrency.ts), so an application that never calls one of those APIs carries none of their code.\n * Renderers reach it through `transitionHooks()`.\n * @since 1.0.0\n */\nexport interface Hooks {\n /** The transition layer of one branch slot (see `slotSwap` in concurrency.ts). */\n 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 Suspense boundary's hold (see `boundaryHold` in concurrency.ts). */\n boundaryHold(): BoundaryHold;\n /** Queues an effect that is due in the transition lane, or parks it while its owner is paused. */\n place(effect: Computation, inLane: boolean): void;\n /** An urgent write reached an effect that waits in the lane or is parked: it moves to the urgent queue. */\n promote(effect: Computation): void;\n /** Forgets the lane queues (the flush loop guard). */\n clear(): void;\n /** Keeps `node` for a transition when `error` is a suspension; returns false for any other error. */\n suspend(node: Computation, error: unknown): boolean;\n /** The engine side of `holdReader`: throws the suspension sentinel when `tracker.hold()` is true. */\n holdReader(tracker: { hold?(): boolean }): void;\n /** The engine side of `startTransition` in the browser. */\n startTransition(fn: () => void): Promise<void>;\n /** The engine side of `beginHold`: counts one more Suspense hold. */\n beginHold(): void;\n /** The engine side of `endHold`: counts one hold less and settles the lane. */\n endHold(): void;\n /** The engine side of `wakeSuspended`. */\n wakeSuspended(): void;\n /** The engine side of `pauseOwner`. */\n pause(owner: Owner): void;\n /** The engine side of `resumeOwner`. */\n resume(owner: Owner): void;\n /** The engine side of `createTransitionHold`. */\n createHold(onSettled: () => void): TransitionHold;\n}\n\n/**\n * The runtime registers (R-CODE-4): the only module-level mutable state of core besides\n * monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).\n */\nexport const rt: {\n /** Owner that adopts newly created nodes. */\n owner: Owner | null;\n /** Computation that records the signals it reads; null while untracked. */\n listener: Computation | null;\n /** Computation currently executing, tracked or not (used by the write-in-memo guard). */\n running: Computation | null;\n /** Nesting depth of batch()/flushSync() calls. */\n
|
|
1
|
+
{"version":3,"file":"state.js","names":["rt","counter","nextSequence"],"sources":["../../../src/internal/state.ts"],"sourcesContent":["import type { Computation } from \"./graph\";\nimport type { Owner } from \"./owner\";\n\n/**\n * A hold for a value a transition builds while its reads wait for data (a `Show` branch built during a\n * transition): the reads that wait count against this hold, not against the Suspense boundary around\n * the value, so the shown value stays until the hold settles. Created by `createTransitionHold`.\n * @since 1.0.0\n */\nexport interface TransitionHold {\n /** Runs `fn` with this hold as the Suspense boundary of the reads inside it. */\n run<T>(fn: () => T): T;\n /** Reads still waiting for data. */\n count(): number;\n /** True once a read in the hold was held (the value is then pending, not ready). */\n engaged(): boolean;\n /** Ends the hold without waking anything (the value is being dropped). */\n drop(): void;\n}\n\n/**\n * The choice a branch slot (Show, Switch) shows: its index, and what decides a rebuild. Renderers\n * extend it with what they need to build the branch.\n * @since 1.0.0\n */\nexport interface SlotChoice {\n /** Which branch is chosen: its position among the slot's branches, or the renderer's fallback index. */\n readonly index: number;\n /** True when the branch is rebuilt whenever `when` changes identity; false when only `index` counts. */\n readonly keyed: boolean;\n /** The condition value that selected the branch. */\n readonly when: unknown;\n}\n\n/**\n * The record of a branch's owner that its accessors read: the value and whether it is being torn down.\n * @since 1.0.0\n */\nexport interface SlotOwned {\n /** The index of the branch this record belongs to (see {@link SlotChoice.index}). */\n index: number;\n /** The latest condition value while the branch is shown; what its accessor returns during teardown. */\n value: unknown;\n /** True while the branch is torn down: its accessor then returns `value` instead of throwing. */\n disposing: boolean;\n}\n\n/**\n * A branch a slot shows, or builds during a transition. A branch without `dispose` is torn down by its memo.\n * @since 1.0.0\n */\nexport interface SlotBranch<C extends SlotChoice> {\n /** The choice the branch was built for. */\n readonly choice: C;\n /** The record its accessors read. */\n readonly owned: SlotOwned;\n /** What the branch produced: the value the slot's output returns while the branch is shown. */\n readonly result: unknown;\n /**\n * Tears the branch down. Set for the branches a transition built: they live under the holder, not\n * under the memo.\n * @default undefined (the slot's memo tears the branch down)\n */\n readonly dispose?: () => void;\n /**\n * The hold a transition built the branch under; null when none of its reads was held.\n * @default undefined (a memo-owned branch has no hold)\n */\n readonly hold?: TransitionHold | null;\n}\n\n/**\n * What a slot's output memo keeps: the branch on screen (its result is the value the output returns).\n * @since 1.0.0\n */\nexport interface SlotState<C extends SlotChoice> {\n /** The branch on screen, or undefined before the first build and while the memo rebuilds it. */\n live: SlotBranch<C> | undefined;\n}\n\n/**\n * The transition layer of one slot, from `transitionHooks()?.slotSwap(...)`: it keeps the shown\n * branch while a transition builds the next one (see `slotSwap` in concurrency.ts).\n * @since 1.0.0\n */\nexport interface SlotSwap<C extends SlotChoice> {\n /**\n * Runs one pass of the slot's memo for `choice`. True when a transition keeps the shown value. False\n * when the usual path follows: the branch on screen has been retired and `state.live` is cleared.\n */\n step(choice: C): boolean;\n}\n\n/**\n * The hold of one Suspense boundary: engaged by a transition read, released when its data arrived.\n * From `transitionHooks()?.boundaryHold()`.\n * @since 1.0.0\n */\nexport interface BoundaryHold {\n /** Engages the hold (a second call changes nothing) so the boundary keeps its content; returns true. */\n engage(): boolean;\n /** When engaged: wakes the readers that waited, then ends the hold. Otherwise does nothing. */\n release(): void;\n /** True while the hold is engaged. */\n holding(): boolean;\n}\n\n/**\n * The transition machinery the engine calls through `rt.hooks`: transition lanes, pauses (Activity)\n * and suspensions (Suspense holds). It is created by the first call of an API that needs it (see\n * concurrency.ts), so an application that never calls one of those APIs carries none of their code.\n * Renderers reach it through `transitionHooks()`.\n * @since 1.0.0\n */\nexport interface Hooks {\n /** The transition layer of one branch slot (see `slotSwap` in concurrency.ts). */\n 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 Suspense boundary's hold (see `boundaryHold` in concurrency.ts). */\n boundaryHold(): BoundaryHold;\n /** Queues an effect that is due in the transition lane, or parks it while its owner is paused. */\n place(effect: Computation, inLane: boolean): void;\n /** An urgent write reached an effect that waits in the lane or is parked: it moves to the urgent queue. */\n promote(effect: Computation): void;\n /** Forgets the lane queues (the flush loop guard). */\n clear(): void;\n /** Keeps `node` for a transition when `error` is a suspension; returns false for any other error. */\n suspend(node: Computation, error: unknown): boolean;\n /** The engine side of `holdReader`: throws the suspension sentinel when `tracker.hold()` is true. */\n holdReader(tracker: { hold?(): boolean }): void;\n /** The engine side of `startTransition` in the browser. */\n startTransition(fn: () => void): Promise<void>;\n /** The engine side of `beginHold`: counts one more Suspense hold. */\n beginHold(): void;\n /** The engine side of `endHold`: counts one hold less and settles the lane. */\n endHold(): void;\n /** The engine side of `wakeSuspended`. */\n wakeSuspended(): void;\n /** The engine side of `pauseOwner`. */\n pause(owner: Owner): void;\n /** The engine side of `resumeOwner`. */\n resume(owner: Owner): void;\n /** The engine side of `createTransitionHold`. */\n createHold(onSettled: () => void): TransitionHold;\n}\n\n/**\n * The runtime registers (R-CODE-4): the only module-level mutable state of core besides\n * monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).\n *\n * Not a public symbol: `core/extend` re-exports only the types of this module, and the registers stay\n * behind the extension functions (`currentOwner`, `untrack` and friends) so a plugin cannot leave one set.\n * @internal\n */\nexport const rt: {\n /** Owner that adopts newly created nodes. */\n owner: Owner | null;\n /** Computation that records the signals it reads; null while untracked. */\n listener: Computation | null;\n /** Computation currently executing, tracked or not (used by the write-in-memo guard). */\n running: Computation | null;\n /** Nesting depth of batch()/flushSync() calls. */\n batches: number;\n /** True while the flush loop is draining the effect queues. */\n flushing: boolean;\n /** Nesting depth of memo recomputation, used to switch to iterative pulls. */\n nesting: number;\n /** Nesting depth of disposals in progress; errors raised meanwhile are collected, not thrown. */\n disposing: number;\n /** Errors nobody handled during the current flush or disposal; rethrown once it completes. */\n uncaught: unknown[];\n /** True while a transition callback or a transition-lane run is active: writes made now join the lane. */\n inTransition: boolean;\n /** True while `hydrate()` claims server markup (useExternalStore reads its server snapshot). */\n hydrating: boolean;\n /** The transition machinery, or null until an API that needs it is first called. */\n hooks: Hooks | null;\n} = {\n owner: null,\n listener: null,\n running: null,\n batches: 0,\n flushing: false,\n nesting: 0,\n disposing: 0,\n uncaught: [],\n inTransition: false,\n hydrating: false,\n hooks: null,\n};\n\nlet counter = 0;\n/**\n * Monotonic creation sequence; orders sibling effects (G-16). Not a public symbol: only the engine\n * stamps nodes with it.\n * @internal\n */\nexport function nextSequence(): number {\n counter += 1;\n return counter;\n}\n"],"mappings":"AA8JA,MAAaA,EAuBT,CACF,MAAO,KACP,SAAU,KACV,QAAS,KACT,QAAS,EACT,SAAU,GACV,QAAS,EACT,UAAW,EACX,SAAU,CAAC,EACX,aAAc,GACd,UAAW,GACX,MAAO,IACT,EAEA,IAAIC,EAAU,EAMd,SAAgBC,GAAuB,CAErC,MADA,IAAW,EACJD,CACT,C"}
|
package/dist/prod/list.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{readSignal as
|
|
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{createRoot as r,getOwner as i,onCleanup as a,runWithOwner as o,untrack as s}from"./ownership.js";import{disposeTree as c}from"./internal/dispose.js";import{writeSignal as l}from"./extend/index.js";import{useMemo as u}from"./memo.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&&l(this.itemNode,e,{allowInMemo:!0})}setIndex(e){this.index=e,this.indexNode!==null&&l(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,s(r)),n?.fallback)}function h(t,n,r,o){let l=new e(i());a(()=>{c(l)});let d=[],f;return u(()=>{let e=g(t()),i=Array.isArray(e)?Array.prototype.slice.call(e):e,a=s(()=>_(i,n)),c=b(d,a),u=[],p=[],m;try{a.forEach((e,t)=>{let n=c[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);u.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 u)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 c)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,i,a,c){let l=new d(t,n,i,a),u=()=>l.readItem(),f=()=>l.readIndex();return o(e,()=>r(e=>{l.dispose=e,l.value=s(()=>c(i,u,f))})),l}function S(e,t){return o(e,()=>r(e=>({value:s(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
|
package/dist/prod/list.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list.js","names":["Row","noop","key","first","item","index","createSignalNode","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n declare readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n declare readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n declare item: T;\n /** Index last written to the row. */\n declare index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":"A,qYAuBA,IAAMA,EAAN,KAAgB,CASd,MAAW,IAAA,GACX,QAAsBC,EAEtB,SAAyC,KAEzC,UAA+C,KAE/C,YAAY,EAAc,EAAgB,EAAS,EAAe,CAChE,KAAK,IAAMC,EACX,KAAK,MAAQC,EACb,KAAK,KAAOC,EACZ,KAAK,MAAQC,CACf,CAEA,UAAc,CAEZ,MADA,MAAK,WAAaC,EAAiB,KAAK,KAAM,OAAO,EAAE,EAChDC,EAAW,KAAK,QAAQ,CACjC,CAEA,WAAoB,CAElB,MADA,MAAK,YAAcD,EAAiB,KAAK,MAAO,OAAO,EAAE,EAClDC,EAAW,KAAK,SAAS,CAClC,CAGA,QAAQ,EAAe,CACrB,KAAK,KAAOC,EACR,KAAK,WAAa,MAAMC,EAAY,KAAK,SAAUD,EAAM,CAAE,YAAa,EAAK,CAAC,CACpF,CAEA,SAAS,EAAoB,CAC3B,KAAK,MAAQA,EACT,KAAK,YAAc,MAAMC,EAAY,KAAK,UAAWD,EAAM,CAAE,YAAa,EAAK,CAAC,CACtF,CACF,EAGA,SAASP,GAAa,CAEtB,CA6FA,SAAgBS,EACd,EACA,EACA,EACe,CACf,IAAMC,EAAQC,GAAS,IACvB,OAAOC,EACLC,EACAH,IAAU,IAAA,GACN,CAAE,MAAQ,GAAYP,EAAM,SAAU,EAAM,EAC5C,CAAE,MAAQ,GAAYO,EAAMP,CAAI,EAAG,SAAU,EAAK,GACrD,EAAM,EAAU,IAAcW,EAA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","Row","noop","key","first","item","index","Signal","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n disposeOwner,\n Owner,\n readSignal,\n SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n declare readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n declare readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n declare item: T;\n /** Index last written to the row. */\n declare index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= new SignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= new SignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":"A,2XAsBA,IAAMC,EAAN,KAAgB,CASd,MAAW,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C,CACA,OAAOrC,CACT,CAMA,SAASS,EACP,EACA,EACA,EACA,EACA,EACA,EACW,CACX,IAAMD,EAAM,IAAI3C,EAAUE,EAAKC,EAAOC,EAAMC,CAAK,EAC3CW,MAAoB2B,EAAI,SAAS,EACjC1B,MAA0B0B,EAAI,UAAU,EAO9C,OANA8B,EAAapD,MACXqD,EAAY,GAAY,CACtB,EAAI,QAAUC,EACd,EAAI,MAAQvD,MAAcyB,EAAMzC,EAAMY,EAAUC,CAAS,CAAC,CAC5D,CAAC,CACH,EACO0B,CACT,CAGA,SAASI,EAAgB,EAAe,EAAgC,CACtE,OAAO0B,EAAapD,MAClBqD,EAAY,IAAa,CAAE,MAAOtD,EAAQ0B,CAAQ,EAAG,SAAQ,EAAE,CACjE,CACF,CAGA,SAASI,EAAkB,EAAqB,EAA2B,CACzE,GAAI,CACFyB,EAAQ,CACV,OAAS3B,EAAO,CACdC,EAAS,KAAKD,CAAK,CACrB,CACF,CAEA,SAASG,EAAgB,EAAkB,EAAuC,CAEhF,OADIF,EAAS,SAAW,EAAU2B,EACvB,eACT,CAACA,EAAS,GAAG3B,CAAQ,EAC0C,mBACjE,CACF,CAGA,SAASM,EAAc,EAAoC,CACzD,GAAIN,EAAS,SAAW,EAExB,MADIA,EAAS,SAAW,EAASA,EAAS,GAChC,eACRA,EAGI,4BACN,CACF,C"}
|
package/dist/prod/resource.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readSignal as
|
|
1
|
+
import{Signal as e,readSignal as t}from"./internal/graph.js";import{batch as n}from"./internal/scheduler.js";import{onCleanup as r,untrack as i}from"./ownership.js";import{useRenderEffect as a}from"./effect.js";import{useContext as o}from"./context.js";import{ResourceCacheContext as s,SuspenseContext as c}from"./suspense.js";import{holdReader as l,inTransition as u}from"./internal/concurrency.js";import{currentListener as d,writeSignal as f}from"./extend/index.js";function p(n,r){let i=new e(n,r?Object.is:!1);return[()=>t(i),e=>{f(i,e,{allowInMemo:!0})}]}function m(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function h(e,t,f){let h=typeof t==`function`,g=h?typeof e==`function`?e:()=>e:()=>!0,_=e,v=h?t:(e,t)=>_(t),y=(h?f:t)??{},b=`initialValue`in y,[x,S]=p(y.initialValue,!1),[C,w]=p(b?`ready`:`unresolved`,!0),T=e=>{w(e)},[E,D]=p(void 0,!1),O=o(s),k=O===null?void 0:O.key(y.key),A=O!==null&&k!==void 0?O.read(k):void 0,j=!1,M=0,N,P=!1,F=b,I=/* @__PURE__ */ new Set,L=()=>{if(I.size===0)return;let e=[...I];I.clear();for(let t of e)t.decrement()},R=(e,t)=>{if(P||e!==M)return!1;try{n(t)}finally{L()}return!0},z=(e,t)=>{if(A!==void 0&&!j&&!t)return j=!0,F=!0,n(()=>{S(A.value),T(`ready`)}),Promise.resolve(A.value);N?.abort();let r=new AbortController;N=r,M+=1;let a=M;n(()=>{T(F?`refreshing`:`pending`),D(void 0)});let o;try{let n=t||O===null||k===void 0?void 0:O.pending?.(k);o=n===void 0?i(()=>v(e,{signal:r.signal,refetching:t,value:i(x)})):n}catch(e){return R(a,()=>{D(e),T(`errored`)}),Promise.resolve(void 0)}if(m(o))return O!==null&&k!==void 0&&O.track(k,Promise.resolve(o),{deferStream:y.deferStream}),Promise.resolve(o).then(e=>R(a,()=>{F=!0,S(e),T(`ready`)})?e:void 0,e=>{R(a,()=>{D(e),T(`errored`)})});let s=o,c=R(a,()=>{F=!0,S(s),T(`ready`)});return Promise.resolve(c?s:void 0)},B=e=>{e===!1||e==null?(N?.abort(),M+=1,L(),T(F?`ready`:`unresolved`)):z(e,F)},V=(()=>{let e=C();if(e===`errored`)throw E();if(e===`pending`){let e=o(c);e!==null&&!I.has(e)&&(I.add(e),e.increment()),e!==null&&d()!==null&&u()&&l(e)}return x()});return Object.defineProperties(V,{state:{get:C},loading:{get:()=>C()===`pending`||C()===`refreshing`},error:{get:E},latest:{get:x},refetch:{value:()=>{if(P)return Promise.resolve(void 0);let e=i(g);return e===!1||e==null?Promise.resolve(void 0):z(e,F)}},mutate:{value:e=>{let t,r=!1;try{n(()=>{t=typeof e==`function`?i(()=>e(x())):e,r=!0,N?.abort(),M+=1,F=!0,S(t),D(void 0),T(`ready`)})}finally{r&&L()}return t}}}),a(g,B),r(()=>{P=!0,N?.abort(),L()}),V}export{h as useResource};
|
|
2
2
|
//# sourceMappingURL=resource.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.js","names":["cell","node","createSignalNode","initial","distinct","readSignal","writeSignal","next","isPromiseLike","value","useResource","hasSource","second","source","first","oneShot","fetcher","info","options","third","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","useContext","ResourceCacheContext","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","batch","apply","load","refetching","current","output","joined","untrack","input","error","result","immediate","applied","onSource","read","SuspenseContext","currentListener","inTransition","holdReader","resolved","changed","useRenderEffect","onCleanup"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":"A,+dAkGA,SAASA,EAAQ,EAAY,EAAqD,CAChF,IAAMC,EAAOC,EAAoBC,EAASC,EAAW,OAAO,GAAK,EAAK,EACtE,MAAO,KACCC,EAAWJ,CAAI,EACpB,GAAS,CACRK,EAAYL,EAAMM,EAAM,CAAE,YAAa,EAAK,CAAC,CAC/C,CACF,CACF,CAEA,SAASC,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAA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CACvB,CACA,OAAOwB,CACT,CACF,CACF,CAAC,EAOIE,EAAgBnD,EAAQ2C,CAAQ,EACrCS,MAAgB,CACd,EAAW,GACX/B,GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMmB,CACT,C"}
|
|
1
|
+
{"version":3,"file":"resource.js","names":["SignalNode","cell","node","Signal","initial","distinct","readSignal","writeSignal","next","isPromiseLike","value","useResource","hasSource","second","source","first","oneShot","fetcher","info","options","third","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","useContext","ResourceCacheContext","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","batch","apply","load","refetching","current","output","joined","untrack","input","error","result","immediate","applied","onSource","read","SuspenseContext","currentListener","inTransition","holdReader","resolved","changed","useRenderEffect","onCleanup"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = new SignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":"A,qdAkGA,SAASC,EAAQ,EAAY,EAAqD,CAChF,IAAMC,EAAO,IAAIF,EAAcI,EAASC,EAAW,OAAO,GAAK,EAAK,EACpE,MAAO,KACCC,EAAWJ,CAAI,EACpB,GAAS,CACRK,EAAYL,EAAMM,EAAM,CAAE,YAAa,EAAK,CAAC,CAC/C,CACF,CACF,CAEA,SAASC,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiFA,SAAgBC,EACd,EACA,EACA,EACa,CACb,IAA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GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMmB,CACT,C"}
|
package/dist/prod/signal.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readSignal as
|
|
1
|
+
import{Signal as e,readSignal as t}from"./internal/graph.js";import{untrack as n}from"./ownership.js";import{writeSignal as r}from"./extend/index.js";function i(i,a){let o=a?.equals===void 0?Object.is:a.equals,s=new e(i,o,a?.name);return[()=>t(s),(e=>{let t=typeof e==`function`?n(()=>e(s.value)):e;return r(s,t),t})]}export{i as useSignal};
|
|
2
2
|
//# sourceMappingURL=signal.js.map
|
package/dist/prod/signal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signal.js","names":["useSignal","equals","options","signal","
|
|
1
|
+
{"version":3,"file":"signal.js","names":["SignalNode","useSignal","equals","options","signal","Signal","value","readSignal","resolved","next","untrack","writeSignal"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n type Equals,\n readSignal,\n type Setter,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value. It runs untracked: a signal it reads\n * is not a dependency of the computation that writes.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string | undefined;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = new SignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":"A,sJAiDA,SAAgBC,EAAa,EAAU,EAAsD,CAC3F,IAAMC,EAAoBC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OACxEC,EAAS,IAAIJ,EAAcM,EAAOJ,EAAQC,GAAS,IAAI,EAS7D,MAAO,KARyBI,EAAWH,CAAM,GACjC,GAAkB,CAChC,IAAMI,EACJ,OAAOC,GAAS,WAAaC,MAAeD,EAAwBL,EAAO,KAAK,CAAC,EAAIK,EAGvF,OADAE,EAAYP,EAAQI,CAAQ,EACrBA,CACT,EACmB,CACrB,C"}
|
package/dist/prod/store/nodes.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{track as
|
|
1
|
+
import{Signal as e,track as t}from"../internal/graph.js";import{isTracking as n,notify as r}from"../extend/index.js";const i=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),a=/* @__PURE__ */ new WeakMap,o=/* @__PURE__ */ new WeakMap;function s(e){return i.has(e)}function c(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;if(e===Object.prototype)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(e){return typeof e!=`object`||!e?e:o.get(e)??e}function u(e){let t=/* @__PURE__ */ new Set([e]),n=[e];for(;n.length>0;){let e=n.pop();for(let r of Object.keys(e)){let i=Reflect.get(e,r);if(typeof i==`object`&&i){if(o.has(i))return!0;c(i)&&!t.has(i)&&(t.add(i),n.push(i))}}}return!1}function d(e){let t=l(e);if(t!==e||!c(t)||!u(t))return t;let n=/* @__PURE__ */ new Map,r=e=>{let t=n.get(e);if(t!==void 0)return t;let r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return n.set(e,r),r},i=r(t),a=[t];for(let e=0;e<a.length;e+=1){let t=a[e],i=n.get(t);for(let e of Object.keys(t)){let s=Reflect.get(t,e);if(typeof s==`object`&&s){let i=o.get(s);if(i!==void 0)s=i;else if(c(s)){let i=n.has(s);s=r(s),i||a.push(Reflect.get(t,e))}}Object.defineProperty(i,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return i}function f(e,t){return Reflect.get(e,t)}function p(e){let t=a.get(e);return t===void 0&&(t={signals:null,keys:null,proxy:null},a.set(e,t)),t}function m(t,n){let r=t.signals;r===null&&(r=/* @__PURE__ */ new Map,t.signals=r);let i=r.get(n);if(i===void 0){let t=r.size;if(t>=256&&!(t&t-1))for(let[e,t]of r)(t.observers?.length??0)===0&&r.delete(e);i=new e(0,!1),r.set(n,i)}return i}function h(e,r){n()&&t(m(e,r))}function g(r){n()&&(r.keys===null&&(r.keys=new e(0,!1)),t(r.keys))}function _(e){e!=null&&r(e)}function v(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===e}function y(e,t){let n=e.signals;if(n!==null)for(let[e,r]of n)v(e)&&Number(e)>=t&&_(r)}function b(e,t,n){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);n=d(n);let r=Array.isArray(e),i=Object.hasOwn(e,t);if(i&&Object.is(f(e,t),n))return!1;let o=r?e.length:0;if(!Reflect.set(e,t,n))throw TypeError(`SHADOW_STORE_PROP_READ_ONLY`);let c=a.get(e);if(c===void 0)return!0;if(_(c.signals?.get(t)),i||_(c.keys),r){let t=e.length;t!==o&&(_(c.signals?.get(`length`)),_(c.keys),t<o&&y(c,t))}return!0}function x(e,t){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_DELETE`);if(!Object.hasOwn(e,t))return!0;if(!Reflect.deleteProperty(e,t))throw TypeError(`SHADOW_STORE_DELETE`);let n=a.get(e);return n===void 0||(_(n.signals?.get(t)),_(n.keys)),!0}export{a as NODES,o as RAW,x as deleteRaw,s as isReservedKey,c as isWrappable,p as nodeOf,f as readRaw,g as trackKeys,h as trackProperty,d as unwrapDeep,l as unwrapValue,b as writeRaw};
|
|
2
2
|
//# sourceMappingURL=nodes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodes.js","names":["notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","size","other","createSignalNode","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import {\n createSignalNode,\n isTracking,\n notify as notifySource,\n type SignalNode,\n track,\n} from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = createSignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = createSignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/** Deletes one own property of a raw object and notifies its signal and the key set. */\nexport function deleteRaw(target: object, key: string): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":"A,+HASA,MAAMC,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAoB/EC,kBAAoC,IAAI,QAGxCC,kBAA+B,IAAI,QAGhD,SAAgBC,EAAc,EAAsB,CAClD,OAAOH,EAAc,IAAII,CAAG,CAC9B,CAGA,SAAgBC,EAAY,EAAiC,CAC3D,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,MAAM,QAAQA,CAAK,EAAG,MAAO,GACjC,GAAIA,IAAU,OAAO,UAAW,MAAO,GACvC,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAGA,SAAgBC,EAAY,EAAyB,CAEnD,OADI,OAAOF,GAAU,WAAYA,EAAuBA,EACjDJ,EAAI,IAAII,CAAK,GAAKA,CAC3B,CAGA,SAASG,EAAc,EAAuB,CAC5C,IAAMC,kBAAO,IAAI,IAAY,CAACC,CAAI,CAAC,EAC7BC,EAAkB,CAACD,CAAI,EAC7B,KAAOC,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAYD,EAAM,IAAI,EAC5B,IAAK,IAAMR,KAAO,OAAO,KAAKS,CAAS,EAAG,CACxC,IAAMC,EAAkB,QAAQ,IAAID,EAAWT,CAAG,EAClD,GAAI,OAAOU,GAAW,UAAYA,EAClC,IAAIZ,EAAI,IAAIY,CAAM,EAAG,MAAO,GACxBT,EAAYS,C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AK,SAAS,IAAI1B,CAAG,CAAC,EAC7BqC,EAAOX,EAAK,IAAI,GACT,EACT,C"}
|
|
1
|
+
{"version":3,"file":"nodes.js","names":["SignalNode","notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","size","other","Signal","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import { isTracking, notify as notifySource, SignalNode, track } from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = new SignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = new SignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/** Deletes one own property of a raw object and notifies its signal and the key set. */\nexport function deleteRaw(target: object, key: string): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n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5BuB,EAAM,OAAO,OAAOvB,EAAQrB,CAAG,EACrC,GAAI4C,GAAO,OAAO,GAAGpB,EAAQH,EAAQrB,CAAG,EAAGE,CAAK,EAAG,MAAO,GAC1D,IAAM2C,EAASF,EAAStB,EAAqB,OAAS,EACtD,GAAI,CAAC,QAAQ,IAAIA,EAAQrB,EAAKE,CAAK,EACjC,MAAU,UAGJ,6BACN,EAEF,IAAMwB,EAAO7B,EAAM,IAAIwB,CAAM,EAC7B,GAAIK,IAAS,IAAA,GAAW,MAAO,GAG/B,GAFAW,EAAOX,EAAK,SAAS,IAAI1B,CAAG,CAAC,EACxB4C,GAAKP,EAAOX,EAAK,IAAI,EACtBiB,EAAO,CACT,IAAMG,EAASzB,EAAqB,OAChCyB,IAAUD,IACZR,EAAOX,EAAK,SAAS,IAAI,QAAQ,CAAC,EAClCW,EAAOX,EAAK,IAAI,EACZoB,EAAQD,GAAQL,EAAkBd,EAAMoB,CAAK,EAErD,CACA,MAAO,EACT,CAGA,SAAgBC,EAAU,EAAgB,EAAsB,CAC9D,GAAIhD,EAAcC,CAAG,EACnB,MAAU,UAGJ,8BACN,EAEF,GAAI,CAAC,OAAO,OAAOqB,EAAQrB,CAAG,EAAG,MAAO,GACxC,GAAI,CAAC,QAAQ,eAAeqB,EAAQrB,CAAG,EACrC,MAAU,UACuD,qBACjE,EAEF,IAAM0B,EAAO7B,EAAM,IAAIwB,CAAM,EAI7B,OAHIK,IAAS,IAAA,KACbW,EAAOX,EAAK,SAAS,IAAI1B,CAAG,CAAC,EAC7BqC,EAAOX,EAAK,IAAI,GACT,EACT,C"}
|
package/dist/server/action.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";import{currentOwner as i}from"./extend/index.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=i(),[l,u]=r(s),[d,f]=r(!1),p=0;return[l,(...r)=>{p+=1;let i=p,s=n(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p
|
|
1
|
+
import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";import{currentOwner as i}from"./extend/index.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=i(),[l,u]=r(s),[d,f]=r(!1),p=0;return[l,(...r)=>{p+=1;let i=p,s=n(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p&&f(!1),c===null)throw t;try{e(t,c)}catch(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}},h;try{h=n(()=>o(s,...r))}catch(e){try{m(e)}catch(e){return Promise.reject(e)}return Promise.resolve()}return a(h)?(f(!0),Promise.resolve(h).then(d,m)):(d(h),Promise.resolve())},d]}export{o as useAction};
|
|
2
2
|
//# sourceMappingURL=action.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action.js","names":["isPromiseLike","value","useAction","owner","currentOwner","state","setState","useSignal","initialState","pending","setPending","latest","args","id","previous","untrack","commit","batch","fail","error","handleError","result","action"],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n if (id
|
|
1
|
+
{"version":3,"file":"action.js","names":["isPromiseLike","value","useAction","owner","currentOwner","state","setState","useSignal","initialState","pending","setPending","latest","args","id","previous","untrack","commit","batch","fail","error","handleError","uncaught","result","action","thrown"],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n // A stale dispatch changes no state, but its error is still the owner's to hear.\n if (id === latest) setPending(false);\n if (owner === null) throw error;\n try {\n handleError(error, owner);\n } catch (uncaught) {\n // No handler took it: report it, as documented, instead of throwing out of dispatch.\n if (typeof reportError === \"function\") reportError(uncaught);\n else queueMicrotask(() => Promise.reject(uncaught));\n }\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n try {\n fail(error);\n } catch (thrown) {\n // Without an owner the returned promise carries the error.\n return Promise.reject(thrown);\n }\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":"A,oOAIA,SAASA,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiCA,SAAgBC,EACd,EACA,EAC2F,CAC3F,IAAMC,EAAQC,EAAa,EACrB,CAACC,EAAOC,GAAYC,EAAaC,CAAY,EAC7C,CAACC,EAASC,GAAcH,EAAU,EAAK,EACzCI,EAAS,EA4Cb,MAAO,CAACN,GA1CU,GAAGO,IAA2B,CAC9C,GAAU,EACV,IAAMC,EAAKF,EACLG,EAAWC,EAAQV,CAAK,EACxBW,EAAU,GAAmB,CAC7BH,IAAOF,GACXM,MAAY,CACVX,MAAeL,CAAK,EACpBS,EAAW,EAAK,CAClB,CAAC,CACH,EACMQ,EAAQ,GAAyB,CAGrC,GADIL,IAAOF,GAAQD,EAAW,EAAK,EAC/BP,IAAU,KAAM,MAAMgB,EAC1B,GAAI,CACFC,EAAYD,EAAOhB,CAAK,CAC1B,OAASkB,EAAU,CAEb,OAAO,aAAgB,WAAY,YAAYA,CAAQ,EACtD,mBAAqB,QAAQ,OAAOA,CAAQ,CAAC,CACpD,CACF,EACIC,EACJ,GAAI,CACF,EAASP,MAAcQ,EAAOT,EAAU,GAAGF,CAAI,CAAC,CAClD,OAASO,EAAO,CACd,GAAI,CACFD,EAAKC,CAAK,CACZ,OAASK,EAAQ,CAEf,OAAO,QAAQ,OAAOA,CAAM,CAC9B,CACA,OAAO,QAAQ,QAAQ,CACzB,CAMA,OALKxB,EAAiBsB,CAAM,GAI5BZ,EAAW,EAAI,EACR,QAAQ,QAAQY,CAAM,CAAC,CAAC,KAAKN,EAAQE,CAAI,IAJ9CF,EAAOM,CAAM,EACN,QAAQ,QAAQ,EAI3B,EACyBb,CAAO,CAClC,C"}
|