@cero-base/cero 3.5.0 → 3.6.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.
@@ -7,6 +7,8 @@ import * as operators from '../lib/operators.js'
7
7
 
8
8
  export * from './profile-sync.js'
9
9
  export * from './handle-sync.js'
10
+ export * from './pulse.js'
11
+ export { calls } from './calls.js'
10
12
 
11
13
  // everything an extension module needs, light enough for the UI bundle the spec pulls it into
12
14
  export { t, schema }
@@ -16,7 +18,7 @@ export const cero = { t, schema, ...operators }
16
18
  /**
17
19
  * @typedef {object} Extension
18
20
  * @property {string} [name]
19
- * @property {Record<string, object>} [schema] Refs to add, or `t.extend` on a builtin, nested by handle type like the app schema.
21
+ * @property {Record<string, object> | ((types: string[]) => Record<string, object>)} [schema] Refs to add, or `t.extend` on a builtin, nested by handle type like the app schema; a function gets the app's handle types and returns them.
20
22
  * @property {(me: import('../handle/index.js').Context) => void | (() => void) | Promise<void | (() => void)>} [setup] Runs before the root opens; a returned function runs on close.
21
23
  */
22
24
 
@@ -0,0 +1,33 @@
1
+ import { t } from '../lib/spec.js'
2
+
3
+ /**
4
+ * Hear through a pulse service when another device writes in a handle you are in, closed here too,
5
+ * and wake that handle so it syncs, without the app opening it. A best effort: a notice may come
6
+ * late or twice. Declares `local.pulses`, a row per handle id: `heard`, the local time a write from
7
+ * another device last landed here, 0 before the first; and what pulse keeps for itself: `told`,
8
+ * `owed`, `since` and `epoch`.
9
+ *
10
+ * @param {string | Uint8Array} [key] The service's public key, as it prints it. The build needs none.
11
+ * @returns {import('./index.js').Extension}
12
+ */
13
+ export function pulse(key) {
14
+ return {
15
+ name: 'pulse',
16
+ schema: {
17
+ local: {
18
+ pulses: t.collection({
19
+ told: t.uint,
20
+ heard: t.uint,
21
+ owed: t.bool,
22
+ since: t.uint,
23
+ epoch: t.uint
24
+ })
25
+ }
26
+ },
27
+ async setup(me) {
28
+ // the worker's runtime; a UI bundle resolves a stand-in, so the client and its DHT stay out of it
29
+ const { follow } = await import('@cero-base/cero/internal/pulse')
30
+ return follow(me, key)
31
+ }
32
+ }
33
+ }
@@ -25,7 +25,6 @@ import { FileServer } from '@cero-base/core/blobs/server'
25
25
  import { KEEP_OPEN, LOOKS, NS, PASSES, REFUSALS, SPENT, TIMEOUT } from '../lib/constants.js'
26
26
 
27
27
  import { Ref } from '../lib/refs.js'
28
- import { box } from '../local/index.js'
29
28
  import { extensionsOf } from '../extensions/index.js'
30
29
 
31
30
  export { Ref } from '../lib/refs.js'
@@ -43,6 +42,7 @@ export { Ref } from '../lib/refs.js'
43
42
  * @property {import('corestore')} [store] Pre-existing Corestore. Falls back to `parent.store.store`.
44
43
  * @property {Spec} [spec] Built cero spec.
45
44
  * @property {Local} [local] Root only, and required there: the device store for handle keypairs and mail.
45
+ * @property {Mailbox} [mailbox] Root only: the device's mailbox, its boxes in `local`, open before the network.
46
46
  * @property {import('hypercore-storage')} [storage] Owned HypercoreStorage to close on shutdown.
47
47
  * @property {{ destroy(): Promise<void> }} [discovery] Owned identity discovery to destroy on shutdown.
48
48
  * @property {string} [dir] Data directory (root handles only).
