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