wenay-common2 1.0.62 → 1.0.64

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.
Files changed (37) hide show
  1. package/CLAUDE.md +63 -0
  2. package/README.md +6 -322
  3. package/doc/NAMING_RENAMES.md +36 -0
  4. package/doc/RECOMMENDATIONS.md +56 -0
  5. package/doc/REPLAY-PLAN.md +81 -0
  6. package/doc/changes/1.0.63.md +8 -0
  7. package/doc/changes/1.0.64.md +10 -0
  8. package/doc/changes/README.md +8 -0
  9. package/doc/wenay-common2-rare.md +522 -0
  10. package/doc/wenay-common2.md +334 -0
  11. package/lib/Common/Observe/index.d.ts +2 -1
  12. package/lib/Common/Observe/index.js +2 -1
  13. package/lib/Common/Observe/reactive.d.ts +21 -0
  14. package/lib/Common/Observe/reactive.js +374 -0
  15. package/lib/Common/Observe/reactive2.d.ts +1 -21
  16. package/lib/Common/Observe/reactive2.js +15 -372
  17. package/lib/Common/Observe/store-manager.d.ts +123 -0
  18. package/lib/Common/Observe/store-manager.js +227 -0
  19. package/lib/Common/Observe/store-offline.d.ts +10 -10
  20. package/lib/Common/Observe/store-offline.js +2 -2
  21. package/lib/Common/Observe/store.d.ts +1 -1
  22. package/lib/Common/Observe/store.js +13 -13
  23. package/lib/Common/async/promiseProgress.d.ts +2 -2
  24. package/lib/Common/events/Listen.d.ts +129 -1
  25. package/lib/Common/events/Listen.js +243 -15
  26. package/lib/Common/events/Listen3.d.ts +1 -129
  27. package/lib/Common/events/Listen3.js +15 -243
  28. package/lib/Common/events/SocketBuffer.d.ts +4 -4
  29. package/lib/Common/events/SocketServerHook.d.ts +2 -2
  30. package/lib/Common/events/replay-conflate.d.ts +2 -2
  31. package/lib/Common/events/replay-conflate.js +2 -2
  32. package/lib/Common/events/replay-history.d.ts +1 -1
  33. package/lib/Common/events/replay-listen.d.ts +9 -9
  34. package/lib/Common/events/replay-listen.js +4 -4
  35. package/lib/Common/events/replay-wire.d.ts +1 -1
  36. package/package.json +9 -2
  37. package/rpc.md +293 -0
