@zhin.js/adapter-napcat 3.0.1 → 4.0.1

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 (140) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +43 -96
  3. package/adapters/napcat.ts +39 -0
  4. package/agent/tools/ai_tts.ts +21 -0
  5. package/agent/tools/del_group_notice.ts +22 -0
  6. package/agent/tools/delete_essence_msg.ts +21 -0
  7. package/agent/tools/delete_friend.ts +20 -0
  8. package/agent/tools/download_file.ts +19 -0
  9. package/agent/tools/forward_single_msg.ts +32 -0
  10. package/agent/tools/get_ai_characters.ts +19 -0
  11. package/agent/tools/get_essence_list.ts +19 -0
  12. package/agent/tools/get_friend_msg_history.ts +20 -0
  13. package/agent/tools/get_group_file_url.ts +21 -0
  14. package/agent/tools/get_group_info_ex.ts +19 -0
  15. package/agent/tools/get_group_msg_history.ts +21 -0
  16. package/agent/tools/get_group_notice.ts +19 -0
  17. package/agent/tools/get_group_root_files.ts +19 -0
  18. package/agent/tools/get_group_shut_list.ts +19 -0
  19. package/agent/tools/get_mini_app_ark.ts +22 -0
  20. package/agent/tools/get_user_status.ts +18 -0
  21. package/agent/tools/group_sign.ts +20 -0
  22. package/agent/tools/mark_msg_as_read.ts +19 -0
  23. package/agent/tools/ocr_image.ts +18 -0
  24. package/agent/tools/send_forward_msg.ts +31 -0
  25. package/agent/tools/send_group_notice.ts +23 -0
  26. package/agent/tools/send_like.ts +20 -0
  27. package/agent/tools/send_poke.ts +20 -0
  28. package/agent/tools/set_avatar.ts +19 -0
  29. package/agent/tools/set_emoji_reaction.ts +20 -0
  30. package/agent/tools/set_essence_msg.ts +21 -0
  31. package/agent/tools/set_group_portrait.ts +22 -0
  32. package/agent/tools/set_online_status.ts +20 -0
  33. package/agent/tools/set_profile.ts +23 -0
  34. package/agent/tools/set_signature.ts +19 -0
  35. package/agent/tools/set_title.ts +23 -0
  36. package/agent/tools/translate.ts +18 -0
  37. package/agent/tools/upload_group_file.ts +23 -0
  38. package/lib/http-endpoint.d.ts +26 -0
  39. package/lib/http-endpoint.js +147 -0
  40. package/lib/index.d.ts +11 -21
  41. package/lib/index.js +10 -59
  42. package/lib/napcat-agent-deps.d.ts +51 -0
  43. package/lib/napcat-agent-deps.js +33 -0
  44. package/lib/napcat-inbound.d.ts +12 -5
  45. package/lib/napcat-inbound.js +28 -13
  46. package/lib/onebot-get-msg.d.ts +13 -2
  47. package/lib/onebot-get-msg.js +0 -1
  48. package/lib/protocol.d.ts +151 -0
  49. package/lib/protocol.js +217 -0
  50. package/lib/webhook.d.ts +2 -0
  51. package/lib/webhook.js +14 -0
  52. package/lib/ws-endpoint.d.ts +61 -0
  53. package/lib/ws-endpoint.js +357 -0
  54. package/lib/ws-transport.d.ts +13 -0
  55. package/lib/ws-transport.js +75 -0
  56. package/lib/ws-types.d.ts +17 -0
  57. package/lib/ws-types.js +1 -0
  58. package/lib/wss-auth.d.ts +2 -0
  59. package/lib/wss-auth.js +16 -0
  60. package/lib/wss-endpoint.d.ts +25 -0
  61. package/lib/wss-endpoint.js +157 -0
  62. package/package.json +48 -32
  63. package/plugin.ts +13 -0
  64. package/schema.json +48 -0
  65. package/src/http-endpoint.ts +197 -0
  66. package/src/index.ts +66 -82
  67. package/src/napcat-agent-deps.ts +95 -0
  68. package/src/napcat-inbound.ts +34 -10
  69. package/src/onebot-get-msg.ts +8 -2
  70. package/src/protocol.ts +373 -0
  71. package/src/webhook.ts +16 -0
  72. package/src/ws-endpoint.ts +452 -0
  73. package/src/ws-transport.ts +105 -0
  74. package/src/ws-types.ts +20 -0
  75. package/src/wss-auth.ts +17 -0
  76. package/src/wss-endpoint.ts +205 -0
  77. package/client/NapCatManagement.tsx +0 -113
  78. package/client/index.tsx +0 -11
  79. package/client/tsconfig.json +0 -7
  80. package/client/utils/api.ts +0 -30
  81. package/dist/index.js +0 -27
  82. package/lib/adapter.d.ts +0 -36
  83. package/lib/adapter.d.ts.map +0 -1
  84. package/lib/adapter.js +0 -102
  85. package/lib/adapter.js.map +0 -1
  86. package/lib/agent-prompt.d.ts +0 -3
  87. package/lib/agent-prompt.d.ts.map +0 -1
  88. package/lib/agent-prompt.js +0 -106
  89. package/lib/agent-prompt.js.map +0 -1
  90. package/lib/endpoint-base.d.ts +0 -144
  91. package/lib/endpoint-base.d.ts.map +0 -1
  92. package/lib/endpoint-base.js +0 -341
  93. package/lib/endpoint-base.js.map +0 -1
  94. package/lib/endpoint-http.d.ts +0 -17
  95. package/lib/endpoint-http.d.ts.map +0 -1
  96. package/lib/endpoint-http.js +0 -106
  97. package/lib/endpoint-http.js.map +0 -1
  98. package/lib/endpoint-ws-client.d.ts +0 -20
  99. package/lib/endpoint-ws-client.d.ts.map +0 -1
  100. package/lib/endpoint-ws-client.js +0 -139
  101. package/lib/endpoint-ws-client.js.map +0 -1
  102. package/lib/endpoint-ws-server.d.ts +0 -20
  103. package/lib/endpoint-ws-server.d.ts.map +0 -1
  104. package/lib/endpoint-ws-server.js +0 -137
  105. package/lib/endpoint-ws-server.js.map +0 -1
  106. package/lib/index.d.ts.map +0 -1
  107. package/lib/index.js.map +0 -1
  108. package/lib/napcat-inbound.d.ts.map +0 -1
  109. package/lib/napcat-inbound.js.map +0 -1
  110. package/lib/onebot-get-msg.d.ts.map +0 -1
  111. package/lib/onebot-get-msg.js.map +0 -1
  112. package/lib/routes.d.ts +0 -4
  113. package/lib/routes.d.ts.map +0 -1
  114. package/lib/routes.js +0 -61
  115. package/lib/routes.js.map +0 -1
  116. package/lib/segment-mapper.d.ts +0 -2
  117. package/lib/segment-mapper.d.ts.map +0 -1
  118. package/lib/segment-mapper.js +0 -2
  119. package/lib/segment-mapper.js.map +0 -1
  120. package/lib/tools.d.ts +0 -8
  121. package/lib/tools.d.ts.map +0 -1
  122. package/lib/tools.js +0 -605
  123. package/lib/tools.js.map +0 -1
  124. package/lib/types.d.ts +0 -275
  125. package/lib/types.d.ts.map +0 -1
  126. package/lib/types.js +0 -6
  127. package/lib/types.js.map +0 -1
  128. package/plugin.yml +0 -3
  129. package/src/adapter.ts +0 -109
  130. package/src/agent-prompt.ts +0 -116
  131. package/src/endpoint-base.ts +0 -386
  132. package/src/endpoint-http.ts +0 -95
  133. package/src/endpoint-ws-client.ts +0 -137
  134. package/src/endpoint-ws-server.ts +0 -136
  135. package/src/routes.ts +0 -61
  136. package/src/segment-mapper.ts +0 -1
  137. package/src/tools.ts +0 -632
  138. package/src/types.ts +0 -266
  139. /package/{skills/napcat → agent}/PERMITS.md +0 -0
  140. /package/{skills/napcat/SKILL.md → agent/skills/napcat.md} +0 -0