@@ -99,15 +99,9 @@ export class Handle extends ReadyResource {
99
99
  this.parent = parent
100
100
 
101
101
  this.local = opts.local || null
102
- // one per device: the root's, its boxes in the local store
102
+ // one per device: the root's
103
103
  /** @type {Mailbox} */
104
- this.mailbox = parent
105
- ? parent.root.mailbox
106
- : new Mailbox(network, {
107
- inbox: box(this.local.store, 'inbox'),
108
- outbox: box(this.local.store, 'outbox'),
109
- onerror: (err) => this._onerror(err)
110
- })
104
+ this.mailbox = parent ? parent.root.mailbox : opts.mailbox
111
105
  /** @private */
112
106
  this._storage = opts.storage || null
113
107
  /** @private */
@@ -192,6 +186,9 @@ export class Handle extends ReadyResource {
192
186
  this._tellers = parent ? null : []
193
187
  /** @private */
194
188
  this._retell = false
189
+ // the device's calls, when the calls() extension runs
190
+ /** @private @type {import('../extensions/calls.js').Calls | null} */
191
+ this._calls = null
195
192
 
196
193
  this.store = new Database({
197
194
  store: store,
@@ -362,6 +359,8 @@ export class Handle extends ReadyResource {
362
359
  async _close() {
363
360
  // a write that raced a suspend holds the close until the storage resumes, once a suspend still running settled
364
361
  if (this._sus) await this._sus.resume()
362
+ // a call is left while the room can still write it
363
+ await this.root._calls?.hangup(this).catch(this._onerror)
365
364
  this.root._coreKeys.delete(b4a.toHex(this.store.key))
366
365
  if (this._blobs?.key) this.root._coreKeys.delete(b4a.toHex(this._blobs.key))
367
366
  for (const b of this._epochBlobs?.values() || []) {
@@ -476,6 +475,8 @@ export class Handle extends ReadyResource {
476
475
  // accepting on the root links the device: this one attests its key
477
476
  /** @private */
478
477
  async _answer(id, { accept, role, reason }) {
478
+ // a ring is the room's own row in me.local.rings
479
+ if (!accept && id === this.id && this.root._calls) return this.root._calls.deny(this, reason)
479
480
  if (!accept) return this._pair.deny(id, reason)
480
481
  if (this.parent) return this._pair.accept(id, { role })
481
482
  const { data: row } = await this.store.get('requests', id)
@@ -488,6 +489,13 @@ export class Handle extends ReadyResource {
488
489
  return this.store.rotate()
489
490
  }
490
491
 
492
+ /** @private */
493
+ _dial(opts) {
494
+ const calls = this.root._calls
495
+ if (!calls) throw CeroError.INVALID('dial needs the calls() extension in the build')
496
+ return calls.dial(this, opts)
497
+ }
498
+
491
499
  /** @private */
492
500
  _removed(id) {
493
501
  return this.store.removed(id)
package/src/index.js CHANGED
@@ -49,13 +49,14 @@ export { t, schema } from './lib/spec.js'
49
49
  * @property {(remotePublicKey: Uint8Array, payload: unknown) => boolean} [firewall] Incoming-connection filter: `true` refuses the connection.
50
50
  * @property {string} [channel] Optional network-isolation label; only same-channel peers connect.
51
51
  * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys. Handles and files are mirrored through them so peers sync even when never online at the same time. Mirrors hold only encrypted blocks — they never read your data.
52
- * @property {{ active?: number, idle?: number }} [presence] How many handles announce and search at once, and the ms one keeps its slot before a touched one may take it.
52
+ * @property {{ active?: number, idle?: number, known?: number, connections?: number }} [presence] How many handles search and announce at once besides the ones in use, the ms one stays on after its last use, how many devices a handle keeps to dial by their keys, and how many connections the device keeps at once.
53
53
  * @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
54
54
  * @property {number} [keepOpen] How many handles stay open after their last close, for a reopen; one more closes the least recently used, 0 closes at once. Defaults to 16.
55
55
  * @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
56
56
  * @property {Uint8Array} [storageKey] 32-byte key encrypting local key material (master seed, device keypairs) at rest. Source it from the OS keychain — cero never stores it.
57
57
  * @property {import('./extensions/index.js').Extension[]} [extensions] The extensions this instance runs, instead of the ones the spec carries. Build with the same list.
58
58
  * @property {{ on?: boolean, topic?: string, backend?: object | null, maxOutbound?: number, maxInbound?: number, pipe?: 'l2cap' | 'gatt' }} [bluetooth] Bluetooth at start: `on` (off by default) and `topic` (the default one, else the channel's own); the app turns the radio on and off with `cero.nearby`, and nothing is stored. `maxOutbound`/`maxInbound` cap concurrent outbound links and inbound sessions. `pipe` picks the data pipe, `'l2cap'` (default, faster) or `'gatt'`; both peers must match. `backend` injects a bare-bluetooth-shaped backend (tests); with none on the host, `status.nearby` reads `'unsupported'`.
59
+ * @property {import('./lib/media.js').Bindings} [webrtc] The WebRTC calls run their media on where Cero runs in the UI itself; a window's own without it, none in a worker.
59
60
  */
60
61
 
61
62
  /**
@@ -82,6 +83,7 @@ async function start(dir, spec, opts = {}) {
82
83
  let store = null
83
84
  let local = null
84
85
  let network = null
86
+ let mailbox = null
85
87
  let discovery = null
86
88
  let bluetooth = null
87
89
  let me = null
@@ -155,10 +157,16 @@ async function start(dir, spec, opts = {}) {
155
157
  presence: opts.presence,
156
158
  onerror
157
159
  })
158
- await network.ready()
160
+ // it readies the network once what its inbox left to erase is erased
161
+ mailbox = new Mailbox(network, {
162
+ inbox: box(local.store, 'inbox'),
163
+ outbox: box(local.store, 'outbox'),
164
+ onerror
165
+ })
166
+ await mailbox.ready()
159
167
  // the link first: who this device is comes with the reply
160
168
  const linked = linking
161
- ? await ask(local, network, spec, { ...opts, writer: keyPair, timeout }, pending)
169
+ ? await ask(local, mailbox, spec, { ...opts, writer: keyPair, timeout }, pending)
162
170
  : null
163
171
  const identity = linked ? linked.identity : resolved.identity
164
172
  // the radio before the pointer read: a phrase recovers from a device in range, no internet
@@ -183,6 +191,7 @@ async function start(dir, spec, opts = {}) {
183
191
  discovery,
184
192
  identity,
185
193
  network,
194
+ mailbox,
186
195
  spec,
187
196
  opts,
188
197
  dir,
@@ -233,6 +242,7 @@ async function start(dir, spec, opts = {}) {
233
242
  await me?.store.close().catch(safetyCatch)
234
243
  await discovery?.destroy().catch(safetyCatch)
235
244
  await bluetooth?.close().catch(safetyCatch)
245
+ await mailbox?.close().catch(safetyCatch)
236
246
  await network?.close().catch(safetyCatch)
237
247
  await local?.close().catch(safetyCatch)
238
248
  await store?.close().catch(safetyCatch)
@@ -378,7 +388,7 @@ async function pendingLink(local) {
378
388
 
379
389
  // the root's join: this device, bare, knocks with the invite and waits for a device of the identity
380
390
  // to let it in. What it learns is kept in its joins row, so a killed launch resumes it
381
- async function ask(local, network, spec, { invite, writer, onrequest, timeout, signal }, pending) {
391
+ async function ask(local, mailbox, spec, { invite, writer, onrequest, timeout, signal }, pending) {
382
392
  const parsed = Invite.parse(invite ?? pending.invite)
383
393
  if (parsed.data?.byteLength !== 32) throw CeroError.INVALID_INVITE('not a device invite')
384
394
  const secret = pending?.device ?? Identity.randomKeyPair().secretKey
@@ -397,11 +407,7 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout, s
397
407
  ? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [] }
398
408
  : null
399
409
  if (!reply) {
400
- const { store } = network
401
- const inbox = box(local.store, 'inbox')
402
- const outbox = box(local.store, 'outbox')
403
- const mailbox = new Mailbox(network, { inbox, outbox })
404
- await mailbox.ready()
410
+ const { store } = mailbox.network
405
411
  try {
406
412
  const signers = [{ publicKey: writer.publicKey }]
407
413
  onrequest?.(hid.encode(Hypercore.key({ version: store.manifestVersion, signers })))
@@ -425,8 +431,6 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout, s
425
431
  // an expired invite leaves no join a later launch could resume
426
432
  if (err.code === 'EXPIRED') await local.store.del('joins', row.id)
427
433
  throw err
428
- } finally {
429
- await mailbox.close()
430
434
  }
431
435
  }
432
436
  // the chain the accepting device wrote ends at this device, under the identity the invite named
@@ -0,0 +1,28 @@
1
+ /** The lanes a mute names. */
2
+ export const LANES = ['audio', 'video']
3
+
4
+ const REFS = {
5
+ peers: { kind: 'collection', type: 'line-peer' },
6
+ _lanes: { kind: 'single', type: 'line-lanes' },
7
+ _ports: { kind: 'collection', type: 'line-port' }
8
+ }
9
+
10
+ /**
11
+ * @typedef {import('./spec.js').Spec} Spec
12
+ * @typedef {Pick<Spec, 'schema' | 'codec'> & { meta: { refs: Record<string, import('./spec.js').RefInfo> } }} Wire
13
+ */
14
+
15
+ /**
16
+ * What a line carries across RPC: its refs are computed on the device, and cross in the encodings
17
+ * of its room's spec, through the same get and watch a handle's refs use.
18
+ *
19
+ * @param {Spec} spec The room's.
20
+ * @returns {Wire}
21
+ */
22
+ export function wire({ meta, schema, codec }) {
23
+ const refs = {}
24
+ for (const [name, { kind, type }] of Object.entries(REFS)) {
25
+ refs[name] = { kind, live: true, schema: `@${meta.ns}/${type}` }
26
+ }
27
+ return { meta: { refs }, schema, codec }
28
+ }
@@ -0,0 +1,285 @@
1
+ import { parse, write } from 'sdp-transform'
2
+ import { inTurn } from '@cero-base/core/utils'
3
+
4
+ const HOST = '127.0.0.1'
5
+ // max-bundle: an offer sends from one local port from the start, so the worker follows one sender
6
+ const CONFIG = { iceServers: [], rtcpMuxPolicy: 'require', bundlePolicy: 'max-bundle' }
7
+ // by mid, in the order the offerer adds them
8
+ const LANES = ['audio', 'video', 'screen']
9
+ const KINDS = ['audio', 'video', 'video']
10
+
11
+ /**
12
+ * @typedef {object} Bindings The WebRTC a line's media runs on: `react-native-webrtc`, or a window's own.
13
+ * @property {typeof RTCPeerConnection} RTCPeerConnection
14
+ * @property {typeof MediaStream} MediaStream
15
+ *
16
+ * @typedef {object} Bridge The worker's side of a line: this device's lanes once its row is read, and the local port of each other device with the description it sent last.
17
+ * @property {{ id: string, audio: boolean, video: boolean, screen: boolean } | null} self
18
+ * @property {Array<{ id: string, port: number, seq?: number, type?: Signal['type'], sdp?: string }>} peers
19
+ *
20
+ * @typedef {{ type: 'offer' | 'answer', sdp: string }} Signal A WebRTC description.
21
+ *
22
+ * @typedef {object} Conn
23
+ * @property {string} id
24
+ * @property {number} port
25
+ * @property {RTCPeerConnection} pc
26
+ * @property {boolean} offerer
27
+ * @property {RTCRtpTransceiver[] | null} lanes
28
+ * @property {boolean} heard A description from the other side reached it.
29
+ * @property {{ stream: MediaStream, screen: MediaStream } | null} streams
30
+ * @property {boolean} closed
31
+ * @property {Promise<void> | null} turn
32
+ */
33
+
34
+ /**
35
+ * The bindings to run on: the ones given, else the window's.
36
+ *
37
+ * @param {Bindings | null} [webrtc]
38
+ * @returns {Bindings | null}
39
+ */
40
+ export function bindings(webrtc) {
41
+ if (webrtc) return webrtc
42
+ return typeof globalThis.RTCPeerConnection === 'function' ? globalThis : null
43
+ }
44
+
45
+ /**
46
+ * A line's WebRTC: one connection per device on the call, its media through the worker's local port
47
+ * for that device, so no ICE server is needed.
48
+ */
49
+ export class Media {
50
+ /**
51
+ * @param {Bindings} webrtc
52
+ * @param {{ send: (id: string, port: number, data: Signal) => void, onchange: () => void, onerror: (err: Error) => void }} opts `send` a signal to the device on `port`.
53
+ */
54
+ constructor(webrtc, { send, onchange, onerror }) {
55
+ this.webrtc = webrtc
56
+ /** @type {MediaStream | null} The camera and microphone. */
57
+ this.camera = null
58
+ /** @type {MediaStream | null} */
59
+ this.screen = null
60
+ this.muted = { audio: false, video: false }
61
+ this.closed = false
62
+ /** @private */
63
+ this._send = send
64
+ /** @private */
65
+ this._onchange = onchange
66
+ /** @private */
67
+ this._onerror = onerror
68
+ /** @private */
69
+ this._self = ''
70
+ // the last description taken from each device
71
+ /** @private @type {Map<string, number>} */
72
+ this._taken = new Map()
73
+ // this device's lanes as its row shows them
74
+ /** @private @type {Bridge['self']} */
75
+ this._row = null
76
+ /** @private @type {Map<string, Conn>} */
77
+ this._conns = new Map()
78
+ }
79
+
80
+ /**
81
+ * Take the worker's side as it is now: a new port rebuilds that device's connection, and the
82
+ * description a device sent last is applied once.
83
+ *
84
+ * @param {Bridge} bridge
85
+ * @returns {void}
86
+ */
87
+ update({ self, peers }) {
88
+ if (this.closed || !self) return
89
+ this._self = self.id
90
+ // a lane goes out only while this device's row shows it on, whoever turned it off
91
+ const moved = LANES.some((lane) => this._row?.[lane] !== self[lane])
92
+ this._row = self
93
+ if (moved) for (const conn of this._conns.values()) this._attach(conn, [0, 1, 2])
94
+ const ports = new Map(peers.map(({ id, port }) => [id, port]))
95
+ for (const [id, conn] of this._conns) if (ports.get(id) !== conn.port) this._drop(conn)
96
+ for (const [id, port] of ports) if (!this._conns.has(id)) this._open(id, port)
97
+ for (const { id, seq, type, sdp } of peers) {
98
+ // taken once, however often the worker's side is read
99
+ if (!(seq > (this._taken.get(id) ?? 0))) continue
100
+ this._taken.set(id, seq)
101
+ this._route(this._conns.get(id), { type, sdp })
102
+ }
103
+ }
104
+
105
+ /**
106
+ * What a device shows: its media only while connected, its screen only while its row shares one.
107
+ *
108
+ * @param {string} id
109
+ * @param {boolean} sharing
110
+ * @returns {{ stream: MediaStream | null, screen: MediaStream | null, connected: boolean }}
111
+ */
112
+ entry(id, sharing) {
113
+ const conn = this._conns.get(id)
114
+ const connected = !!conn?.streams && conn.pc.connectionState === 'connected'
115
+ return {
116
+ stream: connected ? conn.streams.stream : null,
117
+ screen: connected && sharing ? conn.streams.screen : null,
118
+ connected
119
+ }
120
+ }
121
+
122
+ /** @param {MediaStream | null} stream The camera and microphone, or none. */
123
+ share(stream) {
124
+ this.camera = stream
125
+ // a mute holds on the new tracks; one the app turned off is never turned on here, only by an unmute
126
+ for (const lane of ['audio', 'video']) {
127
+ if (this.muted[lane]) for (const track of tracks(stream, lane)) track.enabled = false
128
+ }
129
+ for (const conn of this._conns.values()) this._attach(conn, [0, 1])
130
+ }
131
+
132
+ /** @param {MediaStream | null} stream A screen, or none. */
133
+ present(stream) {
134
+ this.screen = stream
135
+ for (const conn of this._conns.values()) this._attach(conn, [2])
136
+ }
137
+
138
+ /**
139
+ * @param {'audio' | 'video'} lane
140
+ * @param {boolean} on
141
+ */
142
+ lane(lane, on) {
143
+ this.muted[lane] = !on
144
+ for (const track of tracks(this.camera, lane)) track.enabled = on
145
+ for (const conn of this._conns.values()) this._attach(conn, [LANES.indexOf(lane)])
146
+ }
147
+
148
+ close() {
149
+ this.closed = true
150
+ for (const conn of this._conns.values()) this._drop(conn)
151
+ }
152
+
153
+ /** @private */
154
+ _open(id, port) {
155
+ const was = this._conns.get(id)
156
+ if (was) this._drop(was)
157
+ const pc = new this.webrtc.RTCPeerConnection(CONFIG)
158
+ /** @type {Conn} */
159
+ const conn = {
160
+ id,
161
+ port,
162
+ pc,
163
+ offerer: this._self > id,
164
+ lanes: null,
165
+ heard: false,
166
+ streams: null,
167
+ closed: false,
168
+ turn: null
169
+ }
170
+ pc.addEventListener('connectionstatechange', () => this._state(conn))
171
+ this._conns.set(id, conn)
172
+ if (conn.offerer) {
173
+ conn.lanes = KINDS.map((kind) => pc.addTransceiver(kind, { direction: 'sendrecv' }))
174
+ this._attach(conn, [0, 1, 2])
175
+ this._turn(conn, () => this._describe(conn, () => pc.createOffer()))
176
+ }
177
+ this._onchange()
178
+ return conn
179
+ }
180
+
181
+ // decided as it arrives, so the signals after it reach the connection it chose
182
+ /** @private */
183
+ _route(conn, data) {
184
+ const { type } = data
185
+ if (type === 'offer') {
186
+ // the other side started over
187
+ if (conn.heard) conn = this._open(conn.id, conn.port)
188
+ conn.heard = true
189
+ } else if (type === 'answer') {
190
+ if (conn.heard) return
191
+ conn.heard = true
192
+ }
193
+ this._turn(conn, () => this._take(conn, data))
194
+ }
195
+
196
+ /** @private */
197
+ async _take(conn, { type, sdp }) {
198
+ await conn.pc.setRemoteDescription({ type, sdp: route(sdp, conn.port) })
199
+ if (type !== 'offer') return
200
+ conn.lanes = laned(conn.pc.getTransceivers())
201
+ if (!conn.lanes) throw new Error('an offer carries a microphone, a camera and a screen lane')
202
+ for (const transceiver of conn.lanes) transceiver.direction = 'sendrecv'
203
+ this._attach(conn, [0, 1, 2])
204
+ await this._describe(conn, () => conn.pc.createAnswer())
205
+ }
206
+
207
+ /** @private */
208
+ async _describe(conn, make) {
209
+ await conn.pc.setLocalDescription(await make())
210
+ const { type, sdp } = conn.pc.localDescription
211
+ this._send(conn.id, conn.port, { type, sdp })
212
+ }
213
+
214
+ /** @private */
215
+ _attach(conn, lanes) {
216
+ if (!conn.lanes) return
217
+ for (const i of lanes) {
218
+ const track = this._track(LANES[i])
219
+ conn.lanes[i].sender.replaceTrack(track).catch((err) => conn.closed || this._onerror(err))
220
+ }
221
+ }
222
+
223
+ /** @private */
224
+ _track(lane) {
225
+ if (!this._row?.[lane]) return null
226
+ if (lane === 'screen') return tracks(this.screen, 'video')[0] ?? null
227
+ return this.muted[lane] ? null : (tracks(this.camera, lane)[0] ?? null)
228
+ }
229
+
230
+ /** @private */
231
+ _state(conn) {
232
+ // lost on a port that did not move: the side that offers starts over, the other rebuilds on its offer
233
+ if (conn.pc.connectionState === 'failed' && conn.offerer && !conn.closed) {
234
+ this._open(conn.id, conn.port)
235
+ return
236
+ }
237
+ if (conn.pc.connectionState === 'connected' && !conn.streams) {
238
+ const [audio, video, screen] = conn.lanes.map((transceiver) => transceiver.receiver.track)
239
+ const { MediaStream } = this.webrtc
240
+ conn.streams = { stream: new MediaStream([audio, video]), screen: new MediaStream([screen]) }
241
+ }
242
+ this._onchange()
243
+ }
244
+
245
+ /** @private */
246
+ _turn(conn, fn) {
247
+ conn.turn = inTurn(conn.turn, fn).catch((err) => conn.closed || this._onerror(err))
248
+ }
249
+
250
+ // closed before another takes its port: its probes must not reach the next one
251
+ /** @private */
252
+ _drop(conn) {
253
+ conn.closed = true
254
+ if (this._conns.get(conn.id) === conn) this._conns.delete(conn.id)
255
+ conn.pc.close()
256
+ this._onchange()
257
+ }
258
+ }
259
+
260
+ // an offer's lanes by mid, or null when they are not the three in their order
261
+ function laned(transceivers) {
262
+ const lanes = KINDS.map((kind, i) =>
263
+ transceivers.find((t) => t.mid === String(i) && t.receiver.track?.kind === kind)
264
+ )
265
+ return transceivers.length === KINDS.length && lanes.every(Boolean) ? lanes : null
266
+ }
267
+
268
+ function tracks(stream, lane) {
269
+ if (!stream) return []
270
+ return lane === 'audio' ? stream.getAudioTracks() : stream.getVideoTracks()
271
+ }
272
+
273
+ // the other device is reached through this host's port for it, its own addresses are never tried
274
+ function route(sdp, port) {
275
+ const parsed = parse(sdp)
276
+ for (const media of parsed.media) {
277
+ media.port = port
278
+ media.connection = { version: 4, ip: HOST }
279
+ if (media.rtcp) media.rtcp = { port, netType: 'IN', ipVer: 4, address: HOST }
280
+ media.candidates = [
281
+ { foundation: '1', component: 1, transport: 'udp', priority: 1, ip: HOST, port, type: 'host' }
282
+ ]
283
+ }
284
+ return write(parsed)
285
+ }