@@ -0,0 +1,334 @@
1
+ # wenay-common2 — BRIEF cheat sheet (notation)
2
+
3
+ > Root import: `import { ... } from "wenay-common2"`.
4
+ > Notation: `name(args: types) -> ret // note`. Types are shown where they decide a correct call (callback shape,
5
+ > overloads, return). Short names are **canonical**; removed old names are listed in `NAMING_RENAMES.md`.
6
+ > Full surface → **`wenay-common2-rare.md`**. Code style → `CLAUDE.md`. Full RPC guide → `rpc.md`.
7
+
8
+ ## ⭐ events — `listen` / `listenStore`
9
+ ```
10
+ import { listen, listenStore, mapListen } from "wenay-common2"
11
+
12
+ listen<T>(opts?) -> [emit, listen] // pure event list: no local value storage, no current replay
13
+ emit(...args: T) // dispatch event only
14
+ listen.on(cb: (...args: T) => void, {key?, cbClose?}) -> off
15
+ listen.once(cb, {key?}) -> off // one future event
16
+ listen.onClose(cb: () => void) -> off
17
+ listen.close() // clear listeners + fire close hooks + teardown producer
18
+ listen.count() -> number
19
+
20
+ listenStore<T>({current, ...opts}) -> [emit, listen]
21
+ // store wrapper: current() reads external store by reference; the listener does not keep its own value copy
22
+ listen.on(cb, {current: true}) -> off // current store value first, then future events
23
+ listen.on(cb) -> off // future events only
24
+ listen.once(cb, {current: true}) -> off // one value from current store, if present; otherwise waits future event
25
+ listen.once(cb) -> off // one future event
26
+ listen.on(cb, {current: () => argsOrUndefined}) -> off
27
+
28
+ opts: { fast? = true, event?(t: 'add'|'remove', count, api), closeOn? }
29
+ ```
30
+ ```
31
+ mapListen<TIn, TOut>(src, map: (...a: TIn) => TOut | null, opts?) -> [emit, listen] // map+filter (null skips); lazy subscribe
32
+ joinListens(listens | ports, keyExtractor?) -> { listen, add(port, key?), pending: number, clear(tid?) } // zip by key
33
+ ```
34
+ ## ⭐ sleep
35
+ ```
36
+ sleepAsync(ms = 0) -> Promise<void>
37
+ ```
38
+
39
+ ## ⏱️ async
40
+ ```
41
+ createThrottle() -> { throttle(ms: number, fn: () => void) -> void,
42
+ debounce(ms: number, fn: () => void) -> Promise<void> }
43
+ // fn is a ZERO-ARG thunk the scheduler runs itself; NOT a lodash-style wrapper that returns a callable
44
+ // ONE createThrottle() = ONE shared limiter (shared busy/pending) — use a SEPARATE instance per operation;
45
+ // throttle + debounce on the SAME instance contend (a busy throttle silently drops the debounce's trailing run)
46
+ createAsyncQueue(concurrency = 1) -> { add<R>(task: () => Promise<R>) -> Promise<R>, onIdle() -> Promise<void>, size: number } // p-queue
47
+ createReadyGate() -> { add(fn: () => void), ready() } // buffer fns until ready(), then run them in order
48
+ promiseProgress<T>(arr: (Promise<T> | (() => Promise<T>))[]) -> {
49
+ onOk(cb), onError(cb), all() -> Promise<any[]>, allSettled(), items(), stats() -> { ok: number, error: number, count: number } }
50
+ // factory entries start on .all()/.allSettled()/items() (once); .all() rejects like Promise.all — read aggregate progress via stats()
51
+ // alias: enhancedWaitRun->createThrottle · createTaskQueue->createReadyGate(.setReady->.ready) · createAsyncQueue.enqueue->add · .getQueueSize->size
52
+ ```
53
+
54
+ ## 🧰 core — clone / compare
55
+ ```
56
+ clone<T>(v: T) -> T // deep: cycles + Map/Set/Date, rebinds functions (alias: deepClone)
57
+ shallowClone<T>(v: T) -> T
58
+ isEqual(a, b) -> boolean // PLAIN object/array trees ONLY; on Map/Set/Date it returns a vacuous `true` — don't use it on them (alias: deepEqual)
59
+ shallowEqual(a, b) · arrayShallowEqual(a, b) -> boolean // strict-by-key vs loose-by-index — both kept on purpose
60
+ toImmutable<T>(o: T) -> T // deep-frozen clone + Mutable:false marker
61
+ JSON_clone<T>(o: T) -> T // JSON round-trip; DROPS Map/Set (-> {}) and turns Date -> string. NOT a rich clone — use clone() for those
62
+ ```
63
+
64
+ ## 🧰 core — binary search / maps / mutex / memo
65
+ ```
66
+ BSearch<T>(arr: ArrayLike<T>, value: T | comparer, match?: 'equal'|'lessOrEqual'|'greatOrEqual', sort?: SortMode) -> number
67
+ // comparer is (item: T) => number OR (a: T, b) => number; without it, T must have valueOf():number
68
+ BSearchNearest<T>(arr: ArrayLike<T>, value: number, getter?: (el: T) => number, maxDelta?: number) -> number
69
+ new MapExt<K,V>() / new WeakMapExt<K,V>(): .getOrSet(k, () => v) -> V // lazy insert (a plain value is also accepted)
70
+ new Mutex(): .runExclusive<T>(fn: () => T | Promise<T>) -> Promise<T> | .lock() -> Promise<release: () => void> // runExclusive: was dispatch
71
+ MemoFunc<A extends any[], R>(opts?: { timeDelta?: number, maxLimits?: number }) -> { func(...a: A) -> R, cleanAll(), memo } // TTL + LRU; per-call {timeDelta, reSave}
72
+ ```
73
+
74
+ ## 🔢 core — number (frequent)
75
+ ```
76
+ round(value: number, digits = 0) -> number // round to N decimals (alias: NormalizeDouble)
77
+ roundSig(value: number, { digitsR?: number /*total significant digits*/, digitsPoint? = 4, type?: 'max'|'min' }) -> number
78
+ // round to N significant digits — roundSig(1234.5678, {digitsR: 3}) -> 1230 (alias: NormalizeDoubleAnd)
79
+ gcd(a: number, b: number, digits = 8) -> number | gcd(values: Iterable<number>, digits = 8) -> number
80
+ // floats ok; in the ITERABLE overload the 2nd arg is PRECISION digits, not an operand (alias: MaxCommonDivisor[OnArray])
81
+ formatAuto(value: number, maxDigits = 8) -> string // shortest decimal string (alias: DblToStrAuto)
82
+ decimals(value: number, maxDigits = 8, minDigits = 0) -> number // count of meaningful decimals (alias: GetDblPrecision)
83
+ ```
84
+
85
+ ## ⏰ time
86
+ ```
87
+ format(date: Date, pattern, { utc? = true }) -> string // (alias of 11 timeToStr_*/timeLocalToStr_*)
88
+ pattern: 'HH:mm:ss' | 'HH:mm:ss.SSS' | 'yyyy-MM-dd'
89
+ | 'yyyy-MM-dd HH:mm' | 'yyyy-MM-dd HH:mm:ss' | 'yyyy-MM-dd HH:mm:ss.SSS'
90
+ | 'yyyy-MM-dd HH:mm O' | 'yyyy-MM-dd HH:mm:ss O' // O = GMT offset (local)
91
+ { utc: false } -> local variants
92
+ formatDuration(ms: number, pattern?: 'H:mm:ss' | 'H:mm:ss.SSS') -> string // clock; hours unbounded
93
+ durationToStr(ms: number) -> string // humanized
94
+ minDate(a: Date | null, b: Date | null) / maxDate(a, b) -> Date | null // null-tolerant (alias: MinTime/MaxTime)
95
+ convertDatesToStrings(obj) // Date -> strings, recursively (logs)
96
+ const: H1_S D1_S W1_S · M1_MS H1_MS D1_MS W1_MS
97
+ ```
98
+
99
+ ## 🌐 rpc (brief) — transport is ALWAYS caller-supplied (`{emit,on}`); there is NO url / built-in socket
100
+ ```
101
+ // SERVER: `object` is the impl tree, `socket` is a {emit,on} transport adapter
102
+ createRpcServerAuto({ socket: {emit, on}, object, socketKey: string, auth?, limits?, maxPerListen?, throttle?, opt?, replay?, replayOpts? }) -> { api, ... }
103
+ // replay: false|'auto' (default)|'force' — facade members that are replay lines (replayListen) are exposed
104
+ // with BOTH surfaces under the SAME key: legacy plain-Listen path byte-for-byte + line/frameLine/since/keyframe/frame.
105
+ // Upgrading listen -> replayListen is a declaration-site-only change; the facade and clients don't move.
106
+ // replayOpts: {pending?, highWater?, lowWater?, pollMs?} — per-connection lag gate for 'frame'-policy subscribers
107
+ // (pending defaults to socket.io writeBuffer; gates close on disconnect automatically). Replay lines are never throttled.
108
+ createRpcServer(opts) // lower-level core (same { socket, object, socketKey })
109
+ noStrict(obj) // mark a dynamic subtree (no schema)
110
+ endCallback(fn) // mark an RPC stream-callback's end (alias: rpcEndCallback)
111
+
112
+ // CLIENT hub: takes TWO functions — a socket factory + a schema builder; it is NOT an {url} or an options bag
113
+ createRpcClientHub(
114
+ createSocket: (token: string | null) => socket, // YOU build the socket, e.g. socket.io io(url, {auth:{token}})
115
+ schemaBuilder: (rpc) => ({ key: rpc<Api>('socketKey') }), // declare each socketKey's typed API
116
+ hubOpts?: { opt? },
117
+ ) -> hub
118
+ hub: connect(token) -> Promise<clients> · reauth(token) · facade · promise · socket · onConnect/onDisconnect // connect: was setToken
119
+ // connect()'s promise resolves on the socket's 'connect' event; for in-proc/loopback (no 'connect') use hub.facade + await hub.promise
120
+ client (on clients[key], NOT on the hub): func (proxy) · strict (schema-safe) · close() · ready() · init() · subscriptions()
121
+ // pipe = batch a server chain in one packet · space = fire-and-forget
122
+
123
+ // minimal wiring (the part no signature can show):
124
+ const [tick, ticks] = listen<[number]>()
125
+ createRpcServerAuto({ socket, object: { math: { add: (a, b) => a + b, ticks } }, socketKey: 'math' })
126
+ const hub = createRpcClientHub((t) => io(url, { auth: { t } }), (rpc) => ({ math: rpc<Api>('math') }))
127
+ const c = await hub.connect(token) // c = facade of per-socketKey clients
128
+ await c.math.ready(); await c.math.func.add(2, 3)
129
+ const l = c.math.func as unknown as DeepSocketListen<Api> // typed Listen projection; wrap as webListen(c.math) in app code
130
+ const off = l.ticks.on(v => console.log(v)) // canonical stream subscribe; off is callable and awaitable
131
+ off() // unsubscribe; .callback/.removeCallback are legacy compat, don't teach them
132
+ l.ticks.once(v => console.log(v)) // one event, then auto-off
133
+
134
+ // replay upgrade — ONE WORD at the declaration site, everything below follows automatically:
135
+ // const [tick, ticks] = listen<[number]>() // before
136
+ const [tick, ticks] = replayListen<[number]>({history: 1024, current: 'last'}) // after — same facade, same key
137
+ // legacy subscribers unchanged (byte-for-byte). Replay consumers now also get:
138
+ const sub = replaySubscribe(l.ticks, v => {}, {since: saved, onSeq: s => saved = s}) // catch-up + live, no gaps/dups
139
+ const sub2 = replaySubscribe(c.math.func.ticks, v => {}) // replay members project on func/strict directly — no cast needed
140
+ await l.ticks.frame(mySeq) // pull at YOUR pace (50ms timer etc.) — server condenses via the line's frame lambda
141
+ // full guide + examples → rpc.md; frame model / lag policies → 🎞️ recipe below and rare docs
142
+ ```
143
+
144
+ ## 🔁 Observe — reactive state + store/mirror API
145
+ > `import { Observe } from "wenay-common2"` or `import * as Observe from "wenay-common2/observe"`.
146
+ > This is the documented v2 reactive/store surface.
147
+ ```
148
+ // coarse reactive object: subscribe to the fact that a subtree changed, then re-read current state
149
+ Observe.reactive<T extends object>(obj, opts?) -> T
150
+ Observe.onUpdate(node, cb: () => void) -> off
151
+ Observe.onUpdatePaths(node, cb: ({paths}) => void) -> off // optional dirty paths, relative to node
152
+ Observe.flushReactive(node) -> Promise<void>
153
+ Observe.toRaw(node) -> raw value behind the proxy // snapshots/serialization without touching lazy nodes
154
+ Observe.listenUpdate(node) -> Listen<void> // RPC bridge for coarse change notifications
155
+ Observe.listenUpdatePaths(node) -> Listen<{paths: PropertyKey[][]}>
156
+ opts: { drain?: "immediate"|"micro"|number|((flush)=>void), depth?, eager? }
157
+
158
+ // path-addressed store facade over reactive()
159
+ Observe.createStore<T extends object>(initial, opts?) -> Store<T>
160
+ store.state // reactive data object; write normally
161
+ store.node.path.to.leaf.get()/snapshot()/replace(v) // set(v) is a deprecated alias of replace(v)
162
+ store.node.path.to.leaf.on((value, ctx) => {}, {current?, drain?, key?}) -> off
163
+ store.node.path.to.leaf.once(cb, opts?) -> off
164
+ store.update(mask, opts?) -> selection // typed selected snapshot
165
+ selection.get() · selection.on((snap, ctx)=>{}, opts?) -> off · selection.onEach((value, ctx)=>{}, opts?) -> off
166
+ store.each(opts?) -> Listen<[key, value, ctx]> // changed TOP-LEVEL keys as a plain Listen — THE per-key feed
167
+ // one call per CHANGED key per drain window: value = current store.state[key] at flush time; undefined = key deleted;
168
+ // two writes to one key in a window = ONE call (last value); deeper dirt (state.a.b = ...) reports 'a' once
169
+ // root replace (store.replace / mirror keyframe) EXPANDS: one call per key of the new state + (key, undefined)
170
+ // per key the replace removed — cold start / reconnect are NOT special cases for per-key consumers
171
+ // plain Listen shape (on(cb) -> off · once · count); zero cost while it has no subscribers
172
+ // NOT update(true).onEach: onEach fires per SELECTED path, and mask true selects the root —
173
+ // ONE call per window with the whole dict (a dev warn points to each())
174
+ store.count() -> number
175
+
176
+ // network shape: backend exposes snapshots + changed Listen; frontend mirrors selected masks locally
177
+ Observe.exposeStore(store, opts?) -> { get(mask?), set(path,value), replace(path,value), changed, changedPaths, patches?, changedData? }
178
+ Observe.createStoreMirror(remote, initial, opts?) -> store & { sync(mask, opts?) -> Promise<off>; syncPatches(mask, opts?) -> Promise<off>; syncChangedData(mask, opts?) -> Promise<off> }
179
+ // changedPaths is optional optimization: mirror pulls mask ∩ dirty paths; fallback is changed -> get(mask).
180
+ // Optional push-data mode: exposeStore(store,{push:true}) + syncPatches/syncChangedData; details in rare docs.
181
+
182
+ // Sequenced sync (replay line): seq-numbered patch stream — keyframe catch-up, reconnect by seq (tail, not snapshot)
183
+ Observe.exposeStoreReplay(store, {history? = 1024}) -> { api /* spread into the RPC server object */, replay, close }
184
+ // the patch line declares its condensing `frame` itself (last patch per exact path) — reconnect tails and
185
+ // lag recovery arrive as a mini-frame (changed paths only), zero config
186
+ Observe.syncStoreReplay(mirror, remote /*{line, since, keyframe, frame?} of api.replay*/, {since?, onSeq?}) -> off
187
+ // off.ready (catch-up done) · off.seq() (save for reconnect: syncStoreReplay(..., {since: prev.seq()}))
188
+ // lagging/late client NEVER gets a backlog: evicted seq -> ONE fresh keyframe + live
189
+ // freshness is an option, not consumer boilerplate: {staleMs, onStale} flags a silent line / stale keyframe (edge-triggered both ways; 🎞️ in rare docs)
190
+ Observe.syncStoreReplayEach<T>(remote, (key, value, ctx) => {}, opts?) -> off & {store, ready, seq(), isStale(), lastTs()}
191
+ // one-call remote fold: mirror store + syncStoreReplay + store.each() — the callback fires per CHANGED
192
+ // top-level key; first delivery = keyframe EXPANDED per key; (key, undefined) = key deleted
193
+ // opts = all replaySubscribe opts (since/onSeq/policy/staleMs/onStale/onError...) + {drain?, initial?}
194
+ // off() tears down BOTH the store sub and the wire sub; direct reads via off.store.state.KEY
195
+ // reconnect: syncStoreReplayEach(remote, cb, {since: prev.seq(), initial: prev.store.snapshot()})
196
+ // — the tail lands ON TOP of the previous state (a fresh empty mirror would not converge)
197
+ // Offline persisted mirror (snapshot mode): local cache first, then replay catch-up by seq
198
+ Observe.createOfflineStore({key, remote?, initial, storage, version?, debounceMs?, syncOpts?}) -> Promise<store & {ready, flush(), close(), status(), statusListen, reconnect(remote)}>
199
+ Observe.persistStore(store, {key, storage, seq?, debounceMs?}) -> {flush, forceFlush, close, setSeq, seq, status, statusListen}
200
+ Observe.createMemoryOfflineStorage(initial?) -> OfflineStorage
201
+ // persists {version, seq, snapshot, savedAt}; seq is the correctness coordinate, timestamps are UX/freshness only
202
+ // mode:'topLevel' is reserved; first implemented mode is snapshot
203
+
204
+ // Declarative resource manager above mirror/replay/offline: app chooses what to start, not the store core
205
+ Observe.managedStore.mirror({remote, initial, mask, tags?, priority?, explicitOnly?, large?, sync?})
206
+ Observe.managedStore.replay({remote, initial, tags?, priority?, explicitOnly?, large?, syncOpts?})
207
+ Observe.managedStore.offline({remote?, initial, storage, storageKey?, tags?, priority?, explicitOnly?, large?, syncOpts?})
208
+ Observe.createStoreManager(resources) -> {plan(opts?), start(key, opts?), startPlanned(opts?), stop(key), stopAll(), get(key), touch(key, weight?), usage(), statusListen, handles}
209
+ // plan excludes explicitOnly/large by default; {includeExplicit, includeLarge} opts opt them in
210
+ // Slow-client conflation: recipe section 🎞️ below. Full generic surface (any event line, history/time-travel) -> Replay namespace, 🎞️ in rare docs.
211
+ // Object add/delete/deep set are paths. Array mutation dirties the whole array branch, not splice internals.
212
+ ```
213
+ ```
214
+ type Market = {data: {BTC?: number; ETH?: number}; meta: {status?: string}}
215
+ const market = Observe.createStore<Market>({data: {BTC: 1, ETH: 2}, meta: {status: "ok"}})
216
+
217
+ market.state.data.BTC = 3 // plain local mutation
218
+ market.node.data.BTC.on((v, ctx) => {}, {current: true}) // ctx.path = ["data", "BTC"]
219
+ market.node.data.on(data => {}, {current: true, drain: 50}) // branch snapshot, per-sub drain
220
+ market.update({data: {BTC: true, ETH: true}}, {current: true}).on(snap => {})
221
+
222
+ // backend facade over RPC
223
+ const api = Observe.exposeStore(market)
224
+
225
+ // frontend mirror: UI subscribes to local mirror, not RPC directly
226
+ const mirror = Observe.createStoreMirror<Market>(api, {data: {}, meta: {}})
227
+ const stop = await mirror.sync({data: {BTC: true}, meta: {status: true}}, {current: true, drain: 250}) // uses changedPaths when available
228
+ mirror.node.data.BTC.on(v => {}, {current: true})
229
+ stop()
230
+
231
+ // per-key feed — dict store -> grid rows; keyframe / reconnect are just expansion, not special cases
232
+ type Rows = Record<string, {qty: number}>
233
+ const rows = Observe.createStore<Rows>({})
234
+ const offRows = rows.each().on((key, row) => { /* row === undefined ? removeRow(key) : upsertRow(key, row) */ })
235
+
236
+ // the same per-key contract over the wire — ONE call (mirror store + syncStoreReplay + each)
237
+ const exposed = Observe.exposeStoreReplay(rows, {history: 1024}) // server side: spread exposed.api into the RPC object
238
+ const feed = Observe.syncStoreReplayEach<Rows>(exposed.api.replay, (key, row) => {}, {drain: "micro"})
239
+ await feed.ready // catch-up done: keyframe arrived expanded per key
240
+ feed.store.state // the mirror — direct reads / extra subscriptions
241
+ feed() // tears down the store sub AND the wire sub
242
+ // reconnect later: syncStoreReplayEach(remote, cb, {since: feed.seq(), initial: feed.store.snapshot()})
243
+ // offline persisted mirror — cached snapshot first, then replay catch-up over the same remote
244
+ const offline = await Observe.createOfflineStore<Rows>({
245
+ key: "rows",
246
+ remote: exposed.api.replay,
247
+ initial: {},
248
+ storage: Observe.createMemoryOfflineStorage(), // use IndexedDB/SQLite adapter in an app
249
+ debounceMs: 250,
250
+ })
251
+ offline.each().on((key, row) => {})
252
+ await offline.ready
253
+ await offline.flush()
254
+ offline.close()
255
+
256
+ // configurable app-level resource plan
257
+ const manager = Observe.createStoreManager({
258
+ market: Observe.managedStore.mirror({remote: api.market, initial: {data: {}, meta: {}}, mask: {data: {BTC: true}}, tags: ['bootstrap'], priority: 10}),
259
+ rows: Observe.managedStore.offline({remote: exposed.api.replay, initial: {}, storage: Observe.createMemoryOfflineStorage(), tags: ['grid']}),
260
+ video: Observe.managedStore.replay({remote: videoReplay, initial: {}, explicitOnly: true, large: true}),
261
+ })
262
+ await manager.startPlanned({tags: ['bootstrap']})
263
+ manager.touch('rows', 3) // usage can raise future plan score
264
+ await manager.start('video', {explicit: true})
265
+ ```
266
+ Runnable example: `npx tsx observe/store-mirror.example.ts`.
267
+ Offline oracles: `npx tsx replay/offline-store.test.ts`; real Socket.IO/RPC wire: `npx tsx replay/offline-store-socket.test.ts`.
268
+
269
+ ## 🎞️ Fast ticks vs slow client — replay lines + server-owned lag gate (recipe)
270
+ > The problem: the producer emits faster than a bad link drains. Naive streaming grows an unbounded
271
+ > outgoing queue per slow client. The replay stack solves it with ONE mental model — the FRAME:
272
+ > `frame(sinceSeq, hint?)` on the line returns envelopes bringing a consumer from `sinceSeq` to now,
273
+ > as compact as the line allows (exact tail -> condensed mini-frame -> keyframe fallback). The same
274
+ > method serves reconnect (`since`), client pull (own pace) and lag recovery. The transport sees only
275
+ > `seq`; ALL event semantics live in two lambdas declared on the line: `current` (keyframe = pointer
276
+ > to truth) and `frame` (condenser — may honor a client-supplied `hint`, see below).
277
+ ```ts
278
+ import { Observe, Replay } from 'wenay-common2'
279
+
280
+ // ---- producer: declare what the line HAS (its class follows — no mode flags) ----
281
+ const [emitQuote, quotes] = Replay.replayListen<[string, number]>({
282
+ history: 4096,
283
+ frame: (tail, hint) => lastPerSymbol(tail, hint), // mini-frame; hint = client's pick of the condensation rule
284
+ }) // current+frame = condensable · current only = keyframe recovery · neither = sacred queue (never skipped, loud on eviction)
285
+ // store lines: exposeStoreReplay already declares current + frame (last patch per path) — zero config
286
+ const store = Observe.createStore<World>(initial, { drain: 'micro' })
287
+ const exposed = Observe.exposeStoreReplay(store, { history: 1024 })
288
+
289
+ // ---- per CONNECTION: the rpc server owns the gate; the facade does NOT change ----
290
+ io.on('connection', socket => {
291
+ const [disconnect, disconnectListen] = listen<[]>()
292
+ socket.on('disconnect', () => disconnect())
293
+ createRpcServerAuto({
294
+ socket: { emit: (k, d) => socket.emit(k, d), on: (k, cb) => socket.on(k, cb) },
295
+ socketKey: 'world',
296
+ object: { ...exposed.api, quotes }, // replay lines auto-exposed: both surfaces, same key
297
+ disconnectListen, // gates close on disconnect automatically
298
+ replayOpts: { highWater: 64, lowWater: 8 },// arms frameLine; pending defaults to socket.io writeBuffer
299
+ })
300
+ })
301
+
302
+ // ---- client: picks its LAG POLICY per subscription; no conflation logic anywhere ----
303
+ const sub = Replay.replaySubscribe(deep.quotes, cb, {since: saved, policy: 'frame'}) // server may skip; drain -> mini-frame
304
+ const sub2 = Replay.replaySubscribe(deep.quotes, cb2, {since: saved}) // 'queue' (default): nothing ever skipped
305
+ // own pace (e.g. 50ms skips + condensation): pull on YOUR timer — hint picks the rule, server condenses:
306
+ // every(50, async () => { for (const ev of await deep.quotes.frame(mySeq, hint)) apply(ev); })
307
+ // store mirror: Observe.syncStoreReplay(mirror, deep.replay, {since: prev.seq()}) — same contract
308
+ // delivery contract: FIRST delivery = snapshot/tail start (same event type), then strictly-newer,
309
+ // seq-ascending, deduped; reconnect via {since} = mini-frame/tail, not a full snapshot
310
+ ```
311
+ Rules that make it correct (violating any of these silently breaks convergence):
312
+ - **The line declares its recovery sources.** `current` (keyframe: SAMPLED from truth, never computed
313
+ from deltas; `'last'` = last envelope for single-entity lines) and/or `frame` (condenser). A line
314
+ with neither is a sacred queue: full tails only, evicted journal -> `frame()` THROWS (loud) — a
315
+ lagging `'frame'`-policy subscriber gets a stream end, never silent loss.
316
+ - **A `frame` result must be state-equivalent to the tail it replaces** (per the line's own semantics).
317
+ "Can't condense THIS tail" is legal and simple: return the tail as-is. Refuse-loudly is `throw`.
318
+ Multiple condensation standards live INSIDE the lambda, dispatched by the client-supplied `hint`
319
+ (opaque to the transport): `frame(tail, hint)`.
320
+ - **Events must be ABSOLUTE per their entity** for last-per-entity condensing (store patches are).
321
+ - Gate drops never hole the journal — it is written BEFORE any gate. Reconnect via `{since}` still
322
+ gets everything; only an evicted `history` window degrades to keyframe (visible as a seq jump).
323
+ - `pending()` and the watermarks share units (bytes, packets, frames — anything, but the same).
324
+
325
+ Manual path (pre-rev2, still works, `keyOf` @deprecated): build the gate yourself with
326
+ `Replay.conflateReplay(exposed.replay, {pending, highWater, keyOf})` and spread `gated.api` into the
327
+ facade — details in rare docs. New code should declare `frame` on the line instead.
328
+
329
+ Wire-level proof/oracles: `npx ts-node replay/rpc-auto.test.ts` (real Socket.IO: auto-exposure, legacy
330
+ parity, frame equivalence, gate lag sim), plus `replay/conflate-socket.test.ts`, `replay/conflate.test.ts`,
331
+ `replay/coalesce.test.ts`. Full generic surface (history/time-travel, archive) → 🎞️ in rare docs.
332
+
333
+
334
+
@@ -1,4 +1,5 @@
1
- export * from "./reactive2";
1
+ export * from "./reactive";
2
2
  export * from "./store";
3
3
  export * from "./store-replay";
4
4
  export * from "./store-offline";
5
+ export * from "./store-manager";
@@ -14,7 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./reactive2"), exports);
17
+ __exportStar(require("./reactive"), exports);
18
18
  __exportStar(require("./store"), exports);
19
19
  __exportStar(require("./store-replay"), exports);
20
20
  __exportStar(require("./store-offline"), exports);
21
+ __exportStar(require("./store-manager"), exports);
@@ -0,0 +1,21 @@
1
+ type Fn = () => void;
2
+ export type ReactiveChange = {
3
+ paths: PropertyKey[][];
4
+ };
5
+ type PathUpdateFn = (change: ReactiveChange) => void;
6
+ type Drain = 'micro' | 'immediate' | number | ((flush: Fn) => void);
7
+ export type Opts = {
8
+ drain?: Drain;
9
+ depth?: number;
10
+ eager?: boolean;
11
+ };
12
+ export declare function reactive<T extends object>(root: T, opts?: Opts): T;
13
+ export declare function isReactive(p: any): boolean;
14
+ export declare function toRaw<T>(p: T): T;
15
+ export declare function onUpdate(p: any, cb: Fn): () => void;
16
+ export declare function onUpdatePaths(p: any, cb: PathUpdateFn): () => void;
17
+ export declare function flushReactive(p: any): Promise<void>;
18
+ export declare function listenUpdate(p: any): import("../events/Listen").ListenApi<[]>;
19
+ export declare function listenUpdatePaths(p: any): import("../events/Listen").ListenApi<[ReactiveChange]>;
20
+ export type Reactive<T extends object> = T;
21
+ export {};