@tencent-connect/qqbot-nodejs 1.0.4 → 1.0.5
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/CHANGELOG.md +96 -0
- package/LICENSE +21 -0
- package/README.md +167 -86
- package/README.zh-CN.md +280 -0
- package/USAGE.md +80 -27
- package/dist/QQBot.d.ts +33 -3
- package/dist/QQBot.d.ts.map +1 -1
- package/dist/QQBot.js +84 -34
- package/dist/QQBot.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/protocol/api/token.d.ts.map +1 -1
- package/dist/protocol/api/token.js +6 -2
- package/dist/protocol/api/token.js.map +1 -1
- package/dist/protocol/gateway/constants.d.ts +6 -1
- package/dist/protocol/gateway/constants.d.ts.map +1 -1
- package/dist/protocol/gateway/constants.js +6 -1
- package/dist/protocol/gateway/constants.js.map +1 -1
- package/dist/protocol/gateway/errors.d.ts +22 -0
- package/dist/protocol/gateway/errors.d.ts.map +1 -0
- package/dist/protocol/gateway/errors.js +24 -0
- package/dist/protocol/gateway/errors.js.map +1 -0
- package/dist/protocol/gateway/gateway-connection.d.ts +45 -4
- package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -1
- package/dist/protocol/gateway/gateway-connection.js +252 -143
- package/dist/protocol/gateway/gateway-connection.js.map +1 -1
- package/dist/protocol/gateway/reconnect.d.ts +24 -1
- package/dist/protocol/gateway/reconnect.d.ts.map +1 -1
- package/dist/protocol/gateway/reconnect.js +42 -6
- package/dist/protocol/gateway/reconnect.js.map +1 -1
- package/dist/protocol/index.d.ts +4 -3
- package/dist/protocol/index.d.ts.map +1 -1
- package/dist/protocol/index.js +3 -2
- package/dist/protocol/index.js.map +1 -1
- package/dist/protocol/utils/file-utils.d.ts +2 -2
- package/dist/protocol/utils/file-utils.js +2 -2
- package/dist/protocol/utils/image-size.d.ts +3 -3
- package/dist/protocol/utils/image-size.js +3 -3
- package/dist/protocol/utils/ref-index-store.d.ts +1 -1
- package/dist/protocol/utils/ref-index-store.js +1 -1
- package/package.json +23 -7
- package/src/QQBot.ts +93 -37
- package/src/index.ts +5 -0
- package/src/protocol/api/token.ts +6 -2
- package/src/protocol/gateway/constants.ts +6 -1
- package/src/protocol/gateway/errors.ts +32 -0
- package/src/protocol/gateway/gateway-connection.ts +288 -157
- package/src/protocol/gateway/reconnect.ts +61 -7
- package/src/protocol/index.ts +10 -1
- package/src/protocol/utils/file-utils.ts +2 -2
- package/src/protocol/utils/image-size.ts +3 -3
- package/src/protocol/utils/ref-index-store.ts +1 -1
|
@@ -151,12 +151,16 @@ export class TokenManager {
|
|
|
151
151
|
}
|
|
152
152
|
}
|
|
153
153
|
|
|
154
|
-
|
|
154
|
+
// Only release the slot we own: a stop→start cycle may already have
|
|
155
|
+
// registered a replacement loop for the same appId.
|
|
156
|
+
if (this.refreshControllers.get(appId) === controller) {
|
|
157
|
+
this.refreshControllers.delete(appId);
|
|
158
|
+
}
|
|
155
159
|
this.logger?.info?.(`[qqbot:token:${appId}] Background refresh stopped`);
|
|
156
160
|
};
|
|
157
161
|
|
|
158
162
|
loop().catch((err) => {
|
|
159
|
-
if (this.refreshControllers.
|
|
163
|
+
if (this.refreshControllers.get(appId) === controller) {
|
|
160
164
|
this.refreshControllers.delete(appId);
|
|
161
165
|
this.logger?.error?.(
|
|
162
166
|
`[qqbot:token:${appId}] Background refresh crashed: ${formatErrorMessage(err)}`,
|
|
@@ -25,9 +25,14 @@ export const FULL_INTENTS =
|
|
|
25
25
|
|
|
26
26
|
export const RECONNECT_DELAYS = [1000, 2000, 5000, 10000, 30000, 60000] as const;
|
|
27
27
|
export const RATE_LIMIT_DELAY = 60000;
|
|
28
|
-
|
|
28
|
+
/** Default reconnect budget: unlimited. Set `reconnect.maxAttempts` to bound it. */
|
|
29
|
+
export const MAX_RECONNECT_ATTEMPTS = Number.POSITIVE_INFINITY;
|
|
29
30
|
export const MAX_QUICK_DISCONNECT_COUNT = 3;
|
|
30
31
|
export const QUICK_DISCONNECT_THRESHOLD = 5000;
|
|
32
|
+
/** Delay before reconnecting after opcode 9 (INVALID_SESSION). */
|
|
33
|
+
export const INVALID_SESSION_DELAY = 3000;
|
|
34
|
+
/** Default WebSocket upgrade timeout; bounds black-holed handshakes. */
|
|
35
|
+
export const HANDSHAKE_TIMEOUT_MS = 30_000;
|
|
31
36
|
|
|
32
37
|
/** Gateway opcodes used by the QQ Bot WebSocket protocol. */
|
|
33
38
|
export const GatewayOp = {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal gateway errors — the reasons a {@link GatewayConnection} stops
|
|
3
|
+
* retrying and rejects its `start()` promise.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Stable error codes. Match on `code` rather than `instanceof` across module copies. */
|
|
7
|
+
export const GatewayErrorCode = {
|
|
8
|
+
/** A finite `reconnect.maxAttempts` was exhausted (never raised with the unlimited default). */
|
|
9
|
+
RETRY_EXHAUSTED: "GATEWAY_RETRY_EXHAUSTED",
|
|
10
|
+
/** Non-retryable close (4914 offline/sandbox-only, 4915 banned). Needs operator action. */
|
|
11
|
+
FATAL_CLOSE: "GATEWAY_FATAL_CLOSE",
|
|
12
|
+
} as const;
|
|
13
|
+
export type GatewayErrorCode = (typeof GatewayErrorCode)[keyof typeof GatewayErrorCode];
|
|
14
|
+
|
|
15
|
+
/** Error used to reject `GatewayConnection.start()` / `QQBot.start()`. */
|
|
16
|
+
export class GatewayError extends Error {
|
|
17
|
+
readonly code: GatewayErrorCode;
|
|
18
|
+
/** Remote WebSocket close code that caused the failure, when known. */
|
|
19
|
+
readonly closeCode?: number;
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
message: string,
|
|
23
|
+
code: GatewayErrorCode,
|
|
24
|
+
closeCode?: number,
|
|
25
|
+
options?: { cause?: unknown },
|
|
26
|
+
) {
|
|
27
|
+
super(message, options);
|
|
28
|
+
this.name = "GatewayError";
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.closeCode = closeCode;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -8,14 +8,28 @@
|
|
|
8
8
|
* (delegated via callbacks), business policies, message queueing.
|
|
9
9
|
*
|
|
10
10
|
* All state injected through the constructor — no module-level globals.
|
|
11
|
+
*
|
|
12
|
+
* Lifecycle invariants:
|
|
13
|
+
* - State transitions (reconnect scheduling / settling) happen before any
|
|
14
|
+
* user callback is notified, and every callback is isolated, so a throwing
|
|
15
|
+
* handler can never stall the loop.
|
|
16
|
+
* - Terminal failures are reported once, by rejecting `start()`.
|
|
11
17
|
*/
|
|
12
18
|
|
|
13
19
|
import WebSocket from "ws";
|
|
14
20
|
import type { GatewayAccount, InteractionEvent, Logger, WSPayload } from "../types.js";
|
|
15
21
|
import { decodeGatewayMessageData } from "./codec.js";
|
|
16
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
FULL_INTENTS,
|
|
24
|
+
GatewayCloseCode,
|
|
25
|
+
GatewayOp,
|
|
26
|
+
HANDSHAKE_TIMEOUT_MS,
|
|
27
|
+
INVALID_SESSION_DELAY,
|
|
28
|
+
RATE_LIMIT_DELAY,
|
|
29
|
+
} from "./constants.js";
|
|
30
|
+
import { GatewayError, GatewayErrorCode } from "./errors.js";
|
|
17
31
|
import { dispatchEvent, type InboundMessage } from "./event-dispatcher.js";
|
|
18
|
-
import { ReconnectState } from "./reconnect.js";
|
|
32
|
+
import { ReconnectState, type ReconnectPolicy } from "./reconnect.js";
|
|
19
33
|
|
|
20
34
|
/** Persisted session info for RESUME after reconnection. */
|
|
21
35
|
export interface PersistedSession {
|
|
@@ -30,6 +44,15 @@ export interface SessionPersistencePort {
|
|
|
30
44
|
clear: () => void;
|
|
31
45
|
}
|
|
32
46
|
|
|
47
|
+
/** A transport disconnect, reported before any reconnect attempt. */
|
|
48
|
+
export interface GatewayDisconnect {
|
|
49
|
+
/** Remote close code; `1000` for gateway-requested reconnects (opcode 7 / 9). */
|
|
50
|
+
code: number;
|
|
51
|
+
reason: string;
|
|
52
|
+
/** `false` means the retry budget is spent or the close is fatal; `start()` is about to reject. */
|
|
53
|
+
willReconnect: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
33
56
|
export interface GatewayConnectionOptions {
|
|
34
57
|
account: GatewayAccount;
|
|
35
58
|
abortSignal: AbortSignal;
|
|
@@ -51,18 +74,27 @@ export interface GatewayConnectionOptions {
|
|
|
51
74
|
/** Custom intent mask. Defaults to FULL_INTENTS. */
|
|
52
75
|
intents?: number;
|
|
53
76
|
|
|
77
|
+
/** Reconnect budget. Unlimited by default; set `maxAttempts` when an outer supervisor owns restarts. */
|
|
78
|
+
reconnect?: Partial<ReconnectPolicy>;
|
|
79
|
+
/** WebSocket upgrade timeout in ms. Defaults to {@link HANDSHAKE_TIMEOUT_MS}. */
|
|
80
|
+
handshakeTimeoutMs?: number;
|
|
81
|
+
|
|
54
82
|
// ---- Event handlers ----
|
|
55
83
|
onReady?: (data: unknown) => void;
|
|
56
84
|
onResumed?: (data: unknown) => void;
|
|
85
|
+
/** Recoverable failures (connect errors, socket errors). Terminal failures reject `start()` instead. */
|
|
57
86
|
onError?: (error: Error) => void;
|
|
87
|
+
onDisconnected?: (event: GatewayDisconnect) => void;
|
|
58
88
|
onMessage: (msg: InboundMessage) => void | Promise<void>;
|
|
59
89
|
onInteraction?: (event: InteractionEvent) => void | Promise<void>;
|
|
60
90
|
onRawEvent?: (type: string, data: unknown) => void | Promise<void>;
|
|
61
91
|
}
|
|
62
92
|
|
|
63
|
-
/** Pure-protocol gateway connection. */
|
|
93
|
+
/** Pure-protocol gateway connection. Single-use: create a new instance to restart. */
|
|
64
94
|
export class GatewayConnection {
|
|
65
95
|
private isAborted = false;
|
|
96
|
+
private run: Promise<void> | null = null;
|
|
97
|
+
private finish: (error?: Error) => void = () => {};
|
|
66
98
|
private currentWs: WebSocket | null = null;
|
|
67
99
|
private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
|
|
68
100
|
private sessionId: string | null = null;
|
|
@@ -77,19 +109,48 @@ export class GatewayConnection {
|
|
|
77
109
|
|
|
78
110
|
constructor(opts: GatewayConnectionOptions) {
|
|
79
111
|
this.opts = opts;
|
|
80
|
-
this.reconnect = new ReconnectState(opts.account.accountId, opts.log);
|
|
112
|
+
this.reconnect = new ReconnectState(opts.account.accountId, opts.log, opts.reconnect);
|
|
81
113
|
const ua = opts.userAgent ?? "qqbot-nodejs/unknown";
|
|
82
114
|
this.resolveUserAgent = typeof ua === "function" ? ua : () => ua;
|
|
83
115
|
}
|
|
84
116
|
|
|
85
|
-
/**
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
117
|
+
/**
|
|
118
|
+
* Start the connection loop.
|
|
119
|
+
*
|
|
120
|
+
* Resolves when `abortSignal` fires. Rejects with a {@link GatewayError} when
|
|
121
|
+
* a finite reconnect budget is exhausted (`RETRY_EXHAUSTED`) or the gateway sends
|
|
122
|
+
* a non-retryable close (`FATAL_CLOSE`). Repeated calls return the same promise.
|
|
123
|
+
*/
|
|
124
|
+
start(): Promise<void> {
|
|
125
|
+
this.run ??= new Promise<void>((resolve, reject) => {
|
|
126
|
+
const signal = this.opts.abortSignal;
|
|
127
|
+
const onAbort = () => this.finish();
|
|
128
|
+
this.finish = (error) => {
|
|
129
|
+
if (this.isAborted) return;
|
|
130
|
+
this.isAborted = true;
|
|
131
|
+
signal.removeEventListener("abort", onAbort);
|
|
132
|
+
this.clearReconnectTimer();
|
|
133
|
+
this.cleanup();
|
|
134
|
+
if (error) {
|
|
135
|
+
reject(error);
|
|
136
|
+
} else {
|
|
137
|
+
resolve();
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
if (signal.aborted) {
|
|
141
|
+
this.finish();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
145
|
+
try {
|
|
146
|
+
this.restoreSession();
|
|
147
|
+
} catch (error) {
|
|
148
|
+
this.finish(toError(error));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
void this.connect();
|
|
92
152
|
});
|
|
153
|
+
return this.run;
|
|
93
154
|
}
|
|
94
155
|
|
|
95
156
|
// ============ Session persistence ============
|
|
@@ -106,63 +167,92 @@ export class GatewayConnection {
|
|
|
106
167
|
}
|
|
107
168
|
|
|
108
169
|
private saveCurrentSession(): void {
|
|
109
|
-
|
|
170
|
+
const { session } = this.opts;
|
|
171
|
+
if (!this.sessionId || !session) {
|
|
110
172
|
return;
|
|
111
173
|
}
|
|
112
|
-
this.
|
|
113
|
-
|
|
114
|
-
lastSeq: this.lastSeq,
|
|
115
|
-
});
|
|
174
|
+
const snapshot = { sessionId: this.sessionId, lastSeq: this.lastSeq };
|
|
175
|
+
this.notify("session.save", () => session.save(snapshot));
|
|
116
176
|
}
|
|
117
177
|
|
|
118
|
-
|
|
178
|
+
private resetSession(): void {
|
|
179
|
+
this.sessionId = null;
|
|
180
|
+
this.lastSeq = null;
|
|
181
|
+
const { session } = this.opts;
|
|
182
|
+
if (session) this.notify("session.clear", () => session.clear());
|
|
183
|
+
}
|
|
119
184
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
}
|
|
185
|
+
// ============ Callbacks + cleanup ============
|
|
186
|
+
|
|
187
|
+
/** Invoke a user callback without letting sync throws or async rejections escape. */
|
|
188
|
+
private notify(name: string, invoke: () => unknown): void {
|
|
189
|
+
const report = (err: unknown) => {
|
|
190
|
+
this.opts.log?.error(
|
|
191
|
+
`[${this.opts.account.accountId}] ${name} handler threw: ${toError(err).message}`,
|
|
192
|
+
);
|
|
193
|
+
};
|
|
194
|
+
try {
|
|
195
|
+
const result = invoke();
|
|
196
|
+
if (isPromiseLike(result)) Promise.resolve(result).catch(report);
|
|
197
|
+
} catch (err) {
|
|
198
|
+
report(err);
|
|
199
|
+
}
|
|
129
200
|
}
|
|
130
201
|
|
|
202
|
+
/** Release the socket and heartbeat. Emits nothing. */
|
|
131
203
|
private cleanup(): void {
|
|
132
204
|
if (this.heartbeatInterval) {
|
|
133
205
|
clearInterval(this.heartbeatInterval);
|
|
134
206
|
this.heartbeatInterval = null;
|
|
135
207
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
(this.currentWs.readyState === WebSocket.OPEN ||
|
|
139
|
-
this.currentWs.readyState === WebSocket.CONNECTING)
|
|
140
|
-
) {
|
|
141
|
-
this.currentWs.close();
|
|
142
|
-
}
|
|
208
|
+
const ws = this.currentWs;
|
|
209
|
+
// Retire ownership before close: ws can emit error/close after a replacement exists.
|
|
143
210
|
this.currentWs = null;
|
|
211
|
+
this.isConnecting = false;
|
|
212
|
+
if (ws && ws.readyState !== WebSocket.CLOSED) ws.terminate();
|
|
144
213
|
}
|
|
145
214
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
private scheduleReconnect(customDelay?: number): void {
|
|
149
|
-
if (this.isAborted || this.reconnect.isExhausted()) {
|
|
150
|
-
this.opts.log?.error(
|
|
151
|
-
`[${this.opts.account.accountId}] Max reconnect attempts reached or aborted`,
|
|
152
|
-
);
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
215
|
+
private clearReconnectTimer(): void {
|
|
155
216
|
if (this.reconnectTimer) {
|
|
156
217
|
clearTimeout(this.reconnectTimer);
|
|
157
218
|
this.reconnectTimer = null;
|
|
158
219
|
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ============ Reconnect ============
|
|
223
|
+
|
|
224
|
+
/** Schedule the next attempt, or return the terminal error when the budget is spent. */
|
|
225
|
+
private planReconnect(
|
|
226
|
+
customDelay?: number,
|
|
227
|
+
failure: { closeCode?: number; cause?: unknown } = {},
|
|
228
|
+
): GatewayError | null {
|
|
229
|
+
if (this.reconnect.isExhausted()) {
|
|
230
|
+
const error = new GatewayError(
|
|
231
|
+
`Max reconnect attempts reached (${this.reconnect.maxAttempts})`,
|
|
232
|
+
GatewayErrorCode.RETRY_EXHAUSTED,
|
|
233
|
+
failure.closeCode,
|
|
234
|
+
{ cause: failure.cause },
|
|
235
|
+
);
|
|
236
|
+
this.opts.log?.error(`[${this.opts.account.accountId}] ${error.message}`);
|
|
237
|
+
return error;
|
|
238
|
+
}
|
|
239
|
+
this.clearReconnectTimer();
|
|
159
240
|
const delay = this.reconnect.getNextDelay(customDelay);
|
|
160
241
|
this.reconnectTimer = setTimeout(() => {
|
|
161
242
|
this.reconnectTimer = null;
|
|
162
|
-
|
|
163
|
-
void this.connect();
|
|
164
|
-
}
|
|
243
|
+
void this.connect();
|
|
165
244
|
}, delay);
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Report a disconnect after the reconnect decision is made, then settle if terminal. */
|
|
249
|
+
private afterDisconnect(code: number, reason: string, terminal: GatewayError | null): void {
|
|
250
|
+
const { onDisconnected } = this.opts;
|
|
251
|
+
if (onDisconnected) {
|
|
252
|
+
const event: GatewayDisconnect = { code, reason, willReconnect: terminal === null };
|
|
253
|
+
this.notify("onDisconnected", () => onDisconnected(event));
|
|
254
|
+
}
|
|
255
|
+
if (terminal) this.finish(terminal);
|
|
166
256
|
}
|
|
167
257
|
|
|
168
258
|
// ============ Connect ============
|
|
@@ -170,14 +260,15 @@ export class GatewayConnection {
|
|
|
170
260
|
private async connect(): Promise<void> {
|
|
171
261
|
const { log, account } = this.opts;
|
|
172
262
|
|
|
263
|
+
if (this.isAborted) return;
|
|
173
264
|
if (this.isConnecting) {
|
|
174
265
|
log?.debug?.(`[${account.accountId}] Already connecting, skip`);
|
|
175
266
|
return;
|
|
176
267
|
}
|
|
268
|
+
this.cleanup();
|
|
177
269
|
this.isConnecting = true;
|
|
178
270
|
|
|
179
271
|
try {
|
|
180
|
-
this.cleanup();
|
|
181
272
|
if (this.shouldRefreshToken) {
|
|
182
273
|
log?.debug?.(`[${account.accountId}] Refreshing token...`);
|
|
183
274
|
this.opts.clearTokenCache?.();
|
|
@@ -185,118 +276,139 @@ export class GatewayConnection {
|
|
|
185
276
|
}
|
|
186
277
|
|
|
187
278
|
const accessToken = await this.opts.getAccessToken();
|
|
279
|
+
if (this.isAborted) return;
|
|
188
280
|
log?.info(`[${account.accountId}] ✅ Access token obtained`);
|
|
189
281
|
const gatewayUrl = await this.opts.getGatewayUrl(accessToken);
|
|
282
|
+
if (this.isAborted) return;
|
|
190
283
|
log?.info(`[${account.accountId}] Connecting to ${gatewayUrl}`);
|
|
191
284
|
|
|
192
|
-
|
|
193
|
-
headers: { "User-Agent": this.resolveUserAgent() },
|
|
194
|
-
});
|
|
195
|
-
this.currentWs = ws;
|
|
196
|
-
|
|
197
|
-
ws.on("open", () => {
|
|
198
|
-
log?.info(`[${account.accountId}] WebSocket connected`);
|
|
199
|
-
this.isConnecting = false;
|
|
200
|
-
this.reconnect.onConnected();
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
ws.on("message", async (data) => {
|
|
204
|
-
try {
|
|
205
|
-
const rawData = decodeGatewayMessageData(data);
|
|
206
|
-
const payload = JSON.parse(rawData) as WSPayload;
|
|
207
|
-
const { op, d, s, t } = payload;
|
|
208
|
-
|
|
209
|
-
if (s) {
|
|
210
|
-
this.lastSeq = s;
|
|
211
|
-
this.saveCurrentSession();
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
switch (op) {
|
|
215
|
-
case GatewayOp.HELLO:
|
|
216
|
-
this.handleHello(ws, d, accessToken);
|
|
217
|
-
break;
|
|
218
|
-
|
|
219
|
-
case GatewayOp.DISPATCH: {
|
|
220
|
-
log?.debug?.(
|
|
221
|
-
`[${account.accountId}] Dispatch event: t=${t} payload=${previewPayload(d)}`,
|
|
222
|
-
);
|
|
223
|
-
const result = dispatchEvent(t ?? "", d, account.accountId, log);
|
|
224
|
-
if (result.action === "ready") {
|
|
225
|
-
this.sessionId = result.sessionId;
|
|
226
|
-
this.saveCurrentSession();
|
|
227
|
-
this.opts.onReady?.(result.data);
|
|
228
|
-
} else if (result.action === "resumed") {
|
|
229
|
-
(this.opts.onResumed ?? this.opts.onReady)?.(result.data);
|
|
230
|
-
this.saveCurrentSession();
|
|
231
|
-
} else if (result.action === "interaction") {
|
|
232
|
-
// Interaction 有 handler → 调用;否则 fallback 到 rawEvent
|
|
233
|
-
if (this.opts.onInteraction) {
|
|
234
|
-
void Promise.resolve(this.opts.onInteraction(result.event));
|
|
235
|
-
} else if (this.opts.onRawEvent) {
|
|
236
|
-
void Promise.resolve(this.opts.onRawEvent(payload.t!, payload.d));
|
|
237
|
-
}
|
|
238
|
-
} else if (result.action === "message") {
|
|
239
|
-
void Promise.resolve(this.opts.onMessage(result.msg));
|
|
240
|
-
} else if (result.action === "raw") {
|
|
241
|
-
if (this.opts.onRawEvent) {
|
|
242
|
-
void Promise.resolve(this.opts.onRawEvent(result.type, result.data));
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
break;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
case GatewayOp.HEARTBEAT_ACK:
|
|
249
|
-
break;
|
|
250
|
-
|
|
251
|
-
case GatewayOp.RECONNECT:
|
|
252
|
-
this.cleanup();
|
|
253
|
-
this.scheduleReconnect();
|
|
254
|
-
break;
|
|
255
|
-
|
|
256
|
-
case GatewayOp.INVALID_SESSION: {
|
|
257
|
-
const canResume = d as boolean;
|
|
258
|
-
if (!canResume) {
|
|
259
|
-
this.sessionId = null;
|
|
260
|
-
this.lastSeq = null;
|
|
261
|
-
this.opts.session?.clear();
|
|
262
|
-
this.shouldRefreshToken = true;
|
|
263
|
-
}
|
|
264
|
-
this.cleanup();
|
|
265
|
-
this.scheduleReconnect(3000);
|
|
266
|
-
break;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
} catch (err) {
|
|
270
|
-
log?.error(
|
|
271
|
-
`[${account.accountId}] Message parse error: ${err instanceof Error ? err.message : String(err)}`,
|
|
272
|
-
);
|
|
273
|
-
}
|
|
274
|
-
});
|
|
275
|
-
|
|
276
|
-
ws.on("close", (code, reason) => {
|
|
277
|
-
log?.info(`[${account.accountId}] WebSocket closed: ${code} ${reason.toString()}`);
|
|
278
|
-
this.isConnecting = false;
|
|
279
|
-
this.handleClose(code);
|
|
280
|
-
});
|
|
281
|
-
|
|
282
|
-
ws.on("error", (err) => {
|
|
283
|
-
log?.error(`[${account.accountId}] WebSocket error: ${err.message}`);
|
|
284
|
-
this.opts.onError?.(err);
|
|
285
|
-
});
|
|
285
|
+
this.openSocket(gatewayUrl, accessToken);
|
|
286
286
|
} catch (err) {
|
|
287
|
+
if (this.isAborted) return;
|
|
287
288
|
this.isConnecting = false;
|
|
288
|
-
const
|
|
289
|
-
log?.error(`[${account.accountId}] Connection failed: ${
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
}
|
|
289
|
+
const error = toError(err);
|
|
290
|
+
log?.error(`[${account.accountId}] Connection failed: ${error.message}`);
|
|
291
|
+
const terminal = this.planReconnect(
|
|
292
|
+
isRateLimitError(error.message) ? RATE_LIMIT_DELAY : undefined,
|
|
293
|
+
{ cause: error },
|
|
294
|
+
);
|
|
295
|
+
const { onError } = this.opts;
|
|
296
|
+
if (onError) this.notify("onError", () => onError(error));
|
|
297
|
+
if (terminal) this.finish(terminal);
|
|
295
298
|
}
|
|
296
299
|
}
|
|
297
300
|
|
|
301
|
+
private openSocket(gatewayUrl: string, accessToken: string): void {
|
|
302
|
+
const { log, account } = this.opts;
|
|
303
|
+
const ws = new WebSocket(gatewayUrl, {
|
|
304
|
+
headers: { "User-Agent": this.resolveUserAgent() },
|
|
305
|
+
handshakeTimeout: this.opts.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS,
|
|
306
|
+
});
|
|
307
|
+
this.currentWs = ws;
|
|
308
|
+
|
|
309
|
+
ws.on("open", () => {
|
|
310
|
+
if (ws !== this.currentWs) return;
|
|
311
|
+
log?.info(`[${account.accountId}] WebSocket connected`);
|
|
312
|
+
this.isConnecting = false;
|
|
313
|
+
this.reconnect.onSocketOpen();
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
ws.on("message", (data) => {
|
|
317
|
+
if (ws !== this.currentWs) return;
|
|
318
|
+
try {
|
|
319
|
+
const payload = JSON.parse(decodeGatewayMessageData(data)) as WSPayload;
|
|
320
|
+
this.handlePayload(ws, payload, accessToken);
|
|
321
|
+
} catch (err) {
|
|
322
|
+
log?.error(`[${account.accountId}] Message parse error: ${toError(err).message}`);
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
ws.on("close", (code, reason) => {
|
|
327
|
+
if (ws !== this.currentWs) return;
|
|
328
|
+
const reasonText = reason.toString();
|
|
329
|
+
log?.info(`[${account.accountId}] WebSocket closed: ${code} ${reasonText}`);
|
|
330
|
+
this.isConnecting = false;
|
|
331
|
+
this.handleClose(code, reasonText);
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
ws.on("error", (err) => {
|
|
335
|
+
if (ws !== this.currentWs) return;
|
|
336
|
+
log?.error(`[${account.accountId}] WebSocket error: ${err.message}`);
|
|
337
|
+
const { onError } = this.opts;
|
|
338
|
+
if (onError) this.notify("onError", () => onError(err));
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
298
342
|
// ============ Protocol handlers ============
|
|
299
343
|
|
|
344
|
+
private handlePayload(ws: WebSocket, payload: WSPayload, accessToken: string): void {
|
|
345
|
+
const { op, d, s } = payload;
|
|
346
|
+
|
|
347
|
+
if (s) {
|
|
348
|
+
this.lastSeq = s;
|
|
349
|
+
this.saveCurrentSession();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
switch (op) {
|
|
353
|
+
case GatewayOp.HELLO:
|
|
354
|
+
this.handleHello(ws, d, accessToken);
|
|
355
|
+
break;
|
|
356
|
+
|
|
357
|
+
case GatewayOp.DISPATCH:
|
|
358
|
+
this.handleDispatch(payload);
|
|
359
|
+
break;
|
|
360
|
+
|
|
361
|
+
case GatewayOp.HEARTBEAT_ACK:
|
|
362
|
+
break;
|
|
363
|
+
|
|
364
|
+
case GatewayOp.RECONNECT:
|
|
365
|
+
this.handleGatewayReconnect("Gateway requested reconnect");
|
|
366
|
+
break;
|
|
367
|
+
|
|
368
|
+
case GatewayOp.INVALID_SESSION:
|
|
369
|
+
// d = whether the session can be resumed
|
|
370
|
+
if (!d) {
|
|
371
|
+
this.resetSession();
|
|
372
|
+
this.shouldRefreshToken = true;
|
|
373
|
+
}
|
|
374
|
+
this.handleGatewayReconnect("Invalid gateway session", INVALID_SESSION_DELAY);
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private handleDispatch(payload: WSPayload): void {
|
|
380
|
+
const { log, account } = this.opts;
|
|
381
|
+
const { d, t } = payload;
|
|
382
|
+
log?.debug?.(`[${account.accountId}] Dispatch event: t=${t} payload=${previewPayload(d)}`);
|
|
383
|
+
const result = dispatchEvent(t ?? "", d, account.accountId, log);
|
|
384
|
+
|
|
385
|
+
if (result.action === "ready") {
|
|
386
|
+
this.sessionId = result.sessionId;
|
|
387
|
+
this.reconnect.onConnected();
|
|
388
|
+
this.saveCurrentSession();
|
|
389
|
+
const { onReady } = this.opts;
|
|
390
|
+
if (onReady) this.notify("onReady", () => onReady(result.data));
|
|
391
|
+
} else if (result.action === "resumed") {
|
|
392
|
+
this.reconnect.onConnected();
|
|
393
|
+
this.saveCurrentSession();
|
|
394
|
+
const onResumed = this.opts.onResumed ?? this.opts.onReady;
|
|
395
|
+
if (onResumed) this.notify("onResumed", () => onResumed(result.data));
|
|
396
|
+
} else if (result.action === "interaction") {
|
|
397
|
+
// Interaction 有 handler → 调用;否则 fallback 到 rawEvent
|
|
398
|
+
const { onInteraction, onRawEvent } = this.opts;
|
|
399
|
+
if (onInteraction) {
|
|
400
|
+
this.notify("onInteraction", () => onInteraction(result.event));
|
|
401
|
+
} else if (onRawEvent) {
|
|
402
|
+
this.notify("onRawEvent", () => onRawEvent(t ?? "", d));
|
|
403
|
+
}
|
|
404
|
+
} else if (result.action === "message") {
|
|
405
|
+
this.notify("onMessage", () => this.opts.onMessage(result.msg));
|
|
406
|
+
} else if (result.action === "raw") {
|
|
407
|
+
const { onRawEvent } = this.opts;
|
|
408
|
+
if (onRawEvent) this.notify("onRawEvent", () => onRawEvent(result.type, result.data));
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
300
412
|
private handleHello(ws: WebSocket, d: unknown, accessToken: string): void {
|
|
301
413
|
const intents = this.opts.intents ?? FULL_INTENTS;
|
|
302
414
|
if (this.sessionId && this.lastSeq !== null) {
|
|
@@ -334,13 +446,18 @@ export class GatewayConnection {
|
|
|
334
446
|
}, interval);
|
|
335
447
|
}
|
|
336
448
|
|
|
337
|
-
|
|
449
|
+
/** Opcode 7 / 9: drop the socket locally and reconnect. */
|
|
450
|
+
private handleGatewayReconnect(reason: string, customDelay?: number): void {
|
|
451
|
+
this.cleanup();
|
|
452
|
+
const terminal = this.planReconnect(customDelay);
|
|
453
|
+
this.afterDisconnect(GatewayCloseCode.NORMAL, reason, terminal);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
private handleClose(code: number, reason: string): void {
|
|
338
457
|
const action = this.reconnect.handleClose(code, this.isAborted);
|
|
339
458
|
|
|
340
459
|
if (action.clearSession) {
|
|
341
|
-
this.
|
|
342
|
-
this.lastSeq = null;
|
|
343
|
-
this.opts.session?.clear();
|
|
460
|
+
this.resetSession();
|
|
344
461
|
}
|
|
345
462
|
if (action.refreshToken) {
|
|
346
463
|
this.shouldRefreshToken = true;
|
|
@@ -348,15 +465,29 @@ export class GatewayConnection {
|
|
|
348
465
|
|
|
349
466
|
this.cleanup();
|
|
350
467
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
468
|
+
const terminal = action.shouldReconnect
|
|
469
|
+
? this.planReconnect(action.reconnectDelay, { closeCode: code })
|
|
470
|
+
: new GatewayError(
|
|
471
|
+
`Gateway closed (${code}): ${action.reason}`,
|
|
472
|
+
GatewayErrorCode.FATAL_CLOSE,
|
|
473
|
+
code,
|
|
474
|
+
);
|
|
475
|
+
this.afterDisconnect(code, reason, terminal);
|
|
357
476
|
}
|
|
358
477
|
}
|
|
359
478
|
|
|
479
|
+
function toError(err: unknown): Error {
|
|
480
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
484
|
+
return typeof (value as PromiseLike<unknown> | null)?.then === "function";
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function isRateLimitError(message: string): boolean {
|
|
488
|
+
return message.includes("Too many requests") || message.includes("100001");
|
|
489
|
+
}
|
|
490
|
+
|
|
360
491
|
/**
|
|
361
492
|
* Serialize a gateway event payload for debug logging.
|
|
362
493
|
*
|