@zakkster/lite-signal 1.9.0-preview.4 → 1.9.0-preview.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,52 @@ 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.9.0-preview.5] -- 2026-08-18
8
+
9
+ Packaging-only cut. **The engine is UNCHANGED** -- `Signal.js` is behaviourally
10
+ byte-identical to `preview.4`; the sole `Signal.js` edit is the header banner
11
+ version string (see below). This release makes the published package honour its
12
+ own `package.json`: since 1.5.0 the manifest has advertised `"types":
13
+ "./Signal.d.ts"` and listed `Signal.d.ts` in `files[]`, but the 1.9.0 line
14
+ shipped without the file (`preview.4` and earlier packed a `types` pointer to a
15
+ non-existent declaration, so `tsc` consumers got no types). No API, torture, or
16
+ test change from `preview.4`.
17
+
18
+ ### Added -- the missing `Signal.d.ts` (the 1.9.0 type surface)
19
+
20
+ - **`Signal.d.ts`** now ships, modelled on the 1.8.0 declaration (1.9.0's export
21
+ surface is byte-identical to 1.8.0's) plus the 1.9.0 explicit-resource-management
22
+ delta: `[Symbol.dispose](): void` is typed on exactly the handles the engine
23
+ stamps -- both box prototypes (`SignalBox` :1495, `ComputedBox` :1496), every
24
+ `Dispose` function (the shared effect disposer at :1614, reached by `effect()`,
25
+ `.subscribe()`, and the `createScope` disposer at :1853), and the `Registry`
26
+ (-> `destroy`, :2087). Callable value handles (`Signal` / `Computed`) are left
27
+ UNSTAMPED, matching the engine. So `using r = createRegistry()`,
28
+ `using box = signalBox(0)`, and `using stop = effect(fn)` all typecheck.
29
+ - The `[Symbol.dispose]` slot is expressed through a `lib`-conditional helper
30
+ (`ExplicitDisposeSlot`): it resolves to the member only when the ambient
31
+ TypeScript `lib` knows `Symbol.dispose` (`esnext.disposable` -- required to use
32
+ `using` at all), and to `{}` otherwise, so the declaration NEVER forces a `lib`
33
+ upgrade on type-only consumers. Verified: compiles under
34
+ `--lib ES2022,ESNext.Disposable` with `using` on all four shapes; compiles clean
35
+ under `--lib ES2020` for a type-only consumer (zero errors); manual
36
+ `[Symbol.dispose]()` is typed.
37
+
38
+ ### Changed -- header banner reconciled to the manifest
39
+
40
+ - **`Signal.js` header banner** now reads `v1.9.0-preview.5`, matching
41
+ `package.json` and this changelog. `preview.2` through `preview.4` shipped a
42
+ stale `preview.2` banner (a cosmetic drift in a comment; no code depended on
43
+ it). No other line of `Signal.js` changed -- torture stays 22/22 and the unit
44
+ suite is unaffected.
45
+
46
+ ## [1.9.0-preview.4] -- 2026-08-18
47
+
48
+ Version-only re-tag over `preview.3`. `Signal.js` is byte-identical to
49
+ `preview.3` past the header banner; no engine, torture, test, API, or packaging
50
+ change (the `Signal.d.ts` gap and the stale `preview.2` banner were both still
51
+ present -- both are fixed in `preview.5`). Recorded here for continuity.
52
+
7
53
  ## [1.9.0-preview.3] -- 2026-08-18
8
54
 
9
55
  Verification-only parity cut. **The engine is UNCHANGED** -- `Signal.js` (2209
package/Signal.d.ts ADDED
@@ -0,0 +1,542 @@
1
+ /**
2
+ * @zakkster/lite-signal -- zero-GC reactive graph.
3
+ *
4
+ * Public type surface for the JavaScript implementation in `Signal.js`.
5
+ *
6
+ * 1.9.0 adds explicit-resource-management (`using` / `Symbol.dispose`) on
7
+ * lifecycle objects. The engine is otherwise 1.8.0: same exports, same runtime
8
+ * surface. The only type-level delta is the `[Symbol.dispose]()` slot the 1.9.0
9
+ * engine stamps on every disposable handle -- both box prototypes, the
10
+ * `Registry`, and every `Dispose` function (effect / `.subscribe()` /
11
+ * `createScope`). Callable value handles (`Signal` / `Computed`) are NOT
12
+ * stamped, matching the engine. See {@link ExplicitDisposeSlot} for how the
13
+ * slot degrades on TypeScript `lib` targets that predate `Symbol.dispose`.
14
+ */
15
+
16
+ /**
17
+ * The `[Symbol.dispose]()` method the 1.9.0 engine stamps on every disposable
18
+ * handle. Expressed so it never forces a `lib` upgrade: when the ambient
19
+ * TypeScript `lib` knows `Symbol.dispose` (`esnext.disposable` -- required to
20
+ * use `using` at all) this resolves to `{ [Symbol.dispose](): void }` and the
21
+ * `using` declaration typechecks; on any older `lib` the key is `never`, the
22
+ * member vanishes, and these types stay usable as plain values. The runtime
23
+ * mirrors this exactly -- `Signal.js` feature-detects `Symbol.dispose` and only
24
+ * stamps the slot when the host provides it (Node 20+ for manual
25
+ * `[Symbol.dispose]()`, Node 24+ for `using`).
26
+ */
27
+ export type ExplicitDisposeSlot = {
28
+ [K in typeof Symbol extends { readonly dispose: infer S } ? S : never]: () => void;
29
+ };
30
+
31
+ // --- Options ------------------------------------------------------------------
32
+
33
+ /** Equality predicate. Returning `true` halts propagation. */
34
+ export type EqualsFn<T> = (a: T, b: T) => boolean;
35
+
36
+ /** Options accepted by {@link signal}. */
37
+ export interface SignalOptions<T> {
38
+ /** Custom equality predicate. Default: `Object.is`. */
39
+ equals?: EqualsFn<T>;
40
+ }
41
+
42
+ /** Options accepted by {@link computed}. */
43
+ export interface ComputedOptions<T> {
44
+ /** Custom equality predicate. Default: `Object.is`. */
45
+ equals?: EqualsFn<T>;
46
+ }
47
+
48
+ /**
49
+ * Scheduler trampoline. The implementation must call the supplied `run` callback
50
+ * at most once. `requestAnimationFrame`, `queueMicrotask`, and `setTimeout`
51
+ * shapes are all compatible (wrap them if their signature differs).
52
+ */
53
+ export type EffectScheduler = (run: () => void) => void;
54
+
55
+ /** Options accepted by {@link effect}. */
56
+ export interface EffectOptions {
57
+ /** Optional scheduler. If supplied, the effect's first run and every
58
+ * subsequent re-run is deferred through this trampoline. */
59
+ scheduler?: EffectScheduler;
60
+ }
61
+
62
+ /**
63
+ * Idempotent dispose handle returned by {@link effect}, `.subscribe()`, and the
64
+ * scope disposer of {@link Registry.createScope}. Callable as a plain function;
65
+ * from 1.9.0 it ALSO carries `[Symbol.dispose]` (routing to the same idempotent,
66
+ * gen-guarded disposer), so `using stop = effect(...)` disposes at block exit.
67
+ */
68
+ export type Dispose = (() => void) & ExplicitDisposeSlot;
69
+
70
+ /**
71
+ * Cleanup returned from an effect body (1.8.0, Reflex pattern A).
72
+ * Runs before the next re-run and once on dispose, appended after any
73
+ * `onCleanup(fn)` registered in the same body (they compose in call order).
74
+ */
75
+ export type EffectCleanup = () => void;
76
+
77
+ /**
78
+ * An effect body. Returning a function registers it as a cleanup (1.8.0);
79
+ * any other return value is ignored. Computeds are NOT affected -- a computed
80
+ * returning a function keeps treating that function as its value.
81
+ */
82
+ export type EffectBody = () => void | EffectCleanup;
83
+
84
+ /**
85
+ * Anything that can be passed to {@link Registry.dispose}: a {@link Signal},
86
+ * a {@link Computed}, or an effect's {@link Dispose} function. Passing an
87
+ * unrelated value is a safe no-op.
88
+ */
89
+ export type Disposable<T = unknown> = Signal<T> | Computed<T> | SignalBox<T> | ComputedBox<T> | Dispose;
90
+
91
+ // --- Reactive primitive shapes ------------------------------------------------
92
+
93
+ /** Reactive source of truth. */
94
+ export interface Signal<T> {
95
+ /** Read the current value, tracking the read if inside an effect or computed. */
96
+ (): T;
97
+ /** Read the value WITHOUT tracking. */
98
+ peek(): T;
99
+ /** Overwrite the value. No-op if equal under the signal's equality predicate. */
100
+ set(value: T): void;
101
+ /** Functional update: `set(fn(currentValue))`. Reads the current value without tracking. */
102
+ update(fn: (current: T) => T): void;
103
+ /** Subscribe to value changes. Fires immediately with the current value. */
104
+ subscribe(fn: (value: T) => void): Dispose;
105
+ }
106
+
107
+ /** Lazy memoised derivation. */
108
+ export interface Computed<T> {
109
+ /** Resolve the value, tracking the read if inside an effect or computed. */
110
+ (): T;
111
+ /** Resolve the value WITHOUT tracking. */
112
+ peek(): T;
113
+ /** Subscribe to value changes. Fires immediately with the current value. */
114
+ subscribe(fn: (value: T) => void): Dispose;
115
+ }
116
+
117
+ /** Method surface of {@link SignalBox}; see that type for the full contract. */
118
+ interface SignalBoxMembers<T> {
119
+ /** Read the current value, tracking the read if inside an effect or computed. */
120
+ get(): T;
121
+ /** Overwrite the value. No-op if equal under the box's equality predicate. */
122
+ set(value: T): void;
123
+ /** Read the value WITHOUT tracking. */
124
+ peek(): T;
125
+ /** Functional update: `set(fn(currentValue))`. Reads the current value without tracking. */
126
+ update(fn: (current: T) => T): void;
127
+ /** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
128
+ subscribe(fn: (value: T) => void): Dispose;
129
+ }
130
+
131
+ /**
132
+ * Allocation-light, non-callable signal (1.5.0). A plain object on a shared
133
+ * prototype rather than a callable function -- cheaper to construct than
134
+ * {@link Signal} (no closure allocation), with an identical zero-GC read/write
135
+ * path. Interoperates freely with callable handles in the same graph.
136
+ *
137
+ * From 1.9.0 the shared prototype carries `[Symbol.dispose]` (-> `dispose(box)`),
138
+ * so `using box = signalBox(0)` disposes the box at block exit.
139
+ */
140
+ export type SignalBox<T> = SignalBoxMembers<T> & ExplicitDisposeSlot;
141
+
142
+ /** Method surface of {@link ComputedBox}; see that type for the full contract. */
143
+ interface ComputedBoxMembers<T> {
144
+ /** Resolve the value, tracking the read if inside an effect or computed. */
145
+ get(): T;
146
+ /** Resolve the value WITHOUT tracking. */
147
+ peek(): T;
148
+ /** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
149
+ subscribe(fn: (value: T) => void): Dispose;
150
+ }
151
+
152
+ /**
153
+ * Allocation-light, non-callable computed (1.5.0). The derived counterpart to
154
+ * {@link SignalBox}: `{ get, peek, subscribe }`, no `set` / `update`.
155
+ *
156
+ * From 1.9.0 the shared prototype carries `[Symbol.dispose]` (-> `dispose(box)`),
157
+ * so `using box = computedBox(fn)` disposes the box at block exit.
158
+ */
159
+ export type ComputedBox<T> = ComputedBoxMembers<T> & ExplicitDisposeSlot;
160
+
161
+ // --- Diagnostics --------------------------------------------------------------
162
+
163
+ export interface RegistryStats {
164
+ /** Number of signals created in this registry's lifetime. */
165
+ signals: number;
166
+ /** Number of computeds created in this registry's lifetime. */
167
+ computeds: number;
168
+ /** Number of effects currently alive (decrements on dispose). */
169
+ effects: number;
170
+ /** Number of dependency links currently in use. */
171
+ activeLinks: number;
172
+ /** Dependency links available in the pool (ledger-based: `linkPoolCapacity - activeLinks`). */
173
+ pooledLinks: number;
174
+ /** Link-pool capacity ledger. Doubles under the `"grow"` policy; under `"lazy"`
175
+ * prealloc it may exceed the count of physically constructed links. */
176
+ linkPoolCapacity: number;
177
+ /** Node-pool capacity ledger. Doubles under the `"grow"` policy; under `"lazy"`
178
+ * prealloc it may exceed the count of physically constructed nodes. */
179
+ nodePoolCapacity: number;
180
+ /** Number of nodes currently allocated (signals + computeds + alive effects). */
181
+ activeNodes: number;
182
+ /**
183
+ * Cumulative count of every node acquired over the registry's life -- whether
184
+ * popped from the free list or freshly constructed during a pool-growth chunk.
185
+ * Monotonic; reset only by {@link Registry.destroy}. The true total ever handed
186
+ * out, not the live count (`activeNodes` is the live gauge). Added in 1.4.0.
187
+ */
188
+ totalAllocations: number;
189
+ /**
190
+ * Cumulative count of every node returned to the pool (`disposeNode`). Monotonic;
191
+ * reset only by {@link Registry.destroy}. In a quiescent registry
192
+ * `totalAllocations - totalDisposals === activeNodes`. Added in 1.4.0.
193
+ */
194
+ totalDisposals: number;
195
+ /**
196
+ * Cumulative count of pool-growth chunks -- incremented whenever a node *or* link
197
+ * refill pushes capacity past its current ledger. Nonzero after warm-up means the
198
+ * initial pool was undersized and grew at runtime; an eager pool sized for its
199
+ * workload keeps this at 0. Reset only by {@link Registry.destroy}. Added in 1.4.0.
200
+ */
201
+ poolGrowths: number;
202
+ /**
203
+ * Cumulative count of effect-flush drain passes. Advances once per pass, only
204
+ * while a mutation-hook listener is attached (gated by the same `mutationHook !==
205
+ * null` check that admits opcodes 6 and 7); frozen otherwise, so the steady-state
206
+ * write path is byte-identical to 1.5.0. Combined with `totalAllocations` and
207
+ * `poolGrowths`, lets devtools chart flush activity alongside allocation rate
208
+ * without the engine itself computing rates. Reset by {@link Registry.destroy}.
209
+ * Added in 1.6.0.
210
+ */
211
+ flushPasses: number;
212
+ }
213
+
214
+ // --- Observer-lifecycle introspection (1.1.4) ---------------------------------
215
+
216
+ /** Whether a described node is a signal, a computed, or an effect. */
217
+ export type NodeKind = "signal" | "computed" | "effect";
218
+
219
+ /** Non-perturbing snapshot of a graph neighbour yielded by the `forEach*` walkers. */
220
+ export interface NodeDescriptor {
221
+ /** Stable per-allocation node id (1.1.5+). Dedupe key for graph traversal, and the
222
+ * re-walk handle: a descriptor may be passed back into forEachObserver/forEachSource. */
223
+ id: number;
224
+ kind: NodeKind;
225
+ /** The node's current value (last stored/computed value; an effect's is its body return). */
226
+ value: unknown;
227
+ }
228
+
229
+ /** Transition callbacks for {@link Registry.observeObservers}. */
230
+ export interface ObserveObserversHooks {
231
+ /** Fired on the 0->1 observer transition (after registration). */
232
+ onConnect?: () => void;
233
+ /** Fired on the 1->0 observer transition. */
234
+ onDisconnect?: () => void;
235
+ }
236
+
237
+ /** Stops an {@link Registry.observeObservers} subscription. Idempotent. */
238
+ export type Unobserve = () => void;
239
+
240
+ /** Anything carrying a node identity that the introspection surface can read. */
241
+ export type ReactiveHandle = Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any>;
242
+
243
+ // --- Graph-mutation hook (1.2.1) ----------------------------------------------
244
+
245
+ /**
246
+ * Opcode passed as the first argument to a {@link GraphMutationListener}.
247
+ *
248
+ * - `1` node create. `(intA, intB) = (node.id, node.flags)`.
249
+ * - `2` node dispose. `(intA, intB) = (node.id, node.flags)` -- fires for every node
250
+ * disposed, including cascaded owner-tree children.
251
+ * - `3` link add. `(intA, intB) = (source.id, target.id)`.
252
+ * - `4` link remove. `(intA, intB) = (source.id, target.id)` -- `-1` if the link
253
+ * was already nulled (defensive, rare).
254
+ * - `5` recompute. `(intA, intB) = (node.id, 0)` -- fires just before an effect
255
+ * re-run or a computed re-eval.
256
+ */
257
+ export type GraphMutationOpcode = 1 | 2 | 3 | 4 | 5;
258
+
259
+ /**
260
+ * Listener registered with {@link Registry.onGraphMutation}. Called synchronously
261
+ * inside each mutation point with three integers -- no objects allocated.
262
+ *
263
+ * **Contract: observe only.** Listeners MUST NOT throw and MUST NOT mutate the
264
+ * graph from inside the callback. Both will corrupt the engine's state. Wrap any
265
+ * downstream work in a microtask if it could touch the registry.
266
+ */
267
+ export type GraphMutationListener = (opcode: GraphMutationOpcode, intA: number, intB: number) => void;
268
+
269
+ /** Idempotent unsubscriber returned by {@link Registry.onGraphMutation}. */
270
+ export type GraphMutationUnsubscribe = () => void;
271
+
272
+ // --- Errors -------------------------------------------------------------------
273
+
274
+ /** Thrown when a pool ceiling is hit. */
275
+ export class CapacityError extends Error {
276
+ readonly name: "CapacityError";
277
+ readonly kind: "nodes" | "links";
278
+ readonly capacity: number;
279
+ constructor(kind: "nodes" | "links", capacity: number);
280
+ }
281
+
282
+ // --- Registry -----------------------------------------------------------------
283
+
284
+ export interface RegistryConfig {
285
+ /** Initial node-pool capacity (a ledger under `prealloc: "lazy"`). Default: 1024. */
286
+ maxNodes?: number;
287
+ /** Initial link-pool capacity (a ledger under `prealloc: "lazy"`). Default: `maxNodes * 4`. */
288
+ maxLinks?: number;
289
+ /**
290
+ * Pool population strategy. Default: `"eager"`.
291
+ * - `"eager"`: construct the full `maxNodes` / `maxLinks` pools up front.
292
+ * Deterministic latency -- zero allocation inside any subsequent hot path
293
+ * (the contract for render loops, game ticks, and extension frame budgets),
294
+ * at the cost of a larger resident heap that every major GC traces.
295
+ * - `"lazy"`: treat `maxNodes` / `maxLinks` as capacity ledgers and construct
296
+ * nodes/links on first demand, recycling through the free lists thereafter.
297
+ * Smaller heap, faster cold start, lighter GC marking; identical zero-GC
298
+ * steady state after warm-up. Prefer for footprint-sensitive or short-lived
299
+ * registries.
300
+ */
301
+ prealloc?: "eager" | "lazy";
302
+ /**
303
+ * Behaviour when a pool is exhausted. Default: `"throw"`.
304
+ * - `"throw"`: throw {@link CapacityError} immediately when the pool is full.
305
+ * - `"grow"`: extend the pool on demand. Growth is chunked and incremental
306
+ * (contiguous runs of up to 1024 links / 256 nodes per free-list miss),
307
+ * not a single doubling burst, so any one growth pause stays bounded. The
308
+ * capacity ledger still doubles, keeping {@link RegistryStats} semantics
309
+ * unchanged. Link growth is bounded by a hard ceiling of `maxLinks * 16`.
310
+ */
311
+ onCapacityExceeded?: "throw" | "grow";
312
+ /** Max effect-queue drain passes before a flush-cycle `Error` (message prefixed `"CycleError:"`) is thrown. Default: 100. */
313
+ maxFlushPasses?: number;
314
+ }
315
+
316
+ /** Method surface of {@link Registry}; see that type for the full contract. */
317
+ interface RegistryMembers {
318
+ signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
319
+ computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
320
+ effect(fn: EffectBody, opts?: EffectOptions): Dispose;
321
+ /** Allocation-light, non-callable signal (1.5.0). See {@link SignalBox}. */
322
+ signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
323
+ /** Allocation-light, non-callable computed (1.5.0). See {@link ComputedBox}. */
324
+ computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
325
+ /**
326
+ * Run `fn` in a detached ownership scope (1.5.0). Effects/computeds created
327
+ * directly in `fn` are NOT adopted by the enclosing owner, so they survive
328
+ * the enclosing effect's re-runs and disposal -- the caller owns their
329
+ * lifecycle (`fn` typically returns a disposer or the created handle). Both
330
+ * ownership and tracking are detached for the duration of `fn`; inner
331
+ * effect/computed bodies still establish their own scopes. The ownership
332
+ * escape hatch for lazily spawning a long-lived node from inside a consumer
333
+ * effect (e.g. a query watcher). Returns whatever `fn` returns.
334
+ */
335
+ createRoot<T>(fn: () => T): T;
336
+ /**
337
+ * Run `fn(dispose)` in a detached, untracked scope and return whatever `fn`
338
+ * returns (1.6.0). The single `dispose` argument cascade-disposes every effect
339
+ * and computed created inside `fn`. Lifecycle complement to {@link createRoot}:
340
+ * `createRoot` only *detaches* (caller must dispose each child by hand),
341
+ * `createScope` *adopts*, so one disposer tears down a subtree of unknown shape
342
+ * -- the per-item lifecycle a keyed-list or scene reconciler needs. Plain
343
+ * signals created directly in `fn` are NOT adopted (consistent with the 1.2.0
344
+ * ownership rule); computeds and effects are. The owner never re-runs, so
345
+ * direct-body reads in `fn` are untracked; reactive bindings belong in inner
346
+ * effect/computed bodies. A scope created inside a consumer effect SURVIVES
347
+ * that consumer's re-run -- the reconciler-critical detach property. The
348
+ * disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
349
+ * resolves to the owner effect under `describe` / `nodeId` / `forEachOwned`.
350
+ */
351
+ createScope<T>(fn: (dispose: () => void) => T): T;
352
+ /**
353
+ * Universal disposal for anything created by this registry: signals,
354
+ * computeds, boxes, or effect dispose handles. Cross-registry calls are
355
+ * silent no-ops (each registry owns its own private node-identity Symbol).
356
+ * Passing an unrelated value is also a safe no-op.
357
+ */
358
+ dispose(api: Disposable): void;
359
+ batch<T>(fn: () => T): T;
360
+ untrack<T>(fn: () => T): T;
361
+ /** True iff a read RIGHT NOW would record a dependency on this registry.
362
+ * False inside `untrack`, `subscribe` callbacks, `onCleanup` bodies, and
363
+ * outside any observer. Use for lazy-allocation wrappers like lite-store. */
364
+ isTracking(): boolean;
365
+ /** O(1): does this source have at least one live observer right now? A `peek` does not count. */
366
+ hasObservers(handle: ReactiveHandle): boolean;
367
+ /** Auto-pause hook: fires `onConnect` on the 0->1 observer transition and `onDisconnect`
368
+ * on 1->0, after registration (transition-only -- no immediate fire if already observed).
369
+ * Re-tracking a persistently-read source does not churn. Returns an idempotent unobserve.
370
+ * @throws TypeError if `handle` is not a reactive handle. */
371
+ observeObservers(handle: ReactiveHandle, hooks?: ObserveObserversHooks): Unobserve;
372
+ /** Walk the observers (subscribers) of `handle`, newest-first. No-op on a non-handle. */
373
+ forEachObserver(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
374
+ /** Walk the sources (dependencies) of `handle`. No-op on a non-handle. */
375
+ forEachSource(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
376
+ /** Walk the owned children of `handle` -- nodes whose lifetime is bound to this
377
+ * one by the 1.2 owner tree (1.2.1+). Top-level handles and signals have no
378
+ * owned children; effects/computeds may own nested observers created inside
379
+ * their bodies. No-op on a non-handle or stale handle. */
380
+ forEachOwned(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
381
+ /** Descriptor of `handle`'s owner, or `undefined` for top-level handles, stale
382
+ * handles, or non-handles (1.2.1+). The owner is the effect or computed inside
383
+ * whose body `handle` was created -- the node that will cascade-dispose it
384
+ * on re-run or explicit dispose. */
385
+ ownerOf(handle: ReactiveHandle): NodeDescriptor | undefined;
386
+ /** Stable node id of `handle` (1.1.5+), or undefined for a non-handle or stale handle. */
387
+ nodeId(handle: ReactiveHandle): number | undefined;
388
+ /** The own descriptor of `handle` (1.1.5+), or undefined for a non-handle or stale handle.
389
+ * Re-walkable: the returned descriptor may be passed back into forEachObserver/
390
+ * forEachSource/forEachOwned/ownerOf. Descriptors are gen-stamped (1.2.1+): a
391
+ * descriptor obtained pre-recycle goes stale and walks as undefined post-recycle. */
392
+ describe(handle: ReactiveHandle): NodeDescriptor | undefined;
393
+ /** Register a single graph-mutation listener (1.2.1+). Replaces any existing
394
+ * listener and returns an unsubscribe that restores the previous one on call.
395
+ * Listener is invoked synchronously at each mutation point with three integers:
396
+ * `(opcode, intA, intB)` -- see {@link GraphMutationOpcode}. Cost when no
397
+ * listener is registered: one branch-predicted `null` check per mutation point.
398
+ * @throws TypeError if `fn` is not a function or null. */
399
+ onGraphMutation(fn: GraphMutationListener | null): GraphMutationUnsubscribe;
400
+ onCleanup(fn: () => void): void;
401
+ stats(): RegistryStats;
402
+ /** Reset everything: nodes, links, queues, global clock. Outstanding dispose
403
+ * closures become safe no-ops. Outstanding read/set closures still reference
404
+ * pool slots -- they will silently misbehave; use a fresh registry afterwards. */
405
+ destroy(): void;
406
+ }
407
+
408
+ /**
409
+ * Isolated reactive graph. Created by {@link createRegistry}.
410
+ *
411
+ * From 1.9.0 the registry carries `[Symbol.dispose]` (-> `destroy`), so
412
+ * `using r = createRegistry()` resets its pools at block exit.
413
+ */
414
+ export type Registry = RegistryMembers & ExplicitDisposeSlot;
415
+
416
+ /**
417
+ * Create an isolated reactive registry.
418
+ *
419
+ * @example
420
+ * const r = createRegistry({ maxNodes: 4096, onCapacityExceeded: "grow" });
421
+ * const count = r.signal(0);
422
+ * r.effect(() => console.log(count()));
423
+ */
424
+ export function createRegistry(config?: RegistryConfig): Registry;
425
+
426
+ /** Replace the default registry backing the top-level helpers. */
427
+ export function setDefaultRegistry(registry: Registry): void;
428
+
429
+ // --- Top-level helpers (delegate to default registry) ------------------------
430
+
431
+ export function signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
432
+ export function computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
433
+ export function effect(fn: EffectBody, opts?: EffectOptions): Dispose;
434
+ /** Allocation-light, non-callable signal (1.5.0), bound to the default registry. See {@link SignalBox}. */
435
+ export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
436
+ /** Allocation-light, non-callable computed (1.5.0), bound to the default registry. See {@link ComputedBox}. */
437
+ export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
438
+ /** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
439
+ export function createRoot<T>(fn: () => T): T;
440
+ /** Run `fn(dispose)` in a detached, adopting scope (1.6.0), bound to the default registry. See {@link Registry.createScope}. */
441
+ export function createScope<T>(fn: (dispose: () => void) => T): T;
442
+ /** Universal disposal -- see {@link Registry.dispose}. */
443
+ export function dispose(api: Disposable): void;
444
+ export function batch<T>(fn: () => T): T;
445
+ export function untrack<T>(fn: () => T): T;
446
+ /** Top-level binding of {@link Registry.isTracking} against the default registry. */
447
+ export function isTracking(): boolean;
448
+ /** Top-level binding of {@link Registry.hasObservers}. */
449
+ export function hasObservers(handle: ReactiveHandle): boolean;
450
+ /** Top-level binding of {@link Registry.observeObservers}. */
451
+ export function observeObservers(handle: ReactiveHandle, hooks?: ObserveObserversHooks): Unobserve;
452
+ /** Top-level binding of {@link Registry.forEachObserver}. */
453
+ export function forEachObserver(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
454
+ /** Top-level binding of {@link Registry.forEachSource}. */
455
+ export function forEachSource(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
456
+ /** Top-level binding of {@link Registry.forEachOwned} (1.2.1+). */
457
+ export function forEachOwned(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
458
+ /** Top-level binding of {@link Registry.ownerOf} (1.2.1+). */
459
+ export function ownerOf(handle: ReactiveHandle): NodeDescriptor | undefined;
460
+ /** Top-level binding of {@link Registry.nodeId}. */
461
+ export function nodeId(handle: ReactiveHandle): number | undefined;
462
+ /** Top-level binding of {@link Registry.describe}. */
463
+ export function describe(handle: ReactiveHandle): NodeDescriptor | undefined;
464
+ /** Top-level binding of {@link Registry.onGraphMutation} (1.2.1+). */
465
+ export function onGraphMutation(fn: GraphMutationListener | null): GraphMutationUnsubscribe;
466
+ export function onCleanup(fn: () => void): void;
467
+ export function stats(): RegistryStats;
468
+ export function destroy(): void;
469
+
470
+ /**
471
+ * Configuration options for the watch utility.
472
+ */
473
+ export interface WatchOptions {
474
+ /** * If true, fires the callback immediately upon registration
475
+ * with `oldValue` set to `undefined`.
476
+ */
477
+ immediate?: boolean;
478
+ }
479
+
480
+ /**
481
+ * Track a reactive source and run a callback whenever its projected value
482
+ * changes. The callback receives `(newValue, oldValue, stop)` -- the third
483
+ * argument is a dispose function that can be called from inside the callback
484
+ * to terminate the watcher.
485
+ *
486
+ * Internal reads inside the callback are untracked.
487
+ *
488
+ * Uses `Object.is` to guard against the raw-getter case where a dep mutation
489
+ * fires the effect but the projected value is unchanged.
490
+ *
491
+ * @param source Reactive read function.
492
+ * @param callback Called with the new and previous values plus a stop handle.
493
+ * @param options `immediate: true` runs the callback once on registration
494
+ * with `oldValue = undefined`.
495
+ * @returns Dispose function. Idempotent and safe to call at any time, including
496
+ * synchronously during the immediate callback.
497
+ */
498
+ export function watch<T>(
499
+ source: () => T,
500
+ callback: (newValue: T, oldValue: T | undefined, stop: () => void) => void,
501
+ options?: { immediate?: boolean }
502
+ ): () => void;
503
+
504
+ /**
505
+ * Fire `callback` exactly once when `predicate` first returns a truthy value,
506
+ * then auto-dispose. If `predicate` is already truthy at registration, fires
507
+ * synchronously.
508
+ *
509
+ * @param predicate Reactive read function; callback fires when truthy.
510
+ * @param callback Called once when predicate first truthy. Reads inside are untracked.
511
+ * @returns Dispose function. Call before predicate fires to cancel; idempotent.
512
+ */
513
+ export function when(
514
+ predicate: () => unknown,
515
+ callback: () => void
516
+ ): () => void;
517
+
518
+ /**
519
+ * Promise-returning variant of {@link when}. The returned promise resolves
520
+ * when `predicate` first returns a truthy value.
521
+ *
522
+ * ! **HOT-PATH WARNING -- DO NOT USE PER FRAME.** This function calls
523
+ * `new Promise(...)`, which is a heap allocation (one Promise object plus
524
+ * executor closure plus internal infrastructure per call). Promises require
525
+ * heap allocation by the language spec -- this cost is unavoidable.
526
+ *
527
+ * **Use for:** high-level scene/UI orchestration, boot sequences, awaiting
528
+ * user input or network state, level transitions. Anything that runs once
529
+ * or rarely.
530
+ *
531
+ * **NEVER use for:** per-frame entity updates, render-loop logic, animation
532
+ * tick handlers. For zero-GC hot-path logic use {@link when} with a callback.
533
+ *
534
+ * Note: this promise never rejects. If the predicate never becomes truthy,
535
+ * the promise never settles. Wrap in `Promise.race` for timeout semantics.
536
+ *
537
+ * @param predicate Reactive read function; resolves promise when truthy.
538
+ * @returns Promise that resolves when predicate first truthy.
539
+ */
540
+ export function whenAsync(
541
+ predicate: () => unknown
542
+ ): Promise<void>;
package/Signal.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @zakkster/lite-signal v1.9.0-preview.2
2
+ * @zakkster/lite-signal v1.9.0-preview.5
3
3
  * Copyright (c) Zahary Shinikchiev <shinikchiev@yahoo.com>
4
4
  * MIT License
5
5
  * --------------------
package/llms.txt CHANGED
@@ -53,10 +53,36 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
53
53
 
54
54
  ## Version notes
55
55
 
56
- - **1.9.0-preview.3** (current): the **verification-surface parity cut**. No engine
57
- change from preview.2 -- `Signal.js` is byte-identical (its header banner still
58
- reads `preview.2`) and `bench/torture/` stays out of `files[]`; for consumers
59
- preview.3 is preview.2 plus a version number. It brings the torture suite to full
56
+ - **1.9.0-preview.5** (current): a **packaging-only cut** -- the engine is
57
+ behaviourally unchanged from preview.4 (`Signal.js` differs only in its header
58
+ banner string). Two fixes make the tarball honour its own manifest. (1) The
59
+ promised **`Signal.d.ts` now ships**: since 1.5.0 `package.json` has advertised
60
+ `"types": "./Signal.d.ts"` and listed it in `files[]`, but the 1.9.0 line packed
61
+ a `types` pointer to a file that did not exist, so `tsc` consumers got no types.
62
+ The declaration is modelled on 1.8.0's (1.9.0's export surface is byte-identical
63
+ to 1.8.0's) plus the 1.9.0 delta: `[Symbol.dispose](): void` typed on exactly the
64
+ handles the engine stamps -- both box prototypes, every `Dispose` function
65
+ (effect / `.subscribe()` / `createScope`), and the `Registry` (-> `destroy`) --
66
+ with callable `Signal`/`Computed` handles left UNSTAMPED, matching the engine, so
67
+ `using r = createRegistry()`, `using box = signalBox(0)`, and `using stop =
68
+ effect(fn)` all typecheck. The `[Symbol.dispose]` slot is behind a `lib`-conditional
69
+ helper that resolves to `{}` on TypeScript `lib` targets predating `Symbol.dispose`,
70
+ so it never forces a `lib` upgrade on type-only consumers (verified: `using`
71
+ compiles under `esnext.disposable`; a type-only consumer compiles clean under
72
+ `ES2020`). (2) The **`Signal.js` header banner** is reconciled to `preview.5`
73
+ (preview.2 through preview.4 carried a stale `preview.2` banner in the comment).
74
+ No API, torture, or test change: torture stays 22/22, unit **512/511/0/1** under
75
+ `npm test` and **520/519/0/1** under `npm run test:gc`. Drop-in over preview.4.
76
+
77
+ - **1.9.0-preview.4**: a **version-only re-tag** over preview.3. `Signal.js` is
78
+ byte-identical to preview.3 past the header banner; no engine, torture, test, API,
79
+ or packaging change (the missing `Signal.d.ts` and the stale `preview.2` banner
80
+ were both still present -- fixed in preview.5). Recorded for continuity.
81
+
82
+ - **1.9.0-preview.3**: the **verification-surface parity cut**. No engine
83
+ change from preview.2 -- `Signal.js` is byte-identical (at this cut the header
84
+ banner still read `preview.2`; reconciled in preview.5) and `bench/torture/` stays
85
+ out of `files[]`; for consumers preview.3 is preview.2 plus a version number. It brings the torture suite to full
60
86
  parity with the shipped 1.4.4 canonical: a parity port of the last three scenarios
61
87
  -- `error-torture` (throwing effect bodies: single re-thrown unwrapped, two-or-more
62
88
  aggregated into an `AggregateError` carrying exactly those errors, survivors still
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zakkster/lite-signal",
3
- "version": "1.9.0-preview.4",
3
+ "version": "1.9.0-preview.5",
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",