@statewalker/webrun-streams-conformance 0.4.0 → 0.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.
package/README.md CHANGED
@@ -110,6 +110,7 @@ describeDuplexAdapter("loopback", makeLoopbackPair);
110
110
  | L1 | `concurrency` concurrent calls each get back their own body. |
111
111
  | L2 | Half-close: after the caller's input ends, the handler keeps yielding (three chunks, 30 ms apart) and the caller receives all of them. |
112
112
  | L3 | Mid-stream cancellation: the caller breaks out after 3 chunks of an endless response, and within 50 ms the handler's `finally` has run. |
113
+ | L3 (input) | Cancellation and request errors while the handler reads its input: an echo handler reading an endless upload sees the caller break out after 3 chunks (its `finally` runs within 3 s), and an echo handler whose caller's input throws `upload failed` sees its own read throw that error, not a clean end, while the caller's `for await` rejects. |
113
114
  | L4 | Error propagation: a handler that throws an `Error` with `status: 418` and `code: "TEAPOT"` makes the caller's `for await` reject with the same `message`, `status` and `code`, and a non-empty `stack`. |
114
115
  | L5 | Teardown: calling the `serve` teardown twice resolves; `pair.close()` after a completed call resolves. |
115
116
  | L6 | Flow control (spec D17): a 256 KiB body crosses as 4 KiB messages to a consumer that waits 1 ms per chunk, intact; and in each direction, a producer of 4 KiB chunks facing a consumer that stops after one chunk stalls within the pair's `runAheadBytes`, then finishes, every byte intact, once the consumer resumes. |
@@ -1 +1 @@
1
- {"version":3,"file":"describe-duplex-adapter.d.ts","sourceRoot":"","sources":["../src/describe-duplex-adapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAG9C,MAAM,WAAW,4BAA4B;IAC3C,qDAAqD;IACrD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6EAA6E;IAC7E,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,QAAQ,EAClB,IAAI,GAAE,4BAAiC,GACtC,IAAI,CAkON"}
1
+ {"version":3,"file":"describe-duplex-adapter.d.ts","sourceRoot":"","sources":["../src/describe-duplex-adapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAG9C,MAAM,WAAW,4BAA4B;IAC3C,qDAAqD;IACrD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6EAA6E;IAC7E,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,QAAQ,EAClB,IAAI,GAAE,4BAAiC,GACtC,IAAI,CAqTN"}
@@ -0,0 +1,35 @@
1
+ import type { MessagePipe } from "@statewalker/webrun-streams";
2
+ /**
3
+ * One adapter's pipe over a fake (or real) transport, with handles to drive
4
+ * the transport from the outside.
5
+ */
6
+ export interface MessagePipeHarness {
7
+ /** What the adapter returned: `{ target, signal, maxMessageSize }`. */
8
+ pipe: MessagePipe;
9
+ /** The transport delivers one inbound message, as the adapter's transport would. */
10
+ inject(data: unknown): void | Promise<void>;
11
+ /** What the adapter has put on the transport so far, one entry per message. */
12
+ sent(): Uint8Array[] | Promise<Uint8Array[]>;
13
+ /** The transport ends on its own (the peer went away). */
14
+ endRemotely(): void | Promise<void>;
15
+ /** Makes the transport report `bytes` buffered. Absent: the drain cases are skipped. */
16
+ setBuffered?(bytes: number): void;
17
+ /** Lets the adapter see buffered bytes go down, where it needs an event for it. */
18
+ settle?(): void | Promise<void>;
19
+ /** Releases anything the harness holds. */
20
+ dispose?(): void | Promise<void>;
21
+ }
22
+ export interface DescribeMessagePipeOptions {
23
+ /** Build a pipe with this frame ceiling. Absent: the ceiling cases are skipped. */
24
+ withMaxFrameBytes?: (maxFrameBytes: number) => MessagePipeHarness | Promise<MessagePipeHarness>;
25
+ /** The adapter's drain low-water mark. Default 256 KiB. */
26
+ drainLowWater?: number;
27
+ }
28
+ /**
29
+ * The contract every pipe of byte messages keeps (statewalker/webrun-wire#151),
30
+ * run against an adapter through its harness. The pipe module
31
+ * (`newMessagePipe` in `@statewalker/webrun-streams`) implements it once; each
32
+ * `webrun-streams-*` adapter runs this suite to show it still does.
33
+ */
34
+ export declare function describeMessagePipe(name: string, make: () => MessagePipeHarness | Promise<MessagePipeHarness>, options?: DescribeMessagePipeOptions): void;
35
+ //# sourceMappingURL=describe-message-pipe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"describe-message-pipe.d.ts","sourceRoot":"","sources":["../src/describe-message-pipe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAG/D;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,uEAAuE;IACvE,IAAI,EAAE,WAAW,CAAC;IAClB,oFAAoF;IACpF,MAAM,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5C,+EAA+E;IAC/E,IAAI,IAAI,UAAU,EAAE,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;IAC7C,0DAA0D;IAC1D,WAAW,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACpC,wFAAwF;IACxF,WAAW,CAAC,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,mFAAmF;IACnF,MAAM,CAAC,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,2CAA2C;IAC3C,OAAO,CAAC,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAClC;AAED,MAAM,WAAW,0BAA0B;IACzC,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAChG,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAID;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,EAC5D,OAAO,GAAE,0BAA+B,GACvC,IAAI,CAyIN"}
@@ -0,0 +1,19 @@
1
+ import type { NativePort, NativePortMux, ValueCodec } from "@statewalker/webrun-streams";
2
+ /** Two ends of one connection, from an adapter that opens a channel per port. */
3
+ export interface PortMuxHarness {
4
+ /** A mux that opens ports and accepts none. */
5
+ opener: NativePortMux;
6
+ /** A mux on the other end, handing each port the opener opens to `onPort`. */
7
+ serve(onPort: (port: NativePort) => boolean | undefined): Promise<NativePortMux>;
8
+ /** Releases the connection. */
9
+ dispose(): void | Promise<void>;
10
+ }
11
+ /** Builds two connected ends whose muxes use `codec`. */
12
+ export type MakePortMuxHarness = (codec: ValueCodec) => Promise<PortMuxHarness>;
13
+ /**
14
+ * The lifecycle every native port mux keeps (statewalker/webrun-wire#152): the
15
+ * module (`newNativePortMux` in `@statewalker/webrun-streams`) implements it
16
+ * once, and each transport (an in-memory one, WebRTC, libp2p) runs this suite.
17
+ */
18
+ export declare function describePortMux(name: string, make: MakePortMuxHarness): void;
19
+ //# sourceMappingURL=describe-port-mux.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"describe-port-mux.d.ts","sourceRoot":"","sources":["../src/describe-port-mux.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAGzF,iFAAiF;AACjF,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,MAAM,EAAE,aAAa,CAAC;IACtB,8EAA8E;IAC9E,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,OAAO,GAAG,SAAS,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IACjF,+BAA+B;IAC/B,OAAO,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACjC;AAED,yDAAyD;AACzD,MAAM,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;AAiChF;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,kBAAkB,GAAG,IAAI,CAkJ5E"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { type DescribeDuplexAdapterOptions, describeDuplexAdapter, } from "./describe-duplex-adapter.js";
2
+ export { type DescribeMessagePipeOptions, describeMessagePipe, type MessagePipeHarness, } from "./describe-message-pipe.js";
3
+ export { describePortMux, type MakePortMuxHarness, type PortMuxHarness, } from "./describe-port-mux.js";
2
4
  export { type ConnectServePair, type MakePair, makeLoopbackPair, type PairTuning, } from "./loopback.js";
3
5
  export { measureRunAhead, type RunAheadMeasurement } from "./run-ahead.js";
4
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,4BAA4B,EACjC,qBAAqB,GACtB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,QAAQ,EACb,gBAAgB,EAChB,KAAK,UAAU,GAChB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,eAAe,EAAE,KAAK,mBAAmB,EAAE,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,4BAA4B,EACjC,qBAAqB,GACtB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,KAAK,0BAA0B,EAC/B,mBAAmB,EACnB,KAAK,kBAAkB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,KAAK,kBAAkB,EACvB,KAAK,cAAc,GACpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,QAAQ,EACb,gBAAgB,EAChB,KAAK,UAAU,GAChB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,eAAe,EAAE,KAAK,mBAAmB,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -256,6 +256,81 @@ function describeDuplexAdapter(name, makePair, opts = {}) {
256
256
  }
257
257
  });
