MCPcopy Create free account
hub / github.com/NativeScript/SimDeck / NodeWebSocket

Class NodeWebSocket

scripts/e2e-webrtc-reliability.mjs:160–349  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

158}
159
160class NodeWebSocket {
161 constructor(url) {
162 this.url = new URL(url);
163 this.listeners = new Map();
164 this.buffer = Buffer.alloc(0);
165 this.handshakeComplete = false;
166 this.opened = this.connect();
167 }
168
169 addEventListener(type, listener, options = {}) {
170 const listeners = this.listeners.get(type) ?? [];
171 listeners.push({ listener, once: Boolean(options.once) });
172 this.listeners.set(type, listeners);
173 }
174
175 removeEventListener(type, listener) {
176 this.listeners.set(
177 type,
178 (this.listeners.get(type) ?? []).filter(
179 (entry) => entry.listener !== listener,
180 ),
181 );
182 }
183
184 emit(type, event = {}) {
185 const listeners = this.listeners.get(type) ?? [];
186 this.listeners.set(
187 type,
188 listeners.filter(({ listener, once }) => {
189 listener(event);
190 return !once;
191 }),
192 );
193 }
194
195 async connect() {
196 if (this.url.protocol !== "ws:") {
197 throw new Error(
198 `Unsupported CDP WebSocket protocol: ${this.url.protocol}`,
199 );
200 }
201 const port = Number(this.url.port || 80);
202 const key = randomBytes(16).toString("base64");
203 this.socket = net.createConnection({
204 host: this.url.hostname,
205 port,
206 });
207 this.socket.on("data", (chunk) => this.handleData(chunk));
208 this.socket.on("error", (error) => this.emit("error", error));
209 this.socket.on("close", () => this.emit("close", {}));
210 await new Promise((resolve, reject) => {
211 this.socket.once("connect", resolve);
212 this.socket.once("error", reject);
213 });
214 const path = `${this.url.pathname}${this.url.search}`;
215 this.socket.write(
216 [
217 `GET ${path} HTTP/1.1`,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected