@lyku/para-sync 0.0.1-pre.0 → 0.0.1-pre.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lyku/para-sync",
3
- "version": "0.0.1-pre.0",
3
+ "version": "0.0.1-pre.1",
4
4
  "description": "synced<T> distributed object sync for the para:* suite — server-authoritative records with live, version-reconciled client replicas. Pre-release: API may change before 0.1.0. Currently provides the pluggable SyncTransport interface and the InProcessTransport implementation (monolith/edge/no-bus deployments); NatsTransport and the synced<T> primitive land on top.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -8,8 +8,12 @@
8
8
  "type": "module",
9
9
  "main": "./src/index.js",
10
10
  "module": "./src/index.js",
11
+ "types": "./src/index.d.ts",
11
12
  "exports": {
12
- ".": "./src/index.js"
13
+ ".": {
14
+ "types": "./src/index.d.ts",
15
+ "import": "./src/index.js"
16
+ }
13
17
  },
14
18
  "dependencies": {
15
19
  "@lyku/para-signals": "^0.0.1-pre.0"
@@ -0,0 +1,124 @@
1
+ /** @typedef {import('./transport.js').SyncEnvelope} SyncEnvelope */
2
+ /** @typedef {import('./transport.js').SyncTransport} SyncTransport */
3
+ /**
4
+ * A schema's parse result — matches para-schema's Result<T, string>.
5
+ * @typedef {{ tag: 'Ok', value: any } | { tag: 'Err', error: string }} Result
6
+ */
7
+ /**
8
+ * Anything with a `parse` returning {@link Result}. In production this is a
9
+ * para-schema `SchemaValue`; in tests it can be a hand-rolled gate. The replica
10
+ * depends only on this shape, never on para-schema directly — which is also why
11
+ * the client gates branch on `.tag` instead of using the throw-on-Err `::`
12
+ * convention (a malformed delta must trigger recovery, not crash the apply).
13
+ * @typedef {{ parse(v: unknown): Result }} SyncSchema
14
+ */
15
+ /**
16
+ * A minimal reactive value cell: get / peek / set. A para-signals `signal()`
17
+ * satisfies it exactly and is the default. Injectable for testing and for the
18
+ * fork-backed cell on the para-svelte side.
19
+ * @typedef {{ get(): any, peek(): any, set(v: any): void }} Cell
20
+ */
21
+ /**
22
+ * @typedef {'ok' | 'stale' | 'skew' | 'refetching'} ReplicaStatus
23
+ * - ok last apply succeeded; replica is current
24
+ * - stale uninitialized, or a refetch failed / none available
25
+ * - skew an inbound value failed `parse` (malformed or schema-skew)
26
+ * - refetching a recovery refetch is in flight
27
+ */
28
+ /**
29
+ * @typedef {object} ReplicaMeta
30
+ * @property {string | null} schemaVersion schema version of the applied value
31
+ * @property {number} sequence sequence of the applied value (-1 if uninitialized)
32
+ * @property {ReplicaStatus} status
33
+ */
34
+ /**
35
+ * Create a client replica for one synced key.
36
+ *
37
+ * @param {object} opts
38
+ * @param {string} opts.key synced key, e.g. "user:123"
39
+ * @param {SyncSchema} opts.schema the `parse` gate
40
+ * @param {SyncTransport} opts.transport change-envelope source
41
+ * @param {SyncEnvelope} [opts.seed] SSR-embedded initial envelope
42
+ * @param {() => Promise<SyncEnvelope>} [opts.refetch] Err/skew/gap fallback: fetch the
43
+ * current authoritative snapshot. Omit → no recovery (status goes 'stale').
44
+ * @param {Cell} [opts.cell] reactive cell (default: a para signal)
45
+ */
46
+ export function createClientReplica({ key, schema, transport, seed, refetch, cell }: {
47
+ key: string;
48
+ schema: SyncSchema;
49
+ transport: SyncTransport;
50
+ seed?: SyncEnvelope;
51
+ refetch?: () => Promise<SyncEnvelope>;
52
+ cell?: Cell;
53
+ }): {
54
+ /** current value (tracked read) */
55
+ get: () => any;
56
+ /** current value (untracked) */
57
+ peek: () => any;
58
+ /** reconcile metadata (tracked): { schemaVersion, sequence, status } */
59
+ meta: () => any;
60
+ /** reconcile metadata (untracked) */
61
+ peekMeta: () => any;
62
+ /** observability counters — read directly */
63
+ stats: {
64
+ applied: number;
65
+ ignoredStale: number;
66
+ gaps: number;
67
+ parseErrors: number;
68
+ refetches: number;
69
+ };
70
+ /** resolves when no recovery refetch is in flight (test/await aid) */
71
+ whenIdle: () => Promise<void>;
72
+ /** stop listening; idempotent */
73
+ dispose: () => void;
74
+ };
75
+ export type SyncEnvelope = import("./transport.js").SyncEnvelope;
76
+ export type SyncTransport = import("./transport.js").SyncTransport;
77
+ /**
78
+ * A schema's parse result — matches para-schema's Result<T, string>.
79
+ */
80
+ export type Result = {
81
+ tag: "Ok";
82
+ value: any;
83
+ } | {
84
+ tag: "Err";
85
+ error: string;
86
+ };
87
+ /**
88
+ * Anything with a `parse` returning {@link Result}. In production this is a
89
+ * para-schema `SchemaValue`; in tests it can be a hand-rolled gate. The replica
90
+ * depends only on this shape, never on para-schema directly — which is also why
91
+ * the client gates branch on `.tag` instead of using the throw-on-Err `::`
92
+ * convention (a malformed delta must trigger recovery, not crash the apply).
93
+ */
94
+ export type SyncSchema = {
95
+ parse(v: unknown): Result;
96
+ };
97
+ /**
98
+ * A minimal reactive value cell: get / peek / set. A para-signals `signal()`
99
+ * satisfies it exactly and is the default. Injectable for testing and for the
100
+ * fork-backed cell on the para-svelte side.
101
+ */
102
+ export type Cell = {
103
+ get(): any;
104
+ peek(): any;
105
+ set(v: any): void;
106
+ };
107
+ /**
108
+ * - ok last apply succeeded; replica is current
109
+ * - stale uninitialized, or a refetch failed / none available
110
+ * - skew an inbound value failed `parse` (malformed or schema-skew)
111
+ * - refetching a recovery refetch is in flight
112
+ */
113
+ export type ReplicaStatus = "ok" | "stale" | "skew" | "refetching";
114
+ export type ReplicaMeta = {
115
+ /**
116
+ * schema version of the applied value
117
+ */
118
+ schemaVersion: string | null;
119
+ /**
120
+ * sequence of the applied value (-1 if uninitialized)
121
+ */
122
+ sequence: number;
123
+ status: ReplicaStatus;
124
+ };
package/src/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./transport.js";
2
+ export * from "./client.js";
@@ -0,0 +1,226 @@
1
+ /**
2
+ * The change envelope. Delta/full-object model: the new value travels with
3
+ * the reconcile key, so steady-state replication is deliver → parse → apply,
4
+ * with no refetch round-trip (refetch is the Err/gap/skew fallback only).
5
+ *
6
+ * @typedef {object} SyncEnvelope
7
+ * @property {unknown} value The full changed object. NOT validated by
8
+ * the transport — `parse` gating is the
9
+ * consumer's job at the apply boundary.
10
+ * @property {string} schema_version Reconcile key, part 1: the model's schema
11
+ * version (e.g. "3.1"). Distinguishes a
12
+ * compatible-but-behind replica from a
13
+ * different/breaking shape.
14
+ * @property {number} sequence Reconcile key, part 2: the object's
15
+ * monotonic Postgres-authoritative sequence.
16
+ * Sole job is ordering + gap detection.
17
+ */
18
+ /**
19
+ * A listener for a key's change envelopes.
20
+ * @callback SyncHandler
21
+ * @param {SyncEnvelope} envelope
22
+ * @returns {void}
23
+ */
24
+ /**
25
+ * Returned by subscribe(); calling it removes the subscription. Idempotent.
26
+ * @callback Unsub
27
+ * @returns {void}
28
+ */
29
+ /**
30
+ * The pluggable transport contract. `synced<T>` depends ONLY on this shape, not
31
+ * on any concrete transport — that decoupling is what lets the same primitive
32
+ * run on a single box (InProcessTransport) or across services (NatsTransport).
33
+ *
34
+ * Contract notes that every implementation must honor:
35
+ * - publish(key, envelope) delivers `envelope` to every current subscriber of
36
+ * `key`. Publishing to a key with no subscribers is a no-op (never throws).
37
+ * - The transport is a dumb pipe: it does NOT retain the latest value, does
38
+ * NOT validate the envelope, and does NOT dedupe by sequence. A subscriber
39
+ * receives only publishes that happen AFTER it subscribes — initial state
40
+ * arrives via the SSR seed, not the transport.
41
+ * - subscribe(key, handler) returns an idempotent Unsub.
42
+ *
43
+ * @typedef {object} SyncTransport
44
+ * @property {(key: string, envelope: SyncEnvelope) => void} publish
45
+ * @property {(key: string, handler: SyncHandler) => Unsub} subscribe
46
+ */
47
+ /**
48
+ * In-process implementation of {@link SyncTransport}. A keyed pub/sub emitter:
49
+ * `Map<key, Set<handler>>`. No bus, no network, no serialization — the write
50
+ * and the listen happen in the same process, so delivery is a synchronous call.
51
+ *
52
+ * Why a plain emitter and not a para-signal per key: the transport contract is
53
+ * notification semantics ("deliver future publishes to this handler"), not
54
+ * value-cell semantics ("hand me the current value on subscribe, then deltas").
55
+ * Initial state is the SSR seed's job; the transport only carries changes. A
56
+ * keyed emitter models that exactly, without the current-value-on-subscribe and
57
+ * Object.is-dedupe behavior a signal would impose.
58
+ *
59
+ * @implements {SyncTransport}
60
+ */
61
+ export class InProcessTransport implements SyncTransport {
62
+ /**
63
+ * key → set of handlers. A key is present iff it has ≥1 live subscriber;
64
+ * the entry is deleted when its last subscriber unsubscribes (no key leak).
65
+ * @type {Map<string, Set<SyncHandler>>}
66
+ */
67
+ _subs: Map<string, Set<SyncHandler>>;
68
+ /**
69
+ * Deliver `envelope` to every current subscriber of `key`, in subscription
70
+ * order. No-op if `key` has no subscribers.
71
+ * @param {string} key
72
+ * @param {SyncEnvelope} envelope
73
+ */
74
+ publish(key: string, envelope: SyncEnvelope): void;
75
+ /**
76
+ * Subscribe `handler` to `key`'s change envelopes. Returns an idempotent
77
+ * Unsub; calling it more than once is safe and will not remove a handler that
78
+ * was re-subscribed in between.
79
+ * @param {string} key
80
+ * @param {SyncHandler} handler
81
+ * @returns {Unsub}
82
+ */
83
+ subscribe(key: string, handler: SyncHandler): Unsub;
84
+ /**
85
+ * Diagnostic: number of keys with at least one live subscriber. Useful for
86
+ * leak checks (a healthy server returns to a steady key count as sessions
87
+ * come and go).
88
+ * @returns {number}
89
+ */
90
+ keyCount(): number;
91
+ }
92
+ /**
93
+ * NATS implementation of {@link SyncTransport}, for multi-service deployments
94
+ * where a write in the writer's service must reach listeners in other services.
95
+ * Matches Lyku's existing full-object-over-NATS convention.
96
+ *
97
+ * Honors the same contract as InProcessTransport (deliver to current
98
+ * subscribers, no retention, dumb pipe, idempotent unsub). On top it adds:
99
+ * - subject mapping (key → NATS subject),
100
+ * - the wire codec (encode on publish, decode on receipt),
101
+ * - LOCAL FANOUT: N local subscribers to one key share ONE bus subscription,
102
+ * and that bus subscription is torn down when the last local subscriber
103
+ * leaves (the cross-service analog of subscriber-set GC).
104
+ *
105
+ * @implements {SyncTransport}
106
+ */
107
+ export class NatsTransport implements SyncTransport {
108
+ /**
109
+ * @param {object} opts
110
+ * @param {SyncNatsConnection} opts.connection
111
+ * @param {SyncCodec} [opts.codec] default: identity (tests only)
112
+ * @param {(key: string) => string} [opts.subjectOf] default: `synced.${key}`
113
+ */
114
+ constructor({ connection, codec, subjectOf }: {
115
+ connection: SyncNatsConnection;
116
+ codec?: SyncCodec;
117
+ subjectOf?: (key: string) => string;
118
+ });
119
+ _nc: SyncNatsConnection;
120
+ _codec: SyncCodec;
121
+ _subjectOf: (key: string) => string;
122
+ /**
123
+ * key → { natsUnsub, handlers } — present iff the key has ≥1 local
124
+ * subscriber (and therefore one live bus subscription).
125
+ * @type {Map<string, { natsUnsub: () => void, handlers: Set<SyncHandler> }>}
126
+ */
127
+ _keys: Map<string, {
128
+ natsUnsub: () => void;
129
+ handlers: Set<SyncHandler>;
130
+ }>;
131
+ /**
132
+ * @param {string} key
133
+ * @param {SyncEnvelope} envelope
134
+ */
135
+ publish(key: string, envelope: SyncEnvelope): void;
136
+ /**
137
+ * @param {string} key
138
+ * @param {SyncHandler} handler
139
+ * @returns {Unsub}
140
+ */
141
+ subscribe(key: string, handler: SyncHandler): Unsub;
142
+ /**
143
+ * Diagnostic: number of keys with a live bus subscription.
144
+ * @returns {number}
145
+ */
146
+ keyCount(): number;
147
+ }
148
+ /**
149
+ * The change envelope. Delta/full-object model: the new value travels with
150
+ * the reconcile key, so steady-state replication is deliver → parse → apply,
151
+ * with no refetch round-trip (refetch is the Err/gap/skew fallback only).
152
+ */
153
+ export type SyncEnvelope = {
154
+ /**
155
+ * The full changed object. NOT validated by
156
+ * the transport — `parse` gating is the
157
+ * consumer's job at the apply boundary.
158
+ */
159
+ value: unknown;
160
+ /**
161
+ * Reconcile key, part 1: the model's schema
162
+ * version (e.g. "3.1"). Distinguishes a
163
+ * compatible-but-behind replica from a
164
+ * different/breaking shape.
165
+ */
166
+ schema_version: string;
167
+ /**
168
+ * Reconcile key, part 2: the object's
169
+ * monotonic Postgres-authoritative sequence.
170
+ * Sole job is ordering + gap detection.
171
+ */
172
+ sequence: number;
173
+ };
174
+ /**
175
+ * A listener for a key's change envelopes.
176
+ */
177
+ export type SyncHandler = (envelope: SyncEnvelope) => void;
178
+ /**
179
+ * Returned by subscribe(); calling it removes the subscription. Idempotent.
180
+ */
181
+ export type Unsub = () => void;
182
+ /**
183
+ * The pluggable transport contract. `synced<T>` depends ONLY on this shape, not
184
+ * on any concrete transport — that decoupling is what lets the same primitive
185
+ * run on a single box (InProcessTransport) or across services (NatsTransport).
186
+ *
187
+ * Contract notes that every implementation must honor:
188
+ * - publish(key, envelope) delivers `envelope` to every current subscriber of
189
+ * `key`. Publishing to a key with no subscribers is a no-op (never throws).
190
+ * - The transport is a dumb pipe: it does NOT retain the latest value, does
191
+ * NOT validate the envelope, and does NOT dedupe by sequence. A subscriber
192
+ * receives only publishes that happen AFTER it subscribes — initial state
193
+ * arrives via the SSR seed, not the transport.
194
+ * - subscribe(key, handler) returns an idempotent Unsub.
195
+ */
196
+ export type SyncTransport = {
197
+ publish: (key: string, envelope: SyncEnvelope) => void;
198
+ subscribe: (key: string, handler: SyncHandler) => Unsub;
199
+ };
200
+ /**
201
+ * A NATS connection, callback-adapted. NatsTransport expects delivery as a
202
+ * callback + an unsubscribe, NOT nats.js's raw async-iterable subscription —
203
+ * the iterable→callback adaptation is a 3-line caller concern that Lyku already
204
+ * does (`const sub = nc.subscribe(subj); (async () => { for await (const m of
205
+ * sub) onMessage(m.data); })(); return () => sub.unsubscribe();`). Keeping that
206
+ * out of the transport makes delivery synchronous and deterministic to test.
207
+ */
208
+ export type SyncNatsConnection = {
209
+ publish: (subject: string, payload: Uint8Array) => void;
210
+ /**
211
+ * subscribe to `subject`; `onMessage` is called per message with the raw
212
+ * payload; returns an unsubscribe function.
213
+ */
214
+ subscribe: (subject: string, onMessage: (payload: Uint8Array) => void) => (() => void);
215
+ };
216
+ /**
217
+ * Wire codec: envelope ⇄ bytes. NATS payloads are `Uint8Array`. In production
218
+ * inject a BON or msgpackr codec (envelopes carry bigint IDs, which JSON cannot
219
+ * represent — BON is the SSR/wire serializer for exactly this reason). Defaults
220
+ * to identity (object passthrough), which works for in-memory fakes/tests but
221
+ * NOT a real NATS connection.
222
+ */
223
+ export type SyncCodec = {
224
+ encode: (envelope: SyncEnvelope) => any;
225
+ decode: (payload: any) => SyncEnvelope;
226
+ };