258
258
  });
259
+ describe("L3: cancellation and request errors while the handler reads its input", () => {
260
+ it("a handler reading its input sees the caller's .return(): its input ends and its finally runs", async () => {
261
+ const pair = await makePair();
262
+ let stopUpload = false;
263
+ try {
264
+ let handlerCleanupRan = false;
265
+ await pair.serve(async function* readingEcho(input) {
266
+ try {
267
+ for await (const chunk of input) yield chunk;
268
+ } finally {
269
+ handlerCleanupRan = true;
270
+ }
271
+ });
272
+ const { call, close } = await pair.connect();
273
+ try {
274
+ const out = call((async function* endlessUpload() {
275
+ while (!stopUpload) {
276
+ yield new TextEncoder().encode("tick");
277
+ await delay(10);
278
+ }
279
+ })());
280
+ let count = 0;
281
+ for await (const _ of out) {
282
+ count++;
283
+ if (count >= 3) break;
284
+ }
285
+ expect(count).toBe(3);
286
+ expect(await waitFor(() => handlerCleanupRan, 3e3)).toBe(true);
287
+ } finally {
288
+ stopUpload = true;
289
+ await close();
290
+ }
291
+ } finally {
292
+ stopUpload = true;
293
+ await pair.close();
294
+ }
295
+ }, 1e4);
296
+ it("a handler reading its input sees the caller's input error, not a clean end", async () => {
297
+ const pair = await makePair();
298
+ try {
299
+ let handlerSaw = "nothing";
300
+ let handlerCleanupRan = false;
301
+ await pair.serve(async function* readingEcho(input) {
302
+ try {
303
+ for await (const chunk of input) yield chunk;
304
+ handlerSaw = "end";
305
+ } catch (err) {
306
+ handlerSaw = err instanceof Error ? err : new Error(String(err));
307
+ throw err;
308
+ } finally {
309
+ handlerCleanupRan = true;
310
+ }
311
+ });
312
+ const { call, close } = await pair.connect();
313
+ try {
314
+ const out = call((async function* failingUpload() {
315
+ yield new TextEncoder().encode("first");
316
+ yield new TextEncoder().encode("second");
317
+ await delay(20);
318
+ throw new Error("upload failed");
319
+ })());
320
+ await expect(async () => {
321
+ for await (const _ of out);
322
+ }).rejects.toBeInstanceOf(Error);
323
+ expect(await waitFor(() => handlerCleanupRan, 3e3)).toBe(true);
324
+ expect(handlerSaw).toBeInstanceOf(Error);
325
+ expect(handlerSaw.message).toContain("upload failed");
326
+ } finally {
327
+ await close();
328
+ }
329
+ } finally {
330
+ await pair.close();
331
+ }
332
+ }, 1e4);
333
+ });
259
334
  describe("L4: error propagation", () => {
260
335
  it("preserves message, custom fields, and stack across the wire", async () => {
261
336
  const pair = await makePair();
@@ -355,6 +430,12 @@ function bytesEqual(a, b) {
355
430
  for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
356
431
  return true;
357
432
  }
433
+ /** polls `cond` until it holds or `ms` elapse; resolves its last value */
434
+ async function waitFor(cond, ms) {
435
+ const until = Date.now() + ms;
436
+ while (!cond() && Date.now() < until) await delay(10);
437
+ return cond();
438
+ }
358
439
  function delay(ms) {
359
440
  return new Promise((r) => setTimeout(r, ms));
360
441
  }
@@ -368,6 +449,304 @@ function concat(chunks) {
368
449
  return out;
369
450
  }
370
451
  //#endregion
452
+ //#region src/describe-message-pipe.ts
453
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
454
+ /**
455
+ * The contract every pipe of byte messages keeps (statewalker/webrun-wire#151),
456
+ * run against an adapter through its harness. The pipe module
457
+ * (`newMessagePipe` in `@statewalker/webrun-streams`) implements it once; each
458
+ * `webrun-streams-*` adapter runs this suite to show it still does.
459
+ */
460
+ function describeMessagePipe(name, make, options = {}) {
461
+ const lowWater = options.drainLowWater ?? 262144;
462
+ async function withHarness(build, body) {
463
+ const h = await build();
464
+ try {
465
+ await body(h);
466
+ } finally {
467
+ await h.dispose?.();
468
+ }
469
+ }
470
+ describe(`${name}: the message pipe contract`, () => {
471
+ it("carries its own life and ceiling: target.closeSignal is the signal, target.maxMessageSize the ceiling", () => withHarness(make, async ({ pipe }) => {
472
+ expect(pipe.target.closeSignal).toBe(pipe.signal);
473
+ expect(pipe.target.maxMessageSize).toBe(pipe.maxMessageSize);
474
+ }));
475
+ it("delivers inbound bytes to every listener as Uint8Array, in order, past a faulty listener", () => withHarness(make, async (h) => {
476
+ const got = [];
477
+ const other = [];
478
+ h.pipe.target.addEventListener("message", () => {
479
+ throw new Error("a faulty listener");
480
+ });
481
+ h.pipe.target.addEventListener("message", async () => {
482
+ throw new Error("a rejecting listener");
483
+ });
484
+ h.pipe.target.addEventListener("message", (e) => {
485
+ expect(e.data).toBeInstanceOf(Uint8Array);
486
+ got.push([...e.data]);
487
+ });
488
+ const removed = (e) => {
489
+ other.push([...e.data]);
490
+ };
491
+ h.pipe.target.addEventListener("message", removed);
492
+ h.pipe.target.removeEventListener("message", removed);
493
+ await h.inject(new Uint8Array([1, 2]));
494
+ await h.inject(new Uint8Array([3]).buffer);
495
+ await h.inject(new Uint8Array([
496
+ 9,
497
+ 4,
498
+ 9
499
+ ]).subarray(1, 2));
500
+ await flush();
501
+ expect(got).toEqual([
502
+ [1, 2],
503
+ [3],
504
+ [4]
505
+ ]);
506
+ expect(other).toEqual([]);
507
+ expect(h.pipe.signal.aborted).toBe(false);
508
+ }));
509
+ it("sends bytes one message each, and refuses anything else with TypeError", () => withHarness(make, async (h) => {
510
+ h.pipe.target.postMessage(new Uint8Array([
511
+ 1,
512
+ 2,
513
+ 3
514
+ ]));
515
+ h.pipe.target.postMessage(new Uint8Array([4, 5]).buffer);
516
+ expect(() => h.pipe.target.postMessage("text")).toThrow(TypeError);
517
+ expect(() => h.pipe.target.postMessage({ a: 1 })).toThrow(TypeError);
518
+ await flush();
519
+ expect((await h.sent()).map((b) => [...b])).toEqual([[
520
+ 1,
521
+ 2,
522
+ 3
523
+ ], [4, 5]]);
524
+ }));
525
+ it("ends when the transport ends: the signal aborts with an Error, and a post is a no-op", () => withHarness(make, async (h) => {
526
+ await h.endRemotely();
527
+ await flush();
528
+ expect(h.pipe.signal.aborted).toBe(true);
529
+ expect(h.pipe.signal.reason).toBeInstanceOf(Error);
530
+ const before = (await h.sent()).length;
531
+ h.pipe.target.postMessage(new Uint8Array([1]));
532
+ await flush();
533
+ expect((await h.sent()).length).toBe(before);
534
+ }));
535
+ it("close() ends the pipe: the signal aborts, and nothing more is delivered", () => withHarness(make, async (h) => {
536
+ const got = [];
537
+ h.pipe.target.addEventListener("message", (e) => {
538
+ got.push(e.data);
539
+ });
540
+ await h.pipe.target.close();
541
+ expect(h.pipe.signal.aborted).toBe(true);
542
+ await h.inject(new Uint8Array([1]));
543
+ await flush();
544
+ expect(got).toEqual([]);
545
+ await h.pipe.target.close();
546
+ }));
547
+ if (options.withMaxFrameBytes) {
548
+ const build = () => options.withMaxFrameBytes?.(100);
549
+ it("a message of exactly maxFrameBytes is sent; one byte past it ends the pipe with RangeError", () => withHarness(build, async (h) => {
550
+ h.pipe.target.postMessage(/* @__PURE__ */ new Uint8Array(100));
551
+ expect(h.pipe.signal.aborted).toBe(false);
552
+ expect(() => h.pipe.target.postMessage(/* @__PURE__ */ new Uint8Array(101))).toThrow(RangeError);
553
+ expect(h.pipe.signal.aborted).toBe(true);
554
+ expect(h.pipe.signal.reason).toBeInstanceOf(RangeError);
555
+ await flush();
556
+ expect((await h.sent()).map((b) => b.byteLength)).toEqual([100]);
557
+ }));
558
+ }
559
+ it("whenDrained resolves at once on an idle pipe, and once the pipe ended", () => withHarness(make, async (h) => {
560
+ await h.pipe.target.whenDrained();
561
+ await h.endRemotely();
562
+ await h.pipe.target.whenDrained();
563
+ }));
564
+ it("a pending whenDrained resolves when the buffer drains to the low-water mark", () => withHarness(make, async (h) => {
565
+ if (!h.setBuffered) return;
566
+ h.setBuffered(lowWater + 1);
567
+ expect(h.pipe.target.bufferedAmount).toBe(lowWater + 1);
568
+ let drained = false;
569
+ const wait = h.pipe.target.whenDrained().then(() => {
570
+ drained = true;
571
+ });
572
+ await new Promise((resolve) => setTimeout(resolve, 20));
573
+ expect(drained).toBe(false);
574
+ h.setBuffered(lowWater);
575
+ await h.settle?.();
576
+ await wait;
577
+ expect(drained).toBe(true);
578
+ }));
579
+ it("a pending whenDrained resolves when the pipe ends", () => withHarness(make, async (h) => {
580
+ if (!h.setBuffered) return;
581
+ h.setBuffered(lowWater + 1);
582
+ const wait = h.pipe.target.whenDrained();
583
+ await h.endRemotely();
584
+ await wait;
585
+ }));
586
+ });
587
+ }
588
+ //#endregion
589
+ //#region src/describe-port-mux.ts
590
+ /** A value whose encoding the contract's codec refuses to decode. */
591
+ const POISON = "\0poison";
592
+ /** JSON, except that {@link POISON} encodes to a frame `decode` rejects. */
593
+ const contractCodec = {
594
+ encode: (value) => value === POISON ? new Uint8Array([255]) : new TextEncoder().encode(JSON.stringify(value)),
595
+ decode: (bytes) => {
596
+ if (bytes.byteLength === 1 && bytes[0] === 255) throw new Error("undecodable");
597
+ return JSON.parse(new TextDecoder().decode(bytes));
598
+ }
599
+ };
600
+ const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
601
+ async function until(predicate, label, ms = 5e3) {
602
+ const deadline = Date.now() + ms;
603
+ while (!predicate()) {
604
+ if (Date.now() > deadline) throw new Error(`timed out waiting for: ${label}`);
605
+ await tick(5);
606
+ }
607
+ }
608
+ function received(port) {
609
+ const got = [];
610
+ port.addEventListener("message", (e) => {
611
+ got.push(e.data);
612
+ });
613
+ return got;
614
+ }
615
+ /**
616
+ * The lifecycle every native port mux keeps (statewalker/webrun-wire#152): the
617
+ * module (`newNativePortMux` in `@statewalker/webrun-streams`) implements it
618
+ * once, and each transport (an in-memory one, WebRTC, libp2p) runs this suite.
619
+ */
620
+ function describePortMux(name, make) {
621
+ async function withPair(body, accept = () => true) {
622
+ const h = await make(contractCodec);
623
+ const inbound = [];
624
+ try {
625
+ await body(h, inbound, await h.serve((port) => {
626
+ inbound.push(port);
627
+ return accept(port);
628
+ }));
629
+ } finally {
630
+ await h.opener.close().catch(() => void 0);
631
+ await h.dispose();
632
+ }
633
+ }
634
+ describe(`${name}: the native port mux contract`, () => {
635
+ it("a port opened on one end arrives on the other; values cross both ways, encoded", () => withPair(async (h, inbound) => {
636
+ const port = await h.opener.openPort();
637
+ const fromServer = received(port);
638
+ port.postMessage({
639
+ n: 1,
640
+ s: "a"
641
+ });
642
+ await until(() => inbound.length === 1, "the inbound port");
643
+ const server = inbound[0];
644
+ const fromClient = received(server);
645
+ await until(() => fromClient.length === 1, "the first message");
646
+ server.postMessage([2, "b"]);
647
+ await until(() => fromServer.length === 1, "the answer");
648
+ expect(fromClient).toEqual([{
649
+ n: 1,
650
+ s: "a"
651
+ }]);
652
+ expect(fromServer).toEqual([[2, "b"]]);
653
+ }));
654
+ it("messages that arrive before a port's first listener are held, for every listener added in that tick", () => withPair(async (h, inbound) => {
655
+ const port = await h.opener.openPort();
656
+ port.postMessage(1);
657
+ port.postMessage(2);
658
+ port.postMessage(3);
659
+ await until(() => inbound.length === 1, "the inbound port");
660
+ await tick(50);
661
+ const server = inbound[0];
662
+ const first = received(server);
663
+ const second = received(server);
664
+ await until(() => first.length === 3 && second.length === 3, "the held messages");
665
+ expect(first).toEqual([
666
+ 1,
667
+ 2,
668
+ 3
669
+ ]);
670
+ expect(second).toEqual([
671
+ 1,
672
+ 2,
673
+ 3
674
+ ]);
675
+ }));
676
+ it("removeEventListener stops delivery to that listener", () => withPair(async (h, inbound) => {
677
+ const port = await h.opener.openPort();
678
+ port.postMessage("one");
679
+ await until(() => inbound.length === 1, "the inbound port");
680
+ const server = inbound[0];
681
+ const kept = [];
682
+ const dropped = [];
683
+ const drop = (e) => {
684
+ dropped.push(e.data);
685
+ };
686
+ server.addEventListener("message", (e) => {
687
+ kept.push(e.data);
688
+ });
689
+ server.addEventListener("message", drop);
690
+ await until(() => kept.length === 1, "the first message");
691
+ server.removeEventListener("message", drop);
692
+ port.postMessage("two");
693
+ await until(() => kept.length === 2, "the second message");
694
+ expect(dropped).toEqual(["one"]);
695
+ }));
696
+ it("a port the serving end refuses fails: the opener's close signal aborts", () => withPair(async (h) => {
697
+ const port = await h.opener.openPort();
698
+ port.postMessage("hello");
699
+ await until(() => port.closeSignal.aborted, "the refusal");
700
+ }, () => false));
701
+ it("an onPort that throws refuses the port", () => withPair(async (h) => {
702
+ const port = await h.opener.openPort();
703
+ port.postMessage("hello");
704
+ await until(() => port.closeSignal.aborted, "the refusal");
705
+ }, () => {
706
+ throw new Error("onPort failed");
707
+ }));
708
+ it("a frame the codec cannot decode fails the receiving port", () => withPair(async (h, inbound) => {
709
+ const port = await h.opener.openPort();
710
+ port.postMessage("fine");
711
+ await until(() => inbound.length === 1, "the inbound port");
712
+ const server = inbound[0];
713
+ received(server);
714
+ port.postMessage(POISON);
715
+ await until(() => server.closeSignal.aborted, "the receiving port failed");
716
+ expect(String(server.closeSignal.reason?.message)).toMatch(/decode/);
717
+ }));
718
+ it("closing a port ends it on both ends", () => withPair(async (h, inbound) => {
719
+ const port = await h.opener.openPort();
720
+ port.postMessage("hello");
721
+ await until(() => inbound.length === 1, "the inbound port");
722
+ await port.close();
723
+ expect(port.closeSignal.aborted).toBe(true);
724
+ await until(() => inbound[0].closeSignal.aborted, "the peer's port closed");
725
+ }));
726
+ it("close() closes the ports the mux opened, and openPort rejects afterwards", () => withPair(async (h) => {
727
+ const a = await h.opener.openPort();
728
+ const b = await h.opener.openPort();
729
+ await h.opener.close();
730
+ expect(a.closeSignal.aborted).toBe(true);
731
+ expect(b.closeSignal.aborted).toBe(true);
732
+ await expect(h.opener.openPort()).rejects.toThrow(/closed/);
733
+ }));
734
+ it("openPort honours its signal: aborted already, or aborted later, which closes the port", () => withPair(async (h) => {
735
+ const aborted = new AbortController();
736
+ aborted.abort(/* @__PURE__ */ new Error("not wanted"));
737
+ await expect(h.opener.openPort(void 0, { signal: aborted.signal })).rejects.toThrow(/not wanted/);
738
+ const later = new AbortController();
739
+ const port = await h.opener.openPort(void 0, { signal: later.signal });
740
+ expect(port.closeSignal.aborted).toBe(false);
741
+ later.abort(/* @__PURE__ */ new Error("done with it"));
742
+ await until(() => port.closeSignal.aborted, "the port closed");
743
+ }));
744
+ it("reports its maxMessageSize as a positive number", () => withPair(async (h) => {
745
+ expect(h.opener.maxMessageSize).toBeGreaterThan(0);
746
+ }));
747
+ });
748
+ }
749
+ //#endregion
371
750
  //#region src/loopback.ts
372
751
  /**
373
752
  * Loopback pair: `call` invokes the registered `handler` directly, no
@@ -408,4 +787,4 @@ const makeLoopbackPair = async () => {
408
787
  };
409
788
  };
410
789
  //#endregion
411
- export { describeDuplexAdapter, makeLoopbackPair, measureRunAhead };
790
+ export { describeDuplexAdapter, describeMessagePipe, describePortMux, makeLoopbackPair, measureRunAhead };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-conformance",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Conformance test suite for Duplex/Connect/Serve adapters in the webrun-streams-* family",
@@ -31,7 +31,7 @@
31
31
  ],
32
32
  "dependencies": {
33
33
  "vitest": "^5.0.5",
34
- "@statewalker/webrun-streams": "^0.3.0"
34
+ "@statewalker/webrun-streams": "^0.5.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@biomejs/biome": "^2.5.15",
@@ -48,6 +48,8 @@
48
48
  "scripts": {
49
49
  "build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
50
50
  "test": "vitest run",
51
+ "typecheck": "tsc --noEmit",
52
+ "typecheck:tests": "tsc -p tsconfig.tests.json",
51
53
  "lint": "biome check src tests"
52
54
  }
53
55
  }
@@ -150,6 +150,89 @@ export function describeDuplexAdapter(
150
150
  });
151
151
  });
152
152
 
153
+ describe("L3: cancellation and request errors while the handler reads its input", () => {
154
+ it("a handler reading its input sees the caller's .return(): its input ends and its finally runs", async () => {
155
+ const pair = await makePair();
156
+ let stopUpload = false;
157
+ try {
158
+ let handlerCleanupRan = false;
159
+ await pair.serve(async function* readingEcho(input) {
160
+ try {
161
+ for await (const chunk of input) yield chunk;
162
+ } finally {
163
+ handlerCleanupRan = true;
164
+ }
165
+ });
166
+ const { call, close } = await pair.connect();
167
+ try {
168
+ const out = call(
169
+ (async function* endlessUpload() {
170
+ while (!stopUpload) {
171
+ yield new TextEncoder().encode("tick");
172
+ await delay(10);
173
+ }
174
+ })(),
175
+ );
176
+ let count = 0;
177
+ for await (const _ of out) {
178
+ count++;
179
+ if (count >= 3) break;
180
+ }
181
+ expect(count).toBe(3);
182
+ expect(await waitFor(() => handlerCleanupRan, 3000)).toBe(true);
183
+ } finally {
184
+ stopUpload = true;
185
+ await close();
186
+ }
187
+ } finally {
188
+ stopUpload = true;
189
+ await pair.close();
190
+ }
191
+ }, 10_000);
192
+
193
+ it("a handler reading its input sees the caller's input error, not a clean end", async () => {
194
+ const pair = await makePair();
195
+ try {
196
+ let handlerSaw: unknown = "nothing";
197
+ let handlerCleanupRan = false;
198
+ await pair.serve(async function* readingEcho(input) {
199
+ try {
200
+ for await (const chunk of input) yield chunk;
201
+ handlerSaw = "end";
202
+ } catch (err) {
203
+ handlerSaw = err instanceof Error ? err : new Error(String(err));
204
+ throw err;
205
+ } finally {
206
+ handlerCleanupRan = true;
207
+ }
208
+ });
209
+ const { call, close } = await pair.connect();
210
+ try {
211
+ const out = call(
212
+ (async function* failingUpload() {
213
+ yield new TextEncoder().encode("first");
214
+ yield new TextEncoder().encode("second");
215
+ await delay(20);
216
+ throw new Error("upload failed");
217
+ })(),
218
+ );
219
+ await expect(async () => {
220
+ for await (const _ of out) {
221
+ /* drain */
222
+ }
223
+ }).rejects.toBeInstanceOf(Error);
224
+ expect(await waitFor(() => handlerCleanupRan, 3000)).toBe(true);
225
+ expect(handlerSaw).toBeInstanceOf(Error);
226
+ expect((handlerSaw as Error).message).toContain("upload failed");
227
+ } finally {
228
+ await close();
229
+ }
230
+ } finally {
231
+ await pair.close();
232
+ }
233
+ }, 10_000);
234
+ });
235
+
153
236
  describe("L4: error propagation", () => {
154
237
  it("preserves message, custom fields, and stack across the wire", async () => {
155
238
  const pair = await makePair();
@@ -268,6 +351,13 @@ function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
268
351
  return true;
269
352
  }
270
353
 
354
+ /** polls `cond` until it holds or `ms` elapse; resolves its last value */
355
+ async function waitFor(cond: () => boolean, ms: number): Promise<boolean> {
356
+ const until = Date.now() + ms;
357
+ while (!cond() && Date.now() < until) await delay(10);
358
+ return cond();
359
+ }
360
+
271
361
  function delay(ms: number): Promise<void> {
272
362
  return new Promise((r) => setTimeout(r, ms));
273
363
  }
@@ -0,0 +1,181 @@
1
+ import type { MessagePipe } from "@statewalker/webrun-streams";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ /**
5
+ * One adapter's pipe over a fake (or real) transport, with handles to drive
6
+ * the transport from the outside.
7
+ */
8
+ export interface MessagePipeHarness {
9
+ /** What the adapter returned: `{ target, signal, maxMessageSize }`. */
10
+ pipe: MessagePipe;
11
+ /** The transport delivers one inbound message, as the adapter's transport would. */
12
+ inject(data: unknown): void | Promise<void>;
13
+ /** What the adapter has put on the transport so far, one entry per message. */
14
+ sent(): Uint8Array[] | Promise<Uint8Array[]>;
15
+ /** The transport ends on its own (the peer went away). */
16
+ endRemotely(): void | Promise<void>;
17
+ /** Makes the transport report `bytes` buffered. Absent: the drain cases are skipped. */
18
+ setBuffered?(bytes: number): void;
19
+ /** Lets the adapter see buffered bytes go down, where it needs an event for it. */
20
+ settle?(): void | Promise<void>;
21
+ /** Releases anything the harness holds. */
22
+ dispose?(): void | Promise<void>;
23
+ }
24
+
25
+ export interface DescribeMessagePipeOptions {
26
+ /** Build a pipe with this frame ceiling. Absent: the ceiling cases are skipped. */
27
+ withMaxFrameBytes?: (maxFrameBytes: number) => MessagePipeHarness | Promise<MessagePipeHarness>;
28
+ /** The adapter's drain low-water mark. Default 256 KiB. */
29
+ drainLowWater?: number;
30
+ }
31
+
32
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
33
+
34
+ /**
35
+ * The contract every pipe of byte messages keeps (statewalker/webrun-wire#151),
36
+ * run against an adapter through its harness. The pipe module
37
+ * (`newMessagePipe` in `@statewalker/webrun-streams`) implements it once; each
38
+ * `webrun-streams-*` adapter runs this suite to show it still does.
39
+ */
40
+ export function describeMessagePipe(
41
+ name: string,
42
+ make: () => MessagePipeHarness | Promise<MessagePipeHarness>,
43
+ options: DescribeMessagePipeOptions = {},
44
+ ): void {
45
+ const lowWater = options.drainLowWater ?? 256 * 1024;
46
+
47
+ async function withHarness(
48
+ build: () => MessagePipeHarness | Promise<MessagePipeHarness>,
49
+ body: (h: MessagePipeHarness) => Promise<void>,
50
+ ): Promise<void> {
51
+ const h = await build();
52
+ try {
53
+ await body(h);
54
+ } finally {
55
+ await h.dispose?.();
56
+ }
57
+ }
58
+
59
+ describe(`${name}: the message pipe contract`, () => {
60
+ it("carries its own life and ceiling: target.closeSignal is the signal, target.maxMessageSize the ceiling", () =>
61
+ withHarness(make, async ({ pipe }) => {
62
+ expect(pipe.target.closeSignal).toBe(pipe.signal);
63
+ expect(pipe.target.maxMessageSize).toBe(pipe.maxMessageSize);
64
+ }));
65
+
66
+ it("delivers inbound bytes to every listener as Uint8Array, in order, past a faulty listener", () =>
67
+ withHarness(make, async (h) => {
68
+ const got: number[][] = [];
69
+ const other: number[][] = [];
70
+ h.pipe.target.addEventListener("message", () => {
71
+ throw new Error("a faulty listener");
72
+ });
73
+ h.pipe.target.addEventListener("message", async () => {
74
+ throw new Error("a rejecting listener");
75
+ });
76
+ h.pipe.target.addEventListener("message", (e) => {
77
+ expect(e.data).toBeInstanceOf(Uint8Array);
78
+ got.push([...(e.data as Uint8Array)]);
79
+ });
80
+ const removed = (e: MessageEvent) => {
81
+ other.push([...(e.data as Uint8Array)]);
82
+ };
83
+ h.pipe.target.addEventListener("message", removed);
84
+ h.pipe.target.removeEventListener("message", removed);
85
+ await h.inject(new Uint8Array([1, 2]));
86
+ await h.inject(new Uint8Array([3]).buffer);
87
+ await h.inject(new Uint8Array([9, 4, 9]).subarray(1, 2));
88
+ await flush();
89
+ expect(got).toEqual([[1, 2], [3], [4]]);
90
+ expect(other).toEqual([]);
91
+ expect(h.pipe.signal.aborted).toBe(false);
92
+ }));
93
+
94
+ it("sends bytes one message each, and refuses anything else with TypeError", () =>
95
+ withHarness(make, async (h) => {
96
+ h.pipe.target.postMessage(new Uint8Array([1, 2, 3]));
97
+ h.pipe.target.postMessage(new Uint8Array([4, 5]).buffer);
98
+ expect(() => h.pipe.target.postMessage("text")).toThrow(TypeError);
99
+ expect(() => h.pipe.target.postMessage({ a: 1 })).toThrow(TypeError);
100
+ await flush();
101
+ expect((await h.sent()).map((b) => [...b])).toEqual([
102
+ [1, 2, 3],
103
+ [4, 5],
104
+ ]);
105
+ }));
106
+
107
+ it("ends when the transport ends: the signal aborts with an Error, and a post is a no-op", () =>
108
+ withHarness(make, async (h) => {
109
+ await h.endRemotely();
110
+ await flush();
111
+ expect(h.pipe.signal.aborted).toBe(true);
112
+ expect(h.pipe.signal.reason).toBeInstanceOf(Error);
113
+ const before = (await h.sent()).length;
114
+ h.pipe.target.postMessage(new Uint8Array([1]));
115
+ await flush();
116
+ expect((await h.sent()).length).toBe(before);
117
+ }));
118
+
119
+ it("close() ends the pipe: the signal aborts, and nothing more is delivered", () =>
120
+ withHarness(make, async (h) => {
121
+ const got: unknown[] = [];
122
+ h.pipe.target.addEventListener("message", (e) => {
123
+ got.push(e.data);
124
+ });
125
+ await h.pipe.target.close();
126
+ expect(h.pipe.signal.aborted).toBe(true);
127
+ await h.inject(new Uint8Array([1]));
128
+ await flush();
129
+ expect(got).toEqual([]);
130
+ // A second close is harmless.
131
+ await h.pipe.target.close();
132
+ }));
133
+
134
+ if (options.withMaxFrameBytes) {
135
+ const build = () => options.withMaxFrameBytes?.(100) as Promise<MessagePipeHarness>;
136
+ it("a message of exactly maxFrameBytes is sent; one byte past it ends the pipe with RangeError", () =>
137
+ withHarness(build, async (h) => {
138
+ h.pipe.target.postMessage(new Uint8Array(100));
139
+ expect(h.pipe.signal.aborted).toBe(false);
140
+ expect(() => h.pipe.target.postMessage(new Uint8Array(101))).toThrow(RangeError);
141
+ expect(h.pipe.signal.aborted).toBe(true);
142
+ expect(h.pipe.signal.reason).toBeInstanceOf(RangeError);
143
+ await flush();
144
+ expect((await h.sent()).map((b) => b.byteLength)).toEqual([100]);
145
+ }));
146
+ }
147
+
148
+ it("whenDrained resolves at once on an idle pipe, and once the pipe ended", () =>
149
+ withHarness(make, async (h) => {
150
+ await h.pipe.target.whenDrained();
151
+ await h.endRemotely();
152
+ await h.pipe.target.whenDrained();
153
+ }));
154
+
155
+ it("a pending whenDrained resolves when the buffer drains to the low-water mark", () =>
156
+ withHarness(make, async (h) => {
157
+ if (!h.setBuffered) return;
158
+ h.setBuffered(lowWater + 1);
159
+ expect(h.pipe.target.bufferedAmount).toBe(lowWater + 1);
160
+ let drained = false;
161
+ const wait = h.pipe.target.whenDrained().then(() => {
162
+ drained = true;
163
+ });
164
+ await new Promise((resolve) => setTimeout(resolve, 20));
165
+ expect(drained).toBe(false);
166
+ h.setBuffered(lowWater);
167
+ await h.settle?.();
168
+ await wait;
169
+ expect(drained).toBe(true);
170
+ }));
171
+
172
+ it("a pending whenDrained resolves when the pipe ends", () =>
173
+ withHarness(make, async (h) => {
174
+ if (!h.setBuffered) return;
175
+ h.setBuffered(lowWater + 1);
176
+ const wait = h.pipe.target.whenDrained();
177
+ await h.endRemotely();
178
+ await wait;
179
+ }));
180
+ });
181
+ }
@@ -0,0 +1,199 @@
1
+ import type { NativePort, NativePortMux, ValueCodec } from "@statewalker/webrun-streams";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ /** Two ends of one connection, from an adapter that opens a channel per port. */
5
+ export interface PortMuxHarness {
6
+ /** A mux that opens ports and accepts none. */
7
+ opener: NativePortMux;
8
+ /** A mux on the other end, handing each port the opener opens to `onPort`. */
9
+ serve(onPort: (port: NativePort) => boolean | undefined): Promise<NativePortMux>;
10
+ /** Releases the connection. */
11
+ dispose(): void | Promise<void>;
12
+ }
13
+
14
+ /** Builds two connected ends whose muxes use `codec`. */
15
+ export type MakePortMuxHarness = (codec: ValueCodec) => Promise<PortMuxHarness>;
16
+
17
+ /** A value whose encoding the contract's codec refuses to decode. */
18
+ const POISON = "\u0000poison";
19
+
20
+ /** JSON, except that {@link POISON} encodes to a frame `decode` rejects. */
21
+ const contractCodec: ValueCodec = {
22
+ encode: (value) =>
23
+ value === POISON ? new Uint8Array([0xff]) : new TextEncoder().encode(JSON.stringify(value)),
24
+ decode: (bytes) => {
25
+ if (bytes.byteLength === 1 && bytes[0] === 0xff) throw new Error("undecodable");
26
+ return JSON.parse(new TextDecoder().decode(bytes));
27
+ },
28
+ };
29
+
30
+ const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
31
+
32
+ async function until(predicate: () => boolean, label: string, ms = 5000): Promise<void> {
33
+ const deadline = Date.now() + ms;
34
+ while (!predicate()) {
35
+ if (Date.now() > deadline) throw new Error(`timed out waiting for: ${label}`);
36
+ await tick(5);
37
+ }
38
+ }
39
+
40
+ function received(port: NativePort): unknown[] {
41
+ const got: unknown[] = [];
42
+ port.addEventListener("message", (e) => {
43
+ got.push(e.data);
44
+ });
45
+ return got;
46
+ }
47
+
48
+ /**
49
+ * The lifecycle every native port mux keeps (statewalker/webrun-wire#152): the
50
+ * module (`newNativePortMux` in `@statewalker/webrun-streams`) implements it
51
+ * once, and each transport (an in-memory one, WebRTC, libp2p) runs this suite.
52
+ */
53
+ export function describePortMux(name: string, make: MakePortMuxHarness): void {
54
+ async function withPair(
55
+ body: (h: PortMuxHarness, inbound: NativePort[], server: NativePortMux) => Promise<void>,
56
+ accept: (port: NativePort) => boolean | undefined = () => true,
57
+ ): Promise<void> {
58
+ const h = await make(contractCodec);
59
+ const inbound: NativePort[] = [];
60
+ try {
61
+ const server = await h.serve((port) => {
62
+ inbound.push(port);
63
+ return accept(port);
64
+ });
65
+ await body(h, inbound, server);
66
+ } finally {
67
+ await h.opener.close().catch(() => undefined);
68
+ await h.dispose();
69
+ }
70
+ }
71
+
72
+ describe(`${name}: the native port mux contract`, () => {
73
+ it("a port opened on one end arrives on the other; values cross both ways, encoded", () =>
74
+ withPair(async (h, inbound) => {
75
+ const port = await h.opener.openPort();
76
+ const fromServer = received(port);
77
+ port.postMessage({ n: 1, s: "a" });
78
+ await until(() => inbound.length === 1, "the inbound port");
79
+ const server = inbound[0] as NativePort;
80
+ const fromClient = received(server);
81
+ await until(() => fromClient.length === 1, "the first message");
82
+ server.postMessage([2, "b"]);
83
+ await until(() => fromServer.length === 1, "the answer");
84
+ expect(fromClient).toEqual([{ n: 1, s: "a" }]);
85
+ expect(fromServer).toEqual([[2, "b"]]);
86
+ }));
87
+
88
+ it("messages that arrive before a port's first listener are held, for every listener added in that tick", () =>
89
+ withPair(async (h, inbound) => {
90
+ const port = await h.opener.openPort();
91
+ port.postMessage(1);
92
+ port.postMessage(2);
93
+ port.postMessage(3);
94
+ await until(() => inbound.length === 1, "the inbound port");
95
+ await tick(50);
96
+ const server = inbound[0] as NativePort;
97
+ const first = received(server);
98
+ const second = received(server);
99
+ await until(() => first.length === 3 && second.length === 3, "the held messages");
100
+ expect(first).toEqual([1, 2, 3]);
101
+ expect(second).toEqual([1, 2, 3]);
102
+ }));
103
+
104
+ it("removeEventListener stops delivery to that listener", () =>
105
+ withPair(async (h, inbound) => {
106
+ const port = await h.opener.openPort();
107
+ port.postMessage("one");
108
+ await until(() => inbound.length === 1, "the inbound port");
109
+ const server = inbound[0] as NativePort;
110
+ const kept: unknown[] = [];
111
+ const dropped: unknown[] = [];
112
+ const drop = (e: MessageEvent) => {
113
+ dropped.push(e.data);
114
+ };
115
+ server.addEventListener("message", (e) => {
116
+ kept.push(e.data);
117
+ });
118
+ server.addEventListener("message", drop);
119
+ await until(() => kept.length === 1, "the first message");
120
+ server.removeEventListener("message", drop);
121
+ port.postMessage("two");
122
+ await until(() => kept.length === 2, "the second message");
123
+ expect(dropped).toEqual(["one"]);
124
+ }));
125
+
126
+ it("a port the serving end refuses fails: the opener's close signal aborts", () =>
127
+ withPair(
128
+ async (h) => {
129
+ const port = await h.opener.openPort();
130
+ port.postMessage("hello");
131
+ await until(() => port.closeSignal.aborted, "the refusal");
132
+ },
133
+ () => false,
134
+ ));
135
+
136
+ it("an onPort that throws refuses the port", () =>
137
+ withPair(
138
+ async (h) => {
139
+ const port = await h.opener.openPort();
140
+ port.postMessage("hello");
141
+ await until(() => port.closeSignal.aborted, "the refusal");
142
+ },
143
+ () => {
144
+ throw new Error("onPort failed");
145
+ },
146
+ ));
147
+
148
+ it("a frame the codec cannot decode fails the receiving port", () =>
149
+ withPair(async (h, inbound) => {
150
+ const port = await h.opener.openPort();
151
+ port.postMessage("fine");
152
+ await until(() => inbound.length === 1, "the inbound port");
153
+ const server = inbound[0] as NativePort;
154
+ received(server);
155
+ port.postMessage(POISON);
156
+ await until(() => server.closeSignal.aborted, "the receiving port failed");
157
+ expect(String((server.closeSignal.reason as Error)?.message)).toMatch(/decode/);
158
+ }));
159
+
160
+ it("closing a port ends it on both ends", () =>
161
+ withPair(async (h, inbound) => {
162
+ const port = await h.opener.openPort();
163
+ port.postMessage("hello");
164
+ await until(() => inbound.length === 1, "the inbound port");
165
+ await port.close();
166
+ expect(port.closeSignal.aborted).toBe(true);
167
+ await until(() => (inbound[0] as NativePort).closeSignal.aborted, "the peer's port closed");
168
+ }));
169
+
170
+ it("close() closes the ports the mux opened, and openPort rejects afterwards", () =>
171
+ withPair(async (h) => {
172
+ const a = await h.opener.openPort();
173
+ const b = await h.opener.openPort();
174
+ await h.opener.close();
175
+ expect(a.closeSignal.aborted).toBe(true);
176
+ expect(b.closeSignal.aborted).toBe(true);
177
+ await expect(h.opener.openPort()).rejects.toThrow(/closed/);
178
+ }));
179
+
180
+ it("openPort honours its signal: aborted already, or aborted later, which closes the port", () =>
181
+ withPair(async (h) => {
182
+ const aborted = new AbortController();
183
+ aborted.abort(new Error("not wanted"));
184
+ await expect(h.opener.openPort(undefined, { signal: aborted.signal })).rejects.toThrow(
185
+ /not wanted/,
186
+ );
187
+ const later = new AbortController();
188
+ const port = await h.opener.openPort(undefined, { signal: later.signal });
189
+ expect(port.closeSignal.aborted).toBe(false);
190
+ later.abort(new Error("done with it"));
191
+ await until(() => port.closeSignal.aborted, "the port closed");
192
+ }));
193
+
194
+ it("reports its maxMessageSize as a positive number", () =>
195
+ withPair(async (h) => {
196
+ expect(h.opener.maxMessageSize).toBeGreaterThan(0);
197
+ }));
198
+ });
199
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,16 @@ export {
2
2
  type DescribeDuplexAdapterOptions,
3
3
  describeDuplexAdapter,
4
4
  } from "./describe-duplex-adapter.js";
5
+ export {
6
+ type DescribeMessagePipeOptions,
7
+ describeMessagePipe,
8
+ type MessagePipeHarness,
9
+ } from "./describe-message-pipe.js";
10
+ export {
11
+ describePortMux,
12
+ type MakePortMuxHarness,
13
+ type PortMuxHarness,
14
+ } from "./describe-port-mux.js";
5
15
  export {
6
16
  type ConnectServePair,
7
17
  type MakePair,