@minip2p/core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sdk.js CHANGED
@@ -1,402 +1,719 @@
1
- /* oxlint-disable func-style, max-classes-per-file, no-use-before-define, promise/avoid-new, promise/prefer-await-to-then, unicorn/no-useless-spread -- The SDK uses a private queue class, hoisted helpers and Promise adapters, schedules same-tick events on a microtask, and snapshots observer sets before callbacks mutate them. */
2
- import { ClosedError, DriverFailedError, PeerDisconnectedError, TimeoutError, } from "./errors.js";
3
- import { P2pEvent_Tags } from "./types.js";
4
- const QUEUE_CAP = 4096;
5
- const FLUSH_BATCH = 256;
6
- const REPLACEABLE_EVENTS = new Set([
7
- P2pEvent_Tags.ReachabilityChanged,
8
- P2pEvent_Tags.PublicAddressesChanged,
9
- ]);
10
- /**
11
- * A bounded FIFO with constant-time front removal and payload eviction.
12
- *
13
- * Replaceable-event indexes let overflow compaction visit only candidates
14
- * that can actually be discarded rather than rebuilding the entire queue.
15
- */
16
- class EventQueue {
17
- #payloads = new Set();
18
- #replaceable = new Map();
19
- #head;
20
- #tail;
1
+ /* oxlint-disable default-case, func-style, max-classes-per-file, no-empty-function, no-use-before-define, promise/avoid-new, promise/prefer-await-to-callbacks, promise/prefer-await-to-then, typescript/no-invalid-void-type, unicorn/consistent-function-scoping, unicorn/no-new-array, unicorn/no-useless-spread, unicorn/no-useless-undefined -- Promise adapters, void event payloads, snapshot fan-out, and bounded queues are deliberate SDK internals. */
2
+ import { AbortError, ClosedError, ConnectFailedError, ConnectResultUnavailableError, DriverFailedError, EventQueueOverflowError, OpenStreamError, PeerDisconnectedError, StreamClosedError, TimeoutError, } from "./errors.js";
3
+ import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
4
+ const DEFAULT_TIMEOUT_MS = 65_000;
5
+ const EVENT_QUEUE_CAP = 4096;
6
+ const EVENT_FLUSH_BATCH = 256;
7
+ const CONNECT_TERMINAL_CAP = 1024;
8
+ const STREAM_CHUNK_CAP = 64;
9
+ const STREAM_BYTE_CAP = 1024 * 1024;
10
+ class BoundedQueue {
11
+ #items;
12
+ #head = 0;
21
13
  #size = 0;
22
- get size() {
14
+ constructor(capacity) {
15
+ this.#items = new Array(capacity);
16
+ }
17
+ get length() {
23
18
  return this.#size;
24
19
  }
20
+ push(item) {
21
+ if (this.#size === this.#items.length) {
22
+ const dropped = this.#items[this.#head];
23
+ this.#items[this.#head] = item;
24
+ this.#head = (this.#head + 1) % this.#items.length;
25
+ return dropped;
26
+ }
27
+ const tail = (this.#head + this.#size) % this.#items.length;
28
+ this.#items[tail] = item;
29
+ this.#size += 1;
30
+ return undefined;
31
+ }
32
+ shift() {
33
+ if (this.#size === 0) {
34
+ return undefined;
35
+ }
36
+ const item = this.#items[this.#head];
37
+ this.#items[this.#head] = undefined;
38
+ this.#head = (this.#head + 1) % this.#items.length;
39
+ this.#size -= 1;
40
+ return item;
41
+ }
25
42
  clear() {
26
- this.#head = undefined;
27
- this.#tail = undefined;
43
+ this.#items.fill(undefined);
44
+ this.#head = 0;
28
45
  this.#size = 0;
29
- this.#payloads.clear();
30
- this.#replaceable.clear();
31
46
  }
32
- push(event) {
33
- let dropped = 0;
34
- if (this.#size >= QUEUE_CAP) {
35
- dropped += this.#compactReplaceable();
36
- }
37
- if (this.#size >= QUEUE_CAP) {
38
- const payload = this.#payloads.values().next().value;
39
- if (payload === undefined) {
40
- this.shift();
47
+ }
48
+ /** A negotiated custom-protocol stream with exclusive pull or flowing reads. */
49
+ export class Stream {
50
+ /** Remote peer that owns the other end of this stream. */
51
+ peerId;
52
+ /** Negotiated multistream protocol identifier. */
53
+ protocolId;
54
+ /** Endpoint-local transport stream identifier. */
55
+ streamId;
56
+ /** Endpoint-local connection carrying this stream. */
57
+ connId;
58
+ /** Whether this endpoint initiated the stream. */
59
+ initiatedLocally;
60
+ #backend;
61
+ #onTerminal;
62
+ #listeners = new Map();
63
+ #fifo = [];
64
+ #reads = [];
65
+ #fifoBytes = 0;
66
+ #mode;
67
+ #remoteWriteClosed = false;
68
+ #closed = false;
69
+ constructor(backend, meta, onTerminal) {
70
+ this.#backend = backend;
71
+ this.#onTerminal = onTerminal;
72
+ this.peerId = meta.peerId;
73
+ this.protocolId = meta.protocolId;
74
+ this.streamId = meta.streamId;
75
+ this.connId = meta.connId;
76
+ this.initiatedLocally = meta.initiatedLocally;
77
+ }
78
+ /** Subscribes to stream lifecycle or data events. */
79
+ on(type, handler) {
80
+ if (type === "data") {
81
+ if (this.#mode === "pull") {
82
+ throw new Error("Cannot use flowing data handlers after read()");
41
83
  }
42
- else {
43
- this.#remove(payload);
84
+ this.#mode = "flowing";
85
+ }
86
+ let listeners = this.#listeners.get(type);
87
+ if (listeners === undefined) {
88
+ listeners = new Set();
89
+ this.#listeners.set(type, listeners);
90
+ }
91
+ listeners.add(handler);
92
+ if (type === "data") {
93
+ this.#flushFlowing();
94
+ }
95
+ let active = true;
96
+ return () => {
97
+ if (!active) {
98
+ return;
44
99
  }
45
- dropped += 1;
100
+ active = false;
101
+ listeners?.delete(handler);
102
+ };
103
+ }
104
+ /**
105
+ * Reads the next buffered chunk, or `undefined` after the remote write side
106
+ * closes. Pull reads and flowing `data` handlers are mutually exclusive.
107
+ */
108
+ read() {
109
+ if (this.#mode === "flowing") {
110
+ return Promise.reject(new Error('Cannot call read() after subscribing to "data"'));
46
111
  }
47
- const node = { event, previous: this.#tail };
48
- if (this.#tail === undefined) {
49
- this.#head = node;
112
+ this.#mode = "pull";
113
+ const buffered = this.#shift();
114
+ if (buffered !== undefined) {
115
+ return Promise.resolve(buffered);
50
116
  }
51
- else {
52
- this.#tail.next = node;
117
+ if (this.#remoteWriteClosed) {
118
+ return Promise.resolve(this.#shift());
53
119
  }
54
- this.#tail = node;
55
- this.#size += 1;
56
- this.#index(node);
57
- return dropped;
120
+ if (this.#closed) {
121
+ return Promise.reject(new ClosedError());
122
+ }
123
+ return new Promise((resolve, reject) => {
124
+ this.#reads.push({ reject, resolve });
125
+ });
58
126
  }
59
- shift() {
60
- const node = this.#head;
61
- if (node === undefined) {
62
- return undefined;
127
+ /** Writes UTF-8 text or bytes to the stream. */
128
+ write(data) {
129
+ if (this.#closed) {
130
+ throw new ClosedError();
63
131
  }
64
- this.#remove(node);
65
- return node.event;
132
+ this.#backend.sendStream(this.peerId, this.streamId, toUint8Array(data));
66
133
  }
67
- #compactReplaceable() {
68
- let dropped = 0;
69
- for (const nodes of this.#replaceable.values()) {
70
- if (nodes.size < 2) {
71
- continue;
72
- }
73
- const latest = [...nodes].at(-1);
74
- for (const node of [...nodes]) {
75
- if (node !== latest) {
76
- this.#remove(node);
77
- dropped += 1;
78
- }
79
- }
134
+ /** Half-closes the local write side while keeping reads available. */
135
+ closeWrite() {
136
+ if (!this.#closed) {
137
+ this.#backend.closeStreamWrite(this.peerId, this.streamId);
138
+ }
139
+ }
140
+ /** Abruptly resets the stream and emits `closed`. */
141
+ reset() {
142
+ if (!this.#closed) {
143
+ this.#backend.resetStream(this.peerId, this.streamId);
144
+ this.terminal();
145
+ }
146
+ }
147
+ /** Resets and relinquishes the stream, suppressing later native events. */
148
+ abandon() {
149
+ if (!this.#closed) {
150
+ this.#backend.abandonStream(this.peerId, this.streamId);
151
+ this.terminal();
80
152
  }
81
- return dropped;
82
153
  }
83
- #index(node) {
84
- if (node.event.tag === P2pEvent_Tags.Message ||
85
- node.event.tag === P2pEvent_Tags.StreamData) {
86
- this.#payloads.add(node);
154
+ [Symbol.dispose]() {
155
+ this.abandon();
156
+ }
157
+ /** @internal */
158
+ receive(data) {
159
+ if (this.#closed) {
160
+ return;
161
+ }
162
+ const chunk = new Uint8Array(data);
163
+ const read = this.#reads.shift();
164
+ if (read !== undefined) {
165
+ read.resolve(chunk);
166
+ return;
167
+ }
168
+ if (this.#mode === "flowing") {
169
+ this.#emit("data", chunk);
170
+ return;
171
+ }
172
+ if (this.#fifo.length >= STREAM_CHUNK_CAP ||
173
+ this.#fifoBytes + chunk.byteLength > STREAM_BYTE_CAP) {
174
+ this.#emit("dataOverflow", {
175
+ droppedBytes: chunk.byteLength,
176
+ droppedChunks: 1,
177
+ });
178
+ return;
179
+ }
180
+ this.#fifo.push(chunk);
181
+ this.#fifoBytes += chunk.byteLength;
182
+ }
183
+ /** @internal */
184
+ remoteWriteClosed() {
185
+ if (this.#closed || this.#remoteWriteClosed) {
186
+ return;
87
187
  }
88
- if (REPLACEABLE_EVENTS.has(node.event.tag)) {
89
- let nodes = this.#replaceable.get(node.event.tag);
90
- if (nodes === undefined) {
91
- nodes = new Set();
92
- this.#replaceable.set(node.event.tag, nodes);
188
+ this.#remoteWriteClosed = true;
189
+ this.#emit("remoteWriteClosed");
190
+ if (this.#fifo.length === 0) {
191
+ for (const read of this.#reads.splice(0)) {
192
+ read.resolve();
93
193
  }
94
- nodes.add(node);
95
194
  }
96
195
  }
97
- #remove(node) {
98
- if (node.previous === undefined) {
99
- this.#head = node.next;
196
+ /** @internal */
197
+ terminal(error = new ClosedError()) {
198
+ if (this.#closed) {
199
+ return;
100
200
  }
101
- else {
102
- node.previous.next = node.next;
201
+ this.#closed = true;
202
+ this.#fifo.length = 0;
203
+ this.#fifoBytes = 0;
204
+ for (const read of this.#reads.splice(0)) {
205
+ read.reject(error);
103
206
  }
104
- if (node.next === undefined) {
105
- this.#tail = node.previous;
207
+ this.#emit("closed");
208
+ this.#listeners.clear();
209
+ this.#onTerminal();
210
+ }
211
+ #flushFlowing() {
212
+ while (this.#fifo.length > 0 && !this.#closed) {
213
+ const chunk = this.#shift();
214
+ if (chunk !== undefined) {
215
+ this.#emit("data", chunk);
216
+ }
106
217
  }
107
- else {
108
- node.next.previous = node.previous;
218
+ }
219
+ #shift() {
220
+ const chunk = this.#fifo.shift();
221
+ if (chunk !== undefined) {
222
+ this.#fifoBytes -= chunk.byteLength;
109
223
  }
110
- this.#payloads.delete(node);
111
- const replaceable = this.#replaceable.get(node.event.tag);
112
- replaceable?.delete(node);
113
- if (replaceable?.size === 0) {
114
- this.#replaceable.delete(node.event.tag);
224
+ return chunk;
225
+ }
226
+ #emit(type, payload) {
227
+ for (const handler of [...(this.#listeners.get(type) ?? [])]) {
228
+ try {
229
+ handler(payload);
230
+ }
231
+ catch {
232
+ // Stream handlers are isolated from native callbacks and one another.
233
+ }
115
234
  }
116
- this.#size -= 1;
117
235
  }
118
236
  }
119
237
  /**
120
- * Platform-neutral owner for one native minip2p endpoint.
238
+ * Promise-first, platform-neutral owner for one native minip2p endpoint.
121
239
  *
122
- * Platform packages extend this class and expose a zero-argument `create`
123
- * method backed by their native adapter.
240
+ * Platform packages subclass this and provide a native backend factory.
124
241
  */
125
- export class MiniP2pBase {
242
+ export class Minip2pBase {
126
243
  #backend;
127
244
  #relayAddrs;
128
- #handlers = new Set();
245
+ #named = new Map();
246
+ #catchAll = new Set();
247
+ #closeHandlers = new Set();
129
248
  #waiters = new Set();
130
- #queue = new EventQueue();
131
- #connectResults = new Map();
132
- #overflowDropped = 0;
249
+ #queue = new BoundedQueue(EVENT_QUEUE_CAP);
250
+ #connects = new Map();
251
+ #terminalConnects = new Set();
252
+ #streams = new Map();
253
+ #pendingOpens = new Map();
254
+ #pings = new Map();
255
+ #dropped = 0;
133
256
  #flushScheduled = false;
134
257
  #closed = false;
135
258
  constructor(backend, relayAddresses) {
136
259
  this.#backend = backend;
137
260
  this.#relayAddrs = relayAddresses;
138
261
  try {
139
- this.#backend.start((event) => {
140
- this.#enqueue(event);
262
+ backend.start((event) => {
263
+ this.#enqueueNative(event);
141
264
  });
142
265
  }
143
266
  catch (error) {
144
- this.#backend.close();
267
+ backend.close();
145
268
  throw error;
146
269
  }
147
270
  }
148
- /** Adds an event subscriber and returns an idempotent unsubscribe function. */
149
- on(handler) {
271
+ on(typeOrHandler, maybeHandler) {
150
272
  this.#assertOpen();
151
- this.#handlers.add(handler);
152
- let subscribed = true;
153
- return () => {
154
- if (subscribed) {
155
- subscribed = false;
156
- this.#handlers.delete(handler);
157
- }
158
- };
273
+ if (typeof typeOrHandler === "function") {
274
+ return subscribe(this.#catchAll, typeOrHandler);
275
+ }
276
+ let handlers = this.#named.get(typeOrHandler);
277
+ if (handlers === undefined) {
278
+ handlers = new Set();
279
+ this.#named.set(typeOrHandler, handlers);
280
+ }
281
+ return subscribe(handlers, maybeHandler);
282
+ }
283
+ /** Resolves with the next event of `type`. */
284
+ once(type, options) {
285
+ return this.waitFor(type, { ...options });
159
286
  }
160
- waitFor(predicate, timeoutMs = 65_000) {
287
+ /** Resolves with the next event of `type` accepted by `predicate`. */
288
+ waitFor(type, options) {
161
289
  this.#assertOpen();
162
- assertSafeUnsignedInteger(timeoutMs, "timeoutMs");
290
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
291
+ assertTimeout(timeoutMs);
292
+ if (options.signal?.aborted === true) {
293
+ return Promise.reject(new AbortError());
294
+ }
163
295
  return new Promise((resolve, reject) => {
164
- const waiter = { predicate, reject, resolve };
296
+ const waiter = {
297
+ predicate: (event) => options.predicate?.(event) ?? true,
298
+ reject,
299
+ resolve: (event) => {
300
+ resolve(event);
301
+ },
302
+ type,
303
+ };
165
304
  if (timeoutMs > 0) {
166
305
  waiter.timer = setTimeout(() => {
167
306
  this.#waiters.delete(waiter);
307
+ waiter.removeAbort?.();
168
308
  reject(new TimeoutError(timeoutMs));
169
309
  }, timeoutMs);
170
310
  }
311
+ waiter.removeAbort = listenAbort(options.signal, () => {
312
+ this.#waiters.delete(waiter);
313
+ clearTimeout(waiter.timer);
314
+ reject(new AbortError());
315
+ });
171
316
  this.#waiters.add(waiter);
172
317
  });
173
318
  }
174
- /** Requests native shutdown and releases the platform backend. */
175
- close() {
319
+ /** Registers a one-shot endpoint shutdown observer. */
320
+ onClose(handler) {
176
321
  if (this.#closed) {
177
- return;
322
+ return () => { };
178
323
  }
179
- this.#closed = true;
180
- this.#queue.clear();
181
- this.#connectResults.clear();
182
- this.#overflowDropped = 0;
183
- this.#handlers.clear();
184
- for (const waiter of this.#waiters) {
185
- clearWaiterTimer(waiter);
186
- waiter.reject(new ClosedError());
187
- }
188
- this.#waiters.clear();
189
- this.#backend.close();
324
+ return subscribe(this.#closeHandlers, handler);
325
+ }
326
+ /** Idempotently stops the endpoint and rejects outstanding operations. */
327
+ close() {
328
+ this.#teardown({ reason: "close" }, new ClosedError());
190
329
  }
191
- /** Returns the endpoint's base58 peer ID. */
330
+ [Symbol.dispose]() {
331
+ this.close();
332
+ }
333
+ /** Returns this endpoint's base58 peer ID. */
192
334
  peerId() {
193
335
  this.#assertOpen();
194
336
  return this.#backend.peerId();
195
337
  }
196
- /** Returns the endpoint's bound peer addresses. */
338
+ /** Returns the currently bound peer multiaddresses. */
197
339
  listenAddrs() {
198
340
  this.#assertOpen();
199
341
  return this.#backend.listenAddrs();
200
342
  }
201
- /** Returns currently connected peer IDs. */
343
+ /** Returns peer IDs with live transport connections. */
202
344
  connectedPeers() {
203
345
  this.#assertOpen();
204
346
  return this.#backend.connectedPeers();
205
347
  }
206
- /** Returns whether Identify has completed for a connected peer. */
348
+ /** Returns whether Identify completed for a connected peer. */
207
349
  isPeerReady(peerId) {
208
350
  this.#assertOpen();
209
351
  return this.#backend.isPeerReady(peerId);
210
352
  }
211
- /** Returns the latest Identify snapshot for a connected peer. */
353
+ /** Returns the latest Identify snapshot for `peerId`. */
212
354
  peerInfo(peerId) {
213
355
  this.#assertOpen();
214
356
  return this.#backend.peerInfo(peerId);
215
357
  }
216
- /** Returns the normalized discovery address book. */
358
+ /** Returns the normalized multi-source discovery address book. */
217
359
  knownPeers() {
218
360
  this.#assertOpen();
219
361
  return this.#backend.knownPeers();
220
362
  }
221
- /** Returns the native discovery monotonic clock, when discovery is enabled. */
363
+ /** Returns the discovery monotonic clock when discovery is enabled. */
222
364
  discoveryNowMs() {
223
365
  this.#assertOpen();
224
366
  return this.#backend.discoveryNowMs();
225
367
  }
226
- /** Returns the active relay reservation, if one exists. */
368
+ /** Returns the active relay reservation, if any. */
227
369
  activeReservation() {
228
370
  this.#assertOpen();
229
371
  return this.#backend.activeReservation();
230
372
  }
231
- /** Returns this endpoint's currently usable circuit address, if known. */
373
+ /** Returns this endpoint's usable circuit address, if reserved. */
232
374
  get circuitAddress() {
233
375
  const reservation = this.activeReservation();
234
376
  if (reservation === undefined) {
235
377
  return undefined;
236
378
  }
237
- const suffix = `/p2p/${reservation.relayPeerId}`;
238
- const relayAddr = this.#relayAddrs.find((addr) => addr.endsWith(suffix));
239
- return relayAddr === undefined
379
+ const relay = this.#relayAddrs.find((address) => address.endsWith(`/p2p/${reservation.relayPeerId}`));
380
+ return relay === undefined
240
381
  ? undefined
241
- : this.#backend.circuitAddress(relayAddr, this.peerId());
382
+ : this.#backend.circuitAddress(relay, this.peerId());
242
383
  }
243
- /** Returns the current native reachability state. */
384
+ /** Returns the latest AutoNAT reachability verdict. */
244
385
  reachability() {
245
386
  this.#assertOpen();
246
387
  return this.#backend.reachability();
247
388
  }
389
+ /** Returns the authoritative active path to `peerId`, if connected. */
390
+ path(peerId) {
391
+ this.#assertOpen();
392
+ const path = this.#backend.path(peerId);
393
+ return path === undefined ? undefined : normalizePath(path);
394
+ }
248
395
  /** Returns whether the native driver is accepting work. */
249
396
  isRunning() {
250
397
  return !this.#closed && this.#backend.isRunning();
251
398
  }
252
- /** Selects foreground or idle native polling. */
399
+ /** Selects foreground or idle native polling behavior. */
253
400
  setActive(active) {
254
401
  this.#assertOpen();
255
402
  this.#backend.setActive(active);
256
403
  }
257
- /** Subscribes to a pubsub topic. */
404
+ /** Subscribes to a pubsub topic; returns whether the set changed. */
258
405
  subscribe(topic) {
259
406
  this.#assertOpen();
260
407
  return this.#backend.subscribe(topic);
261
408
  }
262
- /** Withdraws a pubsub subscription. */
409
+ /** Unsubscribes from a pubsub topic; returns whether the set changed. */
263
410
  unsubscribe(topic) {
264
411
  this.#assertOpen();
265
412
  return this.#backend.unsubscribe(topic);
266
413
  }
267
- /** Publishes UTF-8 text or bytes. */
414
+ /** Publishes UTF-8 text or bytes to a subscribed pubsub topic. */
268
415
  publish(topic, data) {
269
416
  this.#assertOpen();
270
417
  this.#backend.publish(topic, toUint8Array(data));
271
418
  }
272
- /** Sends an explicit ping; the result is emitted as a ping event. */
273
- ping(peerId) {
419
+ /** Registers an application protocol for future inbound streams. */
420
+ addProtocol(protocolId) {
274
421
  this.#assertOpen();
275
- this.#backend.ping(peerId);
422
+ this.#backend.addProtocol(protocolId);
276
423
  }
277
- /** Waits until Identify completes for `peerId`. */
278
- waitPeerReady(peerId, timeoutMs = 65_000) {
279
- const info = this.peerInfo(peerId);
424
+ /** Waits for Identify readiness or rejects if the peer disconnects. */
425
+ waitPeerReady(peerId, options = {}) {
426
+ const info = this.isPeerReady(peerId) ? this.peerInfo(peerId) : undefined;
280
427
  if (info !== undefined) {
281
- return Promise.resolve({
282
- inner: { peerId, protocols: info.protocols },
283
- tag: P2pEvent_Tags.PeerReady,
284
- });
428
+ return Promise.resolve({ peerId, protocols: info.protocols });
285
429
  }
286
- return this.waitFor((event) => "tag" in event &&
287
- (event.tag === P2pEvent_Tags.PeerReady ||
288
- event.tag === P2pEvent_Tags.ConnectionClosed) &&
289
- event.inner.peerId === peerId, timeoutMs).then((event) => {
290
- if (event.tag === P2pEvent_Tags.ConnectionClosed) {
291
- throw new PeerDisconnectedError(peerId);
292
- }
293
- return event;
430
+ const controller = new AbortController();
431
+ if (options.signal?.aborted === true) {
432
+ controller.abort();
433
+ }
434
+ const removeExternalAbort = listenAbort(options.signal, () => {
435
+ controller.abort();
436
+ });
437
+ const ready = this.waitFor("peerReady", {
438
+ ...options,
439
+ predicate: (event) => event.peerId === peerId,
440
+ signal: controller.signal,
441
+ }).then(({ protocols }) => ({ peerId, protocols }));
442
+ const disconnected = this.waitFor("connectionClosed", {
443
+ ...options,
444
+ predicate: (event) => event.peerId === peerId &&
445
+ !this.#backend.connectedPeers().includes(peerId),
446
+ signal: controller.signal,
447
+ }).then(() => {
448
+ throw new PeerDisconnectedError(peerId, "waitPeerReady");
449
+ });
450
+ return Promise.race([ready, disconnected]).finally(() => {
451
+ removeExternalAbort?.();
452
+ controller.abort();
294
453
  });
295
454
  }
296
- /** Waits for the next explicit or keepalive ping RTT for `peerId`. */
297
- waitPingRtt(peerId, timeoutMs = 65_000) {
298
- return this.waitFor((event) => "tag" in event &&
299
- event.tag === P2pEvent_Tags.PingRttMeasured &&
300
- event.inner.peerId === peerId, timeoutMs);
301
- }
302
- /** Registers an application protocol at runtime. */
303
- addProtocol(protocolId) {
455
+ /** Measures round-trip latency in milliseconds, coalescing concurrent calls. */
456
+ ping(peerId, options = {}) {
304
457
  this.#assertOpen();
305
- this.#backend.addProtocol(protocolId);
458
+ let operation = this.#pings.get(peerId);
459
+ if (operation === undefined) {
460
+ operation = this.#runPing(peerId);
461
+ this.#pings.set(peerId, operation);
462
+ const current = operation;
463
+ void operation.promise.then(() => this.#removePing(peerId, current), () => this.#removePing(peerId, current));
464
+ this.#backend.ping(peerId);
465
+ }
466
+ operation.callers += 1;
467
+ const current = operation;
468
+ return withOptions(operation.promise, options).finally(() => {
469
+ current.callers -= 1;
470
+ if (current.callers === 0 && this.#pings.get(peerId) === current) {
471
+ current.cancel(new AbortError("No ping callers remain"));
472
+ this.#pings.delete(peerId);
473
+ }
474
+ });
306
475
  }
307
- /** Opens a negotiated custom-protocol stream. */
308
- openStream(peerId, protocolId) {
476
+ /** Opens and negotiates an application-protocol stream. */
477
+ openStream(peerId, protocolId, options = {}) {
309
478
  this.#assertOpen();
310
- return this.#backend.openStream(peerId, protocolId);
479
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
480
+ assertTimeout(timeoutMs);
481
+ if (options.signal?.aborted === true) {
482
+ return Promise.reject(new AbortError());
483
+ }
484
+ let identity;
485
+ try {
486
+ identity = this.#backend.openStream(peerId, protocolId);
487
+ }
488
+ catch (error) {
489
+ return Promise.reject(new OpenStreamError({
490
+ detail: errorMessage(error),
491
+ kind: "synchronous",
492
+ peerId,
493
+ }));
494
+ }
495
+ return new Promise((resolve, reject) => {
496
+ const pending = {
497
+ connId: identity.connId,
498
+ peerId,
499
+ protocolId,
500
+ reject,
501
+ resolve,
502
+ streamId: identity.streamId,
503
+ };
504
+ if (timeoutMs > 0) {
505
+ pending.timer = setTimeout(() => {
506
+ this.#expireOpen(pending, new TimeoutError(timeoutMs));
507
+ }, timeoutMs);
508
+ }
509
+ pending.removeAbort = listenAbort(options.signal, () => {
510
+ this.#expireOpen(pending, new AbortError());
511
+ });
512
+ const key = pendingOpenKey(peerId, identity.connId, identity.streamId);
513
+ const overwritten = this.#pendingOpens.get(key);
514
+ if (overwritten !== undefined) {
515
+ clearPendingOpen(overwritten);
516
+ overwritten.reject(new OpenStreamError({
517
+ connId: overwritten.connId,
518
+ detail: "The native backend reused an in-flight stream identity",
519
+ kind: "synchronous",
520
+ peerId: overwritten.peerId,
521
+ streamId: overwritten.streamId,
522
+ }));
523
+ }
524
+ this.#pendingOpens.set(key, pending);
525
+ });
311
526
  }
312
- /** Sends UTF-8 text or bytes on a custom-protocol stream. */
313
- sendStream(peerId, streamId, data) {
527
+ /** Starts an advanced NAT-orchestrated connection attempt. */
528
+ startConnect(peerId) {
314
529
  this.#assertOpen();
315
- assertSafeUnsignedInteger(streamId, "streamId");
316
- this.#backend.sendStream(peerId, streamId, toUint8Array(data));
530
+ return this.#rememberConnect(this.#backend.connect(peerId));
317
531
  }
318
- /** Half-closes the local write side of a stream. */
319
- closeStreamWrite(peerId, streamId) {
532
+ /** Starts a connection attempt with an explicit ordered address set. */
533
+ startConnectWithAddrs(peerId, addresses) {
320
534
  this.#assertOpen();
321
- assertSafeUnsignedInteger(streamId, "streamId");
322
- this.#backend.closeStreamWrite(peerId, streamId);
535
+ return this.#rememberConnect(this.#backend.connectWithAddrs(peerId, addresses));
323
536
  }
324
- /** Resets a stream while retaining later close events. */
325
- resetStream(peerId, streamId) {
537
+ /** Starts a connection attempt from one full peer multiaddress. */
538
+ startConnectAddr(address) {
326
539
  this.#assertOpen();
327
- assertSafeUnsignedInteger(streamId, "streamId");
328
- this.#backend.resetStream(peerId, streamId);
540
+ return this.#rememberConnect(this.#backend.connectAddr(address));
329
541
  }
330
- /** Resets and forgets a stream, suppressing later stream events. */
331
- abandonStream(peerId, streamId) {
332
- this.#assertOpen();
333
- assertSafeUnsignedInteger(streamId, "streamId");
334
- this.#backend.abandonStream(peerId, streamId);
542
+ /** Connects to a known peer and resolves with its first usable path. */
543
+ connect(peerId, options = {}) {
544
+ return this.#primaryConnect(this.startConnect(peerId), options);
335
545
  }
336
- /** Starts a connection attempt and returns its endpoint-local ID. */
337
- connect(peerId) {
338
- this.#assertOpen();
339
- return this.#backend.connect(peerId);
546
+ /** Connects using an explicit ordered address set. */
547
+ connectWithAddrs(peerId, addresses, options = {}) {
548
+ return this.#primaryConnect(this.startConnectWithAddrs(peerId, addresses), options);
340
549
  }
341
- /** Starts a NAT connection attempt using an explicit ordered address set. */
342
- connectWithAddrs(peerId, addresses) {
343
- this.#assertOpen();
344
- return this.#backend.connectWithAddrs(peerId, addresses);
550
+ /** Connects using one full peer multiaddress. */
551
+ connectAddr(address, options = {}) {
552
+ return this.#primaryConnect(this.startConnectAddr(address), options);
345
553
  }
346
- /** Waits for a connection attempt's first usable path or terminal failure. */
347
- waitConnectResult(connectId, timeoutMs = 65_000) {
348
- assertSafeUnsignedInteger(connectId, "connectId");
554
+ /** Consumes the terminal result for a `startConnect*` attempt. */
555
+ waitConnectResult(connectId, options = {}) {
349
556
  this.#assertOpen();
350
- const result = this.#connectResults.get(connectId);
351
- if (result !== undefined) {
352
- return Promise.resolve(result);
557
+ assertId(connectId, "connectId");
558
+ const attempt = this.#connects.get(connectId);
559
+ if (attempt === undefined || attempt.waiting) {
560
+ return Promise.reject(new ConnectResultUnavailableError(connectId));
561
+ }
562
+ if (attempt.terminal !== undefined) {
563
+ this.#connects.delete(connectId);
564
+ this.#terminalConnects.delete(connectId);
565
+ return attempt.terminal.ok
566
+ ? Promise.resolve(attempt.terminal.result)
567
+ : Promise.reject(attempt.terminal.error);
353
568
  }
354
- return this.waitFor((event) => "tag" in event &&
355
- (event.tag === P2pEvent_Tags.PathEstablished ||
356
- event.tag === P2pEvent_Tags.ConnectFailed) &&
357
- event.inner.connectId === connectId, timeoutMs);
569
+ attempt.waiting = true;
570
+ const result = new Promise((resolve, reject) => {
571
+ attempt.resolve = resolve;
572
+ attempt.reject = reject;
573
+ });
574
+ return withOptions(result, options, () => {
575
+ this.cancelConnect(connectId);
576
+ }).finally(() => {
577
+ this.#connects.delete(connectId);
578
+ });
358
579
  }
359
- /** Starts a direct-address connection attempt. */
360
- connectAddr(address) {
580
+ /** Cancels an in-flight advanced connection attempt. */
581
+ cancelConnect(connectId) {
361
582
  this.#assertOpen();
362
- return this.#backend.connectAddr(address);
583
+ assertId(connectId, "connectId");
584
+ this.#backend.cancelConnect(connectId);
585
+ const attempt = this.#connects.get(connectId);
586
+ attempt?.reject?.(new AbortError("The connection attempt was cancelled"));
587
+ this.#connects.delete(connectId);
588
+ this.#terminalConnects.delete(connectId);
363
589
  }
364
- /** Dials a direct address on every applicable local address family. */
590
+ /** Starts direct transport dials for every applicable local address family. */
365
591
  dial(address) {
366
592
  this.#assertOpen();
367
593
  return this.#backend.dial(address);
368
594
  }
369
- /** Dials a direct address using IPv4. */
595
+ /** Starts a direct IPv4 transport dial. */
370
596
  dialIp4(address) {
371
597
  this.#assertOpen();
372
598
  return this.#backend.dialIp4(address);
373
599
  }
374
- /** Dials a direct address using IPv6. */
600
+ /** Starts a direct IPv6 transport dial. */
375
601
  dialIp6(address) {
376
602
  this.#assertOpen();
377
603
  return this.#backend.dialIp6(address);
378
604
  }
379
- /** Suppresses future events for a known connection attempt. */
380
- cancelConnect(id) {
381
- this.#assertOpen();
382
- assertSafeUnsignedInteger(id, "connectId");
383
- this.#backend.cancelConnect(id);
384
- }
385
- /** Closes an established connection to a peer. */
605
+ /** Closes the active connection to `peerId`. */
386
606
  disconnect(peerId) {
387
607
  this.#assertOpen();
388
608
  this.#backend.disconnect(peerId);
389
609
  }
390
- #assertOpen() {
610
+ #rememberConnect(connectId) {
611
+ this.#connects.set(connectId, { waiting: false });
612
+ return connectId;
613
+ }
614
+ #primaryConnect(connectId, options) {
615
+ return this.waitConnectResult(connectId, options);
616
+ }
617
+ #runPing(peerId) {
618
+ let settled = false;
619
+ let rejectOperation = () => { };
620
+ let cleanup = () => { };
621
+ const promise = new Promise((resolve, reject) => {
622
+ rejectOperation = reject;
623
+ const offRtt = this.on("pingRttMeasured", (event) => {
624
+ if (event.peerId === peerId) {
625
+ finish();
626
+ resolve(event.rttMs);
627
+ }
628
+ });
629
+ const offTimeout = this.on("pingTimeout", (event) => {
630
+ if (event.peerId === peerId) {
631
+ finish();
632
+ reject(new TimeoutError());
633
+ }
634
+ });
635
+ const offClosed = this.on("connectionClosed", (event) => {
636
+ if (event.peerId === peerId &&
637
+ !this.#backend.connectedPeers().includes(peerId)) {
638
+ finish();
639
+ reject(new PeerDisconnectedError(peerId, "ping"));
640
+ }
641
+ });
642
+ cleanup = () => {
643
+ offRtt();
644
+ offTimeout();
645
+ offClosed();
646
+ };
647
+ const finish = () => {
648
+ if (!settled) {
649
+ settled = true;
650
+ cleanup();
651
+ }
652
+ };
653
+ });
654
+ return {
655
+ callers: 0,
656
+ cancel: (error) => {
657
+ if (!settled) {
658
+ settled = true;
659
+ cleanup();
660
+ rejectOperation(error);
661
+ }
662
+ },
663
+ promise,
664
+ };
665
+ }
666
+ #removePing(peerId, operation) {
667
+ if (this.#pings.get(peerId) === operation) {
668
+ this.#pings.delete(peerId);
669
+ }
670
+ }
671
+ #handleQueueOverflow() {
672
+ const error = new EventQueueOverflowError();
673
+ for (const waiter of [...this.#waiters]) {
674
+ this.#settleWaiter(waiter, error);
675
+ }
676
+ for (const ping of this.#pings.values()) {
677
+ ping.cancel(error);
678
+ }
679
+ this.#pings.clear();
680
+ for (const [connectId, attempt] of [...this.#connects]) {
681
+ if (attempt.terminal === undefined) {
682
+ attempt.reject?.(error);
683
+ this.#connects.delete(connectId);
684
+ this.#terminalConnects.delete(connectId);
685
+ }
686
+ }
687
+ for (const pending of this.#pendingOpens.values()) {
688
+ clearPendingOpen(pending);
689
+ pending.reject(error);
690
+ try {
691
+ this.#backend.abandonStream(pending.peerId, pending.streamId);
692
+ }
693
+ catch {
694
+ // The operation is already failed; native cleanup is best effort.
695
+ }
696
+ }
697
+ this.#pendingOpens.clear();
698
+ }
699
+ #enqueueNative(event) {
391
700
  if (this.#closed) {
392
- throw new ClosedError();
701
+ return;
702
+ }
703
+ if (this.#queue.push({ event, source: "native" }) !== undefined) {
704
+ this.#dropped += 1;
705
+ this.#handleQueueOverflow();
393
706
  }
707
+ this.#scheduleFlush();
394
708
  }
395
- #enqueue(event) {
709
+ #enqueueHigh(type, payload) {
396
710
  if (this.#closed) {
397
711
  return;
398
712
  }
399
- this.#overflowDropped += this.#queue.push(event);
713
+ if (this.#queue.push({ payload, source: "high", type }) !== undefined) {
714
+ this.#dropped += 1;
715
+ this.#handleQueueOverflow();
716
+ }
400
717
  this.#scheduleFlush();
401
718
  }
402
719
  #scheduleFlush() {
@@ -414,89 +731,512 @@ export class MiniP2pBase {
414
731
  }
415
732
  this.#flushScheduled = false;
416
733
  let delivered = 0;
417
- if (this.#overflowDropped > 0) {
418
- const dropped = this.#overflowDropped;
419
- this.#overflowDropped = 0;
420
- this.#dispatch({ dropped, type: "queueOverflow" });
734
+ if (this.#dropped > 0) {
735
+ const dropped = this.#dropped;
736
+ this.#dropped = 0;
737
+ this.#dispatch("queueOverflow", { dropped }, { dropped });
421
738
  delivered += 1;
422
739
  }
423
- while (delivered < FLUSH_BATCH) {
424
- const event = this.#queue.shift();
425
- if (event === undefined) {
740
+ while (delivered < EVENT_FLUSH_BATCH) {
741
+ const item = this.#queue.shift();
742
+ if (item === undefined) {
426
743
  break;
427
744
  }
428
- this.#dispatch(event);
745
+ if (item.source === "native") {
746
+ this.#dispatchNative(item.event);
747
+ }
748
+ else {
749
+ this.#dispatch(item.type, item.payload, item.payload);
750
+ }
429
751
  delivered += 1;
430
752
  if (this.#closed) {
431
753
  return;
432
754
  }
433
755
  }
434
- if (this.#queue.size > 0 || this.#overflowDropped > 0) {
756
+ if (this.#queue.length > 0) {
435
757
  this.#flushScheduled = true;
436
758
  setTimeout(() => {
437
759
  this.#flush();
438
760
  }, 0);
439
761
  }
440
762
  }
441
- #dispatch(event) {
442
- if ("tag" in event &&
443
- (event.tag === P2pEvent_Tags.PathEstablished ||
444
- event.tag === P2pEvent_Tags.ConnectFailed)) {
445
- this.#connectResults.set(event.inner.connectId, event);
763
+ #dispatchNative(event) {
764
+ if (event.tag === P2pEvent_Tags.DriverFailed) {
765
+ const failure = new DriverFailedError(event.inner.kind, event.inner.detail);
766
+ this.#dispatch("driverFailed", event.inner, event.inner);
767
+ this.#teardown({ error: failure, reason: "driverFailed" }, failure);
768
+ return;
769
+ }
770
+ if (event.tag === P2pEvent_Tags.StreamReady) {
771
+ this.#streamReady(event.inner);
772
+ return;
446
773
  }
447
- if ("tag" in event && event.tag === P2pEvent_Tags.DriverFailed) {
448
- this.#terminateDriver(event);
774
+ if (event.tag === P2pEvent_Tags.StreamData ||
775
+ event.tag === P2pEvent_Tags.StreamRemoteWriteClosed ||
776
+ event.tag === P2pEvent_Tags.StreamClosed) {
777
+ this.#streamEvent(event);
449
778
  return;
450
779
  }
780
+ if (event.tag === P2pEvent_Tags.EndpointError) {
781
+ this.#correlateOpenError(event.inner);
782
+ }
783
+ if (event.tag === P2pEvent_Tags.ConnectionClosed) {
784
+ this.#connectionClosed(event.inner.peerId, event.inner.connId);
785
+ }
786
+ if (event.tag === P2pEvent_Tags.PathEstablished ||
787
+ event.tag === P2pEvent_Tags.ConnectFailed) {
788
+ this.#connectTerminal(event);
789
+ }
790
+ const normalized = normalizeEvent(event);
791
+ if (normalized !== undefined) {
792
+ this.#dispatch(normalized.type, normalized.payload, normalized.payload);
793
+ }
794
+ }
795
+ #dispatch(type, payload, catchPayload) {
796
+ let claimed = false;
797
+ const result = eventResult(type, payload);
451
798
  for (const waiter of [...this.#waiters]) {
452
- let matched;
799
+ if (waiter.type !== type) {
800
+ continue;
801
+ }
802
+ let matched = false;
453
803
  try {
454
- matched = waiter.predicate(event);
804
+ matched = waiter.predicate(result);
455
805
  }
456
806
  catch (error) {
457
- this.#waiters.delete(waiter);
458
- clearWaiterTimer(waiter);
459
- waiter.reject(asError(error));
807
+ this.#settleWaiter(waiter, error);
460
808
  continue;
461
809
  }
462
810
  if (matched) {
811
+ claimed = true;
463
812
  this.#waiters.delete(waiter);
464
- clearWaiterTimer(waiter);
465
- waiter.resolve(event);
813
+ clearTimeout(waiter.timer);
814
+ waiter.removeAbort?.();
815
+ waiter.resolve(result);
466
816
  }
467
817
  }
468
- for (const handler of [...this.#handlers]) {
818
+ const handlers = [...(this.#named.get(type) ?? [])];
819
+ for (const handler of handlers) {
469
820
  try {
470
- handler(event);
821
+ handler(payload);
822
+ if (type === "stream") {
823
+ claimed = true;
824
+ }
471
825
  }
472
- catch {
473
- // One host handler cannot interrupt fan-out or unwind into Rust.
826
+ catch (error) {
827
+ this.#handlerFailed(type, payload, error);
828
+ }
829
+ }
830
+ if (type !== "stream") {
831
+ const catchEvent = eventResult(type, catchPayload);
832
+ for (const handler of [...this.#catchAll]) {
833
+ try {
834
+ handler(catchEvent);
835
+ }
836
+ catch (error) {
837
+ this.#handlerFailed(type, payload, error);
838
+ }
474
839
  }
475
840
  }
841
+ return claimed;
476
842
  }
477
- #terminateDriver(event) {
478
- this.#closed = true;
479
- this.#queue.clear();
480
- this.#connectResults.clear();
481
- this.#overflowDropped = 0;
482
- const handlers = [...this.#handlers];
483
- this.#handlers.clear();
484
- const failure = new DriverFailedError(event.inner.kind, event.inner.detail);
485
- for (const waiter of this.#waiters) {
486
- clearWaiterTimer(waiter);
487
- waiter.reject(failure);
488
- }
489
- this.#waiters.clear();
490
- for (const handler of handlers) {
843
+ #handlerFailed(type, payload, error) {
844
+ if (type === "handlerError") {
845
+ return;
846
+ }
847
+ this.#enqueueHigh("handlerError", {
848
+ error,
849
+ eventType: type,
850
+ metadata: type === "stream"
851
+ ? { ...streamMeta(payload) }
852
+ : safeMetadata(payload),
853
+ });
854
+ }
855
+ #streamReady(meta) {
856
+ const key = streamKey(meta.peerId, meta.connId, meta.streamId);
857
+ const stream = new Stream(this.#backend, meta, () => {
858
+ this.#streams.delete(key);
859
+ });
860
+ this.#streams.set(key, stream);
861
+ const pendingKey = pendingOpenKey(meta.peerId, meta.connId, meta.streamId);
862
+ const pending = this.#pendingOpens.get(pendingKey);
863
+ if (pending !== undefined && meta.initiatedLocally) {
864
+ this.#pendingOpens.delete(pendingKey);
865
+ clearPendingOpen(pending);
866
+ pending.resolve(stream);
867
+ return;
868
+ }
869
+ if (meta.initiatedLocally) {
870
+ stream.abandon();
871
+ return;
872
+ }
873
+ const claimed = this.#dispatch("stream", stream, undefined);
874
+ const inbound = streamMeta(stream);
875
+ this.#dispatchCatchOnly("inboundStream", inbound);
876
+ if (!claimed) {
877
+ stream.abandon();
878
+ }
879
+ }
880
+ #dispatchCatchOnly(type, payload) {
881
+ const event = eventResult(type, payload);
882
+ for (const handler of [...this.#catchAll]) {
491
883
  try {
492
884
  handler(event);
493
885
  }
494
- catch {
495
- // One host handler cannot interrupt fan-out or unwind into Rust.
886
+ catch (error) {
887
+ this.#enqueueHigh("handlerError", {
888
+ error,
889
+ eventType: type,
890
+ metadata: safeMetadata(payload),
891
+ });
892
+ }
893
+ }
894
+ }
895
+ #streamEvent(event) {
896
+ const { peerId, connId, streamId } = event.inner;
897
+ const stream = this.#streams.get(streamKey(peerId, connId, streamId));
898
+ if (event.tag === P2pEvent_Tags.StreamClosed) {
899
+ const pendingKey = pendingOpenKey(peerId, connId, streamId);
900
+ const pending = this.#pendingOpens.get(pendingKey);
901
+ if (pending !== undefined) {
902
+ this.#pendingOpens.delete(pendingKey);
903
+ clearPendingOpen(pending);
904
+ pending.reject(new StreamClosedError());
905
+ }
906
+ stream?.terminal();
907
+ }
908
+ else if (event.tag === P2pEvent_Tags.StreamData) {
909
+ stream?.receive(event.inner.data);
910
+ }
911
+ else {
912
+ stream?.remoteWriteClosed();
913
+ }
914
+ }
915
+ #correlateOpenError(error) {
916
+ if (error.streamId === undefined) {
917
+ return;
918
+ }
919
+ const candidates = [...this.#pendingOpens.values()].filter((pending) => pending.streamId === error.streamId &&
920
+ (error.peerId === undefined || error.peerId === pending.peerId) &&
921
+ (error.connId === undefined || error.connId === pending.connId));
922
+ if (candidates.length !== 1) {
923
+ return;
924
+ }
925
+ const [pending] = candidates;
926
+ if (pending === undefined) {
927
+ return;
928
+ }
929
+ this.#pendingOpens.delete(pendingOpenKey(pending.peerId, pending.connId, pending.streamId));
930
+ clearPendingOpen(pending);
931
+ pending.reject(new OpenStreamError({
932
+ connId: error.connId,
933
+ detail: error.detail,
934
+ kind: error.kind,
935
+ peerId: pending.peerId,
936
+ streamId: error.streamId,
937
+ }));
938
+ }
939
+ #connectionClosed(peerId, connId) {
940
+ for (const [key, stream] of [...this.#streams]) {
941
+ if (stream.peerId === peerId && stream.connId === connId) {
942
+ stream.terminal(new PeerDisconnectedError(peerId, "stream"));
943
+ this.#streams.delete(key);
944
+ }
945
+ }
946
+ if (!this.#backend.connectedPeers().includes(peerId)) {
947
+ for (const pending of [...this.#pendingOpens.values()]) {
948
+ if (pending.peerId === peerId) {
949
+ this.#pendingOpens.delete(pendingOpenKey(pending.peerId, pending.connId, pending.streamId));
950
+ clearPendingOpen(pending);
951
+ pending.reject(new PeerDisconnectedError(peerId, "openStream"));
952
+ }
953
+ }
954
+ }
955
+ }
956
+ #connectTerminal(event) {
957
+ const attempt = this.#connects.get(event.inner.connectId);
958
+ if (attempt === undefined) {
959
+ return;
960
+ }
961
+ const terminal = event.tag === P2pEvent_Tags.PathEstablished
962
+ ? {
963
+ ok: true,
964
+ result: {
965
+ connectId: event.inner.connectId,
966
+ path: normalizePath(event.inner.path),
967
+ peerId: event.inner.peerId,
968
+ },
969
+ }
970
+ : {
971
+ error: new ConnectFailedError(event.inner.connectId, event.inner.peerId, event.inner.kind, event.inner.detail),
972
+ ok: false,
973
+ };
974
+ if (attempt.waiting) {
975
+ if (terminal.ok) {
976
+ attempt.resolve?.(terminal.result);
977
+ }
978
+ else {
979
+ attempt.reject?.(terminal.error);
980
+ }
981
+ }
982
+ else {
983
+ attempt.terminal = terminal;
984
+ this.#terminalConnects.delete(event.inner.connectId);
985
+ this.#terminalConnects.add(event.inner.connectId);
986
+ while (this.#terminalConnects.size > CONNECT_TERMINAL_CAP) {
987
+ const oldest = this.#terminalConnects.values().next().value;
988
+ if (oldest === undefined) {
989
+ break;
990
+ }
991
+ this.#terminalConnects.delete(oldest);
992
+ this.#connects.delete(oldest);
496
993
  }
497
994
  }
498
- this.#backend.close();
499
995
  }
996
+ #expireOpen(pending, error) {
997
+ const key = pendingOpenKey(pending.peerId, pending.connId, pending.streamId);
998
+ if (this.#pendingOpens.get(key) !== pending) {
999
+ return;
1000
+ }
1001
+ this.#pendingOpens.delete(key);
1002
+ clearPendingOpen(pending);
1003
+ pending.reject(error);
1004
+ try {
1005
+ this.#backend.abandonStream(pending.peerId, pending.streamId);
1006
+ }
1007
+ catch {
1008
+ // Cleanup failure must not replace the caller's timeout or abort.
1009
+ }
1010
+ }
1011
+ #settleWaiter(waiter, error) {
1012
+ this.#waiters.delete(waiter);
1013
+ clearTimeout(waiter.timer);
1014
+ waiter.removeAbort?.();
1015
+ waiter.reject(error);
1016
+ }
1017
+ #teardown(reason, error) {
1018
+ if (this.#closed) {
1019
+ return;
1020
+ }
1021
+ this.#closed = true;
1022
+ const closeHandlers = [...this.#closeHandlers];
1023
+ this.#closeHandlers.clear();
1024
+ this.#queue.clear();
1025
+ this.#dropped = 0;
1026
+ this.#named.clear();
1027
+ this.#catchAll.clear();
1028
+ for (const waiter of [...this.#waiters]) {
1029
+ this.#settleWaiter(waiter, error);
1030
+ }
1031
+ for (const attempt of this.#connects.values()) {
1032
+ attempt.reject?.(error);
1033
+ }
1034
+ this.#connects.clear();
1035
+ this.#terminalConnects.clear();
1036
+ for (const pending of this.#pendingOpens.values()) {
1037
+ clearPendingOpen(pending);
1038
+ pending.reject(error);
1039
+ }
1040
+ this.#pendingOpens.clear();
1041
+ for (const stream of this.#streams.values()) {
1042
+ stream.terminal(error);
1043
+ }
1044
+ this.#streams.clear();
1045
+ for (const ping of this.#pings.values()) {
1046
+ ping.cancel(error);
1047
+ }
1048
+ this.#pings.clear();
1049
+ try {
1050
+ this.#backend.close();
1051
+ }
1052
+ finally {
1053
+ for (const handler of closeHandlers) {
1054
+ try {
1055
+ handler(reason);
1056
+ }
1057
+ catch {
1058
+ // Close notification is outside the now-closed event queue.
1059
+ }
1060
+ }
1061
+ }
1062
+ }
1063
+ #assertOpen() {
1064
+ if (this.#closed) {
1065
+ throw new ClosedError();
1066
+ }
1067
+ }
1068
+ }
1069
+ function normalizeEvent(event) {
1070
+ const names = {
1071
+ [P2pEvent_Tags.EventsDropped]: "eventsDropped",
1072
+ [P2pEvent_Tags.ConnectionEstablished]: "connectionEstablished",
1073
+ [P2pEvent_Tags.ConnectionClosed]: "connectionClosed",
1074
+ [P2pEvent_Tags.PeerReady]: "peerReady",
1075
+ [P2pEvent_Tags.IdentifyReceived]: "identifyReceived",
1076
+ [P2pEvent_Tags.PingRttMeasured]: "pingRttMeasured",
1077
+ [P2pEvent_Tags.PingTimeout]: "pingTimeout",
1078
+ [P2pEvent_Tags.EndpointError]: "endpointError",
1079
+ [P2pEvent_Tags.ReachabilityChanged]: "reachabilityChanged",
1080
+ [P2pEvent_Tags.PublicAddressesChanged]: "publicAddressesChanged",
1081
+ [P2pEvent_Tags.RelayReserved]: "relayReserved",
1082
+ [P2pEvent_Tags.RelayReservationLost]: "relayReservationLost",
1083
+ [P2pEvent_Tags.PathEstablished]: "pathEstablished",
1084
+ [P2pEvent_Tags.PathUpgraded]: "pathUpgraded",
1085
+ [P2pEvent_Tags.HolePunchFailed]: "holePunchFailed",
1086
+ [P2pEvent_Tags.FellBackToRelay]: "fellBackToRelay",
1087
+ [P2pEvent_Tags.ConnectFailed]: "connectFailed",
1088
+ [P2pEvent_Tags.InboundDirectUpgrade]: "inboundDirectUpgrade",
1089
+ [P2pEvent_Tags.Message]: "message",
1090
+ [P2pEvent_Tags.PeerSubscribed]: "peerSubscribed",
1091
+ [P2pEvent_Tags.PeerUnsubscribed]: "peerUnsubscribed",
1092
+ [P2pEvent_Tags.PubsubOutboundFailure]: "pubsubOutboundFailure",
1093
+ [P2pEvent_Tags.PubsubProtocolViolation]: "pubsubProtocolViolation",
1094
+ [P2pEvent_Tags.PeerDiscovered]: "peerDiscovered",
1095
+ [P2pEvent_Tags.PeerUpdated]: "peerUpdated",
1096
+ [P2pEvent_Tags.PeerExpired]: "peerExpired",
1097
+ [P2pEvent_Tags.DiscoveryDialFailed]: "discoveryDialFailed",
1098
+ [P2pEvent_Tags.DiscoveryProtocolViolation]: "discoveryProtocolViolation",
1099
+ };
1100
+ const type = names[event.tag];
1101
+ if (type === undefined) {
1102
+ return undefined;
1103
+ }
1104
+ let payload = event.inner;
1105
+ if (event.tag === P2pEvent_Tags.PathEstablished) {
1106
+ payload = { ...event.inner, path: normalizePath(event.inner.path) };
1107
+ }
1108
+ else if (event.tag === P2pEvent_Tags.PathUpgraded) {
1109
+ payload = {
1110
+ ...event.inner,
1111
+ from: normalizePath(event.inner.from),
1112
+ to: normalizePath(event.inner.to),
1113
+ };
1114
+ }
1115
+ return { payload: payload, type: type };
1116
+ }
1117
+ function normalizePath(path) {
1118
+ switch (path.tag) {
1119
+ case PathKind_Tags.DirectDialed: {
1120
+ return { kind: "directDialed" };
1121
+ }
1122
+ case PathKind_Tags.DirectPunched: {
1123
+ return { kind: "directPunched" };
1124
+ }
1125
+ case PathKind_Tags.Relayed: {
1126
+ return { kind: "relayed", relayPeerId: path.inner.relayPeerId };
1127
+ }
1128
+ }
1129
+ }
1130
+ function streamKey(peerId, connId, streamId) {
1131
+ return `${peerId}\u0000${connId}\u0000${streamId}`;
1132
+ }
1133
+ function pendingOpenKey(peerId, connId, streamId) {
1134
+ return streamKey(peerId, connId, streamId);
1135
+ }
1136
+ function streamMeta(stream) {
1137
+ return {
1138
+ connId: stream.connId,
1139
+ initiatedLocally: stream.initiatedLocally,
1140
+ peerId: stream.peerId,
1141
+ protocolId: stream.protocolId,
1142
+ streamId: stream.streamId,
1143
+ };
1144
+ }
1145
+ function safeMetadata(payload) {
1146
+ if (payload === null || typeof payload !== "object") {
1147
+ return {};
1148
+ }
1149
+ const metadata = {};
1150
+ for (const [key, value] of Object.entries(payload)) {
1151
+ if (typeof value === "string" ||
1152
+ typeof value === "number" ||
1153
+ typeof value === "boolean" ||
1154
+ value === undefined) {
1155
+ metadata[key] = value;
1156
+ }
1157
+ else if (Array.isArray(value) &&
1158
+ value.every((item) => typeof item === "string")) {
1159
+ metadata[key] = [...value];
1160
+ }
1161
+ }
1162
+ return metadata;
1163
+ }
1164
+ function eventResult(type, payload) {
1165
+ if (payload instanceof Stream) {
1166
+ Object.defineProperty(payload, "type", {
1167
+ configurable: true,
1168
+ enumerable: false,
1169
+ value: type,
1170
+ });
1171
+ return payload;
1172
+ }
1173
+ if (typeof payload === "object" && payload !== null) {
1174
+ return { type, ...payload };
1175
+ }
1176
+ return { type };
1177
+ }
1178
+ function subscribe(set, value) {
1179
+ set.add(value);
1180
+ let active = true;
1181
+ return () => {
1182
+ if (active) {
1183
+ active = false;
1184
+ set.delete(value);
1185
+ }
1186
+ };
1187
+ }
1188
+ function listenAbort(signal, handler) {
1189
+ if (signal === undefined) {
1190
+ return undefined;
1191
+ }
1192
+ signal.addEventListener("abort", handler, { once: true });
1193
+ return () => {
1194
+ signal.removeEventListener("abort", handler);
1195
+ };
1196
+ }
1197
+ function withOptions(promise, options, onCancel) {
1198
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1199
+ assertTimeout(timeoutMs);
1200
+ if (options.signal?.aborted === true) {
1201
+ onCancel?.();
1202
+ return Promise.reject(new AbortError());
1203
+ }
1204
+ return new Promise((resolve, reject) => {
1205
+ let settled = false;
1206
+ let timer;
1207
+ const finish = (callback) => {
1208
+ if (settled) {
1209
+ return;
1210
+ }
1211
+ settled = true;
1212
+ clearTimeout(timer);
1213
+ removeAbort?.();
1214
+ callback();
1215
+ };
1216
+ const removeAbort = listenAbort(options.signal, () => {
1217
+ finish(() => {
1218
+ onCancel?.();
1219
+ reject(new AbortError());
1220
+ });
1221
+ });
1222
+ if (timeoutMs > 0) {
1223
+ timer = setTimeout(() => {
1224
+ finish(() => {
1225
+ onCancel?.();
1226
+ reject(new TimeoutError(timeoutMs));
1227
+ });
1228
+ }, timeoutMs);
1229
+ }
1230
+ void promise.then((value) => {
1231
+ finish(() => resolve(value));
1232
+ }, (error) => {
1233
+ finish(() => reject(error));
1234
+ });
1235
+ });
1236
+ }
1237
+ function clearPendingOpen(pending) {
1238
+ clearTimeout(pending.timer);
1239
+ pending.removeAbort?.();
500
1240
  }
501
1241
  function toUint8Array(value) {
502
1242
  if (typeof value === "string") {
@@ -504,17 +1244,15 @@ function toUint8Array(value) {
504
1244
  }
505
1245
  return value instanceof Uint8Array ? value : new Uint8Array(value);
506
1246
  }
507
- function assertSafeUnsignedInteger(value, name) {
1247
+ function assertId(value, name) {
508
1248
  if (!Number.isSafeInteger(value) || value < 0) {
509
1249
  throw new RangeError(`${name} must be a non-negative safe integer`);
510
1250
  }
511
1251
  }
512
- function clearWaiterTimer(waiter) {
513
- if (waiter.timer !== undefined) {
514
- clearTimeout(waiter.timer);
515
- }
1252
+ function assertTimeout(timeoutMs) {
1253
+ assertId(timeoutMs, "timeoutMs");
516
1254
  }
517
- function asError(error) {
518
- return error instanceof Error ? error : new Error(String(error));
1255
+ function errorMessage(error) {
1256
+ return error instanceof Error ? error.message : String(error);
519
1257
  }
520
1258
  //# sourceMappingURL=sdk.js.map