@mmstack/mesh 21.6.0 → 21.8.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/README.md +39 -5
- package/fesm2022/mmstack-mesh.mjs +143 -21
- package/fesm2022/mmstack-mesh.mjs.map +1 -1
- package/package.json +3 -3
- package/types/mmstack-mesh.d.ts +34 -1
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ const board = store<Board>(initialBoard());
|
|
|
25
25
|
|
|
26
26
|
const mesh = meshSync(board, {
|
|
27
27
|
room: 'board-42',
|
|
28
|
-
writer: currentUserId,
|
|
28
|
+
writer: currentUserId, // an opaque principal id, never a display name
|
|
29
29
|
transport: webSocketTransport('wss://sync.example.com'),
|
|
30
30
|
});
|
|
31
31
|
```
|
|
@@ -91,7 +91,9 @@ const yjsDoc: MergeFn = (_ancestor, mine, theirs) => {
|
|
|
91
91
|
};
|
|
92
92
|
|
|
93
93
|
meshSync(store, {
|
|
94
|
-
room,
|
|
94
|
+
room,
|
|
95
|
+
writer,
|
|
96
|
+
transport,
|
|
95
97
|
policies: [{ path: 'doc', merge: yjsDoc }],
|
|
96
98
|
});
|
|
97
99
|
```
|
|
@@ -144,6 +146,12 @@ rebases offline edits onto the room. `persist` stays the tool for a store that i
|
|
|
144
146
|
cold offline boot shows the store's initial value plus your restored writes until a welcome arrives.
|
|
145
147
|
If you also need to read the last room state while fully offline, assemble it as a base first, below.
|
|
146
148
|
|
|
149
|
+
The outbox also records the room **generation** the tail was written in (the relay's `instance`
|
|
150
|
+
nonce), this device's emission epoch floors and its clock high-water. A relay cuts a generation on
|
|
151
|
+
a migration: every write from before the cut is refused, and on the first welcome after a reboot
|
|
152
|
+
the client drops such a tail loudly through `onRefused` instead of resending it. A tail written
|
|
153
|
+
before any welcome ever named a generation adopts the first one it meets.
|
|
154
|
+
|
|
147
155
|
## Assemble a base before connecting
|
|
148
156
|
|
|
149
157
|
Pass `whenReady` to hold the connection until a local base is in place. `meshSync` awaits it before
|
|
@@ -270,11 +278,11 @@ the synced store. Its writes stay on the fork, so nothing reaches the room until
|
|
|
270
278
|
`discard()` drops it.
|
|
271
279
|
|
|
272
280
|
```ts
|
|
273
|
-
const proposal = seat.fork();
|
|
281
|
+
const proposal = seat.fork(); // the agent's isolated branch, off the room
|
|
274
282
|
setAtPath(proposal.store, 'plan.endDate', '2026-10-11'); // it writes here
|
|
275
283
|
|
|
276
284
|
const staged = proposal.ops(); // StoreOp[] for the reviewer to see
|
|
277
|
-
proposal.commit();
|
|
285
|
+
proposal.commit(); // approve: emits as concurrent writes to the room
|
|
278
286
|
// proposal.rebase(); // re-observe the room, then commit on top
|
|
279
287
|
// proposal.discard(); // reject: drops the staged writes
|
|
280
288
|
```
|
|
@@ -313,7 +321,7 @@ seat.changes((e) => {
|
|
|
313
321
|
if (!base || sinceBase.length > 200) {
|
|
314
322
|
const next = seat.stableSnapshot();
|
|
315
323
|
if (next) {
|
|
316
|
-
base = next;
|
|
324
|
+
base = next; // new cached prefix
|
|
317
325
|
sinceBase.length = 0;
|
|
318
326
|
}
|
|
319
327
|
}
|
|
@@ -382,6 +390,32 @@ reload prompt instead of a dead connection. A policy tripwire reports `ejected`.
|
|
|
382
390
|
slot for local problems such as a full storage quota or a dead worker; those are your own signals to
|
|
383
391
|
fold in, since `meshSync` only owns the connection side.
|
|
384
392
|
|
|
393
|
+
## Knowing a write landed
|
|
394
|
+
|
|
395
|
+
`health` and `status` describe the connection. They do not answer "is what I wrote in the room",
|
|
396
|
+
and a live socket with an unacknowledged tail answers no. Two members do:
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
mesh.acked(); // signal: every local write is acknowledged
|
|
400
|
+
await mesh.whenAcked(); // resolves when the tail empties
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
`whenAcked()` resolves immediately when nothing is outstanding and rejects with the terminal reason
|
|
404
|
+
if the session is ejected or closed while writes remain — those never reached the room, so every
|
|
405
|
+
later call rejects the same way and `acked()` stays `false`. Await it before publishing anything
|
|
406
|
+
that has to contain every edit; against a relay whose adapter confirms durability before echoing,
|
|
407
|
+
acknowledged also means stored. `agentSeat` exposes the same pair as plain functions.
|
|
408
|
+
|
|
409
|
+
The relay answers every write it neither echoes nor ejects, so the tail is always classified one
|
|
410
|
+
round trip after a welcome. A resend of a write the room already holds comes back as `duplicate`,
|
|
411
|
+
which is the acknowledgement. A refusal — `generation` (written before a cut), `schema` (an older
|
|
412
|
+
data shape), `order` (a version this origin never had admitted, which only a second tab on one
|
|
413
|
+
origin can produce) — means the write is not in the room and never will be: the client hands the
|
|
414
|
+
envelope to `onRefused` (its values are inside, so you can offer to write them again), rehydrates
|
|
415
|
+
from a fresh snapshot so the store shows the room, and rejects any pending `whenAcked()` with
|
|
416
|
+
`refused: <reason>`. `health().refusedWrites` counts them. "Every write was classified" and
|
|
417
|
+
"every write was stored" are different questions; `whenAcked()` answers the second.
|
|
418
|
+
|
|
385
419
|
## Schema versions
|
|
386
420
|
|
|
387
421
|
The data shape a room holds is a third version axis next to `proto` and `policyVersion`. Additive
|
|
@@ -16,7 +16,11 @@ function meshSession(opt) {
|
|
|
16
16
|
const acked = new Map();
|
|
17
17
|
const unackedKey = (env) => `${env.origin} ${env.version}`;
|
|
18
18
|
let lastSeq = 0;
|
|
19
|
-
let instance;
|
|
19
|
+
let instance = opt.instance;
|
|
20
|
+
if (instance)
|
|
21
|
+
sync.adopt(instance);
|
|
22
|
+
// a refusal asks for a fresh snapshot; one hello per burst, cleared by the welcome it earns
|
|
23
|
+
let rehydrating = false;
|
|
20
24
|
let peers = new Map();
|
|
21
25
|
let presenceData;
|
|
22
26
|
let hasPresence = false;
|
|
@@ -25,6 +29,16 @@ function meshSession(opt) {
|
|
|
25
29
|
let reconnectTimer;
|
|
26
30
|
let unsubs = [];
|
|
27
31
|
let closed = false;
|
|
32
|
+
let ackFailure;
|
|
33
|
+
const ackWaiters = [];
|
|
34
|
+
const releaseAckWaiters = (failure) => {
|
|
35
|
+
for (const waiter of ackWaiters.splice(0)) {
|
|
36
|
+
if (failure)
|
|
37
|
+
waiter.reject(failure);
|
|
38
|
+
else
|
|
39
|
+
waiter.resolve();
|
|
40
|
+
}
|
|
41
|
+
};
|
|
28
42
|
const setStatus = (next, reason) => {
|
|
29
43
|
status = next;
|
|
30
44
|
hooks.onStatus(next, reason);
|
|
@@ -41,6 +55,14 @@ function meshSession(opt) {
|
|
|
41
55
|
unsub();
|
|
42
56
|
unsubLocal();
|
|
43
57
|
hooks.onTerminal?.(state, reason); // unacked is still intact here — the persist window
|
|
58
|
+
if (unacked.size > 0) {
|
|
59
|
+
// these writes are not in the room and never will be on this session
|
|
60
|
+
ackFailure = new Error(reason ?? state);
|
|
61
|
+
releaseAckWaiters(ackFailure);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
releaseAckWaiters();
|
|
65
|
+
}
|
|
44
66
|
unacked.clear();
|
|
45
67
|
transport?.close();
|
|
46
68
|
transport = null;
|
|
@@ -49,7 +71,39 @@ function meshSession(opt) {
|
|
|
49
71
|
setStatus(state, reason);
|
|
50
72
|
};
|
|
51
73
|
const sendEnv = (env) => {
|
|
52
|
-
|
|
74
|
+
// an envelope minted before any generation was known adopts the one this session is in
|
|
75
|
+
let out = env;
|
|
76
|
+
if (env.instance === '' && instance) {
|
|
77
|
+
out = { ...env, instance };
|
|
78
|
+
unacked.set(unackedKey(env), out);
|
|
79
|
+
}
|
|
80
|
+
transport?.send({ t: 'env', room: opt.room, env: out });
|
|
81
|
+
};
|
|
82
|
+
const sendHello = () => {
|
|
83
|
+
transport?.send({
|
|
84
|
+
t: 'hello',
|
|
85
|
+
room: opt.room,
|
|
86
|
+
origin: sync.origin,
|
|
87
|
+
proto: MESH_PROTO_VERSION,
|
|
88
|
+
policyVersion: opt.policyVersion,
|
|
89
|
+
seq: lastSeq > 0 ? lastSeq : undefined,
|
|
90
|
+
schemaVersion: opt.schemaVersion,
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
const ackOwn = (origin, version) => {
|
|
94
|
+
if (!unacked.delete(unackedKey({ origin, version })))
|
|
95
|
+
return;
|
|
96
|
+
acked.set(origin, Math.max(acked.get(origin) ?? 0, version));
|
|
97
|
+
hooks.onOutboxChange?.();
|
|
98
|
+
if (unacked.size === 0)
|
|
99
|
+
releaseAckWaiters();
|
|
100
|
+
};
|
|
101
|
+
const refuse = (env, reason) => {
|
|
102
|
+
unacked.delete(unackedKey(env));
|
|
103
|
+
hooks.onRefused?.(env, reason);
|
|
104
|
+
hooks.onOutboxChange?.();
|
|
105
|
+
// "every write was classified" is not "every write was stored": a waiter rejects
|
|
106
|
+
releaseAckWaiters(new Error(`refused: ${reason}`));
|
|
53
107
|
};
|
|
54
108
|
const flushUnacked = () => {
|
|
55
109
|
for (const env of unacked.values())
|
|
@@ -67,9 +121,7 @@ function meshSession(opt) {
|
|
|
67
121
|
lastSeq = Math.max(lastSeq, env.seq);
|
|
68
122
|
hooks.onSynced?.();
|
|
69
123
|
if (ownOrigins.has(env.origin)) {
|
|
70
|
-
|
|
71
|
-
acked.set(env.origin, Math.max(acked.get(env.origin) ?? 0, env.version));
|
|
72
|
-
hooks.onOutboxChange?.();
|
|
124
|
+
ackOwn(env.origin, env.version);
|
|
73
125
|
return;
|
|
74
126
|
}
|
|
75
127
|
sync.receive(env);
|
|
@@ -82,9 +134,18 @@ function meshSession(opt) {
|
|
|
82
134
|
case 'welcome': {
|
|
83
135
|
const instanceChanged = instance !== undefined && msg.instance !== instance;
|
|
84
136
|
const prevSeq = lastSeq;
|
|
85
|
-
if (instanceChanged)
|
|
137
|
+
if (instanceChanged) {
|
|
138
|
+
// the generation boundary on the client: the tail written in the old one is refused
|
|
139
|
+
// loudly, its acknowledgements mean nothing here, and the new generation's snapshot
|
|
140
|
+
// replaces the whole applied state below
|
|
86
141
|
lastSeq = 0;
|
|
142
|
+
acked.clear();
|
|
143
|
+
for (const env of [...unacked.values()])
|
|
144
|
+
refuse(env, 'generation');
|
|
145
|
+
}
|
|
87
146
|
instance = msg.instance;
|
|
147
|
+
sync.adopt(msg.instance);
|
|
148
|
+
rehydrating = false;
|
|
88
149
|
peers = new Map(msg.peers.map((p) => [p.origin, p]));
|
|
89
150
|
hooks.onPeers?.(peers);
|
|
90
151
|
const resync = msg.mode === 'snapshot' || instanceChanged;
|
|
@@ -150,9 +211,26 @@ function meshSession(opt) {
|
|
|
150
211
|
case 'reject':
|
|
151
212
|
terminal('ejected', msg.reason);
|
|
152
213
|
return;
|
|
153
|
-
case '
|
|
154
|
-
sync.
|
|
214
|
+
case 'settled':
|
|
215
|
+
sync.settle(msg.settled);
|
|
216
|
+
return;
|
|
217
|
+
case 'drop': {
|
|
218
|
+
const held = unacked.get(unackedKey(msg));
|
|
219
|
+
if (!held)
|
|
220
|
+
return; // already classified (a duplicate reply after the echo, or an old generation's)
|
|
221
|
+
if (msg.reason === 'duplicate') {
|
|
222
|
+
ackOwn(msg.origin, msg.version); // the room holds it: this is the acknowledgement
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
refuse(held, msg.reason);
|
|
226
|
+
// the refused write is still applied locally: drop and rehydrate from a fresh snapshot
|
|
227
|
+
if (!rehydrating) {
|
|
228
|
+
rehydrating = true;
|
|
229
|
+
lastSeq = 0;
|
|
230
|
+
sendHello();
|
|
231
|
+
}
|
|
155
232
|
return;
|
|
233
|
+
}
|
|
156
234
|
}
|
|
157
235
|
};
|
|
158
236
|
const connect = () => {
|
|
@@ -176,18 +254,13 @@ function meshSession(opt) {
|
|
|
176
254
|
}, delay + Math.random() * 100);
|
|
177
255
|
}),
|
|
178
256
|
];
|
|
179
|
-
|
|
180
|
-
t: 'hello',
|
|
181
|
-
room: opt.room,
|
|
182
|
-
origin: sync.origin,
|
|
183
|
-
proto: MESH_PROTO_VERSION,
|
|
184
|
-
policyVersion: opt.policyVersion,
|
|
185
|
-
seq: lastSeq > 0 ? lastSeq : undefined,
|
|
186
|
-
schemaVersion: opt.schemaVersion,
|
|
187
|
-
});
|
|
257
|
+
sendHello();
|
|
188
258
|
};
|
|
189
259
|
const unsubLocal = sync.subscribe((env) => {
|
|
190
|
-
const violation = checkEnvelope(opt.policy, env, { ...opt.ctx, writer: opt.writer }, opt.room
|
|
260
|
+
const violation = checkEnvelope(opt.policy, env, { ...opt.ctx, writer: opt.writer }, opt.room,
|
|
261
|
+
// the last sequence this client observed; it can only lag the relay's, so a rule that
|
|
262
|
+
// keys off an empty room is at worst more permissive here than it is at the relay
|
|
263
|
+
{ seq: lastSeq });
|
|
191
264
|
if (violation) {
|
|
192
265
|
// same outcome the relay's own check would produce one hop later — the emit-side
|
|
193
266
|
// check is an optimization, never the enforcement
|
|
@@ -206,7 +279,15 @@ function meshSession(opt) {
|
|
|
206
279
|
status: () => status,
|
|
207
280
|
lastSeq: () => lastSeq,
|
|
208
281
|
hasUnacked: () => unacked.size > 0,
|
|
282
|
+
whenAcked: () => ackFailure
|
|
283
|
+
? Promise.reject(ackFailure)
|
|
284
|
+
: unacked.size === 0
|
|
285
|
+
? Promise.resolve()
|
|
286
|
+
: new Promise((resolve, reject) => {
|
|
287
|
+
ackWaiters.push({ resolve, reject });
|
|
288
|
+
}),
|
|
209
289
|
unackedEnvs: () => [...unacked.values()],
|
|
290
|
+
instance: () => instance,
|
|
210
291
|
peers: () => peers,
|
|
211
292
|
setPresence: (data) => {
|
|
212
293
|
presenceData = data;
|
|
@@ -268,6 +349,7 @@ function agentSeat(initial, opt) {
|
|
|
268
349
|
let welcomed = false;
|
|
269
350
|
let diverged = false;
|
|
270
351
|
let terminated = false;
|
|
352
|
+
let lostWrites = false;
|
|
271
353
|
const session = meshSession({
|
|
272
354
|
room: opt.room,
|
|
273
355
|
writer: opt.writer,
|
|
@@ -294,13 +376,19 @@ function agentSeat(initial, opt) {
|
|
|
294
376
|
emit({ kind: 'change', ...batch });
|
|
295
377
|
},
|
|
296
378
|
onResync: (seq) => emit({ kind: 'resync', seq }),
|
|
379
|
+
onRefused: (env, reason) => {
|
|
380
|
+
diverged = true; // the write stays applied until the rehydrate that follows lands
|
|
381
|
+
opt.onRefused?.(env, reason);
|
|
382
|
+
},
|
|
297
383
|
onLocalReject: (violation) => {
|
|
298
384
|
diverged = true; // the write stays in the replica but will never reach the room
|
|
299
385
|
console.warn('[@mmstack/mesh] agent seat write violates the room policy — not sent', violation);
|
|
300
386
|
},
|
|
301
387
|
onTerminal: () => {
|
|
302
|
-
if (session.hasUnacked())
|
|
388
|
+
if (session.hasUnacked()) {
|
|
303
389
|
diverged = true;
|
|
390
|
+
lostWrites = true; // latched: no echo can arrive for them now
|
|
391
|
+
}
|
|
304
392
|
terminated = true;
|
|
305
393
|
},
|
|
306
394
|
},
|
|
@@ -355,6 +443,14 @@ function agentSeat(initial, opt) {
|
|
|
355
443
|
rebase: recapture,
|
|
356
444
|
};
|
|
357
445
|
},
|
|
446
|
+
acked: () => {
|
|
447
|
+
sync.flush(); // a write made this tick counts as pending, not as unstamped
|
|
448
|
+
return !lostWrites && !session.hasUnacked();
|
|
449
|
+
},
|
|
450
|
+
whenAcked: () => {
|
|
451
|
+
sync.flush();
|
|
452
|
+
return session.whenAcked();
|
|
453
|
+
},
|
|
358
454
|
setPresence: (data) => session.setPresence(data),
|
|
359
455
|
sync: {
|
|
360
456
|
override: (fn) => sync.override(fn),
|
|
@@ -469,6 +565,8 @@ function meshSync(source, opt) {
|
|
|
469
565
|
const lastReason = signal(undefined, ...(ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []));
|
|
470
566
|
const lastSyncedAt = signal(undefined, ...(ngDevMode ? [{ debugName: "lastSyncedAt" }] : /* istanbul ignore next */ []));
|
|
471
567
|
const droppedOffline = signal(0, ...(ngDevMode ? [{ debugName: "droppedOffline" }] : /* istanbul ignore next */ []));
|
|
568
|
+
const acked = signal(true, ...(ngDevMode ? [{ debugName: "acked" }] : /* istanbul ignore next */ [])); // nothing has been written yet
|
|
569
|
+
const refused = signal(0, ...(ngDevMode ? [{ debugName: "refused" }] : /* istanbul ignore next */ []));
|
|
472
570
|
const droppedInvalid = signal(0, ...(ngDevMode ? [{ debugName: "droppedInvalid" }] : /* istanbul ignore next */ []));
|
|
473
571
|
const peerMap = signal(new Map(), ...(ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []));
|
|
474
572
|
const peers = computed(() => [...peerMap().values()], ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
|
|
@@ -479,6 +577,7 @@ function meshSync(source, opt) {
|
|
|
479
577
|
const invalid = droppedInvalid();
|
|
480
578
|
const extra = {
|
|
481
579
|
...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),
|
|
580
|
+
...(refused() > 0 ? { refusedWrites: refused() } : undefined),
|
|
482
581
|
...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),
|
|
483
582
|
};
|
|
484
583
|
switch (status()) {
|
|
@@ -506,10 +605,15 @@ function meshSync(source, opt) {
|
|
|
506
605
|
const doPersist = () => {
|
|
507
606
|
if (closed || !opt.outbox || !started || !session)
|
|
508
607
|
return;
|
|
608
|
+
const instance = session.instance();
|
|
609
|
+
const clock = sync.lastStamp();
|
|
509
610
|
const payload = {
|
|
510
611
|
origin: sync.origin,
|
|
511
612
|
version: sync.watermark()[sync.origin] ?? 0,
|
|
512
613
|
envs: session.unackedEnvs(),
|
|
614
|
+
...(instance ? { instance } : {}),
|
|
615
|
+
floors: sync.floors(),
|
|
616
|
+
...(clock ? { clock } : {}),
|
|
513
617
|
};
|
|
514
618
|
void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));
|
|
515
619
|
};
|
|
@@ -550,6 +654,7 @@ function meshSync(source, opt) {
|
|
|
550
654
|
return;
|
|
551
655
|
sync = opSync(source, {
|
|
552
656
|
writer: opt.writer,
|
|
657
|
+
instance: restore?.instance,
|
|
553
658
|
policies: opt.policies,
|
|
554
659
|
policyVersion,
|
|
555
660
|
injector,
|
|
@@ -571,8 +676,16 @@ function meshSync(source, opt) {
|
|
|
571
676
|
ctx: opt.ctx,
|
|
572
677
|
policyVersion,
|
|
573
678
|
schemaVersion: opt.schemaVersion,
|
|
679
|
+
instance: restore?.instance,
|
|
574
680
|
reconnect: opt.reconnect,
|
|
575
681
|
hooks: {
|
|
682
|
+
onRefused: (env, reason) => {
|
|
683
|
+
refused.update((n) => n + 1);
|
|
684
|
+
opt.onRefused?.(env, reason);
|
|
685
|
+
if (isDevMode()) {
|
|
686
|
+
console.warn(`[@mmstack/mesh] the relay refused a write (${reason}); it is not in the room and the store was rehydrated`);
|
|
687
|
+
}
|
|
688
|
+
},
|
|
576
689
|
onStatus: (s, reason) => {
|
|
577
690
|
if (s === 'ejected' || s === 'closed') {
|
|
578
691
|
closed = true;
|
|
@@ -585,9 +698,16 @@ function meshSync(source, opt) {
|
|
|
585
698
|
},
|
|
586
699
|
onSynced: () => lastSyncedAt.set(Date.now()),
|
|
587
700
|
onPeers: (map) => peerMap.set(map),
|
|
588
|
-
onOutboxChange: () =>
|
|
701
|
+
onOutboxChange: () => {
|
|
702
|
+
persistOutbox();
|
|
703
|
+
acked.set(!session?.hasUnacked());
|
|
704
|
+
},
|
|
589
705
|
onTerminal: () => {
|
|
590
706
|
dropLocks();
|
|
707
|
+
// latched: the tail is about to be dropped from the session, but it was never
|
|
708
|
+
// acknowledged, so the answer to "is everything I wrote in the room" stays no
|
|
709
|
+
if (session?.hasUnacked())
|
|
710
|
+
acked.set(false);
|
|
591
711
|
persistOutbox(true); // save the still-unacked tail for the next boot before dropping it
|
|
592
712
|
},
|
|
593
713
|
onLocalReject: (violation) => {
|
|
@@ -606,7 +726,7 @@ function meshSync(source, opt) {
|
|
|
606
726
|
console.warn(`[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`);
|
|
607
727
|
}
|
|
608
728
|
}
|
|
609
|
-
sync.restore(kept, restore.version); // → the session's subscribe repopulates its unacked tail for resend
|
|
729
|
+
sync.restore(kept, restore.version, restore.floors, restore.clock); // → the session's subscribe repopulates its unacked tail for resend
|
|
610
730
|
}
|
|
611
731
|
persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe
|
|
612
732
|
if (pendingPresence) {
|
|
@@ -714,6 +834,8 @@ function meshSync(source, opt) {
|
|
|
714
834
|
return {
|
|
715
835
|
status: status.asReadonly(),
|
|
716
836
|
health,
|
|
837
|
+
acked: acked.asReadonly(),
|
|
838
|
+
whenAcked: () => (session ? session.whenAcked() : Promise.resolve()), // nothing written yet
|
|
717
839
|
peers,
|
|
718
840
|
setPresence: (data) => {
|
|
719
841
|
if (session)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mmstack-mesh.mjs","sources":["../../../../../packages/mesh/client/src/lib/session.ts","../../../../../packages/mesh/client/src/lib/agent-seat.ts","../../../../../packages/mesh/client/src/lib/mesh-sync.ts","../../../../../packages/mesh/client/src/lib/transport.ts","../../../../../packages/mesh/client/src/lib/webrtc-mesh.ts","../../../../../packages/mesh/client/src/mmstack-mesh.ts"],"sourcesContent":["import {\n checkEnvelope,\n MESH_PROTO_VERSION,\n type OpPolicy,\n type PolicyViolation,\n type PresenceState,\n type PrincipalCtx,\n type SeqEnvelope,\n type ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n createConvergingApply,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type StoreOp,\n} from '@mmstack/primitives/core';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\nexport type MeshStatus =\n 'connecting' | 'live' | 'reconnecting' | 'ejected' | 'closed';\n\n/** One sequenced remote envelope's ops, attributed to the writer that made them. */\nexport type RemoteBatch = {\n /** The relay's total-order stamp for this batch. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Environment callbacks a session shell provides. All are optional except `onStatus`; the\n * session never touches signals, timers beyond `schedule`, storage, or the DOM itself.\n */\nexport type MeshSessionHooks = {\n onStatus(status: MeshStatus, reason?: string): void;\n /** A welcome or envelope arrived — the shell's \"last synced\" moment. */\n onSynced?(): void;\n /** The presence roster changed (welcome replace, join/leave, teardown clear). */\n onPeers?(peers: ReadonlyMap<string, PresenceState>): void;\n /** A remote (non-own) envelope was ingested, in seq order. */\n onRemote?(batch: RemoteBatch): void;\n /**\n * Seq continuity broke: a snapshot welcome (or a relay instance change) established state\n * without delivering the individual envelopes in between. Any consumer deriving from the\n * `onRemote` stream must rebuild from current state at this seq; appending across a resync\n * would silently skip history.\n */\n onResync?(seq: number): void;\n /** The unacknowledged local tail changed (emit or ack) — the durable-outbox trigger. */\n onOutboxChange?(): void;\n /**\n * A local write violated the room policy. The session ejects itself immediately after —\n * the outcome the relay's own independent check would have produced one hop later. The\n * emit-side check spares the room the round trip; it is never the enforcement.\n */\n onLocalReject?(violation: PolicyViolation): void;\n /**\n * Teardown is starting; fired before the unacked tail is dropped, so a shell can persist\n * it (and release any single-writer locks) while it is still intact.\n */\n onTerminal?(state: 'ejected' | 'closed', reason?: string): void;\n};\n\nexport type MeshSessionOptions<T extends object> = {\n readonly room: string;\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** The op engine this session feeds. The shell creates (and destroys) it. */\n readonly sync: OpSync<T>;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policy?: OpPolicy;\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion: number;\n readonly schemaVersion?: number;\n readonly reconnect?: { readonly maxDelayMs?: number };\n /** Timer seam (tests, deterministic harnesses). Defaults to global timers. */\n readonly schedule?: {\n set(fn: () => void, ms: number): unknown;\n clear(handle: unknown): void;\n };\n readonly hooks: MeshSessionHooks;\n};\n\n/**\n * The relay-room session protocol, shell-agnostic: hello/welcome handshakes (snapshot\n * hydrate, delta replay, fresh-room seed), own-echo acknowledgement, unacked resend,\n * reconnect backoff, presence, eject/reject and frontier compaction. `meshSync` wraps it for\n * Angular; `agentSeat` wraps it for injector-free environments. One implementation of the\n * wire contract — shells differ only in environment concerns.\n */\nexport type MeshSession = {\n /** Open the first connection. Call once, after any outbox restore has replayed. */\n connect(): void;\n status(): MeshStatus;\n /** Highest relay seq observed. With no unacked writes, local state is the pure fold of the room at this seq. */\n lastSeq(): number;\n hasUnacked(): boolean;\n /** The unacknowledged local tail (the durable-outbox payload). */\n unackedEnvs(): readonly OpEnvelope[];\n peers(): ReadonlyMap<string, PresenceState>;\n setPresence(data: unknown): void;\n close(): void;\n};\n\nconst RECONNECT_BASE_MS = 500;\n\nexport function meshSession<T extends object>(\n opt: MeshSessionOptions<T>,\n): MeshSession {\n const { sync, hooks } = opt;\n const schedule = opt.schedule ?? {\n set: (fn: () => void, ms: number) => setTimeout(fn, ms),\n clear: (handle: unknown) =>\n clearTimeout(handle as ReturnType<typeof setTimeout>),\n };\n\n let status: MeshStatus = 'connecting';\n const ownOrigins = new Set<string>([sync.origin]);\n const unacked = new Map<string, OpEnvelope>();\n const acked = new Map<string, number>();\n const unackedKey = (env: { origin: string; version: number }): string =>\n `${env.origin} ${env.version}`;\n let lastSeq = 0;\n let instance: string | undefined;\n let peers: ReadonlyMap<string, PresenceState> = new Map();\n let presenceData: unknown;\n let hasPresence = false;\n let transport: MeshTransport | null = null;\n let attempts = 0;\n let reconnectTimer: unknown;\n let unsubs: (() => void)[] = [];\n let closed = false;\n\n const setStatus = (next: MeshStatus, reason?: string): void => {\n status = next;\n hooks.onStatus(next, reason);\n };\n\n const terminal = (state: 'ejected' | 'closed', reason?: string): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) {\n schedule.clear(reconnectTimer);\n reconnectTimer = undefined;\n }\n for (const unsub of unsubs.splice(0)) unsub();\n unsubLocal();\n hooks.onTerminal?.(state, reason); // unacked is still intact here — the persist window\n unacked.clear();\n transport?.close();\n transport = null;\n peers = new Map();\n hooks.onPeers?.(peers);\n setStatus(state, reason);\n };\n\n const sendEnv = (env: OpEnvelope): void => {\n transport?.send({ t: 'env', room: opt.room, env });\n };\n\n const flushUnacked = (): void => {\n for (const env of unacked.values()) sendEnv(env);\n };\n\n const applyRemote = (env: SeqEnvelope): void => {\n if (closed) return; // a delta welcome keeps iterating after an eject — nothing lands past it\n\n if (\n opt.schemaVersion !== undefined &&\n env.schemaVersion !== undefined &&\n env.schemaVersion > opt.schemaVersion\n ) {\n terminal('ejected', 'schema');\n return;\n }\n lastSeq = Math.max(lastSeq, env.seq);\n hooks.onSynced?.();\n if (ownOrigins.has(env.origin)) {\n unacked.delete(unackedKey(env));\n acked.set(env.origin, Math.max(acked.get(env.origin) ?? 0, env.version));\n hooks.onOutboxChange?.();\n return;\n }\n sync.receive(env);\n hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });\n };\n\n const handle = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome': {\n const instanceChanged =\n instance !== undefined && msg.instance !== instance;\n\n const prevSeq = lastSeq;\n if (instanceChanged) lastSeq = 0;\n instance = msg.instance;\n peers = new Map(msg.peers.map((p) => [p.origin, p]));\n hooks.onPeers?.(peers);\n const resync = msg.mode === 'snapshot' || instanceChanged;\n if (msg.mode === 'delta') {\n for (const env of msg.envs) applyRemote(env);\n } else if (msg.mode === 'snapshot') {\n const conv = createConvergingApply({ policies: opt.policies });\n conv.load(msg.registers);\n const ownWm: Record<string, number> = {};\n for (const o of ownOrigins) ownWm[o] = acked.get(o) ?? 0;\n sync.hydrate(\n {\n root: conv.materialize() as T,\n registers: msg.registers,\n wm: { ...msg.wm, ...ownWm },\n },\n [...unacked.values()],\n );\n lastSeq = msg.seq;\n } else if (msg.seq === 0 && lastSeq === 0) {\n sync.seed();\n }\n // every branch can end terminal (schema eject in a delta env, a seed or rebase\n // emission tripping the emit-side policy) — never revive to live\n if (closed) {\n if (instanceChanged && lastSeq === 0) lastSeq = prevSeq;\n return;\n }\n lastSeq = Math.max(lastSeq, msg.seq);\n attempts = 0;\n hooks.onSynced?.();\n if (resync) hooks.onResync?.(lastSeq);\n setStatus('live');\n flushUnacked();\n if (hasPresence)\n transport?.send({\n t: 'presence',\n room: opt.room,\n data: presenceData,\n });\n return;\n }\n case 'env':\n applyRemote(msg.env);\n return;\n case 'presence': {\n const next = new Map(peers);\n if (msg.gone) next.delete(msg.peer.origin);\n else next.set(msg.peer.origin, msg.peer);\n peers = next;\n hooks.onPeers?.(peers);\n return;\n }\n case 'eject':\n if (msg.writer === opt.writer) terminal('ejected', msg.reason);\n return;\n case 'reject':\n terminal('ejected', msg.reason);\n return;\n case 'frontier':\n sync.prune(msg.frontier);\n return;\n }\n };\n\n const connect = (): void => {\n if (closed) return;\n for (const unsub of unsubs.splice(0)) unsub();\n const t = opt.transport();\n transport = t;\n unsubs = [\n t.onMessage(handle),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n setStatus('reconnecting');\n const delay = Math.min(\n opt.reconnect?.maxDelayMs ?? 15_000,\n RECONNECT_BASE_MS * 2 ** attempts++,\n );\n reconnectTimer = schedule.set(\n () => {\n reconnectTimer = undefined;\n connect();\n },\n delay + Math.random() * 100,\n );\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion,\n seq: lastSeq > 0 ? lastSeq : undefined,\n schemaVersion: opt.schemaVersion,\n });\n };\n\n const unsubLocal = sync.subscribe((env) => {\n const violation = checkEnvelope(\n opt.policy,\n env,\n { ...opt.ctx, writer: opt.writer },\n opt.room,\n );\n if (violation) {\n // same outcome the relay's own check would produce one hop later — the emit-side\n // check is an optimization, never the enforcement\n hooks.onLocalReject?.(violation);\n terminal('ejected', violation.reason);\n return;\n }\n ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim\n unacked.set(unackedKey(env), env);\n hooks.onOutboxChange?.();\n if (status === 'live') sendEnv(env);\n });\n\n return {\n connect,\n status: () => status,\n lastSeq: () => lastSeq,\n hasUnacked: () => unacked.size > 0,\n unackedEnvs: () => [...unacked.values()],\n peers: () => peers,\n setPresence: (data) => {\n presenceData = data;\n hasPresence = true;\n if (status === 'live') {\n transport?.send({ t: 'presence', room: opt.room, data });\n }\n },\n close: () => terminal('closed'),\n };\n}\n","import { createWatch } from '@angular/core/primitives/signals';\nimport type {\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n createStoreContext,\n forkStore,\n opSync,\n store,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpLogDriver,\n type OpSync,\n type StoreOp,\n type SyncedFork,\n type toStoreOptions,\n type WritableSignalStore,\n} from '@mmstack/primitives/core';\nimport type { SeatSync } from './mesh-sync';\nimport { meshSession, type MeshStatus } from './session';\nimport type { MeshTransportFactory } from './transport';\n\nconst microtaskDriver = (): OpLogDriver => (run) => {\n let scheduled = false;\n const watch = createWatch(\n () => run(),\n (w) => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n w.run();\n });\n },\n false,\n );\n watch.notify();\n return { destroy: () => watch.destroy() };\n};\n\n/** A sequenced batch of another writer's ops, delivered in relay order. */\nexport type SeatChange = {\n readonly kind: 'change';\n /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past\n * the relay's retention, or a relay restart) without seeing the individual changes in\n * between. Anything accumulated from prior `change` events — narration buffers, cached\n * prompt prefixes — no longer extends the stream and must be rebuilt from current state.\n */\nexport type SeatResync = {\n readonly kind: 'resync';\n /** The seq the re-established state corresponds to. */\n readonly seq: number;\n};\n\nexport type SeatEvent = SeatChange | SeatResync;\n\n/** A base state provably derivable from the room's history alone — safe to cache. */\nexport type StableSnapshot<T> = {\n /** The relay seq this state is the fold of. */\n readonly seq: number;\n readonly doc: T;\n};\n\nexport type AgentSeatOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. One identity per seat. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /**\n * Emit-side validation, symmetric with the relay's — an optimization, not the\n * enforcement (the relay validates every envelope regardless). A violating write is\n * never sent and ejects the seat exactly as the relay would have; the refused value\n * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.\n */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion?: number;\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n /**\n * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;\n * pass your own to share proxy caches across several seats in one process.\n */\n readonly context?: toStoreOptions;\n readonly onEject?: (reason: string) => void;\n};\n\nexport type AgentSeat<T extends object> = {\n /** The live converging replica. Reads exactly like a local signal store. */\n readonly doc: WritableSignalStore<T & Record<string, any>>;\n status(): MeshStatus;\n peers(): readonly PresenceState[];\n /** The current document value — plain JSON-serializable data, for context assembly. */\n snapshot(): T;\n /**\n * The current document, stamped with the relay seq it is provably the pure fold of\n * or null when stability cannot be guaranteed\n */\n stableSnapshot(): StableSnapshot<T> | null;\n /** Run local writes and emit them to the room as one envelope, like any peer's edit. */\n write(fn: () => void): void;\n /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */\n setAtPath(path: string | readonly (string | number)[], value: unknown): void;\n /**\n * The room's sequenced history as it arrives: `change` events carry another writer's ops\n * in strictly increasing seq order, so a listener may append them (narration, prompt\n * suffixes) without any diffing. A `resync` event voids that guarantee — everything\n * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).\n * Own writes never echo here.\n */\n changes(cb: (event: SeatEvent) => void): () => void;\n /**\n * An isolated branch for a reviewable proposal. The fork observes the room as it is now;\n * `commit()` emits its diff citing only those observed writes, so a room edit that lands\n * while the fork is open survives as a concurrent value for the merge policy to resolve\n * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the\n * staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */\n setPresence(data: unknown): void;\n /** Authority surface over this seat's op-sync; see {@link SeatSync}. */\n readonly sync: SeatSync<T>;\n close(): void;\n};\n\n/**\n * A headless mesh peer: the same replica and wire contract `meshSync` implements in the\n * browser, without Angular's injector or any browser API — for agents, server-side bridges,\n * and device writers joining a room as first-class, attributed participants. Each call is\n * one identity with its own replica; run several seats in one process for several\n * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as\n * to any human peer.\n */\nexport function agentSeat<T extends object>(\n initial: T,\n opt: AgentSeatOptions,\n): AgentSeat<T> {\n const context = opt.context ?? createStoreContext();\n const root = store(initial as T & Record<string, any>, context);\n const doc = root as unknown as WritableSignalStore<T & Record<string, any>>;\n const read = root as unknown as () => T;\n const policyVersion = opt.policyVersion ?? 0;\n\n // onReject fires synchronously inside receive(); the flag keeps a malformed envelope's\n // ops (which did NOT apply) out of the change stream.\n let rejected = false;\n const sync = opSync(root as never, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion,\n driver: microtaskDriver(),\n onReject: (_env, reason) => {\n rejected = true;\n console.warn(\n `[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`,\n );\n },\n }) as OpSync<T>;\n\n const listeners = new Set<(event: SeatEvent) => void>();\n const emit = (event: SeatEvent): void => {\n for (const cb of [...listeners]) cb(event);\n };\n let welcomed = false;\n let diverged = false;\n let terminated = false;\n\n const session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n reconnect: opt.reconnect,\n hooks: {\n onStatus: (s, reason) => {\n if (s === 'live') welcomed = true;\n if (s === 'ejected' && reason !== undefined) opt.onEject?.(reason);\n },\n onRemote: (batch) => {\n if (rejected) {\n rejected = false;\n return;\n }\n emit({ kind: 'change', ...batch });\n },\n onResync: (seq) => emit({ kind: 'resync', seq }),\n onLocalReject: (violation) => {\n diverged = true; // the write stays in the replica but will never reach the room\n console.warn(\n '[@mmstack/mesh] agent seat write violates the room policy — not sent',\n violation,\n );\n },\n onTerminal: () => {\n if (session.hasUnacked()) diverged = true;\n terminated = true;\n },\n },\n });\n // a write after the terminal state is one the room will never sequence: the doc keeps it\n // (post-mortem), but the seat stops claiming provable folds — same latch as a refused write\n sync.subscribe(() => {\n if (terminated) diverged = true;\n });\n session.connect();\n\n return {\n doc,\n status: () => session.status(),\n peers: () => [...session.peers().values()],\n snapshot: () => read(),\n stableSnapshot: () => {\n sync.flush(); // a write made this tick must count as pending, not linger unstamped\n if (!welcomed || diverged || session.hasUnacked()) return null;\n return { seq: session.lastSeq(), doc: read() };\n },\n write: (fn) => {\n fn();\n sync.flush();\n },\n setAtPath: (path, value) => {\n setAtPath(doc, path, value);\n sync.flush();\n },\n changes: (cb) => {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n fork: (forkOpt) => {\n const f = forkStore(doc, forkOpt);\n let frontier: DotFrontier = sync.captureFrontier();\n const recapture = (): void => {\n frontier = sync.captureFrontier();\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () => {\n sync.commitScope(frontier, () => f.commit());\n sync.flush();\n },\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n setPresence: (data) => session.setPresence(data),\n sync: {\n override: (fn) => sync.override(fn),\n captureFrontier: () => sync.captureFrontier(),\n commitScope: (frontier, fn) => sync.commitScope(frontier, fn),\n liveUnder: (path) => sync.liveUnder(path),\n liveAt: (path) => sync.liveAt(path),\n appliedFrontier: () => sync.appliedFrontier(),\n },\n close: () => {\n diverged = true; // sync is destroyed below: later writes are unwatched, so no more proofs\n session.close();\n sync.destroy();\n },\n };\n}\n\ntype PathSegment = string | number;\n\nconst parsePath = (\n path: string | readonly PathSegment[],\n): readonly PathSegment[] =>\n typeof path === 'string' ? path.split('.').filter((s) => s !== '') : path;\n\n// resolve a string segment against an array ('0' → 0) so dot-paths address list items\nconst resolveKey = (current: unknown, seg: PathSegment): PathSegment =>\n Array.isArray(current) && typeof seg === 'string' && /^\\d+$/.test(seg)\n ? Number(seg)\n : seg;\n\nfunction withPathSet(\n current: unknown,\n path: readonly PathSegment[],\n value: unknown,\n): unknown {\n if (path.length === 0) return value;\n const [head, ...rest] = path;\n if (Array.isArray(current)) {\n const idx = typeof head === 'number' ? head : Number(head);\n const copy = [...current];\n copy[idx] = withPathSet(current[idx], rest, value);\n return copy;\n }\n const base =\n current !== null && typeof current === 'object'\n ? (current as Record<PathSegment, unknown>)\n : {};\n return { ...base, [head]: withPathSet(base[head], rest, value) };\n}\n\n/**\n * Applies `value` at a path on a signal-store node — the write shape a tool-calling model\n * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as\n * the path exists in the current value and finishes with one immutable set on the deepest\n * real node, which also covers paths that do not exist yet (a fresh record key creates it).\n * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer\n * `seat.setAtPath`, which also emits immediately.\n */\nexport function setAtPath(\n node: unknown,\n path: string | readonly PathSegment[],\n value: unknown,\n): void {\n const segs = parsePath(path);\n let cursor = node as Record<PathSegment, unknown> & {\n (): unknown;\n set(v: unknown): void;\n };\n let walked = 0;\n for (const seg of segs) {\n const current = cursor();\n if (current === null || typeof current !== 'object') break;\n const key = resolveKey(current, seg);\n if (!Object.hasOwn(current, key)) break;\n const child = cursor[key];\n if (typeof child !== 'function') break;\n cursor = child as typeof cursor;\n walked++;\n }\n const rest = segs.slice(walked);\n if (rest.length === 0) {\n cursor.set(value);\n return;\n }\n cursor.set(withPathSet(cursor(), rest, value));\n}\n\nconst MAX_VALUE_CHARS = 120;\n\nconst printable = (value: unknown): string => {\n const json = JSON.stringify(value);\n if (json === undefined) return String(value);\n return json.length > MAX_VALUE_CHARS\n ? `${json.slice(0, MAX_VALUE_CHARS - 1)}…`\n : json;\n};\n\n/**\n * One store op as a plain-English line (\"mira set plan.endDate to \\\"2026-10-11\\\"\"), for\n * activity feeds and model context. Values render as truncated JSON. Pair with a seat's\n * `changes` stream: narrating each batch's ops yields an append-only account of the room.\n */\nexport function describeOp(op: StoreOp, writer: string): string {\n const at = op.path.length === 0 ? 'the document root' : op.path.join('.');\n switch (op.kind) {\n case 'set':\n return `${writer} set ${at} to ${printable(op.next)}`;\n case 'delete':\n return `${writer} removed ${at}`;\n case 'clear':\n return `${writer} cleared ${at}`;\n }\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n runInInjectionContext,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport type {\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n forkStore,\n OP_PROTO_VERSION,\n opSync,\n registerResource,\n type AsyncStore,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type ResourceLike,\n type SyncedFork,\n type SyncOp,\n type WritableSignalStore,\n} from '@mmstack/primitives/core';\nimport { meshSession, type MeshSession, type MeshStatus } from './session';\nimport type { MeshTransportFactory } from './transport';\n\nexport type { MeshStatus } from './session';\n\nexport type MeshPeer = PresenceState;\n\n/**\n * A composed, user-facing health status for a synced store the surface that\n * turns a versioned reject from a dead socket into a speakable 'outdated' banner.\n */\nexport type SyncHealthStatus =\n 'live' | 'offline' | 'outdated' | 'ejected' | 'degraded';\n\nexport type SyncHealth = {\n readonly status: SyncHealthStatus;\n /** Why, when the status is `outdated`/`ejected`/`degraded`. */\n readonly reason?:\n 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | (string & {});\n /** `Date.now()` of the last successful sync (welcome or applied env). */\n readonly lastSyncedAt?: number;\n /**\n * Offline writes persisted by an older build that could not be restored on boot. Envelopes\n * from a previous wire-protocol version lack the citation metadata current merging needs,\n * so they are dropped (loudly) instead of being upgraded with fabricated citations.\n */\n readonly droppedOfflineWrites?: number;\n /**\n * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id\n * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a\n * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line\n * against a malformed neighbor; through a relay these are also rejected at the relay.\n */\n readonly droppedInvalidEnvelopes?: number;\n};\n\n// a versioned reject means \"your build is behind\" → prompt an update, not a dead socket\nconst OUTDATED_REASONS: ReadonlySet<string> = new Set([\n 'proto',\n 'policy-version',\n 'schema',\n]);\n\nexport type MeshSyncOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /** Emit-side validation, symmetric with the relay's (tripwire honesty). */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n /**\n * The room's shared configuration pin, checked at hello against the relay's. Bump it\n * together whenever anything peers must agree on changes: the write policy, and just as\n * importantly the merge/fold configuration (`policies`). Peers folding the same register\n * state with different rules read different values, so one room means one fold config; a\n * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.\n */\n readonly policyVersion?: number;\n /** The data shape this client speaks. Older-than-room → `outdated`, and a\n * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n readonly injector?: Injector;\n /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */\n readonly register?: 'track' | 'suspend';\n readonly onEject?: (reason: string) => void;\n /**\n * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects\n * (and before it restores an `outbox`), so a store hydrated from another source first (a worker\n * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.\n * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base\n * that fails to load never wedges the connection.\n */\n readonly whenReady?: () => PromiseLike<void> | void;\n /**\n * Persist the unacknowledged local outbox (and this client's stable origin) so offline writes\n * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room\n * on the next welcome, instead of being lost with in-memory state. The payload is written to\n * `store` under `key`, debounced.\n *\n * By default (`crossTab: 'queue'`) a Web Lock on `key` makes this a single-writer-per-key resource:\n * a second tab sharing the key WAITS (stays `connecting`, surfaced via `status`/`health`) until the\n * first releases, rather than restoring the same origin and colliding on version mints. Set\n * `crossTab: 'off'` to skip the lock and coordinate ownership yourself (e.g. a per-tab key, or\n * leader election over `tabSync`). A debounced write means a hard crash within the debounce window\n * can drop the very last mint — a small, best-effort gap; tune it with `debounceMs`.\n */\n readonly outbox?: {\n readonly key: string;\n readonly store: AsyncStore;\n /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */\n readonly debounceMs?: number;\n /**\n * Cross-tab contention for the shared `key`. `'queue'` (default) holds a Web Lock so only one tab\n * owns the durable outbox at a time; others wait. `'off'` skips the lock (you coordinate).\n * (A future `'ephemeral'` — non-leaders run live with a throwaway origin — is planned.)\n */\n readonly crossTab?: 'queue' | 'off';\n };\n};\n\n/** The shape persisted under `outbox.key`: the stable origin, the emit high-water, and the tail. */\ntype PersistedOutbox = {\n readonly origin: string;\n readonly version: number;\n readonly envs: readonly OpEnvelope[];\n};\n\n/**\n * The authority surface of a peer's op-sync, for callers that compose over a seat rather than\n * inside it: `override` for authority-bumped writes (`rebalanceContainer`, an owner's\n * authoritative commit), `captureFrontier` + `commitScope` for a commit that cites what was\n * observed earlier (a fork whose base is kept elsewhere), `liveUnder` / `liveAt` to read live\n * registers and `appliedFrontier` for the observation vector they are compared against (a\n * conflict projection: \"did the writer see this sibling\", answered by causality, never by order).\n * Deliberately narrow: no `receive`, `flush`, or `destroy` — those stay the seat's own.\n */\nexport type SeatSync<T = unknown> = Pick<\n OpSync<T>,\n | 'override'\n | 'captureFrontier'\n | 'commitScope'\n | 'liveUnder'\n | 'liveAt'\n | 'appliedFrontier'\n>;\n\nexport type MeshSyncRef<T extends object = Record<string, unknown>> = {\n readonly status: Signal<MeshStatus>;\n /** Composed sync-health for a user-facing surface. */\n readonly health: Signal<SyncHealth>;\n readonly peers: Signal<readonly MeshPeer[]>;\n /** Publish this client's ephemeral presence payload (cursor, section, activity…). */\n setPresence(data: unknown): void;\n /**\n * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The\n * fork observes the room as it is now; committing emits its diff citing only those observed\n * writes, so an edit that lands on the room while the fork is open stays a concurrent value the\n * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe\n * the room and commit on top of the latest instead. `discard()` drops the staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */\n readonly sync: SeatSync<T>;\n close(): void;\n};\n\nconst OUTBOX_DEBOUNCE_MS = 300;\n\n/**\n * Replicates a signal store across clients through a relay room: local writes emit stamped\n * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot\n * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.\n * A synced store reads exactly like a local one — connection state surfaces only through\n * `status` and the transition scope.\n */\nexport function meshSync<T extends object>(\n source: WritableSignal<T>,\n opt: MeshSyncOptions,\n): MeshSyncRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const status = signal<MeshStatus>('connecting');\n const lastReason = signal<string | undefined>(undefined);\n const lastSyncedAt = signal<number | undefined>(undefined);\n const droppedOffline = signal(0);\n const droppedInvalid = signal(0);\n const peerMap = signal<ReadonlyMap<string, MeshPeer>>(new Map());\n const peers = computed(() => [...peerMap().values()]);\n const policyVersion = opt.policyVersion ?? 0;\n\n const health = computed<SyncHealth>(() => {\n const at = lastSyncedAt();\n const dropped = droppedOffline();\n const invalid = droppedInvalid();\n const extra = {\n ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),\n ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),\n };\n switch (status()) {\n case 'live':\n return { status: 'live', lastSyncedAt: at, ...extra };\n case 'ejected': {\n const reason = lastReason();\n return reason && OUTDATED_REASONS.has(reason)\n ? { status: 'outdated', reason, lastSyncedAt: at, ...extra }\n : { status: 'ejected', reason, lastSyncedAt: at, ...extra };\n }\n default: // connecting / reconnecting / closed — not reachable\n return { status: 'offline', lastSyncedAt: at, ...extra };\n }\n });\n\n // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything\n let sync!: OpSync<T>;\n let session: MeshSession | undefined;\n let started = false;\n let closed = false;\n let pendingPresence: { data: unknown } | undefined;\n let persistTimer: ReturnType<typeof setTimeout> | undefined;\n let releaseLock: (() => void) | undefined;\n let cancelLock: (() => void) | undefined;\n\n const doPersist = (): void => {\n if (closed || !opt.outbox || !started || !session) return;\n const payload: PersistedOutbox = {\n origin: sync.origin,\n version: sync.watermark()[sync.origin] ?? 0,\n envs: session.unackedEnvs(),\n };\n void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));\n };\n // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)\n const persistOutbox = (immediate = false): void => {\n if (!opt.outbox) return;\n if (immediate) {\n if (persistTimer !== undefined) clearTimeout(persistTimer);\n persistTimer = undefined;\n doPersist();\n return;\n }\n if (persistTimer !== undefined) return;\n persistTimer = setTimeout(() => {\n persistTimer = undefined;\n doPersist();\n }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);\n };\n\n const dropLocks = (): void => {\n cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown\n releaseLock?.(); // free a held lock for the next waiting tab\n cancelLock = releaseLock = undefined;\n };\n\n // Only a tail this boot could actually get admitted is worth resending: recorded under\n // this writer, on the current proto and policyVersion pins (the relay rejects a stale pin\n // per envelope, so restoring one would eject the boot, persist the tail intact, and brick\n // every boot after). Anything else drops loudly instead.\n const restorable = (env: OpEnvelope): boolean =>\n env.proto === OP_PROTO_VERSION &&\n env.writer === opt.writer &&\n env.policyVersion === policyVersion &&\n env.ops.every(\n (op) =>\n Array.isArray((op as SyncOp).cites) &&\n typeof (op as SyncOp).epoch === 'number',\n );\n\n const initCore = (restore?: PersistedOutbox): void => {\n if (closed) return;\n sync = opSync(source, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion,\n injector,\n onReject: (_env, reason) => {\n droppedInvalid.update((n) => n + 1);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`,\n );\n }\n },\n });\n started = true;\n session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n reconnect: opt.reconnect,\n hooks: {\n onStatus: (s, reason) => {\n if (s === 'ejected' || s === 'closed') {\n closed = true;\n lastReason.set(reason);\n }\n status.set(s);\n if ((s === 'ejected' || s === 'closed') && reason !== undefined) {\n opt.onEject?.(reason);\n }\n },\n onSynced: () => lastSyncedAt.set(Date.now()),\n onPeers: (map) => peerMap.set(map),\n onOutboxChange: () => persistOutbox(),\n onTerminal: () => {\n dropLocks();\n persistOutbox(true); // save the still-unacked tail for the next boot before dropping it\n },\n onLocalReject: (violation) => {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] local write violates the room policy — not sent',\n violation,\n );\n }\n },\n },\n });\n if (restore && (restore.envs.length > 0 || restore.version > 0)) {\n const kept = restore.envs.filter(restorable);\n const dropped = restore.envs.length - kept.length;\n if (dropped > 0) {\n droppedOffline.set(dropped);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`,\n );\n }\n }\n\n sync.restore(kept, restore.version); // → the session's subscribe repopulates its unacked tail for resend\n }\n persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe\n if (pendingPresence) {\n session.setPresence(pendingPresence.data);\n pendingPresence = undefined;\n }\n session.connect();\n };\n\n if (opt.register) {\n const connection: ResourceLike = {\n status: computed(() => {\n const s = status();\n return s === 'connecting'\n ? 'loading'\n : s === 'reconnecting'\n ? 'reloading'\n : s === 'ejected'\n ? 'error'\n : 'resolved';\n }),\n isLoading: computed(\n () => status() === 'connecting' || status() === 'reconnecting',\n ),\n hasValue: () => true,\n };\n runInInjectionContext(injector, () =>\n registerResource(connection, { suspends: opt.register === 'suspend' }),\n );\n }\n\n const teardown = (): void => {\n if (session) {\n session.close(); // no-op if already terminal; onTerminal handled locks + persist\n } else if (!closed) {\n // closed before the (async) boot ever created the session\n closed = true;\n dropLocks();\n status.set('closed');\n }\n if (started) sync.destroy();\n };\n\n injector.get(DestroyRef).onDestroy(teardown);\n\n // Load the persisted outbox, then boot with the adopted origin. A fresh/unreadable slot boots clean.\n const bootFromDisk = async (): Promise<void> => {\n if (closed || !opt.outbox) return;\n let saved: PersistedOutbox | undefined;\n try {\n const raw = await opt.outbox.store.get(opt.outbox.key);\n saved =\n raw && typeof raw === 'object' && 'origin' in raw\n ? (raw as PersistedOutbox)\n : undefined;\n } catch {\n saved = undefined; // an unreadable slot must not wedge the boot\n }\n initCore(saved);\n };\n\n const beginConnect = (): void => {\n if (closed) return;\n if (!opt.outbox) {\n initCore();\n } else if ((opt.outbox.crossTab ?? 'queue') === 'off') {\n void bootFromDisk(); // no single-writer lock — the app coordinates ownership\n } else {\n const locks = globalThis.navigator?.locks;\n if (!locks) {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] outbox crossTab:\"queue\" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock. Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:\"off\" to silence this.',\n );\n }\n void bootFromDisk();\n } else {\n const abort = new AbortController();\n cancelLock = () => abort.abort();\n void locks\n .request(\n `@mmstack/mesh:outbox:${opt.outbox.key}`,\n { mode: 'exclusive', signal: abort.signal },\n () => {\n cancelLock = undefined; // granted — no longer abortable, only releasable\n if (closed) return Promise.resolve();\n // hold the lock until teardown resolves this promise\n return new Promise<void>((release) => {\n releaseLock = release;\n void bootFromDisk();\n });\n },\n )\n .catch((e: unknown) => {\n // an aborted request is our own teardown; any other failure → degrade to no-lock\n if (!closed && (e as { name?: string })?.name !== 'AbortError') {\n void bootFromDisk();\n }\n });\n }\n }\n };\n\n if (opt.whenReady) {\n void Promise.resolve()\n .then(() => opt.whenReady?.())\n .then(\n () => beginConnect(),\n () => beginConnect(),\n );\n } else {\n beginConnect();\n }\n\n return {\n status: status.asReadonly(),\n health,\n peers,\n setPresence: (data) => {\n if (session) session.setPresence(data);\n else pendingPresence = { data };\n },\n fork: (forkOpt) => {\n const f = forkStore(\n source as unknown as WritableSignalStore<T & Record<string, any>>,\n forkOpt,\n );\n\n let frontier: DotFrontier = started ? sync.captureFrontier() : { seq: 0 };\n const recapture = (): void => {\n frontier = started ? sync.captureFrontier() : { seq: 0 };\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () =>\n started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n sync: {\n override: (fn) => (started ? sync.override(fn) : fn()),\n captureFrontier: () => (started ? sync.captureFrontier() : { seq: 0 }),\n commitScope: (frontier, fn) =>\n started ? sync.commitScope(frontier, fn) : fn(),\n liveUnder: (path) => (started ? sync.liveUnder(path) : []),\n liveAt: (path) => (started ? sync.liveAt(path) : []),\n appliedFrontier: () => (started ? sync.appliedFrontier() : {}),\n },\n close: teardown,\n };\n}\n","import { isDevMode } from '@angular/core';\nimport type {\n ClientMsg,\n PrincipalCtx,\n Relay,\n ServerMsg,\n} from '@mmstack/mesh-protocol';\n\n/**\n * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport\n * represents a single connection and never reconnects itself.\n */\nexport type MeshTransport = {\n send(msg: ClientMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\nexport type MeshTransportFactory = () => MeshTransport;\n\n/**\n * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and\n * flushed on open; malformed inbound frames are dropped.\n */\nexport function webSocketTransport(\n url: string,\n protocols?: string | string[],\n): MeshTransportFactory {\n return () => {\n const ws = new WebSocket(url, protocols);\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n\n ws.onopen = () => {\n for (const frame of pending.splice(0)) ws.send(frame);\n };\n ws.onmessage = (event) => {\n let msg: ServerMsg;\n try {\n msg = JSON.parse(String(event.data)) as ServerMsg;\n } catch {\n if (isDevMode()) {\n console.warn('[@mmstack/mesh] dropped unparseable frame (expected JSON text)');\n }\n return;\n }\n for (const cb of [...messageCbs]) cb(msg);\n };\n ws.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n\n return {\n send: (msg) => {\n const frame = JSON.stringify(msg);\n if (ws.readyState === WebSocket.OPEN) ws.send(frame);\n else if (ws.readyState === WebSocket.CONNECTING) pending.push(frame);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => ws.close(),\n };\n };\n}\n\n/**\n * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop\n * tests, and handy for single-process demos or an SSR-side room.\n */\nexport function directTransport(\n relay: Relay,\n ctx: PrincipalCtx,\n): MeshTransportFactory {\n return () => {\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n let open = true;\n\n const connection = relay.connect(\n {\n send: (msg) => {\n if (!open) return;\n for (const cb of [...messageCbs]) cb(msg);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n },\n ctx,\n );\n\n return {\n send: (msg) => {\n if (open) connection.receive(msg);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n };\n };\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport { MESH_PROTO_VERSION, type ServerMsg } from '@mmstack/mesh-protocol';\nimport {\n opSync,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSyncCheckpoint,\n} from '@mmstack/primitives/core';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\n/** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */\nexport type DataChannelLike = {\n send(frame: string): void;\n onMessage(cb: (frame: string) => void): () => void;\n onOpen(cb: () => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\n/**\n * Creates one peer link. `polite` assigns the perfect-negotiation role (derived\n * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads\n * through the relay; `signal` delivers the remote side's payloads.\n */\nexport type PeerConnector = (opt: {\n readonly remote: string;\n readonly polite: boolean;\n readonly sendSignal: (data: unknown) => void;\n}) => {\n readonly channel: DataChannelLike;\n signal(data: unknown): void;\n close(): void;\n};\n\n/** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */\nexport function rtcPeerConnector(config?: RTCConfiguration): PeerConnector {\n return ({ polite, sendSignal }) => {\n const pc = new RTCPeerConnection(config);\n const messageCbs = new Set<(frame: string) => void>();\n const openCbs = new Set<() => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n let dc: RTCDataChannel | null = null;\n let makingOffer = false;\n let ignoreOffer = false;\n\n const attach = (channel: RTCDataChannel): void => {\n dc = channel;\n channel.onmessage = (e) => {\n for (const cb of [...messageCbs]) cb(String(e.data));\n };\n channel.onopen = () => {\n for (const frame of pending.splice(0)) channel.send(frame);\n for (const cb of [...openCbs]) cb();\n };\n channel.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n };\n\n if (!polite) attach(pc.createDataChannel('mmstack-mesh'));\n else pc.ondatachannel = (e) => attach(e.channel);\n\n pc.onicecandidate = (e) => {\n if (e.candidate) sendSignal({ ice: e.candidate.toJSON() });\n };\n pc.onnegotiationneeded = async () => {\n try {\n makingOffer = true;\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n } finally {\n makingOffer = false;\n }\n };\n\n return {\n channel: {\n send: (frame) => {\n if (dc && dc.readyState === 'open') dc.send(frame);\n else pending.push(frame);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n close: () => dc?.close(),\n },\n signal: async (data) => {\n const { description, ice } = (data ?? {}) as {\n description?: RTCSessionDescriptionInit;\n ice?: RTCIceCandidateInit;\n };\n if (description) {\n const collision =\n description.type === 'offer' &&\n (makingOffer || pc.signalingState !== 'stable');\n ignoreOffer = !polite && collision;\n if (ignoreOffer) return;\n await pc.setRemoteDescription(description);\n if (description.type === 'offer') {\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n }\n } else if (ice) {\n try {\n await pc.addIceCandidate(ice);\n } catch (err) {\n if (!ignoreOffer) throw err;\n }\n }\n },\n close: () => {\n dc?.close();\n pc.close();\n },\n };\n };\n}\n\ntype P2PMsg =\n | { t: 'hello'; wm: Record<string, number> }\n // the full checkpoint (root + register state + watermark), NOT a bare value: the covered\n // side must inherit supersession state or already-superseded stragglers would resurrect\n | { t: 'state'; state: OpSyncCheckpoint<object> }\n | { t: 'uptodate' }\n | { t: 'env'; env: OpEnvelope };\n\nexport type WebRtcMeshOptions = {\n readonly room: string;\n readonly writer: string;\n /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */\n readonly signaling: MeshTransportFactory;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policyVersion?: number;\n readonly injector?: Injector;\n};\n\nexport type WebRtcMeshRef = {\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins with an OPEN data channel. */\n readonly peers: Signal<readonly string[]>;\n close(): void;\n};\n\ntype Peer = {\n link: ReturnType<PeerConnector>;\n open: boolean;\n unsubs: (() => void)[];\n};\n\n/**\n * Peer-to-peer mesh sync: the relay only signals\n * and tracks membership; envelopes flow over WebRTC data channels and converge via the\n * per-path register map. Catch-up is pairwise: on channel open both sides exchange\n * watermarks; a side whose state is strictly covered hydrates from the other's FULL\n * checkpoint (root + per-path register state + watermark), so supersession and precedence\n * carry over intact: a late joiner is indistinguishable from a peer that saw every\n * envelope. Two peers that each hold envelopes the other lacks keep their convergent\n * go-forward guarantees but do not exchange the missed envelopes retroactively.\n */\nexport function webRtcMesh<T extends object>(\n source: WritableSignal<T>,\n opt: WebRtcMeshOptions,\n): WebRtcMeshRef {\n const injector = opt.injector ?? inject(Injector);\n const connector = opt.connector ?? rtcPeerConnector();\n const status = signal<'connecting' | 'live'>('connecting');\n const openPeers = signal<ReadonlySet<string>>(new Set());\n const peers = new Map<string, Peer>();\n let signalingUnsubs: (() => void)[] = [];\n let transport: MeshTransport | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n\n const sync = opSync(source, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion: opt.policyVersion,\n injector,\n });\n\n const covered = (\n mine: Record<string, number>,\n theirs: Record<string, number>,\n ): boolean => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);\n\n const sendTo = (peer: Peer, msg: P2PMsg): void => {\n peer.link.channel.send(JSON.stringify(msg));\n };\n\n const broadcast = (msg: P2PMsg): void => {\n for (const peer of peers.values()) {\n if (peer.open) sendTo(peer, msg);\n }\n };\n\n const dropPeer = (origin: string): void => {\n const peer = peers.get(origin);\n if (!peer) return;\n peers.delete(origin);\n for (const unsub of peer.unsubs) unsub();\n peer.link.close();\n openPeers.update((set) => {\n const next = new Set(set);\n next.delete(origin);\n return next;\n });\n };\n\n const ensurePeer = (origin: string): Peer => {\n let peer = peers.get(origin);\n if (peer) return peer;\n const link = connector({\n remote: origin,\n polite: sync.origin > origin,\n sendSignal: (data) =>\n transport?.send({ t: 'signal', room: opt.room, to: origin, data }),\n });\n peer = { link, open: false, unsubs: [] };\n peers.set(origin, peer);\n peer.unsubs.push(\n link.channel.onOpen(() => {\n peer!.open = true;\n openPeers.update((set) => new Set(set).add(origin));\n sendTo(peer!, { t: 'hello', wm: sync.watermark() });\n }),\n link.channel.onMessage((frame) => {\n let msg: P2PMsg;\n try {\n msg = JSON.parse(frame) as P2PMsg;\n } catch {\n return;\n }\n handlePeerMsg(peer!, msg);\n }),\n link.channel.onClose(() => dropPeer(origin)),\n );\n return peer;\n };\n\n const handlePeerMsg = (peer: Peer, msg: P2PMsg): void => {\n switch (msg.t) {\n case 'hello': {\n const snap = sync.snapshot();\n if (covered(snap.wm, msg.wm)) sendTo(peer, { t: 'uptodate' });\n else sendTo(peer, { t: 'state', state: snap });\n return;\n }\n case 'state': {\n if (covered(sync.watermark(), msg.state.wm)) {\n sync.hydrate(msg.state as OpSyncCheckpoint<T>);\n }\n return;\n }\n case 'uptodate':\n return;\n case 'env':\n sync.receive(msg.env);\n return;\n }\n };\n\n const handleSignaling = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome':\n for (const origin of msg.members) ensurePeer(origin);\n status.set('live');\n return;\n case 'member':\n if (msg.gone) dropPeer(msg.origin);\n else ensurePeer(msg.origin);\n return;\n case 'signal':\n ensurePeer(msg.from).link.signal(msg.data);\n return;\n case 'reject':\n close();\n return;\n }\n };\n\n const connectSignaling = (): void => {\n if (closed) return;\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n const t = opt.signaling();\n transport = t;\n signalingUnsubs = [\n t.onMessage(handleSignaling),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n reconnectTimer = setTimeout(connectSignaling, 1000);\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion ?? 0,\n });\n };\n\n const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);\n unsubLocal();\n for (const origin of [...peers.keys()]) dropPeer(origin);\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n transport?.close();\n transport = null;\n sync.destroy();\n status.set('connecting');\n };\n\n injector.get(DestroyRef).onDestroy(close);\n connectSignaling();\n\n return {\n status: status.asReadonly(),\n peers: computed(() => [...openPeers()]),\n close,\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;;AAyGA,MAAM,iBAAiB,GAAG,GAAG;AAEvB,SAAU,WAAW,CACzB,GAA0B,EAAA;AAE1B,IAAA,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,GAAG;AAC3B,IAAA,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,IAAI;AAC/B,QAAA,GAAG,EAAE,CAAC,EAAc,EAAE,EAAU,KAAK,UAAU,CAAC,EAAE,EAAE,EAAE,CAAC;QACvD,KAAK,EAAE,CAAC,MAAe,KACrB,YAAY,CAAC,MAAuC,CAAC;KACxD;IAED,IAAI,MAAM,GAAe,YAAY;IACrC,MAAM,UAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACjD,IAAA,MAAM,OAAO,GAAG,IAAI,GAAG,EAAsB;AAC7C,IAAA,MAAM,KAAK,GAAG,IAAI,GA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;"}
|
|
1
|
+
{"version":3,"file":"mmstack-mesh.mjs","sources":["../../../../../packages/mesh/client/src/lib/session.ts","../../../../../packages/mesh/client/src/lib/agent-seat.ts","../../../../../packages/mesh/client/src/lib/mesh-sync.ts","../../../../../packages/mesh/client/src/lib/transport.ts","../../../../../packages/mesh/client/src/lib/webrtc-mesh.ts","../../../../../packages/mesh/client/src/mmstack-mesh.ts"],"sourcesContent":["import {\n checkEnvelope,\n MESH_PROTO_VERSION,\n type OpPolicy,\n type PolicyViolation,\n type PresenceState,\n type PrincipalCtx,\n type SeqEnvelope,\n type ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n createConvergingApply,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type StoreOp,\n} from '@mmstack/primitives/core';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\nexport type MeshStatus =\n 'connecting' | 'live' | 'reconnecting' | 'ejected' | 'closed';\n\n/** One sequenced remote envelope's ops, attributed to the writer that made them. */\nexport type RemoteBatch = {\n /** The relay's total-order stamp for this batch. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Environment callbacks a session shell provides. All are optional except `onStatus`; the\n * session never touches signals, timers beyond `schedule`, storage, or the DOM itself.\n */\nexport type MeshSessionHooks = {\n onStatus(status: MeshStatus, reason?: string): void;\n /** A welcome or envelope arrived — the shell's \"last synced\" moment. */\n onSynced?(): void;\n /** The presence roster changed (welcome replace, join/leave, teardown clear). */\n onPeers?(peers: ReadonlyMap<string, PresenceState>): void;\n /** A remote (non-own) envelope was ingested, in seq order. */\n onRemote?(batch: RemoteBatch): void;\n /**\n * Seq continuity broke: a snapshot welcome (or a relay instance change) established state\n * without delivering the individual envelopes in between. Any consumer deriving from the\n * `onRemote` stream must rebuild from current state at this seq; appending across a resync\n * would silently skip history.\n */\n onResync?(seq: number): void;\n /** The unacknowledged local tail changed (emit or ack) — the durable-outbox trigger. */\n onOutboxChange?(): void;\n /**\n * A local write violated the room policy. The session ejects itself immediately after —\n * the outcome the relay's own independent check would have produced one hop later. The\n * emit-side check spares the room the round trip; it is never the enforcement.\n */\n onLocalReject?(violation: PolicyViolation): void;\n /**\n * Teardown is starting; fired before the unacked tail is dropped, so a shell can persist\n * it (and release any single-writer locks) while it is still intact.\n */\n onTerminal?(state: 'ejected' | 'closed', reason?: string): void;\n /**\n * The relay refused one of this session's writes: it is not in the room and never will be.\n * `'generation'` — written in a room generation that has since been cut (the whole tail is\n * refused at the welcome that names the new one, or one envelope by the relay's reply);\n * `'schema'` — a data shape older than the room's; `'order'` — a version below this origin's\n * admitted maximum that was never admitted (a second tab on one origin). The session drops\n * the write locally and hydrates from a fresh snapshot; the envelope carries the values, so\n * the application can offer to write them again. Any `whenAcked` waiter rejects.\n */\n onRefused?(env: OpEnvelope, reason: 'generation' | 'schema' | 'order'): void;\n};\n\nexport type MeshSessionOptions<T extends object> = {\n readonly room: string;\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** The op engine this session feeds. The shell creates (and destroys) it. */\n readonly sync: OpSync<T>;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policy?: OpPolicy;\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion: number;\n readonly schemaVersion?: number;\n /** The room generation a restored outbox was written in; the first welcome decides whether it still holds. */\n readonly instance?: string;\n readonly reconnect?: { readonly maxDelayMs?: number };\n /** Timer seam (tests, deterministic harnesses). Defaults to global timers. */\n readonly schedule?: {\n set(fn: () => void, ms: number): unknown;\n clear(handle: unknown): void;\n };\n readonly hooks: MeshSessionHooks;\n};\n\n/**\n * The relay-room session protocol, shell-agnostic: hello/welcome handshakes (snapshot\n * hydrate, delta replay, fresh-room seed), own-echo acknowledgement, unacked resend,\n * the relay's per-envelope answers (`drop`), reconnect backoff, presence, eject/reject, the\n * generation fence and settled-vector garbage collection. `meshSync` wraps it for\n * Angular; `agentSeat` wraps it for injector-free environments. One implementation of the\n * wire contract — shells differ only in environment concerns.\n */\nexport type MeshSession = {\n /** Open the first connection. Call once, after any outbox restore has replayed. */\n connect(): void;\n status(): MeshStatus;\n /** Highest relay seq observed. With no unacked writes, local state is the pure fold of the room at this seq. */\n lastSeq(): number;\n hasUnacked(): boolean;\n /**\n * Resolves once the unacknowledged local tail is empty — the acknowledgement barrier a\n * caller awaits before treating its writes as the room's. Resolves immediately when\n * nothing is outstanding. Rejects with the terminal reason if the session ends (eject or\n * close) while entries remain: those writes never reached the room, and every later call\n * rejects the same way.\n *\n * With a relay whose adapter confirms durability before echoing, acknowledged means\n * stored; against a relay that echoes eagerly it means only \"the relay has it\".\n */\n whenAcked(): Promise<void>;\n /** The unacknowledged local tail (the durable-outbox payload). */\n unackedEnvs(): readonly OpEnvelope[];\n /** The room generation this session is in, once a welcome (or a restored outbox) named one. */\n instance(): string | undefined;\n peers(): ReadonlyMap<string, PresenceState>;\n setPresence(data: unknown): void;\n close(): void;\n};\n\nconst RECONNECT_BASE_MS = 500;\n\nexport function meshSession<T extends object>(\n opt: MeshSessionOptions<T>,\n): MeshSession {\n const { sync, hooks } = opt;\n const schedule = opt.schedule ?? {\n set: (fn: () => void, ms: number) => setTimeout(fn, ms),\n clear: (handle: unknown) =>\n clearTimeout(handle as ReturnType<typeof setTimeout>),\n };\n\n let status: MeshStatus = 'connecting';\n const ownOrigins = new Set<string>([sync.origin]);\n const unacked = new Map<string, OpEnvelope>();\n const acked = new Map<string, number>();\n const unackedKey = (env: { origin: string; version: number }): string =>\n `${env.origin} ${env.version}`;\n let lastSeq = 0;\n let instance: string | undefined = opt.instance;\n if (instance) sync.adopt(instance);\n // a refusal asks for a fresh snapshot; one hello per burst, cleared by the welcome it earns\n let rehydrating = false;\n let peers: ReadonlyMap<string, PresenceState> = new Map();\n let presenceData: unknown;\n let hasPresence = false;\n let transport: MeshTransport | null = null;\n let attempts = 0;\n let reconnectTimer: unknown;\n let unsubs: (() => void)[] = [];\n let closed = false;\n let ackFailure: Error | undefined;\n const ackWaiters: {\n resolve: () => void;\n reject: (cause: Error) => void;\n }[] = [];\n\n const releaseAckWaiters = (failure?: Error): void => {\n for (const waiter of ackWaiters.splice(0)) {\n if (failure) waiter.reject(failure);\n else waiter.resolve();\n }\n };\n\n const setStatus = (next: MeshStatus, reason?: string): void => {\n status = next;\n hooks.onStatus(next, reason);\n };\n\n const terminal = (state: 'ejected' | 'closed', reason?: string): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) {\n schedule.clear(reconnectTimer);\n reconnectTimer = undefined;\n }\n for (const unsub of unsubs.splice(0)) unsub();\n unsubLocal();\n hooks.onTerminal?.(state, reason); // unacked is still intact here — the persist window\n if (unacked.size > 0) {\n // these writes are not in the room and never will be on this session\n ackFailure = new Error(reason ?? state);\n releaseAckWaiters(ackFailure);\n } else {\n releaseAckWaiters();\n }\n unacked.clear();\n transport?.close();\n transport = null;\n peers = new Map();\n hooks.onPeers?.(peers);\n setStatus(state, reason);\n };\n\n const sendEnv = (env: OpEnvelope): void => {\n // an envelope minted before any generation was known adopts the one this session is in\n let out = env;\n if (env.instance === '' && instance) {\n out = { ...env, instance };\n unacked.set(unackedKey(env), out);\n }\n transport?.send({ t: 'env', room: opt.room, env: out });\n };\n const sendHello = (): void => {\n transport?.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion,\n seq: lastSeq > 0 ? lastSeq : undefined,\n schemaVersion: opt.schemaVersion,\n });\n };\n const ackOwn = (origin: string, version: number): void => {\n if (!unacked.delete(unackedKey({ origin, version }))) return;\n acked.set(origin, Math.max(acked.get(origin) ?? 0, version));\n hooks.onOutboxChange?.();\n if (unacked.size === 0) releaseAckWaiters();\n };\n const refuse = (env: OpEnvelope, reason: 'generation' | 'schema' | 'order'): void => {\n unacked.delete(unackedKey(env));\n hooks.onRefused?.(env, reason);\n hooks.onOutboxChange?.();\n // \"every write was classified\" is not \"every write was stored\": a waiter rejects\n releaseAckWaiters(new Error(`refused: ${reason}`));\n };\n\n const flushUnacked = (): void => {\n for (const env of unacked.values()) sendEnv(env);\n };\n\n const applyRemote = (env: SeqEnvelope): void => {\n if (closed) return; // a delta welcome keeps iterating after an eject — nothing lands past it\n\n if (\n opt.schemaVersion !== undefined &&\n env.schemaVersion !== undefined &&\n env.schemaVersion > opt.schemaVersion\n ) {\n terminal('ejected', 'schema');\n return;\n }\n lastSeq = Math.max(lastSeq, env.seq);\n hooks.onSynced?.();\n if (ownOrigins.has(env.origin)) {\n ackOwn(env.origin, env.version);\n return;\n }\n sync.receive(env);\n hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });\n };\n\n const handle = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome': {\n const instanceChanged =\n instance !== undefined && msg.instance !== instance;\n const prevSeq = lastSeq;\n if (instanceChanged) {\n // the generation boundary on the client: the tail written in the old one is refused\n // loudly, its acknowledgements mean nothing here, and the new generation's snapshot\n // replaces the whole applied state below\n lastSeq = 0;\n acked.clear();\n for (const env of [...unacked.values()]) refuse(env, 'generation');\n }\n instance = msg.instance;\n sync.adopt(msg.instance);\n rehydrating = false;\n peers = new Map(msg.peers.map((p) => [p.origin, p]));\n hooks.onPeers?.(peers);\n const resync = msg.mode === 'snapshot' || instanceChanged;\n if (msg.mode === 'delta') {\n for (const env of msg.envs) applyRemote(env);\n } else if (msg.mode === 'snapshot') {\n const conv = createConvergingApply({ policies: opt.policies });\n conv.load(msg.registers);\n const ownWm: Record<string, number> = {};\n for (const o of ownOrigins) ownWm[o] = acked.get(o) ?? 0;\n sync.hydrate(\n {\n root: conv.materialize() as T,\n registers: msg.registers,\n wm: { ...msg.wm, ...ownWm },\n },\n [...unacked.values()],\n );\n lastSeq = msg.seq;\n } else if (msg.seq === 0 && lastSeq === 0) {\n sync.seed();\n }\n // every branch can end terminal (schema eject in a delta env, a seed or rebase\n // emission tripping the emit-side policy) — never revive to live\n if (closed) {\n if (instanceChanged && lastSeq === 0) lastSeq = prevSeq;\n return;\n }\n lastSeq = Math.max(lastSeq, msg.seq);\n attempts = 0;\n hooks.onSynced?.();\n if (resync) hooks.onResync?.(lastSeq);\n setStatus('live');\n flushUnacked();\n if (hasPresence)\n transport?.send({\n t: 'presence',\n room: opt.room,\n data: presenceData,\n });\n return;\n }\n case 'env':\n applyRemote(msg.env);\n return;\n case 'presence': {\n const next = new Map(peers);\n if (msg.gone) next.delete(msg.peer.origin);\n else next.set(msg.peer.origin, msg.peer);\n peers = next;\n hooks.onPeers?.(peers);\n return;\n }\n case 'eject':\n if (msg.writer === opt.writer) terminal('ejected', msg.reason);\n return;\n case 'reject':\n terminal('ejected', msg.reason);\n return;\n case 'settled':\n sync.settle(msg.settled);\n return;\n case 'drop': {\n const held = unacked.get(unackedKey(msg));\n if (!held) return; // already classified (a duplicate reply after the echo, or an old generation's)\n if (msg.reason === 'duplicate') {\n ackOwn(msg.origin, msg.version); // the room holds it: this is the acknowledgement\n return;\n }\n refuse(held, msg.reason);\n // the refused write is still applied locally: drop and rehydrate from a fresh snapshot\n if (!rehydrating) {\n rehydrating = true;\n lastSeq = 0;\n sendHello();\n }\n return;\n }\n }\n };\n\n const connect = (): void => {\n if (closed) return;\n for (const unsub of unsubs.splice(0)) unsub();\n const t = opt.transport();\n transport = t;\n unsubs = [\n t.onMessage(handle),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n setStatus('reconnecting');\n const delay = Math.min(\n opt.reconnect?.maxDelayMs ?? 15_000,\n RECONNECT_BASE_MS * 2 ** attempts++,\n );\n reconnectTimer = schedule.set(\n () => {\n reconnectTimer = undefined;\n connect();\n },\n delay + Math.random() * 100,\n );\n }),\n ];\n sendHello();\n };\n\n const unsubLocal = sync.subscribe((env) => {\n const violation = checkEnvelope(\n opt.policy,\n env,\n { ...opt.ctx, writer: opt.writer },\n opt.room,\n // the last sequence this client observed; it can only lag the relay's, so a rule that\n // keys off an empty room is at worst more permissive here than it is at the relay\n { seq: lastSeq },\n );\n if (violation) {\n // same outcome the relay's own check would produce one hop later — the emit-side\n // check is an optimization, never the enforcement\n hooks.onLocalReject?.(violation);\n terminal('ejected', violation.reason);\n return;\n }\n ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim\n unacked.set(unackedKey(env), env);\n hooks.onOutboxChange?.();\n if (status === 'live') sendEnv(env);\n });\n\n return {\n connect,\n status: () => status,\n lastSeq: () => lastSeq,\n hasUnacked: () => unacked.size > 0,\n whenAcked: () =>\n ackFailure\n ? Promise.reject(ackFailure)\n : unacked.size === 0\n ? Promise.resolve()\n : new Promise<void>((resolve, reject) => {\n ackWaiters.push({ resolve, reject });\n }),\n unackedEnvs: () => [...unacked.values()],\n instance: () => instance,\n peers: () => peers,\n setPresence: (data) => {\n presenceData = data;\n hasPresence = true;\n if (status === 'live') {\n transport?.send({ t: 'presence', room: opt.room, data });\n }\n },\n close: () => terminal('closed'),\n };\n}\n","import { createWatch } from '@angular/core/primitives/signals';\nimport type {\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n createStoreContext,\n forkStore,\n opSync,\n store,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpLogDriver,\n type OpSync,\n type StoreOp,\n type SyncedFork,\n type toStoreOptions,\n type WritableSignalStore,\n type OpEnvelope,\n} from '@mmstack/primitives/core';\nimport type { SeatSync } from './mesh-sync';\nimport { meshSession, type MeshStatus } from './session';\nimport type { MeshTransportFactory } from './transport';\n\nconst microtaskDriver = (): OpLogDriver => (run) => {\n let scheduled = false;\n const watch = createWatch(\n () => run(),\n (w) => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n w.run();\n });\n },\n false,\n );\n watch.notify();\n return { destroy: () => watch.destroy() };\n};\n\n/** A sequenced batch of another writer's ops, delivered in relay order. */\nexport type SeatChange = {\n readonly kind: 'change';\n /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past\n * the relay's retention, or a relay restart) without seeing the individual changes in\n * between. Anything accumulated from prior `change` events — narration buffers, cached\n * prompt prefixes — no longer extends the stream and must be rebuilt from current state.\n */\nexport type SeatResync = {\n readonly kind: 'resync';\n /** The seq the re-established state corresponds to. */\n readonly seq: number;\n};\n\nexport type SeatEvent = SeatChange | SeatResync;\n\n/** A base state provably derivable from the room's history alone — safe to cache. */\nexport type StableSnapshot<T> = {\n /** The relay seq this state is the fold of. */\n readonly seq: number;\n readonly doc: T;\n};\n\nexport type AgentSeatOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. One identity per seat. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /**\n * Emit-side validation, symmetric with the relay's — an optimization, not the\n * enforcement (the relay validates every envelope regardless). A violating write is\n * never sent and ejects the seat exactly as the relay would have; the refused value\n * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.\n */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion?: number;\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n /**\n * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;\n * pass your own to share proxy caches across several seats in one process.\n */\n readonly context?: toStoreOptions;\n readonly onEject?: (reason: string) => void;\n /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */\n readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;\n};\n\nexport type AgentSeat<T extends object> = {\n /** The live converging replica. Reads exactly like a local signal store. */\n readonly doc: WritableSignalStore<T & Record<string, any>>;\n status(): MeshStatus;\n peers(): readonly PresenceState[];\n /** The current document value — plain JSON-serializable data, for context assembly. */\n snapshot(): T;\n /**\n * The current document, stamped with the relay seq it is provably the pure fold of\n * or null when stability cannot be guaranteed\n */\n stableSnapshot(): StableSnapshot<T> | null;\n /** Run local writes and emit them to the room as one envelope, like any peer's edit. */\n write(fn: () => void): void;\n /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */\n setAtPath(path: string | readonly (string | number)[], value: unknown): void;\n /**\n * The room's sequenced history as it arrives: `change` events carry another writer's ops\n * in strictly increasing seq order, so a listener may append them (narration, prompt\n * suffixes) without any diffing. A `resync` event voids that guarantee — everything\n * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).\n * Own writes never echo here.\n */\n changes(cb: (event: SeatEvent) => void): () => void;\n /**\n * An isolated branch for a reviewable proposal. The fork observes the room as it is now;\n * `commit()` emits its diff citing only those observed writes, so a room edit that lands\n * while the fork is open survives as a concurrent value for the merge policy to resolve\n * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the\n * staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /**\n * Every local write is acknowledged by the room. `false` while a write is still in the\n * unacknowledged tail, and it stays `false` once the seat ends with writes outstanding.\n */\n acked(): boolean;\n /**\n * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects\n * with the terminal reason if the seat ends while writes are outstanding. The barrier to\n * await before handing a result to something that must contain every edit.\n */\n whenAcked(): Promise<void>;\n /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */\n setPresence(data: unknown): void;\n /** Authority surface over this seat's op-sync; see {@link SeatSync}. */\n readonly sync: SeatSync<T>;\n close(): void;\n};\n\n/**\n * A headless mesh peer: the same replica and wire contract `meshSync` implements in the\n * browser, without Angular's injector or any browser API — for agents, server-side bridges,\n * and device writers joining a room as first-class, attributed participants. Each call is\n * one identity with its own replica; run several seats in one process for several\n * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as\n * to any human peer.\n */\nexport function agentSeat<T extends object>(\n initial: T,\n opt: AgentSeatOptions,\n): AgentSeat<T> {\n const context = opt.context ?? createStoreContext();\n const root = store(initial as T & Record<string, any>, context);\n const doc = root as unknown as WritableSignalStore<T & Record<string, any>>;\n const read = root as unknown as () => T;\n const policyVersion = opt.policyVersion ?? 0;\n\n // onReject fires synchronously inside receive(); the flag keeps a malformed envelope's\n // ops (which did NOT apply) out of the change stream.\n let rejected = false;\n const sync = opSync(root as never, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion,\n driver: microtaskDriver(),\n onReject: (_env, reason) => {\n rejected = true;\n console.warn(\n `[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`,\n );\n },\n }) as OpSync<T>;\n\n const listeners = new Set<(event: SeatEvent) => void>();\n const emit = (event: SeatEvent): void => {\n for (const cb of [...listeners]) cb(event);\n };\n let welcomed = false;\n let diverged = false;\n let terminated = false;\n let lostWrites = false;\n\n const session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n reconnect: opt.reconnect,\n hooks: {\n onStatus: (s, reason) => {\n if (s === 'live') welcomed = true;\n if (s === 'ejected' && reason !== undefined) opt.onEject?.(reason);\n },\n onRemote: (batch) => {\n if (rejected) {\n rejected = false;\n return;\n }\n emit({ kind: 'change', ...batch });\n },\n onResync: (seq) => emit({ kind: 'resync', seq }),\n onRefused: (env, reason) => {\n diverged = true; // the write stays applied until the rehydrate that follows lands\n opt.onRefused?.(env, reason);\n },\n onLocalReject: (violation) => {\n diverged = true; // the write stays in the replica but will never reach the room\n console.warn(\n '[@mmstack/mesh] agent seat write violates the room policy — not sent',\n violation,\n );\n },\n onTerminal: () => {\n if (session.hasUnacked()) {\n diverged = true;\n lostWrites = true; // latched: no echo can arrive for them now\n }\n terminated = true;\n },\n },\n });\n // a write after the terminal state is one the room will never sequence: the doc keeps it\n // (post-mortem), but the seat stops claiming provable folds — same latch as a refused write\n sync.subscribe(() => {\n if (terminated) diverged = true;\n });\n session.connect();\n\n return {\n doc,\n status: () => session.status(),\n peers: () => [...session.peers().values()],\n snapshot: () => read(),\n stableSnapshot: () => {\n sync.flush(); // a write made this tick must count as pending, not linger unstamped\n if (!welcomed || diverged || session.hasUnacked()) return null;\n return { seq: session.lastSeq(), doc: read() };\n },\n write: (fn) => {\n fn();\n sync.flush();\n },\n setAtPath: (path, value) => {\n setAtPath(doc, path, value);\n sync.flush();\n },\n changes: (cb) => {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n fork: (forkOpt) => {\n const f = forkStore(doc, forkOpt);\n let frontier: DotFrontier = sync.captureFrontier();\n const recapture = (): void => {\n frontier = sync.captureFrontier();\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () => {\n sync.commitScope(frontier, () => f.commit());\n sync.flush();\n },\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n acked: () => {\n sync.flush(); // a write made this tick counts as pending, not as unstamped\n return !lostWrites && !session.hasUnacked();\n },\n whenAcked: () => {\n sync.flush();\n return session.whenAcked();\n },\n setPresence: (data) => session.setPresence(data),\n sync: {\n override: (fn) => sync.override(fn),\n captureFrontier: () => sync.captureFrontier(),\n commitScope: (frontier, fn) => sync.commitScope(frontier, fn),\n liveUnder: (path) => sync.liveUnder(path),\n liveAt: (path) => sync.liveAt(path),\n appliedFrontier: () => sync.appliedFrontier(),\n },\n close: () => {\n diverged = true; // sync is destroyed below: later writes are unwatched, so no more proofs\n session.close();\n sync.destroy();\n },\n };\n}\n\ntype PathSegment = string | number;\n\nconst parsePath = (\n path: string | readonly PathSegment[],\n): readonly PathSegment[] =>\n typeof path === 'string' ? path.split('.').filter((s) => s !== '') : path;\n\n// resolve a string segment against an array ('0' → 0) so dot-paths address list items\nconst resolveKey = (current: unknown, seg: PathSegment): PathSegment =>\n Array.isArray(current) && typeof seg === 'string' && /^\\d+$/.test(seg)\n ? Number(seg)\n : seg;\n\nfunction withPathSet(\n current: unknown,\n path: readonly PathSegment[],\n value: unknown,\n): unknown {\n if (path.length === 0) return value;\n const [head, ...rest] = path;\n if (Array.isArray(current)) {\n const idx = typeof head === 'number' ? head : Number(head);\n const copy = [...current];\n copy[idx] = withPathSet(current[idx], rest, value);\n return copy;\n }\n const base =\n current !== null && typeof current === 'object'\n ? (current as Record<PathSegment, unknown>)\n : {};\n return { ...base, [head]: withPathSet(base[head], rest, value) };\n}\n\n/**\n * Applies `value` at a path on a signal-store node — the write shape a tool-calling model\n * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as\n * the path exists in the current value and finishes with one immutable set on the deepest\n * real node, which also covers paths that do not exist yet (a fresh record key creates it).\n * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer\n * `seat.setAtPath`, which also emits immediately.\n */\nexport function setAtPath(\n node: unknown,\n path: string | readonly PathSegment[],\n value: unknown,\n): void {\n const segs = parsePath(path);\n let cursor = node as Record<PathSegment, unknown> & {\n (): unknown;\n set(v: unknown): void;\n };\n let walked = 0;\n for (const seg of segs) {\n const current = cursor();\n if (current === null || typeof current !== 'object') break;\n const key = resolveKey(current, seg);\n if (!Object.hasOwn(current, key)) break;\n const child = cursor[key];\n if (typeof child !== 'function') break;\n cursor = child as typeof cursor;\n walked++;\n }\n const rest = segs.slice(walked);\n if (rest.length === 0) {\n cursor.set(value);\n return;\n }\n cursor.set(withPathSet(cursor(), rest, value));\n}\n\nconst MAX_VALUE_CHARS = 120;\n\nconst printable = (value: unknown): string => {\n const json = JSON.stringify(value);\n if (json === undefined) return String(value);\n return json.length > MAX_VALUE_CHARS\n ? `${json.slice(0, MAX_VALUE_CHARS - 1)}…`\n : json;\n};\n\n/**\n * One store op as a plain-English line (\"mira set plan.endDate to \\\"2026-10-11\\\"\"), for\n * activity feeds and model context. Values render as truncated JSON. Pair with a seat's\n * `changes` stream: narrating each batch's ops yields an append-only account of the room.\n */\nexport function describeOp(op: StoreOp, writer: string): string {\n const at = op.path.length === 0 ? 'the document root' : op.path.join('.');\n switch (op.kind) {\n case 'set':\n return `${writer} set ${at} to ${printable(op.next)}`;\n case 'delete':\n return `${writer} removed ${at}`;\n case 'clear':\n return `${writer} cleared ${at}`;\n }\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n runInInjectionContext,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport type {\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n forkStore,\n OP_PROTO_VERSION,\n opSync,\n registerResource,\n type AsyncStore,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type ResourceLike,\n type SyncedFork,\n type SyncOp,\n type WritableSignalStore,\n type Hlc,\n} from '@mmstack/primitives/core';\nimport { meshSession, type MeshSession, type MeshStatus } from './session';\nimport type { MeshTransportFactory } from './transport';\n\nexport type { MeshStatus } from './session';\n\nexport type MeshPeer = PresenceState;\n\n/**\n * A composed, user-facing health status for a synced store the surface that\n * turns a versioned reject from a dead socket into a speakable 'outdated' banner.\n */\nexport type SyncHealthStatus =\n 'live' | 'offline' | 'outdated' | 'ejected' | 'degraded';\n\nexport type SyncHealth = {\n readonly status: SyncHealthStatus;\n /** Why, when the status is `outdated`/`ejected`/`degraded`. */\n readonly reason?:\n 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | (string & {});\n /** `Date.now()` of the last successful sync (welcome or applied env). */\n readonly lastSyncedAt?: number;\n /**\n * Offline writes persisted by an older build that could not be restored on boot. Envelopes\n * from a previous wire-protocol version lack the citation metadata current merging needs,\n * so they are dropped (loudly) instead of being upgraded with fabricated citations.\n */\n readonly droppedOfflineWrites?: number;\n /**\n * Writes the relay refused on this session: they are not in the room. Each was handed to\n * `onRefused` with its values, and the store was rehydrated from a fresh snapshot after it.\n */\n readonly refusedWrites?: number;\n /**\n * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id\n * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a\n * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line\n * against a malformed neighbor; through a relay these are also rejected at the relay.\n */\n readonly droppedInvalidEnvelopes?: number;\n};\n\n// a versioned reject means \"your build is behind\" → prompt an update, not a dead socket\nconst OUTDATED_REASONS: ReadonlySet<string> = new Set([\n 'proto',\n 'policy-version',\n 'schema',\n]);\n\nexport type MeshSyncOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /** Emit-side validation, symmetric with the relay's (tripwire honesty). */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n /**\n * The room's shared configuration pin, checked at hello against the relay's. Bump it\n * together whenever anything peers must agree on changes: the write policy, and just as\n * importantly the merge/fold configuration (`policies`). Peers folding the same register\n * state with different rules read different values, so one room means one fold config; a\n * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.\n */\n readonly policyVersion?: number;\n /** The data shape this client speaks. Older-than-room → `outdated`, and a\n * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n readonly injector?: Injector;\n /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */\n readonly register?: 'track' | 'suspend';\n readonly onEject?: (reason: string) => void;\n /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */\n readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;\n /**\n * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects\n * (and before it restores an `outbox`), so a store hydrated from another source first (a worker\n * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.\n * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base\n * that fails to load never wedges the connection.\n */\n readonly whenReady?: () => PromiseLike<void> | void;\n /**\n * Persist the unacknowledged local outbox (and this client's stable origin) so offline writes\n * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room\n * on the next welcome, instead of being lost with in-memory state. The payload is written to\n * `store` under `key`, debounced.\n *\n * By default (`crossTab: 'queue'`) a Web Lock on `key` makes this a single-writer-per-key resource:\n * a second tab sharing the key WAITS (stays `connecting`, surfaced via `status`/`health`) until the\n * first releases, rather than restoring the same origin and colliding on version mints. Set\n * `crossTab: 'off'` to skip the lock and coordinate ownership yourself (e.g. a per-tab key, or\n * leader election over `tabSync`). A debounced write means a hard crash within the debounce window\n * can drop the very last mint — a small, best-effort gap; tune it with `debounceMs`.\n */\n readonly outbox?: {\n readonly key: string;\n readonly store: AsyncStore;\n /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */\n readonly debounceMs?: number;\n /**\n * Cross-tab contention for the shared `key`. `'queue'` (default) holds a Web Lock so only one tab\n * owns the durable outbox at a time; others wait. `'off'` skips the lock (you coordinate).\n * (A future `'ephemeral'` — non-leaders run live with a throwaway origin — is planned.)\n */\n readonly crossTab?: 'queue' | 'off';\n };\n};\n\n/** The shape persisted under `outbox.key`: the stable origin, the emit high-water, and the tail. */\ntype PersistedOutbox = {\n readonly origin: string;\n readonly version: number;\n readonly envs: readonly OpEnvelope[];\n /** The room generation the tail was written in; the first welcome decides whether it still holds. */\n readonly instance?: string;\n /** Emission epoch floors: a floor whose own sibling was collected has no other source on reload. */\n readonly floors?: readonly { readonly path: readonly (string | number)[]; readonly epoch: number }[];\n /** The last stamp minted: an acked, dropped tail still moved the clock. */\n readonly clock?: Hlc;\n};\n\n/**\n * The authority surface of a peer's op-sync, for callers that compose over a seat rather than\n * inside it: `override` for authority-bumped writes (`rebalanceContainer`, an owner's\n * authoritative commit), `captureFrontier` + `commitScope` for a commit that cites what was\n * observed earlier (a fork whose base is kept elsewhere), `liveUnder` / `liveAt` to read live\n * registers and `appliedFrontier` for the observation vector they are compared against (a\n * conflict projection: \"did the writer see this sibling\", answered by causality, never by order).\n * Deliberately narrow: no `receive`, `flush`, or `destroy` — those stay the seat's own.\n */\nexport type SeatSync<T = unknown> = Pick<\n OpSync<T>,\n | 'override'\n | 'captureFrontier'\n | 'commitScope'\n | 'liveUnder'\n | 'liveAt'\n | 'appliedFrontier'\n>;\n\nexport type MeshSyncRef<T extends object = Record<string, unknown>> = {\n readonly status: Signal<MeshStatus>;\n /** Composed sync-health for a user-facing surface. */\n readonly health: Signal<SyncHealth>;\n /**\n * Every local write is acknowledged by the room. `false` while a write is still in the\n * unacknowledged tail, and it stays `false` once a session ends with writes outstanding —\n * those never landed, and no later echo can arrive to change that.\n */\n readonly acked: Signal<boolean>;\n /**\n * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects\n * with the terminal reason if the session ends while writes are outstanding. The barrier\n * to await before publishing something that must contain every edit; `synced()` is a\n * connection indicator, not a save barrier.\n */\n whenAcked(): Promise<void>;\n readonly peers: Signal<readonly MeshPeer[]>;\n /** Publish this client's ephemeral presence payload (cursor, section, activity…). */\n setPresence(data: unknown): void;\n /**\n * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The\n * fork observes the room as it is now; committing emits its diff citing only those observed\n * writes, so an edit that lands on the room while the fork is open stays a concurrent value the\n * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe\n * the room and commit on top of the latest instead. `discard()` drops the staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */\n readonly sync: SeatSync<T>;\n close(): void;\n};\n\nconst OUTBOX_DEBOUNCE_MS = 300;\n\n/**\n * Replicates a signal store across clients through a relay room: local writes emit stamped\n * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot\n * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.\n * A synced store reads exactly like a local one — connection state surfaces only through\n * `status` and the transition scope.\n */\nexport function meshSync<T extends object>(\n source: WritableSignal<T>,\n opt: MeshSyncOptions,\n): MeshSyncRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const status = signal<MeshStatus>('connecting');\n const lastReason = signal<string | undefined>(undefined);\n const lastSyncedAt = signal<number | undefined>(undefined);\n const droppedOffline = signal(0);\n const acked = signal(true); // nothing has been written yet\n const refused = signal(0);\n const droppedInvalid = signal(0);\n const peerMap = signal<ReadonlyMap<string, MeshPeer>>(new Map());\n const peers = computed(() => [...peerMap().values()]);\n const policyVersion = opt.policyVersion ?? 0;\n\n const health = computed<SyncHealth>(() => {\n const at = lastSyncedAt();\n const dropped = droppedOffline();\n const invalid = droppedInvalid();\n const extra = {\n ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),\n ...(refused() > 0 ? { refusedWrites: refused() } : undefined),\n ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),\n };\n switch (status()) {\n case 'live':\n return { status: 'live', lastSyncedAt: at, ...extra };\n case 'ejected': {\n const reason = lastReason();\n return reason && OUTDATED_REASONS.has(reason)\n ? { status: 'outdated', reason, lastSyncedAt: at, ...extra }\n : { status: 'ejected', reason, lastSyncedAt: at, ...extra };\n }\n default: // connecting / reconnecting / closed — not reachable\n return { status: 'offline', lastSyncedAt: at, ...extra };\n }\n });\n\n // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything\n let sync!: OpSync<T>;\n let session: MeshSession | undefined;\n let started = false;\n let closed = false;\n let pendingPresence: { data: unknown } | undefined;\n let persistTimer: ReturnType<typeof setTimeout> | undefined;\n let releaseLock: (() => void) | undefined;\n let cancelLock: (() => void) | undefined;\n\n const doPersist = (): void => {\n if (closed || !opt.outbox || !started || !session) return;\n const instance = session.instance();\n const clock = sync.lastStamp();\n const payload: PersistedOutbox = {\n origin: sync.origin,\n version: sync.watermark()[sync.origin] ?? 0,\n envs: session.unackedEnvs(),\n ...(instance ? { instance } : {}),\n floors: sync.floors(),\n ...(clock ? { clock } : {}),\n };\n void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));\n };\n // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)\n const persistOutbox = (immediate = false): void => {\n if (!opt.outbox) return;\n if (immediate) {\n if (persistTimer !== undefined) clearTimeout(persistTimer);\n persistTimer = undefined;\n doPersist();\n return;\n }\n if (persistTimer !== undefined) return;\n persistTimer = setTimeout(() => {\n persistTimer = undefined;\n doPersist();\n }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);\n };\n\n const dropLocks = (): void => {\n cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown\n releaseLock?.(); // free a held lock for the next waiting tab\n cancelLock = releaseLock = undefined;\n };\n\n // Only a tail this boot could actually get admitted is worth resending: recorded under\n // this writer, on the current proto and policyVersion pins (the relay rejects a stale pin\n // per envelope, so restoring one would eject the boot, persist the tail intact, and brick\n // every boot after). Anything else drops loudly instead.\n const restorable = (env: OpEnvelope): boolean =>\n env.proto === OP_PROTO_VERSION &&\n env.writer === opt.writer &&\n env.policyVersion === policyVersion &&\n env.ops.every(\n (op) =>\n Array.isArray((op as SyncOp).cites) &&\n typeof (op as SyncOp).epoch === 'number',\n );\n\n const initCore = (restore?: PersistedOutbox): void => {\n if (closed) return;\n sync = opSync(source, {\n writer: opt.writer,\n instance: restore?.instance,\n policies: opt.policies,\n policyVersion,\n injector,\n onReject: (_env, reason) => {\n droppedInvalid.update((n) => n + 1);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`,\n );\n }\n },\n });\n started = true;\n session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n instance: restore?.instance,\n reconnect: opt.reconnect,\n hooks: {\n onRefused: (env, reason) => {\n refused.update((n) => n + 1);\n opt.onRefused?.(env, reason);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] the relay refused a write (${reason}); it is not in the room and the store was rehydrated`,\n );\n }\n },\n onStatus: (s, reason) => {\n if (s === 'ejected' || s === 'closed') {\n closed = true;\n lastReason.set(reason);\n }\n status.set(s);\n if ((s === 'ejected' || s === 'closed') && reason !== undefined) {\n opt.onEject?.(reason);\n }\n },\n onSynced: () => lastSyncedAt.set(Date.now()),\n onPeers: (map) => peerMap.set(map),\n onOutboxChange: () => {\n persistOutbox();\n acked.set(!session?.hasUnacked());\n },\n onTerminal: () => {\n dropLocks();\n // latched: the tail is about to be dropped from the session, but it was never\n // acknowledged, so the answer to \"is everything I wrote in the room\" stays no\n if (session?.hasUnacked()) acked.set(false);\n persistOutbox(true); // save the still-unacked tail for the next boot before dropping it\n },\n onLocalReject: (violation) => {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] local write violates the room policy — not sent',\n violation,\n );\n }\n },\n },\n });\n if (restore && (restore.envs.length > 0 || restore.version > 0)) {\n const kept = restore.envs.filter(restorable);\n const dropped = restore.envs.length - kept.length;\n if (dropped > 0) {\n droppedOffline.set(dropped);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`,\n );\n }\n }\n\n sync.restore(kept, restore.version, restore.floors, restore.clock); // → the session's subscribe repopulates its unacked tail for resend\n }\n persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe\n if (pendingPresence) {\n session.setPresence(pendingPresence.data);\n pendingPresence = undefined;\n }\n session.connect();\n };\n\n if (opt.register) {\n const connection: ResourceLike = {\n status: computed(() => {\n const s = status();\n return s === 'connecting'\n ? 'loading'\n : s === 'reconnecting'\n ? 'reloading'\n : s === 'ejected'\n ? 'error'\n : 'resolved';\n }),\n isLoading: computed(\n () => status() === 'connecting' || status() === 'reconnecting',\n ),\n hasValue: () => true,\n };\n runInInjectionContext(injector, () =>\n registerResource(connection, { suspends: opt.register === 'suspend' }),\n );\n }\n\n const teardown = (): void => {\n if (session) {\n session.close(); // no-op if already terminal; onTerminal handled locks + persist\n } else if (!closed) {\n // closed before the (async) boot ever created the session\n closed = true;\n dropLocks();\n status.set('closed');\n }\n if (started) sync.destroy();\n };\n\n injector.get(DestroyRef).onDestroy(teardown);\n\n // Load the persisted outbox, then boot with the adopted origin. A fresh/unreadable slot boots clean.\n const bootFromDisk = async (): Promise<void> => {\n if (closed || !opt.outbox) return;\n let saved: PersistedOutbox | undefined;\n try {\n const raw = await opt.outbox.store.get(opt.outbox.key);\n saved =\n raw && typeof raw === 'object' && 'origin' in raw\n ? (raw as PersistedOutbox)\n : undefined;\n } catch {\n saved = undefined; // an unreadable slot must not wedge the boot\n }\n initCore(saved);\n };\n\n const beginConnect = (): void => {\n if (closed) return;\n if (!opt.outbox) {\n initCore();\n } else if ((opt.outbox.crossTab ?? 'queue') === 'off') {\n void bootFromDisk(); // no single-writer lock — the app coordinates ownership\n } else {\n const locks = globalThis.navigator?.locks;\n if (!locks) {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] outbox crossTab:\"queue\" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock. Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:\"off\" to silence this.',\n );\n }\n void bootFromDisk();\n } else {\n const abort = new AbortController();\n cancelLock = () => abort.abort();\n void locks\n .request(\n `@mmstack/mesh:outbox:${opt.outbox.key}`,\n { mode: 'exclusive', signal: abort.signal },\n () => {\n cancelLock = undefined; // granted — no longer abortable, only releasable\n if (closed) return Promise.resolve();\n // hold the lock until teardown resolves this promise\n return new Promise<void>((release) => {\n releaseLock = release;\n void bootFromDisk();\n });\n },\n )\n .catch((e: unknown) => {\n // an aborted request is our own teardown; any other failure → degrade to no-lock\n if (!closed && (e as { name?: string })?.name !== 'AbortError') {\n void bootFromDisk();\n }\n });\n }\n }\n };\n\n if (opt.whenReady) {\n void Promise.resolve()\n .then(() => opt.whenReady?.())\n .then(\n () => beginConnect(),\n () => beginConnect(),\n );\n } else {\n beginConnect();\n }\n\n return {\n status: status.asReadonly(),\n health,\n acked: acked.asReadonly(),\n whenAcked: () => (session ? session.whenAcked() : Promise.resolve()), // nothing written yet\n peers,\n setPresence: (data) => {\n if (session) session.setPresence(data);\n else pendingPresence = { data };\n },\n fork: (forkOpt) => {\n const f = forkStore(\n source as unknown as WritableSignalStore<T & Record<string, any>>,\n forkOpt,\n );\n\n let frontier: DotFrontier = started ? sync.captureFrontier() : { seq: 0 };\n const recapture = (): void => {\n frontier = started ? sync.captureFrontier() : { seq: 0 };\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () =>\n started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n sync: {\n override: (fn) => (started ? sync.override(fn) : fn()),\n captureFrontier: () => (started ? sync.captureFrontier() : { seq: 0 }),\n commitScope: (frontier, fn) =>\n started ? sync.commitScope(frontier, fn) : fn(),\n liveUnder: (path) => (started ? sync.liveUnder(path) : []),\n liveAt: (path) => (started ? sync.liveAt(path) : []),\n appliedFrontier: () => (started ? sync.appliedFrontier() : {}),\n },\n close: teardown,\n };\n}\n","import { isDevMode } from '@angular/core';\nimport type {\n ClientMsg,\n PrincipalCtx,\n Relay,\n ServerMsg,\n} from '@mmstack/mesh-protocol';\n\n/**\n * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport\n * represents a single connection and never reconnects itself.\n */\nexport type MeshTransport = {\n send(msg: ClientMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\nexport type MeshTransportFactory = () => MeshTransport;\n\n/**\n * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and\n * flushed on open; malformed inbound frames are dropped.\n */\nexport function webSocketTransport(\n url: string,\n protocols?: string | string[],\n): MeshTransportFactory {\n return () => {\n const ws = new WebSocket(url, protocols);\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n\n ws.onopen = () => {\n for (const frame of pending.splice(0)) ws.send(frame);\n };\n ws.onmessage = (event) => {\n let msg: ServerMsg;\n try {\n msg = JSON.parse(String(event.data)) as ServerMsg;\n } catch {\n if (isDevMode()) {\n console.warn('[@mmstack/mesh] dropped unparseable frame (expected JSON text)');\n }\n return;\n }\n for (const cb of [...messageCbs]) cb(msg);\n };\n ws.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n\n return {\n send: (msg) => {\n const frame = JSON.stringify(msg);\n if (ws.readyState === WebSocket.OPEN) ws.send(frame);\n else if (ws.readyState === WebSocket.CONNECTING) pending.push(frame);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => ws.close(),\n };\n };\n}\n\n/**\n * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop\n * tests, and handy for single-process demos or an SSR-side room.\n */\nexport function directTransport(\n relay: Relay,\n ctx: PrincipalCtx,\n): MeshTransportFactory {\n return () => {\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n let open = true;\n\n const connection = relay.connect(\n {\n send: (msg) => {\n if (!open) return;\n for (const cb of [...messageCbs]) cb(msg);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n },\n ctx,\n );\n\n return {\n send: (msg) => {\n if (open) connection.receive(msg);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n };\n };\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport { MESH_PROTO_VERSION, type ServerMsg } from '@mmstack/mesh-protocol';\nimport {\n opSync,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSyncCheckpoint,\n} from '@mmstack/primitives/core';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\n/** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */\nexport type DataChannelLike = {\n send(frame: string): void;\n onMessage(cb: (frame: string) => void): () => void;\n onOpen(cb: () => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\n/**\n * Creates one peer link. `polite` assigns the perfect-negotiation role (derived\n * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads\n * through the relay; `signal` delivers the remote side's payloads.\n */\nexport type PeerConnector = (opt: {\n readonly remote: string;\n readonly polite: boolean;\n readonly sendSignal: (data: unknown) => void;\n}) => {\n readonly channel: DataChannelLike;\n signal(data: unknown): void;\n close(): void;\n};\n\n/** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */\nexport function rtcPeerConnector(config?: RTCConfiguration): PeerConnector {\n return ({ polite, sendSignal }) => {\n const pc = new RTCPeerConnection(config);\n const messageCbs = new Set<(frame: string) => void>();\n const openCbs = new Set<() => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n let dc: RTCDataChannel | null = null;\n let makingOffer = false;\n let ignoreOffer = false;\n\n const attach = (channel: RTCDataChannel): void => {\n dc = channel;\n channel.onmessage = (e) => {\n for (const cb of [...messageCbs]) cb(String(e.data));\n };\n channel.onopen = () => {\n for (const frame of pending.splice(0)) channel.send(frame);\n for (const cb of [...openCbs]) cb();\n };\n channel.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n };\n\n if (!polite) attach(pc.createDataChannel('mmstack-mesh'));\n else pc.ondatachannel = (e) => attach(e.channel);\n\n pc.onicecandidate = (e) => {\n if (e.candidate) sendSignal({ ice: e.candidate.toJSON() });\n };\n pc.onnegotiationneeded = async () => {\n try {\n makingOffer = true;\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n } finally {\n makingOffer = false;\n }\n };\n\n return {\n channel: {\n send: (frame) => {\n if (dc && dc.readyState === 'open') dc.send(frame);\n else pending.push(frame);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n close: () => dc?.close(),\n },\n signal: async (data) => {\n const { description, ice } = (data ?? {}) as {\n description?: RTCSessionDescriptionInit;\n ice?: RTCIceCandidateInit;\n };\n if (description) {\n const collision =\n description.type === 'offer' &&\n (makingOffer || pc.signalingState !== 'stable');\n ignoreOffer = !polite && collision;\n if (ignoreOffer) return;\n await pc.setRemoteDescription(description);\n if (description.type === 'offer') {\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n }\n } else if (ice) {\n try {\n await pc.addIceCandidate(ice);\n } catch (err) {\n if (!ignoreOffer) throw err;\n }\n }\n },\n close: () => {\n dc?.close();\n pc.close();\n },\n };\n };\n}\n\ntype P2PMsg =\n | { t: 'hello'; wm: Record<string, number> }\n // the full checkpoint (root + register state + watermark), NOT a bare value: the covered\n // side must inherit supersession state or already-superseded stragglers would resurrect\n | { t: 'state'; state: OpSyncCheckpoint<object> }\n | { t: 'uptodate' }\n | { t: 'env'; env: OpEnvelope };\n\nexport type WebRtcMeshOptions = {\n readonly room: string;\n readonly writer: string;\n /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */\n readonly signaling: MeshTransportFactory;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policyVersion?: number;\n readonly injector?: Injector;\n};\n\nexport type WebRtcMeshRef = {\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins with an OPEN data channel. */\n readonly peers: Signal<readonly string[]>;\n close(): void;\n};\n\ntype Peer = {\n link: ReturnType<PeerConnector>;\n open: boolean;\n unsubs: (() => void)[];\n};\n\n/**\n * Peer-to-peer mesh sync: the relay only signals\n * and tracks membership; envelopes flow over WebRTC data channels and converge via the\n * per-path register map. Catch-up is pairwise: on channel open both sides exchange\n * watermarks; a side whose state is strictly covered hydrates from the other's FULL\n * checkpoint (root + per-path register state + watermark), so supersession and precedence\n * carry over intact: a late joiner is indistinguishable from a peer that saw every\n * envelope. Two peers that each hold envelopes the other lacks keep their convergent\n * go-forward guarantees but do not exchange the missed envelopes retroactively.\n */\nexport function webRtcMesh<T extends object>(\n source: WritableSignal<T>,\n opt: WebRtcMeshOptions,\n): WebRtcMeshRef {\n const injector = opt.injector ?? inject(Injector);\n const connector = opt.connector ?? rtcPeerConnector();\n const status = signal<'connecting' | 'live'>('connecting');\n const openPeers = signal<ReadonlySet<string>>(new Set());\n const peers = new Map<string, Peer>();\n let signalingUnsubs: (() => void)[] = [];\n let transport: MeshTransport | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n\n const sync = opSync(source, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion: opt.policyVersion,\n injector,\n });\n\n const covered = (\n mine: Record<string, number>,\n theirs: Record<string, number>,\n ): boolean => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);\n\n const sendTo = (peer: Peer, msg: P2PMsg): void => {\n peer.link.channel.send(JSON.stringify(msg));\n };\n\n const broadcast = (msg: P2PMsg): void => {\n for (const peer of peers.values()) {\n if (peer.open) sendTo(peer, msg);\n }\n };\n\n const dropPeer = (origin: string): void => {\n const peer = peers.get(origin);\n if (!peer) return;\n peers.delete(origin);\n for (const unsub of peer.unsubs) unsub();\n peer.link.close();\n openPeers.update((set) => {\n const next = new Set(set);\n next.delete(origin);\n return next;\n });\n };\n\n const ensurePeer = (origin: string): Peer => {\n let peer = peers.get(origin);\n if (peer) return peer;\n const link = connector({\n remote: origin,\n polite: sync.origin > origin,\n sendSignal: (data) =>\n transport?.send({ t: 'signal', room: opt.room, to: origin, data }),\n });\n peer = { link, open: false, unsubs: [] };\n peers.set(origin, peer);\n peer.unsubs.push(\n link.channel.onOpen(() => {\n peer!.open = true;\n openPeers.update((set) => new Set(set).add(origin));\n sendTo(peer!, { t: 'hello', wm: sync.watermark() });\n }),\n link.channel.onMessage((frame) => {\n let msg: P2PMsg;\n try {\n msg = JSON.parse(frame) as P2PMsg;\n } catch {\n return;\n }\n handlePeerMsg(peer!, msg);\n }),\n link.channel.onClose(() => dropPeer(origin)),\n );\n return peer;\n };\n\n const handlePeerMsg = (peer: Peer, msg: P2PMsg): void => {\n switch (msg.t) {\n case 'hello': {\n const snap = sync.snapshot();\n if (covered(snap.wm, msg.wm)) sendTo(peer, { t: 'uptodate' });\n else sendTo(peer, { t: 'state', state: snap });\n return;\n }\n case 'state': {\n if (covered(sync.watermark(), msg.state.wm)) {\n sync.hydrate(msg.state as OpSyncCheckpoint<T>);\n }\n return;\n }\n case 'uptodate':\n return;\n case 'env':\n sync.receive(msg.env);\n return;\n }\n };\n\n const handleSignaling = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome':\n for (const origin of msg.members) ensurePeer(origin);\n status.set('live');\n return;\n case 'member':\n if (msg.gone) dropPeer(msg.origin);\n else ensurePeer(msg.origin);\n return;\n case 'signal':\n ensurePeer(msg.from).link.signal(msg.data);\n return;\n case 'reject':\n close();\n return;\n }\n };\n\n const connectSignaling = (): void => {\n if (closed) return;\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n const t = opt.signaling();\n transport = t;\n signalingUnsubs = [\n t.onMessage(handleSignaling),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n reconnectTimer = setTimeout(connectSignaling, 1000);\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion ?? 0,\n });\n };\n\n const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);\n unsubLocal();\n for (const origin of [...peers.keys()]) dropPeer(origin);\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n transport?.close();\n transport = null;\n sync.destroy();\n status.set('connecting');\n };\n\n injector.get(DestroyRef).onDestroy(close);\n connectSignaling();\n\n return {\n status: status.asReadonly(),\n peers: computed(() => [...openPeers()]),\n close,\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;;AAmIA,MAAM,iBAAiB,GAAG,GAAG;AAEvB,SAAU,WAAW,CACzB,GAA0B,EAAA;AAE1B,IAAA,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,GAAG;AAC3B,IAAA,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,IAAI;AAC/B,QAAA,GAAG,EAAE,CAAC,EAAc,EAAE,EAAU,KAAK,UAAU,CAAC,EAAE,EAAE,EAAE,CAAC;QACvD,KAAK,EAAE,CAAC,MAAe,KACrB,YAAY,CAAC,MAAuC,CAAC;KACxD;IAED,IAAI,MAAM,GAAe,YAAY;IACrC,MAAM,UAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACjD,IAAA,MAAM,OAAO,GAAG,IAAI,GAAG,EAAsB;AAC7C,IAAA,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB;AACvC,IAAA,MAAM,UAAU,GAAG,CAAC,GAAwC,KAC1D,CAAA,EAAG,GAAG,CAAC,MAAM,CAAA,CAAA,EAAI,GAAG,CAAC,OAAO,EAAE;IAChC,IAAI,OAAO,GAAG,CAAC;AACf,IAAA,IAAI,QAAQ,GAAuB,GAAG,CAAC,QA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Q,CAAC,MAAM,CAAC;QACxD,KAAK,MAAM,KAAK,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;AAAE,YAAA,KAAK,EAAE;QACtD,SAAS,EAAE,KAAK,EAAE;QAClB,SAAS,GAAG,IAAI;QAChB,IAAI,CAAC,OAAO,EAAE;AACd,QAAA,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC;AAC1B,IAAA,CAAC;IAED,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC;AACzC,IAAA,gBAAgB,EAAE;IAElB,OAAO;AACL,QAAA,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE;QAC3B,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,SAAS,EAAE,CAAC,CAAC;QACvC,KAAK;KACN;AACH;;ACjVA;;AAEG;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mmstack/mesh",
|
|
3
|
-
"version": "21.
|
|
3
|
+
"version": "21.8.0",
|
|
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": ">=21 <22",
|
|
23
|
-
"@mmstack/primitives": ">=21.
|
|
24
|
-
"@mmstack/mesh-protocol": ">=0.
|
|
23
|
+
"@mmstack/primitives": ">=21.14 <22",
|
|
24
|
+
"@mmstack/mesh-protocol": ">=0.9 <1"
|
|
25
25
|
},
|
|
26
26
|
"sideEffects": false,
|
|
27
27
|
"module": "fesm2022/mmstack-mesh.mjs",
|
package/types/mmstack-mesh.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ClientMsg, ServerMsg, Relay, PrincipalCtx, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
|
|
2
|
-
import { OpSync, MergePolicyEntry, AsyncStore, ForkStoreOptions, SyncedFork, WritableSignalStore, StoreOp, toStoreOptions } from '@mmstack/primitives/core';
|
|
2
|
+
import { OpSync, MergePolicyEntry, OpEnvelope, AsyncStore, ForkStoreOptions, SyncedFork, WritableSignalStore, StoreOp, toStoreOptions } from '@mmstack/primitives/core';
|
|
3
3
|
import { Injector, Signal, WritableSignal } from '@angular/core';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -44,6 +44,11 @@ type SyncHealth = {
|
|
|
44
44
|
* so they are dropped (loudly) instead of being upgraded with fabricated citations.
|
|
45
45
|
*/
|
|
46
46
|
readonly droppedOfflineWrites?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Writes the relay refused on this session: they are not in the room. Each was handed to
|
|
49
|
+
* `onRefused` with its values, and the store was rehydrated from a fresh snapshot after it.
|
|
50
|
+
*/
|
|
51
|
+
readonly refusedWrites?: number;
|
|
47
52
|
/**
|
|
48
53
|
* Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id
|
|
49
54
|
* or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a
|
|
@@ -82,6 +87,8 @@ type MeshSyncOptions = {
|
|
|
82
87
|
/** Register with the nearest transition scope so (re)connection surfaces as `pending`. */
|
|
83
88
|
readonly register?: 'track' | 'suspend';
|
|
84
89
|
readonly onEject?: (reason: string) => void;
|
|
90
|
+
/** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */
|
|
91
|
+
readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
|
|
85
92
|
/**
|
|
86
93
|
* Hold the connection until the local base is assembled. `meshSync` awaits this before it connects
|
|
87
94
|
* (and before it restores an `outbox`), so a store hydrated from another source first (a worker
|
|
@@ -130,6 +137,19 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
|
|
|
130
137
|
readonly status: Signal<MeshStatus>;
|
|
131
138
|
/** Composed sync-health for a user-facing surface. */
|
|
132
139
|
readonly health: Signal<SyncHealth>;
|
|
140
|
+
/**
|
|
141
|
+
* Every local write is acknowledged by the room. `false` while a write is still in the
|
|
142
|
+
* unacknowledged tail, and it stays `false` once a session ends with writes outstanding —
|
|
143
|
+
* those never landed, and no later echo can arrive to change that.
|
|
144
|
+
*/
|
|
145
|
+
readonly acked: Signal<boolean>;
|
|
146
|
+
/**
|
|
147
|
+
* Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
|
|
148
|
+
* with the terminal reason if the session ends while writes are outstanding. The barrier
|
|
149
|
+
* to await before publishing something that must contain every edit; `synced()` is a
|
|
150
|
+
* connection indicator, not a save barrier.
|
|
151
|
+
*/
|
|
152
|
+
whenAcked(): Promise<void>;
|
|
133
153
|
readonly peers: Signal<readonly MeshPeer[]>;
|
|
134
154
|
/** Publish this client's ephemeral presence payload (cursor, section, activity…). */
|
|
135
155
|
setPresence(data: unknown): void;
|
|
@@ -208,6 +228,8 @@ type AgentSeatOptions = {
|
|
|
208
228
|
*/
|
|
209
229
|
readonly context?: toStoreOptions;
|
|
210
230
|
readonly onEject?: (reason: string) => void;
|
|
231
|
+
/** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */
|
|
232
|
+
readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
|
|
211
233
|
};
|
|
212
234
|
type AgentSeat<T extends object> = {
|
|
213
235
|
/** The live converging replica. Reads exactly like a local signal store. */
|
|
@@ -241,6 +263,17 @@ type AgentSeat<T extends object> = {
|
|
|
241
263
|
* staged edits.
|
|
242
264
|
*/
|
|
243
265
|
fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
|
|
266
|
+
/**
|
|
267
|
+
* Every local write is acknowledged by the room. `false` while a write is still in the
|
|
268
|
+
* unacknowledged tail, and it stays `false` once the seat ends with writes outstanding.
|
|
269
|
+
*/
|
|
270
|
+
acked(): boolean;
|
|
271
|
+
/**
|
|
272
|
+
* Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
|
|
273
|
+
* with the terminal reason if the seat ends while writes are outstanding. The barrier to
|
|
274
|
+
* await before handing a result to something that must contain every edit.
|
|
275
|
+
*/
|
|
276
|
+
whenAcked(): Promise<void>;
|
|
244
277
|
/** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */
|
|
245
278
|
setPresence(data: unknown): void;
|
|
246
279
|
/** Authority surface over this seat's op-sync; see {@link SeatSync}. */
|