@tencent-connect/qqbot-nodejs 1.0.3

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.
Files changed (293) hide show
  1. package/README.md +205 -0
  2. package/USAGE.md +804 -0
  3. package/dist/QQBot.d.ts +536 -0
  4. package/dist/QQBot.d.ts.map +1 -0
  5. package/dist/QQBot.js +752 -0
  6. package/dist/QQBot.js.map +1 -0
  7. package/dist/index.d.ts +49 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +66 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/middleware/access-policy.d.ts +54 -0
  12. package/dist/middleware/access-policy.d.ts.map +1 -0
  13. package/dist/middleware/access-policy.js +93 -0
  14. package/dist/middleware/access-policy.js.map +1 -0
  15. package/dist/middleware/concurrency-guard.d.ts +105 -0
  16. package/dist/middleware/concurrency-guard.d.ts.map +1 -0
  17. package/dist/middleware/concurrency-guard.js +325 -0
  18. package/dist/middleware/concurrency-guard.js.map +1 -0
  19. package/dist/middleware/content-sanitizer.d.ts +47 -0
  20. package/dist/middleware/content-sanitizer.d.ts.map +1 -0
  21. package/dist/middleware/content-sanitizer.js +85 -0
  22. package/dist/middleware/content-sanitizer.js.map +1 -0
  23. package/dist/middleware/envelope-formatter.d.ts +51 -0
  24. package/dist/middleware/envelope-formatter.d.ts.map +1 -0
  25. package/dist/middleware/envelope-formatter.js +97 -0
  26. package/dist/middleware/envelope-formatter.js.map +1 -0
  27. package/dist/middleware/error-handler.d.ts +36 -0
  28. package/dist/middleware/error-handler.d.ts.map +1 -0
  29. package/dist/middleware/error-handler.js +59 -0
  30. package/dist/middleware/error-handler.js.map +1 -0
  31. package/dist/middleware/history-buffer.d.ts +84 -0
  32. package/dist/middleware/history-buffer.d.ts.map +1 -0
  33. package/dist/middleware/history-buffer.js +113 -0
  34. package/dist/middleware/history-buffer.js.map +1 -0
  35. package/dist/middleware/index.d.ts +71 -0
  36. package/dist/middleware/index.d.ts.map +1 -0
  37. package/dist/middleware/index.js +48 -0
  38. package/dist/middleware/index.js.map +1 -0
  39. package/dist/middleware/mention-gate.d.ts +99 -0
  40. package/dist/middleware/mention-gate.d.ts.map +1 -0
  41. package/dist/middleware/mention-gate.js +117 -0
  42. package/dist/middleware/mention-gate.js.map +1 -0
  43. package/dist/middleware/message-filter.d.ts +38 -0
  44. package/dist/middleware/message-filter.d.ts.map +1 -0
  45. package/dist/middleware/message-filter.js +60 -0
  46. package/dist/middleware/message-filter.js.map +1 -0
  47. package/dist/middleware/quote-ref.d.ts +106 -0
  48. package/dist/middleware/quote-ref.d.ts.map +1 -0
  49. package/dist/middleware/quote-ref.js +168 -0
  50. package/dist/middleware/quote-ref.js.map +1 -0
  51. package/dist/middleware/rate-limiter.d.ts +43 -0
  52. package/dist/middleware/rate-limiter.d.ts.map +1 -0
  53. package/dist/middleware/rate-limiter.js +77 -0
  54. package/dist/middleware/rate-limiter.js.map +1 -0
  55. package/dist/middleware/slash-command.d.ts +112 -0
  56. package/dist/middleware/slash-command.d.ts.map +1 -0
  57. package/dist/middleware/slash-command.js +203 -0
  58. package/dist/middleware/slash-command.js.map +1 -0
  59. package/dist/middleware/types.d.ts +175 -0
  60. package/dist/middleware/types.d.ts.map +1 -0
  61. package/dist/middleware/types.js +138 -0
  62. package/dist/middleware/types.js.map +1 -0
  63. package/dist/middleware/typing-indicator.d.ts +54 -0
  64. package/dist/middleware/typing-indicator.d.ts.map +1 -0
  65. package/dist/middleware/typing-indicator.js +68 -0
  66. package/dist/middleware/typing-indicator.js.map +1 -0
  67. package/dist/protocol/api/api-client.d.ts +27 -0
  68. package/dist/protocol/api/api-client.d.ts.map +1 -0
  69. package/dist/protocol/api/api-client.js +119 -0
  70. package/dist/protocol/api/api-client.js.map +1 -0
  71. package/dist/protocol/api/media-chunked.d.ts +68 -0
  72. package/dist/protocol/api/media-chunked.d.ts.map +1 -0
  73. package/dist/protocol/api/media-chunked.js +298 -0
  74. package/dist/protocol/api/media-chunked.js.map +1 -0
  75. package/dist/protocol/api/media.d.ts +46 -0
  76. package/dist/protocol/api/media.d.ts.map +1 -0
  77. package/dist/protocol/api/media.js +101 -0
  78. package/dist/protocol/api/media.js.map +1 -0
  79. package/dist/protocol/api/messages.d.ts +86 -0
  80. package/dist/protocol/api/messages.d.ts.map +1 -0
  81. package/dist/protocol/api/messages.js +200 -0
  82. package/dist/protocol/api/messages.js.map +1 -0
  83. package/dist/protocol/api/retry.d.ts +23 -0
  84. package/dist/protocol/api/retry.d.ts.map +1 -0
  85. package/dist/protocol/api/retry.js +102 -0
  86. package/dist/protocol/api/retry.js.map +1 -0
  87. package/dist/protocol/api/routes.d.ts +23 -0
  88. package/dist/protocol/api/routes.d.ts.map +1 -0
  89. package/dist/protocol/api/routes.js +50 -0
  90. package/dist/protocol/api/routes.js.map +1 -0
  91. package/dist/protocol/api/token.d.ts +38 -0
  92. package/dist/protocol/api/token.d.ts.map +1 -0
  93. package/dist/protocol/api/token.js +191 -0
  94. package/dist/protocol/api/token.js.map +1 -0
  95. package/dist/protocol/gateway/codec.d.ts +9 -0
  96. package/dist/protocol/gateway/codec.d.ts.map +1 -0
  97. package/dist/protocol/gateway/codec.js +32 -0
  98. package/dist/protocol/gateway/codec.js.map +1 -0
  99. package/dist/protocol/gateway/constants.d.ts +71 -0
  100. package/dist/protocol/gateway/constants.d.ts.map +1 -0
  101. package/dist/protocol/gateway/constants.js +91 -0
  102. package/dist/protocol/gateway/constants.js.map +1 -0
  103. package/dist/protocol/gateway/event-dispatcher.d.ts +97 -0
  104. package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -0
  105. package/dist/protocol/gateway/event-dispatcher.js +155 -0
  106. package/dist/protocol/gateway/event-dispatcher.js.map +1 -0
  107. package/dist/protocol/gateway/gateway-connection.d.ts +73 -0
  108. package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -0
  109. package/dist/protocol/gateway/gateway-connection.js +293 -0
  110. package/dist/protocol/gateway/gateway-connection.js.map +1 -0
  111. package/dist/protocol/gateway/reconnect.d.ts +25 -0
  112. package/dist/protocol/gateway/reconnect.d.ts.map +1 -0
  113. package/dist/protocol/gateway/reconnect.js +118 -0
  114. package/dist/protocol/gateway/reconnect.js.map +1 -0
  115. package/dist/protocol/index.d.ts +41 -0
  116. package/dist/protocol/index.d.ts.map +1 -0
  117. package/dist/protocol/index.js +46 -0
  118. package/dist/protocol/index.js.map +1 -0
  119. package/dist/protocol/transport/index.d.ts +8 -0
  120. package/dist/protocol/transport/index.d.ts.map +1 -0
  121. package/dist/protocol/transport/index.js +4 -0
  122. package/dist/protocol/transport/index.js.map +1 -0
  123. package/dist/protocol/transport/types.d.ts +109 -0
  124. package/dist/protocol/transport/types.d.ts.map +1 -0
  125. package/dist/protocol/transport/types.js +15 -0
  126. package/dist/protocol/transport/types.js.map +1 -0
  127. package/dist/protocol/transport/webhook-server-node.d.ts +14 -0
  128. package/dist/protocol/transport/webhook-server-node.d.ts.map +1 -0
  129. package/dist/protocol/transport/webhook-server-node.js +57 -0
  130. package/dist/protocol/transport/webhook-server-node.js.map +1 -0
  131. package/dist/protocol/transport/webhook-verify.d.ts +49 -0
  132. package/dist/protocol/transport/webhook-verify.d.ts.map +1 -0
  133. package/dist/protocol/transport/webhook-verify.js +98 -0
  134. package/dist/protocol/transport/webhook-verify.js.map +1 -0
  135. package/dist/protocol/transport/webhook.d.ts +37 -0
  136. package/dist/protocol/transport/webhook.d.ts.map +1 -0
  137. package/dist/protocol/transport/webhook.js +183 -0
  138. package/dist/protocol/transport/webhook.js.map +1 -0
  139. package/dist/protocol/types.d.ts +270 -0
  140. package/dist/protocol/types.d.ts.map +1 -0
  141. package/dist/protocol/types.js +59 -0
  142. package/dist/protocol/types.js.map +1 -0
  143. package/dist/protocol/utils/audio.d.ts +79 -0
  144. package/dist/protocol/utils/audio.d.ts.map +1 -0
  145. package/dist/protocol/utils/audio.js +501 -0
  146. package/dist/protocol/utils/audio.js.map +1 -0
  147. package/dist/protocol/utils/decode-media-path.d.ts +26 -0
  148. package/dist/protocol/utils/decode-media-path.d.ts.map +1 -0
  149. package/dist/protocol/utils/decode-media-path.js +79 -0
  150. package/dist/protocol/utils/decode-media-path.js.map +1 -0
  151. package/dist/protocol/utils/ffmpeg.d.ts +38 -0
  152. package/dist/protocol/utils/ffmpeg.d.ts.map +1 -0
  153. package/dist/protocol/utils/ffmpeg.js +119 -0
  154. package/dist/protocol/utils/ffmpeg.js.map +1 -0
  155. package/dist/protocol/utils/file-utils.d.ts +42 -0
  156. package/dist/protocol/utils/file-utils.d.ts.map +1 -0
  157. package/dist/protocol/utils/file-utils.js +108 -0
  158. package/dist/protocol/utils/file-utils.js.map +1 -0
  159. package/dist/protocol/utils/format.d.ts +10 -0
  160. package/dist/protocol/utils/format.d.ts.map +1 -0
  161. package/dist/protocol/utils/format.js +68 -0
  162. package/dist/protocol/utils/format.js.map +1 -0
  163. package/dist/protocol/utils/image-size.d.ts +56 -0
  164. package/dist/protocol/utils/image-size.d.ts.map +1 -0
  165. package/dist/protocol/utils/image-size.js +185 -0
  166. package/dist/protocol/utils/image-size.js.map +1 -0
  167. package/dist/protocol/utils/media-source.d.ts +145 -0
  168. package/dist/protocol/utils/media-source.d.ts.map +1 -0
  169. package/dist/protocol/utils/media-source.js +175 -0
  170. package/dist/protocol/utils/media-source.js.map +1 -0
  171. package/dist/protocol/utils/media-tags.d.ts +15 -0
  172. package/dist/protocol/utils/media-tags.d.ts.map +1 -0
  173. package/dist/protocol/utils/media-tags.js +150 -0
  174. package/dist/protocol/utils/media-tags.js.map +1 -0
  175. package/dist/protocol/utils/media-type.d.ts +41 -0
  176. package/dist/protocol/utils/media-type.d.ts.map +1 -0
  177. package/dist/protocol/utils/media-type.js +89 -0
  178. package/dist/protocol/utils/media-type.js.map +1 -0
  179. package/dist/protocol/utils/payload.d.ts +52 -0
  180. package/dist/protocol/utils/payload.d.ts.map +1 -0
  181. package/dist/protocol/utils/payload.js +100 -0
  182. package/dist/protocol/utils/payload.js.map +1 -0
  183. package/dist/protocol/utils/ref-attachments.d.ts +80 -0
  184. package/dist/protocol/utils/ref-attachments.d.ts.map +1 -0
  185. package/dist/protocol/utils/ref-attachments.js +121 -0
  186. package/dist/protocol/utils/ref-attachments.js.map +1 -0
  187. package/dist/protocol/utils/ref-index-store.d.ts +69 -0
  188. package/dist/protocol/utils/ref-index-store.d.ts.map +1 -0
  189. package/dist/protocol/utils/ref-index-store.js +227 -0
  190. package/dist/protocol/utils/ref-index-store.js.map +1 -0
  191. package/dist/protocol/utils/reply-limiter.d.ts +75 -0
  192. package/dist/protocol/utils/reply-limiter.d.ts.map +1 -0
  193. package/dist/protocol/utils/reply-limiter.js +123 -0
  194. package/dist/protocol/utils/reply-limiter.js.map +1 -0
  195. package/dist/protocol/utils/session-store.d.ts +73 -0
  196. package/dist/protocol/utils/session-store.d.ts.map +1 -0
  197. package/dist/protocol/utils/session-store.js +274 -0
  198. package/dist/protocol/utils/session-store.js.map +1 -0
  199. package/dist/protocol/utils/target.d.ts +53 -0
  200. package/dist/protocol/utils/target.d.ts.map +1 -0
  201. package/dist/protocol/utils/target.js +104 -0
  202. package/dist/protocol/utils/target.js.map +1 -0
  203. package/dist/protocol/utils/text-chunk.d.ts +21 -0
  204. package/dist/protocol/utils/text-chunk.d.ts.map +1 -0
  205. package/dist/protocol/utils/text-chunk.js +25 -0
  206. package/dist/protocol/utils/text-chunk.js.map +1 -0
  207. package/dist/protocol/utils/text-parsing.d.ts +40 -0
  208. package/dist/protocol/utils/text-parsing.d.ts.map +1 -0
  209. package/dist/protocol/utils/text-parsing.js +126 -0
  210. package/dist/protocol/utils/text-parsing.js.map +1 -0
  211. package/dist/protocol/utils/upload-cache.d.ts +27 -0
  212. package/dist/protocol/utils/upload-cache.d.ts.map +1 -0
  213. package/dist/protocol/utils/upload-cache.js +73 -0
  214. package/dist/protocol/utils/upload-cache.js.map +1 -0
  215. package/dist/protocol/utils/voice-text.d.ts +9 -0
  216. package/dist/protocol/utils/voice-text.d.ts.map +1 -0
  217. package/dist/protocol/utils/voice-text.js +16 -0
  218. package/dist/protocol/utils/voice-text.js.map +1 -0
  219. package/dist/storage/index.d.ts +23 -0
  220. package/dist/storage/index.d.ts.map +1 -0
  221. package/dist/storage/index.js +21 -0
  222. package/dist/storage/index.js.map +1 -0
  223. package/dist/storage/kv-store.d.ts +85 -0
  224. package/dist/storage/kv-store.d.ts.map +1 -0
  225. package/dist/storage/kv-store.js +184 -0
  226. package/dist/storage/kv-store.js.map +1 -0
  227. package/dist/storage/session-adapter.d.ts +35 -0
  228. package/dist/storage/session-adapter.d.ts.map +1 -0
  229. package/dist/storage/session-adapter.js +48 -0
  230. package/dist/storage/session-adapter.js.map +1 -0
  231. package/dist/streaming.d.ts +67 -0
  232. package/dist/streaming.d.ts.map +1 -0
  233. package/dist/streaming.js +207 -0
  234. package/dist/streaming.js.map +1 -0
  235. package/package.json +90 -0
  236. package/src/QQBot.ts +1123 -0
  237. package/src/index.ts +175 -0
  238. package/src/middleware/access-policy.ts +139 -0
  239. package/src/middleware/concurrency-guard.ts +450 -0
  240. package/src/middleware/content-sanitizer.ts +125 -0
  241. package/src/middleware/envelope-formatter.ts +140 -0
  242. package/src/middleware/error-handler.ts +77 -0
  243. package/src/middleware/history-buffer.ts +169 -0
  244. package/src/middleware/index.ts +129 -0
  245. package/src/middleware/mention-gate.ts +227 -0
  246. package/src/middleware/message-filter.ts +82 -0
  247. package/src/middleware/quote-ref.ts +237 -0
  248. package/src/middleware/rate-limiter.ts +112 -0
  249. package/src/middleware/slash-command.ts +307 -0
  250. package/src/middleware/types.ts +273 -0
  251. package/src/middleware/typing-indicator.ts +107 -0
  252. package/src/protocol/api/api-client.ts +170 -0
  253. package/src/protocol/api/media-chunked.ts +517 -0
  254. package/src/protocol/api/media.ts +188 -0
  255. package/src/protocol/api/messages.ts +345 -0
  256. package/src/protocol/api/retry.ts +157 -0
  257. package/src/protocol/api/routes.ts +62 -0
  258. package/src/protocol/api/token.ts +250 -0
  259. package/src/protocol/gateway/codec.ts +33 -0
  260. package/src/protocol/gateway/constants.ts +98 -0
  261. package/src/protocol/gateway/event-dispatcher.ts +275 -0
  262. package/src/protocol/gateway/gateway-connection.ts +375 -0
  263. package/src/protocol/gateway/reconnect.ts +155 -0
  264. package/src/protocol/index.ts +238 -0
  265. package/src/protocol/transport/index.ts +17 -0
  266. package/src/protocol/transport/types.ts +121 -0
  267. package/src/protocol/transport/webhook-server-node.ts +64 -0
  268. package/src/protocol/transport/webhook-verify.ts +118 -0
  269. package/src/protocol/transport/webhook.ts +237 -0
  270. package/src/protocol/types.ts +305 -0
  271. package/src/protocol/utils/audio.ts +663 -0
  272. package/src/protocol/utils/decode-media-path.ts +88 -0
  273. package/src/protocol/utils/ffmpeg.ts +131 -0
  274. package/src/protocol/utils/file-utils.ts +121 -0
  275. package/src/protocol/utils/format.ts +69 -0
  276. package/src/protocol/utils/image-size.ts +236 -0
  277. package/src/protocol/utils/media-source.ts +243 -0
  278. package/src/protocol/utils/media-tags.ts +177 -0
  279. package/src/protocol/utils/media-type.ts +102 -0
  280. package/src/protocol/utils/payload.ts +157 -0
  281. package/src/protocol/utils/ref-attachments.ts +190 -0
  282. package/src/protocol/utils/ref-index-store.ts +279 -0
  283. package/src/protocol/utils/reply-limiter.ts +164 -0
  284. package/src/protocol/utils/session-store.ts +346 -0
  285. package/src/protocol/utils/target.ts +121 -0
  286. package/src/protocol/utils/text-chunk.ts +29 -0
  287. package/src/protocol/utils/text-parsing.ts +153 -0
  288. package/src/protocol/utils/upload-cache.ts +107 -0
  289. package/src/protocol/utils/voice-text.ts +16 -0
  290. package/src/storage/index.ts +24 -0
  291. package/src/storage/kv-store.ts +243 -0
  292. package/src/storage/session-adapter.ts +66 -0
  293. package/src/streaming.ts +255 -0
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Centralized API route templates for the QQ Open Platform.
3
+ *
4
+ * Eliminates C2C/Group path duplication by parameterizing on `ChatScope`.
5
+ */
6
+
7
+ import type { ChatScope } from "../types.js";
8
+
9
+ export function messagePath(scope: ChatScope, targetId: string): string {
10
+ return scope === "c2c" ? `/v2/users/${targetId}/messages` : `/v2/groups/${targetId}/messages`;
11
+ }
12
+
13
+ export function channelMessagePath(channelId: string): string {
14
+ return `/channels/${channelId}/messages`;
15
+ }
16
+
17
+ export function dmMessagePath(guildId: string): string {
18
+ return `/dms/${guildId}/messages`;
19
+ }
20
+
21
+ export function mediaUploadPath(scope: ChatScope, targetId: string): string {
22
+ return scope === "c2c" ? `/v2/users/${targetId}/files` : `/v2/groups/${targetId}/files`;
23
+ }
24
+
25
+ export function uploadPreparePath(scope: ChatScope, targetId: string): string {
26
+ return scope === "c2c"
27
+ ? `/v2/users/${targetId}/upload_prepare`
28
+ : `/v2/groups/${targetId}/upload_prepare`;
29
+ }
30
+
31
+ export function uploadPartFinishPath(scope: ChatScope, targetId: string): string {
32
+ return scope === "c2c"
33
+ ? `/v2/users/${targetId}/upload_part_finish`
34
+ : `/v2/groups/${targetId}/upload_part_finish`;
35
+ }
36
+
37
+ export function uploadCompletePath(scope: ChatScope, targetId: string): string {
38
+ return mediaUploadPath(scope, targetId);
39
+ }
40
+
41
+ export function streamMessagePath(openid: string): string {
42
+ return `/v2/users/${openid}/stream_messages`;
43
+ }
44
+
45
+ export function gatewayPath(): string {
46
+ return "/gateway";
47
+ }
48
+
49
+ export function interactionPath(interactionId: string): string {
50
+ return `/interactions/${interactionId}`;
51
+ }
52
+
53
+ /**
54
+ * Generate a message sequence number in the 0..65535 range.
55
+ *
56
+ * Used by both `messages.ts` and `media.ts` to avoid duplicate definitions.
57
+ */
58
+ export function getNextMsgSeq(_msgId: string): number {
59
+ const timePart = Date.now() % 100_000_000;
60
+ const random = Math.floor(Math.random() * 65536);
61
+ return (timePart ^ random) % 65536;
62
+ }
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Token management for the QQ Open Platform.
3
+ *
4
+ * Per-appId token manager with caching, singleflight, and background refresh.
5
+ * All state encapsulated in the class — no module-level globals.
6
+ */
7
+
8
+ import type { Logger } from "../types.js";
9
+ import { formatErrorMessage } from "../utils/format.js";
10
+
11
+ const DEFAULT_TOKEN_BASE_URL = "https://bots.qq.com";
12
+ const TOKEN_PATH = "/app/getAppAccessToken";
13
+
14
+ interface CachedToken {
15
+ token: string;
16
+ expiresAt: number;
17
+ appId: string;
18
+ }
19
+
20
+ export interface BackgroundRefreshOptions {
21
+ refreshAheadMs?: number;
22
+ randomOffsetMs?: number;
23
+ minRefreshIntervalMs?: number;
24
+ retryDelayMs?: number;
25
+ }
26
+
27
+ export class TokenManager {
28
+ private readonly cache = new Map<string, CachedToken>();
29
+ private readonly fetchPromises = new Map<string, Promise<string>>();
30
+ private readonly refreshControllers = new Map<string, AbortController>();
31
+ private readonly logger?: Logger;
32
+ private readonly resolveUserAgent: () => string;
33
+ private readonly baseUrl: string;
34
+
35
+ constructor(config?: { logger?: Logger; userAgent?: string | (() => string); baseUrl?: string }) {
36
+ this.logger = config?.logger;
37
+ const ua = config?.userAgent ?? "qqbot-nodejs/unknown";
38
+ this.resolveUserAgent = typeof ua === "function" ? ua : () => ua;
39
+ this.baseUrl = config?.baseUrl ?? DEFAULT_TOKEN_BASE_URL;
40
+ }
41
+
42
+ async getAccessToken(appId: string, clientSecret: string): Promise<string> {
43
+ const normalizedId = appId.trim();
44
+ const cached = this.cache.get(normalizedId);
45
+
46
+ const refreshAheadMs = cached
47
+ ? Math.min(5 * 60 * 1000, (cached.expiresAt - Date.now()) / 3)
48
+ : 0;
49
+
50
+ if (cached && Date.now() < cached.expiresAt - refreshAheadMs) {
51
+ return cached.token;
52
+ }
53
+
54
+ let pending = this.fetchPromises.get(normalizedId);
55
+ if (pending) {
56
+ this.logger?.debug?.(`[qqbot:token:${normalizedId}] Fetch in progress, reusing promise`);
57
+ return pending;
58
+ }
59
+
60
+ pending = (async () => {
61
+ try {
62
+ return await this.doFetchToken(normalizedId, clientSecret);
63
+ } finally {
64
+ this.fetchPromises.delete(normalizedId);
65
+ }
66
+ })();
67
+
68
+ this.fetchPromises.set(normalizedId, pending);
69
+ return pending;
70
+ }
71
+
72
+ clearCache(appId?: string): void {
73
+ if (appId) {
74
+ this.cache.delete(appId.trim());
75
+ this.logger?.debug?.(`[qqbot:token:${appId}] Cache cleared`);
76
+ } else {
77
+ this.cache.clear();
78
+ this.logger?.debug?.(`[token] All caches cleared`);
79
+ }
80
+ }
81
+
82
+ getStatus(appId: string): {
83
+ status: "valid" | "expired" | "refreshing" | "none";
84
+ expiresAt: number | null;
85
+ } {
86
+ if (this.fetchPromises.has(appId)) {
87
+ return { status: "refreshing", expiresAt: this.cache.get(appId)?.expiresAt ?? null };
88
+ }
89
+ const cached = this.cache.get(appId);
90
+ if (!cached) {
91
+ return { status: "none", expiresAt: null };
92
+ }
93
+ const remaining = cached.expiresAt - Date.now();
94
+ const isValid = remaining > Math.min(5 * 60 * 1000, remaining / 3);
95
+ return { status: isValid ? "valid" : "expired", expiresAt: cached.expiresAt };
96
+ }
97
+
98
+ startBackgroundRefresh(
99
+ appId: string,
100
+ clientSecret: string,
101
+ options?: BackgroundRefreshOptions,
102
+ ): void {
103
+ if (this.refreshControllers.has(appId)) {
104
+ this.logger?.info?.(`[qqbot:token:${appId}] Background refresh already running`);
105
+ return;
106
+ }
107
+
108
+ const {
109
+ refreshAheadMs = 5 * 60 * 1000,
110
+ randomOffsetMs = 30 * 1000,
111
+ minRefreshIntervalMs = 60 * 1000,
112
+ retryDelayMs = 5 * 1000,
113
+ } = options ?? {};
114
+
115
+ const controller = new AbortController();
116
+ this.refreshControllers.set(appId, controller);
117
+ const { signal } = controller;
118
+
119
+ const loop = async () => {
120
+ this.logger?.info?.(`[qqbot:token:${appId}] Background refresh started`);
121
+
122
+ while (!signal.aborted) {
123
+ try {
124
+ await this.getAccessToken(appId, clientSecret);
125
+ const cached = this.cache.get(appId);
126
+
127
+ if (cached) {
128
+ const expiresIn = cached.expiresAt - Date.now();
129
+ const randomOffset = Math.random() * randomOffsetMs;
130
+ const refreshIn = Math.max(
131
+ expiresIn - refreshAheadMs - randomOffset,
132
+ minRefreshIntervalMs,
133
+ );
134
+ this.logger?.debug?.(
135
+ `[qqbot:token:${appId}] Next refresh in ${Math.round(refreshIn / 1000)}s`,
136
+ );
137
+ await this.abortableSleep(refreshIn, signal);
138
+ } else {
139
+ await this.abortableSleep(minRefreshIntervalMs, signal);
140
+ }
141
+ } catch (err) {
142
+ if (signal.aborted) {
143
+ break;
144
+ }
145
+ this.logger?.error?.(
146
+ `[qqbot:token:${appId}] Background refresh failed: ${formatErrorMessage(err)}`,
147
+ );
148
+ await this.abortableSleep(retryDelayMs, signal);
149
+ }
150
+ }
151
+
152
+ this.refreshControllers.delete(appId);
153
+ this.logger?.info?.(`[qqbot:token:${appId}] Background refresh stopped`);
154
+ };
155
+
156
+ loop().catch((err) => {
157
+ this.refreshControllers.delete(appId);
158
+ this.logger?.error?.(`[qqbot:token:${appId}] Background refresh crashed: ${err}`);
159
+ });
160
+ }
161
+
162
+ stopBackgroundRefresh(appId?: string): void {
163
+ if (appId) {
164
+ const ctrl = this.refreshControllers.get(appId);
165
+ if (ctrl) {
166
+ ctrl.abort();
167
+ this.refreshControllers.delete(appId);
168
+ }
169
+ } else {
170
+ for (const ctrl of this.refreshControllers.values()) {
171
+ ctrl.abort();
172
+ }
173
+ this.refreshControllers.clear();
174
+ }
175
+ }
176
+
177
+ isBackgroundRefreshRunning(appId?: string): boolean {
178
+ if (appId) {
179
+ return this.refreshControllers.has(appId);
180
+ }
181
+ return this.refreshControllers.size > 0;
182
+ }
183
+
184
+ private async doFetchToken(appId: string, clientSecret: string): Promise<string> {
185
+ const url = `${this.baseUrl}${TOKEN_PATH}`;
186
+ this.logger?.debug?.(`[qqbot:token:${appId}] >>> POST ${url}`);
187
+
188
+ let response: Response;
189
+ try {
190
+ response = await fetch(url, {
191
+ method: "POST",
192
+ headers: {
193
+ "Content-Type": "application/json",
194
+ "User-Agent": this.resolveUserAgent(),
195
+ },
196
+ body: JSON.stringify({ appId, clientSecret }),
197
+ });
198
+ } catch (err) {
199
+ this.logger?.error?.(`[qqbot:token:${appId}] Network error: ${formatErrorMessage(err)}`);
200
+ throw new Error(`Network error getting access_token: ${formatErrorMessage(err)}`, {
201
+ cause: err,
202
+ });
203
+ }
204
+
205
+ const traceId = response.headers.get("x-tps-trace-id") ?? "";
206
+ this.logger?.debug?.(
207
+ `[qqbot:token:${appId}] <<< ${response.status}${traceId ? ` | TraceId: ${traceId}` : ""}`,
208
+ );
209
+
210
+ let data: { access_token?: string; expires_in?: number };
211
+ try {
212
+ const rawBody = await response.text();
213
+ const logBody = rawBody.replace(/"access_token"\s*:\s*"[^"]+"/g, '"access_token": "***"');
214
+ this.logger?.debug?.(`[qqbot:token:${appId}] <<< Body: ${logBody}`);
215
+ data = JSON.parse(rawBody);
216
+ } catch (err) {
217
+ throw new Error(`Failed to parse access_token response: ${formatErrorMessage(err)}`, {
218
+ cause: err,
219
+ });
220
+ }
221
+
222
+ if (!data.access_token) {
223
+ throw new Error(`Failed to get access_token: ${JSON.stringify(data)}`);
224
+ }
225
+
226
+ const expiresAt = Date.now() + (data.expires_in ?? 7200) * 1000;
227
+ this.cache.set(appId, { token: data.access_token, expiresAt, appId });
228
+ this.logger?.debug?.(
229
+ `[qqbot:token:${appId}] Cached, expires at: ${new Date(expiresAt).toISOString()}`,
230
+ );
231
+
232
+ return data.access_token;
233
+ }
234
+
235
+ private abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
236
+ return new Promise((resolve, reject) => {
237
+ const timer = setTimeout(resolve, ms);
238
+ if (signal.aborted) {
239
+ clearTimeout(timer);
240
+ reject(new Error("Aborted"));
241
+ return;
242
+ }
243
+ const onAbort = () => {
244
+ clearTimeout(timer);
245
+ reject(new Error("Aborted"));
246
+ };
247
+ signal.addEventListener("abort", onAbort, { once: true });
248
+ });
249
+ }
250
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Gateway message decoding utilities.
3
+ *
4
+ * Handles the various data formats that the QQ Bot WebSocket can deliver
5
+ * (string, Buffer, Buffer[], ArrayBuffer).
6
+ */
7
+
8
+ export function decodeGatewayMessageData(data: unknown): string {
9
+ if (typeof data === "string") {
10
+ return data;
11
+ }
12
+ if (Buffer.isBuffer(data)) {
13
+ return data.toString("utf8");
14
+ }
15
+ if (Array.isArray(data) && data.every((chunk) => Buffer.isBuffer(chunk))) {
16
+ return Buffer.concat(data).toString("utf8");
17
+ }
18
+ if (data instanceof ArrayBuffer) {
19
+ return Buffer.from(data).toString("utf8");
20
+ }
21
+ if (ArrayBuffer.isView(data)) {
22
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8");
23
+ }
24
+ return "";
25
+ }
26
+
27
+ export function readOptionalMessageSceneExt(event: Record<string, unknown>): string[] | undefined {
28
+ if (!("message_scene" in event)) {
29
+ return undefined;
30
+ }
31
+ const scene = event.message_scene as { ext?: string[] } | undefined;
32
+ return scene?.ext;
33
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * QQ Bot WebSocket Gateway protocol constants.
3
+ *
4
+ * Pure protocol-layer constants. Zero external dependencies.
5
+ */
6
+
7
+ /** QQ Bot WebSocket intents grouped by permission level. */
8
+ const INTENTS = {
9
+ GUILDS: 1 << 0,
10
+ GUILD_MEMBERS: 1 << 1,
11
+ PUBLIC_GUILD_MESSAGES: 1 << 30,
12
+ DIRECT_MESSAGE: 1 << 12,
13
+ GROUP_AND_C2C: 1 << 25,
14
+ /** Button interaction callbacks (INTERACTION_CREATE). */
15
+ INTERACTION: 1 << 26,
16
+ } as const;
17
+
18
+ export const FULL_INTENTS =
19
+ INTENTS.GUILDS |
20
+ INTENTS.GUILD_MEMBERS |
21
+ INTENTS.PUBLIC_GUILD_MESSAGES |
22
+ INTENTS.DIRECT_MESSAGE |
23
+ INTENTS.GROUP_AND_C2C |
24
+ INTENTS.INTERACTION;
25
+
26
+ export const RECONNECT_DELAYS = [1000, 2000, 5000, 10000, 30000, 60000] as const;
27
+ export const RATE_LIMIT_DELAY = 60000;
28
+ export const MAX_RECONNECT_ATTEMPTS = 100;
29
+ export const MAX_QUICK_DISCONNECT_COUNT = 3;
30
+ export const QUICK_DISCONNECT_THRESHOLD = 5000;
31
+
32
+ /** Gateway opcodes used by the QQ Bot WebSocket protocol. */
33
+ export const GatewayOp = {
34
+ DISPATCH: 0,
35
+ HEARTBEAT: 1,
36
+ IDENTIFY: 2,
37
+ RESUME: 6,
38
+ RECONNECT: 7,
39
+ INVALID_SESSION: 9,
40
+ HELLO: 10,
41
+ HEARTBEAT_ACK: 11,
42
+ } as const;
43
+
44
+ /** WebSocket close codes used by the QQ Gateway. */
45
+ export const GatewayCloseCode = {
46
+ NORMAL: 1000,
47
+ AUTH_FAILED: 4004,
48
+ INVALID_SESSION: 4006,
49
+ SEQ_OUT_OF_RANGE: 4007,
50
+ RATE_LIMITED: 4008,
51
+ SESSION_TIMEOUT: 4009,
52
+ SERVER_ERROR_START: 4900,
53
+ SERVER_ERROR_END: 4913,
54
+ INSUFFICIENT_INTENTS: 4914,
55
+ DISALLOWED_INTENTS: 4915,
56
+ } as const;
57
+
58
+ /** Event type strings dispatched under opcode 0 (DISPATCH). */
59
+ export const GatewayEvent = {
60
+ READY: "READY",
61
+ RESUMED: "RESUMED",
62
+ // ── Message events ──
63
+ C2C_MESSAGE_CREATE: "C2C_MESSAGE_CREATE",
64
+ AT_MESSAGE_CREATE: "AT_MESSAGE_CREATE",
65
+ DIRECT_MESSAGE_CREATE: "DIRECT_MESSAGE_CREATE",
66
+ GROUP_AT_MESSAGE_CREATE: "GROUP_AT_MESSAGE_CREATE",
67
+ GROUP_MESSAGE_CREATE: "GROUP_MESSAGE_CREATE",
68
+ // ── Interaction ──
69
+ INTERACTION_CREATE: "INTERACTION_CREATE",
70
+ // ── Guild events (P1) ──
71
+ GUILD_CREATE: "GUILD_CREATE",
72
+ GUILD_UPDATE: "GUILD_UPDATE",
73
+ GUILD_DELETE: "GUILD_DELETE",
74
+ GUILD_MEMBER_ADD: "GUILD_MEMBER_ADD",
75
+ GUILD_MEMBER_UPDATE: "GUILD_MEMBER_UPDATE",
76
+ GUILD_MEMBER_REMOVE: "GUILD_MEMBER_REMOVE",
77
+ CHANNEL_CREATE: "CHANNEL_CREATE",
78
+ CHANNEL_UPDATE: "CHANNEL_UPDATE",
79
+ CHANNEL_DELETE: "CHANNEL_DELETE",
80
+ // ── Group/C2C lifecycle events (P1) ──
81
+ GROUP_ADD_ROBOT: "GROUP_ADD_ROBOT",
82
+ GROUP_DEL_ROBOT: "GROUP_DEL_ROBOT",
83
+ GROUP_MSG_REJECT: "GROUP_MSG_REJECT",
84
+ GROUP_MSG_RECEIVE: "GROUP_MSG_RECEIVE",
85
+ FRIEND_ADD: "FRIEND_ADD",
86
+ FRIEND_DEL: "FRIEND_DEL",
87
+ C2C_MSG_REJECT: "C2C_MSG_REJECT",
88
+ C2C_MSG_RECEIVE: "C2C_MSG_RECEIVE",
89
+ // ── Reaction events ──
90
+ MESSAGE_REACTION_ADD: "MESSAGE_REACTION_ADD",
91
+ MESSAGE_REACTION_REMOVE: "MESSAGE_REACTION_REMOVE",
92
+ } as const;
93
+
94
+ /** Interaction sub-types carried in `InteractionEvent.data.type`. */
95
+ export const InteractionType = {
96
+ CONFIG_QUERY: 2001,
97
+ CONFIG_UPDATE: 2002,
98
+ } as const;