@tencent-connect/qqbot-nodejs 1.0.5 → 1.0.6
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 +18 -0
- package/README.md +14 -0
- package/README.zh-CN.md +13 -0
- package/assets/docs/feedback.jpg +0 -0
- package/assets/docs/qqchannel.jpg +0 -0
- package/dist/QQBot.d.ts +33 -0
- package/dist/QQBot.d.ts.map +1 -1
- package/dist/QQBot.js +62 -1
- package/dist/QQBot.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/protocol/gateway/event-dispatcher.d.ts +22 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -1
- package/dist/protocol/gateway/event-dispatcher.js +17 -0
- package/dist/protocol/gateway/event-dispatcher.js.map +1 -1
- package/dist/protocol/gateway/gateway-connection.d.ts +24 -0
- package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -1
- package/dist/protocol/gateway/gateway-connection.js +99 -5
- package/dist/protocol/gateway/gateway-connection.js.map +1 -1
- package/dist/protocol/gateway/reconnect.d.ts.map +1 -1
- package/dist/protocol/gateway/reconnect.js +14 -3
- package/dist/protocol/gateway/reconnect.js.map +1 -1
- package/dist/protocol/index.d.ts +1 -1
- package/dist/protocol/index.d.ts.map +1 -1
- package/dist/protocol/index.js.map +1 -1
- package/dist/protocol/types.d.ts +49 -10
- package/dist/protocol/types.d.ts.map +1 -1
- package/dist/protocol/types.js.map +1 -1
- package/package.json +2 -1
- package/src/QQBot.ts +82 -1
- package/src/index.ts +1 -0
- package/src/protocol/gateway/event-dispatcher.ts +41 -0
- package/src/protocol/gateway/gateway-connection.ts +103 -5
- package/src/protocol/gateway/reconnect.ts +15 -3
- package/src/protocol/index.ts +1 -0
- package/src/protocol/types.ts +46 -10
package/src/QQBot.ts
CHANGED
|
@@ -220,6 +220,8 @@ export type QQBotEventMap = {
|
|
|
220
220
|
ready: (data: unknown) => void;
|
|
221
221
|
resumed: (data: unknown) => void;
|
|
222
222
|
disconnected: (event: GatewayDisconnect) => void;
|
|
223
|
+
/** Transport connection state transition (`connectionState` is the same value, readable at any time). */
|
|
224
|
+
connection: (state: ConnectionState, previous: ConnectionState) => void;
|
|
223
225
|
error: (err: Error) => void;
|
|
224
226
|
message: (ctx: MiddlewareContext, msg: QQBotInboundMessage) => void | Promise<void>;
|
|
225
227
|
interaction: (ctx: InteractionContext, event: InteractionEvent) => void | Promise<void>;
|
|
@@ -243,6 +245,22 @@ export type QQBotEventMap = {
|
|
|
243
245
|
rawEvent: (ctx: RawEventContext) => void | Promise<void>;
|
|
244
246
|
};
|
|
245
247
|
|
|
248
|
+
/**
|
|
249
|
+
* Transport connection state, readable at any time via
|
|
250
|
+
* {@link QQBot.connectionState} without subscribing to events.
|
|
251
|
+
*
|
|
252
|
+
* - `idle`: never started, or stopped.
|
|
253
|
+
* - `connecting`: startup (IDENTIFY) or an automatic reconnect is in progress.
|
|
254
|
+
* - `resuming`: a reconnect is recovering the previous session via RESUME.
|
|
255
|
+
* - `connected`: the WS gateway completed READY/RESUMED, or the webhook
|
|
256
|
+
* server is listening.
|
|
257
|
+
* - `disconnected`: startup failed, or the gateway gave up reconnecting.
|
|
258
|
+
*
|
|
259
|
+
* Custom `EventTransport` implementations have no ready signal, so they stay
|
|
260
|
+
* `connecting` until the run ends.
|
|
261
|
+
*/
|
|
262
|
+
export type ConnectionState = "idle" | "connecting" | "resuming" | "connected" | "disconnected";
|
|
263
|
+
|
|
246
264
|
/**
|
|
247
265
|
* Augmented inbound message with a ready-to-use `replyTarget`.
|
|
248
266
|
*/
|
|
@@ -286,6 +304,7 @@ export class QQBot {
|
|
|
286
304
|
ready: new Set(),
|
|
287
305
|
resumed: new Set(),
|
|
288
306
|
disconnected: new Set(),
|
|
307
|
+
connection: new Set(),
|
|
289
308
|
error: new Set(),
|
|
290
309
|
message: new Set(),
|
|
291
310
|
interaction: new Set(),
|
|
@@ -294,6 +313,12 @@ export class QQBot {
|
|
|
294
313
|
|
|
295
314
|
private gateway: GatewayConnection | null = null;
|
|
296
315
|
private abortController: AbortController | null = null;
|
|
316
|
+
/** Mutated only by the start/stop lifecycle and the transport callbacks. */
|
|
317
|
+
private _connectionState: ConnectionState = "idle";
|
|
318
|
+
/** Last heartbeat ACK latency in ms; -1 before the first ACK of the current run. */
|
|
319
|
+
private _ping = -1;
|
|
320
|
+
/** Timestamp of the last heartbeat ACK; undefined until the first ACK of the current run. */
|
|
321
|
+
private _lastHeartbeatAt: number | undefined;
|
|
297
322
|
private _apiGateway: ApiGateway | null = null;
|
|
298
323
|
|
|
299
324
|
constructor(options: QQBotOptions) {
|
|
@@ -378,6 +403,24 @@ export class QQBot {
|
|
|
378
403
|
return this.creds.appId;
|
|
379
404
|
}
|
|
380
405
|
|
|
406
|
+
/**
|
|
407
|
+
* Current transport connection state. Read it any time instead of tracking
|
|
408
|
+
* `ready` / `resumed` / `disconnected` yourself.
|
|
409
|
+
*/
|
|
410
|
+
get connectionState(): ConnectionState {
|
|
411
|
+
return this._connectionState;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Last heartbeat ACK latency in milliseconds, or `-1` before the first ACK. */
|
|
415
|
+
get ping(): number {
|
|
416
|
+
return this._ping;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Last heartbeat ACK timestamp (epoch ms), or `undefined` before the first ACK. */
|
|
420
|
+
get lastHeartbeatAt(): number | undefined {
|
|
421
|
+
return this._lastHeartbeatAt;
|
|
422
|
+
}
|
|
423
|
+
|
|
381
424
|
/** The stable account id (defaults to appId). */
|
|
382
425
|
get accountId(): string {
|
|
383
426
|
return this.account.accountId;
|
|
@@ -481,6 +524,9 @@ export class QQBot {
|
|
|
481
524
|
externalSignal?.addEventListener("abort", onAbort, { once: true });
|
|
482
525
|
}
|
|
483
526
|
|
|
527
|
+
this.setConnectionState("connecting");
|
|
528
|
+
this._ping = -1;
|
|
529
|
+
this._lastHeartbeatAt = undefined;
|
|
484
530
|
try {
|
|
485
531
|
if (controller.signal.aborted) return;
|
|
486
532
|
const transportMode = this.opts.transport ?? "websocket";
|
|
@@ -491,9 +537,17 @@ export class QQBot {
|
|
|
491
537
|
} else {
|
|
492
538
|
await this.startCustomTransport(transportMode, controller.signal);
|
|
493
539
|
}
|
|
540
|
+
} catch (error) {
|
|
541
|
+
// 启动失败是终态:留给 stop()/下一次 start() 重置
|
|
542
|
+
this.setConnectionState("disconnected");
|
|
543
|
+
throw error;
|
|
494
544
|
} finally {
|
|
495
545
|
externalSignal?.removeEventListener("abort", onAbort);
|
|
496
|
-
if (this.abortController === controller)
|
|
546
|
+
if (this.abortController === controller) {
|
|
547
|
+
this.releaseRun();
|
|
548
|
+
// 正常结束(stop/abort)回到 idle;保留启动失败留下的 disconnected
|
|
549
|
+
if (this._connectionState !== "disconnected") this.setConnectionState("idle");
|
|
550
|
+
}
|
|
497
551
|
}
|
|
498
552
|
}
|
|
499
553
|
|
|
@@ -506,9 +560,17 @@ export class QQBot {
|
|
|
506
560
|
stop(): void {
|
|
507
561
|
const controller = this.abortController;
|
|
508
562
|
this.releaseRun();
|
|
563
|
+
this.setConnectionState("idle");
|
|
509
564
|
controller?.abort();
|
|
510
565
|
}
|
|
511
566
|
|
|
567
|
+
private setConnectionState(state: ConnectionState): void {
|
|
568
|
+
if (this._connectionState === state) return;
|
|
569
|
+
const previous = this._connectionState;
|
|
570
|
+
this._connectionState = state;
|
|
571
|
+
void this.emit("connection", state, previous);
|
|
572
|
+
}
|
|
573
|
+
|
|
512
574
|
private releaseRun(): void {
|
|
513
575
|
this.tokenManager.stopBackgroundRefresh(this.creds.appId);
|
|
514
576
|
this.gateway = null;
|
|
@@ -560,17 +622,34 @@ export class QQBot {
|
|
|
560
622
|
clearTokenCache: () => this.tokenManager.clearCache(this.creds.appId),
|
|
561
623
|
getGatewayUrl: () => this.messageApi.getGatewayUrl(this.creds),
|
|
562
624
|
onReady: (data) => {
|
|
625
|
+
this.setConnectionState("connected");
|
|
563
626
|
this.logger.info?.(`[qqbot] gateway READY`);
|
|
564
627
|
void this.emit("ready", data);
|
|
565
628
|
},
|
|
566
629
|
onResumed: (data) => {
|
|
630
|
+
this.setConnectionState("connected");
|
|
567
631
|
this.logger.info?.(`[qqbot] gateway RESUMED`);
|
|
568
632
|
void this.emit("resumed", data);
|
|
569
633
|
},
|
|
634
|
+
onResuming: () => {
|
|
635
|
+
this.setConnectionState("resuming");
|
|
636
|
+
this.logger.debug?.(`[qqbot] gateway resuming session`);
|
|
637
|
+
},
|
|
638
|
+
onIdentifying: () => {
|
|
639
|
+
// RESUME 被拒(session 失效)后重新 IDENTIFY:从 resuming 回到 connecting
|
|
640
|
+
this.setConnectionState("connecting");
|
|
641
|
+
this.logger.debug?.(`[qqbot] gateway identifying`);
|
|
642
|
+
},
|
|
643
|
+
onHeartbeat: (latencyMs) => {
|
|
644
|
+
this._ping = latencyMs;
|
|
645
|
+
this._lastHeartbeatAt = Date.now();
|
|
646
|
+
},
|
|
570
647
|
onError: (err) => {
|
|
571
648
|
void this.emit("error", err);
|
|
572
649
|
},
|
|
573
650
|
onDisconnected: (event) => {
|
|
651
|
+
// 自动重连期间保持 connecting;willReconnect=false 表示不再恢复
|
|
652
|
+
this.setConnectionState(event.willReconnect ? "connecting" : "disconnected");
|
|
574
653
|
void this.emit("disconnected", event);
|
|
575
654
|
},
|
|
576
655
|
onMessage: (raw) => this.handleInboundMessage(raw),
|
|
@@ -606,10 +685,12 @@ export class QQBot {
|
|
|
606
685
|
},
|
|
607
686
|
{
|
|
608
687
|
onReady: (data) => {
|
|
688
|
+
this.setConnectionState("connected");
|
|
609
689
|
this.logger.info?.(`[qqbot] webhook READY`);
|
|
610
690
|
void this.emit("ready", data);
|
|
611
691
|
},
|
|
612
692
|
onResumed: (data) => {
|
|
693
|
+
this.setConnectionState("connected");
|
|
613
694
|
void this.emit("resumed", data);
|
|
614
695
|
},
|
|
615
696
|
onError: (err) => {
|
package/src/index.ts
CHANGED
|
@@ -28,6 +28,8 @@ export interface InboundAttachment {
|
|
|
28
28
|
voice_wav_url?: string;
|
|
29
29
|
/** ASR transcription text for voice messages (QQ built-in speech recognition). */
|
|
30
30
|
asr_refer_text?: string;
|
|
31
|
+
/** Platform-added fields not declared here. */
|
|
32
|
+
[key: string]: unknown;
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
/** One element from the `msg_elements` array pushed by QQ. */
|
|
@@ -42,15 +44,36 @@ export interface InboundMsgElement {
|
|
|
42
44
|
|
|
43
45
|
// ============ Inbound message ============
|
|
44
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Normalized message author — a closed domain model.
|
|
49
|
+
*
|
|
50
|
+
* New sender-related platform fields are mapped here (not as new top-level
|
|
51
|
+
* `InboundMessage` fields), so `keyof InboundAuthor` stays precise and
|
|
52
|
+
* consumers read one nested object instead of a growing flat list.
|
|
53
|
+
*/
|
|
54
|
+
export interface InboundAuthor {
|
|
55
|
+
/** Stable sender id (openid; the scope depends on `InboundMessage.kind`). */
|
|
56
|
+
id: string;
|
|
57
|
+
name?: string;
|
|
58
|
+
/** Sender avatar URL when the platform provides one. */
|
|
59
|
+
avatar?: string;
|
|
60
|
+
isBot?: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
45
63
|
/** Inbound message envelope normalised across C2C / Group / Guild scopes. */
|
|
46
64
|
export interface InboundMessage {
|
|
47
65
|
/** Raw event type from the gateway. */
|
|
48
66
|
rawEventType: string;
|
|
49
67
|
/** Conversation kind. */
|
|
50
68
|
kind: "c2c" | "group" | "guild" | "dm";
|
|
69
|
+
/** @deprecated Use `author.id`. */
|
|
51
70
|
senderId: string;
|
|
71
|
+
/** @deprecated Use `author.name`. */
|
|
52
72
|
senderName?: string;
|
|
73
|
+
/** @deprecated Use `author.isBot`. */
|
|
53
74
|
senderIsBot?: boolean;
|
|
75
|
+
/** Normalized sender; new sender-related platform fields land here. */
|
|
76
|
+
author: InboundAuthor;
|
|
54
77
|
content: string;
|
|
55
78
|
messageId: string;
|
|
56
79
|
timestamp: string;
|
|
@@ -102,6 +125,15 @@ interface Refs {
|
|
|
102
125
|
|
|
103
126
|
const REF_INDEX_KEY = "msg_idx";
|
|
104
127
|
|
|
128
|
+
/**
|
|
129
|
+
* Read the sender avatar, an additive platform field that SDK types only
|
|
130
|
+
* recently declared. Missing or malformed values stay undefined so callers
|
|
131
|
+
* never have to guard the raw event themselves.
|
|
132
|
+
*/
|
|
133
|
+
function readAvatar(author: { avatar?: unknown }): string | undefined {
|
|
134
|
+
return typeof author.avatar === "string" && author.avatar !== "" ? author.avatar : undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
105
137
|
/**
|
|
106
138
|
* Parse `ref_idx` and `msg_idx` from message_scene.ext + msg_elements.
|
|
107
139
|
*/
|
|
@@ -171,6 +203,7 @@ export function dispatchEvent(
|
|
|
171
203
|
rawEventType: eventType,
|
|
172
204
|
kind: "c2c",
|
|
173
205
|
senderId: ev.author.user_openid,
|
|
206
|
+
author: { id: ev.author.user_openid, avatar: readAvatar(ev.author) },
|
|
174
207
|
content: ev.content,
|
|
175
208
|
messageId: ev.id,
|
|
176
209
|
timestamp: ev.timestamp,
|
|
@@ -197,6 +230,7 @@ export function dispatchEvent(
|
|
|
197
230
|
kind: "guild",
|
|
198
231
|
senderId: ev.author.id,
|
|
199
232
|
senderName: ev.author.username,
|
|
233
|
+
author: { id: ev.author.id, name: ev.author.username, avatar: readAvatar(ev.author) },
|
|
200
234
|
content: ev.content,
|
|
201
235
|
messageId: ev.id,
|
|
202
236
|
timestamp: ev.timestamp,
|
|
@@ -222,6 +256,7 @@ export function dispatchEvent(
|
|
|
222
256
|
kind: "dm",
|
|
223
257
|
senderId: ev.author.id,
|
|
224
258
|
senderName: ev.author.username,
|
|
259
|
+
author: { id: ev.author.id, name: ev.author.username, avatar: readAvatar(ev.author) },
|
|
225
260
|
content: ev.content,
|
|
226
261
|
messageId: ev.id,
|
|
227
262
|
timestamp: ev.timestamp,
|
|
@@ -248,6 +283,12 @@ export function dispatchEvent(
|
|
|
248
283
|
senderId: ev.author.member_openid,
|
|
249
284
|
senderName: ev.author.username,
|
|
250
285
|
senderIsBot: ev.author.bot,
|
|
286
|
+
author: {
|
|
287
|
+
id: ev.author.member_openid,
|
|
288
|
+
name: ev.author.username,
|
|
289
|
+
isBot: ev.author.bot,
|
|
290
|
+
avatar: readAvatar(ev.author),
|
|
291
|
+
},
|
|
251
292
|
content: ev.content,
|
|
252
293
|
messageId: ev.id,
|
|
253
294
|
timestamp: ev.timestamp,
|
|
@@ -82,6 +82,12 @@ export interface GatewayConnectionOptions {
|
|
|
82
82
|
// ---- Event handlers ----
|
|
83
83
|
onReady?: (data: unknown) => void;
|
|
84
84
|
onResumed?: (data: unknown) => void;
|
|
85
|
+
/** Called when a reconnect sends RESUME (session recovery) before RESUMED/READY arrives. */
|
|
86
|
+
onResuming?: () => void;
|
|
87
|
+
/** Called when a connection sends IDENTIFY (fresh session: first connect, or RESUME was rejected). */
|
|
88
|
+
onIdentifying?: () => void;
|
|
89
|
+
/** Heartbeat ACK latency in milliseconds, measured from heartbeat send to ACK. */
|
|
90
|
+
onHeartbeat?: (latencyMs: number) => void;
|
|
85
91
|
/** Recoverable failures (connect errors, socket errors). Terminal failures reject `start()` instead. */
|
|
86
92
|
onError?: (error: Error) => void;
|
|
87
93
|
onDisconnected?: (event: GatewayDisconnect) => void;
|
|
@@ -97,6 +103,16 @@ export class GatewayConnection {
|
|
|
97
103
|
private finish: (error?: Error) => void = () => {};
|
|
98
104
|
private currentWs: WebSocket | null = null;
|
|
99
105
|
private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
|
|
106
|
+
/** Server-provided heartbeat interval of the current connection (0 before HELLO). */
|
|
107
|
+
private heartbeatIntervalMs = 0;
|
|
108
|
+
/** Forces terminate() when the zombie-close handshake stalls in a network black hole. */
|
|
109
|
+
private zombieWatchdog: ReturnType<typeof setTimeout> | null = null;
|
|
110
|
+
/** Jittered first heartbeat after HELLO; tracked so cleanup() can release it immediately. */
|
|
111
|
+
private firstBeatTimer: ReturnType<typeof setTimeout> | null = null;
|
|
112
|
+
/** True while a heartbeat is awaiting its ACK; a second beat without ACK means a zombie link. */
|
|
113
|
+
private awaitingHeartbeatAck = false;
|
|
114
|
+
/** Send timestamp of the in-flight heartbeat (0 when none is pending). */
|
|
115
|
+
private lastHeartbeatSentAt = 0;
|
|
100
116
|
private sessionId: string | null = null;
|
|
101
117
|
private lastSeq: number | null = null;
|
|
102
118
|
private isConnecting = false;
|
|
@@ -205,6 +221,16 @@ export class GatewayConnection {
|
|
|
205
221
|
clearInterval(this.heartbeatInterval);
|
|
206
222
|
this.heartbeatInterval = null;
|
|
207
223
|
}
|
|
224
|
+
this.awaitingHeartbeatAck = false;
|
|
225
|
+
this.lastHeartbeatSentAt = 0;
|
|
226
|
+
if (this.zombieWatchdog) {
|
|
227
|
+
clearTimeout(this.zombieWatchdog);
|
|
228
|
+
this.zombieWatchdog = null;
|
|
229
|
+
}
|
|
230
|
+
if (this.firstBeatTimer) {
|
|
231
|
+
clearTimeout(this.firstBeatTimer);
|
|
232
|
+
this.firstBeatTimer = null;
|
|
233
|
+
}
|
|
208
234
|
const ws = this.currentWs;
|
|
209
235
|
// Retire ownership before close: ws can emit error/close after a replacement exists.
|
|
210
236
|
this.currentWs = null;
|
|
@@ -358,8 +384,16 @@ export class GatewayConnection {
|
|
|
358
384
|
this.handleDispatch(payload);
|
|
359
385
|
break;
|
|
360
386
|
|
|
361
|
-
case GatewayOp.HEARTBEAT_ACK:
|
|
387
|
+
case GatewayOp.HEARTBEAT_ACK: {
|
|
388
|
+
this.awaitingHeartbeatAck = false;
|
|
389
|
+
if (this.lastHeartbeatSentAt !== 0) {
|
|
390
|
+
const latency = Date.now() - this.lastHeartbeatSentAt;
|
|
391
|
+
this.lastHeartbeatSentAt = 0;
|
|
392
|
+
const { onHeartbeat } = this.opts;
|
|
393
|
+
if (onHeartbeat) this.notify("onHeartbeat", () => onHeartbeat(latency));
|
|
394
|
+
}
|
|
362
395
|
break;
|
|
396
|
+
}
|
|
363
397
|
|
|
364
398
|
case GatewayOp.RECONNECT:
|
|
365
399
|
this.handleGatewayReconnect("Gateway requested reconnect");
|
|
@@ -410,8 +444,22 @@ export class GatewayConnection {
|
|
|
410
444
|
}
|
|
411
445
|
|
|
412
446
|
private handleHello(ws: WebSocket, d: unknown, accessToken: string): void {
|
|
447
|
+
// Validate before IDENTIFY/RESUME: a malformed interval would clamp
|
|
448
|
+
// setInterval to 1ms and cause a heartbeat storm.
|
|
449
|
+
const interval = readHeartbeatInterval(d);
|
|
450
|
+
if (interval === null) {
|
|
451
|
+
const { log, account } = this.opts;
|
|
452
|
+
log?.error(
|
|
453
|
+
`[${account.accountId}] Invalid HELLO heartbeat interval: ${previewPayload(d)}`,
|
|
454
|
+
);
|
|
455
|
+
this.handleGatewayReconnect("Invalid HELLO heartbeat interval");
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
|
|
413
459
|
const intents = this.opts.intents ?? FULL_INTENTS;
|
|
414
460
|
if (this.sessionId && this.lastSeq !== null) {
|
|
461
|
+
const { onResuming } = this.opts;
|
|
462
|
+
if (onResuming) this.notify("onResuming", () => onResuming());
|
|
415
463
|
ws.send(
|
|
416
464
|
JSON.stringify({
|
|
417
465
|
op: GatewayOp.RESUME,
|
|
@@ -423,6 +471,8 @@ export class GatewayConnection {
|
|
|
423
471
|
}),
|
|
424
472
|
);
|
|
425
473
|
} else {
|
|
474
|
+
const { onIdentifying } = this.opts;
|
|
475
|
+
if (onIdentifying) this.notify("onIdentifying", () => onIdentifying());
|
|
426
476
|
ws.send(
|
|
427
477
|
JSON.stringify({
|
|
428
478
|
op: GatewayOp.IDENTIFY,
|
|
@@ -435,17 +485,51 @@ export class GatewayConnection {
|
|
|
435
485
|
);
|
|
436
486
|
}
|
|
437
487
|
|
|
438
|
-
const interval = (d as { heartbeat_interval: number }).heartbeat_interval;
|
|
439
488
|
if (this.heartbeatInterval) {
|
|
440
489
|
clearInterval(this.heartbeatInterval);
|
|
441
490
|
}
|
|
491
|
+
this.heartbeatIntervalMs = interval;
|
|
492
|
+
// HELLO 后先以 interval×random 的抖动发首拍(避免大规模部署下
|
|
493
|
+
// 心跳相位与服务器下发时刻对齐),之后按固定间隔
|
|
494
|
+
const jitter = Math.max(1, Math.floor(Math.random() * interval));
|
|
495
|
+
this.firstBeatTimer = setTimeout(() => {
|
|
496
|
+
this.firstBeatTimer = null;
|
|
497
|
+
if (ws === this.currentWs) this.sendHeartbeat(ws);
|
|
498
|
+
}, jitter);
|
|
442
499
|
this.heartbeatInterval = setInterval(() => {
|
|
443
|
-
if (ws
|
|
444
|
-
|
|
445
|
-
|
|
500
|
+
if (ws !== this.currentWs) return;
|
|
501
|
+
if (ws.readyState !== WebSocket.OPEN) return;
|
|
502
|
+
this.sendHeartbeat(ws);
|
|
446
503
|
}, interval);
|
|
447
504
|
}
|
|
448
505
|
|
|
506
|
+
/**
|
|
507
|
+
* Send one heartbeat. A still-unacknowledged previous beat means the link
|
|
508
|
+
* is dead: close with 4009 — the server-side code for "please reconnect" —
|
|
509
|
+
* so the reconnect path runs. The session is preserved server-side, so the
|
|
510
|
+
* reconnect resumes from the last seq and replays missed events. Leave a
|
|
511
|
+
* watchdog too: in a network black hole even the close handshake stalls.
|
|
512
|
+
*/
|
|
513
|
+
private sendHeartbeat(ws: WebSocket): void {
|
|
514
|
+
const { log, account } = this.opts;
|
|
515
|
+
if (this.awaitingHeartbeatAck) {
|
|
516
|
+
log?.warn?.(`[${account.accountId}] Heartbeat ACK timeout, closing ${GatewayCloseCode.SESSION_TIMEOUT}`);
|
|
517
|
+
ws.close(GatewayCloseCode.SESSION_TIMEOUT, "heartbeat ACK timeout");
|
|
518
|
+
if (this.zombieWatchdog) clearTimeout(this.zombieWatchdog);
|
|
519
|
+
this.zombieWatchdog = setTimeout(() => {
|
|
520
|
+
this.zombieWatchdog = null;
|
|
521
|
+
if (ws.readyState !== WebSocket.CLOSED) {
|
|
522
|
+
log?.warn?.(`[${account.accountId}] Close handshake stalled, terminating`);
|
|
523
|
+
ws.terminate();
|
|
524
|
+
}
|
|
525
|
+
}, Math.max(1_000, Math.min(this.heartbeatIntervalMs, 5_000)));
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
this.awaitingHeartbeatAck = true;
|
|
529
|
+
this.lastHeartbeatSentAt = Date.now();
|
|
530
|
+
ws.send(JSON.stringify({ op: GatewayOp.HEARTBEAT, d: this.lastSeq }));
|
|
531
|
+
}
|
|
532
|
+
|
|
449
533
|
/** Opcode 7 / 9: drop the socket locally and reconnect. */
|
|
450
534
|
private handleGatewayReconnect(reason: string, customDelay?: number): void {
|
|
451
535
|
this.cleanup();
|
|
@@ -480,6 +564,20 @@ function toError(err: unknown): Error {
|
|
|
480
564
|
return err instanceof Error ? err : new Error(String(err));
|
|
481
565
|
}
|
|
482
566
|
|
|
567
|
+
/**
|
|
568
|
+
* Read the HELLO heartbeat interval; numeric strings are coerced so a
|
|
569
|
+
* server-side serialization change stays non-breaking. Returns `null` for
|
|
570
|
+
* any value that cannot schedule a sane heartbeat.
|
|
571
|
+
*/
|
|
572
|
+
function readHeartbeatInterval(d: unknown): number | null {
|
|
573
|
+
const raw = (d as { heartbeat_interval?: unknown }).heartbeat_interval;
|
|
574
|
+
const value = typeof raw === "string" ? Number(raw.trim()) : raw;
|
|
575
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
576
|
+
return null;
|
|
577
|
+
}
|
|
578
|
+
return value;
|
|
579
|
+
}
|
|
580
|
+
|
|
483
581
|
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
484
582
|
return typeof (value as PromiseLike<unknown> | null)?.then === "function";
|
|
485
583
|
}
|
|
@@ -140,15 +140,27 @@ export class ReconnectState {
|
|
|
140
140
|
};
|
|
141
141
|
}
|
|
142
142
|
|
|
143
|
+
// 4009 是服务端"请重连"的通用关闭码(最大连接时长到期、负载转移、Ping 超时等),
|
|
144
|
+
// 服务端会保留 session 等待客户端 RESUME 并按 seq 重放断线期间的事件。
|
|
145
|
+
// 这里必须保留 session:清掉会让重连退化为 IDENTIFY 新会话,丢失积压消息。
|
|
146
|
+
if (code === GatewayCloseCode.SESSION_TIMEOUT) {
|
|
147
|
+
this.log?.info(`[${this.accountId}] Server requested reconnect (4009), will resume`);
|
|
148
|
+
return {
|
|
149
|
+
shouldReconnect: !isAborted,
|
|
150
|
+
clearSession: false,
|
|
151
|
+
refreshToken: false,
|
|
152
|
+
fatal: false,
|
|
153
|
+
reason: "server requested reconnect",
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
143
157
|
if (
|
|
144
158
|
code === GatewayCloseCode.INVALID_SESSION ||
|
|
145
|
-
code === GatewayCloseCode.SEQ_OUT_OF_RANGE
|
|
146
|
-
code === GatewayCloseCode.SESSION_TIMEOUT
|
|
159
|
+
code === GatewayCloseCode.SEQ_OUT_OF_RANGE
|
|
147
160
|
) {
|
|
148
161
|
const codeDesc: Record<number, string> = {
|
|
149
162
|
[GatewayCloseCode.INVALID_SESSION]: "session no longer valid",
|
|
150
163
|
[GatewayCloseCode.SEQ_OUT_OF_RANGE]: "invalid seq on resume",
|
|
151
|
-
[GatewayCloseCode.SESSION_TIMEOUT]: "session timed out",
|
|
152
164
|
};
|
|
153
165
|
this.log?.info(`[${this.accountId}] Error ${code} (${codeDesc[code]}), will re-identify`);
|
|
154
166
|
return {
|
package/src/protocol/index.ts
CHANGED
package/src/protocol/types.ts
CHANGED
|
@@ -73,7 +73,9 @@ export interface MessageResponse {
|
|
|
73
73
|
/** Reference index for future quoting. */
|
|
74
74
|
ext_info?: {
|
|
75
75
|
ref_idx?: string;
|
|
76
|
-
};
|
|
76
|
+
} & OpenFields;
|
|
77
|
+
/** Platform-added fields not declared here. */
|
|
78
|
+
[key: string]: unknown;
|
|
77
79
|
}
|
|
78
80
|
|
|
79
81
|
// ============ Media Types ============
|
|
@@ -92,6 +94,8 @@ export interface UploadMediaResponse {
|
|
|
92
94
|
file_info: string;
|
|
93
95
|
ttl: number;
|
|
94
96
|
id?: string;
|
|
97
|
+
/** Platform-added fields not declared here. */
|
|
98
|
+
[key: string]: unknown;
|
|
95
99
|
}
|
|
96
100
|
|
|
97
101
|
/** Structured metadata recorded for outbound messages. */
|
|
@@ -119,6 +123,8 @@ export interface ApiClientConfig {
|
|
|
119
123
|
export interface UploadPart {
|
|
120
124
|
index: number;
|
|
121
125
|
presigned_url: string;
|
|
126
|
+
/** Platform-added fields not declared here. */
|
|
127
|
+
[key: string]: unknown;
|
|
122
128
|
}
|
|
123
129
|
|
|
124
130
|
export interface UploadPrepareResponse {
|
|
@@ -127,6 +133,8 @@ export interface UploadPrepareResponse {
|
|
|
127
133
|
parts: UploadPart[];
|
|
128
134
|
concurrency?: number;
|
|
129
135
|
retry_timeout?: number;
|
|
136
|
+
/** Platform-added fields not declared here. */
|
|
137
|
+
[key: string]: unknown;
|
|
130
138
|
}
|
|
131
139
|
|
|
132
140
|
export interface UploadPrepareHashes {
|
|
@@ -192,6 +200,11 @@ export interface InlineKeyboard {
|
|
|
192
200
|
// ============ Interaction Event ============
|
|
193
201
|
|
|
194
202
|
export interface InteractionEvent {
|
|
203
|
+
/**
|
|
204
|
+
* Boundary type: forwarded to consumers as the gateway sends it (open to
|
|
205
|
+
* additive fields). A closed `InboundInteraction` domain model can be
|
|
206
|
+
* introduced later if field-level tooling ever needs it.
|
|
207
|
+
*/
|
|
195
208
|
id: string;
|
|
196
209
|
type: number;
|
|
197
210
|
scene?: string;
|
|
@@ -211,8 +224,10 @@ export interface InteractionEvent {
|
|
|
211
224
|
user_id?: string;
|
|
212
225
|
feature_id?: string;
|
|
213
226
|
message_id?: string;
|
|
214
|
-
};
|
|
215
|
-
};
|
|
227
|
+
} & OpenFields;
|
|
228
|
+
} & OpenFields;
|
|
229
|
+
/** Platform-added fields not declared here. */
|
|
230
|
+
[key: string]: unknown;
|
|
216
231
|
}
|
|
217
232
|
|
|
218
233
|
// ============ Gateway WebSocket Types ============
|
|
@@ -230,11 +245,15 @@ export interface RawMessageAttachment {
|
|
|
230
245
|
filename?: string;
|
|
231
246
|
voice_wav_url?: string;
|
|
232
247
|
asr_refer_text?: string;
|
|
248
|
+
/** Platform-added fields not declared here. */
|
|
249
|
+
[key: string]: unknown;
|
|
233
250
|
}
|
|
234
251
|
|
|
235
252
|
export interface RawMsgElement {
|
|
236
253
|
msg_idx?: string;
|
|
237
254
|
content?: string;
|
|
255
|
+
/** Platform-added fields not declared here. */
|
|
256
|
+
[key: string]: unknown;
|
|
238
257
|
attachments?: Array<
|
|
239
258
|
RawMessageAttachment & {
|
|
240
259
|
height?: number;
|
|
@@ -244,26 +263,39 @@ export interface RawMsgElement {
|
|
|
244
263
|
>;
|
|
245
264
|
}
|
|
246
265
|
|
|
266
|
+
/**
|
|
267
|
+
* Fields the platform sends but this SDK has not declared yet.
|
|
268
|
+
*
|
|
269
|
+
* Platform releases additive event fields before SDK type updates; consumers
|
|
270
|
+
* can still read them (`author.someNewField`) instead of escaping the type
|
|
271
|
+
* system with `as any`.
|
|
272
|
+
*/
|
|
273
|
+
export type OpenFields = { [key: string]: unknown };
|
|
274
|
+
|
|
247
275
|
export interface C2CMessageEvent {
|
|
248
276
|
id: string;
|
|
249
277
|
content: string;
|
|
250
278
|
timestamp: string;
|
|
251
|
-
author: { user_openid: string };
|
|
279
|
+
author: { user_openid: string; avatar?: string } & OpenFields;
|
|
252
280
|
attachments?: RawMessageAttachment[];
|
|
253
|
-
message_scene?: { ext?: string[] };
|
|
281
|
+
message_scene?: { ext?: string[] } & OpenFields;
|
|
254
282
|
message_type?: number;
|
|
255
283
|
msg_elements?: RawMsgElement[];
|
|
284
|
+
/** Platform-added fields not declared here. */
|
|
285
|
+
[key: string]: unknown;
|
|
256
286
|
}
|
|
257
287
|
|
|
258
288
|
export interface GuildMessageEvent {
|
|
259
289
|
id: string;
|
|
260
290
|
content: string;
|
|
261
291
|
timestamp: string;
|
|
262
|
-
author: { id: string; username?: string };
|
|
292
|
+
author: { id: string; username?: string; avatar?: string } & OpenFields;
|
|
263
293
|
channel_id: string;
|
|
264
294
|
guild_id: string;
|
|
265
295
|
attachments?: RawMessageAttachment[];
|
|
266
|
-
message_scene?: { ext?: string[] };
|
|
296
|
+
message_scene?: { ext?: string[] } & OpenFields;
|
|
297
|
+
/** Platform-added fields not declared here. */
|
|
298
|
+
[key: string]: unknown;
|
|
267
299
|
}
|
|
268
300
|
|
|
269
301
|
export interface GroupMessageEvent {
|
|
@@ -274,7 +306,9 @@ export interface GroupMessageEvent {
|
|
|
274
306
|
member_openid: string;
|
|
275
307
|
username?: string;
|
|
276
308
|
bot?: boolean;
|
|
277
|
-
|
|
309
|
+
/** Sender avatar URL; the platform started sending it as an additive field. */
|
|
310
|
+
avatar?: string;
|
|
311
|
+
} & OpenFields;
|
|
278
312
|
group_openid: string;
|
|
279
313
|
attachments?: RawMessageAttachment[];
|
|
280
314
|
mentions?: Array<{
|
|
@@ -286,10 +320,12 @@ export interface GroupMessageEvent {
|
|
|
286
320
|
username?: string;
|
|
287
321
|
bot?: boolean;
|
|
288
322
|
is_you?: boolean;
|
|
289
|
-
}>;
|
|
290
|
-
message_scene?: { source?: string; ext?: string[] };
|
|
323
|
+
} & OpenFields>;
|
|
324
|
+
message_scene?: { source?: string; ext?: string[] } & OpenFields;
|
|
291
325
|
message_type?: number;
|
|
292
326
|
msg_elements?: RawMsgElement[];
|
|
327
|
+
/** Platform-added fields not declared here. */
|
|
328
|
+
[key: string]: unknown;
|
|
293
329
|
}
|
|
294
330
|
|
|
295
331
|
// ============ Account ============
|