@shadow-js/core 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/dev/action.js +11 -7
- package/dist/dev/action.js.map +1 -1
- package/dist/dev/internal/concurrency.js +15 -11
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/dispose.js +1 -1
- package/dist/dev/internal/dispose.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +1 -1
- package/dist/dev/internal/graph.js +28 -33
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/owner.d.ts +2 -1
- package/dist/dev/internal/owner.js +10 -8
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/scheduler.js +17 -8
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/list.js +4 -4
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/resource.js +3 -3
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/signal.js +3 -3
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +4 -4
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/prod/action.js +1 -1
- package/dist/prod/action.js.map +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/dispose.js +1 -1
- package/dist/prod/internal/dispose.js.map +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/owner.js +1 -1
- package/dist/prod/internal/owner.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/list.js +1 -1
- package/dist/prod/list.js.map +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/resource.js.map +1 -1
- package/dist/prod/signal.js +1 -1
- package/dist/prod/signal.js.map +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/server/action.js +1 -1
- package/dist/server/action.js.map +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/dispose.js +1 -1
- package/dist/server/internal/dispose.js.map +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/owner.js +1 -1
- package/dist/server/internal/owner.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/list.js +1 -1
- package/dist/server/list.js.map +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/resource.js.map +1 -1
- package/dist/server/signal.js +1 -1
- package/dist/server/signal.js.map +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server-dev/action.js +11 -7
- package/dist/server-dev/action.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +15 -11
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +1 -1
- package/dist/server-dev/internal/dispose.js.map +1 -1
- package/dist/server-dev/internal/graph.js +28 -33
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/owner.js +10 -8
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +17 -8
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/list.js +4 -4
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/resource.js +3 -3
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/signal.js +3 -3
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +4 -4
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/package.json +1 -1
package/dist/dev/resource.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.js","names":[],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":";;;;;;;;;;;;;;AAkGA,SAAS,KAAQ,SAAY,UAAqD;CAChF,MAAM,OAAO,iBAAoB,SAAS,WAAW,OAAO,KAAK,KAAK;CACtE,OAAO,OACC,WAAW,IAAI,IACpB,SAAS;EACR,YAAY,MAAM,MAAM,EAAE,aAAa,KAAK,CAAC;CAC/C,CACF;AACF;AAEA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;AAiFA,SAAgB,YACd,OACA,QACA,OACa;CACb,MAAM,YAAY,OAAO,WAAW;CAEpC,MAAM,SACJ,YAAa,OAAO,UAAU,aAAa,cAAc,cAAe;CAE1E,MAAM,UAAU;CAChB,MAAM,UAAW,YAAY,UAAU,QAAW,SAA0B,QAAQ,IAAI;CAIxF,MAAM,WAAW,YAAY,QAAS,WAA8C,CAAC;CAErF,MAAM,aAAa,kBAAkB;CAGrC,MAAM,CAAC,OAAO,YAAY,KAAoB,QAAQ,cAAc,KAAK;CACzE,MAAM,CAAC,OAAO,cAAc,KAAoB,aAAa,UAAU,cAAc,IAAI;CAEzF,IAAI;CACJ,MAAM,YAAY,SAA8B;EAC9C,WAAW,IAAI;EAEb,OAAe,eAAe,gBAAgB,QAAQ,MAAM,QAAQ,MAAM,aAAa,CAAC;CAE5F;CACA,MAAM,CAAC,SAAS,cAAc,KAAc,KAAA,GAAW,KAAK;CAC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,EAAE,KAAK,MAAM;EACpB,SAAS,EAAE,WAAW,MAAM,MAAM,aAAa,MAAM,MAAM,aAAa;EACxE,OAAO,EAAE,KAAK,QAAQ;EACtB,QAAQ,EAAE,KAAK,MAAM;EACrB,SAAS,EACP,aAAqC;GAGnC,IAAI,UAAU,OAAO,QAAQ,QAAQ,KAAA,CAAS;GAC9C,MAAM,QAAQ,QAAQ,MAAM;GAC5B,IAAI,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAA,GACjD,OAAO,QAAQ,QAAQ,KAAA,CAAS;GAElC,OAAO,KAAK,OAAO,QAAQ;EAC7B,EACF;EACA,QAAQ,EACN,QAAQ,SAAkD;GACxD,IAAI;GAEJ,IAAI,UAAU;GACd,IAAI;IACF,YAAY;KACV,WACE,OAAO,SAAS,aACZ,cAAe,KAAwC,MAAM,CAAC,CAAC,IAC/D;KACN,UAAU;KACV,YAAY,MAAM;KAClB,WAAW;KACX,WAAW;KACX,SAAS,QAAa;KACtB,WAAW,KAAA,CAAS;KACpB,SAAS,OAAO;IAClB,CAAC;GACH,UAAU;IACR,IAAI,SAAS,QAAQ;GACvB;GACA,OAAO;EACT,EACF;CACF,CAAC;CAID,SAAS;CAGJ,gBAAgB,QAAQ,QAAQ;CACrC,gBAAgB;EACd,WAAW;EACX,YAAY,MAAM;EAClB,QAAQ;CACV,CAAC;CACD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"resource.js","names":["SignalNode"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = new SignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n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,OAAO,QAAQ,QAAQ,KAAA,CAAS;GAElC,OAAO,KAAK,OAAO,QAAQ;EAC7B,EACF;EACA,QAAQ,EACN,QAAQ,SAAkD;GACxD,IAAI;GAEJ,IAAI,UAAU;GACd,IAAI;IACF,YAAY;KACV,WACE,OAAO,SAAS,aACZ,cAAe,KAAwC,MAAM,CAAC,CAAC,IAC/D;KACN,UAAU;KACV,YAAY,MAAM;KAClB,WAAW;KACX,WAAW;KACX,SAAS,QAAa;KACtB,WAAW,KAAA,CAAS;KACpB,SAAS,OAAO;IAClB,CAAC;GACH,UAAU;IACR,IAAI,SAAS,QAAQ;GACvB;GACA,OAAO;EACT,EACF;CACF,CAAC;CAID,SAAS;CAGJ,gBAAgB,QAAQ,QAAQ;CACrC,gBAAgB;EACd,WAAW;EACX,YAAY,MAAM;EAClB,QAAQ;CACV,CAAC;CACD,OAAO;AACT"}
|
package/dist/dev/signal.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { readSignal } from "./internal/graph.js";
|
|
1
|
+
import { Signal, readSignal } from "./internal/graph.js";
|
|
2
2
|
import { untrack } from "./ownership.js";
|
|
3
|
-
import {
|
|
3
|
+
import { writeSignal } from "./extend/index.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
|
|
@@ -24,7 +24,7 @@ import { createSignalNode, writeSignal } from "./extend/index.js";
|
|
|
24
24
|
*/
|
|
25
25
|
function useSignal(value, options) {
|
|
26
26
|
const equals = options?.equals === void 0 ? Object.is : options.equals;
|
|
27
|
-
const signal =
|
|
27
|
+
const signal = new Signal(value, equals, options?.name);
|
|
28
28
|
const read = () => readSignal(signal);
|
|
29
29
|
const write = ((next) => {
|
|
30
30
|
const resolved = typeof next === "function" ? untrack(() => next(signal.value)) : next;
|
package/dist/dev/signal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signal.js","names":[],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n
|
|
1
|
+
{"version":3,"file":"signal.js","names":["SignalNode"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n type Equals,\n readSignal,\n type Setter,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value. It runs untracked: a signal it reads\n * is not a dependency of the computation that writes.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string | undefined;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = new SignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,UAAa,OAAU,SAAsD;CAC3F,MAAM,SAAoB,SAAS,WAAW,KAAA,IAAY,OAAO,KAAK,QAAQ;CAC9E,MAAM,SAAS,IAAIA,OAAc,OAAO,QAAQ,SAAS,IAAI;CAC7D,MAAM,aAA0B,WAAW,MAAM;CACjD,MAAM,UAAU,SAAkB;EAChC,MAAM,WACJ,OAAO,SAAS,aAAa,cAAe,KAAwB,OAAO,KAAK,CAAC,IAAI;EAEvF,YAAY,QAAQ,QAAQ;EAC5B,OAAO;CACT;CACA,OAAO,CAAC,MAAM,KAAK;AACrB"}
|
package/dist/dev/store/nodes.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { track } from "../internal/graph.js";
|
|
2
|
-
import {
|
|
1
|
+
import { Signal, track } from "../internal/graph.js";
|
|
2
|
+
import { isTracking, notify as notify$1 } from "../extend/index.js";
|
|
3
3
|
// src/store/nodes.ts
|
|
4
4
|
/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */
|
|
5
5
|
const RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
@@ -120,7 +120,7 @@ function signalFor(node, key) {
|
|
|
120
120
|
if (size >= SWEEP_AT && (size & size - 1) === 0) {
|
|
121
121
|
for (const [other, node] of signals) if ((node.observers?.length ?? 0) === 0) signals.delete(other);
|
|
122
122
|
}
|
|
123
|
-
signal =
|
|
123
|
+
signal = new Signal(0, false);
|
|
124
124
|
signals.set(key, signal);
|
|
125
125
|
}
|
|
126
126
|
return signal;
|
|
@@ -133,7 +133,7 @@ function trackProperty(node, key) {
|
|
|
133
133
|
/** Subscribes the running computation (if any) to the key set of the object. */
|
|
134
134
|
function trackKeys(node) {
|
|
135
135
|
if (!isTracking()) return;
|
|
136
|
-
if (node.keys === null) node.keys =
|
|
136
|
+
if (node.keys === null) node.keys = new Signal(0, false);
|
|
137
137
|
track(node.keys);
|
|
138
138
|
}
|
|
139
139
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodes.js","names":[],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import {\n createSignalNode,\n isTracking,\n notify as notifySource,\n type SignalNode,\n track,\n} from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = createSignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = createSignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/** Deletes one own property of a raw object and notifies its signal and the key set. */\nexport function deleteRaw(target: object, key: string): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":";;;;AASA,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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B,IAAI,qCAEpC;CAEF,MAAM,OAAO,MAAM,IAAI,MAAM;CAC7B,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,OAAO,KAAK,SAAS,IAAI,GAAG,CAAC;CAC7B,IAAI,CAAC,KAAK,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/** 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,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,MAA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,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"}
|
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{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";import{currentOwner as i}from"./extend/index.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=i(),[l,u]=r(s),[d,f]=r(!1),p=0;return[l,(...r)=>{p+=1;let i=p,s=n(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p
|
|
1
|
+
import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";import{currentOwner as i}from"./extend/index.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=i(),[l,u]=r(s),[d,f]=r(!1),p=0;return[l,(...r)=>{p+=1;let i=p,s=n(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p&&f(!1),c===null)throw t;try{e(t,c)}catch(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}},h;try{h=n(()=>o(s,...r))}catch(e){try{m(e)}catch(e){return Promise.reject(e)}return Promise.resolve()}return a(h)?(f(!0),Promise.resolve(h).then(d,m)):(d(h),Promise.resolve())},d]}export{o as useAction};
|
|
2
2
|
//# sourceMappingURL=action.js.map
|
package/dist/prod/action.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action.js","names":["isPromiseLike","value","useAction","owner","currentOwner","state","setState","useSignal","initialState","pending","setPending","latest","args","id","previous","untrack","commit","batch","fail","error","handleError","result","action"],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n if (id
|
|
1
|
+
{"version":3,"file":"action.js","names":["isPromiseLike","value","useAction","owner","currentOwner","state","setState","useSignal","initialState","pending","setPending","latest","args","id","previous","untrack","commit","batch","fail","error","handleError","uncaught","result","action","thrown"],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n // A stale dispatch changes no state, but its error is still the owner's to hear.\n if (id === latest) setPending(false);\n if (owner === null) throw error;\n try {\n handleError(error, owner);\n } catch (uncaught) {\n // No handler took it: report it, as documented, instead of throwing out of dispatch.\n if (typeof reportError === \"function\") reportError(uncaught);\n else queueMicrotask(() => Promise.reject(uncaught));\n }\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n try {\n fail(error);\n } catch (thrown) {\n // Without an owner the returned promise carries the error.\n return Promise.reject(thrown);\n }\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":"A,oOAIA,SAASA,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiCA,SAAgBC,EACd,EACA,EAC2F,CAC3F,IAAMC,EAAQC,EAAa,EACrB,CAACC,EAAOC,GAAYC,EAAaC,CAAY,EAC7C,CAACC,EAASC,GAAcH,EAAU,EAAK,EACzCI,EAAS,EA4Cb,MAAO,CAACN,GA1CU,GAAGO,IAA2B,CAC9C,GAAU,EACV,IAAMC,EAAKF,EACLG,EAAWC,EAAQV,CAAK,EACxBW,EAAU,GAAmB,CAC7BH,IAAOF,GACXM,MAAY,CACVX,MAAeL,CAAK,EACpBS,EAAW,EAAK,CAClB,CAAC,CACH,EACMQ,EAAQ,GAAyB,CAGrC,GADIL,IAAOF,GAAQD,EAAW,EAAK,EAC/BP,IAAU,KAAM,MAAMgB,EAC1B,GAAI,CACFC,EAAYD,EAAOhB,CAAK,CAC1B,OAASkB,EAAU,CAEb,OAAO,aAAgB,WAAY,YAAYA,CAAQ,EACtD,mBAAqB,QAAQ,OAAOA,CAAQ,CAAC,CACpD,CACF,EACIC,EACJ,GAAI,CACF,EAASP,MAAcQ,EAAOT,EAAU,GAAGF,CAAI,CAAC,CAClD,OAASO,EAAO,CACd,GAAI,CACFD,EAAKC,CAAK,CACZ,OAASK,EAAQ,CAEf,OAAO,QAAQ,OAAOA,CAAM,CAC9B,CACA,OAAO,QAAQ,QAAQ,CACzB,CAMA,OALKxB,EAAiBsB,CAAM,GAI5BZ,EAAW,EAAI,EACR,QAAQ,QAAQY,CAAM,CAAC,CAAC,KAAKN,EAAQE,CAAI,IAJ9CF,EAAOM,CAAM,EACN,QAAQ,QAAQ,EAI3B,EACyBb,CAAO,CAClC,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{Owner as i,addCleanup as a,
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{Owner as i,addCleanup as a,finishDisposal as o}from"./owner.js";import{clearQueues as s,hasPending as c,place as l,renderQueue as u,userQueue as d}from"./queue.js";import{Computation as f,Signal as p,hasObservers as m,markObservers as h,readSignal as g}from"./graph.js";import{byCreation as _,reportUncaught as v,runQueued as y,schedule as b}from"./scheduler.js";import{runWithContext as x}from"../context.js";import{SuspenseContext as S}from"../suspense.js";import{disposeTree as C}from"./dispose.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,r)=>{let i=e.splice(0,r);i.sort(_);for(let e of i)e.flags&1024&&(e.flags&=~(2|n),!(e.flags&4)&&(e.pauses>0?e.flags|=t|n:y(e)));return i.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,r.flushing){R();return}let t=r.inTransition;r.inTransition=!0,r.flushing=!0;let n=64,i=0;try{for(;n>0&&P();){if(i+=1,i>1e3){s(),r.uncaught.push(new e(`INFINITE_LOOP`));break}let t=D.length>0?D:O;n-=I(t,n)}}finally{r.inTransition=t,r.flushing=!1}let a=r.uncaught.splice(0,r.uncaught.length);for(let e of a)v(e);P()?R():L(),c()&&b()},B=e=>{let t=r.inTransition,n=r.listener;r.inTransition=!0,r.listener=null;try{e()}finally{r.inTransition=t,r.listener=n}k??=new Promise(e=>{A=e});let i=k;return L(),i},V=(e,r)=>{if(e.pauses>0){e.flags=r?e.flags|t|n:(e.flags|t)&~n;return}let i=!!(e.flags&16);e.flags=e.flags&~t|2|n,i?D.push(e):O.push(e),R()},H=e=>{e.flags&512||e.pauses>0||(e.flags&2048?l(e,!1):(e.flags&1026)==1026&&(e.flags&=~n,e.flags&16?u.push(e):d.push(e)))},U=()=>{for(let e of[D,O]){for(let t of e)t.flags&=~(2|n),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=r.inTransition;r.inTransition=!0;try{for(let t of e)t.disposed||(t.state=2,t.kind===2?l(t,!0):h(t))}finally{r.inTransition=t}b()},Y=e=>{let t=[];E(e,e=>{e.pauses+=1,t.push(e)}),r.disposing+=1;try{for(let e=t.length-1;e>=0;--e){let n=t[e];n instanceof f&&n.kind===2&&!(n.flags&16)&&!n.disposed&&n.runCleanups()}}finally{o()}},X=e=>{let t=0,n=!1,r=!1,i={increment(){t+=1},decrement(){--t,t===0&&(n&&(n=!1,J(),q()),e())},hold(){return r=!0,n||(n=!0,K()),!0}};return{run:e=>x(S,i,e),count:()=>t,engaged:()=>r,drop:()=>{n&&(n=!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 f&&e.pauses===0&&!e.disposed){if(e.kind===2){if(e.flags&16&&!(e.flags&2048))return;e.state=2,l(e,!1)}else e.state!==0&&h(e)}}),b()},createHold:X,slotSwap:(e,t,n,o)=>{let s,c=new i(o),l=new p(0,!1,void 0),u=()=>{l.value+=1,m(l)&&(h(l),b())},d=e=>{e.owned.disposing=!0;try{e.hold?.drop(),e.dispose?.()}finally{e.owned.disposing=!1}},f=t=>{let n=e.live;e.live=t,n!==void 0&&d(n)},_=e=>{let n={index:e.index,value:e.when,disposing:!1},o=X(()=>{s!==void 0&&s.hold===o&&u()}),l=new i(c),d=r.owner,f=r.listener;r.owner=l,r.listener=null;let p;try{try{p=o.run(()=>t(e,n,!0))}catch(e){if(!T(e))throw e}let r=new i(l);a(r,()=>{n.disposing=!0})}finally{r.owner=d,r.listener=f}return{choice:e,owned:n,result:p,dispose:()=>C(l),hold:o.engaged()?o:null}};return{step(t){if(g(l),s!==void 0){if(!n(s.choice,t)){let e=s;s=void 0,e.hold?.drop(),e.dispose?.()}else if((s.hold?.count()??0)>0)return!0;else{let e=s;return s=void 0,f(e),!0}}if(e.live!==void 0&&r.inTransition){let e=_(t);return e.hold===null?f(e):s=e,!0}let i=e.live;return e.live=void 0,i!==void 0&&d(i),!1}}},boundaryHold:()=>{let e=!1;return{engage:()=>(e||(e=!0,K()),!0),release:()=>{e&&(e=!1,J(),q())},holding:()=>e}}}}function O(){let e=r.hooks;if(e!==null)return e;let t=D();return r.hooks=t,t}function k(){O()}function A(e){return O().startTransition(e)}function j(){r.hooks?.beginHold()}function M(){r.hooks?.endHold()}function N(){r.hooks?.wakeSuspended()}function P(e){r.hooks?.holdReader(e)}function F(){return r.inTransition}function I(e){let t=r.hooks;return t===null?null:t.createHold(e)}function L(){return r.inTransition?r.hooks:null}function R(e){O().pause(e)}function z(e){r.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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","settleLane","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","reportUncaught","hasPending","schedule","startTransition","listener","fn","shared","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","markObservers","pause","owner","Computation","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n readSignal,\n recompute,\n Signal,\n updateIfNecessary,\n} from \"./graph\";\nimport { addCleanup, handleError, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */\nconst SUSPENDED_SWEEP_AT = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) break;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /**\n * The promise every transition that waits for the lane shares (`waiting` counts the callers, for\n * devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew\n * with every `startTransition`, and all of them resolve at the same moment anyway.\n */\n let applied: Promise<void> | null = null;\n let resolveApplied: (() => void) | null = null;\n let waiting = 0;\n /**\n * Memos and effects that caught a suspension; woken all at once when a boundary releases them. A\n * node is listed once (it is a set), and the disposed ones are dropped each time the list\n * length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,\n * grow with the number of nodes that came and went.\n */\n const suspended = new Set<Computation>();\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n try {\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || resolveApplied === null) return;\n const resolve = resolveApplied;\n applied = resolveApplied = null;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.TRANSITION_END, waiting);\n waiting = 0;\n }\n resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n if (__DEV__) waiting += 1;\n applied ??= new Promise<void>((resolve) => {\n resolveApplied = resolve;\n });\n const shared = applied;\n settleLane();\n return shared;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n // Listed once: a node that suspends again before the wake-up is already in the set.\n if (!suspended.has(node)) {\n const size = suspended.size;\n if (size >= SUSPENDED_SWEEP_AT && (size & (size - 1)) === 0) {\n // A disposed node never wakes, so keeping it would leak it for as long as the hold lasts.\n for (const entry of suspended) {\n if (entry.disposed) suspended.delete(entry);\n }\n }\n suspended.add(node);\n }\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const woken = Array.from(suspended);\n suspended.clear();\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of woken) {\n if (node.disposed) continue;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n walk(owner, (node) => {\n node.pauses += 1;\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n });\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":"A,6tBAwDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvB,GAAIE,IAAS,IAAA,GAAW,MACxBC,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI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
|
|
1
|
+
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","runQueued","settleLane","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","error","reportUncaught","hasPending","schedule","startTransition","listener","fn","shared","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","markObservers","pause","nodes","owner","i","Computation","finishDisposal","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport { Computation, hasObservers, markObservers, readSignal, Signal } from \"./graph\";\nimport { addCleanup, finishDisposal, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, runQueued, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */\nconst SUSPENDED_SWEEP_AT = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop() as Owner;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /**\n * The promise every transition that waits for the lane shares (`waiting` counts the callers, for\n * devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew\n * with every `startTransition`, and all of them resolve at the same moment anyway.\n */\n let applied: Promise<void> | null = null;\n let resolveApplied: (() => void) | null = null;\n let waiting = 0;\n /**\n * Memos and effects that caught a suspension; woken all at once when a boundary releases them. A\n * node is listed once (it is a set), and the disposed ones are dropped each time the list\n * length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,\n * grow with the number of nodes that came and went.\n */\n const suspended = new Set<Computation>();\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || resolveApplied === null) return;\n const resolve = resolveApplied;\n applied = resolveApplied = null;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.TRANSITION_END, waiting);\n waiting = 0;\n }\n resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n if (__DEV__) waiting += 1;\n applied ??= new Promise<void>((resolve) => {\n resolveApplied = resolve;\n });\n const shared = applied;\n settleLane();\n return shared;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n // Listed once: a node that suspends again before the wake-up is already in the set.\n if (!suspended.has(node)) {\n const size = suspended.size;\n if (size >= SUSPENDED_SWEEP_AT && (size & (size - 1)) === 0) {\n // A disposed node never wakes, so keeping it would leak it for as long as the hold lasts.\n for (const entry of suspended) {\n if (entry.disposed) suspended.delete(entry);\n }\n }\n suspended.add(node);\n }\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const woken = Array.from(suspended);\n suspended.clear();\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of woken) {\n if (node.disposed) continue;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n // Every node is paused before any cleanup runs: a cleanup that throws must not leave the rest\n // unpaused. Preorder reversed is the disposal order: children first, newest first.\n const nodes: Owner[] = [];\n walk(owner, (node) => {\n node.pauses += 1;\n nodes.push(node);\n });\n rt.disposing += 1;\n try {\n for (let i = nodes.length - 1; i >= 0; i -= 1) {\n const node = nodes[i];\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n }\n } finally {\n finishDisposal();\n }\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":"A,ysBAgDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvBG,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,CAAC,EAC7BC,EAA0B,CAAC,EAM7BC,EAAgC,KAChCC,EAAsC,KAQpCC,kBAAY,IAAI,IAElBC,EAAQ,EACRC,EAAY,GAEVC,MAAgCP,EAAW,OAAS,GAAKC,EAAS,OAAS,EAC3EO,MAA0BD,EAAe,GAAKF,EAAQ,EAMtDI,GAAa,EAAsB,IAA0B,CACjE,IAAMC,EAAQC,EAAM,OAAO,EAAGC,CAAK,EACnCF,EAAM,KAAKG,CAAU,EACrB,IAAK,IAAMC,KAAUJ,EACdI,EAAO,MAAA,OACZ,EAAO,OAAS,EAAA,EAAgBC,GAC3B,IAAO,MAAA,KACRD,EAAO,OAAS,EAClB,EAAO,OAASE,EAAcD,EAGhCE,EAAUH,CAAM,IAElB,OAAOJ,EAAM,MACf,EAGMQ,MAAyB,CAC7B,GAAIV,EAAS,GAAKL,IAAmB,KAAM,OAC3C,IAAMgB,EAAUhB,EAChB,EAAU,EAAiB,KAK3BgB,EAAQ,CACV,EAGMC,MAA2B,CAC3Bd,IACJ,EAAY,GACZ,WAAWe,EAAW,CAAC,EACzB,EAOMA,MAAwB,CAE5B,GADA,EAAY,GACRC,EAAG,SAAU,CACfF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,QAAQ,CACpB,CAkBA,SAAgB+B,GAAsB,CACpC/B,EAAG,OAAO,cAAc,CAC1B,CAuBA,SAAgB2B,EAAW,EAAqC,CAC9D3B,EAAG,OAAO,WAAW4B,CAAO,CAC9B,CAmBA,SAAgBqD,GAAwB,CACtC,OAAOjF,EAAG,YACZ,CAmBA,SAAgBkF,EAAqB,EAA8C,CACjF,IAAMC,EAAQnF,EAAG,MACjB,OAAOmF,IAAU,KAAO,KAAOA,EAAM,WAAWvC,CAAS,CAC3D,CAkBA,SAAgBwC,GAAgC,CAC9C,OAAOpF,EAAG,aAAeA,EAAG,MAAQ,IACtC,CAkBA,SAAgBqF,EAAW,EAAoB,CAC7CR,EAAY,CAAC,CAAC,MAAMzC,CAAK,CAC3B,CAmBA,SAAgBkD,EAAY,EAAoB,CAC9CtF,EAAG,OAAO,OAAOoC,CAAK,CACxB,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{rt as e}from"./state.js";import{disposeTree as t}from"./owner.js";import{hasPending as n}from"./queue.js";import{flush as r}from"./scheduler.js";function i(i){let a,o=!1;try{t(i)}catch(e){o=!0,a=e}if(e.running===null&&e.batchDepth===0&&!e.flushing&&n())try{r()}catch(e){throw o?AggregateError([a,e],`SHADOW_DISPOSE_FLUSH_ERRORS`):e}if(o)throw a}export{i as disposeTree};
|
|
1
|
+
import{rt as e}from"./state.js";import{disposeTree as t}from"./owner.js";import{hasPending as n}from"./queue.js";import{flush as r}from"./scheduler.js";function i(i){let a,o=!1;try{t(i)}catch(e){o=!0,a=e}if(e.running===null&&e.batchDepth===0&&e.disposing===0&&!e.flushing&&n())try{r()}catch(e){throw o?AggregateError([a,e],`SHADOW_DISPOSE_FLUSH_ERRORS`):e}if(o)throw a}export{i as disposeTree};
|
|
2
2
|
//# sourceMappingURL=dispose.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispose.js","names":["disposeTree$1","disposeTree","failure","failed","root","error","rt","hasPending","flush"],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport { flush } from \"./scheduler\";\nimport { rt } from \"./state\";\n\n/**\n * Disposes an owner and everything below it: children first, newest first, then each node's\n * cleanups, newest first. Use it to end an owner made with `createOwner`; disposing an owner that is\n * already disposed does nothing. Exported from `@shadow-js/core/extend` as `disposeOwner`.\n *\n * Cleanups run in an implicit batch (O-3): effects that depend on signals a cleanup wrote are\n * flushed before this returns, unless the disposal happens inside a computation, a batch or a flush,\n * whose own exit flushes.\n *\n * @param root The owner to dispose, with its whole subtree.\n * @throws The error of a cleanup that no error handler caught, once the whole tree is disposed\n * (several such errors are thrown together as an `AggregateError`); during a running flush, that\n * flush throws them instead. An error of the flush that\n * follows is thrown as is, or combined with the cleanup errors in an `AggregateError`.\n * @example\n * import { addCleanup, createOwner, disposeOwner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * addCleanup(owner, () => console.log(\"released\"));\n * disposeOwner(owner); // logs \"released\"\n * @see addCleanup\n * @since 1.0.0\n */\nexport function disposeTree(root: Owner): void {\n let failure: unknown;\n let failed = false;\n try {\n disposeSubtree(root);\n } catch (error) {\n failed = true;\n failure = error;\n }\n if (rt.running === null
|
|
1
|
+
{"version":3,"file":"dispose.js","names":["disposeTree$1","disposeTree","failure","failed","root","error","rt","hasPending","flush"],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport { flush } from \"./scheduler\";\nimport { rt } from \"./state\";\n\n/**\n * Disposes an owner and everything below it: children first, newest first, then each node's\n * cleanups, newest first. Use it to end an owner made with `createOwner`; disposing an owner that is\n * already disposed does nothing. Exported from `@shadow-js/core/extend` as `disposeOwner`.\n *\n * Cleanups run in an implicit batch (O-3): effects that depend on signals a cleanup wrote are\n * flushed before this returns, unless the disposal happens inside a computation, a batch or a flush,\n * whose own exit flushes.\n *\n * @param root The owner to dispose, with its whole subtree.\n * @throws The error of a cleanup that no error handler caught, once the whole tree is disposed\n * (several such errors are thrown together as an `AggregateError`); during a running flush, that\n * flush throws them instead. An error of the flush that\n * follows is thrown as is, or combined with the cleanup errors in an `AggregateError`.\n * @example\n * import { addCleanup, createOwner, disposeOwner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * addCleanup(owner, () => console.log(\"released\"));\n * disposeOwner(owner); // logs \"released\"\n * @see addCleanup\n * @since 1.0.0\n */\nexport function disposeTree(root: Owner): void {\n let failure: unknown;\n let failed = false;\n try {\n disposeSubtree(root);\n } catch (error) {\n failed = true;\n failure = error;\n }\n // Only the outermost disposal flushes: a nested one (a cleanup disposing another owner) would run\n // effects while the tree it sits in is half torn down.\n if (\n rt.running === null &&\n rt.batchDepth === 0 &&\n rt.disposing === 0 &&\n !rt.flushing &&\n hasPending()\n ) {\n try {\n flush();\n } catch (error) {\n if (!failed) throw error;\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Disposal and the following flush both threw.\" : \"SHADOW_DISPOSE_FLUSH_ERRORS\",\n );\n }\n }\n if (failed) throw failure;\n}\n"],"mappings":"A,wJA6BA,SAAgBC,EAAY,EAAmB,CAC7C,IAAIC,EACAC,EAAS,GACb,GAAI,CACFH,EAAeI,CAAI,CACrB,OAASC,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,CAGA,GACEC,EAAG,UAAY,MACfA,EAAG,aAAe,GAClBA,EAAG,YAAc,GACjB,CAACA,EAAG,UACJC,EAAW,EAEX,GAAI,CACFC,EAAM,CACR,OAASH,EAAO,CAEd,MADKF,EACK,eACR,CAACD,EAASG,CAAK,EAC4C,6BAC7D,EAJmBA,CAKrB,CAEF,GAAIF,EAAQ,MAAMD,CACpB,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./diagnostics.js";import{nextSequence as t,rt as n}from"./state.js";import{Owner as r,addCleanup as i,disposeChildren as a,
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{nextSequence as t,rt as n}from"./state.js";import{Owner as r,addCleanup as i,disposeChildren as a,finishDisposal as o,handleError as s,hasErrorHandler as c}from"./owner.js";import{enqueue as l}from"./queue.js";const u=Object.freeze([]);var d=class{kind=0;observers=null;stamp=0;constructor(e,t,n){this.value=e,this.equals=t,this.name=n}},f=class extends r{error=void 0;fn;apply=null;sources=u;observers=null;stamp=0;trackIndex=0;constructor(e,n,r,i,a,o){super(e),this.kind=n,this.flags=r,this.state=2,this.fn=i,this.equals=a,this.name=o,this.value=void 0,this.seq=t()}release(){this.flags|=4,m(this,0),this.fn=null,this.apply=null}};function p(e,t){let n=e.observers;if(n===null)return;let r=n.length-2;if(t!==r){let e=n[r],i=n[r+1];n[t]=e,n[t+1]=i,e.sources[i+1]=t}n.length=r}function m(e,t){let n=e.sources;if(!(n.length<=t)){for(let e=n.length-2;e>=t;e-=2)p(n[e],n[e+1]);n.length=t}}function h(e,t,n){let r=e.length;if(r>=16)return e.push(t,n),e;let i=Array(r+2);for(let t=0;t<r;t+=1)i[t]=e[t];return i[r]=t,i[r+1]=n,i}function g(e){let t=n.listener;if(t===null||e.stamp===t.stamp)return;e.stamp=t.stamp;let r=t.trackIndex;if(r<t.sources.length){if(t.sources[r]===e){t.trackIndex=r+2;return}m(t,r)}let i=e.observers,a=t.sources,o=i===null?0:i.length,s=a.length;e.observers=i===null?[t,s]:h(i,t,s),t.sources=h(a,e,o),t.trackIndex=s+2}function _(e){return b(e.sources)}function v(e){return e.observers===null?[]:b(e.observers)}function y(e){return e.observers!==null&&e.observers.length>0}function b(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(e[n]);return t}const x=[];function S(e,t){let r=e.state;e.kind===2?(r<t&&(e.state=t),r===0?l(e):n.inTransition||n.hooks?.promote(e)):r>=t||(e.state=t,r===0&&e.observers!==null&&e.observers.length>0&&x.push(e))}function C(e,t){return n.hooks?.suspend(e,t)===!0}function w(e){return e.pauses>0&&!(e.flags&32)}function T(e){for(E(e.observers,2);x.length>0;)E(x.pop().observers,1)}function E(e,t){if(e!==null)for(let n=0;n<e.length;n+=2)S(e[n],t)}const D=[],O=[];let k=0;function A(t,n=!1){if(t.state===0)return;let r=k;D[k]=t,O[k]=0,k+=1,t.flags|=128;try{for(;k>r;){let t=k-1,r=D[t];if(r.state===1||r.state===2&&n){let n=r.sources,i=O[t],a=!1;for(;i<n.length;){let r=n[i];if(i+=2,r.kind===0)continue;let o=r;if(j(o)){if(o.flags&1)throw new e(`CYCLE_DETECTED`);if(M(o)){O[t]=i,D[k]=o,O[k]=0,k+=1,o.flags|=128,a=!0;break}}}if(a)continue}r.state===2?F(r):r.state=0,r.flags&=-129,--k}}finally{for(let e=r;e<k;e+=1)D[e].flags&=-129;D.length=r,O.length=r,k=r}}function j(e){return e.state!==0&&!(e.flags&4)&&!w(e)}function M(e){if(!j(e))return!1;let t=[];for(let n=e.parent;n!==null;n=n.parent)n instanceof f&&n.state!==0&&!(n.flags&129)&&t.push(n);for(let e=t.length-1;e>=0;--e){let n=t[e];j(n)&&A(n)}return j(e)}function N(e){return n.listener!==null&&g(e),e.value}function P(t){if(t.flags&1)throw new e(`CYCLE_DETECTED`);if(t.state!==0&&M(t)&&A(t,n.recomputeDepth>=128),n.listener!==null&&g(t),t.flags&8)throw t.error;return t.value}function F(e){let r=e.fn;if(r===null)return;n.disposing+=1;try{a(e),e.runCleanups()}finally{--n.disposing}e.trackIndex=0,e.errorHandlers=null,e.idCount=0,e.childCount=0;let i=n.owner,s=n.listener,c=n.running;n.owner=e,n.listener=e,n.running=e,n.recomputeDepth+=1,e.state=0,e.flags|=1,e.stamp=t();let l,u=!1,d;try{l=r(e.value)}catch(e){u=!0,d=e}finally{n.owner=i,n.listener=s,n.running=c,--n.recomputeDepth,e.flags&=-2,m(e,e.flags&4?0:e.trackIndex)}e.kind===1?L(e,l,u,d):z(e,l,u,d),n.disposing+=1,o()}function I(e,t,r){let i=n.listener;n.listener=null;try{return e(t,r)}finally{n.listener=i}}function L(e,t,n,r){if(n&&C(e,r))return!1;let i=!!(e.flags&32);e.flags&=-33;let a=!!(e.flags&8),o;if(n&&R(e,r))return!1;if(n)e.flags|=8,e.error=r,o=!0;else{e.flags&=-9,e.error=void 0;let n=e.equals;try{o=i||a||n===!1||!I(n,e.value,t),o&&(e.value=t)}catch(t){e.flags|=8,e.error=t,o=!0}}if(!o||i)return o;let s=e.observers;if(s===null)return o;for(let e=0;e<s.length;e+=2){let t=s[e];t.state===1&&(t.state=2)}return o}function R(e,t){if(!c(e))return!1;e.flags&=-9,e.error=void 0;try{s(t,e)}catch(t){e.flags|=8,e.error=t}return!0}function z(e,t,r,a){if(r){C(e,a)||s(a,e);return}let o=e.apply,c;if(o===null)c=t;else{let r=!!(e.flags&64);e.flags&=-65;let i=e.value;if(e.value=t,r)return;let a=n.owner,l=n.listener,u=n.running;n.owner=e,n.listener=null,n.running=e;try{c=o(t,i)}catch(t){C(e,t)||s(t,e);return}finally{n.owner=a,n.listener=l,n.running=u}}typeof c==`function`&&(i(e,c),e.flags&4&&e.runCleanups())}export{f as Computation,d as Signal,y as hasObservers,I as isEqual,w as isFrozen,T as markObservers,v as observersOf,P as readMemo,N as readSignal,F as recompute,M as refreshAncestors,_ as sourcesOf,g as track,A as updateIfNecessary};
|
|
2
2
|
//# sourceMappingURL=graph.js.map
|