@pyreon/reactivity 0.23.0 → 0.24.1

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/lib/lpih.js ADDED
@@ -0,0 +1,177 @@
1
+ import { o as getFireSummaries } from "./_chunks/reactive-devtools-BCpGoGZ5.js";
2
+
3
+ //#region src/lpih.ts
4
+ /**
5
+ * Live Program Inlay Hints — runtime bridge.
6
+ *
7
+ * Writes the current `getFireSummaries()` snapshot to a JSON file that
8
+ * the LSP server reads via the `PYREON_LPIH_CACHE` env var. This is the
9
+ * file-cache bridge mechanism — chosen over IPC/WebSocket because:
10
+ *
11
+ * 1. LSP servers are stdio-only — they can't easily talk to a browser.
12
+ * 2. Filesystem is a universal lowest-common-denominator transport.
13
+ * 3. The runtime side writes (atomic rename); the LSP side reads.
14
+ * 4. The LSP re-reads the file on every inlay-hint request, so live
15
+ * edits land immediately without coordination.
16
+ *
17
+ * Two consumer modes:
18
+ *
19
+ * **Dev-server polled mode**: a dev-server hook calls
20
+ * `writeLpihCache(path)` on every signal write or at a regular interval
21
+ * (e.g. 250ms throttle). The LSP picks it up on next inlay-hint request.
22
+ *
23
+ * **On-demand mode**: a test harness or devtools UI calls
24
+ * `writeLpihCache(path)` explicitly when it wants the LSP to see the
25
+ * current state.
26
+ *
27
+ * Atomic write semantics: writes to `<path>.tmp.<pid>.<seq>` then renames
28
+ * to `<path>`. Readers (the LSP server) never see a half-written file.
29
+ *
30
+ * Zero-cost when devtools is inactive: `getFireSummaries()` returns []
31
+ * unless `activateReactiveDevtools()` has been called. So calling
32
+ * `writeLpihCache()` against an inactive registry writes an empty
33
+ * `{ fires: [] }` — cheap, correct.
34
+ */
35
+ let _seq = 0;
36
+ /**
37
+ * Canonical filename for the LPIH cache file. Co-located with the
38
+ * project — convention: `<cwd>/.pyreon-lpih.json`. The dot-prefix marks
39
+ * it as a hidden / generated file by filesystem convention; the
40
+ * extension makes its contents grep-able as JSON.
41
+ *
42
+ * @internal — exported for tests + symmetry with the LSP-side default.
43
+ */
44
+ const LPIH_DEFAULT_FILENAME = ".pyreon-lpih.json";
45
+ /**
46
+ * Resolve the default LPIH cache path for the current process. The path
47
+ * is **`<cwd>/.pyreon-lpih.json`** — co-located with the project so the
48
+ * LSP can auto-discover it by walking up from any source file.
49
+ *
50
+ * Returns null in environments without `process.cwd()` (e.g. a fresh
51
+ * web worker without polyfills) — callers should fall back to an
52
+ * explicit path argument.
53
+ *
54
+ * @example
55
+ * import { startLpihPolling, getDefaultLpihCachePath } from '@pyreon/reactivity/lpih'
56
+ * console.log(getDefaultLpihCachePath()) // → '/Users/me/proj/.pyreon-lpih.json'
57
+ * startLpihPolling() // writes to that path
58
+ */
59
+ function getDefaultLpihCachePath() {
60
+ if (typeof process === "undefined") return null;
61
+ const proc = process;
62
+ if (typeof proc.cwd !== "function") return null;
63
+ try {
64
+ return `${proc.cwd().replace(/[/\\]+$/, "")}/${LPIH_DEFAULT_FILENAME}`;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+ /**
70
+ * Snapshot `getFireSummaries()` and write it to `path` atomically.
71
+ * Returns the number of fires written.
72
+ *
73
+ * **Path resolution**: when `path` is omitted, defaults to
74
+ * `<cwd>/.pyreon-lpih.json` (`getDefaultLpihCachePath()`). The LSP
75
+ * auto-discovers this convention by walking up from any source file to
76
+ * the nearest `package.json` — so projects that use the default need
77
+ * zero env-var configuration.
78
+ *
79
+ * Errors (filesystem permission, EACCES, etc.) are caught and re-thrown
80
+ * — the caller decides whether to swallow them. The runtime side wraps
81
+ * this in a try/catch when called from hot paths.
82
+ *
83
+ * Throws if `path` is omitted AND no default can be resolved (e.g.
84
+ * a web worker without `process.cwd()`).
85
+ *
86
+ * @example
87
+ * import { activateReactiveDevtools } from '@pyreon/reactivity'
88
+ * import { writeLpihCache } from '@pyreon/reactivity/lpih'
89
+ *
90
+ * activateReactiveDevtools()
91
+ * await writeLpihCache() // → writes to <cwd>/.pyreon-lpih.json
92
+ * // The LSP server auto-discovers this path; no env var needed.
93
+ */
94
+ async function writeLpihCache(path) {
95
+ const resolvedPath = path ?? getDefaultLpihCachePath();
96
+ if (resolvedPath === null) throw new Error("[lpih] writeLpihCache: no path provided and no default could be resolved (process.cwd() unavailable). Pass an explicit path.");
97
+ return await _writeToPath(resolvedPath);
98
+ }
99
+ async function _writeToPath(path) {
100
+ const summaries = getFireSummaries();
101
+ const payload = { fires: summaries.map((s) => ({
102
+ file: s.loc.file,
103
+ line: s.loc.line,
104
+ count: s.count,
105
+ kind: s.kind,
106
+ lastFire: s.lastFire,
107
+ rate1s: s.rate1s
108
+ })) };
109
+ const tmp = `${path}.tmp.${typeof process !== "undefined" && "pid" in process ? process.pid ?? 0 : 0}.${++_seq}`;
110
+ const fs = await import("node:fs/promises");
111
+ try {
112
+ await fs.writeFile(tmp, JSON.stringify(payload), "utf8");
113
+ await fs.rename(tmp, path);
114
+ } catch (err) {
115
+ try {
116
+ await fs.unlink(tmp);
117
+ } catch {}
118
+ throw err;
119
+ }
120
+ return summaries.length;
121
+ }
122
+ /**
123
+ * Polling helper: call `writeLpihCache(path)` every `intervalMs`. Returns
124
+ * a disposer that stops the timer.
125
+ *
126
+ * **Path resolution**: same as `writeLpihCache` — `path` defaults to
127
+ * `<cwd>/.pyreon-lpih.json` when omitted. The LSP auto-discovers this
128
+ * convention so projects need zero configuration.
129
+ *
130
+ * Useful for dev servers that want the LSP to see live updates. The
131
+ * interval is throttled (not debounced); a fast-firing signal won't
132
+ * generate one write per fire. 250-500ms is the recommended range.
133
+ *
134
+ * Throws synchronously if `path` is omitted AND no default can be
135
+ * resolved — the caller catches this once at startup rather than
136
+ * silently never writing.
137
+ *
138
+ * @example
139
+ * import { activateReactiveDevtools } from '@pyreon/reactivity'
140
+ * import { startLpihPolling } from '@pyreon/reactivity/lpih'
141
+ *
142
+ * if (import.meta.env.DEV) {
143
+ * activateReactiveDevtools()
144
+ * startLpihPolling() // writes to <cwd>/.pyreon-lpih.json every 250ms
145
+ * }
146
+ */
147
+ function startLpihPolling(path, intervalMs = 250) {
148
+ const resolvedPath = path ?? getDefaultLpihCachePath();
149
+ if (resolvedPath === null) throw new Error("[lpih] startLpihPolling: no path provided and no default could be resolved (process.cwd() unavailable). Pass an explicit path.");
150
+ return _startPollingAt(resolvedPath, intervalMs);
151
+ }
152
+ function _startPollingAt(path, intervalMs) {
153
+ let active = true;
154
+ let timer = null;
155
+ const tick = async () => {
156
+ if (!active) return;
157
+ try {
158
+ await _writeToPath(path);
159
+ } catch {}
160
+ if (active) {
161
+ timer = setTimeout(tick, intervalMs);
162
+ if (typeof timer === "object" && timer !== null && "unref" in timer) timer.unref();
163
+ }
164
+ };
165
+ tick();
166
+ return () => {
167
+ active = false;
168
+ if (timer !== null) {
169
+ clearTimeout(timer);
170
+ timer = null;
171
+ }
172
+ };
173
+ }
174
+
175
+ //#endregion
176
+ export { LPIH_DEFAULT_FILENAME, getDefaultLpihCachePath, startLpihPolling, writeLpihCache };
177
+ //# sourceMappingURL=lpih.js.map
@@ -67,6 +67,21 @@ interface ComputedOptions<T> {
67
67
  * })
68
68
  */
69
69
  equals?: (prev: T, next: T) => boolean;
70
+ /**
71
+ * @internal — source location injected by `@pyreon/vite-plugin` at build
72
+ * time. When present, the runtime skips the `new Error().stack` capture
73
+ * in `_rdRegister` — saves ~2.2µs per computed creation when devtools is
74
+ * active. Plain user code should NOT set this; the field is opaque
75
+ * (no public type) so it's not part of the public API surface.
76
+ *
77
+ * Shape: `{ file: string; line: number; col: number }` matching
78
+ * `@pyreon/reactivity`'s `SourceLocation`.
79
+ */
80
+ __sourceLocation?: {
81
+ file: string;
82
+ line: number;
83
+ col: number;
84
+ };
70
85
  }
