@mmstack/mesh 21.8.1 → 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, 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')
@@ -974,38 +975,68 @@ function directTransport(relay, ctx) {
974
975
  };
975
976
  }
976
977
 
978
+ /** The single reliable channel every link carries when no channels are asked for. */
979
+ const defaultPeerChannels = [
980
+ { label: 'mmstack-mesh' },
981
+ ];
977
982
  /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
978
983
  function rtcPeerConnector(config) {
979
- return ({ polite, sendSignal }) => {
984
+ return ({ polite, sendSignal, channels = defaultPeerChannels }) => {
980
985
  const pc = new RTCPeerConnection(config);
981
- const messageCbs = new Set();
982
- const openCbs = new Set();
983
- const closeCbs = new Set();
984
- const pending = [];
985
- let dc = null;
986
986
  let makingOffer = false;
987
987
  let ignoreOffer = false;
988
- const attach = (channel) => {
989
- dc = channel;
990
- channel.onmessage = (e) => {
991
- for (const cb of [...messageCbs])
992
- 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
+ };
993
1010
  };
994
- channel.onopen = () => {
995
- for (const frame of pending.splice(0))
996
- channel.send(frame);
997
- for (const cb of [...openCbs])
998
- cb();
999
- };
1000
- channel.onclose = () => {
1001
- for (const cb of [...closeCbs])
1002
- 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(),
1003
1022
  };
1023
+ return { attach, like };
1004
1024
  };
1005
- if (!polite)
1006
- attach(pc.createDataChannel('mmstack-mesh'));
1007
- else
1008
- 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
+ }
1009
1040
  pc.onicecandidate = (e) => {
1010
1041
  if (e.candidate)
1011
1042
  sendSignal({ ice: e.candidate.toJSON() });
@@ -1020,19 +1051,12 @@ function rtcPeerConnector(config) {
1020
1051
  makingOffer = false;
1021
1052
  }
1022
1053
  };
1054
+ const byLabel = {};
1055
+ for (const [label, ch] of made)
1056
+ byLabel[label] = ch.like;
1023
1057
  return {
1024
- channel: {
1025
- send: (frame) => {
1026
- if (dc && dc.readyState === 'open')
1027
- dc.send(frame);
1028
- else
1029
- pending.push(frame);
1030
- },
1031
- onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1032
- onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1033
- onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1034
- close: () => dc?.close(),
1035
- },
1058
+ channel: byLabel[channels[0].label],
1059
+ channels: byLabel,
1036
1060
  signal: async (data) => {
1037
1061
  const { description, ice } = (data ?? {});
1038
1062
  if (description) {
@@ -1058,51 +1082,74 @@ function rtcPeerConnector(config) {
1058
1082
  }
1059
1083
  },
1060
1084
  close: () => {
1061
- dc?.close();
1085
+ for (const ch of made.values())
1086
+ ch.like.close();
1062
1087
  pc.close();
1063
1088
  },
1064
1089
  };
1065
1090
  };
1066
1091
  }
1067
1092
  /**
1068
- * Peer-to-peer mesh sync: the relay only signals
1069
- * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1070
- * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1071
- * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1072
- * checkpoint (root + per-path register state + watermark), so supersession and precedence
1073
- * carry over intact: a late joiner is indistinguishable from a peer that saw every
1074
- * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1075
- * 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.
1076
1113
  *
1077
- * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1078
- * relay-backed session over the same document a peer channel may hand on only envelopes the
1079
- * 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.
1080
1123
  */
1081
- function webRtcMesh(source, opt) {
1124
+ function peerLinks(opt) {
1082
1125
  const injector = opt.injector ?? inject(Injector);
1083
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];
1084
1130
  const status = signal('connecting', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1085
1131
  const openPeers = signal(new Set(), ...(ngDevMode ? [{ debugName: "openPeers" }] : /* istanbul ignore next */ []));
1132
+ const members = signal(new Set(), ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
1086
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();
1087
1139
  let signalingUnsubs = [];
1088
1140
  let transport = null;
1089
1141
  let reconnectTimer;
1142
+ let connected = false;
1090
1143
  let closed = false;
1091
- const sync = opSync(source, {
1092
- writer: opt.writer,
1093
- policies: opt.policies,
1094
- policyVersion: opt.policyVersion,
1095
- injector,
1096
- });
1097
- const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1098
- const sendTo = (peer, msg) => {
1099
- peer.link.channel.send(JSON.stringify(msg));
1100
- };
1101
- const broadcast = (msg) => {
1102
- for (const peer of peers.values()) {
1103
- if (peer.open)
1104
- sendTo(peer, msg);
1105
- }
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);
1106
1153
  };
1107
1154
  const dropPeer = (origin) => {
1108
1155
  const peer = peers.get(origin);
@@ -1117,75 +1164,149 @@ function webRtcMesh(source, opt) {
1117
1164
  next.delete(origin);
1118
1165
  return next;
1119
1166
  });
1167
+ for (const cb of [...closeCbs])
1168
+ cb(origin);
1120
1169
  };
1121
- const ensurePeer = (origin) => {
1122
- let peer = peers.get(origin);
1123
- if (peer)
1124
- return peer;
1125
- const link = connector({
1126
- remote: origin,
1127
- polite: sync.origin > origin,
1128
- sendSignal: (data) => transport?.send({ t: 'signal', room: opt.room, to: origin, data }),
1129
- });
1130
- peer = { link, open: false, unsubs: [] };
1131
- peers.set(origin, peer);
1132
- peer.unsubs.push(link.channel.onOpen(() => {
1133
- peer.open = true;
1134
- openPeers.update((set) => new Set(set).add(origin));
1135
- sendTo(peer, { t: 'hello', wm: sync.watermark() });
1136
- }), link.channel.onMessage((frame) => {
1137
- let msg;
1138
- try {
1139
- msg = JSON.parse(frame);
1140
- }
1141
- 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)
1142
1185
  return;
1143
- }
1144
- handlePeerMsg(peer, msg);
1145
- }), link.channel.onClose(() => dropPeer(origin)));
1146
- return peer;
1147
- };
1148
- const handlePeerMsg = (peer, msg) => {
1149
- switch (msg.t) {
1150
- case 'hello': {
1151
- const snap = sync.snapshot();
1152
- if (covered(snap.wm, msg.wm))
1153
- sendTo(peer, { t: 'uptodate' });
1154
- else
1155
- sendTo(peer, { t: 'state', state: snap });
1186
+ if (building) {
1187
+ building.push(data);
1156
1188
  return;
1157
1189
  }
1158
- case 'state': {
1159
- if (covered(sync.watermark(), msg.state.wm)) {
1160
- 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 }),
1161
1195
  }
1162
- 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;
1163
1228
  }
1164
- case 'uptodate':
1165
- return;
1166
- case 'env':
1167
- sync.receive(msg.env);
1168
- 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)));
1169
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');
1170
1259
  };
