@minip2p/core 0.9.1 → 0.10.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/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAsC5G,wCAAwC;AACxC,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;CACV,CAAC;AAGX,wDAAwD;AACxD,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,MAAM;IACZ,YAAY,EAAE,cAAc;CACpB,CAAC;AAIX,8DAA8D;AAC9D,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,iFAAiF;IACjF,SAAS,EAAE,WAAW;IACtB,2CAA2C;IAC3C,qBAAqB,EAAE,uBAAuB;IAC9C,2BAA2B;IAC3B,EAAE,EAAE,IAAI;IACR,0CAA0C;IAC1C,kBAAkB,EAAE,oBAAoB;IACxC,2DAA2D;IAC3D,SAAS,EAAE,WAAW;IACtB,oDAAoD;IACpD,gBAAgB,EAAE,kBAAkB;IACpC,gDAAgD;IAChD,WAAW,EAAE,aAAa;CAClB,CAAC;AAIX,6EAA6E;AAC7E,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,8CAA8C;IAC9C,SAAS,EAAE,WAAW;IACtB,0BAA0B;IAC1B,SAAS,EAAE,WAAW;IACtB,qBAAqB;IACrB,IAAI,EAAE,MAAM;IACZ;;;OAGG;IACH,OAAO,EAAE,SAAS;IAClB,sCAAsC;IACtC,SAAS,EAAE,WAAW;CACd,CAAC;AAIX,8CAA8C;AAC9C,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,SAAS,EAAE,WAAW;IACtB,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,OAAO;IACd,SAAS,EAAE,WAAW;C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kB,EAAE,oBAAoB;CAChC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@minip2p/core",
3
- "version": "0.9.1",
3
+ "version": "0.10.0",
4
4
  "description": "Platform-neutral TypeScript SDK for minip2p",
5
5
  "keywords": [
6
6
  "libp2p",
package/src/backend.ts CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  MessageTooLargeError,
5
5
  NotPermittedError,
6
6
  } from "./errors.js";
7
- import { ConfigCapability } from "./types.js";
7
+ import { CloseOutcome, ConfigCapability } from "./types.js";
8
8
  import type {
9
9
  Bytes,
10
10
  ConnectionInfo,
@@ -17,6 +17,89 @@ import type {
17
17
  RelayReservationInfo,
18
18
  } from "./types.js";
19
19
 
20
+ /** How the native endpoint's close drain ended (`EndpointClosed`). */
21
+ export interface BackendClosed {
22
+ readonly outcome: CloseOutcome;
23
+ /** Peers whose connections were still tracked, each once. */
24
+ readonly unfinished: readonly string[];
25
+ }
26
+
27
+ /**
28
+ * The peers `EndpointClosed`'s unfinished connections name, each once. An
29
+ * inbound handshake that had not identified its peer names none.
30
+ */
31
+ export const unfinishedPeers = (
32
+ unfinished: readonly { readonly peerId?: string | undefined }[]
33
+ ): string[] => [
34
+ ...new Set(
35
+ unfinished.flatMap(({ peerId }) => (peerId === undefined ? [] : [peerId]))
36
+ ),
37
+ ];
38
+
39
+ /**
40
+ * A native adapter's side of {@link Minip2pBackend.close}: stops native once,
41
+ * then resolves with the native `EndpointClosed` the adapter hands to
42
+ * {@link settle}, or at once when no driver started.
43
+ */
44
+ export class NativeCloseLatch {
45
+ readonly #closed: Promise<BackendClosed>;
46
+ #resolve: ((closed: BackendClosed) => void) | undefined;
47
+ #closing: Promise<BackendClosed> | undefined;
48
+
49
+ constructor() {
50
+ // oxlint-disable-next-line promise/avoid-new -- Settled by a native event, not a callback API.
51
+ this.#closed = new Promise((resolve) => {
52
+ this.#resolve = resolve;
53
+ });
54
+ }
55
+
56
+ /** Whether `close` was called; later native events can be ignored. */
57
+ get requested(): boolean {
58
+ return this.#closing !== undefined;
59
+ }
60
+
61
+ /** Records the native `EndpointClosed`, which may precede `close`. */
62
+ settle(closed: BackendClosed): void {
63
+ this.#resolve?.(closed);
64
+ }
65
+
66
+ /**
67
+ * Runs `stop` on the first call, then resolves once native closed and
68
+ * `release`, if any, ran. Later calls return the same promise.
69
+ */
70
+ close(
71
+ started: boolean,
72
+ stop: () => void,
73
+ release?: () => void
74
+ ): Promise<BackendClosed> {
75
+ this.#closing ??= this.#finish(started, stop, release);
76
+ return this.#closing;
77
+ }
78
+
79
+ async #finish(
80
+ started: boolean,
81
+ stop: () => void,
82
+ release: (() => void) | undefined
83
+ ): Promise<BackendClosed> {
84
+ stop();
85
+ // Without a driver, native released the endpoint at once.
86
+ const closed = started
87
+ ? await this.#closed
88
+ : { outcome: CloseOutcome.Drained, unfinished: [] };
89
+ try {
90
+ release?.();
91
+ } catch {
92
+ // The endpoint is closed either way; the report still stands.
93
+ }
94
+ return closed;
95
+ }
96
+ }
97
+
98
+ /** A native connection snapshot: {@link ConnectionInfo} with the raw path. */
99
+ export interface BackendConnectionInfo extends Omit<ConnectionInfo, "path"> {
100
+ readonly path: PathKind;
101
+ }
102
+
20
103
  /** Full native identity allocated for an outbound stream. */
