node-ws-over-trystero 0.0.0 → 0.1.1

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
@@ -1 +1,85 @@
1
- Coming soon
1
+ # node-ws-over-trystero
2
+
3
+ The **server end** of a trystero pipe, wearing the shape a [`ws`](https://github.com/websockets/ws)
4
+ server expects. It pairs with
5
+ [websocket-over-trystero](../websocket-over-trystero):
6
+ that one gives a browser a WebSocket-shaped socket, this one gives your Node
7
+ server a `ws`-server-shaped socket for every peer that joins the room.
8
+
9
+ > **Release status:** not published yet. The npm name is reserved by a 0.0.x
10
+ > placeholder release; the 0.1.0 build in this repository has not been released.
11
+
12
+ It was written against what `@colyseus/ws-transport` actually touches —
13
+ `readyState`, `send(data, opts, cb)`, `close(code, reason)`, `terminate()`,
14
+ `ping()` (a `pong` must come back), `on("message" | "close" | "error" | "pong")`,
15
+ `pingCount`, `_socket.remoteAddress` — so it drops into such a server unchanged.
16
+
17
+ ## It is not a real socket
18
+
19
+ There is no framing, no backpressure (`bufferedAmount` is always `0`) and no
20
+ `maxPayload` limit: `ws` enforces that inside its own receiver, which these peers
21
+ never pass through. A message larger than your server's configured maximum is
22
+ therefore **not** truncated.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ pnpm add node-ws-over-trystero
28
+ pnpm add @trystero-p2p/mqtt # the strategy you want
29
+ pnpm add werift # Node's WebRTC implementation
30
+ ```
31
+
32
+ ## Use
33
+
34
+ ```js
35
+ import { createTrysteroServer } from "node-ws-over-trystero";
36
+ import { joinRoom, selfId } from "@trystero-p2p/mqtt";
37
+ import { RTCPeerConnection } from "werift";
38
+
39
+ const server = createTrysteroServer({
40
+ joinRoom,
41
+ roomConfig: {
42
+ appId: "my-app",
43
+ relayConfig: { urls: ["wss://broker-cn.emqx.io:8084/mqtt"] },
44
+ rtcConfig: { iceServers: [] },
45
+ rtcPolyfill: RTCPeerConnection,
46
+ },
47
+ roomId: "invite-code", // the code you hand to players
48
+ selfId,
49
+ });
50
+
51
+ server.on("peer", (peer) => {
52
+ console.log(peer.id, "greeted with", new TextDecoder().decode(peer.greeting));
53
+ // peer.socket is ws-shaped from here on.
54
+ peer.socket.on("message", (data) => peer.socket.send(data));
55
+ });
56
+
57
+ // Answer request/response calls from peers (trystero's request channel).
58
+ server.handleRequest(async (payload) => payload);
59
+
60
+ await server.close();
61
+ ```
62
+
63
+ Wiring it into a `ws`-based server is one line per peer:
64
+
65
+ ```js
66
+ wss.emit("connection", peer.socket, {}, { url: new URL(greeting), context });
67
+ ```
68
+
69
+ ## Closing
70
+
71
+ `peer.socket.close()` reaches the client as a normal close event, and a client
72
+ that closes reaches you the same way (`peer.socket` emits `close`). Neither end
73
+ waits on the other: a server that closes the socket and expects the client to
74
+ notice on its own would leave the client's `leave()` hanging.
75
+
76
+ ## The greeting
77
+
78
+ A peer's **first** message is delivered as `peer.greeting` — opaque bytes this
79
+ package never interprets. Everything after it is pipe data. That mirrors the
80
+ client package's `greeting` option, so neither package holds an opinion about
81
+ what a handshake contains.
82
+
83
+ ## Licence
84
+
85
+ LGPL-3.0-or-later. See `LICENSE` and `COPYING.LESSER`.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * node-ws-over-trystero — the server end of a trystero pipe, wearing the shape
3
+ * `ws` servers expect.
4
+ *
5
+ * It pairs with `websocket-over-trystero` (the client end): that one gives a
6
+ * browser a WebSocket-shaped socket, this one gives a Node server a
7
+ * `ws`-server-shaped socket for each peer that joins the room. Neither package
8
+ * knows what protocol rides the pipe.
9
+ */
10
+ export { createTrysteroServer, TrysteroServer, type PeerConnection, type TrysteroServerOptions, } from "./server.js";
11
+ export { PeerWebSocket, type PeerSender } from "./socket.js";
12
+ /**
13
+ * The channel primitive and JSON helpers are re-exported so a server needs only
14
+ * this package: they live in `websocket-over-trystero` but are role-neutral.
15
+ */
16
+ export { createTrysteroChannel, decodeJson, encodeJson, type PeerChannel, type TrysteroAction, type TrysteroStrategy, type TrysteroRequestAction, type TrysteroRoom, type TrysteroRoomConfig, } from "websocket-over-trystero";
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACN,oBAAoB,EACpB,cAAc,EACd,KAAK,cAAc,EACnB,KAAK,qBAAqB,GAC1B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAE7D;;;GAGG;AACH,OAAO,EACN,qBAAqB,EACrB,UAAU,EACV,UAAU,EACV,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,EACjB,KAAK,kBAAkB,GACvB,MAAM,yBAAyB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * node-ws-over-trystero — the server end of a trystero pipe, wearing the shape
3
+ * `ws` servers expect.
4
+ *
5
+ * It pairs with `websocket-over-trystero` (the client end): that one gives a
6
+ * browser a WebSocket-shaped socket, this one gives a Node server a
7
+ * `ws`-server-shaped socket for each peer that joins the room. Neither package
8
+ * knows what protocol rides the pipe.
9
+ */
10
+ export { createTrysteroServer, TrysteroServer, } from "./server.js";
11
+ export { PeerWebSocket } from "./socket.js";
12
+ /**
13
+ * The channel primitive and JSON helpers are re-exported so a server needs only
14
+ * this package: they live in `websocket-over-trystero` but are role-neutral.
15
+ */
16
+ export { createTrysteroChannel, decodeJson, encodeJson, } from "websocket-over-trystero";
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACN,oBAAoB,EACpB,cAAc,GAGd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAmB,MAAM,aAAa,CAAC;AAE7D;;;GAGG;AACH,OAAO,EACN,qBAAqB,EACrB,UAAU,EACV,UAAU,GAOV,MAAM,yBAAyB,CAAC"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The server end of the pipe: a trystero room whose peers each become a
3
+ * `ws`-server-shaped socket.
4
+ *
5
+ * Protocol note — the greeting. A peer's FIRST message is delivered as opaque
6
+ * bytes on `peer.greeting` rather than guessed at; everything after it is pipe
7
+ * data. That is the mirror of the client package's `greeting` option, and it
8
+ * keeps both packages free of any opinion about what a handshake contains: a
9
+ * Colyseus endpoint URL, a token, or nothing at all.
10
+ */
11
+ import { EventEmitter } from "node:events";
12
+ import { type TrysteroStrategy, type TrysteroRoomConfig } from "websocket-over-trystero";
13
+ import { PeerWebSocket } from "./socket.js";
14
+ /** Options for {@link createTrysteroServer}. */
15
+ export interface TrysteroServerOptions {
16
+ /** The strategy module the operator chose (its `joinRoom` and `selfId`). */
17
+ strategy: TrysteroStrategy;
18
+ /** Relay urls, ICE servers, password, polyfill — passed straight through. */
19
+ roomConfig: TrysteroRoomConfig;
20
+ /** The Trystero roomId peers are given. */
21
+ roomId: string;
22
+ }
23
+ /** One peer that joined the room, with its greeting and per-peer socket. */
24
+ export interface PeerConnection {
25
+ /** The peer's id within the room. */
26
+ id: string;
27
+ /** The opaque first message the peer sent. */
28
+ greeting: Uint8Array;
29
+ /** A `ws`-server-shaped socket for the rest of the conversation. */
30
+ socket: PeerWebSocket;
31
+ }
32
+ /** The `peer` event surface of a {@link TrysteroServer}. */
33
+ export interface TrysteroServer extends EventEmitter {
34
+ /** Fires once per peer, after its greeting arrives. */
35
+ on(event: "peer", listener: (peer: PeerConnection) => void): this;
36
+ emit(event: "peer", peer: PeerConnection): boolean;
37
+ }
38
+ /**
39
+ * A trystero room that presents each peer as a `ws`-server-shaped socket.
40
+ * Construct one with {@link createTrysteroServer}; listen for the `peer` event
41
+ * to receive connections as they arrive.
42
+ */
43
+ export declare class TrysteroServer extends EventEmitter {
44
+ /** The trystero room id this server joined. */
45
+ readonly roomId: string;
46
+ /** This peer's id, as reported by the strategy. */
47
+ readonly selfId: string;
48
+ private readonly channel;
49
+ private readonly connections;
50
+ constructor(options: TrysteroServerOptions);
51
+ /** Peers currently in the room, this server included. */
52
+ peers(): string[];
53
+ /**
54
+ * Answer peer requests (trystero's request/response channel). The engine uses
55
+ * it to hand out seat reservations; this package does not interpret them.
56
+ */
57
+ handleRequest(handler: (payload: Uint8Array, peerId: string) => Uint8Array | Promise<Uint8Array>): void;
58
+ /** Close every peer socket and leave the trystero room. */
59
+ close(): Promise<void>;
60
+ private onBytes;
61
+ }
62
+ /** Create a {@link TrysteroServer} over the room described by `options`. */
63
+ export declare function createTrysteroServer(options: TrysteroServerOptions): TrysteroServer;
64
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,gDAAgD;AAChD,MAAM,WAAW,qBAAqB;IACrC,4EAA4E;IAC5E,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,6EAA6E;IAC7E,UAAU,EAAE,kBAAkB,CAAC;IAC/B,2CAA2C;IAC3C,MAAM,EAAE,MAAM,CAAC;CACf;AAED,4EAA4E;AAC5E,MAAM,WAAW,cAAc;IAC9B,qCAAqC;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,8CAA8C;IAC9C,QAAQ,EAAE,UAAU,CAAC;IACrB,oEAAoE;IACpE,MAAM,EAAE,aAAa,CAAC;CACtB;AAED,4DAA4D;AAC5D,MAAM,WAAW,cAAe,SAAQ,YAAY;IACnD,uDAAuD;IACvD,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,GAAG,IAAI,CAAC;IAClE,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC;CACnD;AAED;;;;GAIG;AACH,qBAAa,cAAe,SAAQ,YAAY;IAC/C,+CAA+C;IAC/C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,mDAAmD;IACnD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAqC;IAEjE,YAAY,OAAO,EAAE,qBAAqB,EAoBzC;IAED,yDAAyD;IACzD,KAAK,IAAI,MAAM,EAAE,CAEhB;IAED;;;OAGG;IACH,aAAa,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,KAAK,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAEtG;IAED,2DAA2D;IACrD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAM3B;IAED,OAAO,CAAC,OAAO;CAiCf;AAED,4EAA4E;AAC5E,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CAEnF"}
package/dist/server.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The server end of the pipe: a trystero room whose peers each become a
3
+ * `ws`-server-shaped socket.
4
+ *
5
+ * Protocol note — the greeting. A peer's FIRST message is delivered as opaque
6
+ * bytes on `peer.greeting` rather than guessed at; everything after it is pipe
7
+ * data. That is the mirror of the client package's `greeting` option, and it
8
+ * keeps both packages free of any opinion about what a handshake contains: a
9
+ * Colyseus endpoint URL, a token, or nothing at all.
10
+ */
11
+ import { EventEmitter } from "node:events";
12
+ import { createTrysteroChannel, } from "websocket-over-trystero";
13
+ import { PeerWebSocket } from "./socket.js";
14
+ /**
15
+ * A trystero room that presents each peer as a `ws`-server-shaped socket.
16
+ * Construct one with {@link createTrysteroServer}; listen for the `peer` event
17
+ * to receive connections as they arrive.
18
+ */
19
+ export class TrysteroServer extends EventEmitter {
20
+ /** The trystero room id this server joined. */
21
+ roomId;
22
+ /** This peer's id, as reported by the strategy. */
23
+ selfId;
24
+ channel;
25
+ connections = new Map();
26
+ constructor(options) {
27
+ super();
28
+ this.roomId = options.roomId;
29
+ this.channel = createTrysteroChannel(options.strategy, options.roomConfig, options.roomId);
30
+ this.selfId = this.channel.selfId;
31
+ this.channel.handleData((bytes, peerId) => this.onBytes(peerId, bytes));
32
+ this.channel.handleClose((code, reason, peerId) => {
33
+ const peer = this.connections.get(peerId);
34
+ if (!peer)
35
+ return;
36
+ this.connections.delete(peerId);
37
+ peer.socket.peerClosed(code, reason);
38
+ });
39
+ this.channel.handlePeerLeave((peerId) => {
40
+ const peer = this.connections.get(peerId);
41
+ if (!peer)
42
+ return;
43
+ this.connections.delete(peerId);
44
+ // The peer is gone from the room entirely: nobody left to tell.
45
+ peer.socket.peerClosed(4001, "peer left the room");
46
+ });
47
+ }
48
+ /** Peers currently in the room, this server included. */
49
+ peers() {
50
+ return this.channel.peers();
51
+ }
52
+ /**
53
+ * Answer peer requests (trystero's request/response channel). The engine uses
54
+ * it to hand out seat reservations; this package does not interpret them.
55
+ */
56
+ handleRequest(handler) {
57
+ this.channel.handleRequest(handler);
58
+ }
59
+ /** Close every peer socket and leave the trystero room. */
60
+ async close() {
61
+ for (const peer of this.connections.values()) {
62
+ peer.socket.close(1001, "server shutting down");
63
+ }
64
+ this.connections.clear();
65
+ await this.channel.leave();
66
+ }
67
+ onBytes(peerId, bytes) {
68
+ const existing = this.connections.get(peerId);
69
+ if (existing) {
70
+ existing.socket.deliver(bytes);
71
+ return;
72
+ }
73
+ const peer = {
74
+ id: peerId,
75
+ greeting: bytes,
76
+ socket: new PeerWebSocket({
77
+ // Return the send's Promise so a datachannel failure is
78
+ // surfaced (PeerWebSocket routes it to the "error" event
79
+ // and the ws-style callback) instead of being dropped.
80
+ send: (out) => this.channel.send(out, peerId),
81
+ close: (code, reason) => this.channel.close(peerId, code, reason),
82
+ }),
83
+ };
84
+ this.connections.set(peerId, peer);
85
+ // Forget the peer when its pipe closes — EITHER end may
86
+ // initiate. A server-initiated close (a crashed language
87
+ // server, a torn-down session) used to leave the entry
88
+ // behind, so the peer's next greeting — an editor's Retry
89
+ // within the same page session — was delivered as data to
90
+ // the dead socket and never adopted (the pipe could not be
91
+ // re-established without a page reload). The entry serves
92
+ // no purpose once closed: `deliver` drops everything anyway.
93
+ peer.socket.on("close", () => {
94
+ if (this.connections.get(peerId) === peer) {
95
+ this.connections.delete(peerId);
96
+ }
97
+ });
98
+ this.emit("peer", peer);
99
+ }
100
+ }
101
+ /** Create a {@link TrysteroServer} over the room described by `options`. */
102
+ export function createTrysteroServer(options) {
103
+ return new TrysteroServer(options);
104
+ }
105
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACN,qBAAqB,GAIrB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AA6B5C;;;;GAIG;AACH,MAAM,OAAO,cAAe,SAAQ,YAAY;IAC/C,+CAA+C;IACtC,MAAM,CAAS;IACxB,mDAAmD;IAC1C,MAAM,CAAS;IACP,OAAO,CAAc;IACrB,WAAW,GAAG,IAAI,GAAG,EAA0B,CAAC;IAEjE,YAAY,OAA8B;QACzC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,qBAAqB,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAA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,CAAC,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC;gBAC3C,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACjC,CAAC;QACF,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACzB,CAAC;CACD;AAED,4EAA4E;AAC5E,MAAM,UAAU,oBAAoB,CAAC,OAA8B;IAClE,OAAO,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC"}
@@ -0,0 +1,162 @@
1
+ /**
2
+ * A `ws`-server-shaped socket over one trystero peer.
3
+ *
4
+ * This is the mirror of `Wsp2pSocket` in `websocket-over-trystero`: same pipe,
5
+ * opposite role. It exists so a Node server built on `ws` — Colyseus's own
6
+ * `@colyseus/ws-transport` among them — can serve a peer as if it had arrived on
7
+ * a TCP upgrade, without reimplementing that server's client lifecycle.
8
+ *
9
+ * `ws` usage this covers, taken from what `@colyseus/ws-transport` actually
10
+ * touches: `readyState`, `send(data, opts, cb)`, `close(code, reason)`,
11
+ * `terminate()`, `ping()` (it expects a `pong`), `on("message" | "close" |
12
+ * "error" | "pong")`, `pingCount`, and `_socket.remoteAddress`.
13
+ *
14
+ * It is not a real socket: there is no framing, no backpressure
15
+ * (`bufferedAmount` is always 0), and `maxPayload` — enforced inside `ws`'s own
16
+ * receiver — does not apply, so a message larger than the server's configured
17
+ * maximum is not truncated.
18
+ */
19
+ import { EventEmitter } from "node:events";
20
+ /** Where this socket's outbound bytes go, and how it signals a close. */
21
+ export interface PeerSender {
22
+ /**
23
+ * Sends the bytes. A transport whose send is asynchronous (the
24
+ * trystero datachannel) returns a Promise that rejects when the
25
+ * send fails; a synchronous one returns void.
26
+ */
27
+ send: (bytes: Uint8Array) => void | Promise<void>;
28
+ close: (code: number, reason: string) => void;
29
+ }
30
+ /**
31
+ * DOM-WebSocket-shaped events (hand-rolled — Node has no `MessageEvent`).
32
+ * The mirror of `Wsp2pDomEvent` in `websocket-over-trystero`: consumers that
33
+ * speak `addEventListener`/`on*` (vtlsp's `LSWSServer.handleNewWebsocket`,
34
+ * for one) ride this pipe; `ws`-style `emit("message"|"close")` consumers are
35
+ * untouched and keep their Buffer/reason-Buffer arguments.
36
+ */
37
+ export type PeerDomEvent = {
38
+ type: "message";
39
+ data: ArrayBuffer;
40
+ } | {
41
+ type: "close";
42
+ code: number;
43
+ reason: string;
44
+ wasClean: boolean;
45
+ } | {
46
+ type: "open";
47
+ } | {
48
+ type: "error";
49
+ error?: unknown;
50
+ };
51
+ type PeerListener = (ev: PeerDomEvent) => void;
52
+ /**
53
+ * A `ws`-server-shaped socket for one trystero peer. Created by the
54
+ * {@link TrysteroServer} when a peer's first bytes arrive; consumers see a
55
+ * familiar `ws` socket (`on("message")`, `send`, `close`, `ping`).
56
+ */
57
+ export declare class PeerWebSocket extends EventEmitter {
58
+ private readonly peer;
59
+ readyState: number;
60
+ /** Written and read by `@colyseus/ws-transport`'s heartbeat. */
61
+ pingCount: number;
62
+ protocol: string;
63
+ bufferedAmount: number;
64
+ /** DOM field; the pipe is byte-oriented, so arraybuffer is all we deliver. */
65
+ binaryType: string;
66
+ /** Read when a server builds an auth context from the socket. */
67
+ readonly _socket: {
68
+ remoteAddress: string;
69
+ };
70
+ private closed;
71
+ /** DOM event listeners, mirrored per type (NOT `EventEmitter.listeners()`). */
72
+ private domListeners;
73
+ /** Replay for late "open"/"close" subscribers (the socket starts OPEN). */
74
+ private lastCloseEvent;
75
+ private _onopen;
76
+ private _onmessage;
77
+ private _onclose;
78
+ private _onerror;
79
+ constructor(peer: PeerSender);
80
+ /**
81
+ * DOM `on*` properties (vtlsp assigns them). Setting `onopen` while the
82
+ * socket is already OPEN — the normal case here — replays it once.
83
+ */
84
+ get onopen(): ((ev: {
85
+ type: "open";
86
+ }) => void) | null;
87
+ set onopen(fn: ((ev: {
88
+ type: "open";
89
+ }) => void) | null);
90
+ get onmessage(): ((ev: Extract<PeerDomEvent, {
91
+ type: "message";
92
+ }>) => void) | null;
93
+ set onmessage(fn: ((ev: Extract<PeerDomEvent, {
94
+ type: "message";
95
+ }>) => void) | null);
96
+ get onclose(): ((ev: Extract<PeerDomEvent, {
97
+ type: "close";
98
+ }>) => void) | null;
99
+ set onclose(fn: ((ev: Extract<PeerDomEvent, {
100
+ type: "close";
101
+ }>) => void) | null);
102
+ get onerror(): ((ev: Extract<PeerDomEvent, {
103
+ type: "error";
104
+ }>) => void) | null;
105
+ set onerror(fn: ((ev: Extract<PeerDomEvent, {
106
+ type: "error";
107
+ }>) => void) | null);
108
+ /**
109
+ * DOM `addEventListener` (NOT Node's `on()` alias — plain EventEmitter has
110
+ * no such member): DOM consumers get `emit()`-independent listeners with
111
+ * `removeEventListener` symmetry; ws-style consumers keep `on()`/`emit()`.
112
+ */
113
+ addEventListener(type: string, listener: PeerListener): this;
114
+ /** Remove a listener previously added with {@link addEventListener}. */
115
+ removeEventListener(type: string, listener: PeerListener): this;
116
+ private dispatch;
117
+ /**
118
+ * Recover the exact LSP frame from a Node Buffer-pool slab leak.
119
+ *
120
+ * `@valtown/ls-ws-server`'s writable chunks with
121
+ * `Buffer.slice(i, end).buffer` — for a pool-backed Buffer `.buffer` is
122
+ * the ENTIRE ~64KB pool (stale bytes before/after the logical view), so
123
+ * the far end receives `[garbage][Content-Length frame][garbage]` and its
124
+ * strict reader never parses it (initialize hangs forever). A `ws` shim
125
+ * must deliver the intended BYTES: when the payload does not start with a
126
+ * frame but clearly CONTAINS one (header parses, body is JSON, bounded
127
+ * search), trim to exactly that frame; anything else passes through
128
+ * untouched (game msgpack is never touched — it neither starts with nor
129
+ * validates as an LSP frame).
130
+ */
131
+ static recoverLspFrame(data: Uint8Array): Uint8Array;
132
+ /**
133
+ * Send bytes to the peer. `callback` (the ws-style third argument) fires with
134
+ * an error if the socket is closed or the underlying send rejects.
135
+ */
136
+ send(data: string | ArrayBufferLike | ArrayBufferView, _options?: unknown, callback?: (err?: Error) => void): void;
137
+ /**
138
+ * Servers ping on an interval and terminate clients that stop answering, so a
139
+ * pong has to come back. There is no transport-level ping to make — WebRTC
140
+ * keeps the link alive — so answer at once.
141
+ */
142
+ ping(): void;
143
+ /** Close the socket (code 1006 for {@link terminate}), notifying the peer. */
144
+ close(code?: number, reason?: string): void;
145
+ /** Abruptly terminate the socket, as `ws` does (close code 1006). */
146
+ terminate(): void;
147
+ /** A transport-level error surfaced to DOM-style consumers. */
148
+ error(err: unknown): void;
149
+ /**
150
+ * The peer told us it is closing. Emit the close for the server, but do NOT
151
+ * tell the peer back: the notification would arrive after a reconnecting
152
+ * client has already registered its next socket, and close that one instead.
153
+ * (The mirror case is fine — a socket closed by a remote close never
154
+ * notifies, so the two directions stay balanced.)
155
+ */
156
+ peerClosed(code?: number, reason?: string): void;
157
+ /** Bytes arrived from the peer: deliver them as a `ws` message would. */
158
+ deliver(bytes: Uint8Array): void;
159
+ private dispatchCloseEvent;
160
+ }
161
+ export {};
162
+ //# sourceMappingURL=socket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socket.d.ts","sourceRoot":"","sources":["../src/socket.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAO3C,yEAAyE;AACzE,MAAM,WAAW,UAAU;IAC1B;;;;OAIG;IACH,IAAI,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClD,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9C;AAED;;;;;;GAMG;AACH,MAAM,MAAM,YAAY,GACrB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,IAAI,EAAE,WAAW,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QA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