1171
1260
  const handleSignaling = (msg) => {
1172
- if (msg.room !== opt.room)
1261
+ if (closed || msg.room !== opt.room)
1173
1262
  return;
1174
1263
  switch (msg.t) {
1175
1264
  case 'welcome':
1176
- for (const origin of msg.members)
1177
- ensurePeer(origin);
1178
- status.set('live');
1265
+ welcomeMembers(msg.members);
1179
1266
  return;
1180
1267
  case 'member':
1268
+ setMembers(msg.gone
1269
+ ? [...members()].filter((origin) => origin !== msg.origin)
1270
+ : [...new Set([...members(), msg.origin])]);
1181
1271
  if (msg.gone)
1182
1272
  dropPeer(msg.origin);
1183
1273
  else
1184
1274
  ensurePeer(msg.origin);
1185
1275
  return;
1186
- case 'signal':
1187
- 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);
1188
1308
  return;
1309
+ }
1189
1310
  case 'reject':
1190
1311
  close();
1191
1312
  return;
@@ -1196,6 +1317,18 @@ function webRtcMesh(source, opt) {
1196
1317
  return;
1197
1318
  for (const unsub of signalingUnsubs.splice(0))
1198
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
+ }
1199
1332
  const t = opt.signaling();
1200
1333
  transport = t;
1201
1334
  signalingUnsubs = [
@@ -1204,39 +1337,335 @@ function webRtcMesh(source, opt) {
1204
1337
  if (closed || transport !== t)
1205
1338
  return;
1206
1339
  transport = null;
1340
+ status.set('connecting');
1207
1341
  reconnectTimer = setTimeout(connectSignaling, 1000);
1208
1342
  }),
1209
1343
  ];
1210
1344
  t.send({
1211
1345
  t: 'hello',
1212
1346
  room: opt.room,
1213
- origin: sync.origin,
1347
+ origin: opt.origin,
1214
1348
  proto: MESH_PROTO_VERSION,
1215
1349
  policyVersion: opt.policyVersion ?? 0,
1216
1350
  });
1217
1351
  };
1218
- const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));
1352
+ const connect = () => {
1353
+ if (connected || closed)
1354
+ return;
1355
+ connected = true;
1356
+ connectSignaling();
1357
+ };
1219
1358
  const close = () => {
1220
1359
  if (closed)
1221
1360
  return;
1222
1361
  closed = true;
1223
1362
  if (reconnectTimer !== undefined)
1224
1363
  clearTimeout(reconnectTimer);
1225
- unsubLocal();
1226
1364
  for (const origin of [...peers.keys()])
1227
1365
  dropPeer(origin);
1228
1366
  for (const unsub of signalingUnsubs.splice(0))
1229
1367
  unsub();
1230
1368
  transport?.close();
1231
1369
  transport = null;
1232
- sync.destroy();
1370
+ setMembers([]);
1371
+ memberCbs.clear();
1233
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;
1234
1380
  };
1235
1381
  injector.get(DestroyRef).onDestroy(close);
1236
- connectSignaling();
1382
+ if (opt.autoConnect !== false)
1383
+ connect();
1237
1384
  return {
1238
1385
  status: status.asReadonly(),
1239
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,
1240
1669
  close,
1241
1670
  };
1242
1671
  }
@@ -1245,5 +1674,5 @@ function webRtcMesh(source, opt) {
1245
1674
  * Generated bundle index. Do not edit.
1246
1675
  */
1247
1676
 
1248
- export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
1677
+ export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
1249
1678
  //# sourceMappingURL=mmstack-mesh.mjs.map