21
104
  export interface BackendOpenStream {
22
105
  /** Endpoint-local connection carrying the stream. */
@@ -47,8 +130,14 @@ export interface Minip2pBackend {
47
130
  * elided, dropped, or coalesced into an earlier one.
48
131
  */
49
132
  eventHandled?: (event: P2pEvent) => void;
50
- /** Idempotently releases the native endpoint. */
51
- close: () => void;
133
+ /**
134
+ * Requests native shutdown, draining for up to `timeoutMs` (`0` tears down
135
+ * at once), and resolves with the native `EndpointClosed`, the driver's
136
+ * last event, once the native endpoint is released. Idempotent: later
137
+ * calls return the same promise and their timeout is ignored. Resolves at
138
+ * once for a backend whose `start` failed. Never rejects.
139
+ */
140
+ close: (timeoutMs: number) => Promise<BackendClosed>;
52
141
  /** Returns the local peer ID. */
53
142
  peerId: () => string;
54
143
  /** Returns bound peer multiaddresses. */
@@ -65,10 +154,10 @@ export interface Minip2pBackend {
65
154
  discoveryNowMs: () => number | undefined;
66
155
  /** Returns the active relay reservation. */
67
156
  activeReservation: () => RelayReservationInfo | undefined;
68
- /** Returns the authoritative native path to a peer. */
157
+ /** Returns the path of a peer's established connection. */
69
158
  path: (peerId: string) => PathKind | undefined;
70
- /** Returns the transport connection selected for a peer. */
71
- connectionInfo: (peerId: string) => ConnectionInfo | undefined;
159
+ /** Returns a snapshot of a peer's established connection. */
160
+ connectionInfo: (peerId: string) => BackendConnectionInfo | undefined;
72
161
  /** Builds a circuit address through a relay. */
73
162
  circuitAddress: (relayAddress: string, peerId: string) => string;
74
163
  /** Returns the native reachability state. */
@@ -131,11 +220,13 @@ export { EventDrain } from "./event-drain.js";
131
220
  export { ConnectionIdMap, u64ToNumber } from "./native-ids.js";
132
221
  export { SettleHandles, eventStream } from "./settle-handles.js";
133
222
  export {
223
+ ConnectionCloseReason_Tags,
134
224
  P2pEvent_Tags,
135
225
  PathKind_Tags,
136
226
  type P2pEvent,
137
227
  type P2pEventByTag,
138
228
  type PathKind,
229
+ type RawConnectionCloseReason,
139
230
  } from "./types.js";
140
231
 
141
232
  /**
package/src/index.ts CHANGED
@@ -19,6 +19,7 @@ export {
19
19
  } from "./errors.js";
20
20
  export { Minip2pBase, Stream, type StreamEventMap } from "./sdk.js";
21
21
  export {
22
+ CloseOutcome,
22
23
  ConfigCapability,
23
24
  DiscoverySource,
24
25
  DriverFailureKind,
@@ -27,11 +28,13 @@ export {
27
28
  NatErrorKind,
28
29
  Reachability,
29
30
  type Bytes,
30
- type CloseReason,
31
+ type ConnectionCloseReason,
31
32
  type ConnectionInfo,
32
33
  type ConnectOptions,
33
34
  type ConnectResult,
34
35
  type ConnectTarget,
36
+ type EndpointCloseReason,
37
+ type EndpointCloseReport,
35
38
  type EventsOptions,
36
39
  type IdentifyInfo,
37
40
  type InboundStreamMeta,
package/src/sdk.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  /* oxlint-disable default-case, func-style, max-classes-per-file, no-await-in-loop, no-empty-function, no-loop-func, 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, sequential async iterators, void event payloads, snapshot fan-out, and bounded queues are deliberate SDK internals. */
2
2
 
3
- import type { BackendConnectTarget, Minip2pBackend } from "./backend.js";
3
+ import type {
4
+ BackendClosed,
5
+ BackendConnectTarget,
6
+ Minip2pBackend,
7
+ } from "./backend.js";
4
8
  import {
5
9
  AbortError,
6
10
  ClosedError,
@@ -16,14 +20,20 @@ import {
16
20
  TimeoutError,
17
21
  WriteBufferFullError,
18
22
  } from "./errors.js";
19
- import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
23
+ import {
24
+ CloseOutcome,
25
+ ConnectionCloseReason_Tags,
26
+ P2pEvent_Tags,
27
+ PathKind_Tags,
28
+ } from "./types.js";
20
29
  import type {
21
30
  Bytes,
22
- CloseReason,
31
+ ConnectionCloseReason,
23
32
  ConnectionInfo,
24
33
  ConnectOptions,
25
34
  ConnectResult,
26
35
  ConnectTarget,
36
+ EndpointCloseReport,
27
37
  EventsOptions,
28
38
  IdentifyInfo,
29
39
  InboundStreamMeta,
@@ -37,6 +47,7 @@ import type {
37
47
  P2pEventTag,
38
48
  Path,
39
49
  PathKind,
50
+ RawConnectionCloseReason,
40
51
  Reachability,
41
52
  RelayReservationInfo,
42
53
  Unsubscribe,
@@ -48,6 +59,11 @@ declare const TextEncoder: new () => {
48
59
  };
49
60
 
50
61
  const DEFAULT_TIMEOUT_MS = 65_000;
62
+ /**
63
+ * Default close drain: the Rust `minip2p::DEFAULT_CLOSE_TIMEOUT` (500 ms)
64
+ * that `Endpoint::close` and native's `DEFAULT_STOP_TIMEOUT_MS` use.
65
+ */
66
+ const DEFAULT_CLOSE_TIMEOUT_MS = 500;
51
67
  const EVENT_QUEUE_CAP = 4096;
52
68
  const EVENT_FLUSH_BATCH = 256;
53
69
  const CONNECT_TERMINAL_CAP = 1024;
@@ -1114,7 +1130,7 @@ export class Minip2pBase {
1114
1130
  readonly #relayAddrs: readonly string[];
1115
1131
  readonly #named = new Map<EventKind, Set<(payload: AnyPayload) => void>>();
1116
1132
  readonly #catchAll = new Set<CatchAllHandler>();
1117
- readonly #closeHandlers = new Set<(reason: CloseReason) => void>();
1133
+ readonly #closeHandlers = new Set<(report: EndpointCloseReport) => void>();
1118
1134
  readonly #waiters = new Set<EventWaiter>();
1119
1135
  readonly #queue = new EventQueue(EVENT_QUEUE_CAP, (item) => {
1120
1136
  this.#releaseQueueItem(item);
@@ -1127,6 +1143,9 @@ export class Minip2pBase {
1127
1143
  #dropped = 0;
1128
1144
  #flushScheduled = false;
1129
1145
  #closed = false;
1146
+ /** Settles once the native drain finished and close observers ran. */
1147
+ #closing: Promise<EndpointCloseReport> | undefined;
1148
+ #closeReported = false;
1130
1149
 
1131
1150
  protected constructor(
1132
1151
  backend: Minip2pBackend,
@@ -1139,7 +1158,7 @@ export class Minip2pBase {
1139
1158
  this.#enqueueNative(event);
1140
1159
  });
1141
1160
  } catch (error) {
1142
- backend.close();
1161
+ void backend.close(0);
1143
1162
  throw error;
1144
1163
  }
1145
1164
  }
@@ -1295,21 +1314,43 @@ export class Minip2pBase {
1295
1314
  });
1296
1315
  }
1297
1316
 
1298
- /** Registers a one-shot endpoint shutdown observer. */
1299
- onClose(handler: (reason: CloseReason) => void): Unsubscribe {
1300
- if (this.#closed) {
1317
+ /**
1318
+ * Registers a one-shot endpoint shutdown observer. It stays registered
1319
+ * through the native close drain and fires once that finishes, with the
1320
+ * same report {@link close} resolves with. A no-op once it has fired.
1321
+ */
1322
+ onClose(handler: (report: EndpointCloseReport) => void): Unsubscribe {
1323
+ if (this.#closeReported) {
1301
1324
  return () => {};
1302
1325
  }
1303
1326
  return subscribe(this.#closeHandlers, handler);
1304
1327
  }
1305
1328
 
1306
- /** Idempotently stops the endpoint and rejects outstanding operations. */
1307
- close(): void {
1308
- this.#teardown({ reason: "close" }, new ClosedError());
1329
+ /**
1330
+ * Stops the endpoint: rejects outstanding operations and drops listeners
1331
+ * at once, then has native disconnect peers and drain for up to
1332
+ * `timeoutMs` (default 500; `0` tears down at once, best effort). Resolves
1333
+ * with the close report once the drain finished, after `onClose`
1334
+ * observers ran; it never rejects. The deadline bounds teardown time only,
1335
+ * not delivery of accepted writes: QUIC discards queued writes and TCP may
1336
+ * abort. Idempotent: a later call returns the same promise, including
1337
+ * after a driver failure closed the endpoint.
1338
+ */
1339
+ close(
1340
+ timeoutMs: number = DEFAULT_CLOSE_TIMEOUT_MS
1341
+ ): Promise<EndpointCloseReport> {
1342
+ assertTimeout(timeoutMs);
1343
+ return this.#teardown(new ClosedError(), timeoutMs);
1309
1344
  }
1310
1345
 
1346
+ /** Starts {@link close} with the default drain, without waiting for it. */
1311
1347
  [Symbol.dispose](): void {
1312
- this.close();
1348
+ void this.close();
1349
+ }
1350
+
1351
+ /** {@link close} with the default drain, for `await using`. */
1352
+ async [Symbol.asyncDispose](): Promise<void> {
1353
+ await this.close();
1313
1354
  }
1314
1355
 
1315
1356
  /** Returns this endpoint's base58 peer ID. */
@@ -1380,17 +1421,27 @@ export class Minip2pBase {
1380
1421
  return this.#backend.reachability();
1381
1422
  }
1382
1423
 
1383
- /** Returns the authoritative active path to `peerId`, if connected. */
1424
+ /**
1425
+ * Returns the path of `peerId`'s established connection; `undefined` only
1426
+ * while the peer is not connected.
1427
+ */
1384
1428
  path(peerId: string): Path | undefined {
1385
1429
  this.#assertOpen();
1386
1430
  const path = this.#backend.path(peerId);
1387
1431
  return path === undefined ? undefined : normalizePath(path);
1388
1432
  }
1389
1433
 
1390
- /** Returns the transport connection selected for `peerId`, if connected. */
1434
+ /**
1435
+ * Returns a snapshot of `peerId`'s established connection: its connection
1436
+ * ID, remote address, path, and Identify protocols once ready;
1437
+ * `undefined` while the peer is not connected.
1438
+ */
1391
1439
  connectionInfo(peerId: string): ConnectionInfo | undefined {
1392
1440
  this.#assertOpen();
1393
- return this.#backend.connectionInfo(peerId);
1441
+ const info = this.#backend.connectionInfo(peerId);
1442
+ return info === undefined
1443
+ ? undefined
1444
+ : { ...info, path: normalizePath(info.path) };
1394
1445
  }
1395
1446
 
1396
1447
  /** Returns whether the native driver is accepting work. */
@@ -1858,13 +1909,17 @@ export class Minip2pBase {
1858
1909
  }
1859
1910
 
1860
1911
  #dispatchNative(event: P2pEvent): void {
1912
+ // Backends resolve `close` with it instead of delivering it.
1913
+ if (event.tag === P2pEvent_Tags.EndpointClosed) {
1914
+ return;
1915
+ }
1861
1916
  if (event.tag === P2pEvent_Tags.DriverFailed) {
1862
1917
  const failure = new DriverFailedError(
1863
1918
  event.inner.kind,
1864
1919
  event.inner.detail
1865
1920
  );
1866
1921
  this.#dispatch("driverFailed", event.inner, event.inner);
1867
- this.#teardown({ error: failure, reason: "driverFailed" }, failure);
1922
+ void this.#teardown(failure, 0);
1868
1923
  return;
1869
1924
  }
1870
1925
 
@@ -2233,47 +2288,72 @@ export class Minip2pBase {
2233
2288
  }
2234
2289
  }
2235
2290
 
2236
- #teardown(reason: CloseReason, error: Error): void {
2237
- if (this.#closed) {
2238
- return;
2291
+ /**
2292
+ * Closes the endpoint once, rejecting what is outstanding with `cause`;
2293
+ * later calls return the first call's promise. A
2294
+ * {@link DriverFailedError} cause reports a `driverFailed` close.
2295
+ */
2296
+ #teardown(
2297
+ cause: ClosedError | DriverFailedError,
2298
+ timeoutMs: number
2299
+ ): Promise<EndpointCloseReport> {
2300
+ if (this.#closing !== undefined) {
2301
+ return this.#closing;
2239
2302
  }
2240
2303
  this.#closed = true;
2241
- const closeHandlers = [...this.#closeHandlers];
2242
- this.#closeHandlers.clear();
2243
2304
  this.#clearQueue();
2244
2305
  this.#dropped = 0;
2245
2306
  this.#named.clear();
2246
2307
  this.#catchAll.clear();
2308
+ // Native is asked to close before anything below can call back in: a
2309
+ // re-entrant close returns this promise.
2310
+ let closed: Promise<BackendClosed>;
2311
+ try {
2312
+ closed = this.#backend.close(timeoutMs);
2313
+ } catch {
2314
+ closed = Promise.resolve({
2315
+ outcome: CloseOutcome.Failed,
2316
+ unfinished: [],
2317
+ });
2318
+ }
2319
+ const closing = closed.then(({ outcome, unfinished }) => {
2320
+ const report: EndpointCloseReport =
2321
+ cause instanceof DriverFailedError
2322
+ ? { error: cause, reason: "driverFailed", unfinished }
2323
+ : { outcome, reason: "close", unfinished };
2324
+ this.#closeReported = true;
2325
+ const closeHandlers = [...this.#closeHandlers];
2326
+ this.#closeHandlers.clear();
2327
+ for (const handler of closeHandlers) {
2328
+ try {
2329
+ handler(report);
2330
+ } catch {
2331
+ // Close notification is outside the now-closed event queue.
2332
+ }
2333
+ }
2334
+ return report;
2335
+ });
2336
+ this.#closing = closing;
2247
2337
  for (const waiter of [...this.#waiters]) {
2248
- this.#settleWaiter(waiter, error);
2338
+ this.#settleWaiter(waiter, cause);
2249
2339
  }
2250
2340
  for (const attempt of this.#connects.values()) {
2251
- attempt.settle?.({ error, ok: false });
2341
+ attempt.settle?.({ error: cause, ok: false });
2252
2342
  }
2253
2343
  this.#connects.clear();
2254
2344
  this.#terminalConnects.clear();
2255
2345
  for (const pending of this.#pendingOpens.takeAll()) {
2256
2346
  clearPendingOpen(pending);
2257
- pending.reject(error);
2347
+ pending.reject(cause);
2258
2348
  }
2259
2349
  for (const stream of this.#streams.takeAll()) {
2260
- stream.terminal(error);
2350
+ stream.terminal(cause);
2261
2351
  }
2262
2352
  for (const ping of this.#pings.values()) {
2263
- ping.cancel(error);
2353
+ ping.cancel(cause);
2264
2354
  }
2265
2355
  this.#pings.clear();
2266
- try {
2267
- this.#backend.close();
2268
- } finally {
2269
- for (const handler of closeHandlers) {
2270
- try {
2271
- handler(reason);
2272
- } catch {
2273
- // Close notification is outside the now-closed event queue.
2274
- }
2275
- }
2276
- }
2356
+ return closing;
2277
2357
  }
2278
2358
 
2279
2359
  #assertOpen(): void {
@@ -2315,6 +2395,7 @@ function toBackendTarget(target: ConnectTarget): BackendConnectTarget {
2315
2395
  type UnnamedEventTag =
2316
2396
  | StreamP2pEvent["tag"]
2317
2397
  | typeof P2pEvent_Tags.DriverFailed
2398
+ | typeof P2pEvent_Tags.EndpointClosed
2318
2399
  | typeof P2pEvent_Tags.StreamReady;
2319
2400
  type NamedEventTag = Exclude<P2pEventTag, UnnamedEventTag>;
2320
2401
 
@@ -2366,6 +2447,7 @@ function normalizeEvent(
2366
2447
  | {
2367
2448
  readonly tag:
2368
2449
  | typeof P2pEvent_Tags.DriverFailed
2450
+ | typeof P2pEvent_Tags.EndpointClosed
2369
2451
  | typeof P2pEvent_Tags.StreamReady;
2370
2452
  }
2371
2453
  >
@@ -2389,17 +2471,44 @@ function normalizeEvent(
2389
2471
  from: normalizePath(event.inner.from),
2390
2472
  to: normalizePath(event.inner.to),
2391
2473
  };
2474
+ } else if (event.tag === P2pEvent_Tags.ConnectionClosed) {
2475
+ payload = {
2476
+ ...event.inner,
2477
+ reason: normalizeCloseReason(event.inner.reason),
2478
+ };
2392
2479
  }
2393
2480
  return { payload: payload as AnyPayload, type };
2394
2481
  }
2395
2482
 
2483
+ function normalizeCloseReason(
2484
+ reason: RawConnectionCloseReason
2485
+ ): ConnectionCloseReason {
2486
+ switch (reason.tag) {
2487
+ case ConnectionCloseReason_Tags.Local: {
2488
+ return { kind: "local" };
2489
+ }
2490
+ case ConnectionCloseReason_Tags.Remote: {
2491
+ return { code: reason.inner.code, kind: "remote" };
2492
+ }
2493
+ case ConnectionCloseReason_Tags.TimedOut: {
2494
+ return { kind: "timedOut" };
2495
+ }
2496
+ case ConnectionCloseReason_Tags.Stalled: {
2497
+ return { kind: "stalled" };
2498
+ }
2499
+ case ConnectionCloseReason_Tags.Error: {
2500
+ return { kind: "error", message: reason.inner.message };
2501
+ }
2502
+ }
2503
+ }
2504
+
2396
2505
  function normalizePath(path: PathKind): Path {
2397
2506
  switch (path.tag) {
2398
- case PathKind_Tags.DirectDialed: {
2399
- return { kind: "directDialed" };
2507
+ case PathKind_Tags.Direct: {
2508
+ return { kind: "direct" };
2400
2509
  }
2401
- case PathKind_Tags.DirectPunched: {
2402
- return { kind: "directPunched" };
2510
+ case PathKind_Tags.Punched: {
2511
+ return { kind: "punched" };
2403
2512
  }
2404
2513
  case PathKind_Tags.Relayed: {
2405
2514
  return { kind: "relayed", relayPeerId: path.inner.relayPeerId };