@callbag-recharge/callbag-recharge 0.21.0 → 0.22.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/dist/chunk-DHPPL5V6.js +1 -0
- package/dist/data/index.d.cts +90 -0
- package/dist/data/index.d.ts +90 -0
- package/dist/memory/index.cjs +4 -4
- package/dist/memory/index.d.cts +73 -3
- package/dist/memory/index.d.ts +73 -3
- package/dist/memory/index.js +1 -1
- package/dist/patterns/memoryStore/index.cjs +4 -4
- package/dist/patterns/memoryStore/index.d.cts +1 -1
- package/dist/patterns/memoryStore/index.d.ts +1 -1
- package/dist/patterns/memoryStore/index.js +1 -1
- package/dist/types-9JbU1qd1.d.ts +182 -0
- package/dist/types-FP6jV-p5.d.cts +182 -0
- package/package.json +2 -2
- package/dist/chunk-G65KU7M5.js +0 -1
- package/dist/types-Dp4YpbzK.d.ts +0 -97
- package/dist/types-fnky8Rsi.d.cts +0 -97
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as z}from"./chunk-JCENQEPP.js";import{a as W}from"./chunk-ZJCF5NYF.js";import{a as b}from"./chunk-PV347CGV.js";import{a as E}from"./chunk-GMLWTZFM.js";import{a as A}from"./chunk-EAK2HKAD.js";import{B as S,v as w}from"./chunk-TUPD47IE.js";function k(i){let a=i?.halfLife??864e5,m=i?.recency??1,p=i?.importance??1,T=i?.frequency??.5,y=Math.LN2/a;return(t,f)=>{let l=(f??Date.now())-t.accessedAt,u=Math.exp(-y*l),s=1-1/(1+t.accessCount);return m*u+p*t.importance+T*s}}function v(i,a,m){let p=a?.halfLife??864e5,T=a?.recency??1,y=a?.importance??1,t=a?.frequency??.5,f=(m??Date.now())-i.accessedAt,l=Math.exp(-Math.LN2/p*f),u=1-1/(1+i.accessCount);return T*l+y*i.importance+t*u}var O=0;function q(){return`mem-${++O}`}function L(i,a){let m=a?.id??q(),p=Date.now(),T={id:m,createdAt:p,updatedAt:p,accessedAt:p,accessCount:0,importance:a?.importance??.5,tags:new Set(a?.tags)},y=A(i,{name:`mem:${m}:content`}),t=A(T,{name:`mem:${m}:meta`,equals:()=>!1}),f={},l=b([t],()=>v(t.get(),f),{name:`mem:${m}:score`});return{id:m,content:y,meta:t,scoreStore:l,touch(){let s=Date.now();t.update(d=>({...d,accessedAt:s,accessCount:d.accessCount+1}))},tag(...s){t.update(d=>{let h=new Set(d.tags);for(let M of s)h.add(M);return{...d,tags:h,updatedAt:Date.now()}})},untag(...s){t.update(d=>{let h=new Set(d.tags);for(let M of s)h.delete(M);return{...d,tags:h,updatedAt:Date.now()}})},setImportance(s){t.update(d=>({...d,importance:Math.max(0,Math.min(1,s)),updatedAt:Date.now()}))},update(s){w(()=>{y.set(s),t.update(d=>({...d,updatedAt:Date.now()}))})},score(s){return v(t.get(),s??f)},destroy(){S(y),S(t)}}}var P=0;function oe(i){let a=++P,m=i?.maxSize??1/0,p=i?.weights??{},T=i?.admissionPolicy,y=i?.forgetPolicy,t=new Map,f=W(),l=new Map,u=m<1/0?z(e=>t.get(e).meta,e=>v(e,p)):null,s=A(0,{name:`collection-${a}:ver`}),d=b([s],()=>Array.from(t.values()),{name:`collection-${a}:nodes`}),h=b([s],()=>t.size,{name:`collection-${a}:size`}),M=!1;function _(){s.update(e=>e+1)}function x(e){let o=Array.from(e.meta.get().tags);f.update(e.id,o);let r=E(e.meta,I=>{let n=Array.from(I.tags);f.update(e.id,n)});l.set(e.id,()=>r.unsubscribe())}function D(e){let o=l.get(e);o&&(o(),l.delete(e)),f.remove(e)}function $(){if(!u||t.size<=m)return;let e=u.evict(t.size-m);for(let o of e){let r=t.get(o);r&&(D(o),r.destroy(),t.delete(o))}}function C(){if(!y)return 0;let e=[];for(let o of t.values())y(o)&&e.push(o.id);for(let o of e){let r=t.get(o);r&&(D(o),u?.delete(o),r.destroy(),t.delete(o))}return e.length}return{add(e,o){if(M)throw new Error("Collection is destroyed");if(T){let I=Array.from(t.values()),n=T(e,I);switch(n.action){case"reject":return;case"update":{let c=t.get(n.targetId);if(!c)throw new Error(`Admission update target "${n.targetId}" not found`);return c.update(n.content),c}case"merge":{let c=t.get(n.targetId);if(!c)throw new Error(`Admission merge target "${n.targetId}" not found`);let g=n.reducer(c.content.get(),e);return c.update(g),c}default:break}}y&&C();let r=L(e,o);return t.set(r.id,r),x(r),u?.insert(r.id),$(),_(),r},remove(e){let o=typeof e=="string"?e:e.id,r=t.get(o);return r?(D(o),u?.delete(o),r.destroy(),t.delete(o),_(),!0):!1},get(e){return t.get(e)},has(e){return t.has(e)},nodes:d,size:h,tagIndex:f,query(e){let o=[];for(let r of t.values())e(r)&&o.push(r);return o},byTag(e){let o=f.get(e),r=[];for(let I of o){let n=t.get(I);n&&r.push(n)}return r},topK(e,o){let r=o??p,I=Date.now(),n=Array.from(t.values()).map(c=>({node:c,score:v(c.meta.get(),r,I)}));return n.sort((c,g)=>g.score-c.score),n.slice(0,e).map(c=>c.node)},summarize(e,o,r){if(M)throw new Error("Collection is destroyed");let I=Array.from(new Set(e)),n=[];for(let N of I){let F=t.get(N);F&&n.push(F)}if(n.length===0)throw new Error("No valid nodes to summarize");let c=o(n),g;return w(()=>{for(let N of n)D(N.id),u?.delete(N.id),N.destroy(),t.delete(N.id);y&&C(),g=L(c,r),t.set(g.id,g),x(g),u?.insert(g.id),_()}),g},gc(){if(M)throw new Error("Collection is destroyed");let e=C();return e>0&&_(),e},destroy(){if(!M){M=!0,u?.clear();for(let e of l.values())e();l.clear(),f.destroy(),w(()=>{for(let e of t.values())e.destroy();t.clear()}),S(s)}}}}export{k as a,v as b,L as c,oe as d};
|
package/dist/data/index.d.cts
CHANGED
|
@@ -4,6 +4,31 @@ import { S as Store } from '../types-BohB8jJr.cjs';
|
|
|
4
4
|
import '../eviction-DGPP1vHP.cjs';
|
|
5
5
|
import '../protocol-fwiQ1TAS.cjs';
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Creates a lightweight topic-based publish/subscribe channel.
|
|
9
|
+
*
|
|
10
|
+
* @param opts - Optional configuration.
|
|
11
|
+
*
|
|
12
|
+
* @returns `PubSub<T>` — topic publish/subscribe API with snapshot and lifecycle methods.
|
|
13
|
+
*
|
|
14
|
+
* @remarks **Lazy channels:** Topics are created on first publish/subscribe.
|
|
15
|
+
* @remarks **Reactive subscription:** `subscribe(topic)` returns a read-only store for latest topic value.
|
|
16
|
+
* @remarks **Ephemeral emission semantics:** Message updates always emit, even for referentially equal values.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { pubsub } from "callbag-recharge/data";
|
|
21
|
+
*
|
|
22
|
+
* const bus = pubsub<string>();
|
|
23
|
+
* const chat = bus.subscribe("chat");
|
|
24
|
+
*
|
|
25
|
+
* bus.publish("chat", "hello");
|
|
26
|
+
* chat.get(); // "hello"
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @seeAlso [topic](/api/topic), [subscription](/api/subscription), [reactiveMap](./reactiveMap)
|
|
30
|
+
* @category data
|
|
31
|
+
*/
|
|
7
32
|
declare function pubsub<T = unknown>(opts?: {
|
|
8
33
|
id?: string;
|
|
9
34
|
}): PubSub<T>;
|
|
@@ -15,6 +40,39 @@ interface ReactiveIndexCreateOptions {
|
|
|
15
40
|
/** User-specified ID. Auto-generated if omitted. */
|
|
16
41
|
id?: string;
|
|
17
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Creates a reactive secondary index from index key to sets of primary keys.
|
|
45
|
+
*
|
|
46
|
+
* @param opts - Optional configuration.
|
|
47
|
+
*
|
|
48
|
+
* @returns `ReactiveIndex` — reverse mapping queries, reactive selectors, mutation helpers, and snapshot APIs.
|
|
49
|
+
*
|
|
50
|
+
* @remarks **Reverse map:** Tracks primary key to index keys for efficient `remove()` and `update()`.
|
|
51
|
+
* @remarks **Reactive selectors:** `select(indexKey)` returns cached stores for index-key membership updates.
|
|
52
|
+
* @remarks **Structural versioning:** `keysStore`/`sizeStore` are version-gated and update on keyset changes.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* import { reactiveIndex } from "callbag-recharge/data";
|
|
57
|
+
*
|
|
58
|
+
* const byTag = reactiveIndex();
|
|
59
|
+
* byTag.add("u1", ["admin", "active"]);
|
|
60
|
+
* byTag.get("admin"); // Set { "u1" }
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* @example Update indexed keys
|
|
64
|
+
* ```ts
|
|
65
|
+
* const byTag = reactiveIndex();
|
|
66
|
+
* byTag.add("u1", ["admin"]);
|
|
67
|
+
* byTag.update("u1", ["editor"]);
|
|
68
|
+
*
|
|
69
|
+
* byTag.get("admin").size; // 0
|
|
70
|
+
* byTag.get("editor").size; // 1
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* @seeAlso [reactiveMap](./reactiveMap), [reactiveList](./reactiveList), [pubsub](./pubsub)
|
|
74
|
+
* @category data
|
|
75
|
+
*/
|
|
18
76
|
declare function reactiveIndex(opts?: ReactiveIndexCreateOptions): ReactiveIndex;
|
|
19
77
|
declare namespace reactiveIndex {
|
|
20
78
|
var from: (snap: IndexSnapshot) => ReactiveIndex;
|
|
@@ -135,6 +193,38 @@ declare namespace reactiveLog {
|
|
|
135
193
|
var from: <V>(snap: LogSnapshot<V>, opts?: Omit<ReactiveLogOptions, "id">) => ReactiveLog<V>;
|
|
136
194
|
}
|
|
137
195
|
|
|
196
|
+
/**
|
|
197
|
+
* Creates a reactive key-value store with point reads, reactive selects, and optional TTL.
|
|
198
|
+
*
|
|
199
|
+
* @param opts - Optional configuration.
|
|
200
|
+
*
|
|
201
|
+
* @returns `ReactiveMap<V>` — key-value operations, reactive views, events, and lifecycle controls.
|
|
202
|
+
*
|
|
203
|
+
* @remarks **Single source of truth:** Internal `Map` is authoritative; reactive stores mirror map state.
|
|
204
|
+
* @remarks **Reactive views:** `select(key)`, `keysStore`, and `sizeStore` update through graph propagation.
|
|
205
|
+
* @remarks **TTL + eviction:** Supports per-key/default TTL and optional bounded-size eviction policies.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* ```ts
|
|
209
|
+
* import { reactiveMap } from "callbag-recharge/data";
|
|
210
|
+
*
|
|
211
|
+
* const users = reactiveMap<{ name: string }>();
|
|
212
|
+
* users.set("u1", { name: "Ada" });
|
|
213
|
+
* users.get("u1"); // { name: "Ada" }
|
|
214
|
+
* ```
|
|
215
|
+
*
|
|
216
|
+
* @example Reactive key subscription
|
|
217
|
+
* ```ts
|
|
218
|
+
* const users = reactiveMap<number>();
|
|
219
|
+
* const score = users.select("u1");
|
|
220
|
+
*
|
|
221
|
+
* users.set("u1", 10);
|
|
222
|
+
* score.get(); // 10
|
|
223
|
+
* ```
|
|
224
|
+
*
|
|
225
|
+
* @seeAlso [reactiveIndex](./reactiveIndex), [reactiveLog](./reactiveLog), [compaction](./compaction)
|
|
226
|
+
* @category data
|
|
227
|
+
*/
|
|
138
228
|
declare function reactiveMap<V>(opts?: ReactiveMapOptions<V>): ReactiveMap<V>;
|
|
139
229
|
declare namespace reactiveMap {
|
|
140
230
|
var from: <V>(snap: MapSnapshot<V>, opts?: Omit<ReactiveMapOptions<V>, "id">) => ReactiveMap<V>;
|
package/dist/data/index.d.ts
CHANGED
|
@@ -4,6 +4,31 @@ import { S as Store } from '../types-CB1htCM8.js';
|
|
|
4
4
|
import '../eviction-DGPP1vHP.js';
|
|
5
5
|
import '../protocol-fwiQ1TAS.js';
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Creates a lightweight topic-based publish/subscribe channel.
|
|
9
|
+
*
|
|
10
|
+
* @param opts - Optional configuration.
|
|
11
|
+
*
|
|
12
|
+
* @returns `PubSub<T>` — topic publish/subscribe API with snapshot and lifecycle methods.
|
|
13
|
+
*
|
|
14
|
+
* @remarks **Lazy channels:** Topics are created on first publish/subscribe.
|
|
15
|
+
* @remarks **Reactive subscription:** `subscribe(topic)` returns a read-only store for latest topic value.
|
|
16
|
+
* @remarks **Ephemeral emission semantics:** Message updates always emit, even for referentially equal values.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { pubsub } from "callbag-recharge/data";
|
|
21
|
+
*
|
|
22
|
+
* const bus = pubsub<string>();
|
|
23
|
+
* const chat = bus.subscribe("chat");
|
|
24
|
+
*
|
|
25
|
+
* bus.publish("chat", "hello");
|
|
26
|
+
* chat.get(); // "hello"
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @seeAlso [topic](/api/topic), [subscription](/api/subscription), [reactiveMap](./reactiveMap)
|
|
30
|
+
* @category data
|
|
31
|
+
*/
|
|
7
32
|
declare function pubsub<T = unknown>(opts?: {
|
|
8
33
|
id?: string;
|
|
9
34
|
}): PubSub<T>;
|
|
@@ -15,6 +40,39 @@ interface ReactiveIndexCreateOptions {
|
|
|
15
40
|
/** User-specified ID. Auto-generated if omitted. */
|
|
16
41
|
id?: string;
|
|
17
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Creates a reactive secondary index from index key to sets of primary keys.
|
|
45
|
+
*
|
|
46
|
+
* @param opts - Optional configuration.
|
|
47
|
+
*
|
|
48
|
+
* @returns `ReactiveIndex` — reverse mapping queries, reactive selectors, mutation helpers, and snapshot APIs.
|
|
49
|
+
*
|
|
50
|
+
* @remarks **Reverse map:** Tracks primary key to index keys for efficient `remove()` and `update()`.
|
|
51
|
+
* @remarks **Reactive selectors:** `select(indexKey)` returns cached stores for index-key membership updates.
|
|
52
|
+
* @remarks **Structural versioning:** `keysStore`/`sizeStore` are version-gated and update on keyset changes.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* import { reactiveIndex } from "callbag-recharge/data";
|
|
57
|
+
*
|
|
58
|
+
* const byTag = reactiveIndex();
|
|
59
|
+
* byTag.add("u1", ["admin", "active"]);
|
|
60
|
+
* byTag.get("admin"); // Set { "u1" }
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* @example Update indexed keys
|
|
64
|
+
* ```ts
|
|
65
|
+
* const byTag = reactiveIndex();
|
|
66
|
+
* byTag.add("u1", ["admin"]);
|
|
67
|
+
* byTag.update("u1", ["editor"]);
|
|
68
|
+
*
|
|
69
|
+
* byTag.get("admin").size; // 0
|
|
70
|
+
* byTag.get("editor").size; // 1
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* @seeAlso [reactiveMap](./reactiveMap), [reactiveList](./reactiveList), [pubsub](./pubsub)
|
|
74
|
+
* @category data
|
|
75
|
+
*/
|
|
18
76
|
declare function reactiveIndex(opts?: ReactiveIndexCreateOptions): ReactiveIndex;
|
|
19
77
|
declare namespace reactiveIndex {
|
|
20
78
|
var from: (snap: IndexSnapshot) => ReactiveIndex;
|
|
@@ -135,6 +193,38 @@ declare namespace reactiveLog {
|
|
|
135
193
|
var from: <V>(snap: LogSnapshot<V>, opts?: Omit<ReactiveLogOptions, "id">) => ReactiveLog<V>;
|
|
136
194
|
}
|
|
137
195
|
|
|
196
|
+
/**
|
|
197
|
+
* Creates a reactive key-value store with point reads, reactive selects, and optional TTL.
|
|
198
|
+
*
|
|
199
|
+
* @param opts - Optional configuration.
|
|
200
|
+
*
|
|
201
|
+
* @returns `ReactiveMap<V>` — key-value operations, reactive views, events, and lifecycle controls.
|
|
202
|
+
*
|
|
203
|
+
* @remarks **Single source of truth:** Internal `Map` is authoritative; reactive stores mirror map state.
|
|
204
|
+
* @remarks **Reactive views:** `select(key)`, `keysStore`, and `sizeStore` update through graph propagation.
|
|
205
|
+
* @remarks **TTL + eviction:** Supports per-key/default TTL and optional bounded-size eviction policies.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* ```ts
|
|
209
|
+
* import { reactiveMap } from "callbag-recharge/data";
|
|
210
|
+
*
|
|
211
|
+
* const users = reactiveMap<{ name: string }>();
|
|
212
|
+
* users.set("u1", { name: "Ada" });
|
|
213
|
+
* users.get("u1"); // { name: "Ada" }
|
|
214
|
+
* ```
|
|
215
|
+
*
|
|
216
|
+
* @example Reactive key subscription
|
|
217
|
+
* ```ts
|
|
218
|
+
* const users = reactiveMap<number>();
|
|
219
|
+
* const score = users.select("u1");
|
|
220
|
+
*
|
|
221
|
+
* users.set("u1", 10);
|
|
222
|
+
* score.get(); // 10
|
|
223
|
+
* ```
|
|
224
|
+
*
|
|
225
|
+
* @seeAlso [reactiveIndex](./reactiveIndex), [reactiveLog](./reactiveLog), [compaction](./compaction)
|
|
226
|
+
* @category data
|
|
227
|
+
*/
|
|
138
228
|
declare function reactiveMap<V>(opts?: ReactiveMapOptions<V>): ReactiveMap<V>;
|
|
139
229
|
declare namespace reactiveMap {
|
|
140
230
|
var from: <V>(snap: MapSnapshot<V>, opts?: Omit<ReactiveMapOptions<V>, "id">) => ReactiveMap<V>;
|
package/dist/memory/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}static _signalLabel(e){return e===
|
|
3
|
-
`)}static toD2(e){let
|
|
4
|
-
`)}static annotate(e,s){if(!i.enabled)return;i._annotations.set(e,s);let t={node:i._resolveKey(e),reason:s,timestamp:Date.now()},n=i.maxTraceEntries;n<=0||(i._traceLog.length<n?i._traceLog.push(t):(i._traceLog[i._traceHead]=t,i._traceFull=!0),i._traceHead=(i._traceHead+1)%n)}static getAnnotation(e){return i._annotations.get(e)}static traceLog(){return i._traceFull?[...i._traceLog.slice(i._traceHead),...i._traceLog.slice(0,i._traceHead)]:i._traceLog.slice(0,i._traceHead||i._traceLog.length)}static clearTrace(){i._traceLog=[],i._traceHead=0,i._traceFull=!1}static timeline(e){let s=null,t=[];return e.source(S,(n,o)=>{if(n===S){s=o;return}let a={timestamp:Date.now(),type:n===v?"data":n===m?"signal":"end",data:o,inBatch:K()};t.push(a),n===_&&(s=null)}),{entries:t,dispose:()=>s?.(_)}}static observeDerived(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),evaluations:s};t._fn=()=>{let d=t._deps.map(r=>r.get()),f=n();return s.push({result:f,depValues:d,timestamp:Date.now()}),f};let o=i._observe(e),a=o.dispose;return{...o,evaluations:s,dispose:()=>{t._fn=n,a()},reconnect:()=>(t._fn=n,a(),i.observeDerived(e))}}static observeTaskState(e){let s=e.status.get(),t=[],n=null;return e.status.source(S,(o,a)=>{if(o===S){n=a;return}if(o===v){let u=a;if(u!==s){let d={from:s,to:u,timestamp:Date.now()};u==="error"&&(d.error=e.error.get()),t.push(d),s=u}}o===_&&(n=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{n?.(_)}}}static causalityTrace(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),causality:s};let o=t._deps,a=o.map(r=>r.get());t._fn=()=>{let r=o.map(T=>T.get()),l=n(),g=-1;for(let T=0;T<o.length;T++)if(!Object.is(r[T],a[T])){g=T;break}return s.push({result:l,triggerDepIndex:g,triggerDepName:g>=0?i.getName(o[g]):void 0,depValues:r,timestamp:Date.now()}),a=r,l};let u=i._observe(e),d=u.dispose;return{...u,causality:s,dispose:()=>{t._fn=n,d()},reconnect:()=>(t._fn=n,d(),i.causalityTrace(e))}}static _reset(){i._names=new WeakMap,i._kinds=new WeakMap,i._keys=new WeakMap,i._stores=new Set,i._edges=new Map,i._usedKeys=new Set,i._nextId=0,i._explicitEnabled=null,i._cachedDefault=null,i._annotations=new WeakMap,i._traceLog=[],i._traceHead=0,i._traceFull=!1,i.maxTraceEntries=1e3}};var Y=1,B=2,G=4,M=8,V=32,Oe=64,Be=le<<k,J=ue<<k,Re=fe<<k,te=de<<k,Ge=pe<<k,Te=he<<k,b=ee,ye=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return ge(this._flags)}constructor(e,s,t,n){this._deps=e,this._fn=s,this._eqFn=t?.equals,this._flags=n?Oe:0,this._dirtyDeps=new ne(e.length),this.source=this.source.bind(this),F.register(this,{kind:"derived",...t,deps:e});for(let o of e)F.registerEdge(o,this)}_dispatch(e,s){let t=this._output;if(t)if(this._flags&V)for(let n of t)n(e,s);else t(e,s)}_recompute(){let e;try{e=this._fn()}catch(s){this._handleEnd(s);return}if(this._eqFn&&this._flags&Y&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~b|te,this._dispatch(m,I);return}this._cachedValue=e,this._flags=(this._flags|Y)&~b|Re,this._dispatch(v,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&M)){if(this._eqFn&&this._flags&Y&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~b|te,this._dispatch(m,I);return}this._cachedValue=e,this._flags=(this._flags|Y)&~b|Re,this._dispatch(v,e)}}_lazyConnect(){if(!(this._flags&(B|M))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|Y)&~b|Re,me(),this._connectUpstream(),this._flags&M||(this._flags|=B),Se()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&Oe?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(S,(s,t)=>{if(s===S){this._upstreamTalkbacks.push(t),t(m,X);return}if(!(this._flags&M))if(s===m)if(t===y){if(e)return;e=!0,this._flags=this._flags&~b|J,this._dispatch(m,y)}else t===I?e&&(e=!1,this._flags=this._flags&~b|te,this._dispatch(m,I)):this._dispatch(m,t);else s===v?e?(e=!1,this._recompute()):(this._flags=this._flags&~b|J,this._dispatch(m,y),this._recompute()):s===_&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(S,(s,t)=>{if(s===S){this._upstreamTalkbacks.push(t),t(m,X);return}this._flags&M||(s===m?t===y?(e=!0,this._flags=this._flags&~b|J,this._dispatch(m,y)):t===I?e&&(e=!1,this._flags=this._flags&~b|te,this._dispatch(m,I)):this._dispatch(m,t):s===v?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~b|J,this._dispatch(m,y),this._recomputeIdentity(t)):s===_&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&M);e++){let s=e;this._deps[s].source(S,(t,n)=>{if(t===S){this._upstreamTalkbacks.push(n);return}if(!(this._flags&M))if(t===m)if(n===y){let o=this._dirtyDeps.empty();this._dirtyDeps.set(s),o&&(this._flags&=~G,this._flags=this._flags&~b|J,this._dispatch(m,y))}else n===I?this._dirtyDeps.test(s)&&(this._dirtyDeps.clear(s),this._dirtyDeps.empty()&&(this._flags&G?this._recompute():(this._flags=this._flags&~b|te,this._dispatch(m,I)))):this._dispatch(m,n);else t===v?this._dirtyDeps.test(s)?(this._dirtyDeps.clear(s),this._flags|=G,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~b|J,this._dispatch(m,y),this._recompute()):this._flags|=G:t===_&&this._handleEnd(n)})}}_handleEnd(e){this._flags|=M,this._flags=this._flags&~b|(e!==void 0?Te:Ge),e!==void 0&&(this._cachedValue=e);for(let n of this._upstreamTalkbacks)n(_);this._upstreamTalkbacks=[],this._flags&=~B,this._dirtyDeps.reset();let s=this._output,t=this._flags&V;if(this._output=null,this._flags&=~V,s)if(t)for(let n of s)try{e!==void 0?n(_,e):n(_)}catch{}else e!==void 0?s(_,e):s(_)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(_);this._upstreamTalkbacks.length=0,this._flags&=~(B|G),this._flags=this._flags&~b|Be,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&M)){if(e===H){for(let s of this._upstreamTalkbacks)s(m,H);this._handleEnd(void 0);return}e===q&&(this._flags&=~(Y|G),this._dirtyDeps.reset());for(let s of this._upstreamTalkbacks)s(m,e)}}get(){if(this._flags&B)return this._cachedValue;if(this._flags&M){if((this._flags&b)===Te)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=Y,e}source(e,s){if(e===S){let t=s;if(this._flags&M){let n=(this._flags&b)===Te;t(S,o=>{}),n?t(_,this._cachedValue):t(_);return}if(!(this._flags&B)&&(this._lazyConnect(),this._flags&M)){let n=(this._flags&b)===Te;t(S,o=>{}),n?t(_,this._cachedValue):t(_);return}if(this._output===null)this._output=t;else if(this._flags&V)this._output.add(t);else{let n=new Set;n.add(this._output),n.add(t),this._output=n,this._flags|=V}t(S,(n,o)=>{if(n===v&&t(v,this._cachedValue),n===m&&ce(o)){this._handleLifecycleSignal(o);return}if(n===_){if(this._output===null)return;if(this._flags&V){let a=this._output;a.delete(t),a.size===1?(this._output=a.values().next().value,this._flags&=~V):a.size===0&&(this._output=null,this._flags&=~V,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function A(i,e,s){return new ye(i,e,s)}(e=>{function i(s,t){return new ye([s],()=>s.get(),t,!0)}e.from=i})(A||={});var ve=1,N=64,L=2,Z=4,Ae=8,Ne=16,W=32,C=1024,x=ee,Q=ue<<k,se=fe<<k,be=le<<k,Je=pe<<k,Ze=he<<k,Qe=de<<k,Ee=class{_value;_output=null;_flags;get _status(){return ge(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,s){this._value=s?.initial,this._fn=e,this._eqFn=s?.equals,this._getterFn=s?.getter,this._initial=s?.initial;let t=0;s?.autoDirty!==!1&&(t|=Z),s?.resetOnTeardown&&(t|=Ae),s?.resubscribable&&(t|=Ne),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),s?._skipInspect||F.register(this,{kind:"producer",...s})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,s){let t=this._output;if(t)if(this._flags&N)for(let n of t)n(e,s);else t(e,s)}emit(e){this._flags&L||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&W||(this._flags|=W,this._flags&Z&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),_e(()=>{this._flags&=~W,this._flags=this._flags&~x|se,this._dispatch(v,this._value)})):(this._flags&Z&&!(this._flags&C)&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),this._flags=this._flags&~x|se,this._dispatch(v,this._value))))}signal(e){this._flags&L||!this._output||(e===y?this._flags=this._flags&~x|Q:e===I&&(this._flags=this._flags&~x|Qe),this._dispatch(m,e))}complete(){if(this._flags&L)return;this._flags=(this._flags|L)&~x|Je;let e=this._output,s=this._flags&N;if(this._output=null,this._flags&=~(N|C),this._singleDepCount=0,this._stop(),e)if(s)for(let t of e)t(_);else e(_)}error(e){if(this._flags&L)return;this._flags=(this._flags|L)&~x|Ze;let s=this._output,t=this._flags&N;if(this._output=null,this._flags&=~(N|C),this._singleDepCount=0,this._stop(),s)if(t)for(let n of s)n(_,e);else s(_,e)}_start(){if(this._flags&ve||!this._fn)return;this._flags|=ve,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:s=>this.signal(s),complete:()=>this.complete(),error:s=>this.error(s),onSignal:s=>{this._onLifecycleSignal=s}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&ve&&(this._flags&=~ve,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Ae&&(this._value=this._initial),this._flags&L||(this._flags=this._flags&~x|be))}_handleLifecycleSignal(e){if(!(this._flags&L)){if(e===H){this._onLifecycleSignal?.(e),this.complete();return}e===q&&(this._value=this._initial,this._flags&=~W),this._onLifecycleSignal?.(e),e===q&&this.emit(this._initial)}}source(e,s){if(e===S){let t=s;if(this._flags&L)if(this._flags&Ne&&this._output===null)this._flags=this._flags&~(L|x)|be;else{t(S,o=>{}),t(_);return}if(this._output===null)this._output=t;else if(this._flags&N)this._output.add(t);else{let o=new Set;o.add(this._output),o.add(t),this._output=o,this._flags=(this._flags|N)&~C}let n=!1;t(S,(o,a)=>{if(o===v&&t(v,this._value),o===m){a===X&&!n?(n=!0,this._singleDepCount++,this._flags&N||(this._flags|=C)):ce(a)&&this._handleLifecycleSignal(a);return}if(o===_){if(n&&(n=!1,this._singleDepCount--),this._output===null)return;if(this._flags&N){let u=this._output;u.delete(t),u.size===1?(this._output=u.values().next().value,this._flags&=~N,this._singleDepCount>0&&(this._flags|=C)):u.size===0&&(this._output=null,this._flags&=~(N|C),this._singleDepCount=0,this._flags=this._flags&~x|be,this._stop())}else this._output===t&&(this._output=null,this._flags&=~C,this._singleDepCount=0,this._flags=this._flags&~x|be,this._stop())}}),Le(()=>this._start())}}};var Me=class extends Ee{constructor(e,s){super(void 0,{initial:e,autoDirty:!0,equals:s?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),F.register(this,{kind:"state",...s})}get(){return this._value}set(e){this._flags&L||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&W||(this._flags|=W,this._flags&Z&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),_e(()=>{this._flags&=~W,this._flags=this._flags&~x|se,this._dispatch(v,this._value)})):(this._flags&Z&&!(this._flags&C)&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),this._flags=this._flags&~x|se,this._dispatch(v,this._value))))}update(e){this.set(e(this._value))}};function j(i,e){return new Me(i,e)}function De(i,e,s){let t=null;me(),i.source(S,(o,a)=>{if(o===S&&(t=a),o===_){t=null,s?.onEnd?.(a);return}if(o===1){let u=a,d=n;n=u,e(u,d)}});let n;try{n=i.get()}catch{}return Se(),{unsubscribe(){t?.(_),t=null},signal(o){t?.(m,o)}}}var Xe=0;xe.from=function(e){let s=xe({id:e.id});for(let[t,n]of Object.entries(e.index))for(let o of n)s.add(o,[t]);return s};function xe(i){let e=++Xe,s=i?.id??`ridx-${e}`,t=new Map,n=new Map,o=new Map,a=new Map,u=j(0,{name:`${s}:ver`}),d=A([u],()=>Array.from(t.keys()),{name:`${s}:keys`}),f=A([u],()=>t.size,{name:`${s}:size`}),r=!1,l=Object.freeze(new Set);function g(c){let p=o.get(c);return p||(p=j(t.get(c)??new Set,{name:`${s}:${c}`,equals:()=>!1}),o.set(c,p)),p}function T(c){let p=o.get(c);if(p){let h=t.get(c);p.set(h?new Set(h):new Set)}}function w(c,p){let h=t.get(p),E=!h;return h||(h=new Set,t.set(p,h)),h.add(c),E}function z(c,p){let h=t.get(p);return h?(h.delete(c),h.size===0?(t.delete(p),!0):!1):!1}return{get id(){return s},get version(){return u.get()},get(c){let p=t.get(c);return p?Object.freeze(new Set(p)):l},has(c){let p=t.get(c);return p!==void 0&&p.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(c){let p=a.get(c);if(p)return p;let h=g(c);return p=A([h],()=>h.get(),{name:`${s}:${c}:select`}),a.set(c,p),p},keysStore:d,sizeStore:f,add(c,p){if(r||p.length===0)return;let h=n.get(c);h||(h=new Set,n.set(c,h)),$(()=>{let E=!1;for(let D of p)h.add(D),w(c,D)&&(E=!0),T(D);E&&u.update(D=>D+1)})},remove(c){if(r)return;let p=n.get(c);p&&$(()=>{let h=!1;for(let E of p)z(c,E)&&(h=!0),T(E);n.delete(c),h&&u.update(E=>E+1)})},update(c,p){if(r)return;let h=n.get(c),E=new Set(p);$(()=>{let D=!1;if(h)for(let O of h)E.has(O)||(z(c,O)&&(D=!0),T(O));let R=n.get(c);R||(R=new Set,n.set(c,R)),R.clear();for(let O of p)R.add(O),w(c,O)&&(D=!0),T(O);D&&u.update(O=>O+1)})},clear(){t.size!==0&&$(()=>{t.clear(),n.clear();for(let c of o.values())c.set(new Set);u.update(c=>c+1)})},snapshot(){let c={};for(let[p,h]of t)c[p]=Array.from(h);return{type:"reactiveIndex",id:s,version:u.get(),index:c}},destroy(){if(!r){r=!0,t.clear(),n.clear();for(let c of o.values())P(c);o.clear();for(let c of a.values())P(c);a.clear(),P(u)}}}}function Ce(i,e=s=>s){let s=[],t=new Map,n=new Map;function o(f,r){let l=s[f],g=s[r];s[f]=g,s[r]=l,l.index=r,g.index=f}function a(f){for(;f>0;){let r=f-1>>>1;if(s[r].score<=s[f].score)break;o(f,r),f=r}}function u(f){let r=s.length;for(;;){let l=f,g=2*f+1,T=g+1;if(g<r&&s[g].score<s[l].score&&(l=g),T<r&&s[T].score<s[l].score&&(l=T),l===f)break;o(f,l),f=l}}function d(f){let r=s.length-1;if(f===r){s.pop();return}o(f,r),s.pop(),a(f),u(f)}return{touch(){},insert(f){if(t.has(f))return;let r=i(f),l={key:f,score:e(r.get()),index:s.length};s.push(l),t.set(f,l),a(l.index);let g=De(r,T=>{let w=t.get(f);if(!w)return;let z=w.score;w.score=e(T),w.score<z?a(w.index):w.score>z&&u(w.index)});n.set(f,()=>g.unsubscribe())},delete(f){let r=t.get(f);if(!r)return;let l=n.get(f);l&&(l(),n.delete(f)),d(r.index),t.delete(f)},evict(f=1){let r=[];for(;r.length<f&&s.length>0;){let{key:l}=s[0];r.push(l);let g=n.get(l);g&&(g(),n.delete(l)),d(0),t.delete(l)}return r},size:()=>t.size,clear(){for(let f of n.values())f();n.clear(),t.clear(),s.length=0}}}function $e(i){let e=i?.halfLife??864e5,s=i?.recency??1,t=i?.importance??1,n=i?.frequency??.5,o=Math.LN2/e;return(a,u)=>{let d=(u??Date.now())-a.accessedAt,f=Math.exp(-o*d),r=1-1/(1+a.accessCount);return s*f+t*a.importance+n*r}}function U(i,e,s){let t=e?.halfLife??864e5,n=e?.recency??1,o=e?.importance??1,a=e?.frequency??.5,u=(s??Date.now())-i.accessedAt,d=Math.exp(-Math.LN2/t*u),f=1-1/(1+i.accessCount);return n*d+o*i.importance+a*f}var et=0;function tt(){return`mem-${++et}`}function ke(i,e){let s=e?.id??tt(),t=Date.now(),n={id:s,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},o=j(i,{name:`mem:${s}:content`}),a=j(n,{name:`mem:${s}:meta`,equals:()=>!1}),u={},d=A([a],()=>U(a.get(),u),{name:`mem:${s}:score`});return{id:s,content:o,meta:a,scoreStore:d,touch(){let r=Date.now();a.update(l=>({...l,accessedAt:r,accessCount:l.accessCount+1}))},tag(...r){a.update(l=>{let g=new Set(l.tags);for(let T of r)g.add(T);return{...l,tags:g,updatedAt:Date.now()}})},untag(...r){a.update(l=>{let g=new Set(l.tags);for(let T of r)g.delete(T);return{...l,tags:g,updatedAt:Date.now()}})},setImportance(r){a.update(l=>({...l,importance:Math.max(0,Math.min(1,r)),updatedAt:Date.now()}))},update(r){$(()=>{o.set(r),a.update(l=>({...l,updatedAt:Date.now()}))})},score(r){return U(a.get(),r??u)},destroy(){P(o),P(a)}}}var st=0;function Pe(i){let e=++st,s=i?.maxSize??1/0,t=i?.weights??{},n=new Map,o=xe(),a=new Map,u=s<1/0?Ce(c=>n.get(c).meta,c=>U(c,t)):null,d=j(0,{name:`collection-${e}:ver`}),f=A([d],()=>Array.from(n.values()),{name:`collection-${e}:nodes`}),r=A([d],()=>n.size,{name:`collection-${e}:size`}),l=!1;function g(){d.update(c=>c+1)}function T(c){let p=Array.from(c.meta.get().tags);o.update(c.id,p);let h=De(c.meta,E=>{let D=Array.from(E.tags);o.update(c.id,D)});a.set(c.id,()=>h.unsubscribe())}function w(c){let p=a.get(c);p&&(p(),a.delete(c)),o.remove(c)}function z(){if(!u||n.size<=s)return;let c=u.evict(n.size-s);for(let p of c){let h=n.get(p);h&&(w(p),h.destroy(),n.delete(p))}}return{add(c,p){if(l)throw new Error("Collection is destroyed");let h=ke(c,p);return n.set(h.id,h),T(h),u?.insert(h.id),z(),g(),h},remove(c){let p=typeof c=="string"?c:c.id,h=n.get(p);return h?(w(p),u?.delete(p),h.destroy(),n.delete(p),g(),!0):!1},get(c){return n.get(c)},has(c){return n.has(c)},nodes:f,size:r,tagIndex:o,query(c){let p=[];for(let h of n.values())c(h)&&p.push(h);return p},byTag(c){let p=o.get(c),h=[];for(let E of p){let D=n.get(E);D&&h.push(D)}return h},topK(c,p){let h=p??t,E=Date.now(),D=Array.from(n.values()).map(R=>({node:R,score:U(R.meta.get(),h,E)}));return D.sort((R,O)=>O.score-R.score),D.slice(0,c).map(R=>R.node)},destroy(){if(!l){l=!0,u?.clear();for(let c of a.values())c();a.clear(),o.destroy(),P(d),$(()=>{for(let c of n.values())c.destroy();n.clear()})}}}}0&&(module.exports={collection,computeScore,decay,memoryNode});
|
|
1
|
+
"use strict";var qe=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ut=(s,e)=>{for(var n in e)qe(s,n,{get:e[n],enumerable:!0})},ft=(s,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ct(e))!lt.call(s,r)&&r!==n&&qe(s,r,{get:()=>e[r],enumerable:!(t=at(e,r))||t.enumerable});return s};var dt=s=>ft(qe({},"__esModule",{value:!0}),s);var Rt={};ut(Rt,{collection:()=>rt,computeScore:()=>ie,decay:()=>st,memoryNode:()=>be,vectorIndex:()=>ot});module.exports=dt(Rt);var ve=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let n=this._w;if(n===null)this._v|=1<<e;else{let t=e>>>5,r=1<<(e&31);n[t]&r||(n[t]|=r,this._v++)}}clear(e){let n=this._w;if(n===null)this._v&=~(1<<e);else{let t=e>>>5,r=1<<(e&31);n[t]&r&&(n[t]&=~r,this._v--)}}test(e){let n=this._w;return n===null?(this._v&1<<e)!==0:(n[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var O=Symbol("DIRTY"),U=Symbol("RESOLVED"),me=Symbol("SINGLE_DEP"),le=Symbol("RESET"),gt=Symbol("PAUSE"),ht=Symbol("RESUME"),ue=Symbol("TEARDOWN");function ke(s){return s===le||s===gt||s===ht||s===ue}var Ie=0,Me=1,Ae=2,Re=3,Ne=4,Le=5,H=7,ye=7<<H,pt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Oe(s){return pt[(s&ye)>>>H]}var M=0,C=1,v=2,D=3,Ee=0,De=[],Ye=!1;function X(s){Ee++;try{return s()}finally{if(Ee--,Ee===0&&!Ye){Ye=!0;for(let e=0;e<De.length;e++)De[e]();De.length=0,Ye=!1}}}function ae(){return Ee>0}function Ce(s){De.push(s)}var we=0,xe=[];function Fe(){we++}function $e(){if(we--,we===0){for(let s=0;s<xe.length;s++)xe[s]();xe.length=0}}function Xe(s){we>0?xe.push(s):s()}function G(s){let e=s;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var ne=class s{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(s._explicitEnabled!==null)return s._explicitEnabled;if(s._cachedDefault!==null)return s._cachedDefault;try{s._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{s._cachedDefault=!0}return s._cachedDefault}static set enabled(e){s._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let t=e.map(r=>s._names.get(r)??"?").join(",");return t.length>40?`${t.slice(0,37)}...`:t}static _resolveKey(e){let n=s._keys.get(e)??s._names.get(e);if(n)return n;let t=`anonymous_${s._nextId++}`;return s._keys.set(e,t),t}static register(e,n){if(!s.enabled)return;n?.name&&s._names.set(e,n.name),n?.kind&&s._kinds.set(e,n.kind);let t=s._nextId++,r=n?.name;if(!(r&&!s._usedKeys.has(r)))if(r){let a=s._depSuffix(n?.deps);r=a?`${r}(${a})`:`${r}_${t}`,s._usedKeys.has(r)&&(r=`${r}_${t}`)}else{let a=n?.kind??"store",i=s._depSuffix(n?.deps);r=i?`${a}(${i})`:`${a}_${t}`,s._usedKeys.has(r)&&(r=`${r}_${t}`)}s._usedKeys.add(r),s._keys.set(e,r),s._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!s.enabled)return;let t=s._resolveKey(e),r=s._resolveKey(n),a=s._edges.get(t);a?a.includes(r)||a.push(r):s._edges.set(t,[r])}static getEdges(){return new Map(s._edges)}static getName(e){if(s.enabled)return s._names.get(e)}static getKind(e){return s._kinds.get(e)}static inspect(e){return{name:s._names.get(e),kind:s._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,n=new Set;for(let t of s._stores){let r=t.deref();if(!r){s._stores.delete(t);continue}let a=s._resolveKey(r);n.add(a),e.set(a,s.inspect(r))}for(let[t,r]of s._edges){if(!n.has(t)){s._edges.delete(t),s._usedKeys.delete(t);continue}let a=r.filter(i=>n.has(i));a.length===0?s._edges.delete(t):a.length!==r.length&&s._edges.set(t,a)}return e}static trace(e,n){let t=null,r=e.get();return e.source(M,(a,i)=>{if(a===M&&(t=i),a===v){t=null;return}if(a===1){let f=i;if(!Object.is(f,r)){let c=r;r=f,n(f,c)}}}),()=>t?.(v)}static dumpGraph(){let e=s.graph(),n=s.getEdges(),t=new Map;for(let[i,f]of n)for(let c of f){let u=t.get(c);u?u.includes(i)||u.push(i):t.set(c,[i])}let r=[];for(let[i,f]of e){let c=t.get(i),u=n.get(i),o=c?.length?` \u2190 [${c.join(", ")}]`:"",l=u?.length?` \u2192 [${u.join(", ")}]`:"";r.push(` ${i} (${f.kind}) = ${JSON.stringify(f.value)} [${f.status??"?"}]${o}${l}`)}return[`Store Graph (${e.size} nodes):`,...r].join(`
|
|
2
|
+
`)}static _signalLabel(e){return e===O?"DIRTY":e===U?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,n,t){let r=null,a=!1,i=n??s.getName(e),f=[],c={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return c.ended&&!a},get errored(){return c.ended&&a},dirtyCount:0,resolvedCount:0,name:i,get eventLog(){return f},dispose:()=>r?.(v),reconnect:()=>(r?.(v),s._observe(e,n,t))};return e.source(M,(u,o)=>{if(u===M){r=o;return}let l=ae();u===C?(c.values.push(o),c.events.push({type:"data",data:o,inBatch:l}),f.push(o),t&&t(`[${i}] DATA:`,o)):u===D?(c.signals.push(o),c.events.push({type:"signal",data:o,inBatch:l}),f.push(s._signalLabel(o)),o===O?c.dirtyCount++:o===U&&c.resolvedCount++,t&&t(`[${i}] STATE:`,o)):u===v&&(c.ended=!0,c.endError=o,a=o!==void 0,c.events.push({type:"end",data:o,inBatch:l}),f.push(a?["END",o]:"END"),t&&t(`[${i}] END`,o!==void 0?o:""),r=null)}),c}static observe(e){return s._observe(e)}static activate(e){let n=null;return e.source(M,(t,r)=>{t===M&&(n=r),t===v&&(n=null)}),()=>n?.(v)}static tap(e,n){let t=n??`tap(${s.getName(e)??"anon"})`,r={get:()=>e.get(),source:e.source};return s.register(r,{name:t,kind:"tap"}),s.registerEdge(e,r),r}static spy(e,n){let t=n?.name??s.getName(e)??"spy",r=n?.log??console.log;return s._observe(e,t,r)}static snapshot(){let e=s.graph(),n=s.getEdges(),t=new Map;for(let i of s._stores){let f=i.deref();if(!f)continue;let c=s._annotations.get(f);c!==void 0&&t.set(s._resolveKey(f),c)}let r=[];for(let[i,f]of e){let c={name:i,kind:f.kind,value:f.value,status:f.status},u=t.get(i);u!==void 0&&(c.annotation=u),r.push(c)}let a=[];for(let[i,f]of n)for(let c of f)a.push({from:i,to:c});return{nodes:r,edges:a,trace:s.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",t=s.snapshot(),r=[`graph ${n}`],a={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},i=new Map;function f(o){let l=o.replace(/[^a-zA-Z0-9_]/g,"_"),g=i.get(l);return g===void 0?(i.set(l,1),l):(i.set(l,g+1),`${l}__${g}`)}let c=new Map;function u(o){let l=JSON.stringify(o);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let o of t.nodes){let l=f(o.name);c.set(o.name,l);let g=`${o.name} (${o.kind}) = ${u(o.value)}`,S=a[o.status??""]??"";r.push(` ${l}["${g}"]${S}`)}for(let o of t.edges){let l=c.get(o.from)??f(o.from),g=c.get(o.to)??f(o.to);r.push(` ${l} --> ${g}`)}return r.push(""),r.push(" classDef settled fill:#d4edda,stroke:#28a745"),r.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),r.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),r.push(" classDef completed fill:#cce5ff,stroke:#007bff"),r.join(`
|
|
3
|
+
`)}static toD2(e){let n=e?.direction??"down",t=s.snapshot(),r=[`direction: ${n}`,""],a={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},i=new Map;function f(o){let l=o.replace(/[^a-zA-Z0-9_]/g,"_"),g=i.get(l);return g===void 0?(i.set(l,1),l):(i.set(l,g+1),`${l}__${g}`)}let c=new Map;function u(o){let l=JSON.stringify(o);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let o of t.nodes){let l=f(o.name);c.set(o.name,l);let g=a[o.kind]??"rectangle",S=`${o.name} (${o.kind}) = ${u(o.value)}`,F=o.status?` [${o.status}]`:"";r.push(`${l}: "${S}${F}" { shape: ${g} }`)}t.edges.length>0&&r.push("");for(let o of t.edges){let l=c.get(o.from)??f(o.from),g=c.get(o.to)??f(o.to);r.push(`${l} -> ${g}`)}return r.join(`
|
|
4
|
+
`)}static annotate(e,n){if(!s.enabled)return;s._annotations.set(e,n);let t={node:s._resolveKey(e),reason:n,timestamp:Date.now()},r=s.maxTraceEntries;r<=0||(s._traceLog.length<r?s._traceLog.push(t):(s._traceLog[s._traceHead]=t,s._traceFull=!0),s._traceHead=(s._traceHead+1)%r)}static getAnnotation(e){return s._annotations.get(e)}static traceLog(){return s._traceFull?[...s._traceLog.slice(s._traceHead),...s._traceLog.slice(0,s._traceHead)]:s._traceLog.slice(0,s._traceHead||s._traceLog.length)}static clearTrace(){s._traceLog=[],s._traceHead=0,s._traceFull=!1}static timeline(e){let n=null,t=[];return e.source(M,(r,a)=>{if(r===M){n=a;return}let i={timestamp:Date.now(),type:r===C?"data":r===D?"signal":"end",data:a,inBatch:ae()};t.push(i),r===v&&(n=null)}),{entries:t,dispose:()=>n?.(v)}}static observeDerived(e){let n=[],t=e,r=t._fn;if(typeof r!="function"||!Array.isArray(t._deps))return{...s.observe(e),evaluations:n};t._fn=()=>{let c=t._deps.map(o=>o.get()),u=r();return n.push({result:u,depValues:c,timestamp:Date.now()}),u};let a=s._observe(e),i=a.dispose;return{...a,evaluations:n,dispose:()=>{t._fn=r,i()},reconnect:()=>(t._fn=r,i(),s.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),t=[],r=null;return e.status.source(M,(a,i)=>{if(a===M){r=i;return}if(a===C){let f=i;if(f!==n){let c={from:n,to:f,timestamp:Date.now()};f==="error"&&(c.error=e.error.get()),t.push(c),n=f}}a===v&&(r=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{r?.(v)}}}static causalityTrace(e){let n=[],t=e,r=t._fn;if(typeof r!="function"||!Array.isArray(t._deps))return{...s.observe(e),causality:n};let a=t._deps,i=a.map(o=>o.get());t._fn=()=>{let o=a.map(S=>S.get()),l=r(),g=-1;for(let S=0;S<a.length;S++)if(!Object.is(o[S],i[S])){g=S;break}return n.push({result:l,triggerDepIndex:g,triggerDepName:g>=0?s.getName(a[g]):void 0,depValues:o,timestamp:Date.now()}),i=o,l};let f=s._observe(e),c=f.dispose;return{...f,causality:n,dispose:()=>{t._fn=r,c()},reconnect:()=>(t._fn=r,c(),s.causalityTrace(e))}}static _reset(){s._names=new WeakMap,s._kinds=new WeakMap,s._keys=new WeakMap,s._stores=new Set,s._edges=new Map,s._usedKeys=new Set,s._nextId=0,s._explicitEnabled=null,s._cachedDefault=null,s._annotations=new WeakMap,s._traceLog=[],s._traceHead=0,s._traceFull=!1,s.maxTraceEntries=1e3}};var ce=1,fe=2,de=4,Y=8,se=32,Qe=64,_t=Ie<<H,ge=Me<<H,Be=Ae<<H,Se=Re<<H,mt=Ne<<H,Pe=Le<<H,P=ye,Ve=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return Oe(this._flags)}constructor(e,n,t,r){this._deps=e,this._fn=n,this._eqFn=t?.equals,this._flags=r?Qe:0,this._dirtyDeps=new ve(e.length),this.source=this.source.bind(this),ne.register(this,{kind:"derived",...t,deps:e});for(let a of e)ne.registerEdge(a,this)}_dispatch(e,n){let t=this._output;if(t)if(this._flags&se)for(let r of t)r(e,n);else t(e,n)}_recompute(){let e;try{e=this._fn()}catch(n){this._handleEnd(n);return}if(this._eqFn&&this._flags&ce&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~P|Se,this._dispatch(D,U);return}this._cachedValue=e,this._flags=(this._flags|ce)&~P|Be,this._dispatch(C,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&Y)){if(this._eqFn&&this._flags&ce&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~P|Se,this._dispatch(D,U);return}this._cachedValue=e,this._flags=(this._flags|ce)&~P|Be,this._dispatch(C,e)}}_lazyConnect(){if(!(this._flags&(fe|Y))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|ce)&~P|Be,Fe(),this._connectUpstream(),this._flags&Y||(this._flags|=fe),$e()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&Qe?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(M,(n,t)=>{if(n===M){this._upstreamTalkbacks.push(t),t(D,me);return}if(!(this._flags&Y))if(n===D)if(t===O){if(e)return;e=!0,this._flags=this._flags&~P|ge,this._dispatch(D,O)}else t===U?e&&(e=!1,this._flags=this._flags&~P|Se,this._dispatch(D,U)):this._dispatch(D,t);else n===C?e?(e=!1,this._recompute()):(this._flags=this._flags&~P|ge,this._dispatch(D,O),this._recompute()):n===v&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(M,(n,t)=>{if(n===M){this._upstreamTalkbacks.push(t),t(D,me);return}this._flags&Y||(n===D?t===O?(e=!0,this._flags=this._flags&~P|ge,this._dispatch(D,O)):t===U?e&&(e=!1,this._flags=this._flags&~P|Se,this._dispatch(D,U)):this._dispatch(D,t):n===C?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~P|ge,this._dispatch(D,O),this._recomputeIdentity(t)):n===v&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&Y);e++){let n=e;this._deps[n].source(M,(t,r)=>{if(t===M){this._upstreamTalkbacks.push(r);return}if(!(this._flags&Y))if(t===D)if(r===O){let a=this._dirtyDeps.empty();this._dirtyDeps.set(n),a&&(this._flags&=~de,this._flags=this._flags&~P|ge,this._dispatch(D,O))}else r===U?this._dirtyDeps.test(n)&&(this._dirtyDeps.clear(n),this._dirtyDeps.empty()&&(this._flags&de?this._recompute():(this._flags=this._flags&~P|Se,this._dispatch(D,U)))):this._dispatch(D,r);else t===C?this._dirtyDeps.test(n)?(this._dirtyDeps.clear(n),this._flags|=de,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~P|ge,this._dispatch(D,O),this._recompute()):this._flags|=de:t===v&&this._handleEnd(r)})}}_handleEnd(e){this._flags|=Y,this._flags=this._flags&~P|(e!==void 0?Pe:mt),e!==void 0&&(this._cachedValue=e);for(let r of this._upstreamTalkbacks)r(v);this._upstreamTalkbacks=[],this._flags&=~fe,this._dirtyDeps.reset();let n=this._output,t=this._flags&se;if(this._output=null,this._flags&=~se,n)if(t)for(let r of n)try{e!==void 0?r(v,e):r(v)}catch{}else e!==void 0?n(v,e):n(v)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(v);this._upstreamTalkbacks.length=0,this._flags&=~(fe|de),this._flags=this._flags&~P|_t,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&Y)){if(e===ue){for(let n of this._upstreamTalkbacks)n(D,ue);this._handleEnd(void 0);return}e===le&&(this._flags&=~(ce|de),this._dirtyDeps.reset());for(let n of this._upstreamTalkbacks)n(D,e)}}get(){if(this._flags&fe)return this._cachedValue;if(this._flags&Y){if((this._flags&P)===Pe)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=ce,e}source(e,n){if(e===M){let t=n;if(this._flags&Y){let r=(this._flags&P)===Pe;t(M,a=>{}),r?t(v,this._cachedValue):t(v);return}if(!(this._flags&fe)&&(this._lazyConnect(),this._flags&Y)){let r=(this._flags&P)===Pe;t(M,a=>{}),r?t(v,this._cachedValue):t(v);return}if(this._output===null)this._output=t;else if(this._flags&se)this._output.add(t);else{let r=new Set;r.add(this._output),r.add(t),this._output=r,this._flags|=se}t(M,(r,a)=>{if(r===C&&t(C,this._cachedValue),r===D&&ke(a)){this._handleLifecycleSignal(a);return}if(r===v){if(this._output===null)return;if(this._flags&se){let i=this._output;i.delete(t),i.size===1?(this._output=i.values().next().value,this._flags&=~se):i.size===0&&(this._output=null,this._flags&=~se,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function J(s,e,n){return new Ve(s,e,n)}(e=>{function s(n,t){return new Ve([n],()=>n.get(),t,!0)}e.from=s})(J||={});var ze=1,Z=64,B=2,he=4,et=8,tt=16,re=32,Q=1024,z=ye,pe=Me<<H,Te=Ae<<H,He=Ie<<H,yt=Ne<<H,St=Le<<H,Tt=Re<<H,We=class{_value;_output=null;_flags;get _status(){return Oe(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,n){this._value=n?.initial,this._fn=e,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let t=0;n?.autoDirty!==!1&&(t|=he),n?.resetOnTeardown&&(t|=et),n?.resubscribable&&(t|=tt),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||ne.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let t=this._output;if(t)if(this._flags&Z)for(let r of t)r(e,n);else t(e,n)}emit(e){this._flags&B||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(ae()?this._flags&re||(this._flags|=re,this._flags&he&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),Ce(()=>{this._flags&=~re,this._flags=this._flags&~z|Te,this._dispatch(C,this._value)})):(this._flags&he&&!(this._flags&Q)&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),this._flags=this._flags&~z|Te,this._dispatch(C,this._value))))}signal(e){this._flags&B||!this._output||(e===O?this._flags=this._flags&~z|pe:e===U&&(this._flags=this._flags&~z|Tt),this._dispatch(D,e))}complete(){if(this._flags&B)return;this._flags=(this._flags|B)&~z|yt;let e=this._output,n=this._flags&Z;if(this._output=null,this._flags&=~(Z|Q),this._singleDepCount=0,this._stop(),e)if(n)for(let t of e)t(v);else e(v)}error(e){if(this._flags&B)return;this._flags=(this._flags|B)&~z|St;let n=this._output,t=this._flags&Z;if(this._output=null,this._flags&=~(Z|Q),this._singleDepCount=0,this._stop(),n)if(t)for(let r of n)r(v,e);else n(v,e)}_start(){if(this._flags&ze||!this._fn)return;this._flags|=ze,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n),onSignal:n=>{this._onLifecycleSignal=n}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&ze&&(this._flags&=~ze,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&et&&(this._value=this._initial),this._flags&B||(this._flags=this._flags&~z|He))}_handleLifecycleSignal(e){if(!(this._flags&B)){if(e===ue){this._onLifecycleSignal?.(e),this.complete();return}e===le&&(this._value=this._initial,this._flags&=~re),this._onLifecycleSignal?.(e),e===le&&this.emit(this._initial)}}source(e,n){if(e===M){let t=n;if(this._flags&B)if(this._flags&tt&&this._output===null)this._flags=this._flags&~(B|z)|He;else{t(M,a=>{}),t(v);return}if(this._output===null)this._output=t;else if(this._flags&Z)this._output.add(t);else{let a=new Set;a.add(this._output),a.add(t),this._output=a,this._flags=(this._flags|Z)&~Q}let r=!1;t(M,(a,i)=>{if(a===C&&t(C,this._value),a===D){i===me&&!r?(r=!0,this._singleDepCount++,this._flags&Z||(this._flags|=Q)):ke(i)&&this._handleLifecycleSignal(i);return}if(a===v){if(r&&(r=!1,this._singleDepCount--),this._output===null)return;if(this._flags&Z){let f=this._output;f.delete(t),f.size===1?(this._output=f.values().next().value,this._flags&=~Z,this._singleDepCount>0&&(this._flags|=Q)):f.size===0&&(this._output=null,this._flags&=~(Z|Q),this._singleDepCount=0,this._flags=this._flags&~z|He,this._stop())}else this._output===t&&(this._output=null,this._flags&=~Q,this._singleDepCount=0,this._flags=this._flags&~z|He,this._stop())}}),Xe(()=>this._start())}}};var Ge=class extends We{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),ne.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&B||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(ae()?this._flags&re||(this._flags|=re,this._flags&he&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),Ce(()=>{this._flags&=~re,this._flags=this._flags&~z|Te,this._dispatch(C,this._value)})):(this._flags&he&&!(this._flags&Q)&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),this._flags=this._flags&~z|Te,this._dispatch(C,this._value))))}update(e){this.set(e(this._value))}};function ee(s,e){return new Ge(s,e)}function je(s,e,n){let t=null;Fe(),s.source(M,(a,i)=>{if(a===M&&(t=i),a===v){t=null,n?.onEnd?.(i);return}if(a===1){let f=i,c=r;r=f,e(f,c)}});let r;try{r=s.get()}catch{}return $e(),{unsubscribe(){t?.(v),t=null},signal(a){t?.(D,a)}}}var bt=0;Ue.from=function(e){let n=Ue({id:e.id});for(let[t,r]of Object.entries(e.index))for(let a of r)n.add(a,[t]);return n};function Ue(s){let e=++bt,n=s?.id??`ridx-${e}`,t=new Map,r=new Map,a=new Map,i=new Map,f=ee(0,{name:`${n}:ver`}),c=J([f],()=>Array.from(t.keys()),{name:`${n}:keys`}),u=J([f],()=>t.size,{name:`${n}:size`}),o=!1,l=Object.freeze(new Set);function g(h){let m=a.get(h);return m||(m=ee(t.get(h)??new Set,{name:`${n}:${h}`,equals:()=>!1}),a.set(h,m)),m}function S(h){let m=a.get(h);if(m){let w=t.get(h);m.set(w?new Set(w):new Set)}}function F(h,m){let w=t.get(m),d=!w;return w||(w=new Set,t.set(m,w)),w.add(h),d}function K(h,m){let w=t.get(m);return w?(w.delete(h),w.size===0?(t.delete(m),!0):!1):!1}return{get id(){return n},get version(){return f.get()},get(h){let m=t.get(h);return m?Object.freeze(new Set(m)):l},has(h){let m=t.get(h);return m!==void 0&&m.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(h){let m=i.get(h);if(m)return m;let w=g(h);return m=J([w],()=>w.get(),{name:`${n}:${h}:select`}),i.set(h,m),m},keysStore:c,sizeStore:u,add(h,m){if(o||m.length===0)return;let w=r.get(h);w||(w=new Set,r.set(h,w)),X(()=>{let d=!1;for(let _ of m)w.add(_),F(h,_)&&(d=!0),S(_);d&&f.update(_=>_+1)})},remove(h){if(o)return;let m=r.get(h);m&&X(()=>{let w=!1;for(let d of m)K(h,d)&&(w=!0),S(d);r.delete(h),w&&f.update(d=>d+1)})},update(h,m){if(o)return;let w=r.get(h),d=new Set(m);X(()=>{let _=!1;if(w)for(let L of w)d.has(L)||(K(h,L)&&(_=!0),S(L));let x=r.get(h);x||(x=new Set,r.set(h,x)),x.clear();for(let L of m)x.add(L),F(h,L)&&(_=!0),S(L);_&&f.update(L=>L+1)})},clear(){t.size!==0&&X(()=>{t.clear(),r.clear();for(let h of a.values())h.set(new Set);f.update(h=>h+1)})},snapshot(){let h={};for(let[m,w]of t)h[m]=Array.from(w);return{type:"reactiveIndex",id:n,version:f.get(),index:h}},destroy(){if(!o){o=!0,t.clear(),r.clear();for(let h of a.values())G(h);a.clear();for(let h of i.values())G(h);i.clear(),G(f)}}}}function nt(s,e=n=>n){let n=[],t=new Map,r=new Map;function a(u,o){let l=n[u],g=n[o];n[u]=g,n[o]=l,l.index=o,g.index=u}function i(u){for(;u>0;){let o=u-1>>>1;if(n[o].score<=n[u].score)break;a(u,o),u=o}}function f(u){let o=n.length;for(;;){let l=u,g=2*u+1,S=g+1;if(g<o&&n[g].score<n[l].score&&(l=g),S<o&&n[S].score<n[l].score&&(l=S),l===u)break;a(u,l),u=l}}function c(u){let o=n.length-1;if(u===o){n.pop();return}a(u,o),n.pop(),i(u),f(u)}return{touch(){},insert(u){if(t.has(u))return;let o=s(u),l={key:u,score:e(o.get()),index:n.length};n.push(l),t.set(u,l),i(l.index);let g=je(o,S=>{let F=t.get(u);if(!F)return;let K=F.score;F.score=e(S),F.score<K?i(F.index):F.score>K&&f(F.index)});r.set(u,()=>g.unsubscribe())},delete(u){let o=t.get(u);if(!o)return;let l=r.get(u);l&&(l(),r.delete(u)),c(o.index),t.delete(u)},evict(u=1){let o=[];for(;o.length<u&&n.length>0;){let{key:l}=n[0];o.push(l);let g=r.get(l);g&&(g(),r.delete(l)),c(0),t.delete(l)}return o},size:()=>t.size,clear(){for(let u of r.values())u();r.clear(),t.clear(),n.length=0}}}function st(s){let e=s?.halfLife??864e5,n=s?.recency??1,t=s?.importance??1,r=s?.frequency??.5,a=Math.LN2/e;return(i,f)=>{let c=(f??Date.now())-i.accessedAt,u=Math.exp(-a*c),o=1-1/(1+i.accessCount);return n*u+t*i.importance+r*o}}function ie(s,e,n){let t=e?.halfLife??864e5,r=e?.recency??1,a=e?.importance??1,i=e?.frequency??.5,f=(n??Date.now())-s.accessedAt,c=Math.exp(-Math.LN2/t*f),u=1-1/(1+s.accessCount);return r*c+a*s.importance+i*u}var vt=0;function Et(){return`mem-${++vt}`}function be(s,e){let n=e?.id??Et(),t=Date.now(),r={id:n,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},a=ee(s,{name:`mem:${n}:content`}),i=ee(r,{name:`mem:${n}:meta`,equals:()=>!1}),f={},c=J([i],()=>ie(i.get(),f),{name:`mem:${n}:score`});return{id:n,content:a,meta:i,scoreStore:c,touch(){let o=Date.now();i.update(l=>({...l,accessedAt:o,accessCount:l.accessCount+1}))},tag(...o){i.update(l=>{let g=new Set(l.tags);for(let S of o)g.add(S);return{...l,tags:g,updatedAt:Date.now()}})},untag(...o){i.update(l=>{let g=new Set(l.tags);for(let S of o)g.delete(S);return{...l,tags:g,updatedAt:Date.now()}})},setImportance(o){i.update(l=>({...l,importance:Math.max(0,Math.min(1,o)),updatedAt:Date.now()}))},update(o){X(()=>{a.set(o),i.update(l=>({...l,updatedAt:Date.now()}))})},score(o){return ie(i.get(),o??f)},destroy(){G(a),G(i)}}}var Dt=0;function rt(s){let e=++Dt,n=s?.maxSize??1/0,t=s?.weights??{},r=s?.admissionPolicy,a=s?.forgetPolicy,i=new Map,f=Ue(),c=new Map,u=n<1/0?nt(d=>i.get(d).meta,d=>ie(d,t)):null,o=ee(0,{name:`collection-${e}:ver`}),l=J([o],()=>Array.from(i.values()),{name:`collection-${e}:nodes`}),g=J([o],()=>i.size,{name:`collection-${e}:size`}),S=!1;function F(){o.update(d=>d+1)}function K(d){let _=Array.from(d.meta.get().tags);f.update(d.id,_);let x=je(d.meta,L=>{let N=Array.from(L.tags);f.update(d.id,N)});c.set(d.id,()=>x.unsubscribe())}function te(d){let _=c.get(d);_&&(_(),c.delete(d)),f.remove(d)}function h(){if(!u||i.size<=n)return;let d=u.evict(i.size-n);for(let _ of d){let x=i.get(_);x&&(te(_),x.destroy(),i.delete(_))}}function m(){if(!a)return 0;let d=[];for(let _ of i.values())a(_)&&d.push(_.id);for(let _ of d){let x=i.get(_);x&&(te(_),u?.delete(_),x.destroy(),i.delete(_))}return d.length}return{add(d,_){if(S)throw new Error("Collection is destroyed");if(r){let L=Array.from(i.values()),N=r(d,L);switch(N.action){case"reject":return;case"update":{let $=i.get(N.targetId);if(!$)throw new Error(`Admission update target "${N.targetId}" not found`);return $.update(N.content),$}case"merge":{let $=i.get(N.targetId);if(!$)throw new Error(`Admission merge target "${N.targetId}" not found`);let p=N.reducer($.content.get(),d);return $.update(p),$}default:break}}a&&m();let x=be(d,_);return i.set(x.id,x),K(x),u?.insert(x.id),h(),F(),x},remove(d){let _=typeof d=="string"?d:d.id,x=i.get(_);return x?(te(_),u?.delete(_),x.destroy(),i.delete(_),F(),!0):!1},get(d){return i.get(d)},has(d){return i.has(d)},nodes:l,size:g,tagIndex:f,query(d){let _=[];for(let x of i.values())d(x)&&_.push(x);return _},byTag(d){let _=f.get(d),x=[];for(let L of _){let N=i.get(L);N&&x.push(N)}return x},topK(d,_){let x=_??t,L=Date.now(),N=Array.from(i.values()).map($=>({node:$,score:ie($.meta.get(),x,L)}));return N.sort(($,p)=>p.score-$.score),N.slice(0,d).map($=>$.node)},summarize(d,_,x){if(S)throw new Error("Collection is destroyed");let L=Array.from(new Set(d)),N=[];for(let T of L){let b=i.get(T);b&&N.push(b)}if(N.length===0)throw new Error("No valid nodes to summarize");let $=_(N),p;return X(()=>{for(let T of N)te(T.id),u?.delete(T.id),T.destroy(),i.delete(T.id);a&&m(),p=be($,x),i.set(p.id,p),K(p),u?.insert(p.id),F()}),p},gc(){if(S)throw new Error("Collection is destroyed");let d=m();return d>0&&F(),d},destroy(){if(!S){S=!0,u?.clear();for(let d of c.values())d();c.clear(),f.destroy(),X(()=>{for(let d of i.values())d.destroy();i.clear()}),G(o)}}}}function xt(s,e){let n=0,t=0,r=0;for(let i=0;i<s.length;i++)n+=s[i]*e[i],t+=s[i]*s[i],r+=e[i]*e[i];let a=Math.sqrt(t)*Math.sqrt(r);return a===0?1:1-n/a}function wt(s,e){let n=0;for(let t=0;t<s.length;t++){let r=s[t]-e[t];n+=r*r}return Math.sqrt(n)}function kt(s,e){let n=0;for(let t=0;t<s.length;t++)n+=s[t]*e[t];return-n}var It={cosine:xt,euclidean:wt,dotProduct:kt};function Je(s,e){s.push(e);let n=s.length-1;for(;n>0;){let t=n-1>>1;if(s[t].dist<=s[n].dist)break;let r=s[t];s[t]=s[n],s[n]=r,n=t}}function Mt(s){let e=s[0],n=s.pop();if(s.length>0){s[0]=n;let t=0;for(;;){let r=t,a=2*t+1,i=2*t+2;if(a<s.length&&s[a].dist<s[r].dist&&(r=a),i<s.length&&s[i].dist<s[r].dist&&(r=i),r===t)break;let f=s[r];s[r]=s[t],s[t]=f,t=r}}return e}function it(s,e){if(s.length!==e)throw new Error(`Expected ${e} dimensions, got ${s.length}`);return new Float32Array(s)}function At(s){for(let e=0;e<s.length;e++)if(!Number.isFinite(s[e]))throw new Error("Vector contains non-finite values")}function ot(s){let e=s.dimensions;if(!e||e<=0)throw new Error("dimensions must be a positive integer");let n=s.m??16,t=n*2,r=s.efConstruction??200,a=s.efSearch??50,i=It[s.distance??"cosine"];if(!i)throw new Error(`Unknown distance metric: ${s.distance}`);let f=1/Math.log(n),c=[],u=new Map,o=-1,l=-1,g=0,S=ee(0);function F(){let p=Math.random();return p===0&&(p=Number.EPSILON),Math.floor(-Math.log(p)*f)}function K(p,T,b,y){let A=new Set;A.add(T);let V=i(p,c[T].vector),I=[];Je(I,{idx:T,dist:V});let k=[{idx:T,dist:V}];for(;I.length>0;){let E=Mt(I);if(k.length>=b){let j=-1/0;for(let q=0;q<k.length;q++)k[q].dist>j&&(j=k[q].dist);if(E.dist>j)break}let W=c[E.idx].neighbors[y];if(W)for(let j of W){if(A.has(j))continue;A.add(j);let q=c[j];if(q.deleted)continue;let oe=i(p,q.vector);if(k.length<b)Je(I,{idx:j,dist:oe}),k.push({idx:j,dist:oe});else{let Ze=0,Ke=k[0].dist;for(let _e=1;_e<k.length;_e++)k[_e].dist>Ke&&(Ke=k[_e].dist,Ze=_e);oe<Ke&&(Je(I,{idx:j,dist:oe}),k[Ze]={idx:j,dist:oe})}}}return k}function te(p,T,b){let y=T,A=i(p,c[y].vector),V=!0;for(;V;){V=!1;let I=c[y].neighbors[b];if(!I)break;for(let k of I){let E=c[k];if(E.deleted)continue;let R=i(p,E.vector);R<A&&(y=k,A=R,V=!0)}}return y}function h(p,T){p.sort((y,A)=>y.dist-A.dist);let b=[];for(let y=0;y<Math.min(p.length,T);y++)b.push(p[y].idx);return b}function m(p,T,b){let y=b===0?t:n;c[p].neighbors[b].add(T),c[T].neighbors[b].add(p),c[p].neighbors[b].size>y&&w(p,b,y),c[T].neighbors[b].size>y&&w(T,b,y)}function w(p,T,b){let y=c[p],A=[];for(let I of y.neighbors[T])c[I].deleted||A.push({idx:I,dist:i(y.vector,c[I].vector)});let V=h(A,b);y.neighbors[T]=new Set(V)}function d(p,T){let b=it(T,e);if(At(b),u.has(p)){let E=u.get(p),R=c[E];if(R.deleted){if(R.deleted=!1,R.vector=b,g++,o===-1)o=E,l=R.layer;else{for(let W=R.layer;W>=0;W--)R.neighbors[W]=new Set,_(E,W);R.layer>l&&(o=E,l=R.layer)}S.set(g)}else{R.vector=b;for(let W=R.layer;W>=0;W--){for(let j of R.neighbors[W])c[j].neighbors[W].delete(E);R.neighbors[W]=new Set,_(E,W)}}return}let y=F(),A=c.length,V=[];for(let E=0;E<=y;E++)V.push(new Set);let I={id:p,vector:b,layer:y,neighbors:V,deleted:!1};if(c.push(I),u.set(p,A),g++,o===-1){o=A,l=y,S.set(g);return}let k=o;for(let E=l;E>y;E--)k=te(b,k,E);for(let E=Math.min(y,l);E>=0;E--){let R=K(b,k,r,E),j=h(R,E===0?t:n);for(let q of j)q!==A&&m(A,q,E);R.length>0&&(R.sort((q,oe)=>q.dist-oe.dist),k=R[0].idx)}y>l&&(o=A,l=y),S.set(g)}function _(p,T){let b=o;if(b===p){let I=-1;for(let k=0;k<c.length;k++)if(k!==p&&!c[k].deleted&&c[k].layer>=T){I=k;break}if(I===-1)return;b=I}for(let I=Math.min(l,c[b].layer);I>T;I--)b=te(c[p].vector,b,I);let y=K(c[p].vector,b,r,T),V=h(y,T===0?t:n);for(let I of V)I!==p&&m(p,I,T)}function x(p){let T=u.get(p);if(T===void 0)return!1;let b=c[T];if(b.deleted)return!1;if(b.deleted=!0,g--,S.set(g),T===o){let y=-1;for(let A=0;A<c.length;A++)c[A].deleted||(y===-1||c[A].layer>c[y].layer)&&(y=A);o=y,l=y===-1?-1:c[y].layer}return!0}function L(p,T=10){if(g===0)return[];let b=it(p,e),y=Math.min(T,g),A=Math.max(a,y),V=o;for(let E=l;E>0;E--)V=te(b,V,E);let I=K(b,V,A,0);I.sort((E,R)=>E.dist-R.dist);let k=[];for(let E=0;E<I.length&&k.length<y;E++){let R=c[I[E].idx];R.deleted||k.push({id:R.id,distance:I[E].dist})}return k}function N(p){let T=u.get(p);return T===void 0?!1:!c[T].deleted}function $(){c.length=0,u.clear(),o=-1,l=-1,g=0,S.set(0),G(S)}return{add:d,remove:x,search:L,has:N,size:S,destroy:$}}0&&(module.exports={collection,computeScore,decay,memoryNode,vectorIndex});
|
package/dist/memory/index.d.cts
CHANGED
|
@@ -1,10 +1,77 @@
|
|
|
1
|
-
import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, M as MemoryNodeOptions, a as MemoryNode } from '../types-
|
|
1
|
+
import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, M as MemoryNodeOptions, a as MemoryNode, V as VectorIndexOptions, e as VectorIndex } from '../types-FP6jV-p5.cjs';
|
|
2
|
+
export { A as AdmissionDecision, f as AdmissionPolicyFn, g as DistanceMetric, F as ForgetPolicyFn, h as VectorSearchResult } from '../types-FP6jV-p5.cjs';
|
|
2
3
|
import '../types-BohB8jJr.cjs';
|
|
3
4
|
import '../protocol-fwiQ1TAS.cjs';
|
|
4
5
|
import '../types-BRnNQbJn.cjs';
|
|
5
6
|
import '../eviction-DGPP1vHP.cjs';
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Creates a reactive collection of `MemoryNode<T>` values with tag indexing,
|
|
10
|
+
* decay-scored eviction, and memory lifecycle management.
|
|
11
|
+
*
|
|
12
|
+
* @param opts - Optional configuration.
|
|
13
|
+
*
|
|
14
|
+
* @returns `Collection<T>` with the following API:
|
|
15
|
+
*
|
|
16
|
+
* @returnsTable add(content, opts?) | (content: T, opts?: MemoryNodeOptions) => MemoryNode<T> \| undefined | Add a node. Returns undefined if admissionPolicy rejects.
|
|
17
|
+
* remove(nodeOrId) | (nodeOrId: MemoryNode<T> \| string) => boolean | Remove a node by reference or ID.
|
|
18
|
+
* get(id) | (id: string) => MemoryNode<T> \| undefined | Get a node by ID.
|
|
19
|
+
* has(id) | (id: string) => boolean | Check if a node exists.
|
|
20
|
+
* nodes | Store<MemoryNode<T>[]> | Reactive store of all nodes (updates on add/remove/summarize).
|
|
21
|
+
* size | Store<number> | Reactive node count.
|
|
22
|
+
* query(filter) | (filter: (n: MemoryNode<T>) => boolean) => MemoryNode<T>[] | Snapshot filter.
|
|
23
|
+
* byTag(tag) | (tag: string) => MemoryNode<T>[] | O(1) tag lookup via reactiveIndex.
|
|
24
|
+
* topK(k, weights?) | (k: number, weights?: ScoreWeights) => MemoryNode<T>[] | Top-k by decay score.
|
|
25
|
+
* summarize(ids, reducer, opts?) | (...) => MemoryNode<T> | Consolidate nodes into one.
|
|
26
|
+
* gc() | () => number | Run forgetPolicy on demand; returns count removed.
|
|
27
|
+
* tagIndex | ReactiveIndex | Reactive tag-to-nodeId index.
|
|
28
|
+
* destroy() | () => void | Tear down all nodes and internal stores.
|
|
29
|
+
*
|
|
30
|
+
* @optionsType CollectionOptions
|
|
31
|
+
* @option maxSize | number | Infinity | Maximum nodes. Lowest-scored evicted on overflow.
|
|
32
|
+
* @option weights | ScoreWeights | {} | Default weights for topK and eviction scoring.
|
|
33
|
+
* @option admissionPolicy | AdmissionPolicyFn<T> | undefined | Gate every add(): admit, reject, update an existing node, or merge into one.
|
|
34
|
+
* @option forgetPolicy | ForgetPolicyFn<T> | undefined | Predicate run before each add() and during gc(). Return true to remove a node.
|
|
35
|
+
*
|
|
36
|
+
* @remarks **Admission policy:** Called synchronously on every `add()` with a snapshot of current nodes. Returns `{ action: "admit" | "reject" | "update" | "merge" }`. Use for dedup, conflict resolution, and content merging.
|
|
37
|
+
* @remarks **Forget policy:** Runs on existing nodes before each new admission and on explicit `gc()` calls. The newly-admitted node is never evaluated by the policy in the same call.
|
|
38
|
+
* @remarks **Summarize:** Removes source nodes and inserts one consolidated node in a single `batch()` — subscribers see one atomic update. Run forgetPolicy on survivors before inserting the new node.
|
|
39
|
+
* @remarks **Eviction vs forget:** `maxSize` eviction uses decay scoring (score-based heap). `forgetPolicy` is content/quality-based. Both can coexist — forget runs first, then eviction trims any remaining overflow.
|
|
40
|
+
* @remarks **Reactivity:** `nodes` and `size` are derived from an internal version counter that bumps on structural changes (add/remove/summarize/gc). Node content changes are reactive through each node's own stores, not through the collection stores.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* import { collection } from 'callbag-recharge/memory';
|
|
45
|
+
*
|
|
46
|
+
* const mem = collection<string>({ maxSize: 100 });
|
|
47
|
+
*
|
|
48
|
+
* const n = mem.add("The sky is blue", { importance: 0.8, tags: ["fact"] });
|
|
49
|
+
* n!.touch(); // update accessedAt + accessCount
|
|
50
|
+
* mem.topK(5); // top 5 by decay score
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* @example Dedup with admissionPolicy
|
|
54
|
+
* ```ts
|
|
55
|
+
* const mem = collection<string>({
|
|
56
|
+
* admissionPolicy: (incoming, nodes) => {
|
|
57
|
+
* const dup = nodes.find(n => n.content.get() === incoming);
|
|
58
|
+
* if (dup) return { action: "update", targetId: dup.id, content: incoming };
|
|
59
|
+
* return { action: "admit" };
|
|
60
|
+
* },
|
|
61
|
+
* });
|
|
62
|
+
* ```
|
|
63
|
+
*
|
|
64
|
+
* @example Auto-prune stale nodes with forgetPolicy
|
|
65
|
+
* ```ts
|
|
66
|
+
* const mem = collection<string>({
|
|
67
|
+
* forgetPolicy: (node) => node.meta.get().importance < 0.1,
|
|
68
|
+
* });
|
|
69
|
+
* // Stale nodes pruned before each add(); call mem.gc() for on-demand cleanup.
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @seeAlso [memoryNode](./node) — individual memory node, [decay](./decay) — scoring functions, [vectorIndex](./vectorIndex) — HNSW semantic search
|
|
73
|
+
*/
|
|
74
|
+
declare function collection<T>(opts?: CollectionOptions<T>): Collection<T>;
|
|
8
75
|
|
|
9
76
|
/**
|
|
10
77
|
* Create a decay scoring function with fixed weights.
|
|
@@ -19,4 +86,7 @@ declare function computeScore(meta: MemoryMeta, weights?: ScoreWeights, now?: nu
|
|
|
19
86
|
|
|
20
87
|
declare function memoryNode<T>(initialContent: T, opts?: MemoryNodeOptions): MemoryNode<T>;
|
|
21
88
|
|
|
22
|
-
|
|
89
|
+
/** Create an in-process HNSW vector index. */
|
|
90
|
+
declare function vectorIndex(opts: VectorIndexOptions): VectorIndex;
|
|
91
|
+
|
|
92
|
+
export { Collection, CollectionOptions, DecayFn, DecayOptions, MemoryMeta, MemoryNode, MemoryNodeOptions, ScoreWeights, VectorIndex, VectorIndexOptions, collection, computeScore, decay, memoryNode, vectorIndex };
|
package/dist/memory/index.d.ts
CHANGED
|
@@ -1,10 +1,77 @@
|
|
|
1
|
-
import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, M as MemoryNodeOptions, a as MemoryNode } from '../types-
|
|
1
|
+
import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, M as MemoryNodeOptions, a as MemoryNode, V as VectorIndexOptions, e as VectorIndex } from '../types-9JbU1qd1.js';
|
|
2
|
+
export { A as AdmissionDecision, f as AdmissionPolicyFn, g as DistanceMetric, F as ForgetPolicyFn, h as VectorSearchResult } from '../types-9JbU1qd1.js';
|
|
2
3
|
import '../types-CB1htCM8.js';
|
|
3
4
|
import '../protocol-fwiQ1TAS.js';
|
|
4
5
|
import '../types-n54oEEx_.js';
|
|
5
6
|
import '../eviction-DGPP1vHP.js';
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Creates a reactive collection of `MemoryNode<T>` values with tag indexing,
|
|
10
|
+
* decay-scored eviction, and memory lifecycle management.
|
|
11
|
+
*
|
|
12
|
+
* @param opts - Optional configuration.
|
|
13
|
+
*
|
|
14
|
+
* @returns `Collection<T>` with the following API:
|
|
15
|
+
*
|
|
16
|
+
* @returnsTable add(content, opts?) | (content: T, opts?: MemoryNodeOptions) => MemoryNode<T> \| undefined | Add a node. Returns undefined if admissionPolicy rejects.
|
|
17
|
+
* remove(nodeOrId) | (nodeOrId: MemoryNode<T> \| string) => boolean | Remove a node by reference or ID.
|
|
18
|
+
* get(id) | (id: string) => MemoryNode<T> \| undefined | Get a node by ID.
|
|
19
|
+
* has(id) | (id: string) => boolean | Check if a node exists.
|
|
20
|
+
* nodes | Store<MemoryNode<T>[]> | Reactive store of all nodes (updates on add/remove/summarize).
|
|
21
|
+
* size | Store<number> | Reactive node count.
|
|
22
|
+
* query(filter) | (filter: (n: MemoryNode<T>) => boolean) => MemoryNode<T>[] | Snapshot filter.
|
|
23
|
+
* byTag(tag) | (tag: string) => MemoryNode<T>[] | O(1) tag lookup via reactiveIndex.
|
|
24
|
+
* topK(k, weights?) | (k: number, weights?: ScoreWeights) => MemoryNode<T>[] | Top-k by decay score.
|
|
25
|
+
* summarize(ids, reducer, opts?) | (...) => MemoryNode<T> | Consolidate nodes into one.
|
|
26
|
+
* gc() | () => number | Run forgetPolicy on demand; returns count removed.
|
|
27
|
+
* tagIndex | ReactiveIndex | Reactive tag-to-nodeId index.
|
|
28
|
+
* destroy() | () => void | Tear down all nodes and internal stores.
|
|
29
|
+
*
|
|
30
|
+
* @optionsType CollectionOptions
|
|
31
|
+
* @option maxSize | number | Infinity | Maximum nodes. Lowest-scored evicted on overflow.
|
|
32
|
+
* @option weights | ScoreWeights | {} | Default weights for topK and eviction scoring.
|
|
33
|
+
* @option admissionPolicy | AdmissionPolicyFn<T> | undefined | Gate every add(): admit, reject, update an existing node, or merge into one.
|
|
34
|
+
* @option forgetPolicy | ForgetPolicyFn<T> | undefined | Predicate run before each add() and during gc(). Return true to remove a node.
|
|
35
|
+
*
|
|
36
|
+
* @remarks **Admission policy:** Called synchronously on every `add()` with a snapshot of current nodes. Returns `{ action: "admit" | "reject" | "update" | "merge" }`. Use for dedup, conflict resolution, and content merging.
|
|
37
|
+
* @remarks **Forget policy:** Runs on existing nodes before each new admission and on explicit `gc()` calls. The newly-admitted node is never evaluated by the policy in the same call.
|
|
38
|
+
* @remarks **Summarize:** Removes source nodes and inserts one consolidated node in a single `batch()` — subscribers see one atomic update. Run forgetPolicy on survivors before inserting the new node.
|
|
39
|
+
* @remarks **Eviction vs forget:** `maxSize` eviction uses decay scoring (score-based heap). `forgetPolicy` is content/quality-based. Both can coexist — forget runs first, then eviction trims any remaining overflow.
|
|
40
|
+
* @remarks **Reactivity:** `nodes` and `size` are derived from an internal version counter that bumps on structural changes (add/remove/summarize/gc). Node content changes are reactive through each node's own stores, not through the collection stores.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* import { collection } from 'callbag-recharge/memory';
|
|
45
|
+
*
|
|
46
|
+
* const mem = collection<string>({ maxSize: 100 });
|
|
47
|
+
*
|
|
48
|
+
* const n = mem.add("The sky is blue", { importance: 0.8, tags: ["fact"] });
|
|
49
|
+
* n!.touch(); // update accessedAt + accessCount
|
|
50
|
+
* mem.topK(5); // top 5 by decay score
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* @example Dedup with admissionPolicy
|
|
54
|
+
* ```ts
|
|
55
|
+
* const mem = collection<string>({
|
|
56
|
+
* admissionPolicy: (incoming, nodes) => {
|
|
57
|
+
* const dup = nodes.find(n => n.content.get() === incoming);
|
|
58
|
+
* if (dup) return { action: "update", targetId: dup.id, content: incoming };
|
|
59
|
+
* return { action: "admit" };
|
|
60
|
+
* },
|
|
61
|
+
* });
|
|
62
|
+
* ```
|
|
63
|
+
*
|
|
64
|
+
* @example Auto-prune stale nodes with forgetPolicy
|
|
65
|
+
* ```ts
|
|
66
|
+
* const mem = collection<string>({
|
|
67
|
+
* forgetPolicy: (node) => node.meta.get().importance < 0.1,
|
|
68
|
+
* });
|
|
69
|
+
* // Stale nodes pruned before each add(); call mem.gc() for on-demand cleanup.
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @seeAlso [memoryNode](./node) — individual memory node, [decay](./decay) — scoring functions, [vectorIndex](./vectorIndex) — HNSW semantic search
|
|
73
|
+
*/
|
|
74
|
+
declare function collection<T>(opts?: CollectionOptions<T>): Collection<T>;
|
|
8
75
|
|
|
9
76
|
/**
|
|
10
77
|
* Create a decay scoring function with fixed weights.
|
|
@@ -19,4 +86,7 @@ declare function computeScore(meta: MemoryMeta, weights?: ScoreWeights, now?: nu
|
|
|
19
86
|
|
|
20
87
|
declare function memoryNode<T>(initialContent: T, opts?: MemoryNodeOptions): MemoryNode<T>;
|
|
21
88
|
|
|
22
|
-
|
|
89
|
+
/** Create an in-process HNSW vector index. */
|
|
90
|
+
declare function vectorIndex(opts: VectorIndexOptions): VectorIndex;
|
|
91
|
+
|
|
92
|
+
export { Collection, CollectionOptions, DecayFn, DecayOptions, MemoryMeta, MemoryNode, MemoryNodeOptions, ScoreWeights, VectorIndex, VectorIndexOptions, collection, computeScore, decay, memoryNode, vectorIndex };
|
package/dist/memory/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as W,b as X,c as j,d as J}from"../chunk-DHPPL5V6.js";import"../chunk-JCENQEPP.js";import"../chunk-ZJCF5NYF.js";import"../chunk-PV347CGV.js";import"../chunk-HK7DRUNM.js";import"../chunk-GMLWTZFM.js";import{a as $}from"../chunk-EAK2HKAD.js";import"../chunk-2F6QWERG.js";import"../chunk-2L6223KN.js";import{B as z}from"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";function Q(e,u){let m=0,l=0,h=0;for(let g=0;g<e.length;g++)m+=e[g]*u[g],l+=e[g]*e[g],h+=u[g]*u[g];let M=Math.sqrt(l)*Math.sqrt(h);return M===0?1:1-m/M}function Y(e,u){let m=0;for(let l=0;l<e.length;l++){let h=e[l]-u[l];m+=h*h}return Math.sqrt(m)}function Z(e,u){let m=0;for(let l=0;l<e.length;l++)m+=e[l]*u[l];return-m}var ee={cosine:Q,euclidean:Y,dotProduct:Z};function L(e,u){e.push(u);let m=e.length-1;for(;m>0;){let l=m-1>>1;if(e[l].dist<=e[m].dist)break;let h=e[l];e[l]=e[m],e[m]=h,m=l}}function te(e){let u=e[0],m=e.pop();if(e.length>0){e[0]=m;let l=0;for(;;){let h=l,M=2*l+1,g=2*l+2;if(M<e.length&&e[M].dist<e[h].dist&&(h=M),g<e.length&&e[g].dist<e[h].dist&&(h=g),h===l)break;let D=e[h];e[h]=e[l],e[l]=D,l=h}}return u}function q(e,u){if(e.length!==u)throw new Error(`Expected ${u} dimensions, got ${e.length}`);return new Float32Array(e)}function ne(e){for(let u=0;u<e.length;u++)if(!Number.isFinite(e[u]))throw new Error("Vector contains non-finite values")}function oe(e){let u=e.dimensions;if(!u||u<=0)throw new Error("dimensions must be a positive integer");let m=e.m??16,l=m*2,h=e.efConstruction??200,M=e.efSearch??50,g=ee[e.distance??"cosine"];if(!g)throw new Error(`Unknown distance metric: ${e.distance}`);let D=1/Math.log(m),s=[],E=new Map,p=-1,w=-1,A=0,v=$(0);function T(){let n=Math.random();return n===0&&(n=Number.EPSILON),Math.floor(-Math.log(n)*D)}function H(n,i,o,t){let a=new Set;a.add(i);let b=g(n,s[i].vector),d=[];L(d,{idx:i,dist:b});let c=[{idx:i,dist:b}];for(;d.length>0;){let r=te(d);if(c.length>=o){let x=-1/0;for(let F=0;F<c.length;F++)c[F].dist>x&&(x=c[F].dist);if(r.dist>x)break}let y=s[r.idx].neighbors[t];if(y)for(let x of y){if(a.has(x))continue;a.add(x);let F=s[x];if(F.deleted)continue;let S=g(n,F.vector);if(c.length<o)L(d,{idx:x,dist:S}),c.push({idx:x,dist:S});else{let R=0,V=c[0].dist;for(let N=1;N<c.length;N++)c[N].dist>V&&(V=c[N].dist,R=N);S<V&&(L(d,{idx:x,dist:S}),c[R]={idx:x,dist:S})}}}return c}function C(n,i,o){let t=i,a=g(n,s[t].vector),b=!0;for(;b;){b=!1;let d=s[t].neighbors[o];if(!d)break;for(let c of d){let r=s[c];if(r.deleted)continue;let f=g(n,r.vector);f<a&&(t=c,a=f,b=!0)}}return t}function I(n,i){n.sort((t,a)=>t.dist-a.dist);let o=[];for(let t=0;t<Math.min(n.length,i);t++)o.push(n[t].idx);return o}function P(n,i,o){let t=o===0?l:m;s[n].neighbors[o].add(i),s[i].neighbors[o].add(n),s[n].neighbors[o].size>t&&k(n,o,t),s[i].neighbors[o].size>t&&k(i,o,t)}function k(n,i,o){let t=s[n],a=[];for(let d of t.neighbors[i])s[d].deleted||a.push({idx:d,dist:g(t.vector,s[d].vector)});let b=I(a,o);t.neighbors[i]=new Set(b)}function _(n,i){let o=q(i,u);if(ne(o),E.has(n)){let r=E.get(n),f=s[r];if(f.deleted){if(f.deleted=!1,f.vector=o,A++,p===-1)p=r,w=f.layer;else{for(let y=f.layer;y>=0;y--)f.neighbors[y]=new Set,O(r,y);f.layer>w&&(p=r,w=f.layer)}v.set(A)}else{f.vector=o;for(let y=f.layer;y>=0;y--){for(let x of f.neighbors[y])s[x].neighbors[y].delete(r);f.neighbors[y]=new Set,O(r,y)}}return}let t=T(),a=s.length,b=[];for(let r=0;r<=t;r++)b.push(new Set);let d={id:n,vector:o,layer:t,neighbors:b,deleted:!1};if(s.push(d),E.set(n,a),A++,p===-1){p=a,w=t,v.set(A);return}let c=p;for(let r=w;r>t;r--)c=C(o,c,r);for(let r=Math.min(t,w);r>=0;r--){let f=H(o,c,h,r),x=I(f,r===0?l:m);for(let F of x)F!==a&&P(a,F,r);f.length>0&&(f.sort((F,S)=>F.dist-S.dist),c=f[0].idx)}t>w&&(p=a,w=t),v.set(A)}function O(n,i){let o=p;if(o===n){let d=-1;for(let c=0;c<s.length;c++)if(c!==n&&!s[c].deleted&&s[c].layer>=i){d=c;break}if(d===-1)return;o=d}for(let d=Math.min(w,s[o].layer);d>i;d--)o=C(s[n].vector,o,d);let t=H(s[n].vector,o,h,i),b=I(t,i===0?l:m);for(let d of b)d!==n&&P(n,d,i)}function B(n){let i=E.get(n);if(i===void 0)return!1;let o=s[i];if(o.deleted)return!1;if(o.deleted=!0,A--,v.set(A),i===p){let t=-1;for(let a=0;a<s.length;a++)s[a].deleted||(t===-1||s[a].layer>s[t].layer)&&(t=a);p=t,w=t===-1?-1:s[t].layer}return!0}function G(n,i=10){if(A===0)return[];let o=q(n,u),t=Math.min(i,A),a=Math.max(M,t),b=p;for(let r=w;r>0;r--)b=C(o,b,r);let d=H(o,b,a,0);d.sort((r,f)=>r.dist-f.dist);let c=[];for(let r=0;r<d.length&&c.length<t;r++){let f=s[d[r].idx];f.deleted||c.push({id:f.id,distance:d[r].dist})}return c}function K(n){let i=E.get(n);return i===void 0?!1:!s[i].deleted}function U(){s.length=0,E.clear(),p=-1,w=-1,A=0,v.set(0),z(v)}return{add:_,remove:B,search:G,has:K,size:v,destroy:U}}export{J as collection,X as computeScore,W as decay,j as memoryNode,oe as vectorIndex};
|