71
86
  declare function computed<T>(fn: () => T, options?: ComputedOptions<T>): Computed<T>;
72
87
  //#endregion
@@ -150,6 +165,21 @@ interface Signal<T> {
150
165
  interface SignalOptions {
151
166
  /** Debug name for this signal — shows up in devtools and debug() output. */
152
167
  name?: string;
168
+ /**
169
+ * @internal — source location injected by `@pyreon/vite-plugin` at build
170
+ * time. When present, the runtime skips the `new Error().stack` capture
171
+ * in `_rdRegister` — saves ~2.2µs per signal creation when devtools is
172
+ * active. Plain user code should NOT set this; the field is opaque
173
+ * (no public type) so it's not part of the public API surface.
174
+ *
175
+ * Shape: `{ file: string; line: number; col: number }` matching
176
+ * `@pyreon/reactivity`'s `SourceLocation`.
177
+ */
178
+ __sourceLocation?: {
179
+ file: string;
180
+ line: number;
181
+ col: number;
182
+ };
153
183
  }
154
184
  /**
155
185
  * Create a reactive signal.
@@ -237,6 +267,25 @@ declare function inspectSignal<T>(sig: Signal<T>): SignalDebugInfo<T>;
237
267
  * they get a stable synthetic label (`derived#12` / `effect#7`).
238
268
  */
239
269
  type ReactiveNodeKind = 'signal' | 'derived' | 'effect';
270
+ /**
271
+ * Source location of a reactive node's creation — captured at registration
272
+ * time from the user's call stack. Powers "Live Program Inlay Hints" — the
273
+ * editor surfaces fire counts at the source line where the node was created.
274
+ *
275
+ * Captured ONLY when devtools is active (`_active === true`). Stack parsing
276
+ * is best-effort across V8 / JSC / SpiderMonkey; returns undefined when the
277
+ * stack format isn't recognized (older runtimes, minified prod, web workers
278
+ * without source maps). Dev gate is the existing `process.env.NODE_ENV` at
279
+ * each caller — production paths never run the capture.
280
+ */
281
+ interface SourceLocation {
282
+ /** Absolute path or file URL parsed from the stack frame. */
283
+ file: string;
284
+ /** 1-based line number. */
285
+ line: number;
286
+ /** 1-based column number. */
287
+ col: number;
288
+ }
240
289
  interface ReactiveNode {
241
290
  id: number;
242
291
  kind: ReactiveNodeKind;
@@ -250,6 +299,13 @@ interface ReactiveNode {
250
299
  fires: number;
251
300
  /** `performance.now()` of the most recent fire, or null. */
252
301
  lastFire: number | null;
302
+ /**
303
+ * Source location of the creation call (`signal(0)` / `computed(...)` /
304
+ * `effect(...)`). Undefined when devtools wasn't active at creation
305
+ * time OR the stack format wasn't parseable. Editor inlay-hint surfaces
306
+ * consume this to merge live fire counts onto static spans.
307
+ */
308
+ loc?: SourceLocation;
253
309
  }
254
310
  interface ReactiveEdge {
255
311
  /** Source node id (the reactive value being read). */
@@ -266,6 +322,35 @@ interface ReactiveFire {
266
322
  /** `performance.now()` at fire time. */
267
323
  ts: number;
268
324
  }
325
+ /**
326
+ * Per-source-location fire-count summary. Aggregated from the fire ring
327
+ * buffer + node registry. The shape an editor / LSP inlay-hint consumer
328
+ * needs to merge "this signal at line N fires K times" onto static
329
+ * Reactivity-Lens spans. Pure data, JSON-serializable, no node refs.
330
+ */
331
+ interface FireSummary {
332
+ loc: SourceLocation;
333
+ /** Total fires in the visible ring buffer at this location. */
334
+ count: number;
335
+ /** Most recent fire `performance.now()` at this location, or null. */
336
+ lastFire: number | null;
337
+ /** Node kind that fired most recently at this location. */
338
+ kind: ReactiveNodeKind;
339
+ /**
340
+ * Exponentially-weighted moving average of the fire rate at this
341
+ * location, in fires per second. Decayed to "now" at read time so a
342
+ * node that stopped firing N seconds ago shows a rate that's
343
+ * exponentially smaller than its steady-state value.
344
+ *
345
+ * Calculation uses a 1-second time constant (`LPIH_RATE_TAU_MS`):
346
+ * - On each fire: `r = r * exp(-dt/TAU) + 1`
347
+ * - Steady state at λ fires/sec converges to ≈ λ (when λ × TAU ≫ 1)
348
+ * - On read: `r_now = r * exp(-dt_since_last/TAU)`
349
+ *
350
+ * 0 when there have been no fires (or all fires were >>TAU ago).
351
+ */
352
+ rate1s: number;
353
+ }
269
354
  /** Activate the bridge. Idempotent. Called when a devtools client attaches. */
270
355
  declare function activateReactiveDevtools(): void;
271
356
  /**
@@ -280,6 +365,18 @@ declare function isReactiveDevtoolsActive(): boolean;
280
365
  * framework's real subscription state, no incremental drift.
281
366
  */
282
367
  declare function getReactiveGraph(): ReactiveGraph;
368
+ /**
369
+ * Aggregate fire counts by source-location — powers Live Program Inlay
370
+ * Hints. Walks the live node registry, keys each node by its captured
371
+ * `loc`, and returns one summary per unique `file:line:col`. Nodes
372
+ * without a captured location are skipped (their fires are still
373
+ * visible via `getReactiveGraph()` and `getReactiveFires()` for the
374
+ * existing graph / timeline surfaces).
375
+ *
376
+ * Returns a fresh array, JSON-serializable, safe to ship across the
377
+ * devtools-host bridge or to write into an LSP cache file.
378
+ */
379
+ declare function getFireSummaries(): FireSummary[];
283
380
  /** Bounded recent-fire timeline (oldest → newest). Fresh copy. */
284
381
  declare function getReactiveFires(): ReactiveFire[];
285
382
  //#endregion
@@ -337,6 +434,23 @@ declare function clearReactiveTrace(): void;
337
434
  interface Effect {
338
435
  dispose(): void;
339
436
  }
437
+ interface EffectOptions {
438
+ /**
439
+ * @internal — source location injected by `@pyreon/vite-plugin` at build
440
+ * time. When present, the runtime skips the `new Error().stack` capture
441
+ * in `_rdRegister` — saves ~2.2µs per effect creation when devtools is
442
+ * active. Plain user code should NOT set this; the field is opaque
443
+ * (no public type) so it's not part of the public API surface.
444
+ *
445
+ * Shape: `{ file: string; line: number; col: number }` matching
446
+ * `@pyreon/reactivity`'s `SourceLocation`.
447
+ */
448
+ __sourceLocation?: {
449
+ file: string;
450
+ line: number;
451
+ col: number;
452
+ };
453
+ }
340
454
  interface ReactiveSnapshotCapture {
341
455
  capture: () => unknown;
342
456
  /** Run `fn` with the previously-captured snapshot active. */
@@ -369,7 +483,7 @@ declare function setSnapshotCapture(hook: ReactiveSnapshotCapture | null): void;
369
483
  */
370
484
  declare function onCleanup(fn: () => void): void;
371
485
  declare function setErrorHandler(fn: (err: unknown) => void): void;
372
- declare function effect(fn: () => (() => void) | void): Effect;
486
+ declare function effect(fn: () => (() => void) | void, options?: EffectOptions): Effect;
373
487
  /**
374
488
  * Lightweight effect for DOM render bindings.
375
489
  *
@@ -589,5 +703,5 @@ interface WatchOptions {
589
703
  */
590
704
  declare function watch<T>(source: () => T, callback: (newVal: T, oldVal: T | undefined) => void | (() => void), opts?: WatchOptions): () => void;
591
705
  //#endregion
592
- export { Cell, type Computed, type ComputedOptions, type Effect, EffectScope, type ReactiveEdge, type ReactiveFire, type ReactiveGraph, type ReactiveNode, type ReactiveNodeKind, type ReactiveSnapshotCapture, type ReactiveTraceEntry, type ReadonlySignal, type Resource, type Signal, type SignalDebugInfo, type SignalOptions, type WatchOptions, _bind, activateReactiveDevtools, batch, cell, clearReactiveTrace, computed, createResource, createSelector, createStore, deactivateReactiveDevtools, effect, effectScope, getCurrentScope, getReactiveFires, getReactiveGraph, getReactiveTrace, inspectSignal, isReactiveDevtoolsActive, isStore, markRaw, nextTick, onCleanup, onScopeDispose, onSignalUpdate, reconcile, renderEffect, runUntracked, runUntracked as untrack, setCurrentScope, setErrorHandler, setSnapshotCapture, shallowReactive, signal, watch, why };
706
+ export { Cell, type Computed, type ComputedOptions, type Effect, EffectScope, type FireSummary, type ReactiveEdge, type ReactiveFire, type ReactiveGraph, type ReactiveNode, type ReactiveNodeKind, type ReactiveSnapshotCapture, type ReactiveTraceEntry, type ReadonlySignal, type Resource, type Signal, type SignalDebugInfo, type SignalOptions, type SourceLocation, type WatchOptions, _bind, activateReactiveDevtools, batch, cell, clearReactiveTrace, computed, createResource, createSelector, createStore, deactivateReactiveDevtools, effect, effectScope, getCurrentScope, getFireSummaries, getReactiveFires, getReactiveGraph, getReactiveTrace, inspectSignal, isReactiveDevtoolsActive, isStore, markRaw, nextTick, onCleanup, onScopeDispose, onSignalUpdate, reconcile, renderEffect, runUntracked, runUntracked as untrack, setCurrentScope, setErrorHandler, setSnapshotCapture, shallowReactive, signal, watch, why };
593
707
  //# sourceMappingURL=index2.d.ts.map
@@ -0,0 +1,111 @@
1
+ //#region src/lpih.d.ts
2
+ /**
3
+ * Live Program Inlay Hints — runtime bridge.
4
+ *
5
+ * Writes the current `getFireSummaries()` snapshot to a JSON file that
6
+ * the LSP server reads via the `PYREON_LPIH_CACHE` env var. This is the
7
+ * file-cache bridge mechanism — chosen over IPC/WebSocket because:
8
+ *
9
+ * 1. LSP servers are stdio-only — they can't easily talk to a browser.
10
+ * 2. Filesystem is a universal lowest-common-denominator transport.
11
+ * 3. The runtime side writes (atomic rename); the LSP side reads.
12
+ * 4. The LSP re-reads the file on every inlay-hint request, so live
13
+ * edits land immediately without coordination.
14
+ *
15
+ * Two consumer modes:
16
+ *
17
+ * **Dev-server polled mode**: a dev-server hook calls
18
+ * `writeLpihCache(path)` on every signal write or at a regular interval
19
+ * (e.g. 250ms throttle). The LSP picks it up on next inlay-hint request.
20
+ *
21
+ * **On-demand mode**: a test harness or devtools UI calls
22
+ * `writeLpihCache(path)` explicitly when it wants the LSP to see the
23
+ * current state.
24
+ *
25
+ * Atomic write semantics: writes to `<path>.tmp.<pid>.<seq>` then renames
26
+ * to `<path>`. Readers (the LSP server) never see a half-written file.
27
+ *
28
+ * Zero-cost when devtools is inactive: `getFireSummaries()` returns []
29
+ * unless `activateReactiveDevtools()` has been called. So calling
30
+ * `writeLpihCache()` against an inactive registry writes an empty
31
+ * `{ fires: [] }` — cheap, correct.
32
+ */
33
+ /**
34
+ * Canonical filename for the LPIH cache file. Co-located with the
35
+ * project — convention: `<cwd>/.pyreon-lpih.json`. The dot-prefix marks
36
+ * it as a hidden / generated file by filesystem convention; the
37
+ * extension makes its contents grep-able as JSON.
38
+ *
39
+ * @internal — exported for tests + symmetry with the LSP-side default.
40
+ */
41
+ declare const LPIH_DEFAULT_FILENAME = ".pyreon-lpih.json";
42
+ /**
43
+ * Resolve the default LPIH cache path for the current process. The path
44
+ * is **`<cwd>/.pyreon-lpih.json`** — co-located with the project so the
45
+ * LSP can auto-discover it by walking up from any source file.
46
+ *
47
+ * Returns null in environments without `process.cwd()` (e.g. a fresh
48
+ * web worker without polyfills) — callers should fall back to an
49
+ * explicit path argument.
50
+ *
51
+ * @example
52
+ * import { startLpihPolling, getDefaultLpihCachePath } from '@pyreon/reactivity/lpih'
53
+ * console.log(getDefaultLpihCachePath()) // → '/Users/me/proj/.pyreon-lpih.json'
54
+ * startLpihPolling() // writes to that path
55
+ */
56
+ declare function getDefaultLpihCachePath(): string | null;
57
+ /**
58
+ * Snapshot `getFireSummaries()` and write it to `path` atomically.
59
+ * Returns the number of fires written.
60
+ *
61
+ * **Path resolution**: when `path` is omitted, defaults to
62
+ * `<cwd>/.pyreon-lpih.json` (`getDefaultLpihCachePath()`). The LSP
63
+ * auto-discovers this convention by walking up from any source file to
64
+ * the nearest `package.json` — so projects that use the default need
65
+ * zero env-var configuration.
66
+ *
67
+ * Errors (filesystem permission, EACCES, etc.) are caught and re-thrown
68
+ * — the caller decides whether to swallow them. The runtime side wraps
69
+ * this in a try/catch when called from hot paths.
70
+ *
71
+ * Throws if `path` is omitted AND no default can be resolved (e.g.
72
+ * a web worker without `process.cwd()`).
73
+ *
74
+ * @example
75
+ * import { activateReactiveDevtools } from '@pyreon/reactivity'
76
+ * import { writeLpihCache } from '@pyreon/reactivity/lpih'
77
+ *
78
+ * activateReactiveDevtools()
79
+ * await writeLpihCache() // → writes to <cwd>/.pyreon-lpih.json
80
+ * // The LSP server auto-discovers this path; no env var needed.
81
+ */
82
+ declare function writeLpihCache(path?: string): Promise<number>;
83
+ /**
84
+ * Polling helper: call `writeLpihCache(path)` every `intervalMs`. Returns
85
+ * a disposer that stops the timer.
86
+ *
87
+ * **Path resolution**: same as `writeLpihCache` — `path` defaults to
88
+ * `<cwd>/.pyreon-lpih.json` when omitted. The LSP auto-discovers this
89
+ * convention so projects need zero configuration.
90
+ *
91
+ * Useful for dev servers that want the LSP to see live updates. The
92
+ * interval is throttled (not debounced); a fast-firing signal won't
93
+ * generate one write per fire. 250-500ms is the recommended range.
94
+ *
95
+ * Throws synchronously if `path` is omitted AND no default can be
96
+ * resolved — the caller catches this once at startup rather than
97
+ * silently never writing.
98
+ *
99
+ * @example
100
+ * import { activateReactiveDevtools } from '@pyreon/reactivity'
101
+ * import { startLpihPolling } from '@pyreon/reactivity/lpih'
102
+ *
103
+ * if (import.meta.env.DEV) {
104
+ * activateReactiveDevtools()
105
+ * startLpihPolling() // writes to <cwd>/.pyreon-lpih.json every 250ms
106
+ * }
107
+ */
108
+ declare function startLpihPolling(path?: string, intervalMs?: number): () => void;
109
+ //#endregion
110
+ export { LPIH_DEFAULT_FILENAME, getDefaultLpihCachePath, startLpihPolling, writeLpihCache };
111
+ //# sourceMappingURL=lpih2.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyreon/reactivity",
3
- "version": "0.23.0",
3
+ "version": "0.24.1",
4
4
  "description": "Signals-based reactivity system for Pyreon",
5
5
  "homepage": "https://github.com/pyreon/pyreon/tree/main/packages/reactivity#readme",
6
6
  "bugs": {
@@ -29,6 +29,11 @@
29
29
  "bun": "./src/index.ts",
30
30
  "import": "./lib/index.js",
31
31
  "types": "./lib/types/index.d.ts"
32
+ },
33
+ "./lpih": {
34
+ "bun": "./src/lpih.ts",
35
+ "import": "./lib/lpih.js",
36
+ "types": "./lib/types/lpih.d.ts"
32
37
  }
33
38
  },
34
39
  "publishConfig": {
package/src/computed.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { _markRecompute } from './batch'
2
2
  import { _errorHandler } from './effect'
3
- import { _rdRecordFire, _rdRegister } from './reactive-devtools'
3
+ import { _captureCallerLocation, _rdRecordFire, _rdRegister } from './reactive-devtools'
4
4
  import { getCurrentScope } from './scope'
5
5
  import {
6
6
  cleanupEffect,
@@ -36,6 +36,17 @@ export interface ComputedOptions<T> {
36
36
  * })
37
37
  */
38
38
  equals?: (prev: T, next: T) => boolean
39
+ /**
40
+ * @internal — source location injected by `@pyreon/vite-plugin` at build
41
+ * time. When present, the runtime skips the `new Error().stack` capture
42
+ * in `_rdRegister` — saves ~2.2µs per computed creation when devtools is
43
+ * active. Plain user code should NOT set this; the field is opaque
44
+ * (no public type) so it's not part of the public API surface.
45
+ *
46
+ * Shape: `{ file: string; line: number; col: number }` matching
47
+ * `@pyreon/reactivity`'s `SourceLocation`.
48
+ */
49
+ __sourceLocation?: { file: string; line: number; col: number }
39
50
  }
40
51
 
41
52
  /** Remove a computed from all dependency subscriber sets (local deps array). */
@@ -68,7 +79,14 @@ export function computed<T>(fn: () => T, options?: ComputedOptions<T>): Computed
68
79
  )
69
80
  }
70
81
  }
