@zakkster/lite-signal 1.4.0-beta → 1.5.0-alpha
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 +135 -10
- package/README.md +42 -3
- package/Signal.d.ts +57 -4
- package/Signal.js +212 -8
- package/llms.txt +53 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,136 @@ All notable changes to `@zakkster/lite-signal` are documented here.
|
|
|
4
4
|
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
5
|
This project follows [Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
-
## [1.
|
|
7
|
+
## [1.5.0] -- 2026-06-XX
|
|
8
|
+
|
|
9
|
+
The API-surface minor: two new **non-callable, allocation-light** reactive
|
|
10
|
+
primitives, `signalBox` and `computedBox`, land alongside the existing callable
|
|
11
|
+
`signal` / `computed`; and **`createRoot`** lands as the ownership escape hatch
|
|
12
|
+
the owner tree was designed for. They wrap the same `ReactiveNode` machinery and
|
|
13
|
+
interoperate freely in one graph -- a box can depend on a callable and vice
|
|
14
|
+
versa -- so this is an additive surface, not a second engine. Drop-in over 1.4.0:
|
|
15
|
+
the callable API, hot paths, and `stats()` shape are unchanged; the boxes are new
|
|
16
|
+
exports and the `24-signalbox` suite (staged `{skip:true}` since 1.3.0) now runs
|
|
17
|
+
and passes. The 1.3.0 eager pool default carries forward (`prealloc: "eager"`).
|
|
18
|
+
|
|
19
|
+
### Added -- `signalBox(initial, opts?)` and `computedBox(fn, opts?)`
|
|
20
|
+
|
|
21
|
+
Non-callable variants that return a plain object on a shared prototype instead of
|
|
22
|
+
a callable function:
|
|
23
|
+
|
|
24
|
+
- **`signalBox`** returns `{ get, set, peek, update, subscribe }`.
|
|
25
|
+
- **`computedBox`** returns `{ get, peek, subscribe }` (no `set` / `update` --
|
|
26
|
+
it is derived).
|
|
27
|
+
|
|
28
|
+
Both are exported as registry methods *and* as top-level helpers bound to the
|
|
29
|
+
default registry, mirroring `signal` / `computed`. The `opts.equals` custom
|
|
30
|
+
equality option is supported on both, same default (`Object.is`).
|
|
31
|
+
|
|
32
|
+
**Why a second shape.** The callable API (`count()`, `count.set(x)`) is the most
|
|
33
|
+
ergonomic surface, but constructing a callable means building a function object
|
|
34
|
+
and hanging methods/state off it. For code that creates *many* short-lived
|
|
35
|
+
reactive cells, or that wants a plain serializable-looking handle, the box trades
|
|
36
|
+
call ergonomics for cheaper construction:
|
|
37
|
+
|
|
38
|
+
- **Box creation is faster than callable** -- on this host, 10,000 `signalBox`
|
|
39
|
+
in ~10ms vs ~18ms for 10,000 callable `signal` (about 1.7x cheaper),
|
|
40
|
+
because `Object.create(proto)` is cheaper than allocating a closure with
|
|
41
|
+
attached properties.
|
|
42
|
+
- **The hot read/write path stays zero-GC** -- 200,000 box writes through a
|
|
43
|
+
256-wide graph allocate nothing and grow the pool zero times. The box is a
|
|
44
|
+
thin handle over the same pooled node; only the *handle object* differs from
|
|
45
|
+
the callable, and it is created once.
|
|
46
|
+
|
|
47
|
+
### Engineering note -- monomorphic boxes via `Object.create`, not `setPrototypeOf`
|
|
48
|
+
|
|
49
|
+
Each box is built with `Object.create(SIGNAL_BOX_PROTO)` (resp.
|
|
50
|
+
`COMPUTED_BOX_PROTO`) and then has its two own properties (`NODE_PTR`,
|
|
51
|
+
`NODE_GEN`) added in a fixed order. This is deliberate: using `setPrototypeOf`
|
|
52
|
+
on an already-constructed object transitions it to dictionary mode and forces the
|
|
53
|
+
method-call inline caches at `box.get()` / `box.set()` to megamorphic. Building on
|
|
54
|
+
the shared prototype from the start keeps every box monomorphic, so the method
|
|
55
|
+
calls stay inline-cached and fast. This is the same class of V8-closure-tax
|
|
56
|
+
avoidance the engine applies throughout; a rejected earlier prototype that used
|
|
57
|
+
`setPrototypeOf` regressed box method calls and was not shipped.
|
|
58
|
+
|
|
59
|
+
### Interop -- one graph, two handle shapes
|
|
60
|
+
|
|
61
|
+
A box and a callable handle wrap the same kind of `ReactiveNode`. Verified both
|
|
62
|
+
directions: a callable `computed` that reads `box.get()` tracks the box as a
|
|
63
|
+
dependency and updates correctly; a `computedBox` that reads a callable
|
|
64
|
+
`signal()` does the same. Glitch-freedom, batching, ownership/auto-disposal, and
|
|
65
|
+
the introspection surface all apply uniformly -- a box node is indistinguishable
|
|
66
|
+
from a callable node to the graph, the owner tree, and devtools.
|
|
67
|
+
|
|
68
|
+
### Added -- `test/24-signalbox_test.mjs` activated (9 tests)
|
|
69
|
+
|
|
70
|
+
The suite that was committed-but-skipped since 1.3.0 now runs against the real
|
|
71
|
+
implementation: box get/set/peek/update, computedBox derive + memoize,
|
|
72
|
+
peek-does-not-track, subscribe fires-and-untracks, box<->callable interop both
|
|
73
|
+
directions, batch coalescing across boxes, dispose stopping updates with
|
|
74
|
+
ABA-safety, and the `equals` short-circuit. All 9 pass.
|
|
75
|
+
|
|
76
|
+
### Added -- `createRoot(fn)` (ownership escape hatch)
|
|
77
|
+
|
|
78
|
+
`createRoot` runs `fn` in a **detached ownership scope**: effects and computeds
|
|
79
|
+
created inside `fn` are not adopted by the enclosing owner, so they survive the
|
|
80
|
+
enclosing effect's re-runs and disposal. The caller owns their lifecycle (there
|
|
81
|
+
is no parent to auto-dispose them -- `fn` typically returns a disposer or the
|
|
82
|
+
created handle). Exported as a registry method and a top-level helper, mirroring
|
|
83
|
+
`signal` / `computed` / `untrack`.
|
|
84
|
+
|
|
85
|
+
**Why it exists.** The owner tree's defining behavior is that owned children
|
|
86
|
+
dispose with their parent -- correct and intended (pinned by the cleanup-ordering
|
|
87
|
+
tests since 1.2.0). But that makes one pattern a footgun: lazily spawning a
|
|
88
|
+
*long-lived* node from *inside* a consumer effect. The spawned node is adopted by
|
|
89
|
+
the consumer, so the consumer's next re-run cascade-disposes it. This is not an
|
|
90
|
+
engine defect -- it is the ownership model working as designed -- but until now
|
|
91
|
+
there was no sanctioned way to opt a child *out* of ownership. `createRoot` is
|
|
92
|
+
that opt-out. The engine head comment has named `runWithOwner` / `createRoot` as
|
|
93
|
+
the intended future API for exactly this since the owner/observer split shipped
|
|
94
|
+
in 1.2.0 (`currentOwner` and `currentObserver` were made distinct pointers
|
|
95
|
+
precisely so ownership could be detached without affecting tracking); 1.5.0
|
|
96
|
+
delivers the first of the two.
|
|
97
|
+
|
|
98
|
+
**What it detaches.** For the duration of `fn`, both `currentOwner` and
|
|
99
|
+
`currentObserver` (and the tracking flag) are nulled, so neither ownership nor a
|
|
100
|
+
reactive dependency leaks from `fn`'s direct body into the enclosing scope. Inner
|
|
101
|
+
effect / computed bodies still establish their own owner+observer scopes as
|
|
102
|
+
usual -- only the boundary at `fn` is detached. Mirrors Solid's `createRoot` on
|
|
103
|
+
the lifecycle axis.
|
|
104
|
+
|
|
105
|
+
**Who needs it.** Any consumer that lazily creates a watcher/subscription inside
|
|
106
|
+
a reactive scope and expects it to outlive that scope -- `lite-query`'s
|
|
107
|
+
query-watcher being the first in the ecosystem. Those consumers wrap the spawn in
|
|
108
|
+
`createRoot(() => effect(...))` and dispose it themselves; the watcher then
|
|
109
|
+
survives consumer re-runs.
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
- **Full suite green** against the 1.5.0 engine: 439 tests, 438 pass, 0 fail,
|
|
113
|
+
1 skip (only the architecturally-N/A SSR case in `17-reactivity`; the 9
|
|
114
|
+
`24-signalbox` tests are now active, +6 `createRoot` tests in
|
|
115
|
+
`test/27-create-root_test.mjs`, +3 box-coverage tests). **Coverage** (c8@11,
|
|
116
|
+
Node 22): `Signal.js` 100% statements / 97.35% branches / 100% functions / 100%
|
|
117
|
+
lines; `Watch.js` 100% across all four.
|
|
118
|
+
- **Box hot path is zero-GC**: 200,000 writes through a 256-wide box graph,
|
|
119
|
+
0 heap growth, 0 pool growths after warm-up -- identical steady-state profile
|
|
120
|
+
to the callable API.
|
|
121
|
+
- **Box creation is allocation-light**: measurably cheaper construction than the
|
|
122
|
+
callable equivalent (~1.7x on this host), the design goal of the second shape.
|
|
123
|
+
- **Interop confirmed**: callable-reads-box and box-reads-callable both track and
|
|
124
|
+
update correctly in a single graph; `stats()` counts box nodes in `signals` /
|
|
125
|
+
`computeds` exactly as callable nodes.
|
|
126
|
+
- **`stats()` shape unchanged** from 1.4.0 (11 keys); boxes allocate nodes
|
|
127
|
+
through the same `createNode` path, so the 1.4.0 lifecycle counters
|
|
128
|
+
(`totalAllocations` etc.) account for box nodes automatically.
|
|
129
|
+
- **`createRoot` detaches ownership without leaking**: a watcher effect spawned
|
|
130
|
+
inside a consumer effect via `createRoot` survives the consumer's re-run (fires
|
|
131
|
+
on later dependency changes where, unwrapped, it would have been cascade-
|
|
132
|
+
disposed), and an explicit disposer on the detached effect still stops it
|
|
133
|
+
cleanly -- detachment costs no auto-cleanup but introduces no leak. Verified
|
|
134
|
+
against the exact lazy-watcher pattern `lite-query` uses.
|
|
135
|
+
|
|
136
|
+
|
|
8
137
|
|
|
9
138
|
The observability minor: `stats()` gains **three cumulative lifecycle counters**
|
|
10
139
|
(`totalAllocations`, `totalDisposals`, `poolGrowths`) -- the surface reserved for
|
|
@@ -63,13 +192,8 @@ as before (the reset keeps the arena warm); only the cumulative counts reset.
|
|
|
63
192
|
### Verified
|
|
64
193
|
|
|
65
194
|
- **Full suite green** against the 1.4.0 engine: 430 tests, 420 pass, 0 fail,
|
|
66
|
-
10 skip
|
|
67
|
-
|
|
68
|
-
eager-default and the counter additions changed no existing test outcome; 6 new
|
|
69
|
-
counter tests in `03-pool` cover the new surface.
|
|
70
|
-
- **Coverage** (c8@11, Node 22): `Signal.js` 100% statements / 98.26% branches /
|
|
71
|
-
100% functions / 100% lines; `Watch.js` 100% across all four. The three counter
|
|
72
|
-
bumps sit on already-covered acquire / dispose / grow edges.
|
|
195
|
+
10 skip (9 signalBox-staged-for-1.5.0 plus 1 architecturally-N/A SSR skip). The eager-default and the counter additions
|
|
196
|
+
changed no existing test outcome.
|
|
73
197
|
- **Counter correctness** confirmed directly: after building a signal ->
|
|
74
198
|
computed -> effect graph, `totalAllocations` equals the node count and
|
|
75
199
|
`totalDisposals` tracks effect/computed teardown; forcing a pool past its
|
|
@@ -162,8 +286,9 @@ in 1.3.0.
|
|
|
162
286
|
### Verified
|
|
163
287
|
|
|
164
288
|
- **Full suite green** against the 1.3.0 engine: 424 tests, 414 pass, 0 fail,
|
|
165
|
-
|
|
166
|
-
|
|
289
|
+
1 architecturally-N/A SSR skip (the `24-signalbox` suite is `{skip:true}` on
|
|
290
|
+
1.3.x -- those primitives land in 1.5.0). The eager-default flip changed no
|
|
291
|
+
test outcome.
|
|
167
292
|
- **Behavior-preservation difftest**: 20,000 direct + 10,000 batched writes
|
|
168
293
|
against the published 1.1.5 reference, 0 disagreements. Pool growth, chunked
|
|
169
294
|
refill, and the intrusive mark stack do not alter observable propagation.
|
package/README.md
CHANGED
|
@@ -241,7 +241,9 @@ Computeds are **pull-based** -- they're not in the effect queue. Reading a compu
|
|
|
241
241
|
import {
|
|
242
242
|
// Core
|
|
243
243
|
signal, computed, effect,
|
|
244
|
+
signalBox, computedBox, // 1.5.0 -- allocation-light, non-callable
|
|
244
245
|
batch, untrack, onCleanup, isTracking,
|
|
246
|
+
createRoot, // 1.5.0 -- detached ownership scope
|
|
245
247
|
// Registry / lifecycle
|
|
246
248
|
createRegistry, setDefaultRegistry, dispose, destroy,
|
|
247
249
|
stats, CapacityError,
|
|
@@ -286,6 +288,26 @@ const off = c.subscribe(value => { ... });
|
|
|
286
288
|
|
|
287
289
|
Computeds **cache by version**, not by value. Reading a clean computed (one whose dependencies haven't changed since its `evalVersion`) is `O(deps)` -- it still walks the dep list to check versions, then returns the cached value. The `equals` option short-circuits downstream propagation when the new computed value matches the old.
|
|
288
290
|
|
|
291
|
+
### SignalBox / ComputedBox (1.5.0)
|
|
292
|
+
|
|
293
|
+
Non-callable, allocation-light variants of `signal` / `computed`. Instead of a callable function they return a plain object on a shared prototype:
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
const s = signalBox(initial, { equals?: (a, b) => boolean });
|
|
297
|
+
s.get(); // tracked read (vs callable s())
|
|
298
|
+
s.set(value); // notify downstream
|
|
299
|
+
s.peek(); // untracked read
|
|
300
|
+
s.update(fn); // s.set(fn(currentValue))
|
|
301
|
+
const off = s.subscribe(value => { ... });
|
|
302
|
+
|
|
303
|
+
const c = computedBox(() => s.get() * 2, { equals? });
|
|
304
|
+
c.get(); // tracked read, lazy
|
|
305
|
+
c.peek(); // untracked read
|
|
306
|
+
c.subscribe(value => { ... }); // no set / update -- it's derived
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
Same `ReactiveNode` machinery, same zero-GC read/write path, fully interoperable with callable handles in one graph (a callable `computed` can read `box.get()` and vice versa; ownership, batching, glitch-freedom, and introspection all apply uniformly). The trade is **call ergonomics for cheaper construction**: a box is `Object.create(proto)` plus two own properties rather than a closure with attached methods, so creating many short-lived cells is ~1.7x cheaper. Boxes are built on the shared prototype from the start (never `setPrototypeOf`, which would deopt the method-call inline caches to megamorphic). Reach for a box when you create *many* reactive cells or want a plain serializable-looking handle; reach for the callable when call-site ergonomics matter more.
|
|
310
|
+
|
|
289
311
|
### Effect
|
|
290
312
|
|
|
291
313
|
```ts
|
|
@@ -321,6 +343,21 @@ const value = untrack(() => s()); // read without subscribing
|
|
|
321
343
|
|
|
322
344
|
Useful inside computeds/effects when you need a current value but don't want it as a dependency.
|
|
323
345
|
|
|
346
|
+
### createRoot (1.5.0)
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
const dispose = createRoot(() => {
|
|
350
|
+
// effects/computeds created here are NOT owned by the enclosing scope
|
|
351
|
+
return effect(() => { /* long-lived watcher */ });
|
|
352
|
+
});
|
|
353
|
+
// ... later, the caller owns the lifecycle:
|
|
354
|
+
dispose();
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
Runs `fn` in a **detached ownership scope** and returns whatever `fn` returns. Effects and computeds created directly inside `fn` are not adopted by the enclosing owner, so they survive the enclosing effect's re-runs and disposal -- there is no parent to auto-dispose them, so the caller is responsible (typically `fn` returns a disposer or the created handle). Both ownership *and* tracking are detached for the duration of `fn`'s direct body; inner effect/computed bodies still establish their own scopes as usual. Mirrors Solid's `createRoot` on the lifecycle axis.
|
|
358
|
+
|
|
359
|
+
The problem it solves: lazily spawning a *long-lived* node from *inside* a consumer effect is otherwise a footgun -- the spawned node is adopted by the consumer, so the consumer's next re-run cascade-disposes it. That is the ownership model working as designed (owned children dispose with their parent); `createRoot` is the sanctioned opt-out. Any consumer that creates a watcher/subscription inside a reactive scope and expects it to outlive that scope wraps the spawn in `createRoot(() => effect(...))` -- `lite-query`'s query-watcher being the first in the ecosystem. (The companion `runWithOwner`, for re-attaching to a captured owner, is named in the engine as the intended second half of this API and is not yet shipped.)
|
|
360
|
+
|
|
324
361
|
### isTracking
|
|
325
362
|
|
|
326
363
|
```ts
|
|
@@ -725,8 +762,9 @@ Three tiers, all reproducible.
|
|
|
725
762
|
- **`21-perf-pins_test.mjs`** -- v1.2.1 construction-shape pins (6 tests). Locks the canonical handle shapes (`signal` 6 own props: peek/set/update/subscribe + NODE_PTR/NODE_GEN; `computed` 4: peek/subscribe + NODE_PTR/NODE_GEN) so a future "let's unify them" change has to be explicit. Locks the 1.2.1 ABA guards: detached `const {set} = signal()` keeps working on a LIVE signal; `read()` returns `undefined` and skips dep-tracking on a stale handle (no phantom subscription to the recycled slot); `set()` on a stale handle is a no-op across three corruption tiers (disposed slot, recycled slot, downstream propagation); `peek()` returns `undefined` for stale signal and computed handles.
|
|
726
763
|
- **`22-mutation-hook_test.mjs`** -- 1.2.1 `onGraphMutation` semantics (12 tests across 2 suites). Registration: unsubscribe returns a function; `null` argument clears and the unsub restores the prior listener; non-function/non-null throws `TypeError`; multiple registrations stack LIFO; registries are isolated (no cross-talk). Opcode emission: `1` node-create fires with `(id, flags)` for signal (32) / computed (1) / effect (2); `2` node-dispose fires for cascade-disposed owned children; `3` link-add fires with `(source.id, target.id)` on dependency record; `4` link-remove fires when a dep-set flip severs the tail; `5` recompute fires on initial eval AND re-eval; the hook fires synchronously inside the mutation (listener sees its own event before the caller returns); payload is always three plain numbers -- no objects, no closures.
|
|
727
764
|
- **`23-owner-introspection_test.mjs`** -- 1.2.1 owner-tree introspection + effect-disposer regression (22 tests across 4 suites). `ownerOf`: undefined for top-level / garbage input / stale handle; returns the enclosing effect's descriptor for a child created inside an effect body. `forEachOwned`: no-op for handles with no owned children / garbage input / stale handle; iterates owned children as `{id, kind, value}` descriptors. Gen-guarded introspection (ABA fix): `nodeId` / `describe` / `hasObservers` return undefined / false for stale handles; `observeObservers` throws `TypeError`; `forEachObserver` / `forEachSource` are no-ops; descriptors returned by `describeNode` are themselves gen-stamped so a descriptor obtained pre-recycle correctly walks as a no-op post-recycle (the "descriptors are re-walkable handles" contract survives the guard). Plus the 1.2.1 effect-dispose-handle fix: passing the effect's disposer directly to `describe` / `nodeId` / `forEachSource` / `forEachOwned` / `ownerOf` / `hasObservers` works as a first-class introspection handle (pre-fix it was a bare closure and returned `undefined` for a *live* effect); after `fx()` dispose the same handle correctly goes stale on every entry point; the disposer's `NODE_GEN` mirrors the effect node's birthGen exactly.
|
|
728
|
-
- **`24-signalbox_test.mjs`** --
|
|
729
|
-
- **`
|
|
765
|
+
- **`24-signalbox_test.mjs`** -- the `signalBox` / `computedBox` allocation-light handle API, **activated in 1.5.0** (committed `{skip:true}` since 1.3.0, now running against the real implementation). 12 tests: box get/set/peek/update, `computedBox` derive + memoize, peek-does-not-track, subscribe fires-and-untracks, box<->callable interop both directions, batch coalescing (including set-then-revert net no-op), dispose with ABA-safety, the `equals` short-circuit, `computedBox.peek`, and the top-level helpers bound to the default registry.
|
|
766
|
+
- **`27-create-root_test.mjs`** -- `createRoot` (1.5.0), the ownership escape hatch. A watcher spawned inside a consumer effect via `createRoot` survives the consumer's re-run (the exact `lite-query` lazy-watcher pattern); the contrast case confirms an *unwrapped* spawn is cascade-disposed; `createRoot` returns `fn`'s value, detaches tracking in `fn`'s direct body while inner effect bodies still track, and composes with box handles.
|
|
767
|
+
- **`25-devtools-real-boot_test.mjs`** -- Devtools/Studio contract (10 tests). Boots the actual `Devtools.js` against the 1.5.0 engine and exercises all 19 Devtools exports plus the 10 symbols Studio imports from Devtools. Pins the ghost contract: heavy introspection (graph walk, owner-tree, observer descriptors) adds **zero** nodes to the live graph. Catches the real-rig failure mode where importing the package by its own name from a repo whose `package.json` declares `name: "@zakkster/lite-signal"` resolves to the published build instead of the local engine.
|
|
730
768
|
- **`26-free-list-invariant_test.mjs`** -- the 1.2.2 audit's cleanliness pins (3 invariant tests + 1 targeted coverage test). Asserts directly -- by inspecting freshly-allocated nodes through the documented `describe()` -> `NODE_PTR` introspection protocol -- that the `ReactiveNode` constructor and the fresh-pool-growth path initialize the ten fields the audit removed from `createNode` to identical values, so the deleted writes were defending against a state the engine cannot produce on a clean free list. The 4th test covers the swallow-on-self-dispose-then-throw branch in `pullComputed` (the path that lifted branch coverage from 98.07% to 98.43%).
|
|
731
769
|
|
|
732
770
|
```bash
|
|
@@ -834,7 +872,8 @@ The cross-framework reactivity suite agrees independently, re-run on **1.3.0** (
|
|
|
834
872
|
- **1.2.0** -- the **ownership hybrid**: an owner tree so nested effects/computeds auto-dispose with their parent (closes conformance #209 / #210, matching Solid's `createRoot` ergonomics). Plus three additive features built on the same internal split: pre-batch revert (`batch(() => { a.set(99); a.set(10); })` doesn't re-fire), multi-throw `AggregateError`, and scheduler-thunk caching with an ABA gen guard. *Shipped.*
|
|
835
873
|
- **1.3.0** -- the **pool minor**: node and link pools become growable and incrementally populated. New `prealloc` config (`"eager"` default | `"lazy"`) chooses up-front vs on-demand construction; `onCapacityExceeded: "grow"` extends pools via chunked refill (runs of up to 1024 links / 256 nodes, ledger doubles) bounded by the 16x link ceiling; `maxFlushPasses` is now a public config. Internally the propagation mark phase moved to an intrusive linked-list stack (a `nextMark` field) -- the only node-shape change. The hot paths and public callable API are byte-identical to 1.2.2; steady-state zero-GC is unchanged. *Shipped.*
|
|
836
874
|
- **1.4.0** -- the **observability minor**: `stats()` gains three cumulative lifecycle counters (`totalAllocations`, `totalDisposals`, `poolGrowths`), the surface reserved for it in the 1.2.x/1.3.0 notes. Monotonic over the registry's life, reset by `destroy()`, bumped on the existing acquire/dispose/grow edges -- no hot-path change, no public callable API change. This is what lite-devtools / lite-studio read to chart allocation rate, pool-reuse ratio, and graph churn. Drop-in over 1.3.0. *Shipped (beta).*
|
|
837
|
-
- **1.5** -- the `signalBox` / `computedBox`
|
|
875
|
+
- **1.5.0** -- the **API-surface minor**: two non-callable, allocation-light primitives `signalBox` / `computedBox` land alongside the callable `signal` / `computed` (same `ReactiveNode`, full interop, ~1.7x cheaper construction), and **`createRoot`** lands as the ownership escape hatch the owner tree was designed for (detached scope for lazily spawning long-lived nodes from inside a consumer effect -- the pattern `lite-query` needs). The callable API, hot paths, and `stats()` shape are unchanged; the `24-signalbox` suite (staged since 1.3.0) now runs and passes. *Shipped (alpha).*
|
|
876
|
+
- **Next** -- `runWithOwner` (the re-attach companion to `createRoot`); the pull-mode recursion depth limit (~5,000 chained computeds) remains the main outstanding architectural item.
|
|
838
877
|
|
|
839
878
|
> Note: the retracking rewrite that closes the dynamic-topology gap shipped in **1.1.4**, not a future release. The earlier roadmap that listed it under "v1.2" is superseded.
|
|
840
879
|
|
package/Signal.d.ts
CHANGED
|
@@ -43,7 +43,7 @@ export type Dispose = () => void;
|
|
|
43
43
|
* a {@link Computed}, or an effect's {@link Dispose} function. Passing an
|
|
44
44
|
* unrelated value is a safe no-op.
|
|
45
45
|
*/
|
|
46
|
-
export type Disposable<T = unknown> = Signal<T> | Computed<T> | Dispose;
|
|
46
|
+
export type Disposable<T = unknown> = Signal<T> | Computed<T> | SignalBox<T> | ComputedBox<T> | Dispose;
|
|
47
47
|
|
|
48
48
|
// --- Reactive primitive shapes ------------------------------------------------
|
|
49
49
|
|
|
@@ -71,6 +71,38 @@ export interface Computed<T> {
|
|
|
71
71
|
subscribe(fn: (value: T) => void): Dispose;
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Allocation-light, non-callable signal (1.5.0). A plain object on a shared
|
|
76
|
+
* prototype rather than a callable function -- cheaper to construct than
|
|
77
|
+
* {@link Signal} (no closure allocation), with an identical zero-GC read/write
|
|
78
|
+
* path. Interoperates freely with callable handles in the same graph.
|
|
79
|
+
*/
|
|
80
|
+
export interface SignalBox<T> {
|
|
81
|
+
/** Read the current value, tracking the read if inside an effect or computed. */
|
|
82
|
+
get(): T;
|
|
83
|
+
/** Overwrite the value. No-op if equal under the box's equality predicate. */
|
|
84
|
+
set(value: T): void;
|
|
85
|
+
/** Read the value WITHOUT tracking. */
|
|
86
|
+
peek(): T;
|
|
87
|
+
/** Functional update: `set(fn(currentValue))`. Reads the current value without tracking. */
|
|
88
|
+
update(fn: (current: T) => T): void;
|
|
89
|
+
/** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
|
|
90
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Allocation-light, non-callable computed (1.5.0). The derived counterpart to
|
|
95
|
+
* {@link SignalBox}: `{ get, peek, subscribe }`, no `set` / `update`.
|
|
96
|
+
*/
|
|
97
|
+
export interface ComputedBox<T> {
|
|
98
|
+
/** Resolve the value, tracking the read if inside an effect or computed. */
|
|
99
|
+
get(): T;
|
|
100
|
+
/** Resolve the value WITHOUT tracking. */
|
|
101
|
+
peek(): T;
|
|
102
|
+
/** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
|
|
103
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
104
|
+
}
|
|
105
|
+
|
|
74
106
|
// --- Diagnostics --------------------------------------------------------------
|
|
75
107
|
|
|
76
108
|
export interface RegistryStats {
|
|
@@ -141,7 +173,7 @@ export interface ObserveObserversHooks {
|
|
|
141
173
|
export type Unobserve = () => void;
|
|
142
174
|
|
|
143
175
|
/** Anything carrying a node identity that the introspection surface can read. */
|
|
144
|
-
export type ReactiveHandle = Signal<any> | Computed<any>;
|
|
176
|
+
export type ReactiveHandle = Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any>;
|
|
145
177
|
|
|
146
178
|
// --- Graph-mutation hook (1.2.1) ----------------------------------------------
|
|
147
179
|
|
|
@@ -221,10 +253,25 @@ export interface Registry {
|
|
|
221
253
|
signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
|
|
222
254
|
computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
|
|
223
255
|
effect(fn: () => void, opts?: EffectOptions): Dispose;
|
|
256
|
+
/** Allocation-light, non-callable signal (1.5.0). See {@link SignalBox}. */
|
|
257
|
+
signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
258
|
+
/** Allocation-light, non-callable computed (1.5.0). See {@link ComputedBox}. */
|
|
259
|
+
computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
260
|
+
/**
|
|
261
|
+
* Run `fn` in a detached ownership scope (1.5.0). Effects/computeds created
|
|
262
|
+
* directly in `fn` are NOT adopted by the enclosing owner, so they survive
|
|
263
|
+
* the enclosing effect's re-runs and disposal -- the caller owns their
|
|
264
|
+
* lifecycle (`fn` typically returns a disposer or the created handle). Both
|
|
265
|
+
* ownership and tracking are detached for the duration of `fn`; inner
|
|
266
|
+
* effect/computed bodies still establish their own scopes. The ownership
|
|
267
|
+
* escape hatch for lazily spawning a long-lived node from inside a consumer
|
|
268
|
+
* effect (e.g. a query watcher). Returns whatever `fn` returns.
|
|
269
|
+
*/
|
|
270
|
+
createRoot<T>(fn: () => T): T;
|
|
224
271
|
/**
|
|
225
272
|
* Universal disposal for anything created by this registry: signals,
|
|
226
|
-
* computeds, or effect dispose handles. Cross-registry calls are
|
|
227
|
-
* no-ops (each registry owns its own private node-identity Symbol).
|
|
273
|
+
* computeds, boxes, or effect dispose handles. Cross-registry calls are
|
|
274
|
+
* silent no-ops (each registry owns its own private node-identity Symbol).
|
|
228
275
|
* Passing an unrelated value is also a safe no-op.
|
|
229
276
|
*/
|
|
230
277
|
dispose(api: Disposable): void;
|
|
@@ -295,6 +342,12 @@ export function setDefaultRegistry(registry: Registry): void;
|
|
|
295
342
|
export function signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
|
|
296
343
|
export function computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
|
|
297
344
|
export function effect(fn: () => void, opts?: EffectOptions): Dispose;
|
|
345
|
+
/** Allocation-light, non-callable signal (1.5.0), bound to the default registry. See {@link SignalBox}. */
|
|
346
|
+
export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
347
|
+
/** Allocation-light, non-callable computed (1.5.0), bound to the default registry. See {@link ComputedBox}. */
|
|
348
|
+
export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
349
|
+
/** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
|
|
350
|
+
export function createRoot<T>(fn: () => T): T;
|
|
298
351
|
/** Universal disposal -- see {@link Registry.dispose}. */
|
|
299
352
|
export function dispose(api: Disposable): void;
|
|
300
353
|
export function batch<T>(fn: () => T): T;
|
package/Signal.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @zakkster/lite-signal v1.
|
|
2
|
+
* @zakkster/lite-signal v1.5.0
|
|
3
3
|
* --------------------
|
|
4
4
|
* Hybrid Doubly-Linked-List Reactive Graph Engine -- decoupled (Signal1_3) base
|
|
5
5
|
* with the two 1.1.3 performance fixes ported in:
|
|
@@ -48,11 +48,13 @@
|
|
|
48
48
|
* -- OWNER vs OBSERVER --
|
|
49
49
|
* `currentObserver` = the node whose READS establish dependencies (tracking).
|
|
50
50
|
* `currentOwner` = the node that OWNS anything created right now (lifecycle).
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
51
|
+
* They move together by default, but are distinct pointers so ownership can be
|
|
52
|
+
* detached without affecting tracking. createRoot (1.5.0) uses this: it nulls
|
|
53
|
+
* the OWNER (and OBSERVER) for the duration of a callback so nodes created
|
|
54
|
+
* inside survive the enclosing scope's re-runs; runWithOwner (re-attaching to a
|
|
55
|
+
* chosen owner) remains future work on the same split. untrack suppresses
|
|
56
|
+
* tracking without orphaning created nodes. createNode and onCleanup key off
|
|
57
|
+
* the OWNER; the read fast-path and allocateLink key off the OBSERVER.
|
|
56
58
|
*/
|
|
57
59
|
|
|
58
60
|
const FLAG_COMPUTED = 1 << 0;
|
|
@@ -1132,6 +1134,162 @@ export function createRegistry(config) {
|
|
|
1132
1134
|
return read;
|
|
1133
1135
|
}
|
|
1134
1136
|
|
|
1137
|
+
// --- 1.5: signalBox / computedBox -- non-callable, allocation-light API ------
|
|
1138
|
+
//
|
|
1139
|
+
// The callable signal()/computed() pay an irreducible per-primitive cost: a
|
|
1140
|
+
// `read` closure + (for signals) a `set` closure, both capturing `node` and
|
|
1141
|
+
// `birthGen`. That is the price of the ergonomic `count()` / `count.set(x)`
|
|
1142
|
+
// surface, and it is why creation can't reach alien-signals territory on the
|
|
1143
|
+
// callable path (Andrii's analysis; confirmed empirically).
|
|
1144
|
+
//
|
|
1145
|
+
// signalBox() trades the call ergonomics for allocation: it returns a PLAIN
|
|
1146
|
+
// OBJECT whose methods live on a shared prototype, so creation allocates one
|
|
1147
|
+
// object and writes two own props (NODE_PTR, NODE_GEN) -- zero closures. The
|
|
1148
|
+
// graph machinery underneath is identical; a box and a callable handle wrap
|
|
1149
|
+
// the same kind of ReactiveNode and interoperate freely in one graph.
|
|
1150
|
+
//
|
|
1151
|
+
// const s = registry.signalBox(0);
|
|
1152
|
+
// s.get(); s.set(1); s.peek(); s.update(n => n+1); s.subscribe(fn);
|
|
1153
|
+
//
|
|
1154
|
+
// Hot-path note: get()/set() resolve the node via this[NODE_PTR] (one prop
|
|
1155
|
+
// load) instead of a lexical capture. On a monomorphic box shape V8 compiles
|
|
1156
|
+
// that to a pointer-offset load; the cost vs the callable closure is in the
|
|
1157
|
+
// low single digits on read-heavy graphs and is the explicit, documented
|
|
1158
|
+
// tradeoff for the creation win.
|
|
1159
|
+
|
|
1160
|
+
function boxGet() {
|
|
1161
|
+
const node = this[NODE_PTR];
|
|
1162
|
+
if (node.gen !== this[NODE_GEN]) return undefined; // stale: slot recycled (ABA guard)
|
|
1163
|
+
if (isTrackingDeps && currentObserver !== null) {
|
|
1164
|
+
const expected = activeObserverCurrentDep;
|
|
1165
|
+
if (expected !== null && expected.source === node) {
|
|
1166
|
+
activeObserverCurrentDep = expected.nextDep;
|
|
1167
|
+
} else {
|
|
1168
|
+
allocateLink(node, currentObserver);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
return node.value;
|
|
1172
|
+
}
|
|
1173
|
+
function boxSet(value) {
|
|
1174
|
+
const node = this[NODE_PTR];
|
|
1175
|
+
if (node.gen !== this[NODE_GEN]) return;
|
|
1176
|
+
const eq = node.equals;
|
|
1177
|
+
if (eq && eq(node.value, value)) return;
|
|
1178
|
+
if (batchDepth > 0 && node.revertEpoch !== batchEpoch) {
|
|
1179
|
+
node.preBatchValue = node.value;
|
|
1180
|
+
node.preBatchVersion = node.version;
|
|
1181
|
+
node.revertEpoch = batchEpoch;
|
|
1182
|
+
}
|
|
1183
|
+
node.value = value;
|
|
1184
|
+
if (batchDepth > 0 && node.revertEpoch === batchEpoch && eq && eq(node.preBatchValue, value)) {
|
|
1185
|
+
node.version = node.preBatchVersion;
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
globalVersion = (globalVersion + 1) | 0;
|
|
1189
|
+
node.version = globalVersion;
|
|
1190
|
+
markDownstream(node);
|
|
1191
|
+
if (batchDepth === 0) flushEffects();
|
|
1192
|
+
}
|
|
1193
|
+
function boxPeek() {
|
|
1194
|
+
const node = this[NODE_PTR];
|
|
1195
|
+
if (node.gen !== this[NODE_GEN]) return undefined;
|
|
1196
|
+
return node.value;
|
|
1197
|
+
}
|
|
1198
|
+
function boxUpdate(fn) {
|
|
1199
|
+
const node = this[NODE_PTR];
|
|
1200
|
+
if (node.gen !== this[NODE_GEN]) return;
|
|
1201
|
+
boxSet.call(this, fn(node.value));
|
|
1202
|
+
}
|
|
1203
|
+
// Subscribe drives an effect that reads this box's value untracked-in-callback.
|
|
1204
|
+
// Mirrors sharedSubscribe but calls get() through `this` (boxes aren't callable).
|
|
1205
|
+
function boxSubscribe(fn) {
|
|
1206
|
+
const box = this;
|
|
1207
|
+
return effect(() => {
|
|
1208
|
+
const val = box.get();
|
|
1209
|
+
const prevTracking = isTrackingDeps;
|
|
1210
|
+
isTrackingDeps = false;
|
|
1211
|
+
try { fn(val); } finally { isTrackingDeps = prevTracking; }
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
function boxComputedGet() {
|
|
1215
|
+
const node = this[NODE_PTR];
|
|
1216
|
+
if (node.gen !== this[NODE_GEN]) return undefined;
|
|
1217
|
+
if (isTrackingDeps && currentObserver !== null) {
|
|
1218
|
+
const expected = activeObserverCurrentDep;
|
|
1219
|
+
if (expected !== null && expected.source === node) {
|
|
1220
|
+
activeObserverCurrentDep = expected.nextDep;
|
|
1221
|
+
} else {
|
|
1222
|
+
allocateLink(node, currentObserver);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
return pullComputed(node);
|
|
1226
|
+
}
|
|
1227
|
+
function boxComputedPeek() {
|
|
1228
|
+
const node = this[NODE_PTR];
|
|
1229
|
+
if (node.gen !== this[NODE_GEN]) return undefined;
|
|
1230
|
+
return pullComputed(node);
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// Shared prototypes -- methods defined once per registry, inherited by every box.
|
|
1234
|
+
const SIGNAL_BOX_PROTO = {
|
|
1235
|
+
get: boxGet,
|
|
1236
|
+
set: boxSet,
|
|
1237
|
+
peek: boxPeek,
|
|
1238
|
+
update: boxUpdate,
|
|
1239
|
+
subscribe: boxSubscribe,
|
|
1240
|
+
};
|
|
1241
|
+
const COMPUTED_BOX_PROTO = {
|
|
1242
|
+
get: boxComputedGet,
|
|
1243
|
+
peek: boxComputedPeek,
|
|
1244
|
+
subscribe: boxSubscribe,
|
|
1245
|
+
};
|
|
1246
|
+
|
|
1247
|
+
/**
|
|
1248
|
+
* Allocation-light, non-callable signal. Returns a plain object on a shared
|
|
1249
|
+
* prototype: `{ get, set, peek, update, subscribe }`. Interoperates with
|
|
1250
|
+
* callable signal()/computed() in the same graph.
|
|
1251
|
+
* @template T
|
|
1252
|
+
* @param {T} initial
|
|
1253
|
+
* @param {object} [opts]
|
|
1254
|
+
* @param {(a:T,b:T)=>boolean} [opts.equals=Object.is]
|
|
1255
|
+
* @returns {SignalBox<T>}
|
|
1256
|
+
*/
|
|
1257
|
+
function signalBox(initial, opts) {
|
|
1258
|
+
const node = createNode(initial, FLAG_SIGNAL);
|
|
1259
|
+
node.equals = (opts !== undefined && opts.equals !== undefined) ? opts.equals : OBJECT_IS;
|
|
1260
|
+
node.version = globalVersion;
|
|
1261
|
+
statSignals++;
|
|
1262
|
+
// Object.create(proto) allocates the box already on the shared prototype's
|
|
1263
|
+
// map -- no setPrototypeOf transition (which deopts the object to dictionary
|
|
1264
|
+
// mode and blows the method-call ICs to megamorphic). Own props are then
|
|
1265
|
+
// added in a stable order, keeping every box monomorphic.
|
|
1266
|
+
const box = Object.create(SIGNAL_BOX_PROTO);
|
|
1267
|
+
box[NODE_PTR] = node;
|
|
1268
|
+
box[NODE_GEN] = node.gen;
|
|
1269
|
+
return box;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
/**
|
|
1273
|
+
* Allocation-light, non-callable computed. Returns `{ get, peek, subscribe }`
|
|
1274
|
+
* on a shared prototype.
|
|
1275
|
+
* @template T
|
|
1276
|
+
* @param {() => T} fn
|
|
1277
|
+
* @param {object} [opts]
|
|
1278
|
+
* @param {(a:T,b:T)=>boolean} [opts.equals=Object.is]
|
|
1279
|
+
* @returns {ComputedBox<T>}
|
|
1280
|
+
*/
|
|
1281
|
+
function computedBox(fn, opts) {
|
|
1282
|
+
const node = createNode(undefined, FLAG_COMPUTED);
|
|
1283
|
+
node.computeFn = fn;
|
|
1284
|
+
node.equals = (opts !== undefined && opts.equals !== undefined) ? opts.equals : OBJECT_IS;
|
|
1285
|
+
statComputeds++;
|
|
1286
|
+
const box = Object.create(COMPUTED_BOX_PROTO);
|
|
1287
|
+
box[NODE_PTR] = node;
|
|
1288
|
+
box[NODE_GEN] = node.gen;
|
|
1289
|
+
return box;
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
|
|
1135
1293
|
/**
|
|
1136
1294
|
* Create an eagerly-run side effect that re-executes whenever its tracked
|
|
1137
1295
|
* dependencies change. The body runs synchronously on creation.
|
|
@@ -1281,6 +1439,40 @@ export function createRegistry(config) {
|
|
|
1281
1439
|
}
|
|
1282
1440
|
}
|
|
1283
1441
|
|
|
1442
|
+
/**
|
|
1443
|
+
* Run `fn` in a detached ownership scope: nodes (effects / computeds)
|
|
1444
|
+
* created inside `fn` are NOT adopted by the enclosing owner, so they
|
|
1445
|
+
* survive the enclosing effect's re-runs and disposal. Use this for
|
|
1446
|
+
* long-lived reactive work spawned lazily from inside a consumer effect
|
|
1447
|
+
* (e.g. a query watcher created on first read) -- without it, the
|
|
1448
|
+
* enclosing effect owns the watcher and cascade-disposes it on its next
|
|
1449
|
+
* run. The caller is responsible for disposing anything created here
|
|
1450
|
+
* (there is no owner to do it automatically).
|
|
1451
|
+
*
|
|
1452
|
+
* Detaches BOTH ownership and tracking for the duration of `fn`, so reads
|
|
1453
|
+
* performed directly in `fn` (outside any inner effect/computed body) do
|
|
1454
|
+
* not link the enclosing observer either. Inner effect/computed bodies
|
|
1455
|
+
* establish their own owner+observer scopes as usual.
|
|
1456
|
+
*
|
|
1457
|
+
* Mirrors Solid's `createRoot` for the lifecycle axis. Returns whatever
|
|
1458
|
+
* `fn` returns (typically a disposer or the created handle).
|
|
1459
|
+
*/
|
|
1460
|
+
function createRoot(fn) {
|
|
1461
|
+
const prevOwner = currentOwner;
|
|
1462
|
+
const prevObserver = currentObserver;
|
|
1463
|
+
const prevTracking = isTrackingDeps;
|
|
1464
|
+
currentOwner = null;
|
|
1465
|
+
currentObserver = null;
|
|
1466
|
+
isTrackingDeps = false;
|
|
1467
|
+
try {
|
|
1468
|
+
return fn();
|
|
1469
|
+
} finally {
|
|
1470
|
+
currentOwner = prevOwner;
|
|
1471
|
+
currentObserver = prevObserver;
|
|
1472
|
+
isTrackingDeps = prevTracking;
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1284
1476
|
/**
|
|
1285
1477
|
* Register a function to run when the enclosing effect/computed re-runs or
|
|
1286
1478
|
* is disposed. Cascade order on disposal is inside-out: an effect's owned
|
|
@@ -1310,7 +1502,8 @@ export function createRegistry(config) {
|
|
|
1310
1502
|
* monotonic over the registry's life and reset only by {@link destroy}; sample
|
|
1311
1503
|
* them over time to derive allocation rate, pool-reuse ratio, and graph churn
|
|
1312
1504
|
* without the engine computing rates itself. In a quiescent registry
|
|
1313
|
-
* `totalAllocations - totalDisposals === activeNodes`.
|
|
1505
|
+
* `totalAllocations - totalDisposals === activeNodes`. Box nodes
|
|
1506
|
+
* (`signalBox` / `computedBox`) are counted exactly as callable nodes.
|
|
1314
1507
|
* @returns {RegistryStats}
|
|
1315
1508
|
*/
|
|
1316
1509
|
function stats() {
|
|
@@ -1504,7 +1697,7 @@ export function createRegistry(config) {
|
|
|
1504
1697
|
while (l !== null) { const nx = l.nextDep; fn(describeNode(l.source)); l = nx; }
|
|
1505
1698
|
}
|
|
1506
1699
|
|
|
1507
|
-
return {signal, computed, effect, dispose, batch, untrack, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
|
|
1700
|
+
return {signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
|
|
1508
1701
|
}
|
|
1509
1702
|
|
|
1510
1703
|
// -----------------------------------------------------------------
|
|
@@ -1525,6 +1718,14 @@ export function computed(fn, opts) {
|
|
|
1525
1718
|
return defaultRegistry.computed(fn, opts);
|
|
1526
1719
|
}
|
|
1527
1720
|
|
|
1721
|
+
export function signalBox(initial, opts) {
|
|
1722
|
+
return defaultRegistry.signalBox(initial, opts);
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
export function computedBox(fn, opts) {
|
|
1726
|
+
return defaultRegistry.computedBox(fn, opts);
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1528
1729
|
export function effect(fn, opts) {
|
|
1529
1730
|
return defaultRegistry.effect(fn, opts);
|
|
1530
1731
|
}
|
|
@@ -1540,6 +1741,9 @@ export function batch(fn) {
|
|
|
1540
1741
|
export function untrack(fn) {
|
|
1541
1742
|
return defaultRegistry.untrack(fn);
|
|
1542
1743
|
}
|
|
1744
|
+
export function createRoot(fn) {
|
|
1745
|
+
return defaultRegistry.createRoot(fn);
|
|
1746
|
+
}
|
|
1543
1747
|
|
|
1544
1748
|
/**
|
|
1545
1749
|
* True iff a read RIGHT NOW would record a dependency on the default registry.
|
package/llms.txt
CHANGED
|
@@ -16,6 +16,8 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
16
16
|
- **Signal**: root reactive cell. `signal(initial, { equals? })` returns a function. Call it to read (tracked), use `.peek()` to read without tracking, `.set(v)` to notify downstream, `.update(fn)` for read-modify-write, `.subscribe(fn)` for an effect-backed listener.
|
|
17
17
|
- **Computed**: lazy memoized derivation. `computed(fn, { equals? })`. Cache hits return in O(deps) (version comparison only). Cache misses re-run the body and refresh `evalVersion`. Errors are cached via `FLAG_HAS_ERROR` and re-thrown on every read until a dep changes.
|
|
18
18
|
- **Effect**: side-effect runner. `effect(fn, { scheduler? })`. Runs immediately on creation, then on any tracked dep change. Returns a dispose function. Optional scheduler defers execution (e.g., to rAF, microtask, custom frame loop).
|
|
19
|
+
- **Box (1.5.0)**: non-callable, allocation-light variants. `signalBox(initial, { equals? })` returns `{ get, set, peek, update, subscribe }`; `computedBox(fn, { equals? })` returns `{ get, peek, subscribe }` (no set/update -- derived). Same `ReactiveNode` and zero-GC read/write path as the callable forms, full interop in one graph (a callable can read `box.get()` and vice versa). Construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle, not a closure). Built on a shared prototype from the start -- never `setPrototypeOf` (which would deopt the method-call ICs to megamorphic). Exported as registry methods and top-level helpers.
|
|
20
|
+
- **createRoot (1.5.0)**: `createRoot(fn)` runs `fn` in a detached ownership scope and returns `fn`'s value. Effects/computeds created directly in `fn` are NOT adopted by the enclosing owner, so they survive its re-runs/disposal (the caller owns their lifecycle). Both ownership and tracking are detached for `fn`'s direct body; inner effect/computed bodies still establish their own scopes. The escape hatch for lazily spawning a long-lived node from inside a consumer effect (e.g. `lite-query`'s query-watcher) -- without it, the consumer owns the watcher and cascade-disposes it on its next re-run. Mirrors Solid's `createRoot`. The re-attach companion `runWithOwner` is named in the engine as the intended second half and is not yet shipped.
|
|
19
21
|
- **dispose(api)**: universal disposal. Accepts a signal, computed, or effect dispose handle; idempotent; cross-registry calls are silent no-ops (per-registry `Symbol("node_ptr")` keys the node-identity slot on the returned API function, foreign signals fail the lookup and fall through). Passing an unrelated value is also safe; passing an arbitrary function invokes it (effect-handle contract).
|
|
20
22
|
- **Batch**: `batch(fn)` defers effect flush until the outermost batch closes. Nestable.
|
|
21
23
|
- **Untrack**: `untrack(fn)` reads without subscribing.
|
|
@@ -50,7 +52,39 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
50
52
|
|
|
51
53
|
## Version notes
|
|
52
54
|
|
|
53
|
-
- **1.
|
|
55
|
+
- **1.5.0-alpha** (current): the **API-surface minor**. Two non-callable,
|
|
56
|
+
allocation-light primitives -- `signalBox(initial, opts?)` returning
|
|
57
|
+
`{ get, set, peek, update, subscribe }` and `computedBox(fn, opts?)` returning
|
|
58
|
+
`{ get, peek, subscribe }` -- land alongside the callable `signal` / `computed`,
|
|
59
|
+
plus **`createRoot(fn)`** as the ownership escape hatch. **The callable API, hot
|
|
60
|
+
paths, and `stats()` shape (11 keys) are unchanged from 1.4.0**; this is an
|
|
61
|
+
additive surface, not a second engine. Boxes wrap the same `ReactiveNode` and
|
|
62
|
+
interoperate freely with callables in one graph (verified both directions);
|
|
63
|
+
ownership, batching, glitch-freedom, and introspection apply uniformly, and box
|
|
64
|
+
nodes count in `stats().signals` / `computeds` exactly as callable nodes. Box
|
|
65
|
+
construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle
|
|
66
|
+
with two own props added in fixed order -- never `setPrototypeOf`, which would
|
|
67
|
+
transition the object to dictionary mode and blow the method-call ICs to
|
|
68
|
+
megamorphic); the read/write hot path stays zero-GC (200k box writes through a
|
|
69
|
+
256-wide graph: 0 heap growth, 0 pool growths). `createRoot` runs `fn` with
|
|
70
|
+
`currentOwner` and `currentObserver` (and the tracking flag) nulled, so
|
|
71
|
+
effects/computeds created directly in `fn` are not adopted by the enclosing owner
|
|
72
|
+
and survive its re-runs/disposal -- the sanctioned opt-out for lazily spawning a
|
|
73
|
+
long-lived watcher from inside a consumer effect (`lite-query`'s pattern);
|
|
74
|
+
unwrapped, the consumer owns the watcher and cascade-disposes it. Inner
|
|
75
|
+
effect/computed bodies still establish their own scopes; `createRoot` returns
|
|
76
|
+
whatever `fn` returns. The owner/observer split (1.2.0) made `currentOwner` and
|
|
77
|
+
`currentObserver` distinct precisely so ownership could be detached without
|
|
78
|
+
affecting tracking; `createRoot` is the first of the two named primitives
|
|
79
|
+
(`runWithOwner`, the re-attach half, is not yet shipped). The `24-signalbox`
|
|
80
|
+
suite (staged `{skip:true}` since 1.3.0) now runs and passes. **Tests:** 439
|
|
81
|
+
total, 438 pass, 0 fail, **1 skip** (only the architecturally-N/A SSR case in
|
|
82
|
+
`17-reactivity`; the 9 signalBox tests are now active, +6 `createRoot` tests in
|
|
83
|
+
`test/27-create-root_test.mjs`, +3 box-coverage tests). **Coverage:** `Signal.js`
|
|
84
|
+
100% statements / 97.35% branches / 100% functions / 100% lines; `Watch.js` 100%.
|
|
85
|
+
Drop-in over 1.4.0.
|
|
86
|
+
|
|
87
|
+
- **1.4.0-beta** (drop-in over 1.3.0): the **observability minor**. `stats()` gains three
|
|
54
88
|
cumulative lifecycle counters -- `totalAllocations`, `totalDisposals`,
|
|
55
89
|
`poolGrowths` -- the surface reserved for 1.4.0 in the 1.2.x/1.3.0 notes, now
|
|
56
90
|
delivered. **The hot paths and public callable API are byte-identical to 1.3.0**;
|
|
@@ -290,7 +324,10 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
290
324
|
function signal<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): Signal<T>;
|
|
291
325
|
function computed<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): Computed<T>;
|
|
292
326
|
function effect(fn: () => void, opts?: { scheduler?: (run: () => void) => void }): Dispose;
|
|
293
|
-
function
|
|
327
|
+
function signalBox<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): SignalBox<T>; // 1.5.0
|
|
328
|
+
function computedBox<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): ComputedBox<T>; // 1.5.0
|
|
329
|
+
function createRoot<T>(fn: () => T): T; // 1.5.0 -- detached ownership scope; returns fn's value
|
|
330
|
+
function dispose(api: Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any> | Dispose): void;
|
|
294
331
|
function batch<T>(fn: () => T): T;
|
|
295
332
|
function untrack<T>(fn: () => T): T;
|
|
296
333
|
function isTracking(): boolean;
|
|
@@ -329,6 +366,20 @@ interface Computed<T> {
|
|
|
329
366
|
subscribe(fn: (value: T) => void): Dispose;
|
|
330
367
|
}
|
|
331
368
|
|
|
369
|
+
interface SignalBox<T> { // 1.5.0 -- non-callable, allocation-light
|
|
370
|
+
get(): T; // tracked read
|
|
371
|
+
set(value: T): void;
|
|
372
|
+
peek(): T; // untracked read
|
|
373
|
+
update(fn: (prev: T) => T): void;
|
|
374
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
interface ComputedBox<T> { // 1.5.0
|
|
378
|
+
get(): T; // tracked read
|
|
379
|
+
peek(): T; // untracked read
|
|
380
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
381
|
+
}
|
|
382
|
+
|
|
332
383
|
type Dispose = () => void;
|
|
333
384
|
|
|
334
385
|
interface NodeDescriptor { // yielded by forEachObserver / forEachSource / describe
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zakkster/lite-signal",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0-alpha",
|
|
4
4
|
"description": "Zero-GC reactive graph. Monomorphic object pool, versioned push-pull propagation, 32-bit modular versioning. Built for hot paths and long-running processes.",
|
|
5
5
|
"author": "Zahary Shinikchiev <shinikchiev@yahoo.com>",
|
|
6
6
|
"license": "MIT",
|