@@ -0,0 +1,452 @@
1
+ /**
2
+ * NapCat WS client endpoint — outbound connect to NapCat.
3
+ */
4
+ import WebSocket from 'ws';
5
+ import { clearInterval, clearTimeout, setTimeout } from 'node:timers';
6
+ import type { EndpointInstance } from '@zhin.js/adapter';
7
+ import type { MessageGateway } from '@zhin.js/core/runtime';
8
+ import { formatCompact, getLogger } from '@zhin.js/logger';
9
+ import type { CapabilityId } from '@zhin.js/plugin-runtime';
10
+ import { registerNapcatAgentEndpoint } from './napcat-agent-deps.js';
11
+ import {
12
+ InboundMessageDeduper,
13
+ isNapCatBotMentioned,
14
+ isSelfMessage,
15
+ normalizeMessage,
16
+ } from './napcat-inbound.js';
17
+ import {
18
+ buildSendAction,
19
+ buildWsConnectOptions,
20
+ formatInboundContent,
21
+ formatInboundTarget,
22
+ formatOutboundSegments,
23
+ isMessageEvent,
24
+ senderNickname,
25
+ senderUserId,
26
+ type NapCatEvent,
27
+ type NapCatWsConfig,
28
+ } from './protocol.js';
29
+ import {
30
+ callNapCatWsAction,
31
+ handleNapCatWsMessage,
32
+ rejectAllPending,
33
+ startNapCatHeartbeat,
34
+ } from './ws-transport.js';
35
+ import {
36
+ type NapCatPendingAction,
37
+ type NapCatWsCreateOptions,
38
+ type NapCatWsSocket,
39
+ } from './ws-types.js';
40
+
41
+ const logger = getLogger('napcat');
42
+
43
+ export interface NapCatWsEndpointOptions {
44
+ readonly id: CapabilityId;
45
+ readonly gateway: MessageGateway;
46
+ readonly config: NapCatWsConfig;
47
+ readonly createWebSocket?: (
48
+ url: string,
49
+ options: NapCatWsCreateOptions,
50
+ ) => NapCatWsSocket;
51
+ }
52
+
53
+ export class NapCatWsEndpoint implements EndpointInstance {
54
+ readonly #options: NapCatWsEndpointOptions;
55
+ readonly #inboundDeduper = new InboundMessageDeduper();
56
+ #ws?: NapCatWsSocket;
57
+ #reconnectTimer?: NodeJS.Timeout;
58
+ #heartbeatTimer?: NodeJS.Timeout;
59
+ #requestId = { value: 0 };
60
+ #pending = new Map<string, NapCatPendingAction>();
61
+ #open = false;
62
+ #started = false;
63
+ #stopping = false;
64
+ #unregisterAgent?: () => void;
65
+
66
+ constructor(options: NapCatWsEndpointOptions) {
67
+ this.#options = options;
68
+ }
69
+
70
+ async start(): Promise<void> {
71
+ if (this.#started) return;
72
+ this.#started = true;
73
+ this.#stopping = false;
74
+ this.#unregisterAgent = registerNapcatAgentEndpoint(this.#options.config.name, this);
75
+ try {
76
+ await this.#connect();
77
+ } catch (err) {
78
+ this.#started = false;
79
+ throw err;
80
+ }
81
+ }
82
+
83
+ open(): void {
84
+ this.#open = true;
85
+ }
86
+
87
+ close(): void {
88
+ this.#open = false;
89
+ }
90
+
91
+ async stop(): Promise<void> {
92
+ this.#open = false;
93
+ this.#stopping = true;
94
+ this.#started = false;
95
+ this.#unregisterAgent?.();
96
+ this.#unregisterAgent = undefined;
97
+ if (this.#reconnectTimer) {
98
+ clearTimeout(this.#reconnectTimer);
99
+ this.#reconnectTimer = undefined;
100
+ }
101
+ if (this.#heartbeatTimer) {
102
+ clearInterval(this.#heartbeatTimer);
103
+ this.#heartbeatTimer = undefined;
104
+ }
105
+ rejectAllPending(this.#pending);
106
+ this.#inboundDeduper.clear();
107
+ if (this.#ws) {
108
+ try {
109
+ this.#ws.close();
110
+ } catch {
111
+ /* ignore */
112
+ }
113
+ this.#ws = undefined;
114
+ }
115
+ logger.debug(formatCompact({ op: 'disconnect', endpoint: this.#options.config.name }));
116
+ }
117
+
118
+ async send({ target, payload }: { readonly target: string; readonly payload: unknown }): Promise<string> {
119
+ const message = formatOutboundSegments(payload);
120
+ const { action, params } = buildSendAction(target, message);
121
+ const data = await this.callApi(action, params) as { message_id?: number | string } | undefined;
122
+ const messageId = data?.message_id != null ? String(data.message_id) : '';
123
+ logger.debug(formatCompact({
124
+ op: 'napcat_send',
125
+ endpoint: this.#options.config.name,
126
+ target,
127
+ messageId,
128
+ }));
129
+ return messageId;
130
+ }
131
+
132
+ callApi(action: string, params: Record<string, unknown> = {}): Promise<unknown> {
133
+ return callNapCatWsAction(this.#ws, this.#pending, this.#requestId, action, params);
134
+ }
135
+
136
+ // ── Agent-facing API wrappers ─────────────────────────────────────
137
+
138
+ async setTitle(groupId: number, userId: number, title: string, duration = -1): Promise<boolean> {
139
+ await this.callApi('set_group_special_title', {
140
+ group_id: groupId,
141
+ user_id: userId,
142
+ special_title: title,
143
+ duration,
144
+ });
145
+ return true;
146
+ }
147
+
148
+ sendLike(userId: number, times = 1) {
149
+ return this.callApi('send_like', { user_id: userId, times });
150
+ }
151
+
152
+ deleteFriend(userId: number) {
153
+ return this.callApi('delete_friend', { user_id: userId });
154
+ }
155
+
156
+ markMsgAsRead(messageId: number) {
157
+ return this.callApi('mark_msg_as_read', { message_id: messageId });
158
+ }
159
+
160
+ ocrImage(image: string) {
161
+ return this.callApi('ocr_image', { image });
162
+ }
163
+
164
+ setQQProfile(
165
+ nickname: string,
166
+ company?: string,
167
+ email?: string,
168
+ college?: string,
169
+ personalNote?: string,
170
+ ) {
171
+ return this.callApi('set_qq_profile', {
172
+ nickname,
173
+ company,
174
+ email,
175
+ college,
176
+ personal_note: personalNote,
177
+ });
178
+ }
179
+
180
+ setGroupPortrait(groupId: number, file: string) {
181
+ return this.callApi('set_group_portrait', { group_id: groupId, file });
182
+ }
183
+
184
+ setEssenceMsg(messageId: number) {
185
+ return this.callApi('set_essence_msg', { message_id: messageId });
186
+ }
187
+
188
+ deleteEssenceMsg(messageId: number) {
189
+ return this.callApi('delete_essence_msg', { message_id: messageId });
190
+ }
191
+
192
+ getEssenceMsgList(groupId: number) {
193
+ return this.callApi('get_essence_msg_list', { group_id: groupId });
194
+ }
195
+
196
+ sendGroupSign(groupId: number) {
197
+ return this.callApi('send_group_sign', { group_id: groupId });
198
+ }
199
+
200
+ sendGroupNotice(groupId: number, content: string, image?: string) {
201
+ return this.callApi('_send_group_notice', { group_id: groupId, content, image });
202
+ }
203
+
204
+ getGroupNotice(groupId: number) {
205
+ return this.callApi('_get_group_notice', { group_id: groupId });
206
+ }
207
+
208
+ deleteGroupNotice(groupId: number, noticeId: string) {
209
+ return this.callApi('_del_group_notice', { group_id: groupId, notice_id: noticeId });
210
+ }
211
+
212
+ uploadGroupFile(groupId: number, file: string, name: string, folder?: string) {
213
+ return this.callApi('upload_group_file', { group_id: groupId, file, name, folder });
214
+ }
215
+
216
+ getGroupRootFiles(groupId: number) {
217
+ return this.callApi('get_group_root_files', { group_id: groupId });
218
+ }
219
+
220
+ getGroupFileUrl(groupId: number, fileId: string, busid: number) {
221
+ return this.callApi('get_group_file_url', { group_id: groupId, file_id: fileId, busid });
222
+ }
223
+
224
+ downloadFile(url: string, threadCount = 1, headers?: string[]) {
225
+ return this.callApi('download_file', { url, thread_count: threadCount, headers });
226
+ }
227
+
228
+ setOnlineStatus(status: number, extStatus: number) {
229
+ return this.callApi('set_online_status', { status, ext_status: extStatus });
230
+ }
231
+
232
+ setQQAvatar(file: string) {
233
+ return this.callApi('set_qq_avatar', { file });
234
+ }
235
+
236
+ forwardFriendSingleMsg(userId: number, messageId: number) {
237
+ return this.callApi('forward_friend_single_msg', { user_id: userId, message_id: messageId });
238
+ }
239
+
240
+ forwardGroupSingleMsg(groupId: number, messageId: number) {
241
+ return this.callApi('forward_group_single_msg', { group_id: groupId, message_id: messageId });
242
+ }
243
+
244
+ translateEn2Zh(sourceText: string) {
245
+ return this.callApi('translate_en2zh', { source_text: sourceText });
246
+ }
247
+
248
+ setMsgEmojiLike(messageId: number, emojiId: string) {
249
+ return this.callApi('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId });
250
+ }
251
+
252
+ sendForwardMsg(messageType: 'private' | 'group', id: number, messages: unknown[]) {
253
+ return this.callApi('send_forward_msg', {
254
+ message_type: messageType,
255
+ [messageType === 'group' ? 'group_id' : 'user_id']: id,
256
+ messages,
257
+ });
258
+ }
259
+
260
+ getFriendMsgHistory(userId: number, messageSeq?: number, count?: number) {
261
+ return this.callApi('get_friend_msg_history', {
262
+ user_id: userId,
263
+ message_seq: messageSeq,
264
+ count,
265
+ });
266
+ }
267
+
268
+ getGroupMsgHistory(groupId: number, messageSeq?: number, count?: number) {
269
+ return this.callApi('get_group_msg_history', {
270
+ group_id: groupId,
271
+ message_seq: messageSeq,
272
+ count,
273
+ });
274
+ }
275
+
276
+ setSelfLongnick(longnick: string) {
277
+ return this.callApi('set_self_longnick', { longNick: longnick });
278
+ }
279
+
280
+ getGroupInfoEx(groupId: number) {
281
+ return this.callApi('get_group_info_ex', { group_id: groupId });
282
+ }
283
+
284
+ sendPoke(userId: number, groupId?: number) {
285
+ return this.callApi('send_poke', { user_id: userId, group_id: groupId });
286
+ }
287
+
288
+ ncGetUserStatus(userId: number) {
289
+ return this.callApi('nc_get_user_status', { user_id: userId });
290
+ }
291
+
292
+ getGroupShutList(groupId: number) {
293
+ return this.callApi('get_group_shut_list', { group_id: groupId });
294
+ }
295
+
296
+ getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) {
297
+ return this.callApi('get_mini_app_ark', { type, title, desc, picUrl, jumpUrl });
298
+ }
299
+
300
+ getAiCharacters(groupId: number) {
301
+ return this.callApi('get_ai_characters', { group_id: groupId });
302
+ }
303
+
304
+ sendGroupAiRecord(groupId: number, characterId: string, text: string) {
305
+ return this.callApi('send_group_ai_record', {
306
+ group_id: groupId,
307
+ character: characterId,
308
+ text,
309
+ });
310
+ }
311
+
312
+ /** Test / internal: admit a parsed event when the endpoint is open. */
313
+ admit(ev: NapCatEvent): void {
314
+ if (!this.#open || !isMessageEvent(ev)) return;
315
+ if (isSelfMessage(ev)) return;
316
+ const msgId = String(ev.message_id);
317
+ if (!this.#inboundDeduper.shouldProcess(msgId)) return;
318
+ if (Array.isArray(ev.message) || typeof ev.message === 'string') {
319
+ ev = { ...ev, message: normalizeMessage(ev.message) };
320
+ }
321
+ const target = formatInboundTarget(ev);
322
+ const content = formatInboundContent(ev);
323
+ const nickname = senderNickname(ev);
324
+ const mentioned = isNapCatBotMentioned(ev);
325
+ void this.#options.gateway.receive({
326
+ adapter: this.#options.id,
327
+ target,
328
+ content,
329
+ sender: senderUserId(ev),
330
+ id: msgId,
331
+ metadata: Object.freeze({
332
+ message_type: ev.message_type,
333
+ user_id: ev.user_id != null ? String(ev.user_id) : undefined,
334
+ group_id: ev.group_id != null ? String(ev.group_id) : undefined,
335
+ endpoint: this.#options.config.name,
336
+ time: ev.time,
337
+ self_id: ev.self_id != null ? String(ev.self_id) : undefined,
338
+ role: ev.sender?.role,
339
+ ...(nickname ? { nickname } : {}),
340
+ ...(mentioned ? { mentioned: true } : {}),
341
+ }),
342
+ }).catch((err) => {
343
+ logger.warn(formatCompact({
344
+ op: 'napcat_gateway_receive_failed',
345
+ target,
346
+ error: err instanceof Error ? err.message : String(err),
347
+ }));
348
+ });
349
+ }
350
+
351
+ async #connect(): Promise<void> {
352
+ const { url, headers, safeUrl } = buildWsConnectOptions(this.#options.config);
353
+ const create = this.#options.createWebSocket
354
+ ?? ((connectUrl: string, options: NapCatWsCreateOptions) =>
355
+ new WebSocket(connectUrl, { headers: options.headers }) as unknown as NapCatWsSocket);
356
+
357
+ await new Promise<void>((resolve, reject) => {
358
+ let settled = false;
359
+ const ws = create(url, { headers });
360
+ this.#ws = ws;
361
+
362
+ ws.on('open', () => {
363
+ if (settled) return;
364
+ settled = true;
365
+ if (!this.#options.config.access_token) {
366
+ logger.warn(formatCompact({
367
+ endpoint: this.#options.config.name,
368
+ ok: false,
369
+ error: 'missing access_token',
370
+ }));
371
+ }
372
+ logger.debug(formatCompact({
373
+ endpoint: this.#options.config.name,
374
+ mode: 'ws',
375
+ url: safeUrl,
376
+ }));
377
+ this.#heartbeatTimer = this.#stopping
378
+ ? this.#heartbeatTimer
379
+ : startNapCatHeartbeat(
380
+ this.#ws,
381
+ this.#options.config.heartbeat_interval,
382
+ this.#heartbeatTimer,
383
+ );
384
+ resolve();
385
+ });
386
+
387
+ ws.on('message', (data) => {
388
+ handleNapCatWsMessage(data, {
389
+ endpointName: this.#options.config.name,
390
+ pending: this.#pending,
391
+ admit: (event) => this.admit(event),
392
+ });
393
+ });
394
+
395
+ ws.on('close', (code, reason) => {
396
+ const reasonStr = typeof reason === 'string'
397
+ ? reason
398
+ : Buffer.isBuffer(reason)
399
+ ? reason.toString()
400
+ : String(reason ?? '');
401
+ const codeNum = typeof code === 'number' ? code : Number(code ?? 0);
402
+ const codeHint = codeNum === 1005
403
+ ? ' [no status]'
404
+ : codeNum === 1006
405
+ ? ' [abnormal]'
406
+ : '';
407
+ logger.warn(formatCompact({
408
+ op: 'disconnect',
409
+ endpoint: this.#options.config.name,
410
+ code: codeNum,
411
+ error: `${reasonStr || 'closed'}${codeHint}`,
412
+ reconnect_ms: this.#options.config.reconnect_interval,
413
+ }));
414
+ if (!settled) {
415
+ settled = true;
416
+ reject(new Error(`NapCat WS closed: ${codeNum} ${reasonStr}`));
417
+ }
418
+ this.#scheduleReconnect();
419
+ });
420
+
421
+ ws.on('error', (err) => {
422
+ const error = err instanceof Error ? err : new Error(String(err));
423
+ logger.warn(formatCompact({
424
+ op: 'ws_error',
425
+ endpoint: this.#options.config.name,
426
+ ok: false,
427
+ error: error.message,
428
+ }));
429
+ if (!settled) {
430
+ settled = true;
431
+ reject(error);
432
+ }
433
+ });
434
+ });
435
+ }
436
+
437
+ #scheduleReconnect(): void {
438
+ if (this.#stopping || !this.#started || this.#reconnectTimer) return;
439
+ const delay = this.#options.config.reconnect_interval;
440
+ this.#reconnectTimer = setTimeout(() => {
441
+ this.#reconnectTimer = undefined;
442
+ void this.#connect().catch((err) => {
443
+ logger.warn(formatCompact({
444
+ op: 'reconnect',
445
+ endpoint: this.#options.config.name,
446
+ ok: false,
447
+ error: err instanceof Error ? err.message : String(err),
448
+ }));
449
+ });
450
+ }, delay);
451
+ }
452
+ }
@@ -0,0 +1,105 @@
1
+ import { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';
2
+ import { formatCompact, getLogger } from '@zhin.js/logger';
3
+ import {
4
+ type NapCatActionRequest,
5
+ type NapCatActionResponse,
6
+ type NapCatEvent,
7
+ } from './protocol.js';
8
+ import {
9
+ WS_OPEN,
10
+ type NapCatPendingAction,
11
+ type NapCatWsSocket,
12
+ } from './ws-types.js';
13
+
14
+ const logger = getLogger('napcat');
15
+
16
+ export function decodeWsPayload(data: unknown): string {
17
+ if (typeof data === 'string') return data;
18
+ if (Buffer.isBuffer(data)) return data.toString();
19
+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
20
+ return String(data ?? '');
21
+ }
22
+
23
+ export function handleNapCatWsMessage(
24
+ data: unknown,
25
+ options: {
26
+ readonly endpointName: string;
27
+ readonly pending: Map<string, NapCatPendingAction>;
28
+ readonly admit: (ev: NapCatEvent) => void;
29
+ },
30
+ ): void {
31
+ try {
32
+ const raw = decodeWsPayload(data);
33
+ const msg = JSON.parse(raw) as NapCatEvent | NapCatActionResponse;
34
+ if ('echo' in msg && typeof (msg as NapCatActionResponse).echo === 'string') {
35
+ const resp = msg as NapCatActionResponse;
36
+ const pending = options.pending.get(resp.echo!);
37
+ if (pending) {
38
+ options.pending.delete(resp.echo!);
39
+ clearTimeout(pending.timeout);
40
+ if (resp.status === 'ok') pending.resolve(resp.data);
41
+ else {
42
+ pending.reject(new Error(
43
+ `API error [${resp.retcode}]: ${resp.message || resp.wording || 'unknown'}`,
44
+ ));
45
+ }
46
+ }
47
+ return;
48
+ }
49
+ options.admit(msg as NapCatEvent);
50
+ } catch (error) {
51
+ logger.warn(formatCompact({
52
+ op: 'napcat_parse_failed',
53
+ endpoint: options.endpointName,
54
+ error: error instanceof Error ? error.message : String(error),
55
+ }));
56
+ }
57
+ }
58
+
59
+ export function callNapCatWsAction(
60
+ ws: NapCatWsSocket | undefined,
61
+ pending: Map<string, NapCatPendingAction>,
62
+ requestId: { value: number },
63
+ action: string,
64
+ params: Record<string, unknown>,
65
+ ): Promise<unknown> {
66
+ if (!ws || ws.readyState !== WS_OPEN) {
67
+ return Promise.reject(new Error('WebSocket is not connected'));
68
+ }
69
+ const echo = `req_${++requestId.value}`;
70
+ const req: NapCatActionRequest = { action, params, echo };
71
+ return new Promise((resolve, reject) => {
72
+ const timeout = setTimeout(() => {
73
+ pending.delete(echo);
74
+ reject(new Error(`API call timeout: ${action}`));
75
+ }, 30_000);
76
+ pending.set(echo, { resolve, reject, timeout });
77
+ ws.send(JSON.stringify(req));
78
+ });
79
+ }
80
+
81
+ export function startNapCatHeartbeat(
82
+ ws: NapCatWsSocket | undefined,
83
+ intervalMs: number,
84
+ existingTimer?: NodeJS.Timeout,
85
+ ): NodeJS.Timeout {
86
+ if (existingTimer) clearInterval(existingTimer);
87
+ return setInterval(() => {
88
+ try {
89
+ ws?.ping?.();
90
+ } catch {
91
+ /* ignore */
92
+ }
93
+ }, intervalMs);
94
+ }
95
+
96
+ export function rejectAllPending(
97
+ pending: Map<string, NapCatPendingAction>,
98
+ message = 'Connection closed',
99
+ ): void {
100
+ for (const [, entry] of pending) {
101
+ clearTimeout(entry.timeout);
102
+ entry.reject(new Error(message));
103
+ }
104
+ pending.clear();
105
+ }
@@ -0,0 +1,20 @@
1
+ /** Minimal WS surface used by the endpoint (real `ws` or test mock). */
2
+ export interface NapCatWsSocket {
3
+ readonly readyState: number;
4
+ send(data: string): void;
5
+ close(code?: number, reason?: string): void;
6
+ ping?(): void;
7
+ on(event: 'open' | 'message' | 'close' | 'error', listener: (...args: unknown[]) => void): void;
8
+ }
9
+
10
+ export interface NapCatWsCreateOptions {
11
+ readonly headers?: Record<string, string>;
12
+ }
13
+
14
+ export const WS_OPEN = 1;
15
+
16
+ export interface NapCatPendingAction {
17
+ resolve: (value: unknown) => void;
18
+ reject: (err: Error) => void;
19
+ timeout: NodeJS.Timeout;
20
+ }
@@ -0,0 +1,17 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+
3
+ export function verifyNapCatAccessToken(
4
+ accessToken: string | undefined,
5
+ request: IncomingMessage,
6
+ ): boolean {
7
+ if (!accessToken) return true;
8
+ const auth = request.headers.authorization ?? '';
9
+ if (auth === `Bearer ${accessToken}`) return true;
10
+ try {
11
+ const url = new URL(request.url ?? '/', 'http://localhost');
12
+ if (url.searchParams.get('access_token') === accessToken) return true;
13
+ } catch {
14
+ /* ignore */
15
+ }
16
+ return false;
17
+ }