@pyreon/state-tree 0.0.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/LICENSE +21 -0
- package/README.md +249 -0
- package/lib/analysis/devtools.js.html +5406 -0
- package/lib/analysis/index.js.html +5406 -0
- package/lib/devtools.js +111 -0
- package/lib/devtools.js.map +1 -0
- package/lib/index.js +353 -0
- package/lib/index.js.map +1 -0
- package/lib/types/devtools.d.ts +104 -0
- package/lib/types/devtools.d.ts.map +1 -0
- package/lib/types/devtools2.d.ts +40 -0
- package/lib/types/devtools2.d.ts.map +1 -0
- package/lib/types/index.d.ts +316 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index2.d.ts +198 -0
- package/lib/types/index2.d.ts.map +1 -0
- package/package.json +54 -0
- package/src/devtools.ts +87 -0
- package/src/index.ts +29 -0
- package/src/instance.ts +128 -0
- package/src/middleware.ts +57 -0
- package/src/model.ts +117 -0
- package/src/patch.ts +173 -0
- package/src/registry.ts +16 -0
- package/src/snapshot.ts +66 -0
- package/src/tests/devtools.test.ts +163 -0
- package/src/tests/model.test.ts +718 -0
- package/src/types.ts +98 -0
package/lib/devtools.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
//#region src/registry.ts
|
|
2
|
+
/**
|
|
3
|
+
* WeakMap from every model instance object → its internal metadata.
|
|
4
|
+
* Shared across patch, middleware, and snapshot modules.
|
|
5
|
+
*/
|
|
6
|
+
const instanceMeta = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
/** Returns true when a value is a model instance (has metadata registered). */
|
|
8
|
+
function isModelInstance(value) {
|
|
9
|
+
return value != null && typeof value === "object" && instanceMeta.has(value);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/snapshot.ts
|
|
14
|
+
/**
|
|
15
|
+
* Serialize a model instance to a plain JS object (no signals, no functions).
|
|
16
|
+
* Nested model instances are recursively serialized.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* getSnapshot(counter) // { count: 6 }
|
|
20
|
+
* getSnapshot(app) // { profile: { name: "Alice" }, title: "My App" }
|
|
21
|
+
*/
|
|
22
|
+
function getSnapshot(instance) {
|
|
23
|
+
const meta = instanceMeta.get(instance);
|
|
24
|
+
if (!meta) throw new Error("[@pyreon/state-tree] getSnapshot: not a model instance");
|
|
25
|
+
const out = {};
|
|
26
|
+
for (const key of meta.stateKeys) {
|
|
27
|
+
const sig = instance[key];
|
|
28
|
+
if (!sig) continue;
|
|
29
|
+
const val = sig.peek();
|
|
30
|
+
out[key] = isModelInstance(val) ? getSnapshot(val) : val;
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/devtools.ts
|
|
37
|
+
/**
|
|
38
|
+
* @pyreon/state-tree devtools introspection API.
|
|
39
|
+
* Import: `import { ... } from "@pyreon/state-tree/devtools"`
|
|
40
|
+
*/
|
|
41
|
+
const _activeModels = /* @__PURE__ */ new Map();
|
|
42
|
+
const _listeners = /* @__PURE__ */ new Set();
|
|
43
|
+
function _notify() {
|
|
44
|
+
for (const listener of _listeners) listener();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Register a model instance for devtools inspection.
|
|
48
|
+
* Call this when creating instances you want visible in devtools.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* const counter = Counter.create()
|
|
52
|
+
* registerInstance("app-counter", counter)
|
|
53
|
+
*/
|
|
54
|
+
function registerInstance(name, instance) {
|
|
55
|
+
_activeModels.set(name, new WeakRef(instance));
|
|
56
|
+
_notify();
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Unregister a model instance.
|
|
60
|
+
*/
|
|
61
|
+
function unregisterInstance(name) {
|
|
62
|
+
_activeModels.delete(name);
|
|
63
|
+
_notify();
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Get all registered model instance names.
|
|
67
|
+
* Automatically cleans up garbage-collected instances.
|
|
68
|
+
*/
|
|
69
|
+
function getActiveModels() {
|
|
70
|
+
for (const [name, ref] of _activeModels) if (ref.deref() === void 0) _activeModels.delete(name);
|
|
71
|
+
return [..._activeModels.keys()];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Get a model instance by name (or undefined if GC'd or not registered).
|
|
75
|
+
*/
|
|
76
|
+
function getModelInstance(name) {
|
|
77
|
+
const ref = _activeModels.get(name);
|
|
78
|
+
if (!ref) return void 0;
|
|
79
|
+
const instance = ref.deref();
|
|
80
|
+
if (!instance) {
|
|
81
|
+
_activeModels.delete(name);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
return instance;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Get a snapshot of a registered model instance.
|
|
88
|
+
*/
|
|
89
|
+
function getModelSnapshot(name) {
|
|
90
|
+
const instance = getModelInstance(name);
|
|
91
|
+
if (!instance) return void 0;
|
|
92
|
+
return getSnapshot(instance);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Subscribe to model registry changes. Returns unsubscribe function.
|
|
96
|
+
*/
|
|
97
|
+
function onModelChange(listener) {
|
|
98
|
+
_listeners.add(listener);
|
|
99
|
+
return () => {
|
|
100
|
+
_listeners.delete(listener);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** @internal — reset devtools registry (for tests). */
|
|
104
|
+
function _resetDevtools() {
|
|
105
|
+
_activeModels.clear();
|
|
106
|
+
_listeners.clear();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
//#endregion
|
|
110
|
+
export { _resetDevtools, getActiveModels, getModelInstance, getModelSnapshot, onModelChange, registerInstance, unregisterInstance };
|
|
111
|
+
//# sourceMappingURL=devtools.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.js","names":[],"sources":["../src/registry.ts","../src/snapshot.ts","../src/devtools.ts"],"sourcesContent":["import type { InstanceMeta } from './types'\n\n/**\n * WeakMap from every model instance object → its internal metadata.\n * Shared across patch, middleware, and snapshot modules.\n */\nexport const instanceMeta = new WeakMap<object, InstanceMeta>()\n\n/** Returns true when a value is a model instance (has metadata registered). */\nexport function isModelInstance(value: unknown): boolean {\n return (\n value != null &&\n typeof value === 'object' &&\n instanceMeta.has(value as object)\n )\n}\n","import type { Signal } from '@pyreon/reactivity'\nimport { batch } from '@pyreon/reactivity'\nimport { instanceMeta, isModelInstance } from './registry'\nimport type { Snapshot, StateShape } from './types'\n\n// ─── getSnapshot ──────────────────────────────────────────────────────────────\n\n/**\n * Serialize a model instance to a plain JS object (no signals, no functions).\n * Nested model instances are recursively serialized.\n *\n * @example\n * getSnapshot(counter) // { count: 6 }\n * getSnapshot(app) // { profile: { name: \"Alice\" }, title: \"My App\" }\n */\nexport function getSnapshot<TState extends StateShape>(\n instance: object,\n): Snapshot<TState> {\n const meta = instanceMeta.get(instance)\n if (!meta)\n throw new Error('[@pyreon/state-tree] getSnapshot: not a model instance')\n\n const out: Record<string, unknown> = {}\n for (const key of meta.stateKeys) {\n const sig = (instance as Record<string, Signal<unknown>>)[key]\n if (!sig) continue\n const val = sig.peek()\n out[key] = isModelInstance(val) ? getSnapshot(val as object) : val\n }\n return out as Snapshot<TState>\n}\n\n// ─── applySnapshot ────────────────────────────────────────────────────────────\n\n/**\n * Restore a model instance from a plain-object snapshot.\n * All signal writes are coalesced via `batch()` for a single reactive flush.\n * Keys absent from the snapshot are left unchanged.\n *\n * @example\n * applySnapshot(counter, { count: 0 })\n */\nexport function applySnapshot<TState extends StateShape>(\n instance: object,\n snapshot: Partial<Snapshot<TState>>,\n): void {\n const meta = instanceMeta.get(instance)\n if (!meta)\n throw new Error('[@pyreon/state-tree] applySnapshot: not a model instance')\n\n batch(() => {\n for (const key of meta.stateKeys) {\n if (!(key in snapshot)) continue\n const sig = (instance as Record<string, Signal<unknown>>)[key]\n if (!sig) continue\n const val = (snapshot as Record<string, unknown>)[key]\n const current = sig.peek()\n if (isModelInstance(current)) {\n // Recurse into nested model instance\n applySnapshot(current as object, val as Record<string, unknown>)\n } else {\n sig.set(val)\n }\n }\n })\n}\n","/**\n * @pyreon/state-tree devtools introspection API.\n * Import: `import { ... } from \"@pyreon/state-tree/devtools\"`\n */\n\nimport { getSnapshot } from './snapshot'\n\n// Track active model instances (devtools-only, opt-in)\nconst _activeModels = new Map<string, WeakRef<object>>()\nconst _listeners = new Set<() => void>()\n\nfunction _notify(): void {\n for (const listener of _listeners) listener()\n}\n\n/**\n * Register a model instance for devtools inspection.\n * Call this when creating instances you want visible in devtools.\n *\n * @example\n * const counter = Counter.create()\n * registerInstance(\"app-counter\", counter)\n */\nexport function registerInstance(name: string, instance: object): void {\n _activeModels.set(name, new WeakRef(instance))\n _notify()\n}\n\n/**\n * Unregister a model instance.\n */\nexport function unregisterInstance(name: string): void {\n _activeModels.delete(name)\n _notify()\n}\n\n/**\n * Get all registered model instance names.\n * Automatically cleans up garbage-collected instances.\n */\nexport function getActiveModels(): string[] {\n for (const [name, ref] of _activeModels) {\n if (ref.deref() === undefined) _activeModels.delete(name)\n }\n return [..._activeModels.keys()]\n}\n\n/**\n * Get a model instance by name (or undefined if GC'd or not registered).\n */\nexport function getModelInstance(name: string): object | undefined {\n const ref = _activeModels.get(name)\n if (!ref) return undefined\n const instance = ref.deref()\n if (!instance) {\n _activeModels.delete(name)\n return undefined\n }\n return instance\n}\n\n/**\n * Get a snapshot of a registered model instance.\n */\nexport function getModelSnapshot(\n name: string,\n): Record<string, unknown> | undefined {\n const instance = getModelInstance(name)\n if (!instance) return undefined\n return getSnapshot(instance)\n}\n\n/**\n * Subscribe to model registry changes. Returns unsubscribe function.\n */\nexport function onModelChange(listener: () => void): () => void {\n _listeners.add(listener)\n return () => {\n _listeners.delete(listener)\n }\n}\n\n/** @internal — reset devtools registry (for tests). */\nexport function _resetDevtools(): void {\n _activeModels.clear()\n _listeners.clear()\n}\n"],"mappings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AAO;AACtB,QAAO,YAAY,SAAS;;;;;AAM9B,SAAgB,cAAc,UAAkC;AAC9D,YAAW,IAAI,SAAS;AACxB,cAAa;AACX,aAAW,OAAO,SAAS;;;;AAK/B,SAAgB,iBAAuB;AACrC,eAAc,OAAO;AACrB,YAAW,OAAO"}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { batch, signal } from "@pyreon/reactivity";
|
|
2
|
+
|
|
3
|
+
//#region src/registry.ts
|
|
4
|
+
/**
|
|
5
|
+
* WeakMap from every model instance object → its internal metadata.
|
|
6
|
+
* Shared across patch, middleware, and snapshot modules.
|
|
7
|
+
*/
|
|
8
|
+
const instanceMeta = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
/** Returns true when a value is a model instance (has metadata registered). */
|
|
10
|
+
function isModelInstance(value) {
|
|
11
|
+
return value != null && typeof value === "object" && instanceMeta.has(value);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/middleware.ts
|
|
16
|
+
/**
|
|
17
|
+
* Run an action through the middleware chain registered on `meta`.
|
|
18
|
+
* Each middleware receives the call descriptor and a `next` function.
|
|
19
|
+
* If no middlewares, the action runs directly.
|
|
20
|
+
*/
|
|
21
|
+
function runAction(meta, name, fn, args) {
|
|
22
|
+
const call = {
|
|
23
|
+
name,
|
|
24
|
+
args,
|
|
25
|
+
path: `/${name}`
|
|
26
|
+
};
|
|
27
|
+
const dispatch = (idx, c) => {
|
|
28
|
+
if (idx >= meta.middlewares.length) return fn(...c.args);
|
|
29
|
+
const mw = meta.middlewares[idx];
|
|
30
|
+
if (!mw) return fn(...c.args);
|
|
31
|
+
return mw(c, (nextCall) => dispatch(idx + 1, nextCall));
|
|
32
|
+
};
|
|
33
|
+
return dispatch(0, call);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Intercept every action call on `instance`.
|
|
37
|
+
* Middlewares run in registration order — call `next(call)` to continue.
|
|
38
|
+
*
|
|
39
|
+
* Returns an unsubscribe function.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* const unsub = addMiddleware(counter, (call, next) => {
|
|
43
|
+
* console.log(`> ${call.name}(${call.args})`)
|
|
44
|
+
* const result = next(call)
|
|
45
|
+
* console.log(`< ${call.name}`)
|
|
46
|
+
* return result
|
|
47
|
+
* })
|
|
48
|
+
*/
|
|
49
|
+
function addMiddleware(instance, middleware) {
|
|
50
|
+
const meta = instanceMeta.get(instance);
|
|
51
|
+
if (!meta) throw new Error("[@pyreon/state-tree] addMiddleware: not a model instance");
|
|
52
|
+
meta.middlewares.push(middleware);
|
|
53
|
+
return () => {
|
|
54
|
+
const idx = meta.middlewares.indexOf(middleware);
|
|
55
|
+
if (idx !== -1) meta.middlewares.splice(idx, 1);
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/patch.ts
|
|
61
|
+
/** Property names that must never be used as patch path segments. */
|
|
62
|
+
const RESERVED_KEYS = new Set([
|
|
63
|
+
"__proto__",
|
|
64
|
+
"constructor",
|
|
65
|
+
"prototype"
|
|
66
|
+
]);
|
|
67
|
+
/**
|
|
68
|
+
* Wraps a signal so that every write emits a JSON patch via `emitPatch`.
|
|
69
|
+
* Reads are pass-through — no overhead on hot reactive paths.
|
|
70
|
+
*
|
|
71
|
+
* @param hasListeners Optional predicate — when provided, patch object allocation
|
|
72
|
+
* and snapshotting are skipped entirely when no listeners are registered.
|
|
73
|
+
*/
|
|
74
|
+
function trackedSignal(inner, path, emitPatch, hasListeners) {
|
|
75
|
+
const read = () => inner();
|
|
76
|
+
read.peek = () => inner.peek();
|
|
77
|
+
read.subscribe = (listener) => inner.subscribe(listener);
|
|
78
|
+
read.set = (newValue) => {
|
|
79
|
+
const prev = inner.peek();
|
|
80
|
+
inner.set(newValue);
|
|
81
|
+
if (!Object.is(prev, newValue) && (!hasListeners || hasListeners())) emitPatch({
|
|
82
|
+
op: "replace",
|
|
83
|
+
path,
|
|
84
|
+
value: isModelInstance(newValue) ? snapshotValue(newValue) : newValue
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
read.update = (fn) => {
|
|
88
|
+
read.set(fn(inner.peek()));
|
|
89
|
+
};
|
|
90
|
+
return read;
|
|
91
|
+
}
|
|
92
|
+
/** Shallow snapshot helper (avoids importing snapshot.ts to prevent circular deps). */
|
|
93
|
+
function snapshotValue(instance) {
|
|
94
|
+
const meta = instanceMeta.get(instance);
|
|
95
|
+
if (!meta) return instance;
|
|
96
|
+
const out = {};
|
|
97
|
+
for (const key of meta.stateKeys) {
|
|
98
|
+
const sig = instance[key];
|
|
99
|
+
if (!sig) continue;
|
|
100
|
+
const val = sig.peek();
|
|
101
|
+
out[key] = isModelInstance(val) ? snapshotValue(val) : val;
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Subscribe to every state mutation in `instance` as a JSON patch.
|
|
107
|
+
* Also captures mutations in nested model instances (path is prefixed).
|
|
108
|
+
*
|
|
109
|
+
* Returns an unsubscribe function.
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* const unsub = onPatch(counter, patch => {
|
|
113
|
+
* // { op: "replace", path: "/count", value: 6 }
|
|
114
|
+
* })
|
|
115
|
+
*/
|
|
116
|
+
function onPatch(instance, listener) {
|
|
117
|
+
const meta = instanceMeta.get(instance);
|
|
118
|
+
if (!meta) throw new Error("[@pyreon/state-tree] onPatch: not a model instance");
|
|
119
|
+
meta.patchListeners.add(listener);
|
|
120
|
+
return () => meta.patchListeners.delete(listener);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Apply a JSON patch (or array of patches) to a model instance.
|
|
124
|
+
* Only "replace" operations are supported (matching the patches emitted by `onPatch`).
|
|
125
|
+
*
|
|
126
|
+
* Paths use JSON pointer format: `"/count"` for top-level, `"/profile/name"` for nested.
|
|
127
|
+
* Nested model instances are resolved automatically.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* applyPatch(counter, { op: "replace", path: "/count", value: 10 })
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* // Replay patches recorded from onPatch (undo/redo, time-travel)
|
|
134
|
+
* applyPatch(counter, [
|
|
135
|
+
* { op: "replace", path: "/count", value: 1 },
|
|
136
|
+
* { op: "replace", path: "/count", value: 2 },
|
|
137
|
+
* ])
|
|
138
|
+
*/
|
|
139
|
+
function applyPatch(instance, patch) {
|
|
140
|
+
const patches = Array.isArray(patch) ? patch : [patch];
|
|
141
|
+
batch(() => {
|
|
142
|
+
for (const p of patches) {
|
|
143
|
+
if (p.op !== "replace") throw new Error(`[@pyreon/state-tree] applyPatch: unsupported op "${p.op}"`);
|
|
144
|
+
const segments = p.path.split("/").filter(Boolean);
|
|
145
|
+
if (segments.length === 0) throw new Error("[@pyreon/state-tree] applyPatch: empty path");
|
|
146
|
+
let target = instance;
|
|
147
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
148
|
+
const segment = segments[i];
|
|
149
|
+
if (RESERVED_KEYS.has(segment)) throw new Error(`[@pyreon/state-tree] applyPatch: reserved property name "${segment}"`);
|
|
150
|
+
if (!instanceMeta.get(target)) throw new Error(`[@pyreon/state-tree] applyPatch: not a model instance at "${segment}"`);
|
|
151
|
+
const sig = target[segment];
|
|
152
|
+
if (!sig || typeof sig.peek !== "function") throw new Error(`[@pyreon/state-tree] applyPatch: unknown state key "${segment}"`);
|
|
153
|
+
const nested = sig.peek();
|
|
154
|
+
if (!nested || typeof nested !== "object" || !isModelInstance(nested)) throw new Error(`[@pyreon/state-tree] applyPatch: "${segment}" is not a nested model instance`);
|
|
155
|
+
target = nested;
|
|
156
|
+
}
|
|
157
|
+
const lastKey = segments[segments.length - 1];
|
|
158
|
+
if (RESERVED_KEYS.has(lastKey)) throw new Error(`[@pyreon/state-tree] applyPatch: reserved property name "${lastKey}"`);
|
|
159
|
+
const meta = instanceMeta.get(target);
|
|
160
|
+
if (!meta) throw new Error("[@pyreon/state-tree] applyPatch: not a model instance");
|
|
161
|
+
if (!meta.stateKeys.includes(lastKey)) throw new Error(`[@pyreon/state-tree] applyPatch: unknown state key "${lastKey}"`);
|
|
162
|
+
const sig = target[lastKey];
|
|
163
|
+
if (sig && typeof sig.set === "function") sig.set(p.value);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
//#endregion
|
|
169
|
+
//#region src/types.ts
|
|
170
|
+
/** Property key stamped on every ModelDefinition to distinguish it from plain objects. */
|
|
171
|
+
const MODEL_BRAND = "__pyreonMod";
|
|
172
|
+
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/instance.ts
|
|
175
|
+
function isModelDef(v) {
|
|
176
|
+
if (v == null || typeof v !== "object") return false;
|
|
177
|
+
return v[MODEL_BRAND] === true;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Create a live model instance from a config + optional initial snapshot.
|
|
181
|
+
* Called by `ModelDefinition.create()`.
|
|
182
|
+
*/
|
|
183
|
+
function createInstance(config, initial) {
|
|
184
|
+
const instance = {};
|
|
185
|
+
const meta = {
|
|
186
|
+
stateKeys: [],
|
|
187
|
+
patchListeners: /* @__PURE__ */ new Set(),
|
|
188
|
+
middlewares: [],
|
|
189
|
+
emitPatch(patch) {
|
|
190
|
+
if (this.patchListeners.size === 0) return;
|
|
191
|
+
for (const listener of this.patchListeners) listener(patch);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
instanceMeta.set(instance, meta);
|
|
195
|
+
const self = new Proxy(instance, { get(_, k) {
|
|
196
|
+
return instance[k];
|
|
197
|
+
} });
|
|
198
|
+
for (const [key, defaultValue] of Object.entries(config.state)) {
|
|
199
|
+
meta.stateKeys.push(key);
|
|
200
|
+
const path = `/${key}`;
|
|
201
|
+
const initValue = key in initial ? initial[key] : void 0;
|
|
202
|
+
let rawSig;
|
|
203
|
+
if (isModelDef(defaultValue)) {
|
|
204
|
+
const nestedInstance = createInstance(defaultValue._config, initValue ?? {});
|
|
205
|
+
rawSig = signal(nestedInstance);
|
|
206
|
+
onPatch(nestedInstance, (patch) => {
|
|
207
|
+
meta.emitPatch({
|
|
208
|
+
...patch,
|
|
209
|
+
path: path + patch.path
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
} else rawSig = signal(initValue !== void 0 ? initValue : defaultValue);
|
|
213
|
+
instance[key] = trackedSignal(rawSig, path, (p) => meta.emitPatch(p), () => meta.patchListeners.size > 0);
|
|
214
|
+
}
|
|
215
|
+
if (config.views) {
|
|
216
|
+
const views = config.views(self);
|
|
217
|
+
for (const [key, view] of Object.entries(views)) instance[key] = view;
|
|
218
|
+
}
|
|
219
|
+
if (config.actions) {
|
|
220
|
+
const rawActions = config.actions(self);
|
|
221
|
+
for (const [key, actionFn] of Object.entries(rawActions)) instance[key] = (...args) => runAction(meta, key, actionFn, args);
|
|
222
|
+
}
|
|
223
|
+
return instance;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
//#endregion
|
|
227
|
+
//#region src/model.ts
|
|
228
|
+
const _hookRegistry = /* @__PURE__ */ new Map();
|
|
229
|
+
/** Destroy a hook singleton by id so next call re-creates the instance. */
|
|
230
|
+
function resetHook(id) {
|
|
231
|
+
_hookRegistry.delete(id);
|
|
232
|
+
}
|
|
233
|
+
/** Destroy all hook singletons. */
|
|
234
|
+
function resetAllHooks() {
|
|
235
|
+
_hookRegistry.clear();
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Returned by `model()`. Call `.create()` for instances or `.asHook(id)` for
|
|
239
|
+
* a Zustand-style singleton hook.
|
|
240
|
+
*/
|
|
241
|
+
var ModelDefinition = class {
|
|
242
|
+
/** Brand used to identify ModelDefinition objects at runtime (without instanceof). */
|
|
243
|
+
[MODEL_BRAND] = true;
|
|
244
|
+
/** @internal — exposed so nested instance creation can read it. */
|
|
245
|
+
_config;
|
|
246
|
+
constructor(config) {
|
|
247
|
+
this._config = config;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Create a new independent model instance.
|
|
251
|
+
* Pass a partial snapshot to override defaults.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* const counter = Counter.create({ count: 5 })
|
|
255
|
+
*/
|
|
256
|
+
create(initial) {
|
|
257
|
+
return createInstance(this._config, initial ?? {});
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Returns a hook function that always returns the same singleton instance
|
|
261
|
+
* for the given `id` — Zustand / Pinia style.
|
|
262
|
+
*
|
|
263
|
+
* @example
|
|
264
|
+
* const useCounter = Counter.asHook("app-counter")
|
|
265
|
+
* // Any call to useCounter() returns the same instance.
|
|
266
|
+
* const store = useCounter()
|
|
267
|
+
*/
|
|
268
|
+
asHook(id) {
|
|
269
|
+
return () => {
|
|
270
|
+
if (!_hookRegistry.has(id)) _hookRegistry.set(id, this.create());
|
|
271
|
+
return _hookRegistry.get(id);
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
/**
|
|
276
|
+
* Define a reactive model with state, views, and actions.
|
|
277
|
+
*
|
|
278
|
+
* - **state** — plain JS object; each key becomes a `Signal<T>` on the instance.
|
|
279
|
+
* - **views** — factory receiving `self`; return computed signals for derived state.
|
|
280
|
+
* - **actions** — factory receiving `self`; return functions that mutate state.
|
|
281
|
+
*
|
|
282
|
+
* Use nested `ModelDefinition` values in `state` to compose models.
|
|
283
|
+
*
|
|
284
|
+
* @example
|
|
285
|
+
* const Counter = model({
|
|
286
|
+
* state: { count: 0 },
|
|
287
|
+
* views: (self) => ({
|
|
288
|
+
* doubled: computed(() => self.count() * 2),
|
|
289
|
+
* }),
|
|
290
|
+
* actions: (self) => ({
|
|
291
|
+
* inc: () => self.count.update(c => c + 1),
|
|
292
|
+
* reset: () => self.count.set(0),
|
|
293
|
+
* }),
|
|
294
|
+
* })
|
|
295
|
+
*
|
|
296
|
+
* const c = Counter.create({ count: 5 })
|
|
297
|
+
* c.count() // 5
|
|
298
|
+
* c.inc()
|
|
299
|
+
* c.doubled() // 12
|
|
300
|
+
*/
|
|
301
|
+
function model(config) {
|
|
302
|
+
return new ModelDefinition(config);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
//#endregion
|
|
306
|
+
//#region src/snapshot.ts
|
|
307
|
+
/**
|
|
308
|
+
* Serialize a model instance to a plain JS object (no signals, no functions).
|
|
309
|
+
* Nested model instances are recursively serialized.
|
|
310
|
+
*
|
|
311
|
+
* @example
|
|
312
|
+
* getSnapshot(counter) // { count: 6 }
|
|
313
|
+
* getSnapshot(app) // { profile: { name: "Alice" }, title: "My App" }
|
|
314
|
+
*/
|
|
315
|
+
function getSnapshot(instance) {
|
|
316
|
+
const meta = instanceMeta.get(instance);
|
|
317
|
+
if (!meta) throw new Error("[@pyreon/state-tree] getSnapshot: not a model instance");
|
|
318
|
+
const out = {};
|
|
319
|
+
for (const key of meta.stateKeys) {
|
|
320
|
+
const sig = instance[key];
|
|
321
|
+
if (!sig) continue;
|
|
322
|
+
const val = sig.peek();
|
|
323
|
+
out[key] = isModelInstance(val) ? getSnapshot(val) : val;
|
|
324
|
+
}
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Restore a model instance from a plain-object snapshot.
|
|
329
|
+
* All signal writes are coalesced via `batch()` for a single reactive flush.
|
|
330
|
+
* Keys absent from the snapshot are left unchanged.
|
|
331
|
+
*
|
|
332
|
+
* @example
|
|
333
|
+
* applySnapshot(counter, { count: 0 })
|
|
334
|
+
*/
|
|
335
|
+
function applySnapshot(instance, snapshot) {
|
|
336
|
+
const meta = instanceMeta.get(instance);
|
|
337
|
+
if (!meta) throw new Error("[@pyreon/state-tree] applySnapshot: not a model instance");
|
|
338
|
+
batch(() => {
|
|
339
|
+
for (const key of meta.stateKeys) {
|
|
340
|
+
if (!(key in snapshot)) continue;
|
|
341
|
+
const sig = instance[key];
|
|
342
|
+
if (!sig) continue;
|
|
343
|
+
const val = snapshot[key];
|
|
344
|
+
const current = sig.peek();
|
|
345
|
+
if (isModelInstance(current)) applySnapshot(current, val);
|
|
346
|
+
else sig.set(val);
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
//#endregion
|
|
352
|
+
export { addMiddleware, applyPatch, applySnapshot, getSnapshot, model, onPatch, resetAllHooks, resetHook };
|
|
353
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/registry.ts","../src/middleware.ts","../src/patch.ts","../src/types.ts","../src/instance.ts","../src/model.ts","../src/snapshot.ts"],"sourcesContent":["import type { InstanceMeta } from './types'\n\n/**\n * WeakMap from every model instance object → its internal metadata.\n * Shared across patch, middleware, and snapshot modules.\n */\nexport const instanceMeta = new WeakMap<object, InstanceMeta>()\n\n/** Returns true when a value is a model instance (has metadata registered). */\nexport function isModelInstance(value: unknown): boolean {\n return (\n value != null &&\n typeof value === 'object' &&\n instanceMeta.has(value as object)\n )\n}\n","import { instanceMeta } from './registry'\nimport type { ActionCall, InstanceMeta, MiddlewareFn } from './types'\n\n// ─── Action runner ────────────────────────────────────────────────────────────\n\n/**\n * Run an action through the middleware chain registered on `meta`.\n * Each middleware receives the call descriptor and a `next` function.\n * If no middlewares, the action runs directly.\n */\nexport function runAction(\n meta: InstanceMeta,\n name: string,\n fn: (...fnArgs: unknown[]) => unknown,\n args: unknown[],\n): unknown {\n const call: ActionCall = { name, args, path: `/${name}` }\n\n const dispatch = (idx: number, c: ActionCall): unknown => {\n if (idx >= meta.middlewares.length) return fn(...c.args)\n const mw = meta.middlewares[idx]\n if (!mw) return fn(...c.args)\n return mw(c, (nextCall) => dispatch(idx + 1, nextCall))\n }\n\n return dispatch(0, call)\n}\n\n// ─── addMiddleware ────────────────────────────────────────────────────────────\n\n/**\n * Intercept every action call on `instance`.\n * Middlewares run in registration order — call `next(call)` to continue.\n *\n * Returns an unsubscribe function.\n *\n * @example\n * const unsub = addMiddleware(counter, (call, next) => {\n * console.log(`> ${call.name}(${call.args})`)\n * const result = next(call)\n * console.log(`< ${call.name}`)\n * return result\n * })\n */\nexport function addMiddleware(\n instance: object,\n middleware: MiddlewareFn,\n): () => void {\n const meta = instanceMeta.get(instance)\n if (!meta)\n throw new Error('[@pyreon/state-tree] addMiddleware: not a model instance')\n meta.middlewares.push(middleware)\n return () => {\n const idx = meta.middlewares.indexOf(middleware)\n if (idx !== -1) meta.middlewares.splice(idx, 1)\n }\n}\n","import type { Signal } from '@pyreon/reactivity'\nimport { batch } from '@pyreon/reactivity'\nimport { instanceMeta, isModelInstance } from './registry'\nimport type { Patch, PatchListener } from './types'\n\n/** Property names that must never be used as patch path segments. */\nconst RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype'])\n\n// ─── Tracked signal ───────────────────────────────────────────────────────────\n\n/**\n * Wraps a signal so that every write emits a JSON patch via `emitPatch`.\n * Reads are pass-through — no overhead on hot reactive paths.\n *\n * @param hasListeners Optional predicate — when provided, patch object allocation\n * and snapshotting are skipped entirely when no listeners are registered.\n */\nexport function trackedSignal<T>(\n inner: Signal<T>,\n path: string,\n emitPatch: (patch: Patch) => void,\n hasListeners?: () => boolean,\n): Signal<T> {\n const read = (): T => inner()\n\n read.peek = (): T => inner.peek()\n\n read.subscribe = (listener: () => void): (() => void) =>\n inner.subscribe(listener)\n\n read.set = (newValue: T): void => {\n const prev = inner.peek()\n inner.set(newValue)\n // Skip patch emission entirely when no one is listening — avoids object\n // allocation and (for nested instances) a full recursive snapshot.\n if (!Object.is(prev, newValue) && (!hasListeners || hasListeners())) {\n // For model instances, emit the snapshot rather than the live object\n // so patches are always plain JSON-serializable values.\n const patchValue = isModelInstance(newValue)\n ? snapshotValue(newValue as object)\n : newValue\n emitPatch({ op: 'replace', path, value: patchValue })\n }\n }\n\n read.update = (fn: (current: T) => T): void => {\n read.set(fn(inner.peek()))\n }\n\n return read as Signal<T>\n}\n\n/** Shallow snapshot helper (avoids importing snapshot.ts to prevent circular deps). */\nfunction snapshotValue(instance: object): Record<string, unknown> {\n const meta = instanceMeta.get(instance)\n if (!meta) return instance as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of meta.stateKeys) {\n const sig = (instance as Record<string, Signal<unknown>>)[key]\n if (!sig) continue\n const val = sig.peek()\n out[key] = isModelInstance(val) ? snapshotValue(val as object) : val\n }\n return out\n}\n\n// ─── onPatch ──────────────────────────────────────────────────────────────────\n\n/**\n * Subscribe to every state mutation in `instance` as a JSON patch.\n * Also captures mutations in nested model instances (path is prefixed).\n *\n * Returns an unsubscribe function.\n *\n * @example\n * const unsub = onPatch(counter, patch => {\n * // { op: \"replace\", path: \"/count\", value: 6 }\n * })\n */\nexport function onPatch(instance: object, listener: PatchListener): () => void {\n const meta = instanceMeta.get(instance)\n if (!meta)\n throw new Error('[@pyreon/state-tree] onPatch: not a model instance')\n meta.patchListeners.add(listener)\n return () => meta.patchListeners.delete(listener)\n}\n\n// ─── applyPatch ─────────────────────────────────────────────────────────────\n\n/**\n * Apply a JSON patch (or array of patches) to a model instance.\n * Only \"replace\" operations are supported (matching the patches emitted by `onPatch`).\n *\n * Paths use JSON pointer format: `\"/count\"` for top-level, `\"/profile/name\"` for nested.\n * Nested model instances are resolved automatically.\n *\n * @example\n * applyPatch(counter, { op: \"replace\", path: \"/count\", value: 10 })\n *\n * @example\n * // Replay patches recorded from onPatch (undo/redo, time-travel)\n * applyPatch(counter, [\n * { op: \"replace\", path: \"/count\", value: 1 },\n * { op: \"replace\", path: \"/count\", value: 2 },\n * ])\n */\nexport function applyPatch(instance: object, patch: Patch | Patch[]): void {\n const patches = Array.isArray(patch) ? patch : [patch]\n\n batch(() => {\n for (const p of patches) {\n if (p.op !== 'replace') {\n throw new Error(\n `[@pyreon/state-tree] applyPatch: unsupported op \"${p.op}\"`,\n )\n }\n\n const segments = p.path.split('/').filter(Boolean)\n if (segments.length === 0) {\n throw new Error('[@pyreon/state-tree] applyPatch: empty path')\n }\n\n // Walk to the target instance for nested paths\n let target: object = instance\n for (let i = 0; i < segments.length - 1; i++) {\n const segment = segments[i]!\n if (RESERVED_KEYS.has(segment)) {\n throw new Error(\n `[@pyreon/state-tree] applyPatch: reserved property name \"${segment}\"`,\n )\n }\n const meta = instanceMeta.get(target)\n if (!meta)\n throw new Error(\n `[@pyreon/state-tree] applyPatch: not a model instance at \"${segment}\"`,\n )\n const sig = (target as Record<string, Signal<unknown>>)[segment]\n if (!sig || typeof sig.peek !== 'function') {\n throw new Error(\n `[@pyreon/state-tree] applyPatch: unknown state key \"${segment}\"`,\n )\n }\n const nested = sig.peek()\n if (!nested || typeof nested !== 'object' || !isModelInstance(nested)) {\n throw new Error(\n `[@pyreon/state-tree] applyPatch: \"${segment}\" is not a nested model instance`,\n )\n }\n target = nested as object\n }\n\n const lastKey = segments[segments.length - 1]!\n if (RESERVED_KEYS.has(lastKey)) {\n throw new Error(\n `[@pyreon/state-tree] applyPatch: reserved property name \"${lastKey}\"`,\n )\n }\n const meta = instanceMeta.get(target)\n if (!meta)\n throw new Error('[@pyreon/state-tree] applyPatch: not a model instance')\n if (!meta.stateKeys.includes(lastKey)) {\n throw new Error(\n `[@pyreon/state-tree] applyPatch: unknown state key \"${lastKey}\"`,\n )\n }\n\n const sig = (target as Record<string, Signal<unknown>>)[lastKey]\n if (sig && typeof sig.set === 'function') {\n sig.set(p.value)\n }\n }\n })\n}\n","import type { Computed, Signal } from '@pyreon/reactivity'\n\n// ─── Model brand ──────────────────────────────────────────────────────────────\n\n/** Property key stamped on every ModelDefinition to distinguish it from plain objects. */\nexport const MODEL_BRAND = '__pyreonMod' as const\n\n// ─── State type helpers ───────────────────────────────────────────────────────\n\nexport type StateShape = Record<string, unknown>\n\n/**\n * Resolve a state field type:\n * - ModelDefinition → the instance type it produces\n * - Anything else → as-is\n */\nexport type ResolveField<T> = T extends {\n readonly __pyreonMod: true\n create(initial?: any): infer I\n}\n ? I\n : T\n\n/** Map state shape to per-field signals. */\nexport type StateSignals<TState extends StateShape> = {\n readonly [K in keyof TState]: Signal<ResolveField<TState[K]>>\n}\n\n/**\n * `self` type inside actions / views:\n * strongly typed for state signals, `any` for actions and views so that\n * actions can call each other without circular type issues.\n */\nexport type ModelSelf<TState extends StateShape> = StateSignals<TState> &\n Record<string, any>\n\n/** The public instance type returned by `.create()` and hooks. */\nexport type ModelInstance<\n TState extends StateShape,\n TActions extends Record<string, (...args: any[]) => any>,\n TViews extends Record<string, Signal<any> | Computed<any>>,\n> = StateSignals<TState> & TActions & TViews\n\n/**\n * Extract the state type from a ModelDefinition.\n * Used by Snapshot to recursively resolve nested model types.\n */\ntype ExtractModelState<T> = T extends {\n readonly __pyreonMod: true\n readonly _config: { state: infer S extends StateShape }\n}\n ? S\n : never\n\n/**\n * Snapshot type: plain JS values (no signals, no model instances).\n * Nested model fields recursively produce their own typed snapshot.\n */\nexport type Snapshot<TState extends StateShape> = {\n [K in keyof TState]: TState[K] extends { readonly __pyreonMod: true }\n ? Snapshot<ExtractModelState<TState[K]>>\n : TState[K]\n}\n\n// ─── Patch ────────────────────────────────────────────────────────────────────\n\nexport interface Patch {\n op: 'replace'\n path: string\n value: unknown\n}\n\nexport type PatchListener = (patch: Patch) => void\n\n// ─── Middleware ───────────────────────────────────────────────────────────────\n\nexport interface ActionCall {\n /** Action name. */\n name: string\n /** Arguments passed to the action. */\n args: unknown[]\n /** JSON-pointer-style path, e.g. `\"/inc\"`. */\n path: string\n}\n\nexport type MiddlewareFn = (\n call: ActionCall,\n next: (nextCall: ActionCall) => unknown,\n) => unknown\n\n// ─── Instance metadata ────────────────────────────────────────────────────────\n\nexport interface InstanceMeta {\n stateKeys: string[]\n patchListeners: Set<PatchListener>\n middlewares: MiddlewareFn[]\n emitPatch(patch: Patch): void\n}\n","import type { Computed, Signal } from '@pyreon/reactivity'\nimport { signal } from '@pyreon/reactivity'\nimport { runAction } from './middleware'\nimport { onPatch, trackedSignal } from './patch'\nimport { instanceMeta } from './registry'\nimport type { InstanceMeta, ModelInstance, Snapshot, StateShape } from './types'\nimport { MODEL_BRAND } from './types'\n\n// ─── Model definition detection ───────────────────────────────────────────────\n\ninterface AnyModelDef {\n readonly [MODEL_BRAND]: true\n readonly _config: ModelConfig<\n StateShape,\n Record<string, (...args: unknown[]) => unknown>,\n Record<string, Signal<unknown>>\n >\n}\n\nfunction isModelDef(v: unknown): v is AnyModelDef {\n if (v == null || typeof v !== 'object') return false\n return (v as Record<string, unknown>)[MODEL_BRAND] === true\n}\n\n// ─── Config shape ─────────────────────────────────────────────────────────────\n\nexport interface ModelConfig<TState extends StateShape, TActions, TViews> {\n state: TState\n views?: (self: any) => TViews\n actions?: (self: any) => TActions\n}\n\n// ─── createInstance ───────────────────────────────────────────────────────────\n\n/**\n * Create a live model instance from a config + optional initial snapshot.\n * Called by `ModelDefinition.create()`.\n */\nexport function createInstance<\n TState extends StateShape,\n TActions extends Record<string, (...args: any[]) => any>,\n TViews extends Record<string, Signal<any> | Computed<any>>,\n>(\n config: ModelConfig<TState, TActions, TViews>,\n initial: Partial<Snapshot<TState>>,\n): ModelInstance<TState, TActions, TViews> {\n // Raw object that will become the instance.\n const instance: Record<string, unknown> = {}\n\n // Metadata for this instance.\n const meta: InstanceMeta = {\n stateKeys: [],\n patchListeners: new Set(),\n middlewares: [],\n emitPatch(patch) {\n // Guard avoids iterating an empty Set on the hot signal-write path.\n if (this.patchListeners.size === 0) return\n for (const listener of this.patchListeners) listener(patch)\n },\n }\n instanceMeta.set(instance, meta)\n\n // `self` is a live proxy so that actions/views always see the final\n // (fully-populated) instance — including wrapped actions added later.\n const self = new Proxy(instance, {\n get(_, k) {\n return instance[k as string]\n },\n })\n\n // ── 1. State signals ──────────────────────────────────────────────────────\n for (const [key, defaultValue] of Object.entries(config.state)) {\n meta.stateKeys.push(key)\n const path = `/${key}`\n const initValue: unknown =\n key in initial ? (initial as Record<string, unknown>)[key] : undefined\n\n let rawSig: Signal<unknown>\n\n if (isModelDef(defaultValue)) {\n // Nested model — create its instance from the supplied snapshot (or defaults).\n const nestedInstance = createInstance(\n defaultValue._config,\n (initValue as Record<string, unknown>) ?? {},\n )\n rawSig = signal(nestedInstance)\n\n // Propagate nested patches upward with the key as path prefix.\n onPatch(nestedInstance, (patch) => {\n meta.emitPatch({ ...patch, path: path + patch.path })\n })\n } else {\n rawSig = signal(initValue !== undefined ? initValue : defaultValue)\n }\n\n const tracked = trackedSignal(\n rawSig,\n path,\n (p) => meta.emitPatch(p),\n () => meta.patchListeners.size > 0,\n )\n instance[key] = tracked\n }\n\n // ── 2. Views ──────────────────────────────────────────────────────────────\n if (config.views) {\n const views = config.views(self)\n for (const [key, view] of Object.entries(\n views as Record<string, unknown>,\n )) {\n instance[key] = view\n }\n }\n\n // ── 3. Actions (wrapped with middleware runner) ───────────────────────────\n if (config.actions) {\n const rawActions = config.actions(self) as Record<\n string,\n (...args: unknown[]) => unknown\n >\n for (const [key, actionFn] of Object.entries(rawActions)) {\n instance[key] = (...args: unknown[]) =>\n runAction(meta, key, actionFn, args)\n }\n }\n\n return instance as ModelInstance<TState, TActions, TViews>\n}\n","import type { Computed, Signal } from '@pyreon/reactivity'\nimport { createInstance, type ModelConfig } from './instance'\nimport type { ModelInstance, Snapshot, StateShape } from './types'\nimport { MODEL_BRAND } from './types'\n\n// ─── Hook registry ────────────────────────────────────────────────────────────\n\n// Module-level singleton registry for `asHook()` — isolated per package import.\n// Use `resetHook(id)` or `resetAllHooks()` to clear entries (useful for tests / HMR).\nconst _hookRegistry = new Map<string, unknown>()\n\n/** Destroy a hook singleton by id so next call re-creates the instance. */\nexport function resetHook(id: string): void {\n _hookRegistry.delete(id)\n}\n\n/** Destroy all hook singletons. */\nexport function resetAllHooks(): void {\n _hookRegistry.clear()\n}\n\n// ─── ModelDefinition ──────────────────────────────────────────────────────────\n\n/**\n * Returned by `model()`. Call `.create()` for instances or `.asHook(id)` for\n * a Zustand-style singleton hook.\n */\nexport class ModelDefinition<\n TState extends StateShape,\n TActions extends Record<string, (...args: any[]) => any>,\n TViews extends Record<string, Signal<any> | Computed<any>>,\n> {\n /** Brand used to identify ModelDefinition objects at runtime (without instanceof). */\n readonly [MODEL_BRAND] = true as const\n\n /** @internal — exposed so nested instance creation can read it. */\n readonly _config: ModelConfig<TState, TActions, TViews>\n\n constructor(config: ModelConfig<TState, TActions, TViews>) {\n this._config = config\n }\n\n /**\n * Create a new independent model instance.\n * Pass a partial snapshot to override defaults.\n *\n * @example\n * const counter = Counter.create({ count: 5 })\n */\n create(\n initial?: Partial<Snapshot<TState>>,\n ): ModelInstance<TState, TActions, TViews> {\n return createInstance(this._config, initial ?? {})\n }\n\n /**\n * Returns a hook function that always returns the same singleton instance\n * for the given `id` — Zustand / Pinia style.\n *\n * @example\n * const useCounter = Counter.asHook(\"app-counter\")\n * // Any call to useCounter() returns the same instance.\n * const store = useCounter()\n */\n asHook(id: string): () => ModelInstance<TState, TActions, TViews> {\n return () => {\n if (!_hookRegistry.has(id)) {\n _hookRegistry.set(id, this.create())\n }\n return _hookRegistry.get(id) as ModelInstance<TState, TActions, TViews>\n }\n }\n}\n\n// ─── model() factory ──────────────────────────────────────────────────────────\n\n/**\n * Define a reactive model with state, views, and actions.\n *\n * - **state** — plain JS object; each key becomes a `Signal<T>` on the instance.\n * - **views** — factory receiving `self`; return computed signals for derived state.\n * - **actions** — factory receiving `self`; return functions that mutate state.\n *\n * Use nested `ModelDefinition` values in `state` to compose models.\n *\n * @example\n * const Counter = model({\n * state: { count: 0 },\n * views: (self) => ({\n * doubled: computed(() => self.count() * 2),\n * }),\n * actions: (self) => ({\n * inc: () => self.count.update(c => c + 1),\n * reset: () => self.count.set(0),\n * }),\n * })\n *\n * const c = Counter.create({ count: 5 })\n * c.count() // 5\n * c.inc()\n * c.doubled() // 12\n */\nexport function model<\n TState extends StateShape,\n TActions extends Record<string, (...args: any[]) => any> = Record<\n never,\n never\n >,\n TViews extends Record<string, Signal<any> | Computed<any>> = Record<\n never,\n never\n >,\n>(\n config: ModelConfig<TState, TActions, TViews>,\n): ModelDefinition<TState, TActions, TViews> {\n return new ModelDefinition(config)\n}\n","import type { Signal } from '@pyreon/reactivity'\nimport { batch } from '@pyreon/reactivity'\nimport { instanceMeta, isModelInstance } from './registry'\nimport type { Snapshot, StateShape } from './types'\n\n// ─── getSnapshot ──────────────────────────────────────────────────────────────\n\n/**\n * Serialize a model instance to a plain JS object (no signals, no functions).\n * Nested model instances are recursively serialized.\n *\n * @example\n * getSnapshot(counter) // { count: 6 }\n * getSnapshot(app) // { profile: { name: \"Alice\" }, title: \"My App\" }\n */\nexport function getSnapshot<TState extends StateShape>(\n instance: object,\n): Snapshot<TState> {\n const meta = instanceMeta.get(instance)\n if (!meta)\n throw new Error('[@pyreon/state-tree] getSnapshot: not a model instance')\n\n const out: Record<string, unknown> = {}\n for (const key of meta.stateKeys) {\n const sig = (instance as Record<string, Signal<unknown>>)[key]\n if (!sig) continue\n const val = sig.peek()\n out[key] = isModelInstance(val) ? getSnapshot(val as object) : val\n }\n return out as Snapshot<TState>\n}\n\n// ─── applySnapshot ────────────────────────────────────────────────────────────\n\n/**\n * Restore a model instance from a plain-object snapshot.\n * All signal writes are coalesced via `batch()` for a single reactive flush.\n * Keys absent from the snapshot are left unchanged.\n *\n * @example\n * applySnapshot(counter, { count: 0 })\n */\nexport function applySnapshot<TState extends StateShape>(\n instance: object,\n snapshot: Partial<Snapshot<TState>>,\n): void {\n const meta = instanceMeta.get(instance)\n if (!meta)\n throw new Error('[@pyreon/state-tree] applySnapshot: not a model instance')\n\n batch(() => {\n for (const key of meta.stateKeys) {\n if (!(key in snapshot)) continue\n const sig = (instance as Record<string, Signal<unknown>>)[key]\n if (!sig) continue\n const val = (snapshot as Record<string, unknown>)[key]\n const current = sig.peek()\n if (isModelInstance(current)) {\n // Recurse into nested model instance\n applySnapshot(current as object, val as Record<string, unknown>)\n } else {\n sig.set(val)\n }\n }\n })\n}\n"],"mapp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CAAC;AAEtC,UAAO,cAAc,IAAI,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiClC,SAAgB,MAWd,QAC2C;AAC3C,QAAO,IAAI,gBAAgB,OAAO;;;;;;;;;;;;;ACpGpC,SAAgB,YACd,UACkB;CAClB,MAAM,OAAO,aAAa,IAAI,SAAS;AACvC,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,yDAAyD;CAE3E,MAAM,MAA+B,EAAE;AACvC,MAAK,MAAM,OAAO,KAAK,WAAW;EAChC,MAAM,MAAO,SAA6C;AAC1D,MAAI,CAAC,IAAK;EACV,MAAM,MAAM,IAAI,MAAM;AACtB,MAAI,OAAO,gBAAgB,IAAI,GAAG,YAAY,IAAc,GAAG;;AAEjE,QAAO;;;;;;;;;;AAaT,SAAgB,cACd,UACA,UACM;CACN,MAAM,OAAO,aAAa,IAAI,SAAS;AACvC,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,2DAA2D;AAE7E,aAAY;AACV,OAAK,MAAM,OAAO,KAAK,WAAW;AAChC,OAAI,EAAE,OAAO,UAAW;GACxB,MAAM,MAAO,SAA6C;AAC1D,OAAI,CAAC,IAAK;GACV,MAAM,MAAO,SAAqC;GAClD,MAAM,UAAU,IAAI,MAAM;AAC1B,OAAI,gBAAgB,QAAQ,CAE1B,eAAc,SAAmB,IAA+B;OAEhE,KAAI,IAAI,IAAI;;GAGhB"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/** Returns true when a value is a model instance (has metadata registered). */
|
|
2
|
+
function isModelInstance(value) {
|
|
3
|
+
return value != null && typeof value === "object" && instanceMeta.has(value);
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region src/snapshot.ts
|
|
8
|
+
/**
|
|
9
|
+
* Serialize a model instance to a plain JS object (no signals, no functions).
|
|
10
|
+
* Nested model instances are recursively serialized.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* getSnapshot(counter) // { count: 6 }
|
|
14
|
+
* getSnapshot(app) // { profile: { name: "Alice" }, title: "My App" }
|
|
15
|
+
*/
|
|
16
|
+
function getSnapshot(instance) {
|
|
17
|
+
const meta = instanceMeta.get(instance);
|
|
18
|
+
if (!meta) throw new Error("[@pyreon/state-tree] getSnapshot: not a model instance");
|
|
19
|
+
const out = {};
|
|
20
|
+
for (const key of meta.stateKeys) {
|
|
21
|
+
const sig = instance[key];
|
|
22
|
+
if (!sig) continue;
|
|
23
|
+
const val = sig.peek();
|
|
24
|
+
out[key] = isModelInstance(val) ? getSnapshot(val) : val;
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/devtools.ts
|
|
31
|
+
/**
|
|
32
|
+
* @pyreon/state-tree devtools introspection API.
|
|
33
|
+
* Import: `import { ... } from "@pyreon/state-tree/devtools"`
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
function _notify() {
|
|
37
|
+
for (const listener of _listeners) listener();
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Register a model instance for devtools inspection.
|
|
41
|
+
* Call this when creating instances you want visible in devtools.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* const counter = Counter.create()
|
|
45
|
+
* registerInstance("app-counter", counter)
|
|
46
|
+
*/
|
|
47
|
+
function registerInstance(name, instance) {
|
|
48
|
+
_activeModels.set(name, new WeakRef(instance));
|
|
49
|
+
_notify();
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Unregister a model instance.
|
|
53
|
+
*/
|
|
54
|
+
function unregisterInstance(name) {
|
|
55
|
+
_activeModels.delete(name);
|
|
56
|
+
_notify();
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Get all registered model instance names.
|
|
60
|
+
* Automatically cleans up garbage-collected instances.
|
|
61
|
+
*/
|
|
62
|
+
function getActiveModels() {
|
|
63
|
+
for (const [name, ref] of _activeModels) if (ref.deref() === void 0) _activeModels.delete(name);
|
|
64
|
+
return [..._activeModels.keys()];
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Get a model instance by name (or undefined if GC'd or not registered).
|
|
68
|
+
*/
|
|
69
|
+
function getModelInstance(name) {
|
|
70
|
+
const ref = _activeModels.get(name);
|
|
71
|
+
if (!ref) return void 0;
|
|
72
|
+
const instance = ref.deref();
|
|
73
|
+
if (!instance) {
|
|
74
|
+
_activeModels.delete(name);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
return instance;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Get a snapshot of a registered model instance.
|
|
81
|
+
*/
|
|
82
|
+
function getModelSnapshot(name) {
|
|
83
|
+
const instance = getModelInstance(name);
|
|
84
|
+
if (!instance) return void 0;
|
|
85
|
+
return getSnapshot(instance);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Subscribe to model registry changes. Returns unsubscribe function.
|
|
89
|
+
*/
|
|
90
|
+
function onModelChange(listener) {
|
|
91
|
+
_listeners.add(listener);
|
|
92
|
+
return () => {
|
|
93
|
+
_listeners.delete(listener);
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/** @internal — reset devtools registry (for tests). */
|
|
97
|
+
function _resetDevtools() {
|
|
98
|
+
_activeModels.clear();
|
|
99
|
+
_listeners.clear();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
//#endregion
|
|
103
|
+
export { _resetDevtools, getActiveModels, getModelInstance, getModelSnapshot, onModelChange, registerInstance, unregisterInstance };
|
|
104
|
+
//# sourceMappingURL=devtools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.d.ts","names":[],"sources":["../../src/registry.ts","../../src/snapshot.ts","../../src/devtools.ts"],"mappings":";AASA,SAAgB,eAAA,CAAgB,KAAA,EAAyB;EACvD,OACE,KAAA,IAAS,IAAA,IACT,OAAO,KAAA,KAAU,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