71
- return options?.equals ? computedWithEquals(fn, options.equals) : computedLazy(fn)
82
+ // Prefer build-time-injected location (zero runtime cost) over the
83
+ // ~2.2µs stack-capture fallback. @pyreon/vite-plugin's `injectSignalNames`
84
+ // rewrites `computed(() => …)` to `computed(() => …, { __sourceLocation: {…} })`
85
+ // at transform time so most dev-mode computeds never pay the stack-capture cost.
86
+ const loc = options?.__sourceLocation
87
+ return options?.equals
88
+ ? computedWithEquals(fn, options.equals, loc)
89
+ : computedLazy(fn, loc)
72
90
  }
73
91
 
74
92
  /**
@@ -81,7 +99,10 @@ export function computed<T>(fn: () => T, options?: ComputedOptions<T>): Computed
81
99
  * in diamond patterns (a→b,c→d: b notifies d, c tries to notify d again —
82
100
  * skipped because d is already dirty).
83
101
  */
84
- function computedLazy<T>(fn: () => T): Computed<T> {
102
+ function computedLazy<T>(
103
+ fn: () => T,
104
+ injectedLoc?: { file: string; line: number; col: number },
105
+ ): Computed<T> {
85
106
  let value: T
86
107
  let dirty = true
87
108
  let disposed = false
@@ -165,7 +186,15 @@ function computedLazy<T>(fn: () => T): Computed<T> {
165
186
  }
166
187
 
167
188
  if (process.env.NODE_ENV !== 'production')
168
- _rdRegister(read, 'derived', host, recompute, undefined)
189
+ // skipFrames=2: skip computedLazy/computedWithEquals + computed, capture user's call site.
190
+ _rdRegister(
191
+ read,
192
+ 'derived',
193
+ host,
194
+ recompute,
195
+ undefined,
196
+ injectedLoc ?? _captureCallerLocation(2),
197
+ )
169
198
 
170
199
  getCurrentScope()?.add({ dispose: read.dispose })
171
200
  return read as Computed<T>
@@ -177,7 +206,11 @@ function computedLazy<T>(fn: () => T): Computed<T> {
177
206
  * Re-evaluates immediately when deps change and only notifies downstream
178
207
  * if `equals(prev, next)` returns false.
179
208
  */
180
- function computedWithEquals<T>(fn: () => T, equals: (prev: T, next: T) => boolean): Computed<T> {
209
+ function computedWithEquals<T>(
210
+ fn: () => T,
211
+ equals: (prev: T, next: T) => boolean,
212
+ injectedLoc?: { file: string; line: number; col: number },
213
+ ): Computed<T> {
181
214
  let value: T
182
215
  let dirty = true
183
216
  let initialized = false
@@ -265,7 +298,15 @@ function computedWithEquals<T>(fn: () => T, equals: (prev: T, next: T) => boolea
265
298
  }
266
299
 
267
300
  if (process.env.NODE_ENV !== 'production')
268
- _rdRegister(read, 'derived', host, recompute, undefined)
301
+ // skipFrames=2: skip computedLazy/computedWithEquals + computed, capture user's call site.
302
+ _rdRegister(
303
+ read,
304
+ 'derived',
305
+ host,
306
+ recompute,
307
+ undefined,
308
+ injectedLoc ?? _captureCallerLocation(2),
309
+ )
269
310
 
270
311
  getCurrentScope()?.add({ dispose: read.dispose })
271
312
  return read as Computed<T>
package/src/effect.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { _rdRecordFire, _rdRegister } from './reactive-devtools'
1
+ import { _captureCallerLocation, _rdRecordFire, _rdRegister } from './reactive-devtools'
2
2
  import { getCurrentScope } from './scope'
3
3
  import { _restoreActiveEffect, _setActiveEffect, setDepsCollector, withTracking } from './tracking'
4
4
 
@@ -9,6 +9,20 @@ export interface Effect {
9
9
  dispose(): void
10
10
  }
11
11
 
12
+ export interface EffectOptions {
13
+ /**
14
+ * @internal — source location injected by `@pyreon/vite-plugin` at build
15
+ * time. When present, the runtime skips the `new Error().stack` capture
16
+ * in `_rdRegister` — saves ~2.2µs per effect creation when devtools is
17
+ * active. Plain user code should NOT set this; the field is opaque
18
+ * (no public type) so it's not part of the public API surface.
19
+ *
20
+ * Shape: `{ file: string; line: number; col: number }` matching
21
+ * `@pyreon/reactivity`'s `SourceLocation`.
22
+ */
23
+ __sourceLocation?: { file: string; line: number; col: number }
24
+ }
25
+
12
26
  // ─── Effect-scoped snapshot capture (DI from `@pyreon/core`) ─────────────────
13
27
  //
14
28
  // Effects re-run reactively in response to signal changes. When that re-run
@@ -137,7 +151,10 @@ function cleanupLocalDeps(deps: Set<() => void>[], fn: () => void): void {
137
151
  }
138
152
  }
139
153
 
140
- export function effect(fn: () => (() => void) | void): Effect {
154
+ export function effect(
155
+ fn: () => (() => void) | void,
156
+ options?: EffectOptions,
157
+ ): Effect {
141
158
  // Dev-mode warning for async effect callbacks (audit bug #1). The
142
159
  // tracking context is the synchronous frame around `fn()`'s top half;
143
160
  // anything after the first `await` runs detached, so signal reads on
@@ -258,7 +275,18 @@ export function effect(fn: () => (() => void) | void): Effect {
258
275
  }
259
276
 
260
277
  if (process.env.NODE_ENV !== 'production')
261
- _rdRegister(run, 'effect', null, run, undefined)
278
+ // skipFrames=1: skip the `effect()` / `renderEffect()` frame, capture the user's call site.
279
+ // Prefer build-time-injected location over the ~2.2µs stack-capture
280
+ // fallback. @pyreon/vite-plugin's `injectSignalNames` rewrites
281
+ // `effect(() => …)` to `effect(() => …, { __sourceLocation: {…} })`.
282
+ _rdRegister(
283
+ run,
284
+ 'effect',
285
+ null,
286
+ run,
287
+ undefined,
288
+ options?.__sourceLocation ?? _captureCallerLocation(1),
289
+ )
262
290
 
263
291
  run()
264
292
 
@@ -416,7 +444,8 @@ export function renderEffect(fn: () => void): () => void {
416
444
  }
417
445
 
418
446
  if (process.env.NODE_ENV !== 'production')
419
- _rdRegister(run, 'effect', null, run, undefined)
447
+ // skipFrames=1: skip the `effect()` / `renderEffect()` frame, capture the user's call site.
448
+ _rdRegister(run, 'effect', null, run, undefined, _captureCallerLocation(1))
420
449
 
421
450
  run()
422
451
 
package/src/index.ts CHANGED
@@ -6,19 +6,27 @@ export { type Computed, type ComputedOptions, computed } from './computed'
6
6
  export { createSelector } from './createSelector'
7
7
  export { inspectSignal, onSignalUpdate, why } from './debug'
8
8
  export type {
9
+ FireSummary,
9
10
  ReactiveEdge,
10
11
  ReactiveFire,
11
12
  ReactiveGraph,
12
13
  ReactiveNode,
13
14
  ReactiveNodeKind,
15
+ SourceLocation,
14
16
  } from './reactive-devtools'
15
17
  export {
16
18
  activateReactiveDevtools,
17
19
  deactivateReactiveDevtools,
20
+ getFireSummaries,
18
21
  getReactiveFires,
19
22
  getReactiveGraph,
20
23
  isReactiveDevtoolsActive,
21
24
  } from './reactive-devtools'
25
+ // `writeLpihCache` + `startLpihPolling` ship at the `@pyreon/reactivity/lpih`
26
+ // subpath. They depend on `node:fs/promises` (Node-only) and are dev-mode
27
+ // integration utilities — separating them keeps the core main-entry bundle
28
+ // smaller AND clarifies that LPIH writes are an opt-in side-channel, not a
29
+ // core reactivity primitive. See `./lpih.ts` and `docs/docs/lpih.md`.
22
30
  export type { ReactiveTraceEntry } from './reactive-trace'
23
31
  export { clearReactiveTrace, getReactiveTrace } from './reactive-trace'
24
32
  export {