(ws: WebSocket, text: string, options)
| 99 | }); |
| 100 | } |
| 101 | |
| 102 | #sendMessageToWebSocket(ws: WebSocket, text: string, options): Promise<void> { |
| 103 | return (new Promise<void>((resolve, reject) => { |
| 104 | rejectOnWebSocketError(ws, reject, options.signal); |
| 105 | ws.on('message', (data) => { |
| 106 | // Handle received messages from BingChat. |
| 107 | const events = data.toString() |
| 108 | .split(nullChar) |
| 109 | .filter(s => s != '') |
| 110 | .map(s => JSON.parse(s)); |
| 111 | for (const event of events) { |
| 112 | if (event.type == 1) { |
| 113 | // Updates. |
| 114 | if (!event.arguments[0].messages) |
| 115 | continue; |
| 116 | this.#handlePayload(event.arguments[0].messages[0], options); |
| 117 | } else if (event.type == 2) { |
| 118 | // Possible denied service. |
| 119 | if (event.item.result.value != 'Success') { |
| 120 | const error = new APIError(event.item.result.message); |
| 121 | if (event.item.result.value == 'InvalidSession') |
| 122 | error.code = 'invalid-session'; |
| 123 | reject(error); |
| 124 | return; |
| 125 | } |
| 126 | const message = event.item.messages[event.item.messages.length - 1]; |
| 127 | if (message['hiddenText']?.includes('Conversation disengaged.')) |
| 128 | reject(new APIError('Conversation disengaged.')); |
| 129 | else if (event.item.messages.find(m => m.contentOrigin == 'TurnLimiter')) |
| 130 | reject(new APIError('Chat turn limit has been reached.')); |
| 131 | } else if (event.type == 3) { |
| 132 | // Finished. |
| 133 | resolve(); |
| 134 | } |
| 135 | } |
| 136 | }); |
| 137 | // Send the message to BingChat. |
| 138 | const params = { |
| 139 | type: 4, |
| 140 | target: 'chat', |
| 141 | invocationId: String(this.session.invocationId), |
| 142 | arguments: [ |
| 143 | { |
| 144 | ...chatArgument, |
| 145 | traceId: crypto.randomBytes(16).toString('hex'), |
| 146 | isStartOfSession: this.session.invocationId == 0, |
| 147 | message: { |
| 148 | messageType: 'Chat', |
| 149 | author: 'user', |
| 150 | text, |
| 151 | }, |
| 152 | conversationSignature: this.session.conversationSignature, |
| 153 | participant: {id: this.session.clientId}, |
| 154 | conversationId: this.session.conversationId, |
| 155 | }, |
| 156 | ], |
| 157 | }; |
| 158 | params.arguments[0].optionsSets.push(this.getParam('tone')); |
no test coverage detected