@shadow-js/core 1.0.4 → 1.0.5
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 +8 -0
- package/dist/dev/action.js +1 -1
- package/dist/dev/cache.js +1 -1
- package/dist/dev/context.js +2 -2
- package/dist/dev/effect.js +1 -1
- package/dist/dev/extend/index.d.ts +4 -4
- package/dist/dev/extend/index.js +5 -5
- package/dist/dev/external-store.js +2 -2
- package/dist/dev/index.d.ts +6 -6
- package/dist/dev/index.js +9 -9
- package/dist/dev/internal/concurrency.js +5 -5
- package/dist/dev/internal/dispose.js +1 -1
- package/dist/dev/internal/graph.d.ts +1 -1
- package/dist/dev/internal/graph.js +5 -1
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/scheduler.js +2 -2
- package/dist/dev/internal/state.d.ts +1 -1
- package/dist/dev/list.js +2 -2
- package/dist/dev/optimistic.js +1 -1
- package/dist/dev/ownership.js +6 -1
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.js +1 -1
- package/dist/dev/reaction.js +2 -2
- package/dist/dev/resource.js +4 -4
- package/dist/dev/selector.js +1 -1
- package/dist/dev/signal.js +1 -1
- package/dist/dev/store/index.d.ts +1 -1
- package/dist/dev/store/nodes.js +7 -3
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/reconcile.js +1 -1
- package/dist/dev/store/reconcile.js.map +1 -1
- package/dist/dev/store/use-store.js +9 -5
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/transitions.js +2 -2
- package/dist/prod/action.js +1 -1
- package/dist/prod/cache.js +1 -1
- package/dist/prod/context.js +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/extend/index.js +1 -1
- package/dist/prod/external-store.js +1 -1
- package/dist/prod/index.js +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/dispose.js +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/list.js +1 -1
- package/dist/prod/optimistic.js +1 -1
- package/dist/prod/ownership.js +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js +1 -1
- package/dist/prod/reaction.js +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/selector.js +1 -1
- package/dist/prod/signal.js +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/reconcile.js +1 -1
- package/dist/prod/store/reconcile.js.map +1 -1
- package/dist/prod/store/use-store.js +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/transitions.js +1 -1
- package/dist/server/action.js +1 -1
- package/dist/server/cache.js +1 -1
- package/dist/server/context.js +1 -1
- package/dist/server/extend/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/dispose.js +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/list.js +1 -1
- package/dist/server/optimistic.js +1 -1
- package/dist/server/ownership.js +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js +1 -1
- package/dist/server/reaction.js +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/selector.js +1 -1
- package/dist/server/signal.js +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/reconcile.js +1 -1
- package/dist/server/store/reconcile.js.map +1 -1
- package/dist/server/store/use-store.js +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/transitions.js +1 -1
- package/dist/server-dev/action.js +1 -1
- package/dist/server-dev/cache.js +1 -1
- package/dist/server-dev/context.js +1 -1
- package/dist/server-dev/extend/index.js +5 -5
- package/dist/server-dev/index.js +9 -9
- package/dist/server-dev/internal/concurrency.js +5 -5
- package/dist/server-dev/internal/dispose.js +1 -1
- package/dist/server-dev/internal/graph.js +5 -1
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +2 -2
- package/dist/server-dev/list.js +2 -2
- package/dist/server-dev/optimistic.js +1 -1
- package/dist/server-dev/ownership.js +6 -1
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +1 -1
- package/dist/server-dev/reaction.js +2 -2
- package/dist/server-dev/resource.js +3 -3
- package/dist/server-dev/selector.js +1 -1
- package/dist/server-dev/signal.js +1 -1
- package/dist/server-dev/store/nodes.js +7 -3
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/reconcile.js +1 -1
- package/dist/server-dev/store/reconcile.js.map +1 -1
- package/dist/server-dev/store/use-store.js +9 -5
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/transitions.js +1 -1
- package/package.json +2 -2
package/dist/dev/selector.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { track } from "./internal/graph.js";
|
|
2
|
-
import { onCleanup, untrack } from "./ownership.js";
|
|
3
2
|
import { useRenderEffect } from "./effect.js";
|
|
4
3
|
import { isTracking, notify } from "./extend/index.js";
|
|
4
|
+
import { onCleanup, untrack } from "./ownership.js";
|
|
5
5
|
// src/selector.ts
|
|
6
6
|
/**
|
|
7
7
|
* The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the
|
package/dist/dev/signal.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Signal, readSignal } from "./internal/graph.js";
|
|
2
|
-
import { untrack } from "./ownership.js";
|
|
3
2
|
import { writeSignal } from "./extend/index.js";
|
|
3
|
+
import { untrack } from "./ownership.js";
|
|
4
4
|
// src/signal.ts
|
|
5
5
|
/**
|
|
6
6
|
* Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Mutable, Reconciler, SetStore, Store, StoreResult } from "./types.js";
|
|
2
1
|
import { snapshot, unwrap } from "./read.js";
|
|
3
2
|
import { ReconcileOptions, produce, reconcile } from "./reconcile.js";
|
|
3
|
+
import { Mutable, Reconciler, SetStore, Store, StoreResult } from "./types.js";
|
|
4
4
|
import { StoreOptions, useStore } from "./use-store.js";
|
|
5
5
|
export { type Mutable, type ReconcileOptions, type Reconciler, type SetStore, type Store, type StoreOptions, type StoreResult, produce, reconcile, snapshot, unwrap, useStore };
|
package/dist/dev/store/nodes.js
CHANGED
|
@@ -181,9 +181,13 @@ function writeRaw(target, key, value) {
|
|
|
181
181
|
}
|
|
182
182
|
return true;
|
|
183
183
|
}
|
|
184
|
-
/**
|
|
185
|
-
|
|
186
|
-
|
|
184
|
+
/**
|
|
185
|
+
* Deletes one own property of a raw object and notifies its signal and the key set. A reserved key is
|
|
186
|
+
* refused unless `cleanup` is set: removing an own data property named `__proto__` (it arrived in parsed
|
|
187
|
+
* JSON) cannot reach a prototype, and `reconcile` must be able to clear it like any other stale key.
|
|
188
|
+
*/
|
|
189
|
+
function deleteRaw(target, key, cleanup = false) {
|
|
190
|
+
if (!cleanup && isReservedKey(key)) throw new TypeError(`ShadowStore: "${key}" cannot be deleted; it is a reserved key`);
|
|
187
191
|
if (!Object.hasOwn(target, key)) return true;
|
|
188
192
|
if (!Reflect.deleteProperty(target, key)) throw new TypeError(`ShadowStore: property "${key}" cannot be deleted`);
|
|
189
193
|
const node = NODES.get(target);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodes.js","names":["SignalNode"],"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"],"mappings":";;;;AAGA,MAAM,gCAAqC,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAoB5F,MAAa,wBAAoC,IAAI,QAAQ;;AAG7D,MAAa,sBAA+B,IAAI,QAAQ;;AAGxD,SAAgB,cAAc,KAAsB;CAClD,OAAO,cAAc,IAAI,GAAG;AAC9B;;AAGA,SAAgB,YAAY,OAAiC;CAC3D,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,IAAI,UAAU,OAAO,WAAW,OAAO;CACvC,MAAM,YAAqB,OAAO,eAAe,KAAK;CACtD,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;AAGA,SAAgB,YAAY,OAAyB;CACnD,IAAI,OAAO,UAA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K,OAAO,KAAK,IAAI;CAC1B,IAAI,OAAO;EACT,MAAM,QAAS,OAAqB;EACpC,IAAI,UAAU,QAAQ;GACpB,OAAO,KAAK,SAAS,IAAI,QAAQ,CAAC;GAClC,OAAO,KAAK,IAAI;GAChB,IAAI,QAAQ,QAAQ,kBAAkB,MAAM,KAAK;EACnD;CACF;CACA,OAAO;AACT;;AAGA,SAAgB,UAAU,QAAgB,KAAsB;CAC9D,IAAI,cAAc,GAAG,GACnB,MAAM,IAAI,UAEJ,iBAAiB,IAAI,0CAE3B;CAEF,IAAI,CAAC,OAAO,OAAO,QAAQ,GAAG,GAAG,OAAO;CACxC,IAAI,CAAC,QAAQ,eAAe,QAAQ,GAAG,GACrC,MAAM,IAAI,UACE,0BAA0B,IAAI,oBAC1C;CAEF,MAAM,OAAO,MAAM,IAAI,MAAM;CAC7B,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,OAAO,KAAK,SAAS,IAAI,GAAG,CAAC;CAC7B,OAAO,KAAK,IAAI;CAChB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"nodes.js","names":["SignalNode"],"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/**\n * Deletes one own property of a raw object and notifies its signal and the key set. A reserved key is\n * refused unless `cleanup` is set: removing an own data property named `__proto__` (it arrived in parsed\n * JSON) cannot reach a prototype, and `reconcile` must be able to clear it like any other stale key.\n */\nexport function deleteRaw(target: object, key: string, cleanup = false): boolean {\n if (!cleanup && 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":";;;;AAGA,MAAM,gCAAqC,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAoB5F,MAAa,wBAAoC,IAAI,QAAQ;;AAG7D,MAAa,sBAA+B,IAAI,QAAQ;;AAGxD,SAAgB,cAAc,KAAsB;CAClD,OAAO,cAAc,IAAI,GAAG;AAC9B;;AAGA,SAAgB,YAAY,OAAiC;CAC3D,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,IAAI,UAAU,OAAO,WAAW,OAAO;CACvC,MAAM,YAAqB,OAAO,eAAe,KAAK;CACtD,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;AAGA,SAAgB,YAAY,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,IAAI,IAAI,KAAK,KAAK;AAC3B;;AAGA,SAAS,cAAc,MAAuB;CAC5C,MAAM,uBAAO,IAAI,IAAY,CAAC,IAAI,CAAC;CACnC,MAAM,QAAkB,CAAC,IAAI;CAC7B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,YAAY,MAAM,IAAI;EAC5B,KAAK,MAAM,OAAO,OAAO,KAAK,SAAS,GAAG;GACx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I,CAAC,WAAW,cAAc,GAAG,GAC/B,MAAM,IAAI,UAEJ,iBAAiB,IAAI,0CAE3B;CAEF,IAAI,CAAC,OAAO,OAAO,QAAQ,GAAG,GAAG,OAAO;CACxC,IAAI,CAAC,QAAQ,eAAe,QAAQ,GAAG,GACrC,MAAM,IAAI,UACE,0BAA0B,IAAI,oBAC1C;CAEF,MAAM,OAAO,MAAM,IAAI,MAAM;CAC7B,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,OAAO,KAAK,SAAS,IAAI,GAAG,CAAC;CAC7B,OAAO,KAAK,IAAI;CAChB,OAAO;AACT"}
|
|
@@ -111,7 +111,7 @@ function mergeObject(target, source, spec, enqueue) {
|
|
|
111
111
|
writeRaw(target, key, value);
|
|
112
112
|
}
|
|
113
113
|
if (spec.merge) return;
|
|
114
|
-
for (const key of Object.keys(target)) if (!Object.hasOwn(source, key)) deleteRaw(target, key);
|
|
114
|
+
for (const key of Object.keys(target)) if (!Object.hasOwn(source, key)) deleteRaw(target, key, true);
|
|
115
115
|
}
|
|
116
116
|
function mergeArray(target, source, spec, enqueue) {
|
|
117
117
|
const list = target;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":";;;AAuCA,MAAM,wBAAwC,IAAI,QAAQ;;;;;;;;;AAU1D,SAAgB,OAAO,QAA2C;CAChE,OAAO,MAAM,IAAI,MAAM;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,UAAa,MAAS,SAA2C;CAC/E,MAAM,OAAsB;EAC1B;EACA,KAAK,SAAS,OAAO;EACrB,OAAO,SAAS,UAAU;CAC5B;CACA,MAAM,mBAAkC;EACtC,MAAM,IAAI,UAEJ,gEAEN;CACF;CACA,MAAM,IAAI,YAAY,IAAI;CAC1B,OAAO;AACT;;AAQA,SAAS,WAAW,MAAe,KAAqD;CACtF,IAAI,CAAC,YAAY,IAAI,GAAG,OAAO,KAAA;CAC/B,IAAI,OAAO,QAAQ,YAAY,OAAO,IAAI,IAAI;CAC9C,OAAO,OAAO,OAAO,MAAM,GAAG,IAAI,QAAQ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SAAoB,CAAC;CAC3B,KAAK,IAAI,WAAW,GAAG,WAAW,SAAS,QAAQ,YAAY,GAAG;EAChE,MAAM,OAAO,YAAY,SAAS,SAAS;EAC3C,MAAM,QAAQ,QAAQ,aAAa;EACnC,IAAI,UAAU,IAAI;GAChB,OAAO,KAAK,IAAI;GAChB;EACF;EACA,MAAM,WAAW,SAAS;EAC1B,IAAI,YAAY,QAAQ,KAAK,YAAY,IAAI,KAAK,SAAS,UAAU,IAAI,GAAG;GAC1E,IAAI,aAAa,MAAM,QAAQ,UAAU,IAAI;GAC7C,OAAO,KAAK,QAAQ;EACtB,OACE,OAAO,KAAK,IAAI;CAEpB;CACA,IAAI,KAAK,OACF;OAAA,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GACpD,IAAI,KAAK,WAAW,MAAM,OAAO,KAAK,SAAS,MAAM;CAAA;CAIzD,KAAK,IAAI,WAAW,GAAG,WAAW,OAAO,QAAQ,YAAY,GAC3D,SAAS,QAAQ,OAAO,QAAQ,GAAG,OAAO,SAAS;CAErD,IAAI,KAAK,SAAS,OAAO,QAAQ,SAAS,QAAQ,UAAU,OAAO,MAAM;AAC3E;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,QAAW,QAAgD;CACzE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key, true);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":";;;AAuCA,MAAM,wBAAwC,IAAI,QAAQ;;;;;;;;;AAU1D,SAAgB,OAAO,QAA2C;CAChE,OAAO,MAAM,IAAI,MAAM;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,UAAa,MAAS,SAA2C;CAC/E,MAAM,OAAsB;EAC1B;EACA,KAAK,SAAS,OAAO;EACrB,OAAO,SAAS,UAAU;CAC5B;CACA,MAAM,mBAAkC;EACtC,MAAM,IAAI,UAEJ,gEAEN;CACF;CACA,MAAM,IAAI,YAAY,IAAI;CAC1B,OAAO;AACT;;AAQA,SAAS,WAAW,MAAe,KAAqD;CACtF,IAAI,CAAC,YAAY,IAAI,GAAG,OAAO,KAAA;CAC/B,IAAI,OAAO,QAAQ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;EAEvC,IAAI,UAAU,IAAI,KAAK,SAAS;EAChC,QAAQ,KAAK,KAAK;CACpB;CAEA,MAAM,SAAoB,CAAC;CAC3B,KAAK,IAAI,WAAW,GAAG,WAAW,SAAS,QAAQ,YAAY,GAAG;EAChE,MAAM,OAAO,YAAY,SAAS,SAAS;EAC3C,MAAM,QAAQ,QAAQ,aAAa;EACnC,IAAI,UAAU,IAAI;GAChB,OAAO,KAAK,IAAI;GAChB;EACF;EACA,MAAM,WAAW,SAAS;EAC1B,IAAI,YAAY,QAAQ,KAAK,YAAY,IAAI,KAAK,SAAS,UAAU,IAAI,GAAG;GAC1E,IAAI,aAAa,MAAM,QAAQ,UAAU,IAAI;GAC7C,OAAO,KAAK,QAAQ;EACtB,OACE,OAAO,KAAK,IAAI;CAEpB;CACA,IAAI,KAAK,OACF;OAAA,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GACpD,IAAI,KAAK,WAAW,MAAM,OAAO,KAAK,SAAS,MAAM;CAAA;CAIzD,KAAK,IAAI,WAAW,GAAG,WAAW,OAAO,QAAQ,YAAY,GAC3D,SAAS,QAAQ,OAAO,QAAQ,GAAG,OAAO,SAAS;CAErD,IAAI,KAAK,SAAS,OAAO,QAAQ,SAAS,QAAQ,UAAU,OAAO,MAAM;AAC3E;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,QAAW,QAAgD;CACzE,OAAO;AACT"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { DEVTOOLS_EVENT, report } from "../internal/devtools.js";
|
|
2
2
|
import { ShadowError } from "../internal/diagnostics.js";
|
|
3
3
|
import { group } from "../internal/scheduler.js";
|
|
4
|
+
import { currentOwner, isComputingMemo } from "../extend/index.js";
|
|
4
5
|
import { untrack } from "../ownership.js";
|
|
5
6
|
import { useSignal } from "../signal.js";
|
|
6
|
-
import { currentOwner, isComputingMemo } from "../extend/index.js";
|
|
7
7
|
import { isReservedKey, isWrappable, unwrapValue } from "./nodes.js";
|
|
8
|
+
import { Transaction, draftOf, readProxyOf } from "./proxies.js";
|
|
8
9
|
import { snapshot } from "./read.js";
|
|
9
10
|
import { applyReconcile, reconcile, specOf } from "./reconcile.js";
|
|
10
|
-
import { Transaction, draftOf, readProxyOf } from "./proxies.js";
|
|
11
11
|
// src/store/use-store.ts
|
|
12
12
|
function isPlainObject(value) {
|
|
13
13
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
@@ -26,6 +26,10 @@ function rangeKeys(range, length) {
|
|
|
26
26
|
}
|
|
27
27
|
return keys;
|
|
28
28
|
}
|
|
29
|
+
/** Appends `items` to `keys` one by one: a spread into `push` overflows the call stack for a long list. */
|
|
30
|
+
function appendKeys(keys, items) {
|
|
31
|
+
for (const item of items) keys.push(item);
|
|
32
|
+
}
|
|
29
33
|
/** The keys one path step addresses on `target` (a draft). */
|
|
30
34
|
function stepKeys(target, step, label) {
|
|
31
35
|
const keys = [];
|
|
@@ -34,11 +38,11 @@ function stepKeys(target, step, label) {
|
|
|
34
38
|
else if (typeof step === "function") {
|
|
35
39
|
const filter = step;
|
|
36
40
|
for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);
|
|
37
|
-
} else if (Array.isArray(step)) keys
|
|
38
|
-
else if (typeof step === "object" && step !== null) keys
|
|
41
|
+
} else if (Array.isArray(step)) appendKeys(keys, step);
|
|
42
|
+
else if (typeof step === "object" && step !== null) appendKeys(keys, rangeKeys(step, target.length));
|
|
39
43
|
else throw new TypeError(`ShadowStore${label}: bad path step for an array`);
|
|
40
44
|
} else if (typeof step === "string" || typeof step === "number") keys.push(step);
|
|
41
|
-
else if (Array.isArray(step)) keys
|
|
45
|
+
else if (Array.isArray(step)) appendKeys(keys, step);
|
|
42
46
|
else throw new TypeError(`ShadowStore${label}: bad path step for an object`);
|
|
43
47
|
for (const key of keys) if (typeof key === "string" && isReservedKey(key)) throw new TypeError(`ShadowStore${label}: the key "${key}" cannot be used in a path`);
|
|
44
48
|
return keys;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-store.js","names":[],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * A property read in a tracked context gets a small notifier. Reading many transient keys\n * (`store.byId[id]` with churning ids) does not grow it for the life of the store: once an object\n * has collected a few hundred notifiers, the ones nothing observes any more are dropped, and a key\n * read again gets a fresh one that reflects the current value.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(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sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** Appends `items` to `keys` one by one: a spread into `push` overflows the call stack for a long list. */\nfunction appendKeys(keys: Array<string | number>, items: ReadonlyArray<string | number>): void {\n for (const item of items) keys.push(item);\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) appendKeys(keys, step as number[]);\n else if (typeof step === \"object\" && step !== null)\n appendKeys(keys, rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n appendKeys(keys, step as Array<string | number>);\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * A property read in a tracked context gets a small notifier. Reading many transient keys\n * (`store.byId[id]` with churning ids) does not grow it for the life of the store: once an object\n * has collected a few hundred notifiers, the ones nothing observes any more are dropped, and a key\n * read again gets a fresh one that reflects the current value.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":";;;;;;;;;;;AA4BA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,UAAU,OAAoD,QAA0B;CAC/F,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,KAAK,MAAM,MAAM,SAAS;CAChC,MAAM,KAAK,MAAM,MAAM;CACvB,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,OAAO,GACjC,MAAM,IAAI,UACE,4CACZ;CACF,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI;EACtD,KAAK,KAAK,CAAC;EACX,IAAI,KAAK,SAAS,SAAS,GAAG;CAChC;CACA,OAAO;AACT;;AAGA,SAAS,WAAW,MAA8B,OAA6C;CAC7F,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,IAAI;AAC1C;;AAGA,SAAS,SAAS,QAAgB,MAAe,OAAuC;CACtF,MAAM,OAA+B,CAAC;CACtC,IAAI,MAAM,QAAQ,MAAM,GAAG;EACzB,IAAI,OAAO,SAAS,UAAU,KAAK,KAAK,IAAI;OACvC,IAAI,OAAO,SAAS,YAAY;GACnC,MAAM,SAAS;GACf,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,GAAG,IAAI,OAAO,OAAO,IAAI,CAAC,GAAG,KAAK,KAAK,CAAC;EAClF,OAAO,IAAI,MAAM,QAAQ,IAAI,GAAG,WAAW,MAAM,IAAgB;OAC5D,IAAI,OAAO,SAAS,YAAY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AAS,SAAS,OAAyB;CACzC,MAAM,MAAM,YAAY,KAAK;CAC7B,OAAO,YAAY,GAAG,IAAI,YAAY,GAAG,IAAI;AAC/C"}
|
package/dist/dev/transitions.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { createComputation } from "./extend/index.js";
|
|
1
2
|
import { untrack } from "./ownership.js";
|
|
2
|
-
import { useSignal } from "./signal.js";
|
|
3
3
|
import { registerTransitionLane, startTransition } from "./internal/concurrency.js";
|
|
4
|
-
import {
|
|
4
|
+
import { useSignal } from "./signal.js";
|
|
5
5
|
// src/transitions.ts
|
|
6
6
|
/**
|
|
7
7
|
* Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:
|
package/dist/prod/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{
|
|
1
|
+
import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{currentOwner as n}from"./extend/index.js";import{untrack as r}from"./ownership.js";import{useSignal as i}from"./signal.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=n(),[l,u]=i(s),[d,f]=i(!1),p=0;return[l,(...n)=>{p+=1;let i=p,s=r(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=r(()=>o(s,...n))}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
|
package/dist/prod/cache.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{currentOwner as e}from"./extend/index.js";import{untrack as t}from"./ownership.js";function n(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0}function r(e){let t=e;for(;t!==null&&t.parent!==null;)t=t.parent;return t}function i(i,a){let o=a?.limit??100;if(!Number.isInteger(o)||o<1)throw RangeError(`SHADOW_CACHE_LIMIT`);let s=/* @__PURE__ */ new WeakMap;return(...a)=>{let c=r(e());if(c===null)return t(()=>i(...a));let l=s.get(c);l===void 0&&(l=[],s.set(c,l));for(let e of l)if(n(e.args,a))return e.value;let u=t(()=>i(...a));return l.push({args:a,value:u}),l.length>o&&l.shift(),u}}export{i as cache};
|
|
2
2
|
//# sourceMappingURL=cache.js.map
|
package/dist/prod/context.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t}from"./internal/owner.js";import{
|
|
1
|
+
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t}from"./internal/owner.js";import{useRenderEffect as n}from"./effect.js";import{currentOwner as r}from"./extend/index.js";import{runWithOwner as i}from"./ownership.js";import{useSignal as a}from"./signal.js";function o(e,o){let s=Symbol(o?.name??`context`),c=e=>{let o=new t(r()),c=o.context,l=Object.create(c);return l[s]=e.value,o.context=l,i(o,()=>{let[t,r]=a(void 0,{equals:!1});return n(()=>e.children,e=>{r(()=>e)}),t})};return Object.assign(c,{id:s,defaultValue:e,Provider:c})}function s(e,n,a){let o=new t(r()),s=Object.create(o.context);return s[e.id]=n,o.context=s,i(o,a)}function c(t){let n=r()?.context;if(n!=null&&t.id in n)return n[t.id];if(t.defaultValue===void 0)throw new e(`CONTEXT_MISSING`);return t.defaultValue}export{o as createContext,s as runWithContext,c as useContext};
|
|
2
2
|
//# sourceMappingURL=context.js.map
|
package/dist/prod/effect.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./internal/diagnostics.js";import{
|
|
1
|
+
import"./internal/diagnostics.js";import{createComputation as e,currentOwner as t}from"./extend/index.js";import{untrack as n}from"./ownership.js";function r(n,r,i,a,o){let s=i?null:t()?.gate??null;if(s!==null){let e=!1,t=!1,i=a,o=n,c=r;a=!1,n=n=>(t=!e&&s(),e||=!t,t?void 0:o(n)),c!==null&&(r=(e,n)=>{if(!t){if(!i)return c(e,n);i=!1}})}e({kind:`effect`,fn:n,render:i,defer:a,apply:r??void 0,name:o})}function i(e,t,n){typeof t==`function`?r(e,t,!1,n?.defer===!0,n?.name):r(e,null,!1,!1,t?.name)}function a(e,t){r(e,t??null,!0,!1,void 0)}function o(e){r(()=>n(e),null,!1,!1,`onMount`)}export{o as onMount,i as useEffect,a as useRenderEffect};
|
|
2
2
|
//# sourceMappingURL=effect.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{DEVTOOLS_EVENT as e,report as t}from"../internal/devtools.js";import{
|
|
1
|
+
import{DEVTOOLS_EVENT as e,report as t}from"../internal/devtools.js";import{ShadowError as n,resetWarningDedupe as r,setWarningListener as i,warn as a}from"../internal/diagnostics.js";import{Computation as o,Signal as s,hasObservers as c,isEqual as l,markObservers as u,observersOf as d,readMemo as f,readSignal as p,recompute as m,sourcesOf as h,track as g,updateIfNecessary as _}from"../internal/graph.js";import{Owner as v,addCleanup as y,handleError as b}from"../internal/owner.js";import{enqueue as x}from"../internal/queue.js";import{batch as S,flush as C,flushSync as w,group as T,schedule as E}from"../internal/scheduler.js";import{rt as D}from"../internal/state.js";import{runWithContext as O}from"../context.js";import{beginHold as k,createTransitionHold as A,endHold as j,holdReader as M,inTransition as ee,pauseOwner as N,registerTransitionLane as P,resumeOwner as F,startTransition as I,transitionHooks as L,wakeSuspended as R}from"../internal/concurrency.js";import{disposeTree as z}from"../internal/dispose.js";import{isHydrating as B,withHydration as V}from"../internal/hydration-flag.js";import{MESSAGES as H,formatMessage as U}from"../internal/messages.js";import{SUSPENSION as W,isSuspension as G}from"../internal/suspension.js";function K(){return D.owner}function q(){return D.listener}function J(){return D.listener!==null}function Y(){return D.disposing===0&&D.running!==null&&D.running.kind===1&&!(D.running.flags&256)}function X(e,t){let n=D.owner,r=D.listener;try{let n=e.owner;n!==void 0&&(D.owner=n);let r=e.listener;return r!==void 0&&(D.listener=r),t()}finally{D.owner=n,D.listener=r}}function Z(e,t,n){return new s(e,t,n)}function Q(e,t,n){let r=e.equals;return r!==!1&&l(r,e.value,t)?!1:(e.value=t,$(e),!0)}function $(e){c(e)&&(u(e),E())}function te(e){let t=e.owner===void 0?D.owner:e.owner,n=e.kind===`memo`,r=new o(t,n?1:2,n?32|(e.allowWrites===!0?256:0):(e.render===!0?16:0)|(e.defer===!0?64:0)|(e.lane===!0?512:0),e.fn,n?e.equals??Object.is:!1,e.name);return n?(e.lazy!==!0&&_(r),r):(r.apply=e.apply??null,e.render===!0?m(r):(x(r),E()),r)}function ne(e){return f(e)}function re(e){_(e)}function ie(e){return new v(e===void 0?D.owner:e)}export{o as ComputationNode,e as DEVTOOLS_EVENT,H as MESSAGES,v as Owner,W as SUSPENSION,n as ShadowError,s as SignalNode,y as addCleanup,S as batch,k as beginHold,te as createComputation,ie as createOwner,Z as createSignalNode,A as createTransitionHold,q as currentListener,K as currentOwner,t as devtoolsReport,z as disposeOwner,j as endHold,C as flush,w as flushSync,U as formatMessage,T as group,b as handleError,M as holdReader,ee as inTransition,Y as isComputingMemo,B as isHydrating,G as isSuspension,J as isTracking,u as markObservers,$ as notify,d as observersOf,N as pauseOwner,ne as readComputation,p as readSignal,re as refresh,P as registerTransitionLane,r as resetWarningDedupe,F as resumeOwner,X as runInScope,O as runWithContext,E as schedule,i as setWarningListener,h as sourcesOf,I as startTransition,g as track,L as transitionHooks,R as wakeSuspended,a as warn,V as withHydration,Q as writeSignal};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useEffect as e}from"./effect.js";import{isHydrating as t}from"./internal/hydration-flag.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";function i(i,a,o){let s=t()&&o?.getServerSnapshot!==void 0?o.getServerSnapshot:a,[c,l]=r(n(s),{equals:o?.equals??Object.is,name:o?.name}),u=()=>{let e=n(a);l(()=>e)};return e(()=>{let e=n(()=>i(u));try{u()}catch(t){throw e(),t}return e}),c}export{i as useExternalStore};
|
|
2
2
|
//# sourceMappingURL=external-store.js.map
|
package/dist/prod/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useAction as e}from"./action.js";import{cache as t}from"./cache.js";import{createContext as n,useContext as r}from"./context.js";import{onMount as i,useEffect as a,useRenderEffect as o}from"./effect.js";import{isDev as s,isServer as c}from"./env.js";import{useEvent as l}from"./events.js";import{batch as u,flushSync as d}from"./internal/scheduler.js";import{startTransition as f}from"./internal/concurrency.js";import{useExternalStore as p}from"./external-store.js";import{indexArray as m,mapArray as h}from"./list.js";import{useMemo as g}from"./memo.js";import{useOptimistic as _}from"./optimistic.js";import{catchError as v,createRoot as y,getOwner as b,onCleanup as x,onError as S,runWithOwner as C,untrack as w,useId as T}from"./ownership.js";import{children as E,mergeProps as D,splitProps as O}from"./props.js";import{useReaction as k}from"./reaction.js";import{useReducer as A}from"./reducer.js";import{createRef as j,useImperativeHandle as M}from"./refs.js";import{useResource as N}from"./resource.js";import{useSelector as P}from"./selector.js";import{useSignal as F}from"./signal.js";import{produce as I,reconcile as L}from"./store/reconcile.js";import{snapshot as R,unwrap as z}from"./store/read.js";import{useStore as B}from"./store/use-store.js";import{ResourceCacheContext as V,SuspenseContext as H}from"./suspense.js";import{useDeferredValue as U,useTransition as W}from"./transitions.js";export{V as ResourceCacheContext,H as SuspenseContext,u as batch,t as cache,v as catchError,E as children,n as createContext,j as createRef,y as createRoot,d as flushSync,b as getOwner,m as indexArray,s as isDev,c as isServer,h as mapArray,D as mergeProps,x as onCleanup,S as onError,i as onMount,I as produce,L as reconcile,C as runWithOwner,R as snapshot,O as splitProps,f as startTransition,w as untrack,z as unwrap,e as useAction,r as useContext,U as useDeferredValue,a as useEffect,l as useEvent,p as useExternalStore,T as useId,M as useImperativeHandle,g as useMemo,_ as useOptimistic,k as useReaction,A as useReducer,o as useRenderEffect,N as useResource,P as useSelector,F as useSignal,B as useStore,W as useTransition};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{runWithContext as e}from"../context.js";import{SuspenseContext as t}from"../suspense.js";import{ShadowError as n}from"./diagnostics.js";import{disposeTree as r}from"./dispose.js";import{FLAG_PARKED as i,FLAG_TRANSITION as a}from"./flags.js";import{Computation as o,Signal as s,hasObservers as c,markObservers as l,readSignal as u}from"./graph.js";import{Owner as d,addCleanup as f,finishDisposal as p}from"./owner.js";import{clearQueues as m,hasPending as h,place as g,renderQueue as _,userQueue as v}from"./queue.js";import{byCreation as y,reportUncaught as b,runQueued as x,schedule as S}from"./scheduler.js";import{rt as C}from"./state.js";import{SUSPENSION as w,isSuspension as T}from"./suspension.js";function E(e,t){let n=[e];for(;n.length>0;){let e=n.pop();t(e);for(let t=e.lastChild;t!==null;t=t.prevSibling)n.push(t)}}function D(){let D=[],O=[],k=null,A=null,j=/* @__PURE__ */ new Set,M=0,N=!1,P=()=>D.length>0||O.length>0,F=()=>P()||M>0,I=(e,t)=>{let n=e.splice(0,t);n.sort(y);for(let e of n)e.flags&1024&&(e.flags&=~(2|a),e.flags&4||(e.pauses>0?e.flags|=i|a:x(e)));return n.length},L=()=>{if(F()||A===null)return;let e=A;k=A=null,e()},R=()=>{N||(N=!0,setTimeout(z,0))},z=()=>{if(N=!1,C.flushing){R();return}let e=C.inTransition;C.inTransition=!0,C.flushing=!0;let t=64,r=0;try{for(;t>0&&P();){if(r+=1,r>1e3){m(),C.uncaught.push(new n(`INFINITE_LOOP`));break}let e=D.length>0?D:O;t-=I(e,t)}}finally{C.inTransition=e,C.flushing=!1}let i=C.uncaught.splice(0,C.uncaught.length);for(let e of i)b(e);P()?R():L(),h()&&S()},B=e=>{let t=C.inTransition,n=C.listener;C.inTransition=!0,C.listener=null;try{e()}finally{C.inTransition=t,C.listener=n}k??=new Promise(e=>{A=e});let r=k;return L(),r},V=(e,t)=>{if(e.pauses>0){e.flags=t?e.flags|i|a:(e.flags|i)&~a;return}let n=!!(e.flags&16);e.flags=e.flags&~i|2|a,n?D.push(e):O.push(e),R()},H=e=>{e.flags&512||e.pauses>0||(e.flags&2048?g(e,!1):(e.flags&1026)==1026&&(e.flags&=~a,e.flags&16?_.push(e):v.push(e)))},U=()=>{for(let e of[D,O]){for(let t of e)t.flags&=~(2|a),t.state=0;e.length=0}},W=(e,t)=>{if(t!==w)return!1;if(!j.has(e)){let t=j.size;if(t>=64&&!(t&t-1))for(let e of j)e.disposed&&j.delete(e);j.add(e)}return!0},G=e=>{if(e.hold?.()===!0)throw w},K=()=>{M+=1},q=()=>{M>0&&--M,P()&&R(),L()},J=()=>{let e=Array.from(j);j.clear();let t=C.inTransition;C.inTransition=!0;try{for(let t of e)t.disposed||(t.state=2,t.kind===2?g(t,!0):l(t))}finally{C.inTransition=t}S()},Y=e=>{let t=[];E(e,e=>{e.pauses+=1,t.push(e)}),C.disposing+=1;try{for(let e=t.length-1;e>=0;--e){let n=t[e];n instanceof o&&n.kind===2&&!(n.flags&16)&&!n.disposed&&n.runCleanups()}}finally{p()}},X=n=>{let r=0,i=!1,a=!1,o={increment(){r+=1},decrement(){--r,r===0&&(i&&(i=!1,J(),q()),n())},hold(){return a=!0,i||(i=!0,K()),!0}};return{run:n=>e(t,o,n),count:()=>r,engaged:()=>a,drop:()=>{i&&(i=!1,q())}}};return{place:V,promote:H,clear:U,suspend:W,holdReader:G,startTransition:B,beginHold:K,endHold:q,wakeSuspended:J,pause:Y,resume:e=>{E(e,e=>{if(e.pauses>0&&--e.pauses,e instanceof o&&e.pauses===0&&!e.disposed){if(e.kind===2){if(e.flags&16&&!(e.flags&2048))return;e.state=2,g(e,!1)}else e.state!==0&&l(e)}}),S()},createHold:X,slotSwap:(e,t,n,i)=>{let a,o=new d(i),p=new s(0,!1,void 0),m=()=>{p.value+=1,c(p)&&(l(p),S())},h=e=>{e.owned.disposing=!0;try{e.hold?.drop(),e.dispose?.()}finally{e.owned.disposing=!1}},g=t=>{let n=e.live;e.live=t,n!==void 0&&h(n)},_=e=>{let n={index:e.index,value:e.when,disposing:!1},i=X(()=>{a!==void 0&&a.hold===i&&m()}),s=new d(o),c=C.owner,l=C.listener;C.owner=s,C.listener=null;let u;try{try{u=i.run(()=>t(e,n,!0))}catch(e){if(!T(e))throw e}let r=new d(s);f(r,()=>{n.disposing=!0})}finally{C.owner=c,C.listener=l}return{choice:e,owned:n,result:u,dispose:()=>r(s),hold:i.engaged()?i:null}};return{step(t){if(u(p),a!==void 0){if(!n(a.choice,t)){let e=a;a=void 0,e.hold?.drop(),e.dispose?.()}else if((a.hold?.count()??0)>0)return!0;else{let e=a;return a=void 0,g(e),!0}}if(e.live!==void 0&&C.inTransition){let e=_(t);return e.hold===null?g(e):a=e,!0}let r=e.live;return e.live=void 0,r!==void 0&&h(r),!1}}},boundaryHold:()=>{let e=!1;return{engage:()=>(e||(e=!0,K()),!0),release:()=>{e&&(e=!1,J(),q())},holding:()=>e}}}}function O(){let e=C.hooks;if(e!==null)return e;let t=D();return C.hooks=t,t}function k(){O()}function A(e){return O().startTransition(e)}function j(){C.hooks?.beginHold()}function M(){C.hooks?.endHold()}function N(){C.hooks?.wakeSuspended()}function P(e){C.hooks?.holdReader(e)}function F(){return C.inTransition}function I(e){let t=C.hooks;return t===null?null:t.createHold(e)}function L(){return C.inTransition?C.hooks:null}function R(e){O().pause(e)}function z(e){C.hooks?.resume(e)}export{j as beginHold,I as createTransitionHold,M as endHold,P as holdReader,F as inTransition,R as pauseOwner,k as registerTransitionLane,z as resumeOwner,A as startTransition,L as transitionHooks,N as wakeSuspended};
|
|
2
2
|
//# sourceMappingURL=concurrency.js.map
|