@mmstack/mesh 22.8.1 → 22.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { createWatch } from '@angular/core/primitives/signals';
2
- import { createConvergingApply, createStoreContext, store, opSync, forkStore, OP_PROTO_VERSION, registerResource } from '@mmstack/primitives/core';
2
+ import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource, throttled } from '@mmstack/primitives/core';
3
3
  import { MESH_PROTO_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
4
- import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef } from '@angular/core';
4
+ import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef, effect, untracked } from '@angular/core';
5
5
 
6
6
  const RECONNECT_BASE_MS = 500;
7
7
  function meshSession(opt) {
@@ -504,7 +504,8 @@ function setAtPath(node, path, value) {
504
504
  if (current === null || typeof current !== 'object')
505
505
  break;
506
506
  const key = resolveKey(current, seg);
507
- if (!Object.hasOwn(current, key))
507
+ // a key the node answers itself has no child node; the rest of the path is set on this value
508
+ if (!Object.hasOwn(current, key) || isStoreReservedKey(key))
508
509
  break;
509
510
  const child = cursor[key];
510
511
  if (typeof child !== 'function')
@@ -984,38 +985,68 @@ function directTransport(relay, ctx) {
984
985
  };
985
986
  }
986
987
 
988
+ /** The single reliable channel every link carries when no channels are asked for. */
989
+ const defaultPeerChannels = [
990
+ { label: 'mmstack-mesh' },
991
+ ];
987
992
  /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
988
993
  function rtcPeerConnector(config) {
989
- return ({ polite, sendSignal }) => {
994
+ return ({ polite, sendSignal, channels = defaultPeerChannels }) => {
990
995
  const pc = new RTCPeerConnection(config);
991
- const messageCbs = new Set();
992
- const openCbs = new Set();
993
- const closeCbs = new Set();
994
- const pending = [];
995
- let dc = null;
996
996
  let makingOffer = false;
997
997
  let ignoreOffer = false;
998
- const attach = (channel) => {
999
- dc = channel;
1000
- channel.onmessage = (e) => {
1001
- for (const cb of [...messageCbs])
1002
- cb(String(e.data));
998
+ const makeChannel = () => {
999
+ const messageCbs = new Set();
1000
+ const openCbs = new Set();
1001
+ const closeCbs = new Set();
1002
+ const pending = [];
1003
+ let dc = null;
1004
+ const attach = (channel) => {
1005
+ dc = channel;
1006
+ channel.onmessage = (e) => {
1007
+ for (const cb of [...messageCbs])
1008
+ cb(String(e.data));
1009
+ };
1010
+ channel.onopen = () => {
1011
+ for (const frame of pending.splice(0))
1012
+ channel.send(frame);
1013
+ for (const cb of [...openCbs])
1014
+ cb();
1015
+ };
1016
+ channel.onclose = () => {
1017
+ for (const cb of [...closeCbs])
1018
+ cb();
1019
+ };
1003
1020
  };
1004
- channel.onopen = () => {
1005
- for (const frame of pending.splice(0))
1006
- channel.send(frame);
1007
- for (const cb of [...openCbs])
1008
- cb();
1009
- };
1010
- channel.onclose = () => {
1011
- for (const cb of [...closeCbs])
1012
- cb();
1021
+ const like = {
1022
+ send: (frame) => {
1023
+ if (dc && dc.readyState === 'open')
1024
+ dc.send(frame);
1025
+ else
1026
+ pending.push(frame);
1027
+ },
1028
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1029
+ onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1030
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1031
+ close: () => dc?.close(),
1013
1032
  };
1033
+ return { attach, like };
1014
1034
  };
1015
- if (!polite)
1016
- attach(pc.createDataChannel('mmstack-mesh'));
1017
- else
1018
- pc.ondatachannel = (e) => attach(e.channel);
1035
+ const made = new Map(channels.map((c) => [c.label, makeChannel()]));
1036
+ // the impolite side opens every channel; the polite side adopts them by label
1037
+ if (!polite) {
1038
+ for (const spec of channels) {
1039
+ const init = {};
1040
+ if (spec.ordered !== undefined)
1041
+ init.ordered = spec.ordered;
1042
+ if (spec.maxRetransmits !== undefined)
1043
+ init.maxRetransmits = spec.maxRetransmits;
1044
+ made.get(spec.label)?.attach(pc.createDataChannel(spec.label, init));
1045
+ }
1046
+ }
1047
+ else {
1048
+ pc.ondatachannel = (e) => made.get(e.channel.label)?.attach(e.channel);
1049
+ }
1019
1050
  pc.onicecandidate = (e) => {
1020
1051
  if (e.candidate)
1021
1052
  sendSignal({ ice: e.candidate.toJSON() });
@@ -1030,19 +1061,12 @@ function rtcPeerConnector(config) {
1030
1061
  makingOffer = false;
1031
1062
  }
1032
1063
  };
1064
+ const byLabel = {};
1065
+ for (const [label, ch] of made)
1066
+ byLabel[label] = ch.like;
1033
1067
  return {
1034
- channel: {
1035
- send: (frame) => {
1036
- if (dc && dc.readyState === 'open')
1037
- dc.send(frame);
1038
- else
1039
- pending.push(frame);
1040
- },
1041
- onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1042
- onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1043
- onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1044
- close: () => dc?.close(),
1045
- },
1068
+ channel: byLabel[channels[0].label],
1069
+ channels: byLabel,
1046
1070
  signal: async (data) => {
1047
1071
  const { description, ice } = (data ?? {});
1048
1072
  if (description) {
@@ -1068,53 +1092,77 @@ function rtcPeerConnector(config) {
1068
1092
  }
1069
1093
  },
1070
1094
  close: () => {
1071
- dc?.close();
1095
+ for (const ch of made.values())
1096
+ ch.like.close();
1072
1097
  pc.close();
1073
1098
  },
1074
1099
  };
1075
1100
  };
1076
1101
  }
1077
1102
  /**
1078
- * Peer-to-peer mesh sync: the relay only signals
1079
- * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1080
- * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1081
- * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1082
- * checkpoint (root + per-path register state + watermark), so supersession and precedence
1083
- * carry over intact: a late joiner is indistinguishable from a peer that saw every
1084
- * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1085
- * go-forward guarantees but do not exchange the missed envelopes retroactively.
1103
+ * A signal payload split into its addressing and the connector's part: `link` is the sending
1104
+ * instance, `to` the receiving instance it was bound to when it sent (absent until it is).
1105
+ */
1106
+ const unwrapSignal = (data) => {
1107
+ if (typeof data !== 'object' || data === null)
1108
+ return { payload: data };
1109
+ const { link, to, ...rest } = data;
1110
+ if (typeof link !== 'string')
1111
+ return { payload: data };
1112
+ return {
1113
+ link,
1114
+ to: typeof to === 'string' ? to : undefined,
1115
+ payload: Object.keys(rest).length ? rest : undefined,
1116
+ };
1117
+ };
1118
+ /**
1119
+ * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
1120
+ * room, set up from relay membership and negotiated over relay `signal` frames. Each link
1121
+ * carries the same labelled channels; frames are opaque strings, what they mean is the
1122
+ * consumer's business.
1086
1123
  *
1087
- * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1088
- * relay-backed session over the same document a peer channel may hand on only envelopes the
1089
- * relay has sequenced, never a peer's own unacknowledged writes.
1124
+ * An origin is one seat: the relay hands a second connection with the same origin the seat
1125
+ * and reports it to the room as a plain join. Links tell seats apart by instance, not by
1126
+ * order: every link announces a random instance id in its signals and, once it knows the
1127
+ * instance across, addresses its signals to it. A signal addressed to an instance this side
1128
+ * no longer has is dropped. An unaddressed signal from an instance other than the one linked
1129
+ * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed
1130
+ * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
1131
+ * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
1132
+ * still take the seat from each other on every reconnect; give each tab its own origin.
1090
1133
  */
1091
- function webRtcMesh(source, opt) {
1134
+ function peerLinks(opt) {
1092
1135
  const injector = opt.injector ?? inject(Injector);
1093
1136
  const connector = opt.connector ?? rtcPeerConnector();
1137
+ const specs = opt.channels?.length ? opt.channels : defaultPeerChannels;
1138
+ const labels = specs.map((c) => c.label);
1139
+ const primary = labels[0];
1094
1140
  const status = signal('connecting', /* @ts-ignore */
1095
1141
  ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1096
1142
  const openPeers = signal(new Set(), /* @ts-ignore */
1097
1143
  ...(ngDevMode ? [{ debugName: "openPeers" }] : /* istanbul ignore next */ []));
1144
+ const members = signal(new Set(), /* @ts-ignore */
1145
+ ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
1098
1146
  const peers = new Map();
1147
+ const openCbs = new Set();
1148
+ const messageCbs = new Set();
1149
+ const closeCbs = new Set();
1150
+ const endCbs = new Set();
1151
+ const memberCbs = new Set();
1099
1152
  let signalingUnsubs = [];
1100
1153
  let transport = null;
1101
1154
  let reconnectTimer;
1155
+ let connected = false;
1102
1156
  let closed = false;
1103
- const sync = opSync(source, {
1104
- writer: opt.writer,
1105
- policies: opt.policies,
1106
- policyVersion: opt.policyVersion,
1107
- injector,
1108
- });
1109
- const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1110
- const sendTo = (peer, msg) => {
1111
- peer.link.channel.send(JSON.stringify(msg));
1112
- };
1113
- const broadcast = (msg) => {
1114
- for (const peer of peers.values()) {
1115
- if (peer.open)
1116
- sendTo(peer, msg);
1117
- }
1157
+ // links are told apart by instance, never by order: a random tag plus a counter
1158
+ const tag = Math.random().toString(36).slice(2, 10);
1159
+ let linkSeq = 0;
1160
+ const port = typeof opt.signaling === 'function' ? null : opt.signaling;
1161
+ const sendSignal = (msg) => {
1162
+ if (port)
1163
+ port.send(msg);
1164
+ else
1165
+ transport?.send(msg);
1118
1166
  };
1119
1167
  const dropPeer = (origin) => {
1120
1168
  const peer = peers.get(origin);
@@ -1129,75 +1177,149 @@ function webRtcMesh(source, opt) {
1129
1177
  next.delete(origin);
1130
1178
  return next;
1131
1179
  });
1180
+ for (const cb of [...closeCbs])
1181
+ cb(origin);
1132
1182
  };
1133
- const ensurePeer = (origin) => {
1134
- let peer = peers.get(origin);
1135
- if (peer)
1136
- return peer;
1137
- const link = connector({
1138
- remote: origin,
1139
- polite: sync.origin > origin,
1140
- sendSignal: (data) => transport?.send({ t: 'signal', room: opt.room, to: origin, data }),
1141
- });
1142
- peer = { link, open: false, unsubs: [] };
1143
- peers.set(origin, peer);
1144
- peer.unsubs.push(link.channel.onOpen(() => {
1145
- peer.open = true;
1146
- openPeers.update((set) => new Set(set).add(origin));
1147
- sendTo(peer, { t: 'hello', wm: sync.watermark() });
1148
- }), link.channel.onMessage((frame) => {
1149
- let msg;
1150
- try {
1151
- msg = JSON.parse(frame);
1152
- }
1153
- catch {
1183
+ /**
1184
+ * Builds the link to `origin`; `remote` is the instance on the other side when the link is
1185
+ * built in answer to one of its signals, so everything this side sends is addressed to it.
1186
+ */
1187
+ const ensurePeer = (origin, remote) => {
1188
+ const existing = peers.get(origin);
1189
+ if (existing)
1190
+ return existing;
1191
+ const id = `${tag}.${++linkSeq}`;
1192
+ // signals the connector sends while it is still being built wait until the peer is
1193
+ // registered, so the remote's synchronous answer finds it instead of building another
1194
+ let building = [];
1195
+ let retired = false;
1196
+ const signal = (data) => {
1197
+ if (retired)
1154
1198
  return;
1155
- }
1156
- handlePeerMsg(peer, msg);
1157
- }), link.channel.onClose(() => dropPeer(origin)));
1158
- return peer;
1159
- };
1160
- const handlePeerMsg = (peer, msg) => {
1161
- switch (msg.t) {
1162
- case 'hello': {
1163
- const snap = sync.snapshot();
1164
- if (covered(snap.wm, msg.wm))
1165
- sendTo(peer, { t: 'uptodate' });
1166
- else
1167
- sendTo(peer, { t: 'state', state: snap });
1199
+ if (building) {
1200
+ building.push(data);
1168
1201
  return;
1169
1202
  }
1170
- case 'state': {
1171
- if (covered(sync.watermark(), msg.state.wm)) {
1172
- sync.hydrate(msg.state);
1203
+ const stamped = typeof data === 'object' && data !== null
1204
+ ? {
1205
+ ...data,
1206
+ link: id,
1207
+ ...(p.remote === undefined ? {} : { to: p.remote }),
1173
1208
  }
1174
- return;
1209
+ : data;
1210
+ sendSignal({ t: 'signal', room: opt.room, to: origin, data: stamped });
1211
+ };
1212
+ const link = connector({
1213
+ remote: origin,
1214
+ polite: opt.origin > origin,
1215
+ sendSignal: signal,
1216
+ channels: specs,
1217
+ });
1218
+ const p = {
1219
+ id,
1220
+ remote,
1221
+ link,
1222
+ channels: new Map(),
1223
+ unsubs: [() => (retired = true)],
1224
+ };
1225
+ peers.set(origin, p);
1226
+ const early = building;
1227
+ building = null;
1228
+ // announce the instance, so a side that still holds a link to an earlier seat of this
1229
+ // origin (a takeover the relay reports as a plain join) replaces it
1230
+ signal({});
1231
+ for (const data of early)
1232
+ signal(data);
1233
+ for (const label of labels) {
1234
+ const channel = link.channels?.[label] ??
1235
+ (label === primary ? link.channel : undefined);
1236
+ if (!channel) {
1237
+ if (isDevMode()) {
1238
+ console.warn(`[@mmstack/mesh] the peer connector returned no channel labelled '${label}'`);
1239
+ }
1240
+ continue;
1175
1241
  }
1176
- case 'uptodate':
1177
- return;
1178
- case 'env':
1179
- sync.receive(msg.env);
1180
- return;
1242
+ const state = { channel, open: false };
1243
+ p.channels.set(label, state);
1244
+ p.unsubs.push(channel.onOpen(() => {
1245
+ state.open = true;
1246
+ if (labels.every((l) => p.channels.get(l)?.open)) {
1247
+ openPeers.update((set) => new Set(set).add(origin));
1248
+ }
1249
+ for (const cb of [...openCbs])
1250
+ cb(origin, label);
1251
+ }), channel.onMessage((frame) => {
1252
+ for (const cb of [...messageCbs])
1253
+ cb(origin, frame, label);
1254
+ }), channel.onClose(() => dropPeer(origin)));
1181
1255
  }
1256
+ return p;
1257
+ };
1258
+ const setMembers = (origins) => {
1259
+ const next = new Set(origins);
1260
+ members.set(next);
1261
+ for (const cb of [...memberCbs])
1262
+ cb([...next]);
1263
+ };
1264
+ const welcomeMembers = (origins) => {
1265
+ setMembers(origins);
1266
+ for (const origin of [...peers.keys()])
1267
+ if (!members().has(origin))
1268
+ dropPeer(origin);
1269
+ for (const origin of origins)
1270
+ ensurePeer(origin);
1271
+ status.set('live');
1182
1272
  };
1183
1273
  const handleSignaling = (msg) => {
1184
- if (msg.room !== opt.room)
1274
+ if (closed || msg.room !== opt.room)
1185
1275
  return;
1186
1276
  switch (msg.t) {
1187
1277
  case 'welcome':
1188
- for (const origin of msg.members)
1189
- ensurePeer(origin);
1190
- status.set('live');
1278
+ welcomeMembers(msg.members);
1191
1279
  return;
1192
1280
  case 'member':
1281
+ setMembers(msg.gone
1282
+ ? [...members()].filter((origin) => origin !== msg.origin)
1283
+ : [...new Set([...members(), msg.origin])]);
1193
1284
  if (msg.gone)
1194
1285
  dropPeer(msg.origin);
1195
1286
  else
1196
1287
  ensurePeer(msg.origin);
1197
1288
  return;
1198
- case 'signal':
1199
- ensurePeer(msg.from).link.signal(msg.data);
1289
+ case 'signal': {
1290
+ const { link, to, payload } = unwrapSignal(msg.data);
1291
+ let peer = peers.get(msg.from);
1292
+ if (link === undefined) {
1293
+ // an unstamped sender: nothing to tell instances apart by
1294
+ peer ??= ensurePeer(msg.from);
1295
+ }
1296
+ else if (to !== undefined && to !== peer?.id) {
1297
+ // addressed to an instance this side no longer has: a retired link's leftovers
1298
+ return;
1299
+ }
1300
+ else if (!peer) {
1301
+ peer = ensurePeer(msg.from, link);
1302
+ }
1303
+ else if (peer.remote === undefined) {
1304
+ peer.remote = link;
1305
+ }
1306
+ else if (peer.remote !== link) {
1307
+ if (to === undefined) {
1308
+ // a new instance over there that does not know this side yet: a new seat or a
1309
+ // restarted link, so this side rebuilds, addressing it, which is what makes the
1310
+ // rebuild final: the other side never rebuilds in answer to an addressed signal
1311
+ dropPeer(msg.from);
1312
+ peer = ensurePeer(msg.from, link);
1313
+ }
1314
+ else {
1315
+ // built for this very instance, so it is the newer end of this link: adopt it
1316
+ peer.remote = link;
1317
+ }
1318
+ }
1319
+ if (payload !== undefined)
1320
+ peer.link.signal(payload);
1200
1321
  return;
1322
+ }
1201
1323
  case 'reject':
1202
1324
  close();
1203
1325
  return;
@@ -1208,6 +1330,18 @@ function webRtcMesh(source, opt) {
1208
1330
  return;
1209
1331
  for (const unsub of signalingUnsubs.splice(0))
1210
1332
  unsub();
1333
+ if (port) {
1334
+ const unsub = port.onMessage(handleSignaling);
1335
+ if (closed) {
1336
+ unsub();
1337
+ return;
1338
+ }
1339
+ signalingUnsubs = [unsub];
1340
+ const current = port.members();
1341
+ if (current !== undefined)
1342
+ welcomeMembers(current);
1343
+ return;
1344
+ }
1211
1345
  const t = opt.signaling();
1212
1346
  transport = t;
1213
1347
  signalingUnsubs = [
@@ -1216,39 +1350,337 @@ function webRtcMesh(source, opt) {
1216
1350
  if (closed || transport !== t)
1217
1351
  return;
1218
1352
  transport = null;
1353
+ status.set('connecting');
1219
1354
  reconnectTimer = setTimeout(connectSignaling, 1000);
1220
1355
  }),
1221
1356
  ];
1222
1357
  t.send({
1223
1358
  t: 'hello',
1224
1359
  room: opt.room,
1225
- origin: sync.origin,
1360
+ origin: opt.origin,
1226
1361
  proto: MESH_PROTO_VERSION,
1227
1362
  policyVersion: opt.policyVersion ?? 0,
1228
1363
  });
1229
1364
  };
1230
- const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));
1365
+ const connect = () => {
1366
+ if (connected || closed)
1367
+ return;
1368
+ connected = true;
1369
+ connectSignaling();
1370
+ };
1231
1371
  const close = () => {
1232
1372
  if (closed)
1233
1373
  return;
1234
1374
  closed = true;
1235
1375
  if (reconnectTimer !== undefined)
1236
1376
  clearTimeout(reconnectTimer);
1237
- unsubLocal();
1238
1377
  for (const origin of [...peers.keys()])
1239
1378
  dropPeer(origin);
1240
1379
  for (const unsub of signalingUnsubs.splice(0))
1241
1380
  unsub();
1242
1381
  transport?.close();
1243
1382
  transport = null;
1244
- sync.destroy();
1383
+ setMembers([]);
1384
+ memberCbs.clear();
1245
1385
  status.set('connecting');
1386
+ for (const cb of [...endCbs])
1387
+ cb();
1388
+ endCbs.clear();
1389
+ };
1390
+ const openChannel = (origin, label) => {
1391
+ const state = peers.get(origin)?.channels.get(label);
1392
+ return state?.open ? state.channel : null;
1246
1393
  };
1247
1394
  injector.get(DestroyRef).onDestroy(close);
1248
- connectSignaling();
1395
+ if (opt.autoConnect !== false)
1396
+ connect();
1249
1397
  return {
1250
1398
  status: status.asReadonly(),
1251
1399
  peers: computed(() => [...openPeers()]),
1400
+ members: computed(() => [...members()]),
1401
+ onMembers: (cb) => {
1402
+ if (!closed)
1403
+ memberCbs.add(cb);
1404
+ cb([...members()]);
1405
+ return () => memberCbs.delete(cb);
1406
+ },
1407
+ channels: labels,
1408
+ onOpen: (cb) => {
1409
+ openCbs.add(cb);
1410
+ for (const [origin, peer] of peers) {
1411
+ for (const [label, state] of peer.channels) {
1412
+ if (state.open)
1413
+ cb(origin, label);
1414
+ }
1415
+ }
1416
+ return () => openCbs.delete(cb);
1417
+ },
1418
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1419
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1420
+ onEnd: (cb) => (endCbs.add(cb), () => endCbs.delete(cb)),
1421
+ send: (origin, frame, channel = primary) => {
1422
+ openChannel(origin, channel)?.send(frame);
1423
+ },
1424
+ broadcast: (frame, channel = primary) => {
1425
+ for (const origin of peers.keys())
1426
+ openChannel(origin, channel)?.send(frame);
1427
+ },
1428
+ connect,
1429
+ close,
1430
+ };
1431
+ }
1432
+
1433
+ /**
1434
+ * Peer-to-peer mesh sync: the relay only signals
1435
+ * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1436
+ * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1437
+ * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1438
+ * checkpoint (root + per-path register state + watermark), so supersession and precedence
1439
+ * carry over intact: a late joiner is indistinguishable from a peer that saw every
1440
+ * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1441
+ * go-forward guarantees but do not exchange the missed envelopes retroactively.
1442
+ *
1443
+ * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1444
+ * relay-backed session over the same document a peer channel may hand on only envelopes the
1445
+ * relay has sequenced, never a peer's own unacknowledged writes.
1446
+ */
1447
+ function webRtcMesh(source, opt) {
1448
+ const injector = opt.injector ?? inject(Injector);
1449
+ const meshChannel = defaultPeerChannels[0];
1450
+ let closed = false;
1451
+ const sync = opSync(source, {
1452
+ writer: opt.writer,
1453
+ origin: opt.origin,
1454
+ policies: opt.policies,
1455
+ policyVersion: opt.policyVersion,
1456
+ injector,
1457
+ });
1458
+ // subscribe before signaling starts: a link can open, and its first frame arrive, while
1459
+ // the hello is still being answered
1460
+ const links = peerLinks({
1461
+ room: opt.room,
1462
+ origin: sync.origin,
1463
+ signaling: opt.signaling,
1464
+ connector: opt.connector,
1465
+ channels: [
1466
+ meshChannel,
1467
+ ...(opt.channels ?? []).filter((c) => c.label !== meshChannel.label),
1468
+ ],
1469
+ policyVersion: opt.policyVersion,
1470
+ autoConnect: false,
1471
+ injector,
1472
+ });
1473
+ const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1474
+ const sendTo = (origin, msg) => {
1475
+ links.send(origin, JSON.stringify(msg));
1476
+ };
1477
+ const handlePeerMsg = (origin, msg) => {
1478
+ switch (msg.t) {
1479
+ case 'hello': {
1480
+ const snap = sync.snapshot();
1481
+ if (covered(snap.wm, msg.wm))
1482
+ sendTo(origin, { t: 'uptodate' });
1483
+ else
1484
+ sendTo(origin, { t: 'state', state: snap });
1485
+ return;
1486
+ }
1487
+ case 'state': {
1488
+ if (covered(sync.watermark(), msg.state.wm)) {
1489
+ sync.hydrate(msg.state);
1490
+ }
1491
+ return;
1492
+ }
1493
+ case 'uptodate':
1494
+ return;
1495
+ case 'env':
1496
+ sync.receive(msg.env);
1497
+ return;
1498
+ }
1499
+ };
1500
+ links.onOpen((origin, channel) => {
1501
+ if (channel === meshChannel.label)
1502
+ sendTo(origin, { t: 'hello', wm: sync.watermark() });
1503
+ });
1504
+ links.onMessage((origin, frame, channel) => {
1505
+ if (channel !== meshChannel.label)
1506
+ return;
1507
+ let msg;
1508
+ try {
1509
+ msg = JSON.parse(frame);
1510
+ }
1511
+ catch {
1512
+ return;
1513
+ }
1514
+ handlePeerMsg(origin, msg);
1515
+ });
1516
+ const unsubLocal = sync.subscribe((env) => links.broadcast(JSON.stringify({ t: 'env', env })));
1517
+ const close = () => {
1518
+ if (closed)
1519
+ return;
1520
+ closed = true;
1521
+ unsubLocal();
1522
+ links.close();
1523
+ sync.destroy();
1524
+ };
1525
+ // a relay reject ends the links; the mesh ends with them
1526
+ links.onEnd(close);
1527
+ links.connect();
1528
+ return {
1529
+ origin: sync.origin,
1530
+ status: links.status,
1531
+ peers: links.peers,
1532
+ links,
1533
+ close,
1534
+ };
1535
+ }
1536
+
1537
+ /**
1538
+ * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that
1539
+ * waits for a retransmit is already stale, and ordering would hold newer frames behind it.
1540
+ * Put it in the `channels` of the {@link PeerLinks} the presence rides on.
1541
+ */
1542
+ const presenceChannel = {
1543
+ label: 'mmstack-presence',
1544
+ ordered: false,
1545
+ maxRetransmits: 0,
1546
+ };
1547
+ const none = Symbol('none');
1548
+ // one send counter per links object and channel, shared by every sender created on them
1549
+ const counters = new WeakMap();
1550
+ const counterOf = (links, label) => {
1551
+ let byLabel = counters.get(links);
1552
+ if (!byLabel)
1553
+ counters.set(links, (byLabel = new Map()));
1554
+ let counter = byLabel.get(label);
1555
+ if (!counter)
1556
+ byLabel.set(label, (counter = { seq: 0 }));
1557
+ return counter;
1558
+ };
1559
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
1560
+ /**
1561
+ * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no
1562
+ * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the
1563
+ * sender's next `set`.
1564
+ *
1565
+ * Order comes from causality the receiver observes, never from clocks or from numbers chosen
1566
+ * by different senders. A value is held only for an origin in the roster, and it is removed
1567
+ * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or
1568
+ * below it is dropped: one counter stamps every frame sent on that link in send order, so a
1569
+ * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a
1570
+ * frame of an old link cannot arrive on a new one. An origin that leaves and comes back
1571
+ * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives
1572
+ * and nobody reads `peers` between leave and rejoin.
1573
+ *
1574
+ * The counter belongs to the links and the channel, not to this sender, so a sender closed
1575
+ * and recreated on the same links carries on where the last one stopped and is heard at
1576
+ * once. A new tab or device is a new link, which every receiver already treats as fresh.
1577
+ *
1578
+ * Values travel as JSON.
1579
+ */
1580
+ function rtcPresence(links, opt) {
1581
+ const injector = opt.injector ?? inject(Injector);
1582
+ const label = opt.channel ?? presenceChannel.label;
1583
+ if (!links.channels.includes(label)) {
1584
+ throw new Error(`[@mmstack/mesh] rtcPresence needs a '${label}' channel on its peer links`);
1585
+ }
1586
+ const held = new Map();
1587
+ const version = signal(0, /* @ts-ignore */
1588
+ ...(ngDevMode ? [{ debugName: "version" }] : /* istanbul ignore next */ []));
1589
+ const counter = counterOf(links, label);
1590
+ let closed = false;
1591
+ let roster = new Set();
1592
+ const forget = (origin) => {
1593
+ if (held.delete(origin))
1594
+ version.update((v) => v + 1);
1595
+ };
1596
+ const receive = (origin, frame) => {
1597
+ if (closed)
1598
+ return;
1599
+ let msg;
1600
+ try {
1601
+ msg = JSON.parse(frame);
1602
+ }
1603
+ catch {
1604
+ return;
1605
+ }
1606
+ if (typeof msg !== 'object' ||
1607
+ msg === null ||
1608
+ !isNum(msg.seq) ||
1609
+ !('value' in msg)) {
1610
+ return;
1611
+ }
1612
+ if (!roster.has(origin))
1613
+ return;
1614
+ const prev = held.get(origin);
1615
+ if (prev && msg.seq <= prev.seq)
1616
+ return;
1617
+ held.set(origin, { seq: msg.seq, value: msg.value });
1618
+ version.update((v) => v + 1);
1619
+ };
1620
+ const unsubs = [
1621
+ opt.roster((members) => {
1622
+ roster = new Set(members);
1623
+ for (const origin of held.keys())
1624
+ if (!roster.has(origin))
1625
+ forget(origin);
1626
+ }),
1627
+ links.onMessage((origin, frame, channel) => {
1628
+ if (channel === label)
1629
+ receive(origin, frame);
1630
+ }),
1631
+ // the link is the epoch: a new or lost link starts the origin fresh
1632
+ links.onOpen((origin, channel) => {
1633
+ if (channel === label)
1634
+ forget(origin);
1635
+ }),
1636
+ links.onClose(forget),
1637
+ links.onEnd(() => close()),
1638
+ ];
1639
+ const peers = computed(() => {
1640
+ version();
1641
+ if (closed)
1642
+ return new Map();
1643
+ const out = new Map();
1644
+ for (const [origin, entry] of held) {
1645
+ if (roster.has(origin))
1646
+ out.set(origin, entry.value);
1647
+ }
1648
+ return out;
1649
+ }, /* @ts-ignore */
1650
+ ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
1651
+ const destroyRef = injector.get(DestroyRef);
1652
+ const outgoing = throttled(none, {
1653
+ ms: opt.throttleMs ?? 33,
1654
+ leading: true,
1655
+ trailing: true,
1656
+ destroyRef,
1657
+ });
1658
+ const publisher = effect(() => {
1659
+ const value = outgoing();
1660
+ if (value === none || closed)
1661
+ return;
1662
+ untracked(() => links.broadcast(JSON.stringify({
1663
+ seq: counter.seq++,
1664
+ value,
1665
+ }), label));
1666
+ }, { ...(ngDevMode ? { debugName: "publisher" } : /* istanbul ignore next */ {}), injector });
1667
+ const close = () => {
1668
+ if (closed)
1669
+ return;
1670
+ closed = true;
1671
+ publisher.destroy();
1672
+ for (const unsub of unsubs.splice(0))
1673
+ unsub();
1674
+ held.clear();
1675
+ version.update((v) => v + 1);
1676
+ };
1677
+ destroyRef.onDestroy(close);
1678
+ return {
1679
+ set: (value) => {
1680
+ if (!closed)
1681
+ outgoing.set(value);
1682
+ },
1683
+ peers,
1252
1684
  close,
1253
1685
  };
1254
1686
  }
@@ -1257,5 +1689,5 @@ function webRtcMesh(source, opt) {
1257
1689
  * Generated bundle index. Do not edit.
1258
1690
  */
1259
1691
 
1260
- export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
1692
+ export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
1261
1693
  //# sourceMappingURL=mmstack-mesh.mjs.map