@shadow-js/core 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/dist/dev/action.d.ts +0 -2
- package/dist/dev/action.js +1 -2
- package/dist/dev/cache.d.ts +2 -3
- package/dist/dev/cache.js +6 -5
- package/dist/dev/cache.js.map +1 -1
- package/dist/dev/context.d.ts +0 -2
- package/dist/dev/context.js +1 -2
- package/dist/dev/effect.d.ts +0 -2
- package/dist/dev/effect.js +18 -35
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/env.d.ts +0 -2
- package/dist/dev/env.js +1 -2
- package/dist/dev/events.d.ts +0 -2
- package/dist/dev/events.js +1 -2
- package/dist/dev/extend/index.d.ts +7 -8
- package/dist/dev/extend/index.js +8 -9
- package/dist/dev/extend/index.js.map +1 -1
- package/dist/dev/external-store.d.ts +0 -2
- package/dist/dev/external-store.js +9 -5
- package/dist/dev/external-store.js.map +1 -1
- package/dist/dev/internal/concurrency.d.ts +0 -2
- package/dist/dev/internal/concurrency.js +43 -22
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/devtools.d.ts +0 -2
- package/dist/dev/internal/devtools.js +1 -2
- package/dist/dev/internal/diagnostics.d.ts +0 -2
- package/dist/dev/internal/diagnostics.js +1 -4
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/dispose.d.ts +0 -2
- package/dist/dev/internal/dispose.js +1 -2
- package/dist/dev/internal/flags.js +2 -5
- package/dist/dev/internal/flags.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +0 -3
- package/dist/dev/internal/graph.js +21 -39
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/hydration-flag.d.ts +0 -2
- package/dist/dev/internal/hydration-flag.js +1 -2
- package/dist/dev/internal/messages.d.ts +0 -2
- package/dist/dev/internal/messages.js +1 -2
- package/dist/dev/internal/owner.d.ts +7 -7
- package/dist/dev/internal/owner.js +13 -24
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/queue.js +1 -2
- package/dist/dev/internal/scheduler.d.ts +0 -2
- package/dist/dev/internal/scheduler.js +34 -73
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/internal/state.d.ts +0 -2
- package/dist/dev/internal/state.js +1 -2
- package/dist/dev/internal/suspension.d.ts +0 -2
- package/dist/dev/internal/suspension.js +1 -2
- package/dist/dev/internal/types.d.ts +0 -2
- package/dist/dev/list.d.ts +0 -2
- package/dist/dev/list.js +1 -10
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/memo.d.ts +2 -3
- package/dist/dev/memo.js +5 -6
- package/dist/dev/memo.js.map +1 -1
- package/dist/dev/optimistic.d.ts +0 -2
- package/dist/dev/optimistic.js +1 -2
- package/dist/dev/ownership.d.ts +4 -4
- package/dist/dev/ownership.js +60 -5
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.d.ts +0 -2
- package/dist/dev/props.js +19 -13
- package/dist/dev/props.js.map +1 -1
- package/dist/dev/reaction.d.ts +1 -3
- package/dist/dev/reaction.js +6 -3
- package/dist/dev/reaction.js.map +1 -1
- package/dist/dev/reducer.d.ts +0 -2
- package/dist/dev/reducer.js +2 -3
- package/dist/dev/reducer.js.map +1 -1
- package/dist/dev/refs.d.ts +0 -2
- package/dist/dev/refs.js +1 -2
- package/dist/dev/resource.d.ts +0 -2
- package/dist/dev/resource.js +22 -14
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/selector.d.ts +0 -2
- package/dist/dev/selector.js +2 -7
- package/dist/dev/selector.js.map +1 -1
- package/dist/dev/signal.d.ts +3 -4
- package/dist/dev/signal.js +1 -2
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +7 -2
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/proxies.js +1 -2
- package/dist/dev/store/read.d.ts +0 -2
- package/dist/dev/store/read.js +1 -2
- package/dist/dev/store/reconcile.d.ts +0 -2
- package/dist/dev/store/reconcile.js +1 -2
- package/dist/dev/store/types.d.ts +0 -2
- package/dist/dev/store/use-store.d.ts +5 -2
- package/dist/dev/store/use-store.js +1 -2
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/suspense.d.ts +0 -2
- package/dist/dev/suspense.js +1 -2
- package/dist/dev/transitions.d.ts +0 -2
- package/dist/dev/transitions.js +2 -3
- package/dist/dev/transitions.js.map +1 -1
- package/dist/prod/cache.js +1 -1
- package/dist/prod/cache.js.map +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/extend/index.js +1 -1
- package/dist/prod/extend/index.js.map +1 -1
- package/dist/prod/external-store.js +1 -1
- package/dist/prod/external-store.js.map +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/flags.js +1 -1
- package/dist/prod/internal/flags.js.map +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/owner.js +1 -1
- package/dist/prod/internal/owner.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/list.js +1 -1
- package/dist/prod/list.js.map +1 -1
- package/dist/prod/memo.js +1 -1
- package/dist/prod/memo.js.map +1 -1
- package/dist/prod/ownership.js +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js.map +1 -1
- package/dist/prod/reaction.js +1 -1
- package/dist/prod/reaction.js.map +1 -1
- package/dist/prod/reducer.js +1 -1
- package/dist/prod/reducer.js.map +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/resource.js.map +1 -1
- package/dist/prod/selector.js +1 -1
- package/dist/prod/selector.js.map +1 -1
- package/dist/prod/signal.js.map +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/transitions.js +1 -1
- package/dist/prod/transitions.js.map +1 -1
- package/dist/server/cache.js +1 -1
- package/dist/server/cache.js.map +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/extend/index.js +1 -1
- package/dist/server/extend/index.js.map +1 -1
- package/dist/server/external-store.js.map +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/flags.js +1 -1
- package/dist/server/internal/flags.js.map +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/owner.js +1 -1
- package/dist/server/internal/owner.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/list.js +1 -1
- package/dist/server/list.js.map +1 -1
- package/dist/server/memo.js +1 -1
- package/dist/server/memo.js.map +1 -1
- package/dist/server/ownership.js +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js.map +1 -1
- package/dist/server/reaction.js +1 -1
- package/dist/server/reaction.js.map +1 -1
- package/dist/server/reducer.js +1 -1
- package/dist/server/reducer.js.map +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/resource.js.map +1 -1
- package/dist/server/selector.js +1 -1
- package/dist/server/selector.js.map +1 -1
- package/dist/server/signal.js.map +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/transitions.js.map +1 -1
- package/dist/server-dev/action.js +1 -2
- package/dist/server-dev/cache.js +6 -5
- package/dist/server-dev/cache.js.map +1 -1
- package/dist/server-dev/context.js +1 -2
- package/dist/server-dev/effect.js +1 -2
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/env.js +1 -2
- package/dist/server-dev/events.js +1 -2
- package/dist/server-dev/extend/index.js +8 -9
- package/dist/server-dev/extend/index.js.map +1 -1
- package/dist/server-dev/external-store.js +1 -2
- package/dist/server-dev/external-store.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +43 -22
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/devtools.js +1 -2
- package/dist/server-dev/internal/diagnostics.js +1 -4
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +1 -2
- package/dist/server-dev/internal/flags.js +2 -5
- package/dist/server-dev/internal/flags.js.map +1 -1
- package/dist/server-dev/internal/graph.js +21 -39
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/hydration-flag.js +1 -2
- package/dist/server-dev/internal/messages.js +1 -2
- package/dist/server-dev/internal/owner.js +13 -24
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/queue.js +1 -2
- package/dist/server-dev/internal/scheduler.js +34 -73
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/internal/state.js +1 -2
- package/dist/server-dev/internal/suspension.js +1 -2
- package/dist/server-dev/list.js +1 -10
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/memo.js +5 -6
- package/dist/server-dev/memo.js.map +1 -1
- package/dist/server-dev/optimistic.js +1 -2
- package/dist/server-dev/ownership.js +60 -5
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +19 -13
- package/dist/server-dev/props.js.map +1 -1
- package/dist/server-dev/reaction.js +6 -3
- package/dist/server-dev/reaction.js.map +1 -1
- package/dist/server-dev/reducer.js +2 -3
- package/dist/server-dev/reducer.js.map +1 -1
- package/dist/server-dev/refs.js +1 -2
- package/dist/server-dev/resource.js +22 -14
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/selector.js +2 -7
- package/dist/server-dev/selector.js.map +1 -1
- package/dist/server-dev/signal.js +1 -2
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +7 -2
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/proxies.js +1 -2
- package/dist/server-dev/store/read.js +1 -2
- package/dist/server-dev/store/reconcile.js +1 -2
- package/dist/server-dev/store/use-store.js +1 -2
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/suspense.js +1 -2
- package/dist/server-dev/transitions.js +1 -2
- package/dist/server-dev/transitions.js.map +1 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.2
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- A computation that disposed its own owner while running no longer leaves graph edges for the signals it read afterward.
|
|
8
|
+
- `resource.refetch()` on a disposed resource starts no fetch, and a Suspense boundary is released even when the flush after a resource settles (or after `mutate()`) throws.
|
|
9
|
+
- The updater of `resource.mutate()`, the `equals` of `useSelector`, the function behind `cache()` and the `subscribe` function of `useExternalStore` run untracked.
|
|
10
|
+
- `useExternalStore` unsubscribes when its first `getSnapshot()` after subscribing throws, `useReaction`'s `track()` does nothing once its owner is disposed, and a throwing cleanup of a `createRoot` no longer replaces the error its body threw (both are thrown in an `AggregateError`).
|
|
11
|
+
- A store no longer keeps one tracking signal per key it ever read in a tracked context: once an object has collected a few hundred of them, the ones nothing observes are dropped, and a key read again gets a fresh one that reflects the current value (`store.byId[id]` with churning ids no longer grows without bound).
|
|
12
|
+
- Transitions started while a Suspense hold is engaged share one promise instead of adding a waiter each, and the list of suspended memos and effects lists a node once and drops the disposed ones.
|
|
13
|
+
- The `equals` of a memo and of a signal runs untracked, so what it reads is not a dependency of the reader that pulled the memo or of the computation that writes.
|
|
14
|
+
- `DUPLICATE_CORE` is raised now: in development builds `createRoot` lists its copy of core in a registry at `globalThis[Symbol.for("shadow-js.core.instances")]` (at most 8 copies, each with its number of live roots, removed with its last root) and warns once when a root is created while another copy of the same build (client or server) has live roots. Copies that never overlap, such as separate test files, do not warn.
|
|
15
|
+
|
|
16
|
+
## 1.0.1
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Released at 1.0.1 with the other packages, which share one version. No change to this package.
|
|
21
|
+
|
|
3
22
|
## 1.0.0
|
|
4
23
|
|
|
5
24
|
### Added
|
package/dist/dev/action.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Accessor } from "./internal/types.js";
|
|
2
|
-
//#region src/action.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,
|
|
5
4
|
* tracks whether it is pending, and commits its result. The ShadowJS form of React's
|
|
@@ -32,5 +31,4 @@ import { Accessor } from "./internal/types.js";
|
|
|
32
31
|
* @since 1.0.0
|
|
33
32
|
*/
|
|
34
33
|
export declare function useAction<S, A extends unknown[]>(action: (previous: S, ...args: A) => S | PromiseLike<S>, initialState: S): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>];
|
|
35
|
-
//#endregion
|
|
36
34
|
//# sourceMappingURL=action.d.ts.map
|
package/dist/dev/action.js
CHANGED
|
@@ -3,7 +3,7 @@ import { batch } from "./internal/scheduler.js";
|
|
|
3
3
|
import { untrack } from "./ownership.js";
|
|
4
4
|
import { useSignal } from "./signal.js";
|
|
5
5
|
import { currentOwner } from "./extend/index.js";
|
|
6
|
-
|
|
6
|
+
// src/action.ts
|
|
7
7
|
function isPromiseLike(value) {
|
|
8
8
|
return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
|
9
9
|
}
|
|
@@ -84,7 +84,6 @@ function useAction(action, initialState) {
|
|
|
84
84
|
pending
|
|
85
85
|
];
|
|
86
86
|
}
|
|
87
|
-
//#endregion
|
|
88
87
|
export { useAction };
|
|
89
88
|
|
|
90
89
|
//# sourceMappingURL=action.js.map
|
package/dist/dev/cache.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/cache.d.ts
|
|
2
1
|
/** Options of {@link cache}. @since 1.0.0 */
|
|
3
2
|
export interface CacheOptions {
|
|
4
3
|
/**
|
|
@@ -11,7 +10,8 @@ export interface CacheOptions {
|
|
|
11
10
|
* Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
|
|
12
11
|
* arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
|
|
13
12
|
* position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
|
|
14
|
-
* A call that throws is not kept.
|
|
13
|
+
* A call that throws is not kept. `fn` runs untracked, so the first caller does not alone subscribe to what
|
|
14
|
+
* it reads. Outside any owner nothing is scoped, so `fn` runs every time.
|
|
15
15
|
*
|
|
16
16
|
* Use it to share one data fetch between components rendered in the same request.
|
|
17
17
|
*
|
|
@@ -31,5 +31,4 @@ export interface CacheOptions {
|
|
|
31
31
|
* @since 1.0.0
|
|
32
32
|
*/
|
|
33
33
|
export declare function cache<A extends unknown[], R>(fn: (...args: A) => R, options?: CacheOptions): (...args: A) => R;
|
|
34
|
-
//#endregion
|
|
35
34
|
//# sourceMappingURL=cache.d.ts.map
|
package/dist/dev/cache.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { untrack } from "./ownership.js";
|
|
1
2
|
import { currentOwner } from "./extend/index.js";
|
|
2
|
-
|
|
3
|
+
// src/cache.ts
|
|
3
4
|
function sameArgs(a, b) {
|
|
4
5
|
if (a.length !== b.length) return false;
|
|
5
6
|
for (let i = 0; i < a.length; i += 1) if (!Object.is(a[i], b[i])) return false;
|
|
@@ -15,7 +16,8 @@ function rootOf(owner) {
|
|
|
15
16
|
* Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
|
|
16
17
|
* arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
|
|
17
18
|
* position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
|
|
18
|
-
* A call that throws is not kept.
|
|
19
|
+
* A call that throws is not kept. `fn` runs untracked, so the first caller does not alone subscribe to what
|
|
20
|
+
* it reads. Outside any owner nothing is scoped, so `fn` runs every time.
|
|
19
21
|
*
|
|
20
22
|
* Use it to share one data fetch between components rendered in the same request.
|
|
21
23
|
*
|
|
@@ -40,14 +42,14 @@ function cache(fn, options) {
|
|
|
40
42
|
const scopes = /* @__PURE__ */ new WeakMap();
|
|
41
43
|
return (...args) => {
|
|
42
44
|
const root = rootOf(currentOwner());
|
|
43
|
-
if (root === null) return fn(...args);
|
|
45
|
+
if (root === null) return untrack(() => fn(...args));
|
|
44
46
|
let entries = scopes.get(root);
|
|
45
47
|
if (entries === void 0) {
|
|
46
48
|
entries = [];
|
|
47
49
|
scopes.set(root, entries);
|
|
48
50
|
}
|
|
49
51
|
for (const entry of entries) if (sameArgs(entry.args, args)) return entry.value;
|
|
50
|
-
const value = fn(...args);
|
|
52
|
+
const value = untrack(() => fn(...args));
|
|
51
53
|
entries.push({
|
|
52
54
|
args,
|
|
53
55
|
value
|
|
@@ -56,7 +58,6 @@ function cache(fn, options) {
|
|
|
56
58
|
return value;
|
|
57
59
|
};
|
|
58
60
|
}
|
|
59
|
-
//#endregion
|
|
60
61
|
export { cache };
|
|
61
62
|
|
|
62
63
|
//# sourceMappingURL=cache.js.map
|
package/dist/dev/cache.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.js","names":[],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return fn(...args);\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = fn(...args);\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"cache.js","names":[],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. `fn` runs untracked, so the first caller does not alone subscribe to what\n * it reads. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return untrack(() => fn(...args));\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = untrack(() => fn(...args));\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":";;;AAiBA,SAAS,SAAS,GAAuB,GAAgC;CACvE,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GACjC,IAAI,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO;CAErC,OAAO;AACT;;AAGA,SAAS,OAAO,OAAmC;CACjD,IAAI,OAAO;CACX,OAAO,SAAS,QAAQ,KAAK,WAAW,MAAM,OAAO,KAAK;CAC1D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,MACd,IACA,SACmB;CACnB,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WACE,yCACZ;CAEF,MAAM,yBAAS,IAAI,QAAwB;CAC3C,QAAQ,GAAG,SAAe;EACxB,MAAM,OAAO,OAAO,aAAa,CAAC;EAClC,IAAI,SAAS,MAAM,OAAO,cAAc,GAAG,GAAG,IAAI,CAAC;EACnD,IAAI,UAAU,OAAO,IAAI,IAAI;EAC7B,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,CAAC;GACX,OAAO,IAAI,MAAM,OAAO;EAC1B;EACA,KAAK,MAAM,SAAS,SAClB,IAAI,SAAS,MAAM,MAAM,IAAI,GAAG,OAAO,MAAM;EAE/C,MAAM,QAAQ,cAAc,GAAG,GAAG,IAAI,CAAC;EACvC,QAAQ,KAAK;GAAE;GAAM;EAAM,CAAC;EAC5B,IAAI,QAAQ,SAAS,OAAO,QAAQ,MAAM;EAC1C,OAAO;CACT;AACF"}
|
package/dist/dev/context.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/context.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* A context made by {@link createContext}: a value that a subtree receives from the nearest provider
|
|
4
3
|
* above it. The context is itself the provider component; `Provider` is the same function.
|
|
@@ -102,5 +101,4 @@ export declare function runWithContext<T, R>(context: Context<T>, value: T, fn:
|
|
|
102
101
|
* @since 1.0.0
|
|
103
102
|
*/
|
|
104
103
|
export declare function useContext<T>(context: Context<T>): T;
|
|
105
|
-
//#endregion
|
|
106
104
|
//# sourceMappingURL=context.d.ts.map
|
package/dist/dev/context.js
CHANGED
|
@@ -4,7 +4,7 @@ import { runWithOwner } from "./ownership.js";
|
|
|
4
4
|
import { useRenderEffect } from "./effect.js";
|
|
5
5
|
import { useSignal } from "./signal.js";
|
|
6
6
|
import { currentOwner } from "./extend/index.js";
|
|
7
|
-
|
|
7
|
+
// src/context.ts
|
|
8
8
|
/**
|
|
9
9
|
* Creates a context: a value that components read with {@link useContext} without passing it
|
|
10
10
|
* through props. Render the returned component around a subtree to provide a value. The value is
|
|
@@ -105,7 +105,6 @@ function useContext(context) {
|
|
|
105
105
|
if (context.defaultValue === void 0) throw new ShadowError("CONTEXT_MISSING");
|
|
106
106
|
return context.defaultValue;
|
|
107
107
|
}
|
|
108
|
-
//#endregion
|
|
109
108
|
export { createContext, runWithContext, useContext };
|
|
110
109
|
|
|
111
110
|
//# sourceMappingURL=context.js.map
|
package/dist/dev/effect.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Cleanup } from "./internal/types.js";
|
|
2
|
-
//#region src/effect.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.
|
|
5
4
|
* @since 1.0.0
|
|
@@ -118,5 +117,4 @@ export declare function useRenderEffect<T>(compute: () => T, apply?: (value: T,
|
|
|
118
117
|
* @since 1.0.0
|
|
119
118
|
*/
|
|
120
119
|
export declare function onMount(fn: () => void | Cleanup): void;
|
|
121
|
-
//#endregion
|
|
122
120
|
//# sourceMappingURL=effect.d.ts.map
|
package/dist/dev/effect.js
CHANGED
|
@@ -1,54 +1,38 @@
|
|
|
1
1
|
import { warn } from "./internal/diagnostics.js";
|
|
2
2
|
import { untrack } from "./ownership.js";
|
|
3
3
|
import { createComputation, currentOwner } from "./extend/index.js";
|
|
4
|
-
|
|
5
|
-
/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */
|
|
6
|
-
const HELD = Symbol("held");
|
|
7
|
-
/** The nearest gate above the current owner (see `Owner.gate`), or null. */
|
|
8
|
-
function nearestGate() {
|
|
9
|
-
for (let owner = currentOwner(); owner !== null; owner = owner.parent) if (owner.gate !== null) return owner.gate;
|
|
10
|
-
return null;
|
|
11
|
-
}
|
|
4
|
+
// src/effect.ts
|
|
12
5
|
function createEffect(fnIn, applyIn, render, deferIn, name) {
|
|
13
6
|
if (currentOwner() === null) warn("NO_OWNER_EFFECT");
|
|
14
7
|
let fn = fnIn;
|
|
15
8
|
let apply = applyIn;
|
|
16
9
|
let defer = deferIn;
|
|
17
|
-
const gate = render ? null :
|
|
10
|
+
const gate = render ? null : currentOwner()?.gate ?? null;
|
|
18
11
|
if (gate !== null) {
|
|
19
12
|
let opened = false;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
13
|
+
let closed = false;
|
|
14
|
+
const innerFn = fn;
|
|
15
|
+
const innerApply = apply;
|
|
16
|
+
let skipFirst = defer;
|
|
17
|
+
defer = false;
|
|
18
|
+
fn = (previous) => {
|
|
19
|
+
closed = !opened && gate();
|
|
20
|
+
opened ||= !closed;
|
|
21
|
+
return closed ? void 0 : innerFn(previous);
|
|
22
|
+
};
|
|
23
|
+
if (innerApply !== null) apply = (value, previous) => {
|
|
24
|
+
if (closed) return void 0;
|
|
25
|
+
if (!skipFirst) return innerApply(value, previous);
|
|
26
|
+
skipFirst = false;
|
|
25
27
|
};
|
|
26
|
-
if (apply === null) {
|
|
27
|
-
const inner = fn;
|
|
28
|
-
fn = (previous) => held() ? void 0 : inner(previous);
|
|
29
|
-
} else {
|
|
30
|
-
const innerFn = fn;
|
|
31
|
-
const innerApply = apply;
|
|
32
|
-
let skipFirst = defer;
|
|
33
|
-
defer = false;
|
|
34
|
-
fn = (previous) => held() ? HELD : innerFn(previous);
|
|
35
|
-
apply = (value, previous) => {
|
|
36
|
-
if (value === HELD) return void 0;
|
|
37
|
-
if (skipFirst) {
|
|
38
|
-
skipFirst = false;
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
return innerApply(value, previous === HELD ? void 0 : previous);
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
28
|
}
|
|
45
29
|
createComputation({
|
|
46
30
|
kind: "effect",
|
|
47
31
|
fn,
|
|
48
32
|
render,
|
|
49
33
|
defer,
|
|
50
|
-
|
|
51
|
-
|
|
34
|
+
apply: apply ?? void 0,
|
|
35
|
+
name
|
|
52
36
|
});
|
|
53
37
|
}
|
|
54
38
|
function useEffect(first, second, third) {
|
|
@@ -105,7 +89,6 @@ function useRenderEffect(compute, apply) {
|
|
|
105
89
|
function onMount(fn) {
|
|
106
90
|
createEffect(() => untrack(fn), null, false, false, "onMount");
|
|
107
91
|
}
|
|
108
|
-
//#endregion
|
|
109
92
|
export { onMount, useEffect, useRenderEffect };
|
|
110
93
|
|
|
111
94
|
//# sourceMappingURL=effect.js.map
|
package/dist/dev/effect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\
|
|
1
|
+
{"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (__DEV__ && currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : (currentOwner()?.gate ?? null);\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect. `closed` is what the latest run of `fn`\n // found: `apply` runs right after it, and does nothing for a run that was held.\n let opened = false;\n let closed = false;\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => {\n closed = !opened && gate();\n opened ||= !closed;\n return closed ? undefined : innerFn(previous);\n };\n if (innerApply !== null) {\n apply = (value, previous) => {\n if (closed) return undefined;\n if (!skipFirst) return innerApply(value, previous);\n skipFirst = false;\n return undefined;\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n apply: apply ?? undefined,\n name,\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":";;;;AA4BA,SAAS,aACP,MACA,SACA,QACA,SACA,MACM;CAGN,IAAe,aAAa,MAAM,MAAM,KAAK,iBAAiB;CAC9D,IAAI,KAAK;CACT,IAAI,QAAQ;CACZ,IAAI,QAAQ;CACZ,MAAM,OAAO,SAAS,OAAQ,aAAa,CAAC,EAAE,QAAQ;CACtD,IAAI,SAAS,MAAM;EAIjB,IAAI,SAAS;EACb,IAAI,SAAS;EACb,MAAM,UAAU;EAChB,MAAM,aAAa;EAEnB,IAAI,YAAY;EAChB,QAAQ;EACR,MAAM,aAAa;GACjB,SAAS,CAAC,UAAU,KAAK;GACzB,WAAW,CAAC;GACZ,OAAO,SAAS,KAAA,IAAY,QAAQ,QAAQ;EAC9C;EACA,IAAI,eAAe,MACjB,SAAS,OAAO,aAAa;GAC3B,IAAI,QAAQ,OAAO,KAAA;GACnB,IAAI,CAAC,WAAW,OAAO,WAAW,OAAO,QAAQ;GACjD,YAAY;EAEd;CAEJ;CACA,kBAAkB;EAChB,MAAM;EACN;EACA;EACA;EACA,OAAO,SAAS,KAAA;EAChB;CACF,CAAC;AACH;AA0DA,SAAgB,UACd,OACA,QACA,OACM;CACN,IAAI,OAAO,WAAW,YACpB,aACE,OACA,QACA,OACA,OAAO,UAAU,MACjB,OAAO,IACT;MACK;EACL,IAAI,MAAM,QAAQ,MAAM,GAAG,KAAK,qBAAqB;EACrD,aAAa,OAAO,MAAM,OAAO,OAAQ,QAAsC,IAAI;CACrF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBACd,SACA,OACM;CACN,aACE,SACC,SAAS,MACV,MACA,OACA,KAAA,CACF;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,IAAgC;CACtD,mBAAmB,QAAQ,EAAE,GAAG,MAAM,OAAO,OAAO,SAAS;AAC/D"}
|
package/dist/dev/env.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/env.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* True in the server condition build, where effects never run and rendering produces strings. Use
|
|
4
3
|
* it to skip browser-only work. The value is fixed per build: the package export conditions
|
|
@@ -25,5 +24,4 @@ export declare const isServer: boolean;
|
|
|
25
24
|
* @since 1.0.0
|
|
26
25
|
*/
|
|
27
26
|
export declare const isDev: boolean;
|
|
28
|
-
//#endregion
|
|
29
27
|
//# sourceMappingURL=env.d.ts.map
|
package/dist/dev/env.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/env.ts
|
|
2
2
|
/**
|
|
3
3
|
* True in the server condition build, where effects never run and rendering produces strings. Use
|
|
4
4
|
* it to skip browser-only work. The value is fixed per build: the package export conditions
|
|
@@ -25,7 +25,6 @@ const isServer = false;
|
|
|
25
25
|
* @since 1.0.0
|
|
26
26
|
*/
|
|
27
27
|
const isDev = true;
|
|
28
|
-
//#endregion
|
|
29
28
|
export { isDev, isServer };
|
|
30
29
|
|
|
31
30
|
//# sourceMappingURL=env.js.map
|
package/dist/dev/events.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/events.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* A stable callback that always runs its handler untracked. The ShadowJS form of React's
|
|
4
3
|
* `useEffectEvent`: components run once and props are getters, so the handler already sees the
|
|
@@ -24,5 +23,4 @@
|
|
|
24
23
|
* @since 1.0.0
|
|
25
24
|
*/
|
|
26
25
|
export declare function useEvent<A extends unknown[], R>(handler: (...args: A) => R): (...args: A) => R;
|
|
27
|
-
//#endregion
|
|
28
26
|
//# sourceMappingURL=events.d.ts.map
|
package/dist/dev/events.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { untrack } from "./ownership.js";
|
|
2
|
-
|
|
2
|
+
// src/events.ts
|
|
3
3
|
/**
|
|
4
4
|
* A stable callback that always runs its handler untracked. The ShadowJS form of React's
|
|
5
5
|
* `useEffectEvent`: components run once and props are getters, so the handler already sees the
|
|
@@ -27,7 +27,6 @@ import { untrack } from "./ownership.js";
|
|
|
27
27
|
function useEvent(handler) {
|
|
28
28
|
return (...args) => untrack(() => handler(...args));
|
|
29
29
|
}
|
|
30
|
-
//#endregion
|
|
31
30
|
export { useEvent };
|
|
32
31
|
|
|
33
32
|
//# sourceMappingURL=events.js.map
|
|
@@ -11,7 +11,6 @@ import { ShadowError, WarningListener, resetWarningDedupe, setWarningListener, w
|
|
|
11
11
|
import { disposeTree } from "../internal/dispose.js";
|
|
12
12
|
import { isHydrating, withHydration } from "../internal/hydration-flag.js";
|
|
13
13
|
import { SUSPENSION, isSuspension } from "../internal/suspension.js";
|
|
14
|
-
//#region src/extend.d.ts
|
|
15
14
|
/**
|
|
16
15
|
* Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use
|
|
17
16
|
* it in a primitive that attaches a node or a cleanup to its caller's owner.
|
|
@@ -112,7 +111,8 @@ export declare function runInScope<T>(scope: {
|
|
|
112
111
|
*
|
|
113
112
|
* @param value Initial value.
|
|
114
113
|
* @param equals Decides whether a write is a change: readers are notified only when it returns
|
|
115
|
-
* `false`. `false` notifies on every write.
|
|
114
|
+
* `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's
|
|
115
|
+
* own `equals`), so what it reads is not a dependency of the writer or the reader.
|
|
116
116
|
* @param name Label shown by devtools. Undefined leaves the signal unnamed.
|
|
117
117
|
* @returns The signal node. It has no owner: it lives as long as something references it.
|
|
118
118
|
* @example
|
|
@@ -199,12 +199,12 @@ export interface ComputationOptions {
|
|
|
199
199
|
* returns `false`, and `false` always propagates. Ignored for effects.
|
|
200
200
|
* @default Object.is
|
|
201
201
|
*/
|
|
202
|
-
equals?: Equals<unknown
|
|
202
|
+
equals?: Equals<unknown> | undefined;
|
|
203
203
|
/**
|
|
204
204
|
* Label shown by devtools and diagnostics.
|
|
205
205
|
* @default undefined (the node is unnamed)
|
|
206
206
|
*/
|
|
207
|
-
name?: string;
|
|
207
|
+
name?: string | undefined;
|
|
208
208
|
/**
|
|
209
209
|
* Effects: run in the render phase, synchronously at creation and before user effects in each
|
|
210
210
|
* flush. Ignored for memos.
|
|
@@ -220,19 +220,19 @@ export interface ComputationOptions {
|
|
|
220
220
|
* Memos: do not compute until the first read.
|
|
221
221
|
* @default false (the memo computes once at creation)
|
|
222
222
|
*/
|
|
223
|
-
lazy?: boolean;
|
|
223
|
+
lazy?: boolean | undefined;
|
|
224
224
|
/**
|
|
225
225
|
* Memos that run component setup (such as a hot-reload wrapper): writing signals inside is
|
|
226
226
|
* legitimate there, so the dev-mode write guard stays off.
|
|
227
227
|
* @default false
|
|
228
228
|
*/
|
|
229
|
-
allowWrites?: boolean;
|
|
229
|
+
allowWrites?: boolean | undefined;
|
|
230
230
|
/**
|
|
231
231
|
* Effects: second stage, run untracked with the value `fn` computed and the previous one. It may
|
|
232
232
|
* return a cleanup function.
|
|
233
233
|
* @default undefined (`fn` is the whole effect)
|
|
234
234
|
*/
|
|
235
|
-
apply?: (value: never, previous: never) => unknown;
|
|
235
|
+
apply?: ((value: never, previous: never) => unknown) | undefined;
|
|
236
236
|
/**
|
|
237
237
|
* Owner to attach to. `null` creates a node that no owner disposes.
|
|
238
238
|
* @default the current owner
|
|
@@ -326,6 +326,5 @@ export declare function refresh(node: Computation): void;
|
|
|
326
326
|
* @since 1.0.0
|
|
327
327
|
*/
|
|
328
328
|
export declare function createOwner(parent?: Owner | null): Owner;
|
|
329
|
-
//#endregion
|
|
330
329
|
export { type Accessor, type AnyFunction, type BoundaryHold, type Cleanup, Computation as ComputationNode, type ContextMap, DEVTOOLS_EVENT, type Equals, type ErrorHandler, MESSAGES, type MessageCode, Owner, SUSPENSION, type Setter, ShadowError, Signal as SignalNode, type SlotBranch, type SlotChoice, type SlotOwned, type SlotState, type SlotSwap, type Source as SourceNode, type TransitionHold, type WarningListener, addCleanup, batch, beginHold, createTransitionHold, report as devtoolsReport, disposeTree as disposeOwner, endHold, flush, flushSync, formatMessage, group, handleError, holdReader, inTransition, isHydrating, isSuspension, markObservers, observersOf, pauseOwner, readSignal, registerTransitionLane, resetWarningDedupe, resumeOwner, runWithContext, schedule, setWarningListener, sourcesOf, startTransition, track, transitionHooks, wakeSuspended, warn, withHydration };
|
|
331
330
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/dev/extend/index.js
CHANGED
|
@@ -4,14 +4,14 @@ import { ShadowError, resetWarningDedupe, setWarningListener, warn } from "../in
|
|
|
4
4
|
import { rt } from "../internal/state.js";
|
|
5
5
|
import { Owner, addCleanup, handleError } from "../internal/owner.js";
|
|
6
6
|
import { enqueue } from "../internal/queue.js";
|
|
7
|
-
import { Computation, Signal, hasObservers, markObservers, observersOf, readMemo, readSignal, recompute, sourcesOf, track, updateIfNecessary } from "../internal/graph.js";
|
|
7
|
+
import { Computation, Signal, hasObservers, isEqual, markObservers, observersOf, readMemo, readSignal, recompute, sourcesOf, track, updateIfNecessary } from "../internal/graph.js";
|
|
8
8
|
import { batch, flush, flushSync, group, schedule } from "../internal/scheduler.js";
|
|
9
9
|
import { runWithContext } from "../context.js";
|
|
10
10
|
import { disposeTree } from "../internal/dispose.js";
|
|
11
11
|
import { SUSPENSION, isSuspension } from "../internal/suspension.js";
|
|
12
12
|
import { beginHold, createTransitionHold, endHold, holdReader, inTransition, pauseOwner, registerTransitionLane, resumeOwner, startTransition, transitionHooks, wakeSuspended } from "../internal/concurrency.js";
|
|
13
13
|
import { isHydrating, withHydration } from "../internal/hydration-flag.js";
|
|
14
|
-
|
|
14
|
+
// src/extend.ts
|
|
15
15
|
/**
|
|
16
16
|
* The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,
|
|
17
17
|
* `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import
|
|
@@ -141,7 +141,8 @@ function runInScope(scope, fn) {
|
|
|
141
141
|
*
|
|
142
142
|
* @param value Initial value.
|
|
143
143
|
* @param equals Decides whether a write is a change: readers are notified only when it returns
|
|
144
|
-
* `false`. `false` notifies on every write.
|
|
144
|
+
* `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's
|
|
145
|
+
* own `equals`), so what it reads is not a dependency of the writer or the reader.
|
|
145
146
|
* @param name Label shown by devtools. Undefined leaves the signal unnamed.
|
|
146
147
|
* @returns The signal node. It has no owner: it lives as long as something references it.
|
|
147
148
|
* @example
|
|
@@ -181,7 +182,7 @@ function createSignalNode(value, equals, name) {
|
|
|
181
182
|
function writeSignal(signal, next, options) {
|
|
182
183
|
if (options?.allowInMemo !== true && isComputingMemo()) throw new ShadowError("WRITE_IN_MEMO");
|
|
183
184
|
const equals = signal.equals;
|
|
184
|
-
if (equals !== false && equals
|
|
185
|
+
if (equals !== false && isEqual(equals, signal.value, next)) return false;
|
|
185
186
|
signal.value = next;
|
|
186
187
|
report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));
|
|
187
188
|
notify(signal);
|
|
@@ -233,13 +234,12 @@ function notify(source) {
|
|
|
233
234
|
*/
|
|
234
235
|
function createComputation(options) {
|
|
235
236
|
const owner = options.owner === void 0 ? rt.owner : options.owner;
|
|
236
|
-
|
|
237
|
-
|
|
237
|
+
const memo = options.kind === "memo";
|
|
238
|
+
const node = new Computation(owner, memo ? 1 : 2, memo ? 32 | (options.allowWrites === true ? 256 : 0) : (options.render === true ? 16 : 0) | (options.defer === true ? 64 : 0) | (options.lane === true ? 512 : 0), options.fn, memo ? options.equals ?? Object.is : false, options.name);
|
|
239
|
+
if (memo) {
|
|
238
240
|
if (options.lazy !== true) updateIfNecessary(node);
|
|
239
241
|
return node;
|
|
240
242
|
}
|
|
241
|
-
const flags = (options.render === true ? 16 : 0) | (options.defer === true ? 64 : 0) | (options.lane === true ? 512 : 0);
|
|
242
|
-
const node = new Computation(owner, 2, flags, options.fn, false, options.name);
|
|
243
243
|
node.apply = options.apply ?? null;
|
|
244
244
|
if (options.render === true) recompute(node);
|
|
245
245
|
else {
|
|
@@ -311,7 +311,6 @@ function refresh(node) {
|
|
|
311
311
|
function createOwner(parent) {
|
|
312
312
|
return new Owner(parent === void 0 ? rt.owner : parent);
|
|
313
313
|
}
|
|
314
|
-
//#endregion
|
|
315
314
|
export { Computation as ComputationNode, DEVTOOLS_EVENT, MESSAGES, Owner, SUSPENSION, ShadowError, Signal as SignalNode, addCleanup, batch, beginHold, createComputation, createOwner, createSignalNode, createTransitionHold, currentListener, currentOwner, report as devtoolsReport, disposeTree as disposeOwner, endHold, flush, flushSync, formatMessage, group, handleError, holdReader, inTransition, isComputingMemo, isHydrating, isSuspension, isTracking, markObservers, notify, observersOf, pauseOwner, readComputation, readSignal, refresh, registerTransitionLane, resetWarningDedupe, resumeOwner, runInScope, runWithContext, schedule, setWarningListener, sourcesOf, startTransition, track, transitionHooks, wakeSuspended, warn, withHydration, writeSignal };
|
|
316
315
|
|
|
317
316
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["OwnerClass"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && equals(signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: (value: never, previous: never) => unknown;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n if (options.kind === \"memo\") {\n const node = new Computation(\n owner,\n KIND_MEMO,\n FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0),\n options.fn,\n options.equals ?? Object.is,\n options.name,\n );\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n const flags =\n (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0);\n const node = new Computation(owner, KIND_EFFECT, flags, options.fn, false, options.name);\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,SAAgB,eAA6B;CAC3C,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAsC;CACpD,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;AAiBA,SAAgB,aAAsB;CACpC,OAAO,GAAG,aAAa;AACzB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAA2B;CACzC,OACE,GAAG,cAAc,KACjB,GAAG,YAAY,QACf,GAAG,QAAQ,SAAA,MACV,GAAG,QAAQ,QAAA,SAA+B;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,WACd,OACA,IACG;CACH,MAAM,QAAQ,GAAG;CACjB,MAAM,WAAW,GAAG;CACpB,IAAI;EACF,MAAM,YAAY,MAAM;EACxB,IAAI,cAAc,KAAA,GAAW,GAAG,QAAQ;EACxC,MAAM,eAAe,MAAM;EAC3B,IAAI,iBAAiB,KAAA,GAAW,GAAG,WAAW;EAC9C,OAAO,GAAG;CACZ,UAAU;EACR,GAAG,QAAQ;EACX,GAAG,WAAW;CAChB;AACF;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,iBAAoB,OAAU,QAAmB,MAA0B;CACzF,OAAO,IAAI,OAAU,OAAO,QAAQ,IAAI;AAC1C;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,YAAe,QAAmB,MAAS,SAAiC;CAC1F,IAAe,SAAS,gBAAgB,QAAQ,gBAAgB,GAC9D,MAAM,IAAI,YAAY,eAAe;CAEvC,MAAM,SAAS,OAAO;CACtB,IAAI,WAAW,SAAS,OAAO,OAAO,OAAO,IAAI,GAAG,OAAO;CAC3D,OAAO,QAAQ;CAEb,OAAO,eAAe,gBAAgB,QAAQ,MAAM,GAAG,SAAS,YAAY,MAAM,CAAC;CAErF,OAAO,MAAM;CACb,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,OAAO,QAAsB;CAC3C,IAAI,CAAC,aAAa,MAAM,GAAG;CAC3B,cAAc,MAAM;CACpB,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBAAkB,SAA0C;CAC1E,MAAM,QAAQ,QAAQ,UAAU,KAAA,IAAY,GAAG,QAAQ,QAAQ;CAC/D,IAAI,QAAQ,SAAS,QAAQ;EAC3B,MAAM,OAAO,IAAI,YACf,OAAA,GAAA,MAEe,QAAQ,gBAAgB,OAAA,MAA2B,IAClE,QAAQ,IACR,QAAQ,UAAU,OAAO,IACzB,QAAQ,IACV;EACA,IAAI,QAAQ,SAAS,MAAM,kBAAkB,IAAI;EACjD,OAAO;CACT;CACA,MAAM,SACH,QAAQ,WAAW,OAAA,KAAqB,MACxC,QAAQ,UAAU,OAAA,KAAoB,MACtC,QAAQ,SAAS,OAAA,MAAmB;CACvC,MAAM,OAAO,IAAI,YAAY,OAAA,GAAoB,OAAO,QAAQ,IAAI,OAAO,QAAQ,IAAI;CACvF,KAAK,QAAQ,QAAQ,SAAS;CAC9B,IAAI,QAAQ,WAAW,MAGrB,UAAU,IAAI;MACT;EACL,QAAQ,IAAI;EACZ,SAAS;CACX;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAmB,MAAsB;CACvD,OAAO,SAAY,IAAI;AACzB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,MAAyB;CAC/C,kBAAkB,IAAI;AACxB;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,QAA8B;CACxD,OAAO,IAAIA,MAAW,WAAW,KAAA,IAAY,GAAG,QAAQ,MAAM;AAChE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["OwnerClass"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n isEqual,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's\n * own `equals`), so what it reads is not a dependency of the writer or the reader.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && isEqual(equals, signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown> | undefined;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string | undefined;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean | undefined;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean | undefined;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: ((value: never, previous: never) => unknown) | undefined;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n const memo = options.kind === \"memo\";\n const node = new Computation(\n owner,\n memo ? KIND_MEMO : KIND_EFFECT,\n memo\n ? FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0)\n : (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0),\n options.fn,\n memo ? (options.equals ?? Object.is) : false,\n options.name,\n );\n if (memo) {\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,SAAgB,eAA6B;CAC3C,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAsC;CACpD,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;AAiBA,SAAgB,aAAsB;CACpC,OAAO,GAAG,aAAa;AACzB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAA2B;CACzC,OACE,GAAG,cAAc,KACjB,GAAG,YAAY,QACf,GAAG,QAAQ,SAAA,MACV,GAAG,QAAQ,QAAA,SAA+B;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,WACd,OACA,IACG;CACH,MAAM,QAAQ,GAAG;CACjB,MAAM,WAAW,GAAG;CACpB,IAAI;EACF,MAAM,YAAY,MAAM;EACxB,IAAI,cAAc,KAAA,GAAW,GAAG,QAAQ;EACxC,MAAM,eAAe,MAAM;EAC3B,IAAI,iBAAiB,KAAA,GAAW,GAAG,WAAW;EAC9C,OAAO,GAAG;CACZ,UAAU;EACR,GAAG,QAAQ;EACX,GAAG,WAAW;CAChB;AACF;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAoB,OAAU,QAAmB,MAA0B;CACzF,OAAO,IAAI,OAAU,OAAO,QAAQ,IAAI;AAC1C;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,YAAe,QAAmB,MAAS,SAAiC;CAC1F,IAAe,SAAS,gBAAgB,QAAQ,gBAAgB,GAC9D,MAAM,IAAI,YAAY,eAAe;CAEvC,MAAM,SAAS,OAAO;CACtB,IAAI,WAAW,SAAS,QAAQ,QAAQ,OAAO,OAAO,IAAI,GAAG,OAAO;CACpE,OAAO,QAAQ;CAEb,OAAO,eAAe,gBAAgB,QAAQ,MAAM,GAAG,SAAS,YAAY,MAAM,CAAC;CAErF,OAAO,MAAM;CACb,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,OAAO,QAAsB;CAC3C,IAAI,CAAC,aAAa,MAAM,GAAG;CAC3B,cAAc,MAAM;CACpB,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBAAkB,SAA0C;CAC1E,MAAM,QAAQ,QAAQ,UAAU,KAAA,IAAY,GAAG,QAAQ,QAAQ;CAC/D,MAAM,OAAO,QAAQ,SAAS;CAC9B,MAAM,OAAO,IAAI,YACf,OACA,OAAA,IAAA,GACA,OAAA,MACmB,QAAQ,gBAAgB,OAAA,MAA2B,MACjE,QAAQ,WAAW,OAAA,KAAqB,MACtC,QAAQ,UAAU,OAAA,KAAoB,MACtC,QAAQ,SAAS,OAAA,MAAmB,IAC3C,QAAQ,IACR,OAAQ,QAAQ,UAAU,OAAO,KAAM,OACvC,QAAQ,IACV;CACA,IAAI,MAAM;EACR,IAAI,QAAQ,SAAS,MAAM,kBAAkB,IAAI;EACjD,OAAO;CACT;CACA,KAAK,QAAQ,QAAQ,SAAS;CAC9B,IAAI,QAAQ,WAAW,MAGrB,UAAU,IAAI;MACT;EACL,QAAQ,IAAI;EACZ,SAAS;CACX;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAmB,MAAsB;CACvD,OAAO,SAAY,IAAI;AACzB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,MAAyB;CAC/C,kBAAkB,IAAI;AACxB;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,QAA8B;CACxD,OAAO,IAAIA,MAAW,WAAW,KAAA,IAAY,GAAG,QAAQ,MAAM;AAChE"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Accessor, Equals } from "./internal/types.js";
|
|
2
|
-
//#region src/external-store.d.ts
|
|
3
2
|
/** Options of {@link useExternalStore}. @since 1.0.0 */
|
|
4
3
|
export interface ExternalStoreOptions<T> {
|
|
5
4
|
/**
|
|
@@ -56,5 +55,4 @@ export interface ExternalStoreOptions<T> {
|
|
|
56
55
|
* @since 1.0.0
|
|
57
56
|
*/
|
|
58
57
|
export declare function useExternalStore<T>(subscribe: (notify: () => void) => () => void, getSnapshot: () => T, options?: ExternalStoreOptions<T>): Accessor<T>;
|
|
59
|
-
//#endregion
|
|
60
58
|
//# sourceMappingURL=external-store.d.ts.map
|