@vielzeug/ripple 1.2.2 → 1.3.0
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/README.md +4 -3
- package/dist/async-computed.cjs +1 -1
- package/dist/async-computed.cjs.map +1 -1
- package/dist/async-computed.d.ts.map +1 -1
- package/dist/async-computed.js +37 -33
- package/dist/async-computed.js.map +1 -1
- package/dist/computed.cjs +1 -1
- package/dist/computed.js +13 -13
- package/dist/effect.cjs +1 -1
- package/dist/effect.cjs.map +1 -1
- package/dist/effect.d.ts.map +1 -1
- package/dist/effect.js +53 -52
- package/dist/effect.js.map +1 -1
- package/dist/execution-context.cjs +2 -0
- package/dist/execution-context.cjs.map +1 -0
- package/dist/execution-context.d.ts +49 -0
- package/dist/execution-context.d.ts.map +1 -0
- package/dist/execution-context.js +32 -0
- package/dist/execution-context.js.map +1 -0
- package/dist/{store-history.d.ts → history.d.ts} +15 -1
- package/dist/history.d.ts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -6
- package/dist/ripple.cjs +1 -1
- package/dist/ripple.cjs.map +1 -1
- package/dist/ripple.iife.js +1 -1
- package/dist/ripple.iife.js.map +1 -1
- package/dist/ripple.js +1 -1
- package/dist/ripple.js.map +1 -1
- package/dist/scheduling.cjs +1 -1
- package/dist/scheduling.cjs.map +1 -1
- package/dist/scheduling.js +8 -8
- package/dist/scheduling.js.map +1 -1
- package/dist/signal.cjs +1 -1
- package/dist/signal.js +8 -8
- package/dist/src/history.cjs +2 -0
- package/dist/src/history.cjs.map +1 -0
- package/dist/{store-history.js → src/history.js} +5 -5
- package/dist/{store-history.cjs.map → src/history.js.map} +1 -1
- package/dist/src/ssr/index.cjs +1 -1
- package/dist/src/ssr/index.cjs.map +1 -1
- package/dist/src/ssr/index.js +1 -1
- package/dist/src/ssr/index.js.map +1 -1
- package/dist/ssr/index.d.ts +1 -1
- package/dist/ssr/index.d.ts.map +1 -1
- package/dist/store.cjs +1 -1
- package/dist/store.cjs.map +1 -1
- package/dist/store.d.ts +13 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +40 -38
- package/dist/store.js.map +1 -1
- package/dist/subscription.cjs.map +1 -1
- package/dist/subscription.d.ts.map +1 -1
- package/dist/subscription.js.map +1 -1
- package/dist/symbols.cjs +1 -1
- package/dist/symbols.cjs.map +1 -1
- package/dist/symbols.js +2 -2
- package/dist/symbols.js.map +1 -1
- package/dist/tracking.cjs +1 -1
- package/dist/tracking.cjs.map +1 -1
- package/dist/tracking.d.ts +0 -31
- package/dist/tracking.d.ts.map +1 -1
- package/dist/tracking.js +10 -58
- package/dist/tracking.js.map +1 -1
- package/dist/types.d.ts +10 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utilities.cjs +1 -1
- package/dist/utilities.cjs.map +1 -1
- package/dist/utilities.d.ts +2 -2
- package/dist/utilities.d.ts.map +1 -1
- package/dist/utilities.js +5 -5
- package/dist/utilities.js.map +1 -1
- package/package.json +8 -2
- package/dist/store-history.cjs +0 -2
- package/dist/store-history.d.ts.map +0 -1
- package/dist/store-history.js.map +0 -1
package/dist/scheduling.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { runAll as e } from "./_error-utils.js";
|
|
2
2
|
import { RippleInfiniteLoopError as t } from "./errors.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { getSchedulingState as n, hasContextHook as r } from "./execution-context.js";
|
|
4
|
+
import { warn as i } from "./_dev.js";
|
|
5
5
|
var a = !1, o = 0, s = [], c = (e) => e.activeDirty === "a" ? e.dirtyWithEffectSubsA : e.dirtyWithEffectSubsB, l = (e, t) => {
|
|
6
6
|
let n = ++o;
|
|
7
7
|
for (let n of t.effectSubs()) e.pendingSubscribers.add(n);
|
|
@@ -37,19 +37,19 @@ var a = !1, o = 0, s = [], c = (e) => e.activeDirty === "a" ? e.dirtyWithEffectS
|
|
|
37
37
|
}
|
|
38
38
|
}, f = globalThis.process?.versions != null, p = (e) => {
|
|
39
39
|
if (!e.hasSubscribers()) return;
|
|
40
|
-
!a && f && !
|
|
41
|
-
let t =
|
|
40
|
+
!a && f && !r() && (a = !0, i("Signal updated in a Node.js-like environment. The module-level flush queue is shared across concurrent requests — use per-request worker isolation or the @vielzeug/ripple/ssr sub-path for request-isolated scheduling."));
|
|
41
|
+
let t = n();
|
|
42
42
|
l(t, e), t.batchDepth === 0 && d(t);
|
|
43
43
|
}, m = (e) => {
|
|
44
|
-
let t =
|
|
44
|
+
let t = n();
|
|
45
45
|
t.batchDepth++;
|
|
46
|
-
let
|
|
46
|
+
let r;
|
|
47
47
|
try {
|
|
48
|
-
|
|
48
|
+
r = e();
|
|
49
49
|
} catch (e) {
|
|
50
50
|
throw t.batchDepth--, t.batchDepth === 0 && (t.pendingSubscribers.clear(), t.dirtyWithEffectSubsA.clear(), t.dirtyWithEffectSubsB.clear()), e;
|
|
51
51
|
}
|
|
52
|
-
return t.batchDepth--, t.batchDepth === 0 && d(t),
|
|
52
|
+
return t.batchDepth--, t.batchDepth === 0 && d(t), r;
|
|
53
53
|
};
|
|
54
54
|
//#endregion
|
|
55
55
|
export { m as batch, p as notifyNodeChange };
|
package/dist/scheduling.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduling.js","names":[],"sources":["../src/scheduling.ts"],"sourcesContent":["import type { ComputedBase, ReactiveBase } from './reactive-base';\nimport type { Subscriber } from './types';\n\nimport { warn } from './_dev';\nimport { runAll } from './_error-utils';\nimport { RippleInfiniteLoopError } from './errors';\nimport { getSchedulingState, hasContextHook, type SchedulingState } from './
|
|
1
|
+
{"version":3,"file":"scheduling.js","names":[],"sources":["../src/scheduling.ts"],"sourcesContent":["import type { ComputedBase, ReactiveBase } from './reactive-base';\nimport type { Subscriber } from './types';\n\nimport { warn } from './_dev';\nimport { runAll } from './_error-utils';\nimport { RippleInfiniteLoopError } from './errors';\nimport { getSchedulingState, hasContextHook, type SchedulingState } from './execution-context';\n\nexport const DEFAULT_MAX_ITERATIONS = 100;\n\n// batchDepth, pendingSubscribers, and the dirty-computed sets live in `SchedulingState`\n// (see tracking.ts) rather than as module-level variables — this lets the /ripple/ssr\n// sub-path isolate the flush queue per request (via the same AsyncLocalStorage-backed\n// context hook that already isolates tracking), closing the gap where concurrent SSR\n// requests previously shared one flush queue. Outside SSR (no hook installed), this is\n// a single module-level singleton with identical behavior and cost to before.\nlet ssrWarnFired = false;\n\n// ── F1: Simplified flush — no topological sort ─────────────────────────────\n//\n// Push phase (propagateDirty):\n// Mark all downstream computeds dirty in a BFS pass.\n// Directly collect effect subscribers of the changed signal.\n// For computeds with direct effect subscribers, defer to the pull phase.\n//\n// Pull phase (recomputeWithEffectSubs):\n// For each dirty computed that has direct effect subscribers, recompute it.\n// If the value changed, queue its effect subscribers.\n// Any further downstream dirty computeds with effect subs are handled in the\n// same loop (re-queued into dirtyWithEffectSubs if they become dirty during\n// a parent recompute).\n//\n// Effect phase: run all queued effect subscribers.\n//\n// This eliminates the O(n²) topo sort while preserving the equality-suppression\n// guarantee: effect subs of a computed are only notified when the computed's\n// value actually changes.\n//\n// Computeds without direct effect subs (pure lazy nodes) are still pulled\n// lazily when an effect reads them during re-run.\n\n// Module-level scratch state — safe to share even under SSR isolation. Both are only\n// touched within a single synchronous call stack (no `await` inside propagateDirty /\n// recomputeWithEffectSubs / flushEffects), which JS's run-to-completion model already\n// isolates; they never carry information across two separate top-level signal writes.\nlet _propEpoch = 0;\nconst _propagateStack: ComputedBase<unknown>[] = [];\n\n/** Returns (and possibly swaps) the currently-active dirty-with-effect-subs set. */\nconst activeDirtySet = (s: SchedulingState): Set<ComputedBase<unknown>> =>\n s.activeDirty === 'a' ? s.dirtyWithEffectSubsA : s.dirtyWithEffectSubsB;\n\nconst propagateDirty = (\n s: SchedulingState,\n node: {\n computedSubs(): Generator<ComputedBase<unknown>>;\n effectSubs(): ReadonlySet<Subscriber>;\n },\n): void => {\n const epoch = ++_propEpoch;\n\n // Queue direct effect subs of the changed node\n for (const sub of node.effectSubs()) {\n s.pendingSubscribers.add(sub);\n }\n\n for (const c of node.computedSubs()) {\n _propagateStack.push(c);\n }\n\n try {\n while (_propagateStack.length > 0) {\n const c = _propagateStack.pop()!;\n\n if (c.lastPropEpoch_ === epoch) continue;\n\n c.lastPropEpoch_ = epoch;\n\n if (!c.markDirty()) continue; // already dirty — already processed\n\n // If this computed has effect subs, defer recompute to the pull phase.\n // We cannot queue them immediately because the computed might not change.\n if (c.effectSubs().size > 0) {\n activeDirtySet(s).add(c);\n }\n\n for (const downstream of c.computedSubs()) {\n _propagateStack.push(downstream);\n }\n }\n } finally {\n _propagateStack.length = 0;\n }\n};\n\nconst recomputeWithEffectSubs = (s: SchedulingState): void => {\n // Iterate until stable — recomputing one computed may dirty others.\n // Set-swap pattern: swap active/idle sets each pass so new dirty nodes accumulate\n // in the idle set while we iterate the current batch — zero array allocations.\n while (activeDirtySet(s).size > 0) {\n const toProcess = activeDirtySet(s);\n\n // Swap: new dirty nodes from this iteration go into the other set\n s.activeDirty = s.activeDirty === 'a' ? 'b' : 'a';\n activeDirtySet(s).clear();\n\n for (const c of toProcess) {\n if (!c.hasSubscribers()) continue;\n\n const changed = c.refreshIfDirty();\n\n if (!changed) continue;\n\n // Value changed — queue effect subs\n for (const sub of c.effectSubs()) {\n s.pendingSubscribers.add(sub);\n }\n\n // Downstream computeds may now need recomputing too\n for (const downstream of c.computedSubs()) {\n if (downstream.markDirty() && downstream.effectSubs().size > 0) {\n activeDirtySet(s).add(downstream);\n }\n }\n }\n\n toProcess.clear();\n }\n};\n\nconst flushEffects = (s: SchedulingState): void => {\n let iterations = 0;\n\n while (s.pendingSubscribers.size > 0 || activeDirtySet(s).size > 0) {\n if (++iterations > DEFAULT_MAX_ITERATIONS) {\n throw new RippleInfiniteLoopError(`infinite flush loop (> ${DEFAULT_MAX_ITERATIONS} iterations)`);\n }\n\n if (activeDirtySet(s).size > 0) recomputeWithEffectSubs(s);\n\n if (s.pendingSubscribers.size === 0) continue;\n\n const subscribersToRun = [...s.pendingSubscribers];\n\n s.pendingSubscribers.clear();\n runAll(subscribersToRun, 'subscriber errors');\n }\n};\n\n// Fire the warning once per module load in environments that look like Node.js,\n// and only when no SSR context hook is installed (once installed, the flush queue\n// is genuinely request-isolated via SchedulingState — see tracking.ts).\n// window-check is unreliable (jsdom sets window in tests); check for process.versions instead.\n// Access entirely via globalThis to avoid requiring @types/node in downstream tsconfigs.\nconst isNodeLike = (globalThis as { process?: { versions?: unknown } }).process?.versions != null;\n\nexport const notifyNodeChange = (node: ReactiveBase<unknown>): void => {\n if (!node.hasSubscribers()) return;\n\n if (!ssrWarnFired && isNodeLike && !hasContextHook()) {\n ssrWarnFired = true;\n warn(\n 'Signal updated in a Node.js-like environment. The module-level flush queue is shared across concurrent requests ' +\n '— use per-request worker isolation or the @vielzeug/ripple/ssr sub-path for request-isolated scheduling.',\n );\n }\n\n const s = getSchedulingState();\n\n propagateDirty(s, node);\n\n if (s.batchDepth === 0) flushEffects(s);\n};\n\nexport const batch = <T>(fn: () => T): T => {\n const s = getSchedulingState();\n\n s.batchDepth++;\n\n let result: T;\n\n try {\n result = fn();\n } catch (e) {\n s.batchDepth--;\n\n // Outermost batch: clear the pending flush queue on body error.\n // Leaving stale subscribers in the queue would flush them on the next unrelated\n // signal write, surfacing errors in unexpected contexts.\n if (s.batchDepth === 0) {\n s.pendingSubscribers.clear();\n s.dirtyWithEffectSubsA.clear();\n s.dirtyWithEffectSubsB.clear();\n }\n\n throw e;\n }\n\n s.batchDepth--;\n\n if (s.batchDepth === 0) flushEffects(s);\n\n return result;\n};\n"],"mappings":";;;;AAgBA,IAAI,IAAe,IA6Bf,IAAa,GACX,IAA2C,CAAC,GAG5C,KAAkB,MACtB,EAAE,gBAAgB,MAAM,EAAE,uBAAuB,EAAE,sBAE/C,KACJ,GACA,MAIS;CACT,IAAM,IAAQ,EAAE;CAGhB,KAA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AAmB,CAAC,GAAG,EAAE,kBAAkB;EAGjD,AADA,EAAE,mBAAmB,MAAM,GAC3B,EAAO,GAAkB,mBAAmB;CAC9C;AACF,GAOM,IAAc,WAAoD,SAAS,YAAY,MAEhF,KAAoB,MAAsC;CACrE,IAAI,CAAC,EAAK,eAAe,GAAG;CAE5B,AAAI,CAAC,KAAgB,KAAc,CAAC,EAAe,MACjD,IAAe,IACf,EACE,0NAEF;CAGF,IAAM,IAAI,EAAmB;CAI7B,AAFA,EAAe,GAAG,CAAI,GAElB,EAAE,eAAe,KAAG,EAAa,CAAC;AACxC,GAEa,KAAY,MAAmB;CAC1C,IAAM,IAAI,EAAmB;CAE7B,EAAE;CAEF,IAAI;CAEJ,IAAI;EACF,IAAS,EAAG;CACd,SAAS,GAAG;EAYV,MAXA,EAAE,cAKE,EAAE,eAAe,MACnB,EAAE,mBAAmB,MAAM,GAC3B,EAAE,qBAAqB,MAAM,GAC7B,EAAE,qBAAqB,MAAM,IAGzB;CACR;CAMA,OAJA,EAAE,cAEE,EAAE,eAAe,KAAG,EAAa,CAAC,GAE/B;AACT"}
|
package/dist/signal.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./devtools-hook.cjs"),t=require("./
|
|
1
|
+
const e=require("./devtools-hook.cjs"),t=require("./scheduling.cjs"),n=require("./subscription.cjs"),r=require("./tracking.cjs"),i=require("./reactive-base.cjs");var a=class extends i.ReactiveBase{value_;equals_;disposed_;constructor(e,t,n){super(n),this.value_=e,this.equals_=t??Object.is,this.disposed_=!1}get value(){return this.disposed_||r.trackSource(this),this.value_}set value(n){if(this.disposed_||this.equals_(this.value_,n))return;let i=this.value_;this.value_=n,this.version=r.tickRevision(),e.getDevToolsHook()?.write?.({name:this.name,newValue:n,oldValue:i}),t.notifyNodeChange(this)}peek(){return this.value_}subscribe=e=>{if(this.disposed_){let e=new n.SubscriptionImpl(()=>{});return e.dispose(),e}return this.addEffectSub(e),new n.SubscriptionImpl(()=>{this.removeEffectSub(e)})};get disposed(){return this.disposed_}dispose(){this.disposed_||(this.disposed_=!0,this.clearSubscribers(),e.getDevToolsHook()?.dispose?.({kind:`signal`,name:this.name}))}[Symbol.dispose](){this.dispose()}},o=(e,t)=>new a(e,t?.equals,t?.name);exports.SignalImpl=a,exports.signal=o;
|
|
2
2
|
//# sourceMappingURL=signal.cjs.map
|
package/dist/signal.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getDevToolsHook as e } from "./devtools-hook.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { notifyNodeChange as t } from "./scheduling.js";
|
|
3
|
+
import { SubscriptionImpl as n } from "./subscription.js";
|
|
4
|
+
import { tickRevision as r, trackSource as i } from "./tracking.js";
|
|
5
5
|
import { ReactiveBase as a } from "./reactive-base.js";
|
|
6
6
|
//#region src/signal.ts
|
|
7
7
|
var o = class extends a {
|
|
@@ -12,26 +12,26 @@ var o = class extends a {
|
|
|
12
12
|
super(n), this.value_ = e, this.equals_ = t ?? Object.is, this.disposed_ = !1;
|
|
13
13
|
}
|
|
14
14
|
get value() {
|
|
15
|
-
return this.disposed_ ||
|
|
15
|
+
return this.disposed_ || i(this), this.value_;
|
|
16
16
|
}
|
|
17
17
|
set value(n) {
|
|
18
18
|
if (this.disposed_ || this.equals_(this.value_, n)) return;
|
|
19
19
|
let i = this.value_;
|
|
20
|
-
this.value_ = n, this.version =
|
|
20
|
+
this.value_ = n, this.version = r(), e()?.write?.({
|
|
21
21
|
name: this.name,
|
|
22
22
|
newValue: n,
|
|
23
23
|
oldValue: i
|
|
24
|
-
}),
|
|
24
|
+
}), t(this);
|
|
25
25
|
}
|
|
26
26
|
peek() {
|
|
27
27
|
return this.value_;
|
|
28
28
|
}
|
|
29
29
|
subscribe = (e) => {
|
|
30
30
|
if (this.disposed_) {
|
|
31
|
-
let e = new
|
|
31
|
+
let e = new n(() => {});
|
|
32
32
|
return e.dispose(), e;
|
|
33
33
|
}
|
|
34
|
-
return this.addEffectSub(e), new
|
|
34
|
+
return this.addEffectSub(e), new n(() => {
|
|
35
35
|
this.removeEffectSub(e);
|
|
36
36
|
});
|
|
37
37
|
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../signal.cjs"),t=require("../store.cjs"),n=require("../utilities.cjs");var r=(e,t)=>({label:t,state:Object.freeze(structuredClone({...e}))}),i=(i,a)=>{let o=a?.maxHistory??50,s=!n.isStore(i),c=s?t.store(i,{name:a?.name}):i,l=[r(c.peek())],u=e.signal(0,{name:a?.name?`${a.name}.cursor`:void 0}),d=!1,f=e=>{d||(l.splice(u.peek()+1),l.push(r(c.peek(),e)),l.length>o&&l.splice(0,l.length-o),u.value=l.length-1)},p=()=>{d||u.peek()<=0||(u.value=u.peek()-1,c.replace(()=>l[u.peek()].state))},m=()=>{d||u.peek()>=l.length-1||(u.value=u.peek()+1,c.replace(()=>l[u.peek()].state))},h=e=>{if(!(e<0||e>=l.length))return l[e]},g=()=>{d||(d=!0,u.dispose(),s&&c.dispose())};return{get canRedo(){return u.value<l.length-1},get canUndo(){return u.value>0},dispose:g,get disposed(){return d},historyAt:h,get historyLength(){return l.length},lens:e=>c.lens(e),get name(){return c.name},patch:e=>c.patch(e),peek:()=>c.peek(),push:()=>f(),pushNamed:e=>f(e),redo:m,replace:e=>c.replace(e),reset:()=>c.reset(),get store(){return c},subscribe:e=>c.subscribe(e),[Symbol.dispose]:g,undo:p,get value(){return c.value}}};exports.storeWithHistory=i;
|
|
2
|
+
//# sourceMappingURL=history.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"history.cjs","names":[],"sources":["../../src/history.ts"],"sourcesContent":["/**\n * @vielzeug/ripple — snapshot-based store undo/redo.\n *\n * Import from the dedicated sub-path so it is tree-shaken from bundles that\n * never use it:\n * ```ts\n * import { storeWithHistory } from '@vielzeug/ripple/history';\n * ```\n *\n * This is a thin, synchronous, single-store adapter — for async commands,\n * multi-step undo grouping, or history over anything other than a `Store<T>`,\n * use `@vielzeug/ledger` instead.\n */\n\nimport type { HistoryEntry, Store, StoreWithHistory } from './types';\n\nimport { signal } from './signal';\nimport { store } from './store';\nimport { isStore } from './utilities';\n\n// Re-export the history-specific types from the core module so consumers of\n// this sub-path don't need to import from two places.\nexport type { HistoryEntry, StoreWithHistory } from './types';\n\nconst snapshot = <T extends object>(state: Readonly<T>, label?: string): HistoryEntry<T> => ({\n label,\n state: Object.freeze(structuredClone({ ...state })) as Readonly<T>,\n});\n\n/**\n * Wraps a store (or creates one from an initial value) with explicit snapshot history\n * for undo/redo / time-travel.\n *\n * **Ownership:** if called with an initial value, the adapter creates and owns\n * the underlying store — `dispose()` will also dispose it. If called with an\n * existing `Store<T>`, the adapter does NOT own it — `dispose()` leaves the\n * store alive.\n *\n * History is **explicit** — call `push()` or `pushNamed()` after mutations you want\n * to be undoable. This gives you full control over snapshot granularity: you can\n * batch multiple mutations before pushing, or avoid pushing for programmatic\n * operations like server sync or reset-and-reload.\n *\n * This is a pure external adapter — it does not access any store internals.\n *\n * @example\n * ```ts\n * const h = storeWithHistory({ count: 0 }, { maxHistory: 10 });\n *\n * h.patch({ count: 1 });\n * h.push(); // save checkpoint\n * h.patch({ count: 2 });\n * h.pushNamed('increment');\n *\n * h.undo(); // back to { count: 1 }\n * h.redo(); // forward to { count: 2 }\n * h.historyAt(0); // { label: undefined, state: { count: 0 } }\n * h.canUndo; // true\n *\n * // Wrap an existing store:\n * const existingStore = store({ x: 0 });\n * const h2 = storeWithHistory(existingStore);\n * h2.dispose(); // existingStore is NOT disposed\n * ```\n */\nexport const storeWithHistory = <T extends object>(\n storeOrInitial: Store<T> | T,\n options?: { maxHistory?: number; name?: string },\n): StoreWithHistory<T> => {\n const maxHistory = options?.maxHistory ?? 50;\n const ownsStore = !isStore(storeOrInitial);\n const base: Store<T> = ownsStore ? store(storeOrInitial as T, { name: options?.name }) : (storeOrInitial as Store<T>);\n\n const snapshots: HistoryEntry<T>[] = [snapshot(base.peek())];\n\n // cursor is a reactive signal so canUndo/canRedo participate in the reactive graph.\n const cursor = signal(0, { name: options?.name ? `${options.name}.cursor` : undefined });\n\n let disposed = false;\n\n const pushSnapshot = (label?: string): void => {\n if (disposed) return;\n\n snapshots.splice(cursor.peek() + 1);\n snapshots.push(snapshot(base.peek(), label));\n\n if (snapshots.length > maxHistory) {\n snapshots.splice(0, snapshots.length - maxHistory);\n }\n\n cursor.value = snapshots.length - 1;\n };\n\n const undo = (): void => {\n if (disposed || cursor.peek() <= 0) return;\n\n cursor.value = cursor.peek() - 1;\n base.replace(() => snapshots[cursor.peek()]!.state as T);\n };\n\n const redo = (): void => {\n if (disposed || cursor.peek() >= snapshots.length - 1) return;\n\n cursor.value = cursor.peek() + 1;\n base.replace(() => snapshots[cursor.peek()]!.state as T);\n };\n\n const historyAt = (index: number): HistoryEntry<T> | undefined => {\n if (index < 0 || index >= snapshots.length) return undefined;\n\n return snapshots[index];\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n cursor.dispose();\n\n if (ownsStore) base.dispose();\n };\n\n // Explicit delegation: all Store<T> methods are forwarded directly to base.\n // History-specific properties are defined inline.\n const adapter: StoreWithHistory<T> = {\n get canRedo() {\n return cursor.value < snapshots.length - 1;\n },\n // History-specific\n get canUndo() {\n return cursor.value > 0;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n historyAt,\n get historyLength() {\n return snapshots.length;\n },\n lens: <P extends string>(path: P) => base.lens(path),\n // Store<T> delegation\n get name() {\n return base.name;\n },\n patch: (partial) => base.patch(partial),\n peek: () => base.peek(),\n push: () => pushSnapshot(),\n pushNamed: (label: string) => pushSnapshot(label),\n redo,\n replace: (fn) => base.replace(fn),\n reset: () => base.reset(),\n get store() {\n return base;\n },\n subscribe: (listener) => base.subscribe(listener),\n [Symbol.dispose]: dispose,\n undo,\n get value() {\n return base.value;\n },\n };\n\n return adapter;\n};\n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AO,EAAO,MAAQ,CACxB,EACA,UACA,IAAI,UAAW,CACb,OAAO,CACT,EACA,YACA,IAAI,eAAgB,CAClB,OAAO,EAAU,MACnB,EACA,KAAyB,GAAY,EAAK,KAAK,CAAI,EAEnD,IAAI,MAAO,CACT,OAAO,EAAK,IACd,EACA,MAAQ,GAAY,EAAK,MAAM,CAAO,EACtC,SAAY,EAAK,KAAK,EACtB,SAAY,EAAa,EACzB,UAAY,GAAkB,EAAa,CAAK,EAChD,OACA,QAAU,GAAO,EAAK,QAAQ,CAAE,EAChC,UAAa,EAAK,MAAM,EACxB,IAAI,OAAQ,CACV,OAAO,CACT,EACA,UAAY,GAAa,EAAK,UAAU,CAAQ,GAC/C,OAAO,SAAU,EAClB,OACA,IAAI,OAAQ,CACV,OAAO,EAAK,KACd,CAGK,CACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { signal as e } from "
|
|
2
|
-
import { store as t } from "
|
|
3
|
-
import { isStore as n } from "
|
|
4
|
-
//#region src/
|
|
1
|
+
import { signal as e } from "../signal.js";
|
|
2
|
+
import { store as t } from "../store.js";
|
|
3
|
+
import { isStore as n } from "../utilities.js";
|
|
4
|
+
//#region src/history.ts
|
|
5
5
|
var r = (e, t) => ({
|
|
6
6
|
label: t,
|
|
7
7
|
state: Object.freeze(structuredClone({ ...e }))
|
|
@@ -57,4 +57,4 @@ var r = (e, t) => ({
|
|
|
57
57
|
//#endregion
|
|
58
58
|
export { i as storeWithHistory };
|
|
59
59
|
|
|
60
|
-
//# sourceMappingURL=
|
|
60
|
+
//# sourceMappingURL=history.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"
|
|
1
|
+
{"version":3,"file":"history.js","names":[],"sources":["../../src/history.ts"],"sourcesContent":["/**\n * @vielzeug/ripple — snapshot-based store undo/redo.\n *\n * Import from the dedicated sub-path so it is tree-shaken from bundles that\n * never use it:\n * ```ts\n * import { storeWithHistory } from '@vielzeug/ripple/history';\n * ```\n *\n * This is a thin, synchronous, single-store adapter — for async commands,\n * multi-step undo grouping, or history over anything other than a `Store<T>`,\n * use `@vielzeug/ledger` instead.\n */\n\nimport type { HistoryEntry, Store, StoreWithHistory } from './types';\n\nimport { signal } from './signal';\nimport { store } from './store';\nimport { isStore } from './utilities';\n\n// Re-export the history-specific types from the core module so consumers of\n// this sub-path don't need to import from two places.\nexport type { HistoryEntry, StoreWithHistory } from './types';\n\nconst snapshot = <T extends object>(state: Readonly<T>, label?: string): HistoryEntry<T> => ({\n label,\n state: Object.freeze(structuredClone({ ...state })) as Readonly<T>,\n});\n\n/**\n * Wraps a store (or creates one from an initial value) with explicit snapshot history\n * for undo/redo / time-travel.\n *\n * **Ownership:** if called with an initial value, the adapter creates and owns\n * the underlying store — `dispose()` will also dispose it. If called with an\n * existing `Store<T>`, the adapter does NOT own it — `dispose()` leaves the\n * store alive.\n *\n * History is **explicit** — call `push()` or `pushNamed()` after mutations you want\n * to be undoable. This gives you full control over snapshot granularity: you can\n * batch multiple mutations before pushing, or avoid pushing for programmatic\n * operations like server sync or reset-and-reload.\n *\n * This is a pure external adapter — it does not access any store internals.\n *\n * @example\n * ```ts\n * const h = storeWithHistory({ count: 0 }, { maxHistory: 10 });\n *\n * h.patch({ count: 1 });\n * h.push(); // save checkpoint\n * h.patch({ count: 2 });\n * h.pushNamed('increment');\n *\n * h.undo(); // back to { count: 1 }\n * h.redo(); // forward to { count: 2 }\n * h.historyAt(0); // { label: undefined, state: { count: 0 } }\n * h.canUndo; // true\n *\n * // Wrap an existing store:\n * const existingStore = store({ x: 0 });\n * const h2 = storeWithHistory(existingStore);\n * h2.dispose(); // existingStore is NOT disposed\n * ```\n */\nexport const storeWithHistory = <T extends object>(\n storeOrInitial: Store<T> | T,\n options?: { maxHistory?: number; name?: string },\n): StoreWithHistory<T> => {\n const maxHistory = options?.maxHistory ?? 50;\n const ownsStore = !isStore(storeOrInitial);\n const base: Store<T> = ownsStore ? store(storeOrInitial as T, { name: options?.name }) : (storeOrInitial as Store<T>);\n\n const snapshots: HistoryEntry<T>[] = [snapshot(base.peek())];\n\n // cursor is a reactive signal so canUndo/canRedo participate in the reactive graph.\n const cursor = signal(0, { name: options?.name ? `${options.name}.cursor` : undefined });\n\n let disposed = false;\n\n const pushSnapshot = (label?: string): void => {\n if (disposed) return;\n\n snapshots.splice(cursor.peek() + 1);\n snapshots.push(snapshot(base.peek(), label));\n\n if (snapshots.length > maxHistory) {\n snapshots.splice(0, snapshots.length - maxHistory);\n }\n\n cursor.value = snapshots.length - 1;\n };\n\n const undo = (): void => {\n if (disposed || cursor.peek() <= 0) return;\n\n cursor.value = cursor.peek() - 1;\n base.replace(() => snapshots[cursor.peek()]!.state as T);\n };\n\n const redo = (): void => {\n if (disposed || cursor.peek() >= snapshots.length - 1) return;\n\n cursor.value = cursor.peek() + 1;\n base.replace(() => snapshots[cursor.peek()]!.state as T);\n };\n\n const historyAt = (index: number): HistoryEntry<T> | undefined => {\n if (index < 0 || index >= snapshots.length) return undefined;\n\n return snapshots[index];\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n cursor.dispose();\n\n if (ownsStore) base.dispose();\n };\n\n // Explicit delegation: all Store<T> methods are forwarded directly to base.\n // History-specific properties are defined inline.\n const adapter: StoreWithHistory<T> = {\n get canRedo() {\n return cursor.value < snapshots.length - 1;\n },\n // History-specific\n get canUndo() {\n return cursor.value > 0;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n historyAt,\n get historyLength() {\n return snapshots.length;\n },\n lens: <P extends string>(path: P) => base.lens(path),\n // Store<T> delegation\n get name() {\n return base.name;\n },\n patch: (partial) => base.patch(partial),\n peek: () => base.peek(),\n push: () => pushSnapshot(),\n pushNamed: (label: string) => pushSnapshot(label),\n redo,\n replace: (fn) => base.replace(fn),\n reset: () => base.reset(),\n get store() {\n return base;\n },\n subscribe: (listener) => base.subscribe(listener),\n [Symbol.dispose]: dispose,\n undo,\n get value() {\n return base.value;\n },\n };\n\n return adapter;\n};\n"],"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xB;EACA;EACA,IAAI,WAAW;GACb,OAAO;EACT;EACA;EACA,IAAI,gBAAgB;GAClB,OAAO,EAAU;EACnB;EACA,OAAyB,MAAY,EAAK,KAAK,CAAI;EAEnD,IAAI,OAAO;GACT,OAAO,EAAK;EACd;EACA,QAAQ,MAAY,EAAK,MAAM,CAAO;EACtC,YAAY,EAAK,KAAK;EACtB,YAAY,EAAa;EACzB,YAAY,MAAkB,EAAa,CAAK;EAChD;EACA,UAAU,MAAO,EAAK,QAAQ,CAAE;EAChC,aAAa,EAAK,MAAM;EACxB,IAAI,QAAQ;GACV,OAAO;EACT;EACA,YAAY,MAAa,EAAK,UAAU,CAAQ;GAC/C,OAAO,UAAU;EAClB;EACA,IAAI,QAAQ;GACV,OAAO,EAAK;EACd;CAGK;AACT"}
|
package/dist/src/ssr/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../errors.cjs"),t=require("../../
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../errors.cjs"),t=require("../../execution-context.cjs");var n={scheduling:t.createSchedulingState(),scopeCleanups:null,tracking:null},r=()=>({scheduling:t.createSchedulingState(),scopeCleanups:null,tracking:null}),i=null,a={get:()=>i?.get()??n,run:(e,t)=>i?i.run(e,t):t()},o=e=>{i=e,t._installContextHook(e===null?null:a)},s=()=>{if(typeof require>`u`)throw new e.RippleEnvironmentError(`createAsyncProvider() requires Node.js (async_hooks) and cannot be used in browser environments.`);let{AsyncLocalStorage:t}=require("async_hooks"),r=new t;return{get:()=>r.getStore()??n,run:(e,t)=>r.run(e,t)}},c=(e,t)=>e.run(r(),t),l=(e,n)=>{let o=i;i=e;let s=t._installContextHook(a);try{return e.run(r(),n)}finally{i=o,t._installContextHook(s)}};exports.createAsyncProvider=s,exports.runWithProvider=c,exports.setTrackingProvider=o,exports.withProvider=l;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/ssr/index.ts"],"sourcesContent":["/**\n * /ripple/ssr\n *\n * SSR helpers for installing a custom tracking context provider.\n * Import this sub-entry **only** in server-side code — it is not needed for browser builds.\n *\n * @example\n * ```ts\n * // frameworks/hono.ts\n * import { createAsyncProvider, setTrackingProvider } from '@vielzeug/ripple/ssr';\n *\n * const provider = createAsyncProvider();\n * setTrackingProvider(provider);\n *\n * // Inside a request handler:\n * await runWithProvider(provider, () => renderToString(App));\n * ```\n */\n\nimport { RippleEnvironmentError } from '../errors';\nimport {
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/ssr/index.ts"],"sourcesContent":["/**\n * /ripple/ssr\n *\n * SSR helpers for installing a custom tracking context provider.\n * Import this sub-entry **only** in server-side code — it is not needed for browser builds.\n *\n * @example\n * ```ts\n * // frameworks/hono.ts\n * import { createAsyncProvider, setTrackingProvider } from '@vielzeug/ripple/ssr';\n *\n * const provider = createAsyncProvider();\n * setTrackingProvider(provider);\n *\n * // Inside a request handler:\n * await runWithProvider(provider, () => renderToString(App));\n * ```\n */\n\nimport { RippleEnvironmentError } from '../errors';\nimport {\n _installContextHook,\n createSchedulingState,\n type ContextHook,\n type ExecutionContext,\n} from '../execution-context';\n\n// eslint-disable-next-line no-var\ndeclare var require: (id: string) => unknown;\n\ninterface AsyncLocalStorageType<T> {\n getStore(): T | undefined;\n run<R>(store: T, callback: () => R): R;\n}\n\n// ── Public interfaces ─────────────────────────────────────────────────────────\n\n/**\n * The clean starting context used as a fallback when no request is active\n * (e.g. a signal write outside any `runWithProvider`/`withProvider` call) —\n * a single shared instance is fine here since there's no concurrent request to isolate from.\n */\nconst EMPTY_CTX: ExecutionContext = { scheduling: createSchedulingState(), scopeCleanups: null, tracking: null };\n\n/**\n * Builds a fresh, isolated starting context for one request — no tracking, no scope,\n * and its own `SchedulingState` so this request's `batch()`/flush queue never shares\n * state with a concurrently-running request. Must be called anew per `run()` — reusing\n * a single context object across requests would defeat scheduling isolation.\n */\nconst freshRequestContext = (): ExecutionContext => ({\n scheduling: createSchedulingState(),\n scopeCleanups: null,\n tracking: null,\n});\n\nexport interface TrackingProvider {\n get(): ExecutionContext;\n run<T>(ctx: ExecutionContext, fn: () => T): T;\n}\n\n// ── Sync provider (simple stack-based) ───────────────────────────────────────\n\nlet _currentProvider: TrackingProvider | null = null;\n\nconst syncHook: ContextHook = {\n get: () => _currentProvider?.get() ?? EMPTY_CTX,\n run: <T>(ctx: ExecutionContext, fn: () => T): T => {\n if (_currentProvider) return _currentProvider.run(ctx, fn);\n\n return fn();\n },\n};\n\nexport const setTrackingProvider = (provider: TrackingProvider | null): void => {\n _currentProvider = provider;\n _installContextHook(provider !== null ? syncHook : null);\n};\n\n// ── Async provider (AsyncLocalStorage-based) ─────────────────────────────────\n\n/**\n * Creates a provider that uses `AsyncLocalStorage` to carry the full execution\n * context (tracking + scope cleanups) across async boundaries.\n * Requires Node.js 16+ or a compatible runtime.\n *\n * @example\n * ```ts\n * const provider = createAsyncProvider();\n * setTrackingProvider(provider);\n *\n * // In a request handler:\n * await runWithProvider(provider, requestHandler);\n * ```\n */\nexport const createAsyncProvider = (): TrackingProvider => {\n // Dynamic require so this module can be bundled for environments without AsyncLocalStorage.\n // In browser builds, this code path should never be reached.\n if (typeof require === 'undefined') {\n throw new RippleEnvironmentError(\n 'createAsyncProvider() requires Node.js (async_hooks) and cannot be used in browser environments.',\n );\n }\n\n const { AsyncLocalStorage } = require('async_hooks') as { AsyncLocalStorage: new <T>() => AsyncLocalStorageType<T> };\n const storage = new AsyncLocalStorage<ExecutionContext>();\n\n return {\n get: () => storage.getStore() ?? EMPTY_CTX,\n run: <T>(ctx: ExecutionContext, fn: () => T): T => storage.run(ctx, fn),\n };\n};\n\n/**\n * Runs `fn` inside the given provider with a clean (no tracking, no scope) context.\n * Signals read inside `fn` will not register any tracking deps — equivalent to\n * starting a clean reactive root for each request.\n *\n * @example\n * ```ts\n * const html = await runWithProvider(provider, () => renderToString(App));\n * ```\n */\nexport const runWithProvider = <T>(provider: TrackingProvider, fn: () => T): T =>\n provider.run(freshRequestContext(), fn);\n\n// ── Convenience: run once without installing a persistent provider ─────────────\n\n/**\n * Temporarily installs a provider, runs `fn`, then restores the previous provider.\n * Useful for one-off server renders without modifying global state.\n */\nexport const withProvider = <T>(provider: TrackingProvider, fn: () => T): T => {\n const prevProvider = _currentProvider;\n\n _currentProvider = provider;\n\n const prevHook = _installContextHook(syncHook);\n\n try {\n return provider.run(freshRequestContext(), fn);\n } finally {\n _currentProvider = prevProvider;\n _installContextHook(prevHook);\n }\n};\n"],"mappings":"gJA0CA,IAAM,EAA8B,CAAE,WAAY,EAAA,sBAAsB,EAAG,cAAe,KAAM,SAAU,IAAK,EAQzG,OAA+C,CACnD,WAAY,EAAA,sBAAsB,EAClC,cAAe,KACf,SAAU,IACZ,GASI,EAA4C,KAE1C,EAAwB,CAC5B,QAAW,GAAkB,IAAI,GAAK,EACtC,KAAS,EAAuB,IAC1B,EAAyB,EAAiB,IAAI,EAAK,CAAE,EAElD,EAAG,CAEd,EAEa,EAAuB,GAA4C,CAC9E,EAAmB,EACnB,EAAA,oBAAoB,IAAa,KAAkB,KAAX,CAAe,CACzD,EAkBa,MAA8C,CAGzD,GAAI,OAAO,QAAY,IACrB,MAAM,IAAI,EAAA,uBACR,kGACF,EAGF,GAAM,CAAE,qBAAsB,QAAQ,aAAa,EAC7C,EAAU,IAAI,EAEpB,MAAO,CACL,QAAW,EAAQ,SAAS,GAAK,EACjC,KAAS,EAAuB,IAAmB,EAAQ,IAAI,EAAK,CAAE,CACxE,CACF,EAYa,GAAsB,EAA4B,IAC7D,EAAS,IAAI,EAAoB,EAAG,CAAE,EAQ3B,GAAmB,EAA4B,IAAmB,CAC7E,IAAM,EAAe,EAErB,EAAmB,EAEnB,IAAM,EAAW,EAAA,oBAAoB,CAAQ,EAE7C,GAAI,CACF,OAAO,EAAS,IAAI,EAAoB,EAAG,CAAE,CAC/C,QAAU,CACR,EAAmB,EACnB,EAAA,oBAAoB,CAAQ,CAC9B,CACF"}
|
package/dist/src/ssr/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __require as e } from "../../_virtual/_rolldown/runtime.js";
|
|
2
2
|
import { RippleEnvironmentError as t } from "../../errors.js";
|
|
3
|
-
import { _installContextHook as n, createSchedulingState as r } from "../../
|
|
3
|
+
import { _installContextHook as n, createSchedulingState as r } from "../../execution-context.js";
|
|
4
4
|
//#region src/ssr/index.ts
|
|
5
5
|
var i = {
|
|
6
6
|
scheduling: r(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/ssr/index.ts"],"sourcesContent":["/**\n * /ripple/ssr\n *\n * SSR helpers for installing a custom tracking context provider.\n * Import this sub-entry **only** in server-side code — it is not needed for browser builds.\n *\n * @example\n * ```ts\n * // frameworks/hono.ts\n * import { createAsyncProvider, setTrackingProvider } from '@vielzeug/ripple/ssr';\n *\n * const provider = createAsyncProvider();\n * setTrackingProvider(provider);\n *\n * // Inside a request handler:\n * await runWithProvider(provider, () => renderToString(App));\n * ```\n */\n\nimport { RippleEnvironmentError } from '../errors';\nimport {
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/ssr/index.ts"],"sourcesContent":["/**\n * /ripple/ssr\n *\n * SSR helpers for installing a custom tracking context provider.\n * Import this sub-entry **only** in server-side code — it is not needed for browser builds.\n *\n * @example\n * ```ts\n * // frameworks/hono.ts\n * import { createAsyncProvider, setTrackingProvider } from '@vielzeug/ripple/ssr';\n *\n * const provider = createAsyncProvider();\n * setTrackingProvider(provider);\n *\n * // Inside a request handler:\n * await runWithProvider(provider, () => renderToString(App));\n * ```\n */\n\nimport { RippleEnvironmentError } from '../errors';\nimport {\n _installContextHook,\n createSchedulingState,\n type ContextHook,\n type ExecutionContext,\n} from '../execution-context';\n\n// eslint-disable-next-line no-var\ndeclare var require: (id: string) => unknown;\n\ninterface AsyncLocalStorageType<T> {\n getStore(): T | undefined;\n run<R>(store: T, callback: () => R): R;\n}\n\n// ── Public interfaces ─────────────────────────────────────────────────────────\n\n/**\n * The clean starting context used as a fallback when no request is active\n * (e.g. a signal write outside any `runWithProvider`/`withProvider` call) —\n * a single shared instance is fine here since there's no concurrent request to isolate from.\n */\nconst EMPTY_CTX: ExecutionContext = { scheduling: createSchedulingState(), scopeCleanups: null, tracking: null };\n\n/**\n * Builds a fresh, isolated starting context for one request — no tracking, no scope,\n * and its own `SchedulingState` so this request's `batch()`/flush queue never shares\n * state with a concurrently-running request. Must be called anew per `run()` — reusing\n * a single context object across requests would defeat scheduling isolation.\n */\nconst freshRequestContext = (): ExecutionContext => ({\n scheduling: createSchedulingState(),\n scopeCleanups: null,\n tracking: null,\n});\n\nexport interface TrackingProvider {\n get(): ExecutionContext;\n run<T>(ctx: ExecutionContext, fn: () => T): T;\n}\n\n// ── Sync provider (simple stack-based) ───────────────────────────────────────\n\nlet _currentProvider: TrackingProvider | null = null;\n\nconst syncHook: ContextHook = {\n get: () => _currentProvider?.get() ?? EMPTY_CTX,\n run: <T>(ctx: ExecutionContext, fn: () => T): T => {\n if (_currentProvider) return _currentProvider.run(ctx, fn);\n\n return fn();\n },\n};\n\nexport const setTrackingProvider = (provider: TrackingProvider | null): void => {\n _currentProvider = provider;\n _installContextHook(provider !== null ? syncHook : null);\n};\n\n// ── Async provider (AsyncLocalStorage-based) ─────────────────────────────────\n\n/**\n * Creates a provider that uses `AsyncLocalStorage` to carry the full execution\n * context (tracking + scope cleanups) across async boundaries.\n * Requires Node.js 16+ or a compatible runtime.\n *\n * @example\n * ```ts\n * const provider = createAsyncProvider();\n * setTrackingProvider(provider);\n *\n * // In a request handler:\n * await runWithProvider(provider, requestHandler);\n * ```\n */\nexport const createAsyncProvider = (): TrackingProvider => {\n // Dynamic require so this module can be bundled for environments without AsyncLocalStorage.\n // In browser builds, this code path should never be reached.\n if (typeof require === 'undefined') {\n throw new RippleEnvironmentError(\n 'createAsyncProvider() requires Node.js (async_hooks) and cannot be used in browser environments.',\n );\n }\n\n const { AsyncLocalStorage } = require('async_hooks') as { AsyncLocalStorage: new <T>() => AsyncLocalStorageType<T> };\n const storage = new AsyncLocalStorage<ExecutionContext>();\n\n return {\n get: () => storage.getStore() ?? EMPTY_CTX,\n run: <T>(ctx: ExecutionContext, fn: () => T): T => storage.run(ctx, fn),\n };\n};\n\n/**\n * Runs `fn` inside the given provider with a clean (no tracking, no scope) context.\n * Signals read inside `fn` will not register any tracking deps — equivalent to\n * starting a clean reactive root for each request.\n *\n * @example\n * ```ts\n * const html = await runWithProvider(provider, () => renderToString(App));\n * ```\n */\nexport const runWithProvider = <T>(provider: TrackingProvider, fn: () => T): T =>\n provider.run(freshRequestContext(), fn);\n\n// ── Convenience: run once without installing a persistent provider ─────────────\n\n/**\n * Temporarily installs a provider, runs `fn`, then restores the previous provider.\n * Useful for one-off server renders without modifying global state.\n */\nexport const withProvider = <T>(provider: TrackingProvider, fn: () => T): T => {\n const prevProvider = _currentProvider;\n\n _currentProvider = provider;\n\n const prevHook = _installContextHook(syncHook);\n\n try {\n return provider.run(freshRequestContext(), fn);\n } finally {\n _currentProvider = prevProvider;\n _installContextHook(prevHook);\n }\n};\n"],"mappings":";;;;AA0CA,IAAM,IAA8B;CAAE,YAAY,EAAsB;CAAG,eAAe;CAAM,UAAU;AAAK,GAQzG,WAA+C;CACnD,YAAY,EAAsB;CAClC,eAAe;CACf,UAAU;AACZ,IASI,IAA4C,MAE1C,IAAwB;CAC5B,WAAW,GAAkB,IAAI,KAAK;CACtC,MAAS,GAAuB,MAC1B,IAAyB,EAAiB,IAAI,GAAK,CAAE,IAElD,EAAG;AAEd,GAEa,KAAuB,MAA4C;CAE9E,AADA,IAAmB,GACnB,EAAoB,MAAa,OAAkB,OAAX,CAAe;AACzD,GAkBa,UAA8C;CAGzD,IAAI,MAAmB,QACrB,MAAM,IAAI,EACR,kGACF;CAGF,IAAM,EAAE,yBAAA,EAA8B,aAAa,GAC7C,IAAU,IAAI,EAAoC;CAExD,OAAO;EACL,WAAW,EAAQ,SAAS,KAAK;EACjC,MAAS,GAAuB,MAAmB,EAAQ,IAAI,GAAK,CAAE;CACxE;AACF,GAYa,KAAsB,GAA4B,MAC7D,EAAS,IAAI,EAAoB,GAAG,CAAE,GAQ3B,KAAmB,GAA4B,MAAmB;CAC7E,IAAM,IAAe;CAErB,IAAmB;CAEnB,IAAM,IAAW,EAAoB,CAAQ;CAE7C,IAAI;EACF,OAAO,EAAS,IAAI,EAAoB,GAAG,CAAE;CAC/C,UAAU;EAER,AADA,IAAmB,GACnB,EAAoB,CAAQ;CAC9B;AACF"}
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* await runWithProvider(provider, () => renderToString(App));
|
|
17
17
|
* ```
|
|
18
18
|
*/
|
|
19
|
-
import { type ExecutionContext } from '../
|
|
19
|
+
import { type ExecutionContext } from '../execution-context';
|
|
20
20
|
export interface TrackingProvider {
|
|
21
21
|
get(): ExecutionContext;
|
|
22
22
|
run<T>(ctx: ExecutionContext, fn: () => T): T;
|
package/dist/ssr/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ssr/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ssr/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,sBAAsB,CAAC;AA+B9B,MAAM,WAAW,gBAAgB;IAC/B,GAAG,IAAI,gBAAgB,CAAC;IACxB,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,gBAAgB,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;CAC/C;AAeD,eAAO,MAAM,mBAAmB,GAAI,UAAU,gBAAgB,GAAG,IAAI,KAAG,IAGvE,CAAC;AAIF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,mBAAmB,QAAO,gBAgBtC,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,GAAI,CAAC,EAAE,UAAU,gBAAgB,EAAE,IAAI,MAAM,CAAC,KAAG,CACpC,CAAC;AAI1C;;;GAGG;AACH,eAAO,MAAM,YAAY,GAAI,CAAC,EAAE,UAAU,gBAAgB,EAAE,IAAI,MAAM,CAAC,KAAG,CAazE,CAAC"}
|
package/dist/store.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./devtools-hook.cjs"),t=require("./errors.cjs"),n=require("./scheduling.cjs"),r=require("./symbols.cjs"),i=require("./
|
|
1
|
+
const e=require("./devtools-hook.cjs"),t=require("./errors.cjs"),n=require("./scheduling.cjs"),r=require("./symbols.cjs"),i=require("./signal.cjs"),a=require("./computed.cjs");var o=e=>{if(e===`__proto__`||e===`constructor`||e===`prototype`)throw new t.RippleInvalidStoreError(`Unsafe key "${e}" rejected to prevent prototype pollution.`)},s=(e,t)=>{let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n},c=(e,n,r)=>{if(n.length===0)return r;if(typeof e!=`object`||!e)throw new t.RippleInvalidStoreError(`Cannot write to a nested path through a null or non-object intermediate value.`);let[i,...a]=n,o=e;return{...o,[i]:c(o[i],a,r)}},l=class{[r.IS_SIGNAL]=!0;source_;write_;evict_;disposeSource_;name_;disposed_=!1;get name(){return this.name_??this.source_.name}constructor(e){this.source_=e.source,this.write_=e.write,this.evict_=e.evict,this.disposeSource_=e.disposeSource,this.name_=e.name}get value(){return this.source_.value}set value(e){this.write_(e)}peek(){return this.source_.peek()}subscribe(e){return this.source_.subscribe(e)}get disposed(){return this.disposed_||this.source_.disposed}dispose(){this.disposed_=!0,this.evict_(),this.disposeSource_?.()}[Symbol.dispose](){this.dispose()}},u=class{[r.IS_SIGNAL]=!0;[r.IS_STORE]=!0;name;current_;disposed_;initial_;lensCache_;propSignals_;readonlyProxy_;version_;constructor(e,n){this.name=n,this.current_=structuredClone(e),this.disposed_=!1,this.initial_=structuredClone(e),this.lensCache_=new Map,this.propSignals_=new Map,this.version_=new i.SignalImpl(0,void 0,n?`${n}.version`:void 0),this.readonlyProxy_=new Proxy(this.current_,{deleteProperty(e,n){throw new t.RippleInvalidStoreError(`Direct deletion from store.value is not allowed. Use store.patch() or store.lens(). (key: "${String(n)}")`)},set(e,n){throw new t.RippleInvalidStoreError(`Direct mutation of store.value is not allowed. Use store.patch(), store.lens(), or store.replace(). (key: "${String(n)}")`)}})}propSignalFor_(e){let t=this.propSignals_.get(e);return t===void 0&&(t=new i.SignalImpl(this.current_[e],void 0,this.name===void 0?e:`${this.name}.${e}`),this.propSignals_.set(e,t)),t}setPath_(e,t){let[n,...r]=e,i=this.current_[n],a=c(i,r,t);this.applyTopLevelChange_(n,a)}applyTopLevelChange_(e,t){o(e);let n=this.current_[e];Object.is(n,t)||(this.current_[e]=t,this.propSignalFor_(e).value=t,this.version_.value=this.version_.peek()+1)}deleteTopLevelKey_(e){Object.hasOwn(this.current_,e)&&(delete this.current_[e],this.propSignalFor_(e).value=void 0,this.version_.value=this.version_.peek()+1)}applyFullState_(e){let t=this.current_,r=new Set([...Object.keys(t),...Object.keys(e)]);for(let e of r)o(e);n.batch(()=>{for(let t of r)Object.hasOwn(e,t)?this.applyTopLevelChange_(t,e[t]):this.deleteTopLevelKey_(t)})}get value(){return this.version_.value,this.readonlyProxy_}peek(){return Object.freeze(structuredClone(this.current_))}subscribe=e=>this.version_.subscribe(e);patch(r){if(typeof r!=`object`||!r||Array.isArray(r))throw new t.RippleInvalidStoreError(`store.patch() requires a plain object partial.`);let i=Object.keys(r);if(i.length!==0){for(let e of i)o(e);n.batch(()=>{for(let e of i)this.applyTopLevelChange_(e,r[e])}),e.getDevToolsHook()?.mutate?.({kind:`patch`,name:this.name})}}replace(t){let n=structuredClone(this.current_),r=t(n);r!==n&&(this.applyFullState_(r),e.getDevToolsHook()?.mutate?.({kind:`replace`,name:this.name}))}reset(){this.applyFullState_(this.initial_),e.getDevToolsHook()?.mutate?.({kind:`reset`,name:this.name})}topLevelLens_(t,r){return new l({evict:()=>this.lensCache_.delete(r),source:this.propSignalFor_(t),write:i=>{n.batch(()=>this.applyTopLevelChange_(t,i)),e.getDevToolsHook()?.mutate?.({kind:`lens`,name:this.name,path:r})}})}nestedLens_(t,r){let i=a.computed(()=>s(this.propSignalFor_(t[0]).value,t.slice(1)));return new l({disposeSource:()=>i.dispose(),evict:()=>this.lensCache_.delete(r),name:this.name?`${this.name}.${r}`:r,source:i,write:a=>{Object.is(i.peek(),a)||(n.batch(()=>this.setPath_(t,a)),e.getDevToolsHook()?.mutate?.({kind:`lens`,name:this.name,path:r}))}})}validatedLensParts_(e){let n=e.split(`.`);if(n.length>32)throw new t.RippleInvalidStoreError(`Lens path exceeds maximum depth of 32 segments: "${e}".`);for(let r of n){if(r===``)throw new t.RippleInvalidStoreError(`Empty path segment in lens path "${e}". Check for consecutive dots.`);if(r===`__proto__`||r===`constructor`||r===`prototype`)throw new t.RippleInvalidStoreError(`Unsafe path segment "${r}" in lens path "${e}".`)}return n}lens(e){let t=this.lensCache_.get(e);if(t!==void 0)return t;let n=this.validatedLensParts_(e),r=n.length===1?this.topLevelLens_(n[0],e):this.nestedLens_(n,e);return this.lensCache_.set(e,r),r}get disposed(){return this.disposed_}dispose(){if(!this.disposed_){this.disposed_=!0;for(let e of[...this.lensCache_.values()])e.dispose();this.lensCache_.clear();for(let e of this.propSignals_.values())e.dispose();this.propSignals_.clear(),this.version_.dispose(),e.getDevToolsHook()?.dispose?.({kind:`store`,name:this.name})}}[Symbol.dispose](){this.dispose()}},d=(e,n)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw new t.RippleInvalidStoreError(`store() requires a plain object initial state.`);for(let t of Object.keys(e))o(t);return new u(e,n?.name)};exports.StoreImpl=u,exports.store=d;
|
|
2
2
|
//# sourceMappingURL=store.cjs.map
|
package/dist/store.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.cjs","names":[],"sources":["../src/store.ts"],"sourcesContent":["import type { PathValue, Readable, Signal, Store, Subscription } from './types';\n\nimport { computed } from './computed';\nimport { getDevToolsHook } from './devtools-hook';\nimport { RippleInvalidStoreError } from './errors';\nimport { batch } from './scheduling';\nimport { SignalImpl } from './signal';\nimport { IS_SIGNAL, IS_STORE } from './symbols';\n\n// ── Key safety ────────────────────────────────────────────────────────────────\n\n/**\n * Rejects prototype-pollution-prone top-level keys. Called both as an upfront\n * validation pass (patch/replace — so a later unsafe key never leaves earlier,\n * safe keys partially applied) and defensively inside applyTopLevelChange_.\n */\nconst assertSafeKey = (key: string): void => {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n throw new RippleInvalidStoreError(`Unsafe key \"${key}\" rejected to prevent prototype pollution.`);\n }\n};\n\n// ── Nested path helpers ───────────────────────────────────────────────────────\n\nconst getNestedValue = (obj: unknown, parts: string[]): unknown => {\n let current = obj;\n\n for (const key of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n\n current = (current as Record<string, unknown>)[key];\n }\n\n return current;\n};\n\nconst setNestedValue = <T>(obj: T, parts: string[], value: unknown): T => {\n if (parts.length === 0) return value as T;\n\n if (obj === null || typeof obj !== 'object') {\n throw new RippleInvalidStoreError('Cannot write to a nested path through a null or non-object intermediate value.');\n }\n\n const [key, ...rest] = parts;\n const currentObj = obj as Record<string, unknown>;\n\n return { ...currentObj, [key!]: setNestedValue(currentObj[key!], rest, value) } as T;\n};\n\n// ── LensSignal ───────────────────────────────────────────────────────────────\n//\n// A unified writable Signal that delegates reads to an inner Reactive<V>\n// and writes to an injected callback. Replaces the old TopLevelLens +\n// NestedLens pair — same interface, one class to update when Signal<T> changes.\n\ntype LensOptions<V> = {\n disposeSource?: () => void;\n evict: () => void;\n name?: string;\n source: Readable<V>;\n write: (v: V) => void;\n};\n\nclass LensSignal<V> implements Signal<V> {\n [IS_SIGNAL] = true as const;\n\n private source_: Readable<V>;\n private write_: (v: V) => void;\n private evict_: () => void;\n private disposeSource_: (() => void) | undefined;\n private name_: string | undefined;\n // Own flag — top-level lenses don't own their source (the store does), so\n // `dispose()` can't rely on `source_.disposed` alone to reflect \"was this\n // handle disposed?\". Nested lenses still cascade into `source_.disposed`\n // via `disposeSource_`, so the getter below ORs both signals.\n private disposed_ = false;\n\n get name(): string | undefined {\n return this.name_ ?? this.source_.name;\n }\n\n constructor(opts: LensOptions<V>) {\n this.source_ = opts.source;\n this.write_ = opts.write;\n this.evict_ = opts.evict;\n this.disposeSource_ = opts.disposeSource;\n this.name_ = opts.name;\n }\n\n get value(): V {\n return this.source_.value;\n }\n\n set value(next: V) {\n this.write_(next);\n }\n\n peek(): V {\n return this.source_.peek();\n }\n\n subscribe(listener: () => void): Subscription {\n return this.source_.subscribe(listener);\n }\n\n get disposed(): boolean {\n return this.disposed_ || this.source_.disposed;\n }\n\n dispose(): void {\n this.disposed_ = true;\n this.evict_();\n this.disposeSource_?.();\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\n// ── StoreImpl ─────────────────────────────────────────────────────────────────\n//\n// Fine-grained reactive store.\n//\n// Internal layout:\n// - current_: mutable backing object — NEVER exposed directly, internal writes only\n// - readonlyProxy_: Proxy over current_ that throws on set/delete — returned by .peek()\n// - propSignals_: per-top-level-key SignalImpl, lazily created on first lens/read\n// - version_: whole-store monotonic counter (bumped on any change, used by subscribe())\n//\n// StoreImpl is a standalone class — does not extend ReactiveBase.\n// applyTopLevelChange_() has NO batch() wrapper — callers that need atomicity\n// (patch, replace, reset, and both lens write paths) wrap with batch() at their\n// own call sites; the method itself stays free of any scheduling concern.\n\nexport class StoreImpl<T extends object> implements Store<T> {\n [IS_SIGNAL] = true as const;\n [IS_STORE] = true as const;\n\n readonly name: string | undefined;\n\n private current_: T;\n private disposed_: boolean;\n private readonly initial_: T;\n private readonly lensCache_: Map<string, LensSignal<unknown>>;\n private readonly propSignals_: Map<string, SignalImpl<unknown>>;\n private readonly readonlyProxy_: Readonly<T>;\n private readonly version_: SignalImpl<number>;\n\n constructor(initial: T, name?: string) {\n this.name = name;\n this.current_ = structuredClone(initial);\n this.disposed_ = false;\n this.initial_ = structuredClone(initial);\n this.lensCache_ = new Map();\n this.propSignals_ = new Map();\n this.version_ = new SignalImpl(0, undefined, name ? `${name}.version` : undefined);\n\n // Shallow proxy: throws on any top-level mutation attempt.\n // All external reads go through this proxy; internal writes use this.current_ directly.\n // NOTE: nested objects are plain references — mutations on nested properties\n // bypass reactivity. Use store.lens('a.b') or store.replace() to update nested state.\n this.readonlyProxy_ = new Proxy(this.current_, {\n deleteProperty(_target, key): never {\n throw new RippleInvalidStoreError(\n `Direct deletion from store.value is not allowed. Use store.patch() or store.lens(). (key: \"${String(key)}\")`,\n );\n },\n set(_target, key): never {\n throw new RippleInvalidStoreError(\n `Direct mutation of store.value is not allowed. Use store.patch(), store.lens(), or store.replace(). (key: \"${String(key)}\")`,\n );\n },\n }) as Readonly<T>;\n }\n\n /** Returns (or lazily creates) the per-property signal for a top-level key. */\n propSignalFor_(key: string): SignalImpl<unknown> {\n let sig = this.propSignals_.get(key);\n\n if (sig === undefined) {\n sig = new SignalImpl(\n (this.current_ as Record<string, unknown>)[key],\n undefined,\n this.name !== undefined ? `${this.name}.${key}` : key,\n );\n this.propSignals_.set(key, sig);\n }\n\n return sig;\n }\n\n /** @internal Called by nested lens write to update the store through a path. */\n setPath_(parts: string[], value: unknown): void {\n const [rootKey, ...rest] = parts;\n const rootVal = (this.current_ as Record<string, unknown>)[rootKey!];\n const newRootVal = setNestedValue(rootVal, rest, value);\n\n this.applyTopLevelChange_(rootKey!, newRootVal);\n }\n\n /**\n * @internal Apply a change to a top-level key and propagate to prop signal + version.\n * R4: No batch() wrapper — callers that need atomicity must wrap themselves.\n */\n applyTopLevelChange_(key: string, newValue: unknown): void {\n assertSafeKey(key);\n\n const current = (this.current_ as Record<string, unknown>)[key];\n\n if (Object.is(current, newValue)) return;\n\n (this.current_ as Record<string, unknown>)[key] = newValue;\n this.propSignalFor_(key).value = newValue as never;\n this.version_.value = this.version_.peek() + 1;\n }\n\n /**\n * @internal Removes a top-level key entirely (as opposed to applyTopLevelChange_,\n * which can only ever assign a value — including `undefined` — never delete the key).\n * Companion used by applyFullState_ for keys absent from the target state.\n */\n deleteTopLevelKey_(key: string): void {\n if (!Object.hasOwn(this.current_ as object, key)) return;\n\n delete (this.current_ as Record<string, unknown>)[key];\n this.propSignalFor_(key).value = undefined as never;\n this.version_.value = this.version_.peek() + 1;\n }\n\n /**\n * @internal Applies `next` as the authoritative full top-level state: keys present in\n * `next` are set via applyTopLevelChange_, keys present in current_ but absent from\n * `next` are removed via deleteTopLevelKey_. Shared by replace() and reset() so both\n * can actually remove a key, not just null it out — see B1 in the ripple improvement plan.\n */\n applyFullState_(next: Record<string, unknown>): void {\n const current = this.current_ as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(current), ...Object.keys(next)]);\n\n for (const key of allKeys) assertSafeKey(key);\n\n batch(() => {\n for (const key of allKeys) {\n if (Object.hasOwn(next, key)) {\n this.applyTopLevelChange_(key, next[key]);\n } else {\n this.deleteTopLevelKey_(key);\n }\n }\n });\n }\n\n /**\n * Returns the current state as a tracked read — registers the store as a dependency\n * inside `effect()` / `computed()`. Any mutation re-runs the subscriber.\n * For untracked one-off reads, use `peek()` instead.\n */\n get value(): Readonly<T> {\n void this.version_.value;\n\n return this.readonlyProxy_;\n }\n\n /**\n * Returns a frozen deep snapshot of the current state.\n * The returned object reflects state at call time — it does not update as the store mutates.\n * Nested objects are cloned (not aliased), so mutating nested properties on the snapshot\n * does not affect the live store state.\n * Use for serialization or one-off reads outside reactive contexts.\n * For reactive reads, use `store.lens(path)` instead.\n */\n peek(): Readonly<T> {\n return Object.freeze(structuredClone(this.current_)) as Readonly<T>;\n }\n\n readonly subscribe = (listener: () => void): Subscription => {\n return this.version_.subscribe(listener);\n };\n\n patch(partial: Partial<T>): void {\n if (typeof partial !== 'object' || partial === null || Array.isArray(partial)) {\n throw new RippleInvalidStoreError('store.patch() requires a plain object partial.');\n }\n\n const keys = Object.keys(partial) as Array<keyof T & string>;\n\n if (keys.length === 0) return;\n\n // Validate every key before mutating any — a key rejected mid-loop must not\n // leave earlier, safe keys partially applied (and un-notified — see batch()'s\n // error path, which clears the pending flush queue rather than replaying it).\n for (const key of keys) assertSafeKey(key);\n\n batch(() => {\n for (const key of keys) {\n this.applyTopLevelChange_(key, (partial as Record<string, unknown>)[key]);\n }\n });\n\n getDevToolsHook()?.mutate?.({ kind: 'patch', name: this.name });\n }\n\n replace(fn: (state: Readonly<T>) => T): void {\n const snapshot = structuredClone(this.current_) as Readonly<T>;\n const next = fn(snapshot);\n\n if (next === snapshot) return;\n\n this.applyFullState_(next as Record<string, unknown>);\n\n getDevToolsHook()?.mutate?.({ kind: 'replace', name: this.name });\n }\n\n reset(): void {\n this.applyFullState_(this.initial_ as Record<string, unknown>);\n\n getDevToolsHook()?.mutate?.({ kind: 'reset', name: this.name });\n }\n\n lens<P extends string>(path: P): Signal<PathValue<T, P>> {\n const cached = this.lensCache_.get(path);\n\n if (cached !== undefined) return cached as unknown as Signal<PathValue<T, P>>;\n\n const evict = (): void => {\n this.lensCache_.delete(path);\n };\n\n const parts = path.split('.');\n\n if (parts.length > 32) {\n throw new RippleInvalidStoreError(`Lens path exceeds maximum depth of 32 segments: \"${path}\".`);\n }\n\n for (const part of parts) {\n if (part === '') {\n throw new RippleInvalidStoreError(`Empty path segment in lens path \"${path}\". Check for consecutive dots.`);\n }\n\n if (part === '__proto__' || part === 'constructor' || part === 'prototype') {\n throw new RippleInvalidStoreError(`Unsafe path segment \"${part}\" in lens path \"${path}\".`);\n }\n }\n\n let lens: LensSignal<unknown>;\n\n if (parts.length === 1) {\n // Top-level lens: backed directly by the per-property signal.\n const propSig = this.propSignalFor_(parts[0]!) as SignalImpl<PathValue<T, P>>;\n\n lens = new LensSignal<PathValue<T, P>>({\n evict,\n // propSig lifecycle is owned by the store — do not dispose it\n source: propSig,\n write: (v) => {\n batch(() => this.applyTopLevelChange_(parts[0]!, v));\n getDevToolsHook()?.mutate?.({ kind: 'lens', name: this.name, path });\n },\n }) as unknown as LensSignal<unknown>;\n } else {\n // Nested lens: backed by a derived computed over the root property signal.\n // Write path uses batch() here so nested lens writes remain atomic.\n const readComputed = computed(\n () => getNestedValue(this.propSignalFor_(parts[0]!).value, parts.slice(1)) as PathValue<T, P>,\n );\n\n lens = new LensSignal<PathValue<T, P>>({\n disposeSource: () => readComputed.dispose(),\n evict,\n name: this.name ? `${this.name}.${path}` : path,\n source: readComputed,\n write: (v) => {\n const current = readComputed.peek();\n\n if (Object.is(current, v)) return;\n\n batch(() => this.setPath_(parts, v));\n getDevToolsHook()?.mutate?.({ kind: 'lens', name: this.name, path });\n },\n }) as unknown as LensSignal<unknown>;\n }\n\n this.lensCache_.set(path, lens);\n\n return lens as unknown as Signal<PathValue<T, P>>;\n }\n\n get disposed(): boolean {\n return this.disposed_;\n }\n\n dispose(): void {\n if (this.disposed_) return;\n\n this.disposed_ = true;\n\n for (const lens of [...this.lensCache_.values()]) {\n lens.dispose();\n }\n\n this.lensCache_.clear();\n\n for (const sig of this.propSignals_.values()) {\n sig.dispose();\n }\n\n this.propSignals_.clear();\n this.version_.dispose();\n getDevToolsHook()?.dispose?.({ kind: 'store', name: this.name });\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\nexport const store = <T extends object>(initial: T, options?: { name?: string }): Store<T> => {\n if (typeof initial !== 'object' || initial === null || Array.isArray(initial)) {\n throw new RippleInvalidStoreError('store() requires a plain object initial state.');\n }\n\n // Same guard as patch()/replace() — reject an unsafe top-level key (e.g. a real\n // own \"__proto__\" property from JSON.parse) before it ever enters store state.\n for (const key of Object.keys(initial)) assertSafeKey(key);\n\n return new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from './types';\n\nimport { computed } from './computed';\nimport { getDevToolsHook } from './devtools-hook';\nimport { RippleInvalidStoreError } from './errors';\nimport { batch } from './scheduling';\nimport { SignalImpl } from './signal';\nimport { IS_SIGNAL, IS_STORE } from './symbols';\n\n// ── Key safety ────────────────────────────────────────────────────────────────\n\n/**\n * Rejects prototype-pollution-prone top-level keys. Called both as an upfront\n * validation pass (patch/replace — so a later unsafe key never leaves earlier,\n * safe keys partially applied) and defensively inside applyTopLevelChange_.\n */\nconst assertSafeKey = (key: string): void => {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n throw new RippleInvalidStoreError(`Unsafe key \"${key}\" rejected to prevent prototype pollution.`);\n }\n};\n\n// ── Nested path helpers ───────────────────────────────────────────────────────\n\nconst getNestedValue = (obj: unknown, parts: string[]): unknown => {\n let current = obj;\n\n for (const key of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n\n current = (current as Record<string, unknown>)[key];\n }\n\n return current;\n};\n\nconst setNestedValue = <T>(obj: T, parts: string[], value: unknown): T => {\n if (parts.length === 0) return value as T;\n\n if (obj === null || typeof obj !== 'object') {\n throw new RippleInvalidStoreError('Cannot write to a nested path through a null or non-object intermediate value.');\n }\n\n const [key, ...rest] = parts;\n const currentObj = obj as Record<string, unknown>;\n\n return { ...currentObj, [key!]: setNestedValue(currentObj[key!], rest, value) } as T;\n};\n\n// ── LensSignal ───────────────────────────────────────────────────────────────\n//\n// A unified writable Signal that delegates reads to an inner Reactive<V>\n// and writes to an injected callback. Replaces the old TopLevelLens +\n// NestedLens pair — same interface, one class to update when Signal<T> changes.\n\ntype LensOptions<V> = {\n disposeSource?: () => void;\n evict: () => void;\n name?: string;\n source: Readable<V>;\n write: (v: V) => void;\n};\n\nclass LensSignal<V> implements Signal<V> {\n [IS_SIGNAL] = true as const;\n\n private source_: Readable<V>;\n private write_: (v: V) => void;\n private evict_: () => void;\n private disposeSource_: (() => void) | undefined;\n private name_: string | undefined;\n // Own flag — top-level lenses don't own their source (the store does), so\n // `dispose()` can't rely on `source_.disposed` alone to reflect \"was this\n // handle disposed?\". Nested lenses still cascade into `source_.disposed`\n // via `disposeSource_`, so the getter below ORs both signals.\n private disposed_ = false;\n\n get name(): string | undefined {\n return this.name_ ?? this.source_.name;\n }\n\n constructor(opts: LensOptions<V>) {\n this.source_ = opts.source;\n this.write_ = opts.write;\n this.evict_ = opts.evict;\n this.disposeSource_ = opts.disposeSource;\n this.name_ = opts.name;\n }\n\n get value(): V {\n return this.source_.value;\n }\n\n set value(next: V) {\n this.write_(next);\n }\n\n peek(): V {\n return this.source_.peek();\n }\n\n subscribe(listener: () => void): Subscription {\n return this.source_.subscribe(listener);\n }\n\n get disposed(): boolean {\n return this.disposed_ || this.source_.disposed;\n }\n\n dispose(): void {\n this.disposed_ = true;\n this.evict_();\n this.disposeSource_?.();\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\n// ── StoreImpl ─────────────────────────────────────────────────────────────────\n//\n// Fine-grained reactive store.\n//\n// Internal layout:\n// - current_: mutable backing object — NEVER exposed directly, internal writes only\n// - readonlyProxy_: Proxy over current_ that throws on set/delete — returned by .peek()\n// - propSignals_: per-top-level-key SignalImpl, lazily created on first lens/read\n// - version_: whole-store monotonic counter (bumped on any change, used by subscribe())\n//\n// StoreImpl is a standalone class — does not extend ReactiveBase.\n// applyTopLevelChange_() has NO batch() wrapper — callers that need atomicity\n// (patch, replace, reset, and both lens write paths) wrap with batch() at their\n// own call sites; the method itself stays free of any scheduling concern.\n\nexport class StoreImpl<T extends object> implements Store<T> {\n [IS_SIGNAL] = true as const;\n [IS_STORE] = true as const;\n\n readonly name: string | undefined;\n\n private current_: T;\n private disposed_: boolean;\n private readonly initial_: T;\n private readonly lensCache_: Map<string, LensSignal<unknown>>;\n private readonly propSignals_: Map<string, SignalImpl<unknown>>;\n private readonly readonlyProxy_: Readonly<T>;\n private readonly version_: SignalImpl<number>;\n\n constructor(initial: T, name?: string) {\n this.name = name;\n this.current_ = structuredClone(initial);\n this.disposed_ = false;\n this.initial_ = structuredClone(initial);\n this.lensCache_ = new Map();\n this.propSignals_ = new Map();\n this.version_ = new SignalImpl(0, undefined, name ? `${name}.version` : undefined);\n\n // Shallow proxy: throws on any top-level mutation attempt.\n // All external reads go through this proxy; internal writes use this.current_ directly.\n // NOTE: nested objects are plain references — mutations on nested properties\n // bypass reactivity. Use store.lens('a.b') or store.replace() to update nested state.\n this.readonlyProxy_ = new Proxy(this.current_, {\n deleteProperty(_target, key): never {\n throw new RippleInvalidStoreError(\n `Direct deletion from store.value is not allowed. Use store.patch() or store.lens(). (key: \"${String(key)}\")`,\n );\n },\n set(_target, key): never {\n throw new RippleInvalidStoreError(\n `Direct mutation of store.value is not allowed. Use store.patch(), store.lens(), or store.replace(). (key: \"${String(key)}\")`,\n );\n },\n }) as Readonly<T>;\n }\n\n /** Returns (or lazily creates) the per-property signal for a top-level key. */\n propSignalFor_(key: string): SignalImpl<unknown> {\n let sig = this.propSignals_.get(key);\n\n if (sig === undefined) {\n sig = new SignalImpl(\n (this.current_ as Record<string, unknown>)[key],\n undefined,\n this.name !== undefined ? `${this.name}.${key}` : key,\n );\n this.propSignals_.set(key, sig);\n }\n\n return sig;\n }\n\n /** @internal Called by nested lens write to update the store through a path. */\n setPath_(parts: string[], value: unknown): void {\n const [rootKey, ...rest] = parts;\n const rootVal = (this.current_ as Record<string, unknown>)[rootKey!];\n const newRootVal = setNestedValue(rootVal, rest, value);\n\n this.applyTopLevelChange_(rootKey!, newRootVal);\n }\n\n /**\n * @internal Apply a change to a top-level key and propagate to prop signal + version.\n * R4: No batch() wrapper — callers that need atomicity must wrap themselves.\n */\n applyTopLevelChange_(key: string, newValue: unknown): void {\n assertSafeKey(key);\n\n const current = (this.current_ as Record<string, unknown>)[key];\n\n if (Object.is(current, newValue)) return;\n\n (this.current_ as Record<string, unknown>)[key] = newValue;\n this.propSignalFor_(key).value = newValue as never;\n this.version_.value = this.version_.peek() + 1;\n }\n\n /**\n * @internal Removes a top-level key entirely (as opposed to applyTopLevelChange_,\n * which can only ever assign a value — including `undefined` — never delete the key).\n * Companion used by applyFullState_ for keys absent from the target state.\n */\n deleteTopLevelKey_(key: string): void {\n if (!Object.hasOwn(this.current_ as object, key)) return;\n\n delete (this.current_ as Record<string, unknown>)[key];\n this.propSignalFor_(key).value = undefined as never;\n this.version_.value = this.version_.peek() + 1;\n }\n\n /**\n * @internal Applies `next` as the authoritative full top-level state: keys present in\n * `next` are set via applyTopLevelChange_, keys present in current_ but absent from\n * `next` are removed via deleteTopLevelKey_. Shared by replace() and reset() so both\n * can actually remove a key, not just null it out — see B1 in the ripple improvement plan.\n */\n applyFullState_(next: Record<string, unknown>): void {\n const current = this.current_ as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(current), ...Object.keys(next)]);\n\n for (const key of allKeys) assertSafeKey(key);\n\n batch(() => {\n for (const key of allKeys) {\n if (Object.hasOwn(next, key)) {\n this.applyTopLevelChange_(key, next[key]);\n } else {\n this.deleteTopLevelKey_(key);\n }\n }\n });\n }\n\n /**\n * Returns the current state as a tracked read — registers the store as a dependency\n * inside `effect()` / `computed()`. Any mutation re-runs the subscriber.\n * For untracked one-off reads, use `peek()` instead.\n */\n get value(): Readonly<T> {\n void this.version_.value;\n\n return this.readonlyProxy_;\n }\n\n /**\n * Returns a frozen deep snapshot of the current state.\n * The returned object reflects state at call time — it does not update as the store mutates.\n * Nested objects are cloned (not aliased), so mutating nested properties on the snapshot\n * does not affect the live store state.\n * Use for serialization or one-off reads outside reactive contexts.\n * For reactive reads, use `store.lens(path)` instead.\n */\n peek(): Readonly<T> {\n return Object.freeze(structuredClone(this.current_)) as Readonly<T>;\n }\n\n readonly subscribe = (listener: () => void): Subscription => {\n return this.version_.subscribe(listener);\n };\n\n patch(partial: Partial<T>): void {\n if (typeof partial !== 'object' || partial === null || Array.isArray(partial)) {\n throw new RippleInvalidStoreError('store.patch() requires a plain object partial.');\n }\n\n const keys = Object.keys(partial) as Array<keyof T & string>;\n\n if (keys.length === 0) return;\n\n // Validate every key before mutating any — a key rejected mid-loop must not\n // leave earlier, safe keys partially applied (and un-notified — see batch()'s\n // error path, which clears the pending flush queue rather than replaying it).\n for (const key of keys) assertSafeKey(key);\n\n batch(() => {\n for (const key of keys) {\n this.applyTopLevelChange_(key, (partial as Record<string, unknown>)[key]);\n }\n });\n\n getDevToolsHook()?.mutate?.({ kind: 'patch', name: this.name });\n }\n\n replace(fn: (state: Readonly<T>) => T): void {\n const snapshot = structuredClone(this.current_) as Readonly<T>;\n const next = fn(snapshot);\n\n if (next === snapshot) return;\n\n this.applyFullState_(next as Record<string, unknown>);\n\n getDevToolsHook()?.mutate?.({ kind: 'replace', name: this.name });\n }\n\n reset(): void {\n this.applyFullState_(this.initial_ as Record<string, unknown>);\n\n getDevToolsHook()?.mutate?.({ kind: 'reset', name: this.name });\n }\n\n /**\n * Top-level lens: backed directly by the per-property signal — no extra graph node.\n * The store owns propSig's lifecycle, so this lens has no `disposeSource`.\n */\n private topLevelLens_<V>(key: string, path: string): LensSignal<V> {\n return new LensSignal<V>({\n evict: () => this.lensCache_.delete(path),\n source: this.propSignalFor_(key) as SignalImpl<V>,\n write: (v) => {\n batch(() => this.applyTopLevelChange_(key, v));\n getDevToolsHook()?.mutate?.({ kind: 'lens', name: this.name, path });\n },\n });\n }\n\n /**\n * Nested lens: backed by a derived `computed()` over the root property signal — the\n * lens owns that computed (disposeSource) since nothing else references it.\n * Write path batches the update so a nested lens write remains atomic.\n */\n private nestedLens_<V>(parts: string[], path: string): LensSignal<V> {\n const readComputed = computed(() => getNestedValue(this.propSignalFor_(parts[0]!).value, parts.slice(1)) as V);\n\n return new LensSignal<V>({\n disposeSource: () => readComputed.dispose(),\n evict: () => this.lensCache_.delete(path),\n name: this.name ? `${this.name}.${path}` : path,\n source: readComputed,\n write: (v) => {\n if (Object.is(readComputed.peek(), v)) return;\n\n batch(() => this.setPath_(parts, v));\n getDevToolsHook()?.mutate?.({ kind: 'lens', name: this.name, path });\n },\n });\n }\n\n /** Splits `path` on `.` and rejects empty/unsafe/too-deep segments before any lens is built. */\n private validatedLensParts_(path: string): string[] {\n const parts = path.split('.');\n\n if (parts.length > 32) {\n throw new RippleInvalidStoreError(`Lens path exceeds maximum depth of 32 segments: \"${path}\".`);\n }\n\n for (const part of parts) {\n if (part === '') {\n throw new RippleInvalidStoreError(`Empty path segment in lens path \"${path}\". Check for consecutive dots.`);\n }\n\n if (part === '__proto__' || part === 'constructor' || part === 'prototype') {\n throw new RippleInvalidStoreError(`Unsafe path segment \"${part}\" in lens path \"${path}\".`);\n }\n }\n\n return parts;\n }\n\n lens<P extends string>(path: P): Signal<PathValue<T, P>> {\n const cached = this.lensCache_.get(path);\n\n if (cached !== undefined) return cached as unknown as Signal<PathValue<T, P>>;\n\n const parts = this.validatedLensParts_(path);\n const lens =\n parts.length === 1\n ? this.topLevelLens_<PathValue<T, P>>(parts[0]!, path)\n : this.nestedLens_<PathValue<T, P>>(parts, path);\n\n this.lensCache_.set(path, lens as unknown as LensSignal<unknown>);\n\n return lens;\n }\n\n get disposed(): boolean {\n return this.disposed_;\n }\n\n dispose(): void {\n if (this.disposed_) return;\n\n this.disposed_ = true;\n\n for (const lens of [...this.lensCache_.values()]) {\n lens.dispose();\n }\n\n this.lensCache_.clear();\n\n for (const sig of this.propSignals_.values()) {\n sig.dispose();\n }\n\n this.propSignals_.clear();\n this.version_.dispose();\n getDevToolsHook()?.dispose?.({ kind: 'store', name: this.name });\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\nexport const store = <T extends object>(initial: T, options?: { name?: string }): Store<T> => {\n if (typeof initial !== 'object' || initial === null || Array.isArray(initial)) {\n throw new RippleInvalidStoreError('store() requires a plain object initial state.');\n }\n\n // Same guard as patch()/replace() — reject an unsafe top-level key (e.g. a real\n // own \"__proto__\" property from JSON.parse) before it ever enters store state.\n for (const key of Object.keys(initial)) assertSafeKey(key);\n\n return new StoreImpl(initial, options?.name) as unknown as Store<T>;\n};\n"],"mappings":"gLA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EAAS,GAAS,IAAI,CAC7C"}
|
package/dist/store.d.ts
CHANGED
|
@@ -34,6 +34,19 @@ export declare class StoreImpl<T extends object> implements Store<T> {
|
|
|
34
34
|
patch(partial: Partial<T>): void;
|
|
35
35
|
replace(fn: (state: Readonly<T>) => T): void;
|
|
36
36
|
reset(): void;
|
|
37
|
+
/**
|
|
38
|
+
* Top-level lens: backed directly by the per-property signal — no extra graph node.
|
|
39
|
+
* The store owns propSig's lifecycle, so this lens has no `disposeSource`.
|
|
40
|
+
*/
|
|
41
|
+
private topLevelLens_;
|
|
42
|
+
/**
|
|
43
|
+
* Nested lens: backed by a derived `computed()` over the root property signal — the
|
|
44
|
+
* lens owns that computed (disposeSource) since nothing else references it.
|
|
45
|
+
* Write path batches the update so a nested lens write remains atomic.
|
|
46
|
+
*/
|
|
47
|
+
private nestedLens_;
|
|
48
|
+
/** Splits `path` on `.` and rejects empty/unsafe/too-deep segments before any lens is built. */
|
|
49
|
+
private validatedLensParts_;
|
|
37
50
|
lens<P extends string>(path: P): Signal<PathValue<T, P>>;
|
|
38
51
|
get disposed(): boolean;
|
|
39
52
|
dispose(): void;
|
package/dist/store.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAY,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAMhF,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAgIhD,qBAAa,SAAS,CAAC,CAAC,SAAS,MAAM,CAAE,YAAW,KAAK,CAAC,CAAC,CAAC;IAC1D,CAAC,SAAS,CAAC,EAAG,IAAI,CAAU;IAC5B,CAAC,QAAQ,CAAC,EAAG,IAAI,CAAU;IAE3B,QAAQ,CAAC,IAAI,EAAE,MAAM,GA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