* Create a new websocket connection * @param _webSocketUrl
(_webSocketUrl)
| 31 | * @param _webSocketUrl |
| 32 | */ |
| 33 | constructor(_webSocketUrl) { |
| 34 | super() |
| 35 | this.connected = false |
| 36 | this._closed = false |
| 37 | this._pending = new Map() |
| 38 | this._connectWaiters = new Set() |
| 39 | this._ws = new WebSocket(_webSocketUrl) |
| 40 | this._ws.on('open', () => { |
| 41 | // The handshake can complete after close()/_failPending() has already |
| 42 | // marked the connection closed. Don't flip connected back to true and |
| 43 | // proactively close the now-orphan socket so it does not leak. |
| 44 | if (this._closed) { |
| 45 | try { |
| 46 | this._ws.close() |
| 47 | } catch { |
| 48 | /* socket already closing */ |
| 49 | } |
| 50 | return |
| 51 | } |
| 52 | this.connected = true |
| 53 | for (const { resolve } of this._connectWaiters) { |
| 54 | resolve() |
| 55 | } |
| 56 | this._connectWaiters.clear() |
| 57 | }) |
| 58 | // Single shared response dispatcher. Avoids attaching a new 'message' |
| 59 | // listener for every in-flight send(), which previously caused |
| 60 | // MaxListenersExceededWarning under concurrent BiDi traffic |
| 61 | // (e.g. network interception during a page navigation). |
| 62 | this._ws.on('message', (data) => { |
| 63 | // Frames can arrive after close() has cleared _pending; ignore them |
| 64 | // rather than re-emitting parse errors or dispatching to nothing. |
| 65 | if (this._closed) { |
| 66 | return |
| 67 | } |
| 68 | let payload |
| 69 | try { |
| 70 | payload = JSON.parse(data.toString()) |
| 71 | } catch (err) { |
| 72 | // Surface protocol parse failures rather than silently dropping — |
| 73 | // otherwise callers see misleading send() timeouts. |
| 74 | const wrapped = new Error(`Failed to parse BiDi message: ${err.message}`) |
| 75 | if (this.listenerCount('error') > 0) { |
| 76 | this.emit('error', wrapped) |
| 77 | } else { |
| 78 | process.emitWarning(wrapped.message, 'BiDiProtocolWarning') |
| 79 | } |
| 80 | return |
| 81 | } |
| 82 | // Messages without a numeric id are BiDi events, not command responses. |
| 83 | // Re-emit them on this EventEmitter by method name (e.g. |
| 84 | // 'browsingContext.contextCreated') so that generated domain classes can |
| 85 | // subscribe via bidi.on(methodName, callback) instead of each attaching |
| 86 | // a new raw ws.on('message', ...) listener. The existing hand-written |
| 87 | // modules (logInspector, network, etc.) continue to use their own |
| 88 | // ws.on('message', ...) listeners unchanged — this emission is purely |
| 89 | // additive and does not affect those code paths. |
| 90 | if (payload == null || typeof payload.id !== 'number') { |