@mmstack/mesh 22.14.1 → 22.15.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": "@mmstack/mesh",
3
- "version": "22.14.1",
3
+ "version": "22.15.1",
4
4
  "keywords": [
5
5
  "angular",
6
6
  "signals",
@@ -20,8 +20,8 @@
20
20
  "homepage": "https://github.com/mihajm/mmstack/blob/master/packages/mesh/client",
21
21
  "peerDependencies": {
22
22
  "@angular/core": ">=22 <23",
23
- "@mmstack/primitives": ">=22.24 <23",
24
- "@mmstack/mesh-protocol": ">=0.14 <1"
23
+ "@mmstack/primitives": ">=22.25 <23",
24
+ "@mmstack/mesh-protocol": ">=0.15.1 <1"
25
25
  },
26
26
  "sideEffects": false,
27
27
  "module": "fesm2022/mmstack-mesh.mjs",
@@ -1,6 +1,130 @@
1
- import { ClientMsg, ClientSignalMsg, IceServer, OpPolicy, PolicyViolation, PresenceState, PrincipalCtx, Relay, ServerDirectMsg, ServerMsg } from "@mmstack/mesh-protocol";
2
- import { AsyncStore, DiffOpsOptions, ForkStoreOptions, MergePolicyEntry, OpEnvelope, OpSync, StoreOp, SyncedFork, WritableSignalStore, toStoreOptions } from "@mmstack/primitives/core";
3
1
  import { Injector, Signal, WritableSignal } from "@angular/core";
2
+ import { ClientMsg, ClientSignalMsg, CoverContext, Dot, GenerationReason, Hlc, IceServer, Key, OpEnvelope, OpPolicy, PolicyViolation, PresenceState, PrincipalCtx, Ranges, Receipts, RegisterStore, Relay, ServerDirectMsg, ServerMsg, StoreOp, TailPolicy, VersionRange } from "@mmstack/mesh-protocol";
3
+ import { AsyncStore, DiffOpsOptions, ForkStoreOptions, MergePolicyEntry, OpEnvelope as OpEnvelope$1, OpSync, StoreOp as StoreOp$1, SyncedFork, WritableSignalStore, toStoreOptions } from "@mmstack/primitives/core";
4
+ /**
5
+ * The client half of a room generation: the record fields a snapshot welcome carries, the admission
6
+ * evidence the client keeps for its pre-check, and the pure decisions the session takes on them
7
+ * (which welcome to install, what a new generation does with the pending tail, whether a replayed
8
+ * envelope may be sent, when a member is ready for a consensus cut). Nothing here touches a socket,
9
+ * a store or a timer, so a harness can drive the same decisions the session does.
10
+ */
11
+ /** The immutable fields of the installed generation, as the client keeps them in its record. */
12
+ type InstalledGeneration = {
13
+ readonly instance: string;
14
+ readonly index: number;
15
+ readonly reason: GenerationReason;
16
+ readonly policy: TailPolicy;
17
+ readonly extent: Readonly<Record<string, Readonly<Record<string, Hlc>>>>;
18
+ readonly preCutMax: Readonly<Record<string, Hlc>>;
19
+ /** The seq of the snapshot welcome that installed it (or a later one of the same generation). */
20
+ readonly seq: number;
21
+ };
22
+ /**
23
+ * The admission evidence of the installed generation as this client knows it: the welcome's ranges,
24
+ * settled vector and first stamps, then every envelope the client ingests (its own included).
25
+ * A lead or lag against the relay's view only ever yields a refusal the client lands as a conflict.
26
+ */
27
+ type ClientAdmission = {
28
+ readonly ranges: Map<string, Ranges>;
29
+ readonly settled: Map<string, Hlc>;
30
+ readonly firstStamps: Map<string, Hlc>;
31
+ };
32
+ /** The serializable form of {@link ClientAdmission}. */
33
+ type ClientAdmissionRecord = {
34
+ readonly ranges: Readonly<Record<string, readonly VersionRange[]>>;
35
+ readonly settled: Readonly<Record<string, Hlc>>;
36
+ readonly firstStamps: Readonly<Record<string, Hlc>>;
37
+ };
38
+ declare const emptyAdmission: () => ClientAdmission;
39
+ /** The admission evidence a snapshot welcome carries, as of its seq. */
40
+ declare const admissionOf: (src: ClientAdmissionRecord) => ClientAdmission;
41
+ declare const admissionRecord: (a: ClientAdmission) => ClientAdmissionRecord;
42
+ /**
43
+ * One envelope reaches this client's view (its own emission, a relay delivery, a replayed or
44
+ * re-applied own write). A version it already holds is a duplicate, and one below its origin's
45
+ * maximum was skipped by the relay: both are refused (`false`), nothing is recorded. Otherwise the
46
+ * version joins the evidence exactly as the relay records it.
47
+ */
48
+ declare function admitLocal(a: ClientAdmission, env: {
49
+ readonly origin: string;
50
+ readonly version: number;
51
+ readonly hlc: Hlc;
52
+ }): boolean;
53
+ /** The context `admits` reads: the installed record's extent and preCutMax, the client's evidence. */
54
+ declare const coverContext: (gen: Pick<InstalledGeneration, "extent" | "preCutMax">, a: ClientAdmission) => CoverContext;
55
+ /**
56
+ * The replay pre-check: every cite of `env` (its own dot excepted) the installed state does not
57
+ * cover, by the same `admits` the relay runs, over the client's register store. An envelope with
58
+ * an uncovered cite is never sent; it is a conflict.
59
+ */
60
+ declare function uncoveredCites(store: RegisterStore, ctx: CoverContext, env: OpEnvelope): {
61
+ readonly path: readonly Key[];
62
+ readonly dot: Dot;
63
+ }[];
64
+ /** What the client knows of its installed generation when a snapshot welcome arrives. */
65
+ type WelcomeFence = {
66
+ readonly index: number;
67
+ readonly instance: string | undefined;
68
+ /** The seq of the installed snapshot. */
69
+ readonly seq: number;
70
+ /** The highest seq of a relay-delivered envelope of this generation, deduplicated or not. */
71
+ readonly maxSeq: number;
72
+ };
73
+ /**
74
+ * Which snapshot welcome installs. A newer generation (higher index) always does. One of the
75
+ * installed generation does when it is not older than the installed snapshot (`stale` otherwise)
76
+ * and not older than relay traffic already delivered (`older-than-traffic`): installing it would
77
+ * replace that traffic with an earlier state. Anything else is stale.
78
+ */
79
+ declare function welcomeVerdict(installed: WelcomeFence, msg: {
80
+ readonly index: number;
81
+ readonly instance: string;
82
+ readonly seq: number;
83
+ }): 'newer' | 'same' | 'stale' | 'older-than-traffic';
84
+ /** A pending envelope of an earlier generation, as the tail policy reads it. */
85
+ type Pending = {
86
+ readonly env: Pick<OpEnvelope, 'origin' | 'instance' | 'version'>;
87
+ };
88
+ /**
89
+ * A new generation's first step with the pending tail: in version order, an envelope whose version
90
+ * the receipts of its origin hold — in ANY generation — was admitted and is never resent; the rest
91
+ * is kept for the tail policy. Membership is instance-agnostic: a replayed envelope carries the
92
+ * current instance, so the relay receipts it there while the tail entry still names the generation
93
+ * it was authored in, and a crash between the wire and the record would otherwise replay it again
94
+ * after the next cut. An origin's versions never repeat (the counter runs through replay; a restart
95
+ * that loses it mints a new origin), so the version alone identifies the write.
96
+ */
97
+ declare function trimByReceipts<T extends Pending>(pending: readonly T[], receipts: Receipts): {
98
+ readonly trimmed: T[];
99
+ readonly keep: T[];
100
+ };
101
+ /** A refusal was classified: a snapshot at or past its seq is owed. */
102
+ declare const owedAfterRefusal: (owed: number | undefined, seq: number) => number;
103
+ /** A snapshot installed at `seq`: the owed rehydration completes when it reaches the refusal. */
104
+ declare const owedAfterInstall: (owed: number | undefined, seq: number) => number | undefined;
105
+ /**
106
+ * A member's readiness for a consensus cut: it pressed Compact, it is connected, and nothing it
107
+ * wrote is outstanding (its outbox empty, no replay running). A conflict is never outstanding: it
108
+ * is out of the outbox the moment it is classified.
109
+ */
110
+ declare const readyValue: (s: {
111
+ readonly pressed: boolean;
112
+ readonly connected: boolean;
113
+ readonly replaying: boolean;
114
+ readonly outstanding: number;
115
+ }) => boolean;
116
+ /**
117
+ * The authored intent of an envelope: its raw op list and one bump flag, what a re-author rebuilds
118
+ * from. The raws are the stamped ops without their expansion clears (a diffed write never emits a
119
+ * `clear` of its own, so every `clear` is one) and without cites and epoch. The envelope bumped when
120
+ * an op's epoch rises above the register baseline at its path as the client held it before the
121
+ * envelope (the relay's own test for a bump).
122
+ */
123
+ type Intent = {
124
+ readonly raws: readonly StoreOp[];
125
+ readonly bump: boolean;
126
+ };
127
+ declare function intentOf(env: OpEnvelope, baseline: (path: readonly Key[]) => number): Intent;
4
128
  /**
5
129
  * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport
6
130
  * represents a single connection and never reconnects itself.
@@ -27,6 +151,61 @@ export declare function webSocketTransport(url: string, protocols?: string | str
27
151
  * would reach relay memory where a socket peer's would have been dropped.
28
152
  */
29
153
  export declare function directTransport(relay: Relay, ctx: PrincipalCtx): MeshTransportFactory;
154
+ /**
155
+ * Why a write is a conflict: its replay into a new generation cites something the generation does
156
+ * not hold (`'uncovered'`, never sent), or the relay refused it — a cite it does not cover
157
+ * (`'citation'`) or an epoch raised without the authority to (`'epoch-bump'`).
158
+ */
159
+ type ConflictCause = 'uncovered' | 'citation' | 'epoch-bump';
160
+ /**
161
+ * A write that will never be admitted as it stands. Its local effect is retracted (a replay that
162
+ * failed its pre-check is never applied; a refused write is dropped by the snapshot that follows).
163
+ * The two verbs are the whole surface: `discard()` lets it go, `reauthor()` writes its raw ops again
164
+ * as a new write citing the current state. Neither can submit the original envelope.
165
+ */
166
+ type MeshConflict = {
167
+ /** The envelope as it was authored (its values, cites and epoch). */
168
+ readonly env: OpEnvelope$1;
169
+ readonly intent: Intent;
170
+ readonly cause: ConflictCause;
171
+ discard(): void;
172
+ /** Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`). */
173
+ reauthor(): boolean;
174
+ };
175
+ /** The room's compaction state, as the relay last announced it. */
176
+ type CompactionState = {
177
+ /** Droppable tombstones counted against the budget. */
178
+ readonly count: number;
179
+ /** The hard budget, 0 when the room arms none. */
180
+ readonly budget: number;
181
+ /** Origins of the members currently declared ready for a consensus cut. */
182
+ readonly ready: readonly string[];
183
+ };
184
+ /** The room generation the client installed, as its snapshot welcome named it. */
185
+ type GenerationState = Pick<InstalledGeneration, 'instance' | 'index' | 'reason' | 'policy'>;
186
+ /**
187
+ * The session's durable half, persisted as one unit with the outbox: the fields of the generation
188
+ * the tail was written in and its admission evidence, the intents of the pending writes, unresolved
189
+ * conflicts and an owed snapshot. It holds NO registers and no sequence knowledge: a restart never
190
+ * trusts stale registers — it installs nothing from disk, asks for a snapshot (hello without seq)
191
+ * and resends its outbox first.
192
+ */
193
+ type SessionRecord = {
194
+ readonly generation?: Omit<InstalledGeneration, 'seq'>;
195
+ readonly admission?: ClientAdmissionRecord;
196
+ readonly intents?: readonly {
197
+ readonly origin: string;
198
+ readonly version: number;
199
+ readonly intent: Intent;
200
+ }[];
201
+ readonly conflicts?: readonly {
202
+ readonly env: OpEnvelope$1;
203
+ readonly intent: Intent;
204
+ readonly cause: ConflictCause;
205
+ }[];
206
+ /** A refusal's seq: a snapshot at or past it must install before the client trusts its view. */
207
+ readonly rehydrateOwed?: number;
208
+ };
30
209
  type MeshStatus = 'connecting' |
31
210
  /** Queued behind another tab that owns this key's durable outbox (`crossTab: 'queue'`). */
32
211
  'waiting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
@@ -46,7 +225,7 @@ type RemoteBatch = {
46
225
  /** The relay's total-order stamp for this batch. */
47
226
  readonly seq: number;
48
227
  readonly writer: string;
49
- readonly ops: readonly StoreOp[];
228
+ readonly ops: readonly StoreOp$1[];
50
229
  };
51
230
  /**
52
231
  * Environment callbacks a session shell provides. All are optional except `onStatus`; the
@@ -99,14 +278,26 @@ type MeshSessionHooks = {
99
278
  onTerminal?(state: 'ejected' | 'closed', reason?: string): void;
100
279
  /**
101
280
  * The relay refused one of this session's writes: it is not in the room and never will be.
102
- * `'generation'` — written in a room generation that has since been cut (the whole tail is
103
- * refused at the welcome that names the new one, or one envelope by the relay's reply);
104
- * `'schema'` — a data shape older than the room's; `'order'` — a version below this origin's
105
- * admitted maximum that was never admitted (a second tab on one origin). The session drops
106
- * the write locally and hydrates from a fresh snapshot; the envelope carries the values, so
107
- * the application can offer to write them again. Any `whenAcked` waiter rejects.
281
+ * `'generation'` — written in a room generation that a cut with the `discard` policy closed (a
282
+ * migration or a rollback: the reset is the intent), or in a room recreated without its
283
+ * generation record; `'schema'` — a data shape older than the room's; `'order'` — a version
284
+ * below this origin's admitted maximum that was never admitted (a second tab on one origin);
285
+ * `'compacting'` — a host refused a write from a connection declared ready for the current
286
+ * generation (the relay itself never sends it). The session drops the write locally and hydrates from a fresh snapshot; the envelope carries the
287
+ * values, so the application can offer to write them again. Any `whenAcked` waiter rejects.
288
+ * A write a compaction cut replays is never refused here: it is resent, or it is a conflict.
289
+ */
290
+ onRefused?(env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order' | 'compacting'): void;
291
+ /** The unresolved conflicts changed (a write classified, discarded or re-authored). */
292
+ onConflicts?(conflicts: readonly MeshConflict[]): void;
293
+ /** The relay announced the room's compaction state (count, budget, ready members). */
294
+ onCompaction?(state: CompactionState): void;
295
+ /**
296
+ * A snapshot welcome of a NEW generation installed (a cut's welcome, or the first snapshot of
297
+ * the session); `undefined` when the room was recreated without its record. A welcome of the
298
+ * installed generation never fires it.
108
299
  */
109
- onRefused?(env: OpEnvelope, reason: 'generation' | 'schema' | 'order'): void;
300
+ onGeneration?(generation: GenerationState | undefined): void;
110
301
  };
111
302
  type MeshSessionOptions<T extends object> = {
112
303
  readonly room: string;
@@ -121,6 +312,16 @@ type MeshSessionOptions<T extends object> = {
121
312
  readonly schemaVersion?: number;
122
313
  /** The room generation a restored outbox was written in; the first welcome decides whether it still holds. */
123
314
  readonly instance?: string;
315
+ /**
316
+ * The restored durable record (see {@link SessionRecord}), applied at `connect()` on top of the
317
+ * restored outbox: the registers are hydrated with the pending writes re-applied over them.
318
+ */
319
+ readonly record?: SessionRecord;
320
+ /**
321
+ * Write a conflict's raw ops again (a new write citing the current state), on the shell's store;
322
+ * with `bump`, as an authority override. Without it a conflict can only be discarded.
323
+ */
324
+ readonly reauthor?: (intent: Intent) => void;
124
325
  readonly reconnect?: {
125
326
  readonly maxDelayMs?: number;
126
327
  };
@@ -158,7 +359,7 @@ type MeshSession = {
158
359
  */
159
360
  whenAcked(): Promise<void>;
160
361
  /** The unacknowledged local tail (the durable-outbox payload). */
161
- unackedEnvs(): readonly OpEnvelope[];
362
+ unackedEnvs(): readonly OpEnvelope$1[];
162
363
  /** The room generation this session is in, once a welcome (or a restored outbox) named one. */
163
364
  instance(): string | undefined;
164
365
  peers(): ReadonlyMap<string, PresenceState>;
@@ -167,6 +368,16 @@ type MeshSession = {
167
368
  sendSignal(msg: ClientSignalMsg): void;
168
369
  /** Send a `direct` frame to one member over the current connection; lost when there is none. */
169
370
  sendDirect(to: string, data: unknown): void;
371
+ /** Writes that will never be admitted as they stand, each with its two verbs. */
372
+ conflicts(): readonly MeshConflict[];
373
+ /**
374
+ * The member pressed (or released) Compact. While pressed, the session declares itself ready for
375
+ * a consensus cut whenever nothing it wrote is outstanding, and re-declares on every change; a
376
+ * reconnect and a new generation release the press. Safety never depends on it.
377
+ */
378
+ declareReady(pressed: boolean): void;
379
+ /** The durable record to persist with the outbox (see {@link SessionRecord}). */
380
+ record(): SessionRecord;
170
381
  close(): void;
171
382
  };
172
383
  declare function meshSession<T extends object>(opt: MeshSessionOptions<T>): MeshSession;
@@ -413,7 +624,7 @@ type MeshSyncOptions = {
413
624
  /** The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message too big, 1006 = dropped). */
414
625
  readonly onDisconnect?: (code: number, reason: string) => void;
415
626
  /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */
416
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
627
+ readonly onRefused?: (env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order' | 'compacting') => void;
417
628
  /**
418
629
  * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects
419
630
  * (and before it restores an `outbox`), so a store hydrated from another source first (a worker
@@ -512,6 +723,26 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
512
723
  fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
513
724
  /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */
514
725
  readonly sync: SeatSync<T>;
726
+ /**
727
+ * Writes that will never be admitted as they stand: a write a compaction cut could not replay
728
+ * (it cites something the cut folded away) or one the relay refused. Each offers `discard()` or
729
+ * `reauthor()` (write its values again, citing the current state). Persisted with the outbox.
730
+ */
731
+ readonly conflicts: Signal<readonly MeshConflict[]>;
732
+ /** The room's compaction state as the relay last announced it; undefined before any notice. */
733
+ readonly compaction: Signal<CompactionState | undefined>;
734
+ /**
735
+ * The room generation this client installed: set by every snapshot welcome of a new generation
736
+ * (a cut's welcome flips it), untouched by one of the installed generation. Undefined until the
737
+ * first snapshot welcome and after a room was recreated without its record.
738
+ */
739
+ readonly generation: Signal<GenerationState | undefined>;
740
+ /**
741
+ * The member pressed (`true`) or released Compact: the client declares itself ready for a
742
+ * consensus cut whenever nothing it wrote is outstanding, re-declaring on every change. A
743
+ * reconnect or a new generation releases it.
744
+ */
745
+ declareReady(pressed: boolean): void;
515
746
  close(): void;
516
747
  };
517
748
  /**
@@ -528,7 +759,7 @@ type SeatChange = {
528
759
  /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */
529
760
  readonly seq: number;
530
761
  readonly writer: string;
531
- readonly ops: readonly StoreOp[];
762
+ readonly ops: readonly StoreOp$1[];
532
763
  };
533
764
  /**
534
765
  * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past
@@ -583,7 +814,7 @@ type AgentSeatOptions = {
583
814
  readonly context?: toStoreOptions;
584
815
  readonly onEject?: (reason: string) => void;
585
816
  /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */
586
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
817
+ readonly onRefused?: (env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order' | 'compacting') => void;
587
818
  };
588
819
  type AgentSeat<T extends object> = {
589
820
  /** The live converging replica. Reads exactly like a local signal store. */
@@ -599,6 +830,19 @@ type AgentSeat<T extends object> = {
599
830
  stableSnapshot(): StableSnapshot<T> | null;
600
831
  /** Run local writes and emit them to the room as one envelope, like any peer's edit. */
601
832
  write(fn: () => void): void;
833
+ /**
834
+ * The seat's writes that will never be admitted as they stand (a replay a compaction cut could not
835
+ * carry, or a relay refusal), each with `discard()` and `reauthor()`.
836
+ */
837
+ conflicts(): readonly MeshConflict[];
838
+ /** The room's compaction state as the relay last announced it; undefined before any notice. */
839
+ readonly compaction: Signal<CompactionState | undefined>;
840
+ /**
841
+ * The seat pressed (`true`) or released Compact: it declares itself ready for a consensus cut
842
+ * whenever it is connected and nothing it wrote is outstanding, re-declaring on every change. A
843
+ * reconnect or a new generation releases it.
844
+ */
845
+ declareReady(pressed: boolean): void;
602
846
  /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */
603
847
  setAtPath(path: string | readonly (string | number)[], value: unknown): void;
604
848
  /**
@@ -668,7 +912,7 @@ export declare function setAtPath(node: unknown, path: string | readonly PathSeg
668
912
  * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
669
913
  * `changes` stream: narrating each batch's ops yields an append-only account of the room.
670
914
  */
671
- export declare function describeOp(op: StoreOp, writer: string): string;
915
+ export declare function describeOp(op: StoreOp$1, writer: string): string;
672
916
  type WebRtcMeshOptions = {
673
917
  readonly room: string;
674
918
  readonly writer: string;