@statewalker/webrun-streams-ws 0.2.3 → 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/connect.d.ts DELETED
@@ -1,28 +0,0 @@
1
- import { type Connect, type EmulateMuxOptions } from "@statewalker/webrun-streams";
2
- import { type WebSocketLike } from "./websocket-like.js";
3
- export interface ConnectWsParams {
4
- /** WebSocket URL (`ws://` or `wss://`). */
5
- url: string;
6
- /** Optional subprotocol(s) passed to the WebSocket constructor. */
7
- protocols?: string | string[];
8
- /**
9
- * WebSocket constructor. Defaults to the global `WebSocket` when present
10
- * (browser); pass Node's `ws` package's `WebSocket` in Node.
11
- */
12
- WebSocketCtor?: new (url: string, protocols?: string | string[]) => WebSocketLike;
13
- /**
14
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
15
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
16
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
17
- * suite's L6 uses this to run at a window small enough that a sender
18
- * genuinely stalls.
19
- */
20
- mux?: EmulateMuxOptions;
21
- }
22
- /**
23
- * Open a WebSocket to `params.url`, wrap it as a `ByteChannel`, and run it
24
- * through `emulateMux`. Returns `{ call, close }` where `call` is the
25
- * caller-side `Duplex`.
26
- */
27
- export declare const connect: Connect<ConnectWsParams>;
28
- //# sourceMappingURL=connect.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,iBAAiB,EAAc,MAAM,6BAA6B,CAAC;AAE/F,OAAO,EAAE,KAAK,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AAEzE,MAAM,WAAW,eAAe;IAC9B,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC9B;;;OAGG;IACH,aAAa,CAAC,EAAE,KACd,GAAG,EAAE,MAAM,EACX,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,KAC1B,aAAa,CAAC;IACnB;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO,EAAE,OAAO,CAAC,eAAe,CAiB5C,CAAC"}
package/dist/serve.d.ts DELETED
@@ -1,29 +0,0 @@
1
- import { type Duplex, type EmulateMuxOptions } from "@statewalker/webrun-streams";
2
- import type { WebSocketLike } from "./websocket-like.js";
3
- export interface ServeWsParams {
4
- /**
5
- * Source of inbound WebSocket connections. Either a `wss` instance with a
6
- * `connection` event, or a manual handler the caller wires to its own
7
- * server.
8
- */
9
- onConnection: (cb: (ws: WebSocketLike) => void) => () => void;
10
- /**
11
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
12
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
13
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
14
- * suite's L6 uses this to run at a window small enough that a sender
15
- * genuinely stalls.
16
- */
17
- mux?: EmulateMuxOptions;
18
- }
19
- /**
20
- * Register a `Duplex` handler against an inbound-WebSocket source. The
21
- * `onConnection` callback is invoked once per accepted connection; the
22
- * adapter wraps each in `emulateMux` and binds the handler.
23
- *
24
- * Returns an idempotent teardown that unregisters the connection listener.
25
- * Open `emulateMux` instances continue running until their underlying
26
- * WebSocket closes.
27
- */
28
- export declare function serve(params: ServeWsParams, handler: Duplex): Promise<() => Promise<void>>;
29
- //# sourceMappingURL=serve.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,iBAAiB,EAAc,MAAM,6BAA6B,CAAC;AAE9F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,MAAM,WAAW,aAAa;IAC5B;;;;OAIG;IACH,YAAY,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,aAAa,KAAK,IAAI,KAAK,MAAM,IAAI,CAAC;IAC9D;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED;;;;;;;;GAQG;AACH,wBAAsB,KAAK,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAahG"}
@@ -1,122 +0,0 @@
1
- import { type ByteChannel, normalizeToUint8Array } from "@statewalker/webrun-streams";
2
- import { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
3
-
4
- /**
5
- * Wrap an open `WebSocket` (or any `WebSocketLike` — Node `ws` works) into a
6
- * `ByteChannel` consumable by `emulateMux`. The socket MUST already be in the
7
- * `OPEN` state; the adapter does not perform handshakes.
8
- *
9
- * Inbound binary frames are normalised to `Uint8Array`. Text frames are also
10
- * accepted (rare on this transport) and surfaced as their UTF-8 bytes.
11
- */
12
- export function byteChannelFromWebSocket(ws: WebSocketLike): ByteChannel {
13
- if (ws.readyState !== WS_READY_STATE.OPEN) {
14
- throw new Error(
15
- `byteChannelFromWebSocket: WebSocket is in readyState ${ws.readyState}, expected OPEN (1)`,
16
- );
17
- }
18
-
19
- let closedResolve!: () => void;
20
- const closed = new Promise<void>((r) => {
21
- closedResolve = r;
22
- });
23
- let isClosed = false;
24
-
25
- // Inbound: queue of received chunks + pending next() resolver
26
- const queue: Uint8Array[] = [];
27
- let pending: ((value: IteratorResult<Uint8Array>) => void) | null = null;
28
-
29
- const onMessage = (event: MessageEvent): void => {
30
- if (isClosed) return;
31
- const data = event.data as unknown;
32
- let normalised: Uint8Array;
33
- if (data instanceof Uint8Array) {
34
- normalised = data;
35
- } else if (data instanceof ArrayBuffer) {
36
- normalised = new Uint8Array(data);
37
- } else if (ArrayBuffer.isView(data)) {
38
- const view = data as ArrayBufferView;
39
- normalised = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
40
- } else if (typeof Blob !== "undefined" && data instanceof Blob) {
41
- void data.arrayBuffer().then((buf) => deliver(new Uint8Array(buf)));
42
- return;
43
- } else if (typeof data === "string") {
44
- const n = normalizeToUint8Array(data);
45
- if (n instanceof Uint8Array) normalised = n;
46
- else {
47
- void n.then(deliver);
48
- return;
49
- }
50
- } else {
51
- return;
52
- }
53
- deliver(normalised);
54
- };
55
-
56
- const deliver = (bytes: Uint8Array): void => {
57
- if (isClosed) return;
58
- if (pending) {
59
- const r = pending;
60
- pending = null;
61
- r({ value: bytes, done: false });
62
- } else {
63
- queue.push(bytes);
64
- }
65
- };
66
-
67
- const onClose = (): void => {
68
- if (isClosed) return;
69
- isClosed = true;
70
- ws.removeEventListener("message", onMessage);
71
- ws.removeEventListener("close", onClose);
72
- if (pending) {
73
- const r = pending;
74
- pending = null;
75
- r({ value: undefined, done: true } as IteratorResult<Uint8Array>);
76
- }
77
- closedResolve();
78
- };
79
-
80
- ws.addEventListener("message", onMessage);
81
- ws.addEventListener("close", onClose);
82
-
83
- const recv: AsyncIterable<Uint8Array> = {
84
- [Symbol.asyncIterator]() {
85
- return {
86
- next(): Promise<IteratorResult<Uint8Array>> {
87
- if (queue.length > 0) {
88
- return Promise.resolve({ value: queue.shift() as Uint8Array, done: false });
89
- }
90
- if (isClosed) {
91
- return Promise.resolve({
92
- value: undefined,
93
- done: true,
94
- } as IteratorResult<Uint8Array>);
95
- }
96
- return new Promise<IteratorResult<Uint8Array>>((resolve) => {
97
- pending = resolve;
98
- });
99
- },
100
- };
101
- },
102
- };
103
-
104
- return {
105
- send(bytes) {
106
- if (isClosed) return;
107
- if (ws.readyState !== WS_READY_STATE.OPEN) return;
108
- ws.send(bytes);
109
- },
110
- recv,
111
- closed,
112
- close() {
113
- if (isClosed) return;
114
- try {
115
- ws.close();
116
- } catch {
117
- /* ignore */
118
- }
119
- onClose();
120
- },
121
- };
122
- }
package/src/connect.ts DELETED
@@ -1,76 +0,0 @@
1
- import { type Connect, type EmulateMuxOptions, emulateMux } from "@statewalker/webrun-streams";
2
- import { byteChannelFromWebSocket } from "./byte-channel.js";
3
- import { type WebSocketLike, WS_READY_STATE } from "./websocket-like.js";
4
-
5
- export interface ConnectWsParams {
6
- /** WebSocket URL (`ws://` or `wss://`). */
7
- url: string;
8
- /** Optional subprotocol(s) passed to the WebSocket constructor. */
9
- protocols?: string | string[];
10
- /**
11
- * WebSocket constructor. Defaults to the global `WebSocket` when present
12
- * (browser); pass Node's `ws` package's `WebSocket` in Node.
13
- */
14
- WebSocketCtor?: new (
15
- url: string,
16
- protocols?: string | string[],
17
- ) => WebSocketLike;
18
- /**
19
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
20
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
21
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
22
- * suite's L6 uses this to run at a window small enough that a sender
23
- * genuinely stalls.
24
- */
25
- mux?: EmulateMuxOptions;
26
- }
27
-
28
- /**
29
- * Open a WebSocket to `params.url`, wrap it as a `ByteChannel`, and run it
30
- * through `emulateMux`. Returns `{ call, close }` where `call` is the
31
- * caller-side `Duplex`.
32
- */
33
- export const connect: Connect<ConnectWsParams> = async (params) => {
34
- const Ctor = params.WebSocketCtor ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;
35
- if (!Ctor) {
36
- throw new Error(
37
- "webrun-streams-ws connect: no WebSocket constructor available. Pass `params.WebSocketCtor` (e.g. the `ws` package's WebSocket in Node).",
38
- );
39
- }
40
- const ws = new Ctor(params.url, params.protocols) as WebSocketLike;
41
- await waitForOpen(ws);
42
- const channel = byteChannelFromWebSocket(ws);
43
- const mux = emulateMux(channel, { ...params.mux, side: "initiator" });
44
- return {
45
- call: mux.call,
46
- async close() {
47
- await mux.close();
48
- },
49
- };
50
- };
51
-
52
- function waitForOpen(ws: WebSocketLike): Promise<void> {
53
- if (ws.readyState === WS_READY_STATE.OPEN) return Promise.resolve();
54
- return new Promise<void>((resolve, reject) => {
55
- const cleanup = (): void => {
56
- ws.removeEventListener("open", onOpen);
57
- ws.removeEventListener("error", onError);
58
- ws.removeEventListener("close", onCloseEarly);
59
- };
60
- const onOpen = (): void => {
61
- cleanup();
62
- resolve();
63
- };
64
- const onError = (): void => {
65
- cleanup();
66
- reject(new Error("WebSocket error before open"));
67
- };
68
- const onCloseEarly = (): void => {
69
- cleanup();
70
- reject(new Error("WebSocket closed before it opened"));
71
- };
72
- ws.addEventListener("open", onOpen);
73
- ws.addEventListener("error", onError);
74
- ws.addEventListener("close", onCloseEarly);
75
- });
76
- }
package/src/serve.ts DELETED
@@ -1,44 +0,0 @@
1
- import { type Duplex, type EmulateMuxOptions, emulateMux } from "@statewalker/webrun-streams";
2
- import { byteChannelFromWebSocket } from "./byte-channel.js";
3
- import type { WebSocketLike } from "./websocket-like.js";
4
-
5
- export interface ServeWsParams {
6
- /**
7
- * Source of inbound WebSocket connections. Either a `wss` instance with a
8
- * `connection` event, or a manual handler the caller wires to its own
9
- * server.
10
- */
11
- onConnection: (cb: (ws: WebSocketLike) => void) => () => void;
12
- /**
13
- * Flow-control tuning forwarded to `emulateMux` — `mtu` and
14
- * `maxStreamBuffer`, which is the credit this side advertises. `side` here
15
- * wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
16
- * suite's L6 uses this to run at a window small enough that a sender
17
- * genuinely stalls.
18
- */
19
- mux?: EmulateMuxOptions;
20
- }
21
-
22
- /**
23
- * Register a `Duplex` handler against an inbound-WebSocket source. The
24
- * `onConnection` callback is invoked once per accepted connection; the
25
- * adapter wraps each in `emulateMux` and binds the handler.
26
- *
27
- * Returns an idempotent teardown that unregisters the connection listener.
28
- * Open `emulateMux` instances continue running until their underlying
29
- * WebSocket closes.
30
- */
31
- export async function serve(params: ServeWsParams, handler: Duplex): Promise<() => Promise<void>> {
32
- const off = params.onConnection((ws) => {
33
- const channel = byteChannelFromWebSocket(ws);
34
- const mux = emulateMux(channel, { ...params.mux, side: "responder" });
35
- mux.serve(handler);
36
- void channel.closed.then(() => mux.close());
37
- });
38
- let torn = false;
39
- return async () => {
40
- if (torn) return;
41
- torn = true;
42
- off();
43
- };
44
- }