@im-more/dsh-kook 0.0.0-stage → 0.1.0

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +12 -0
  3. package/lib/index.js +2380 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +53 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +138 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +46 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +52 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +88 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +564 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +46 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +159 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +17 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +24 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +15 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +15 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/kmarkdown.d.ts +76 -0
  30. package/lib/types/kmarkdown.d.ts.map +1 -0
  31. package/lib/types/kmarkdown.js +201 -0
  32. package/lib/types/kmarkdown.js.map +1 -0
  33. package/lib/types/modes/kmarkdown.d.ts +17 -0
  34. package/lib/types/modes/kmarkdown.d.ts.map +1 -0
  35. package/lib/types/modes/kmarkdown.js +166 -0
  36. package/lib/types/modes/kmarkdown.js.map +1 -0
  37. package/lib/types/modes/shared.d.ts +192 -0
  38. package/lib/types/modes/shared.d.ts.map +1 -0
  39. package/lib/types/modes/shared.js +371 -0
  40. package/lib/types/modes/shared.js.map +1 -0
  41. package/lib/types/request.d.ts +53 -0
  42. package/lib/types/request.d.ts.map +1 -0
  43. package/lib/types/request.js +147 -0
  44. package/lib/types/request.js.map +1 -0
  45. package/lib/types/send.d.ts +57 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +141 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/types.d.ts +807 -0
  50. package/lib/types/types.d.ts.map +1 -0
  51. package/lib/types/types.js +168 -0
  52. package/lib/types/types.js.map +1 -0
  53. package/lib/types/webhook.d.ts +35 -0
  54. package/lib/types/webhook.d.ts.map +1 -0
  55. package/lib/types/webhook.js +132 -0
  56. package/lib/types/webhook.js.map +1 -0
  57. package/lib/types/ws.d.ts +54 -0
  58. package/lib/types/ws.d.ts.map +1 -0
  59. package/lib/types/ws.js +358 -0
  60. package/lib/types/ws.js.map +1 -0
  61. package/package.json +61 -3
  62. package/src/bot.ts +217 -0
  63. package/src/config.ts +84 -0
  64. package/src/decode.ts +660 -0
  65. package/src/errors.ts +188 -0
  66. package/src/identity.ts +32 -0
  67. package/src/index.ts +80 -0
  68. package/src/kmarkdown.ts +246 -0
  69. package/src/modes/kmarkdown.ts +204 -0
  70. package/src/modes/shared.ts +498 -0
  71. package/src/request.ts +196 -0
  72. package/src/send.ts +216 -0
  73. package/src/types.ts +764 -0
  74. package/src/webhook.ts +170 -0
  75. package/src/ws.ts +431 -0
  76. package/README.md +0 -3
package/lib/index.js ADDED
@@ -0,0 +1,2380 @@
1
+ import { Adapter, ElementRegistry, PlatformError, Status, defineMode, h, normalize } from "@deepseek-ai/cordis-plugin-im-core";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import { isPhrasingContainer } from "@deepseek-ai/satori-element";
4
+ // \0rolldown/runtime.js
5
+ var __defProp = Object.defineProperty;
6
+ var __exportAll = (all, no_symbols) => {
7
+ let target = {};
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
13
+ return target;
14
+ };
15
+ // lib/types/errors.js
16
+ /** One failed KOOK call: an HTTP answer, a non-zero business code, or a Gateway refusal code. */
17
+ var KookApiError = class extends Error {
18
+ status;
19
+ code;
20
+ retryAfterMs;
21
+ constructor(message, init = {}) {
22
+ super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
23
+ this.name = "KookApiError";
24
+ this.status = init.status;
25
+ this.code = init.code;
26
+ this.retryAfterMs = init.retryAfterMs;
27
+ }
28
+ };
29
+ /** The configured `selfId` and the account the bot token belongs to disagree. */
30
+ var KookIdentityError = class extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "KookIdentityError";
34
+ }
35
+ };
36
+ /** HELLO codes that only a corrected configuration can fix (missing parameter, invalid/failed/expired token). */
37
+ const PERMANENT_HELLO_CODES = /* @__PURE__ */ new Set([
38
+ 40100,
39
+ 40101,
40
+ 40102,
41
+ 40103
42
+ ]);
43
+ /** RECONNECT codes that report a resume/session/sn refusal; v1 does not resume, so the connection is simply redialed. */
44
+ const RESUME_CODES = /* @__PURE__ */ new Set([
45
+ 40106,
46
+ 40107,
47
+ 40108
48
+ ]);
49
+ /**
50
+ * Whether a HELLO answer means the configured token cannot work at all.
51
+ * @param code - `d.code` of the HELLO frame.
52
+ * @returns true for the four documented configuration refusals.
53
+ */
54
+ function isPermanentHelloCode(code) {
55
+ return code !== void 0 && PERMANENT_HELLO_CODES.has(code);
56
+ }
57
+ /**
58
+ * Whether a RECONNECT notice names a resume/session refusal.
59
+ * @param code - `d.code` of the RECONNECT frame.
60
+ * @returns true for the three documented resume refusals.
61
+ */
62
+ function isResumeCode(code) {
63
+ return code !== void 0 && RESUME_CODES.has(code);
64
+ }
65
+ /** Whether a caught value is the abort error of a cancelled request. */
66
+ function isAbortError$1(error) {
67
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
68
+ }
69
+ /**
70
+ * Map any KOOK failure onto the core platform taxonomy.
71
+ *
72
+ * A non-2xx answer and a non-zero business code are the platform refusing the call, so nothing was published; a
73
+ * transport failure or a 5xx answer leaves the outcome unknown. Business codes are not interpreted beyond the two
74
+ * documented Gateway ranges, because KOOK publishes no error-code reference (the linked page is gone).
75
+ *
76
+ * @param error - the caught failure.
77
+ * @returns the classified platform error.
78
+ */
79
+ function classifyKookError(error) {
80
+ if (error instanceof PlatformError) return error;
81
+ if (isAbortError$1(error)) return new PlatformError("fatal", error instanceof Error ? error.message : "kook request aborted", {
82
+ published: "unknown",
83
+ cause: error
84
+ });
85
+ if (error instanceof KookApiError) {
86
+ const init = {
87
+ ...error.code === void 0 ? {} : { code: error.code },
88
+ ...error.retryAfterMs === void 0 ? {} : { retryAfterMs: error.retryAfterMs },
89
+ cause: error
90
+ };
91
+ if (error.code !== void 0 && error.status === void 0) {
92
+ if (isPermanentHelloCode(error.code)) return new PlatformError("permission", error.message, {
93
+ ...init,
94
+ published: "no"
95
+ });
96
+ if (isResumeCode(error.code)) return new PlatformError("fatal", error.message, {
97
+ ...init,
98
+ published: "no"
99
+ });
100
+ return new PlatformError("invalid", error.message, {
101
+ ...init,
102
+ published: "no"
103
+ });
104
+ }
105
+ if (error.status === 429) return new PlatformError("rate-limit", error.message, {
106
+ ...init,
107
+ published: "no"
108
+ });
109
+ if (error.code !== void 0) {
110
+ if (error.status === 401 || error.status === 403) return new PlatformError("permission", error.message, {
111
+ ...init,
112
+ published: "no"
113
+ });
114
+ if (error.status === 404) return new PlatformError("not-found", error.message, {
115
+ ...init,
116
+ published: "no"
117
+ });
118
+ if (error.status !== void 0 && error.status >= 500) return new PlatformError("retryable", error.message, {
119
+ ...init,
120
+ published: "unknown"
121
+ });
122
+ return new PlatformError("invalid", error.message, {
123
+ ...init,
124
+ published: "no"
125
+ });
126
+ }
127
+ if (error.status === 401 || error.status === 403) return new PlatformError("permission", error.message, {
128
+ ...init,
129
+ published: "no"
130
+ });
131
+ if (error.status === 404) return new PlatformError("not-found", error.message, {
132
+ ...init,
133
+ published: "no"
134
+ });
135
+ if (error.status !== void 0 && error.status >= 400 && error.status < 500) return new PlatformError("invalid", error.message, {
136
+ ...init,
137
+ published: "no"
138
+ });
139
+ if (error.status !== void 0 && error.status >= 500) return new PlatformError("retryable", error.message, {
140
+ ...init,
141
+ published: "unknown"
142
+ });
143
+ return new PlatformError("retryable", error.message, {
144
+ ...init,
145
+ published: "unknown"
146
+ });
147
+ }
148
+ const message = error instanceof Error ? error.message : String(error);
149
+ return new PlatformError("retryable", `kook request failed: ${message}`, {
150
+ published: "unknown",
151
+ cause: error
152
+ });
153
+ }
154
+ // lib/types/request.js
155
+ /**
156
+ * KOOK API transport: one request path for every v3 endpoint, the `{ code, message, data }` envelope and its error
157
+ * classification input, and the rate-limit headers.
158
+ *
159
+ * The typed method surface lives on `Internal` (`types.ts`); this module owns the wire mechanics so the migrated
160
+ * client and the adapter's own calls cannot diverge.
161
+ */
162
+ /**
163
+ * Build the request endpoints for one bot.
164
+ * @param ctx - context whose `http` service performs requests.
165
+ * @param apiBaseUrl - API root (`https://www.kookapp.cn/api/v3`).
166
+ * @param token - bot token.
167
+ * @returns the shared request endpoints.
168
+ */
169
+ function createKookRequest(ctx, apiBaseUrl, token) {
170
+ return {
171
+ ctx,
172
+ baseUrl: apiBaseUrl.replace(/\/+$/, ""),
173
+ token
174
+ };
175
+ }
176
+ /** Whether a caught value is the abort error of a cancelled request. */
177
+ function isAbortError(error) {
178
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
179
+ }
180
+ /**
181
+ * Deliver the cancellation of a request: the signal's reason when it aborted, else the error `ctx.http` produced.
182
+ * @param cause - the value `ctx.http` rejected with.
183
+ * @param signal - the cancellation signal handed to the request.
184
+ * @returns the error to rethrow.
185
+ */
186
+ function cancellation(cause, signal) {
187
+ return signal?.aborted === true ? signal.reason : cause;
188
+ }
189
+ /** Whether a failed request was cancelled, by its signal or by the error the transport produced. */
190
+ function isCancellation(cause, signal) {
191
+ if (signal?.aborted === true) return true;
192
+ if (isAbortError(cause)) return true;
193
+ return signal?.reason !== void 0 && cause === signal.reason;
194
+ }
195
+ /**
196
+ * Delay a rate-limited answer asked for, in milliseconds.
197
+ *
198
+ * KOOK documents `X-Rate-Limit-Reset` (seconds) and says nothing about `Retry-After`; both are read, the standard
199
+ * header first, because an undocumented one is only useful while it is present.
200
+ *
201
+ * @param response - the answer.
202
+ * @returns the delay in milliseconds, or undefined when neither header is present or readable.
203
+ */
204
+ function retryAfterOf(response) {
205
+ const standard = response.headers.get("retry-after");
206
+ if (standard !== null) {
207
+ const seconds = Number(standard);
208
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
209
+ }
210
+ const reset = response.headers.get("x-rate-limit-reset");
211
+ if (reset !== null) {
212
+ const seconds = Number(reset);
213
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
214
+ }
215
+ }
216
+ /** Read a JSON answer; an unreadable body is reported as absence rather than a parse error. */
217
+ async function jsonOf(response) {
218
+ let body;
219
+ try {
220
+ body = await response.json();
221
+ } catch (error) {
222
+ return;
223
+ }
224
+ if (typeof body !== "object" || body === null) return void 0;
225
+ return body;
226
+ }
227
+ /** The URL of one request. */
228
+ function urlOf(request, path) {
229
+ return `${request.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
230
+ }
231
+ /**
232
+ * Call one KOOK API endpoint and return its envelope's `data`.
233
+ *
234
+ * @param request - endpoints for this bot.
235
+ * @param method - HTTP method (`GET`, `POST`, `DELETE`).
236
+ * @param path - endpoint below the API root (`/message/create`).
237
+ * @param payload - query parameters of `GET`/`DELETE`, else the request body (JSON or a multipart form).
238
+ * @param signal - cancellation.
239
+ * @returns the endpoint's `data` field.
240
+ * @throws KookApiError for a transport failure, a non-2xx answer or a non-zero business code.
241
+ */
242
+ async function invoke(request, method, path, payload, signal) {
243
+ const config = {
244
+ method,
245
+ headers: { authorization: `Bot ${request.token}` }
246
+ };
247
+ if (method === "GET" || method === "DELETE") config.params = payload ?? {};
248
+ else config.data = payload ?? {};
249
+ if (signal !== void 0) config.signal = signal;
250
+ let response;
251
+ try {
252
+ response = await request.ctx.http(urlOf(request, path), config);
253
+ } catch (cause) {
254
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal);
255
+ throw new KookApiError(`kook ${method} ${path} request failed`, { cause });
256
+ }
257
+ const status = response.status;
258
+ const retryAfterMs = retryAfterOf(response);
259
+ const body = await jsonOf(response);
260
+ if (body === void 0) {
261
+ if (signal?.aborted === true) throw signal.reason;
262
+ throw new KookApiError(`kook ${method} ${path} answered ${status} without a JSON envelope`, {
263
+ status,
264
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs }
265
+ });
266
+ }
267
+ if (status === 429) throw new KookApiError(`kook ${method} ${path} was rate limited`, {
268
+ status,
269
+ ...typeof body.code === "number" ? { code: body.code } : {},
270
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs }
271
+ });
272
+ if (body.code !== 0) throw new KookApiError(`kook ${method} ${path} failed: ${body.message ?? "the answer carries no success code"}`, {
273
+ status,
274
+ ...typeof body.code === "number" ? { code: body.code } : {},
275
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs }
276
+ });
277
+ if (status >= 400) throw new KookApiError(`kook ${method} ${path} answered ${status} with a success envelope`, {
278
+ status,
279
+ code: body.code,
280
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs }
281
+ });
282
+ return body.data;
283
+ }
284
+ // lib/types/types.js
285
+ var types_exports = /* @__PURE__ */ __exportAll({
286
+ Card: () => Card,
287
+ GuildMute: () => GuildMute,
288
+ Internal: () => Internal,
289
+ Permissions: () => Permissions,
290
+ Signal: () => Signal,
291
+ Type: () => Type,
292
+ UserStatus: () => UserStatus,
293
+ hasPermission: () => hasPermission
294
+ });
295
+ var Signal;
296
+ (function(Signal) {
297
+ Signal[Signal["event"] = 0] = "event";
298
+ Signal[Signal["hello"] = 1] = "hello";
299
+ Signal[Signal["ping"] = 2] = "ping";
300
+ Signal[Signal["pong"] = 3] = "pong";
301
+ Signal[Signal["reconnect"] = 4] = "reconnect";
302
+ Signal[Signal["resume"] = 5] = "resume";
303
+ })(Signal || (Signal = {}));
304
+ var Type;
305
+ (function(Type) {
306
+ Type[Type["text"] = 1] = "text";
307
+ Type[Type["image"] = 2] = "image";
308
+ Type[Type["video"] = 3] = "video";
309
+ Type[Type["file"] = 4] = "file";
310
+ Type[Type["unknown"] = 7] = "unknown";
311
+ Type[Type["audio"] = 8] = "audio";
312
+ Type[Type["kmarkdown"] = 9] = "kmarkdown";
313
+ Type[Type["card"] = 10] = "card";
314
+ Type[Type["system"] = 255] = "system";
315
+ })(Type || (Type = {}));
316
+ var Card;
317
+ (function(Card) {
318
+ Card.Theme = [
319
+ "primary",
320
+ "secondary",
321
+ "warning",
322
+ "danger",
323
+ "info",
324
+ "none",
325
+ "success"
326
+ ];
327
+ Card.Size = ["lg", "sm"];
328
+ (function(Button) {
329
+ Button.Theme = [
330
+ "primary",
331
+ "secondary",
332
+ "warning",
333
+ "danger",
334
+ "info",
335
+ "none",
336
+ "success"
337
+ ];
338
+ })(Card.Button || (Card.Button = {}));
339
+ })(Card || (Card = {}));
340
+ var UserStatus;
341
+ (function(UserStatus) {
342
+ UserStatus[UserStatus["normal"] = 0] = "normal";
343
+ UserStatus[UserStatus["normal_1"] = 1] = "normal_1";
344
+ UserStatus[UserStatus["banned"] = 10] = "banned";
345
+ })(UserStatus || (UserStatus = {}));
346
+ var Permissions;
347
+ (function(Permissions) {
348
+ Permissions[Permissions["GUILD_ADMIN"] = 0] = "GUILD_ADMIN";
349
+ Permissions[Permissions["GUILD_MANAGE"] = 1] = "GUILD_MANAGE";
350
+ Permissions[Permissions["GUILD_LOG"] = 2] = "GUILD_LOG";
351
+ Permissions[Permissions["GUILD_INVITE_CREATE"] = 3] = "GUILD_INVITE_CREATE";
352
+ Permissions[Permissions["GUILD_INVITE_MANAGE"] = 4] = "GUILD_INVITE_MANAGE";
353
+ Permissions[Permissions["CHANNEL_MANAGE"] = 5] = "CHANNEL_MANAGE";
354
+ Permissions[Permissions["GUILD_USER_KICK"] = 6] = "GUILD_USER_KICK";
355
+ Permissions[Permissions["GUILD_USER_BAN"] = 7] = "GUILD_USER_BAN";
356
+ Permissions[Permissions["GUILD_EMOJI_MANAGE"] = 8] = "GUILD_EMOJI_MANAGE";
357
+ Permissions[Permissions["GUILD_USER_NAME_CHANGE"] = 9] = "GUILD_USER_NAME_CHANGE";
358
+ Permissions[Permissions["GUILD_ROLE_MANAGE"] = 10] = "GUILD_ROLE_MANAGE";
359
+ Permissions[Permissions["CHANNEL_VIEW"] = 11] = "CHANNEL_VIEW";
360
+ Permissions[Permissions["CHANNEL_MESSAGE"] = 12] = "CHANNEL_MESSAGE";
361
+ Permissions[Permissions["CHANNEL_MANAGE_MESSAGE"] = 13] = "CHANNEL_MANAGE_MESSAGE";
362
+ Permissions[Permissions["CHANNEL_UPLOAD"] = 14] = "CHANNEL_UPLOAD";
363
+ Permissions[Permissions["CHANNEL_VOICE_CONNECT"] = 15] = "CHANNEL_VOICE_CONNECT";
364
+ Permissions[Permissions["CHANNEL_VOICE_MANAGE"] = 16] = "CHANNEL_VOICE_MANAGE";
365
+ Permissions[Permissions["CHANNEL_MESSAGE_AT_ALL"] = 17] = "CHANNEL_MESSAGE_AT_ALL";
366
+ Permissions[Permissions["CHANNEL_MESSAGE_REACTION_CREATE"] = 18] = "CHANNEL_MESSAGE_REACTION_CREATE";
367
+ Permissions[Permissions["CHANNEL_MESSAGE_REACTION_FOLLOW"] = 19] = "CHANNEL_MESSAGE_REACTION_FOLLOW";
368
+ Permissions[Permissions["CHANNEL_VOICE_CONNECT_PASSIVE"] = 20] = "CHANNEL_VOICE_CONNECT_PASSIVE";
369
+ Permissions[Permissions["CHANNEL_VOICE_SPEAK_KEY_ONLY"] = 21] = "CHANNEL_VOICE_SPEAK_KEY_ONLY";
370
+ Permissions[Permissions["CHANNEL_VOICR_SPEAK_FREE"] = 22] = "CHANNEL_VOICR_SPEAK_FREE";
371
+ Permissions[Permissions["CHANNEL_VOICE_SPEAK"] = 23] = "CHANNEL_VOICE_SPEAK";
372
+ Permissions[Permissions["GUILD_USER_DEAFEN"] = 24] = "GUILD_USER_DEAFEN";
373
+ Permissions[Permissions["GUILD_USER_MUTEGUILD_USER_NAME_CHANGE_OTHER"] = 25] = "GUILD_USER_MUTEGUILD_USER_NAME_CHANGE_OTHER";
374
+ Permissions[Permissions["GUILD_USER_NAME_CHANGE_OTHER"] = 26] = "GUILD_USER_NAME_CHANGE_OTHER";
375
+ Permissions[Permissions["CHANNEL_VOICE_BGM"] = 27] = "CHANNEL_VOICE_BGM";
376
+ })(Permissions || (Permissions = {}));
377
+ function hasPermission(permissions, permission) {
378
+ return (permissions & 1 << permission) === 1 << permission;
379
+ }
380
+ var GuildMute;
381
+ (function(GuildMute) {
382
+ (function(Type) {
383
+ Type[Type["mic"] = 1] = "mic";
384
+ Type[Type["headset"] = 2] = "headset";
385
+ })(GuildMute.Type || (GuildMute.Type = {}));
386
+ })(GuildMute || (GuildMute = {}));
387
+ var Internal = class Internal {
388
+ request;
389
+ constructor(request) {
390
+ this.request = request;
391
+ }
392
+ static define(name, method, path) {
393
+ Object.defineProperty(Internal.prototype, name, {
394
+ configurable: true,
395
+ writable: true,
396
+ value: async function(payload) {
397
+ return await invoke(this.request, method, path, payload);
398
+ }
399
+ });
400
+ }
401
+ };
402
+ Internal.define("getGuildList", "GET", "/guild/list");
403
+ Internal.define("getGuildView", "GET", "/guild/view");
404
+ Internal.define("getGuildUserList", "GET", "/guild/user-list");
405
+ Internal.define("setGuildUserNickname", "POST", "/guild/nickname");
406
+ Internal.define("leaveGuild", "POST", "/guild/leave");
407
+ Internal.define("kickoutGuildUser", "POST", "/guild/kickout");
408
+ Internal.define("getGuildMuteList", "GET", "/guild-mute/list");
409
+ Internal.define("createGuildMute", "POST", "/guild-mute/create");
410
+ Internal.define("deleteGuildMute", "POST", "/guild-mute/delete");
411
+ Internal.define("getGuildBoostHistory", "GET", "/guild-boost/history");
412
+ Internal.define("getChannelList", "GET", "/channel/list");
413
+ Internal.define("getChannelView", "GET", "/channel/view");
414
+ Internal.define("createChannel", "POST", "/channel/create");
415
+ Internal.define("updateChannel", "POST", "/channel/update");
416
+ Internal.define("deleteChannel", "POST", "/channel/delete");
417
+ Internal.define("getChannelUserList", "GET", "/channel/user-list");
418
+ Internal.define("kickChannelUser", "POST", "/channel/kickout");
419
+ Internal.define("moveChannelUser", "POST", "/channel/move-user");
420
+ Internal.define("getChannelRoleIndex", "GET", "/channel-role/index");
421
+ Internal.define("createChannelRole", "POST", "/channel-role/create");
422
+ Internal.define("updateChannelRole", "POST", "/channel-role/update");
423
+ Internal.define("deleteChannelRole", "POST", "/channel-role/delete");
424
+ Internal.define("getMessageList", "GET", "/message/list");
425
+ Internal.define("getMessageView", "GET", "/message/view");
426
+ Internal.define("createMessage", "POST", "/message/create");
427
+ Internal.define("updateMessage", "POST", "/message/update");
428
+ Internal.define("deleteMessage", "POST", "/message/delete");
429
+ Internal.define("getMessageReactionList", "GET", "/message/reaction-list");
430
+ Internal.define("addMessageReaction", "POST", "/message/add-reaction");
431
+ Internal.define("deleteMessageReaction", "POST", "/message/delete-reaction");
432
+ Internal.define("getChannelJoinedUserList", "GET", "/channel-user/get-joined-channel");
433
+ Internal.define("getPrivateChatList", "GET", "/user-chat/list");
434
+ Internal.define("getPrivateChatView", "GET", "/user-chat/view");
435
+ Internal.define("createPrivateChat", "POST", "/user-chat/create");
436
+ Internal.define("deletePrivateChat", "POST", "/user-chat/delete");
437
+ Internal.define("getDirectMessageList", "GET", "/direct-message/list");
438
+ Internal.define("createDirectMessage", "POST", "/direct-message/create");
439
+ Internal.define("updateDirectMessage", "POST", "/direct-message/update");
440
+ Internal.define("deleteDirectMessage", "POST", "/direct-message/delete");
441
+ Internal.define("getDirectMessageReactionList", "GET", "/direct-message/reaction-list");
442
+ Internal.define("addDirectMessageReaction", "POST", "/direct-message/add-reaction");
443
+ Internal.define("deleteDirectMessageReaction", "POST", "/direct-message/delete-reaction");
444
+ Internal.define("getGateway", "GET", "/gateway/index");
445
+ Internal.define("getToken", "POST", "/oauth2/token");
446
+ Internal.define("createAsset", "POST", "/asset/create");
447
+ Internal.define("getUserMe", "GET", "/user/me");
448
+ Internal.define("getUserView", "GET", "/user/view");
449
+ Internal.define("offline", "POST", "/user/offline");
450
+ Internal.define("getGuildRoleList", "GET", "/guild-role/list");
451
+ Internal.define("createGuildRole", "POST", "/guild-role/create");
452
+ Internal.define("updateGuildRole", "POST", "/guild-role/update");
453
+ Internal.define("deleteGuildRole", "POST", "/guild-role/delete");
454
+ Internal.define("grantGuildRole", "POST", "/guild-role/grant");
455
+ Internal.define("revokeGuildRole", "POST", "/guild-role/revoke");
456
+ Internal.define("getIntimacy", "GET", "/intimacy/index");
457
+ Internal.define("updateIntimacy", "POST", "/intimacy/update");
458
+ Internal.define("getGuildEmojiList", "GET", "/guild-emoji/list");
459
+ Internal.define("createGuildEmoji", "POST", "/guild-emoji/create");
460
+ Internal.define("updateGuildEmoji", "POST", "/guild-emoji/update");
461
+ Internal.define("deleteGuildEmoji", "POST", "/guild-emoji/delete");
462
+ Internal.define("getInviteList", "GET", "/invite/list");
463
+ Internal.define("createInvite", "POST", "/invite/create");
464
+ Internal.define("deleteInvite", "POST", "/invite/delete");
465
+ Internal.define("getBlacklist", "GET", "/blacklist/list");
466
+ Internal.define("createBlacklist", "POST", "/blacklist/create");
467
+ Internal.define("deleteBlacklist", "POST", "/blacklist/delete");
468
+ Internal.define("getGuildBadge", "GET", "/badge/guild");
469
+ Internal.define("getGameList", "GET", "/game");
470
+ Internal.define("createGame", "POST", "/game/create");
471
+ Internal.define("updateGame", "POST", "/game/update");
472
+ Internal.define("deleteGame", "POST", "/game/delete");
473
+ Internal.define("createGameActivity", "POST", "/game/activity");
474
+ Internal.define("deleteGameActivity", "POST", "/game/delete-activity");
475
+ // lib/types/config.js
476
+ /** Validated KOOK adapter configuration. */
477
+ const Config = z.object({
478
+ token: z.string().role("secret").required(),
479
+ selfId: z.string().pattern(/^\d+$/).required(),
480
+ protocol: z.union(["ws", "http"]).required(),
481
+ path: z.string().default("/kook"),
482
+ verifyToken: z.string().role("secret").default(""),
483
+ apiBaseUrl: z.string().role("url").default("https://www.kookapp.cn/api/v3"),
484
+ ws: z.object({
485
+ retryTimes: z.natural().default(6),
486
+ retryInterval: z.natural().role("ms").default(5e3),
487
+ retryLazy: z.natural().role("ms").default(6e4)
488
+ }).default({})
489
+ });
490
+ /**
491
+ * The configuration the selected protocol cannot work from.
492
+ *
493
+ * The schema already refuses a missing token or a non-numeric `selfId`; what it cannot express is which credential a
494
+ * protocol needs, so that check runs when the plugin loads and names the corrective action.
495
+ *
496
+ * @param config - the validated configuration.
497
+ * @returns the configuration error, or undefined when the selection is complete.
498
+ */
499
+ function configError(config) {
500
+ let url;
501
+ try {
502
+ url = new URL(config.apiBaseUrl);
503
+ } catch {
504
+ return /* @__PURE__ */ new Error("kook: apiBaseUrl must be an absolute http(s) URL");
505
+ }
506
+ if (url.protocol !== "http:" && url.protocol !== "https:") return /* @__PURE__ */ new Error("kook: apiBaseUrl must be an absolute http(s) URL");
507
+ if (config.protocol === "http" && config.verifyToken === "") return /* @__PURE__ */ new Error("kook: protocol \"http\" needs verifyToken (the verify_token KOOK issues for the webhook)");
508
+ }
509
+ /**
510
+ * Normalize an inbound route path: absolute, no trailing slash.
511
+ * @param path - the configured `path`.
512
+ * @returns the pathname to register.
513
+ */
514
+ function routePath(path) {
515
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
516
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
517
+ }
518
+ // lib/types/identity.js
519
+ /**
520
+ * Verify that the bot token belongs to the configured bot.
521
+ *
522
+ * The token is an opaque platform-issued string, so the bot id cannot be derived from it; `selfId` is configured and
523
+ * checked here. The host keys `ctx.bots`, `sources.bot` and the intake dedupe key on `bot.id`, so a mismatch is a
524
+ * configuration error that reconnecting cannot fix.
525
+ *
526
+ * @param request - endpoints for this bot.
527
+ * @param selfId - the configured bot user id.
528
+ * @param signal - cancellation of the transport that asked.
529
+ * @returns the bot's own user record.
530
+ * @throws KookIdentityError when `/user/me` reports another account.
531
+ */
532
+ async function verifyIdentity(request, selfId, signal) {
533
+ const user = await invoke(request, "GET", "/user/me", void 0, signal);
534
+ const actual = user === void 0 || user === null ? "" : String(user.id);
535
+ if (actual !== selfId) throw new KookIdentityError(`kook: selfId is configured as ${selfId} but the bot token belongs to ${actual === "" ? "an unknown account" : actual}; fix selfId and restart`);
536
+ return user;
537
+ }
538
+ // lib/types/kmarkdown.js
539
+ /**
540
+ * KMarkdown text handling: the escaping the platform requires, the inbound `(met|chn|rol)` tokens, and the
541
+ * visible-length splitter the message budgets use.
542
+ *
543
+ * Escaping follows the upstream adapter exactly: a backslash goes in front of `\`, `*`, `` ` ``, `~`, `(` and `)`, so
544
+ * user text cannot open a control sequence or a formatting run. `[` and `]` stay unescaped because a lone one is
545
+ * harmless.
546
+ */
547
+ /**
548
+ * Escape user text for KMarkdown.
549
+ * @param text - plain text.
550
+ * @returns the text with the six metacharacters escaped.
551
+ */
552
+ function escapeKMarkdown(text) {
553
+ return text.replace(/[\\*`~()]/g, "\\$&");
554
+ }
555
+ /**
556
+ * Undo KMarkdown escaping.
557
+ * @param text - escaped text.
558
+ * @returns the text with `\x` collapsed to `x`.
559
+ */
560
+ function unescapeKMarkdown(text) {
561
+ return text.replace(/\\(.)/g, "$1");
562
+ }
563
+ /** Token of one kmarkdown control sequence, including the emoji form. */
564
+ const CONTROL = /^\((met|chn|rol)\)([\w-]+)\(\1\)/;
565
+ const EMOJI = /^\(emj\)([^()]*)\(emj\)\[([^\]]*)\]/;
566
+ /**
567
+ * Parse the kmarkdown body of one message into content elements.
568
+ *
569
+ * Only the control sequences KOOK defines are interpreted; markdown syntax (`**bold**`, `> quote`, fences) stays in
570
+ * the text as the platform sent it, because rewriting the source would show the model something the user did not
571
+ * write.
572
+ *
573
+ * @param content - `d.content` of a kind-9 message.
574
+ * @param names - mention and role names of `extra.kmarkdown`.
575
+ * @returns the decoded content nodes, in source order.
576
+ */
577
+ function parseKMarkdown(content, names = {}) {
578
+ const users = names.users ?? [];
579
+ const roles = names.roles ?? [];
580
+ const elements = [];
581
+ let buffer = "";
582
+ let rest = content;
583
+ const flush = () => {
584
+ if (buffer === "") return;
585
+ elements.push(h.text(buffer));
586
+ buffer = "";
587
+ };
588
+ while (rest !== "") {
589
+ if (rest.startsWith("\\") && rest.length > 1) {
590
+ buffer += rest[1];
591
+ rest = rest.slice(2);
592
+ continue;
593
+ }
594
+ const control = CONTROL.exec(rest);
595
+ if (control !== null) {
596
+ const whole = control.at(0) ?? "";
597
+ const kind = control.at(1) ?? "";
598
+ const id = control.at(2) ?? "";
599
+ rest = rest.slice(whole.length);
600
+ flush();
601
+ if (kind === "met") {
602
+ if (id === "all" || id === "here") elements.push(h("at", { type: id }));
603
+ else {
604
+ const name = users.find((user) => user.id === id)?.username;
605
+ elements.push(h("at", {
606
+ type: "user",
607
+ id,
608
+ ...name === void 0 ? {} : { name }
609
+ }));
610
+ }
611
+ } else if (kind === "chn") elements.push(h("channel", { id }));
612
+ else {
613
+ const name = roles.find((role) => String(role.role_id) === id)?.name;
614
+ elements.push(h("at", {
615
+ type: "role",
616
+ id,
617
+ ...name === void 0 ? {} : { name }
618
+ }));
619
+ }
620
+ continue;
621
+ }
622
+ buffer += rest.charAt(0);
623
+ rest = rest.slice(1);
624
+ }
625
+ flush();
626
+ return elements;
627
+ }
628
+ /** Split a kmarkdown body into the pieces a cut may not break. */
629
+ function tokenize(content) {
630
+ const tokens = [];
631
+ let rest = content;
632
+ while (rest !== "") {
633
+ if (rest.startsWith("\\") && rest.length > 1) {
634
+ tokens.push({
635
+ raw: rest.slice(0, 2),
636
+ visible: 1,
637
+ newline: false,
638
+ space: false
639
+ });
640
+ rest = rest.slice(2);
641
+ continue;
642
+ }
643
+ const control = CONTROL.exec(rest) ?? EMOJI.exec(rest);
644
+ if (control !== null) {
645
+ const whole = control.at(0) ?? "";
646
+ tokens.push({
647
+ raw: whole,
648
+ visible: 1,
649
+ newline: false,
650
+ space: false
651
+ });
652
+ rest = rest.slice(whole.length);
653
+ continue;
654
+ }
655
+ const codePoint = rest.codePointAt(0);
656
+ const raw = String.fromCodePoint(codePoint);
657
+ tokens.push({
658
+ raw,
659
+ visible: 1,
660
+ newline: raw === "\n",
661
+ space: raw === " "
662
+ });
663
+ rest = rest.slice(raw.length);
664
+ }
665
+ return tokens;
666
+ }
667
+ /**
668
+ * Visible characters of a kmarkdown body: control sequences and escape pairs count once, like a rendered mention.
669
+ * @param content - kmarkdown text.
670
+ * @returns the number of visible characters.
671
+ */
672
+ function visibleLength(content) {
673
+ let length = 0;
674
+ for (const token of tokenize(content)) length += token.visible;
675
+ return length;
676
+ }
677
+ /**
678
+ * Split a kmarkdown body into chunks of at most `limit` visible characters.
679
+ *
680
+ * The cut prefers the last line break of the window, then the last space, then a hard cut, and it never lands inside
681
+ * an escape pair or a control sequence. Concatenating the chunks returns the input exactly: splitting moves no
682
+ * character and adds no marker.
683
+ *
684
+ * @param content - kmarkdown text.
685
+ * @param limit - visible characters per chunk.
686
+ * @returns the chunks, in order.
687
+ */
688
+ function splitKMarkdown(content, limit) {
689
+ const tokens = tokenize(content);
690
+ if (tokens.reduce((sum, token) => sum + token.visible, 0) <= limit) return [content];
691
+ const chunks = [];
692
+ let start = 0;
693
+ while (start < tokens.length) {
694
+ let end = start;
695
+ let visible = 0;
696
+ while (end < tokens.length && visible + tokens[end].visible <= limit) {
697
+ visible += tokens[end].visible;
698
+ end += 1;
699
+ }
700
+ if (end === tokens.length) {
701
+ chunks.push(tokens.slice(start).map((token) => token.raw).join(""));
702
+ break;
703
+ }
704
+ let cut = end;
705
+ for (let index = end - 1; index >= start; index--) if (tokens[index].newline) {
706
+ cut = index + 1;
707
+ break;
708
+ }
709
+ if (cut === end) {
710
+ for (let index = end - 1; index >= start; index--) if (tokens[index].space) {
711
+ cut = index + 1;
712
+ break;
713
+ }
714
+ }
715
+ if (cut <= start) cut = start + 1;
716
+ chunks.push(tokens.slice(start, cut).map((token) => token.raw).join(""));
717
+ start = cut;
718
+ }
719
+ return chunks;
720
+ }
721
+ /**
722
+ * Encode the inline kmarkdown of a subtree, for a control that only carries text (a card button).
723
+ * @param nodes - rendered text fragments.
724
+ * @returns the concatenated kmarkdown.
725
+ */
726
+ function inlineKMarkdown(nodes) {
727
+ return nodes.map((node) => node.text).join("");
728
+ }
729
+ // lib/types/modes/shared.js
730
+ /**
731
+ * Draft model of the single `kmarkdown` mode: the node stream, the text/card buffers, the documented card budgets, and
732
+ * the exact request body of one platform message.
733
+ *
734
+ * One logical message is either kmarkdown (`type: 9`) or card JSON (`type: 10`), exactly as the upstream encoder
735
+ * flushes: text alone stays a `type: 9` message, and the first element that needs a card module (media, a button, a
736
+ * divider) turns the whole message into a card.
737
+ */
738
+ /** KOOK's documented bounds; nothing else is a limit. */
739
+ const KOOK_LIMITS = {
740
+ /** `content` of one message ("请不要超过 8000 字符"). */
741
+ textChars: 8e3,
742
+ /** kmarkdown text of one section/context module. */
743
+ sectionChars: 5e3,
744
+ /** Modules of one card. */
745
+ cardModules: 50,
746
+ /** Buttons of one `action-group`. */
747
+ buttonsPerRow: 4,
748
+ /** Images of one `image-group`. */
749
+ imagesPerGroup: 9,
750
+ /** `page_size` of `/guild/user-list`. */
751
+ membersPageSize: 50
752
+ };
753
+ /** A paragraph break node. */
754
+ const BREAK = { type: "break" };
755
+ /**
756
+ * One text node holding already encoded kmarkdown.
757
+ * @param text - kmarkdown text.
758
+ * @returns the node.
759
+ */
760
+ function textNode(text) {
761
+ return {
762
+ type: "text",
763
+ text
764
+ };
765
+ }
766
+ /**
767
+ * Group items into runs of at most `size`.
768
+ * @param items - the items, in order.
769
+ * @param size - maximum run length.
770
+ * @returns the runs, in order.
771
+ */
772
+ function chunk(items, size) {
773
+ const runs = [];
774
+ for (let start = 0; start < items.length; start += size) runs.push(items.slice(start, start + size));
775
+ return runs;
776
+ }
777
+ /**
778
+ * The card `image-group` runs of an image list (1–9 images each; DSH has no album element yet, so only a future
779
+ * caller uses this).
780
+ * @param images - the images, in order.
781
+ * @returns the groups, in order.
782
+ */
783
+ function groupImages(images) {
784
+ return chunk(images, KOOK_LIMITS.imagesPerGroup);
785
+ }
786
+ /**
787
+ * The platform colour of a button theme.
788
+ * @param theme - the element's theme, when it declared one.
789
+ * @returns the KOOK button colour.
790
+ */
791
+ function themeOf(theme) {
792
+ switch (theme) {
793
+ case "info":
794
+ case "success":
795
+ case "warning":
796
+ case "danger": return theme;
797
+ default: return "primary";
798
+ }
799
+ }
800
+ /** The name of an outbound attachment: the declared name, else the last path segment of the source. */
801
+ function fileName(name, src) {
802
+ if (name !== void 0 && name !== "") return name;
803
+ try {
804
+ const segment = new URL(src).pathname.split("/").pop();
805
+ if (segment !== void 0 && segment !== "") return decodeURIComponent(segment);
806
+ } catch (error) {
807
+ if (src !== "" && !src.includes("/")) return src;
808
+ }
809
+ return "file";
810
+ }
811
+ /** The kmarkdown text of a node list (a button label, a link label). */
812
+ function textOf(nodes) {
813
+ return inlineKMarkdown(nodes.filter((node) => node.type === "text"));
814
+ }
815
+ /**
816
+ * Wrap every text run of a node list with one kmarkdown construct.
817
+ *
818
+ * Each contiguous text run is wrapped on its own, so a media node between two runs never leaves a marker open across
819
+ * the card module boundary. Nested marks compose (`<b><i>x</i></b>` → `***x***`), as the upstream encoder emits.
820
+ *
821
+ * @param nodes - rendered children.
822
+ * @param open - opening marker.
823
+ * @param close - closing marker, `open` when symmetric.
824
+ * @returns the children with their text runs wrapped.
825
+ */
826
+ function withMark(nodes, open, close = open) {
827
+ const out = [];
828
+ let run = [];
829
+ const flush = () => {
830
+ if (run.length === 0) return;
831
+ out.push(textNode(open + run.join("") + close));
832
+ run = [];
833
+ };
834
+ for (const node of nodes) {
835
+ if (node.type === "text") {
836
+ run.push(node.text);
837
+ continue;
838
+ }
839
+ flush();
840
+ out.push(node);
841
+ }
842
+ flush();
843
+ return out;
844
+ }
845
+ /**
846
+ * Prefix every line of a node list with the quote marker.
847
+ * @param nodes - rendered children.
848
+ * @returns the children with `> ` at the start of every line.
849
+ */
850
+ function quoteLines(nodes) {
851
+ const out = [];
852
+ let atLineStart = true;
853
+ for (const node of nodes) {
854
+ if (node.type === "break") {
855
+ atLineStart = true;
856
+ out.push(node);
857
+ continue;
858
+ }
859
+ if (node.type !== "text") {
860
+ out.push(node);
861
+ continue;
862
+ }
863
+ let text = "";
864
+ for (const char of node.text) {
865
+ if (atLineStart && char !== "\n") text += "> ";
866
+ text += char;
867
+ atLineStart = char === "\n";
868
+ }
869
+ out.push(textNode(text));
870
+ }
871
+ return out;
872
+ }
873
+ /**
874
+ * The media node of one attachment element, reporting a phrasing-position attachment as `moved`.
875
+ * @param el - one of `img`/`audio`/`video`/`file`.
876
+ * @param ctx - render context of the mode.
877
+ * @returns the node.
878
+ */
879
+ function mediaNode(el, ctx) {
880
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
881
+ if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
882
+ tag: el.type,
883
+ reason: "kook-media-split",
884
+ path: ctx.stableId(el)
885
+ });
886
+ switch (el.type) {
887
+ case "img": return {
888
+ type: "image",
889
+ ref: ctx.resource("image", el.attrs.src, {})
890
+ };
891
+ case "audio": return {
892
+ type: "media",
893
+ kind: "audio",
894
+ ref: ctx.resource("audio", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
895
+ title: fileName(el.attrs.name, el.attrs.src)
896
+ };
897
+ case "video": return {
898
+ type: "media",
899
+ kind: "video",
900
+ ref: ctx.resource("video", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
901
+ title: fileName(el.attrs.name, el.attrs.src)
902
+ };
903
+ case "file": return {
904
+ type: "media",
905
+ kind: "file",
906
+ ref: ctx.resource("file", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
907
+ title: fileName(el.attrs.name, el.attrs.src)
908
+ };
909
+ }
910
+ }
911
+ /**
912
+ * Fold the rendered node stream into platform messages.
913
+ *
914
+ * Text accumulates in one buffer; the first media, button or divider element turns the message into a card and every
915
+ * text run becomes a `section`. A card holds at most 50 modules, a section at most 5,000 visible characters, and a
916
+ * kmarkdown message at most 8,000: the buffer is cut at those bounds and each extra platform message is reported as a
917
+ * split. The result is never empty.
918
+ *
919
+ * @param nodes - rendered nodes in document order.
920
+ * @param ctx - render context, for the split and moved report.
921
+ * @returns one draft per platform message.
922
+ */
923
+ function assembleDraft(nodes, ctx) {
924
+ const drafts = [];
925
+ let text = "";
926
+ let modules = [];
927
+ let card = false;
928
+ const flushCard = () => {
929
+ if (modules.length === 0) return;
930
+ drafts.push({
931
+ kind: "card",
932
+ modules
933
+ });
934
+ modules = [];
935
+ };
936
+ const pushModule = (module) => {
937
+ card = true;
938
+ modules.push(module);
939
+ if (modules.length >= KOOK_LIMITS.cardModules) flushCard();
940
+ };
941
+ const flushText = () => {
942
+ const content = text.trim();
943
+ text = "";
944
+ if (content === "") return;
945
+ for (const section of splitKMarkdown(content, KOOK_LIMITS.sectionChars)) pushModule({
946
+ type: "section",
947
+ content: section
948
+ });
949
+ };
950
+ const lineBreak = () => {
951
+ if (text === "") return;
952
+ if (text.endsWith("\n")) return;
953
+ text += "\n";
954
+ };
955
+ for (const node of nodes) switch (node.type) {
956
+ case "text":
957
+ text += node.text;
958
+ break;
959
+ case "break":
960
+ lineBreak();
961
+ break;
962
+ case "divider":
963
+ flushText();
964
+ pushModule({ type: "divider" });
965
+ break;
966
+ case "image":
967
+ flushText();
968
+ pushModule({
969
+ type: "container",
970
+ image: { ref: node.ref }
971
+ });
972
+ break;
973
+ case "media":
974
+ flushText();
975
+ pushModule({
976
+ type: "media",
977
+ kind: node.kind,
978
+ ref: node.ref,
979
+ title: node.title
980
+ });
981
+ break;
982
+ case "buttons":
983
+ flushText();
984
+ pushModule({
985
+ type: "buttons",
986
+ buttons: node.buttons
987
+ });
988
+ }
989
+ if (card) {
990
+ flushText();
991
+ flushCard();
992
+ } else {
993
+ const content = text.trim();
994
+ if (content !== "") for (const part of splitKMarkdown(content, KOOK_LIMITS.textChars)) drafts.push({
995
+ kind: "text",
996
+ content: part
997
+ });
998
+ }
999
+ if (drafts.length === 0) drafts.push({
1000
+ kind: "text",
1001
+ content: "⁠"
1002
+ });
1003
+ ctx.report.split += drafts.length - 1;
1004
+ return drafts;
1005
+ }
1006
+ /** The resource key `prepare` resolved for one media source. */
1007
+ function resolvedKey(prepared, ref) {
1008
+ const resolved = prepared.resolved.get(ref);
1009
+ if (resolved === void 0) throw new Error("kook: the media was not prepared before serialize");
1010
+ return resolved.key;
1011
+ }
1012
+ /** One image as a card element. */
1013
+ function imageOf(prepared, image) {
1014
+ return {
1015
+ type: "image",
1016
+ src: resolvedKey(prepared, image.ref)
1017
+ };
1018
+ }
1019
+ /** One button as a card element. */
1020
+ function buttonOf(button) {
1021
+ return {
1022
+ type: "button",
1023
+ theme: button.theme,
1024
+ value: button.value,
1025
+ click: button.click,
1026
+ text: {
1027
+ type: "kmarkdown",
1028
+ content: button.text
1029
+ }
1030
+ };
1031
+ }
1032
+ /** One draft module as the wire module(s) it produces. */
1033
+ function modulesOf(prepared, module) {
1034
+ switch (module.type) {
1035
+ case "section": return [{
1036
+ type: "section",
1037
+ text: {
1038
+ type: "kmarkdown",
1039
+ content: module.content
1040
+ }
1041
+ }];
1042
+ case "container": return [{
1043
+ type: "container",
1044
+ elements: [imageOf(prepared, module.image)]
1045
+ }];
1046
+ case "image-group": return groupImages(module.images).map((images) => ({
1047
+ type: "image-group",
1048
+ elements: images.map((image) => imageOf(prepared, image))
1049
+ }));
1050
+ case "buttons": return chunk(module.buttons, KOOK_LIMITS.buttonsPerRow).map((buttons) => ({
1051
+ type: "action-group",
1052
+ elements: buttons.map(buttonOf)
1053
+ }));
1054
+ case "divider": return [{ type: "divider" }];
1055
+ case "media": return [{
1056
+ type: module.kind,
1057
+ src: resolvedKey(prepared, module.ref),
1058
+ title: module.title
1059
+ }];
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Build the exact request body of one draft.
1064
+ *
1065
+ * Only the first platform message answers the quoted one; `SerializeContext.quote` reaches every part, so the adapter
1066
+ * picks the one that carries it.
1067
+ *
1068
+ * @param prepared - the draft with every resource resolved.
1069
+ * @param ctx - serialize context (part index and quote).
1070
+ * @returns the request body.
1071
+ */
1072
+ function serializeDraft(prepared, ctx) {
1073
+ const quote = ctx.index === 0 ? ctx.quote : void 0;
1074
+ const common = quote === void 0 ? {} : { quote };
1075
+ if (prepared.draft.kind === "text") return {
1076
+ kind: "text",
1077
+ type: 9,
1078
+ content: prepared.draft.content,
1079
+ ...common
1080
+ };
1081
+ const card = {
1082
+ type: "card",
1083
+ modules: prepared.draft.modules.flatMap((module) => modulesOf(prepared, module))
1084
+ };
1085
+ return {
1086
+ kind: "card",
1087
+ type: 10,
1088
+ content: JSON.stringify([card]),
1089
+ ...common
1090
+ };
1091
+ }
1092
+ // lib/types/modes/kmarkdown.js
1093
+ /**
1094
+ * The single `kmarkdown` mode: KOOK message text with its KMarkdown markup, and a card when the content needs one.
1095
+ *
1096
+ * Native tags are the ones the upstream encoder renders (`text`, `p`, `br`, `b`, `i`, `u`, `s`, `spoiler`, `code`,
1097
+ * `a`, `at`, `channel`, `emoji`) plus the block structure KMarkdown shows as text (headings, lists, quotes, fences, a
1098
+ * divider) and the media and buttons that only a card module can carry. A `<button type="input">` is not declared: a
1099
+ * click that sends a text as the reader has no card component, so the core fallback renders its label and command.
1100
+ * Everything else takes the core fallback, which keeps its text — the platform has no second way to render it.
1101
+ */
1102
+ /** Drop the paragraph breaks a container put in front of its content, so a list marker is not followed by a newline. */
1103
+ function withoutLeadingBreaks(nodes) {
1104
+ let start = 0;
1105
+ while (start < nodes.length && nodes[start].type === "break") start += 1;
1106
+ return nodes.slice(start);
1107
+ }
1108
+ /** The nodes of a render without its text runs, for a construct that carries the text in its own markup. */
1109
+ function nonText(nodes) {
1110
+ return nodes.filter((node) => node.type !== "text");
1111
+ }
1112
+ /** A heading: KMarkdown has no heading syntax, so a bold line stands in. */
1113
+ function heading(nodes) {
1114
+ return [
1115
+ BREAK,
1116
+ ...withMark(nodes, "**"),
1117
+ BREAK
1118
+ ];
1119
+ }
1120
+ /** The action button of one `<button>` element. */
1121
+ function actionButton(el, ctx) {
1122
+ const label = textOf(ctx.render(el.children)).trim();
1123
+ if (el.attrs.type === "link") return {
1124
+ click: "link",
1125
+ value: el.attrs.href,
1126
+ text: label === "" ? escapeKMarkdown(el.attrs.href) : label,
1127
+ theme: themeOf(el.attrs.theme)
1128
+ };
1129
+ const id = el.attrs.type === "input" ? "" : el.attrs.id;
1130
+ return {
1131
+ click: "return-val",
1132
+ value: id,
1133
+ text: label === "" ? escapeKMarkdown(id) : label,
1134
+ theme: themeOf(el.attrs.theme)
1135
+ };
1136
+ }
1137
+ /**
1138
+ * Build the `kmarkdown` mode.
1139
+ * @returns the only mode of this adapter.
1140
+ */
1141
+ function createKmarkdownMode() {
1142
+ const elements = new ElementRegistry().register("text", (el) => textNode(escapeKMarkdown(el.attrs.content))).register("p", (el, ctx) => [
1143
+ BREAK,
1144
+ ...ctx.render(el.children),
1145
+ BREAK
1146
+ ]).register("br", () => textNode("\n")).register("b", (el, ctx) => withMark(ctx.render(el.children), "**")).register("i", (el, ctx) => withMark(ctx.render(el.children), "*")).register("u", (el, ctx) => withMark(ctx.render(el.children), "(ins)")).register("s", (el, ctx) => withMark(ctx.render(el.children), "~~")).register("spoiler", (el, ctx) => withMark(ctx.render(el.children), "(spl)")).register("code", (el, ctx) => textNode(`\`${ctx.text(el.children)}\``)).register("pre", (el, ctx) => {
1147
+ return textNode(`\`\`\`${el.attrs.lang ?? ""}\n${ctx.text(el.children)}\n\`\`\``);
1148
+ }, { variants: ["lang"] }).register("a", (el, ctx) => {
1149
+ const children = ctx.render(el.children);
1150
+ const label = textOf(children).trim();
1151
+ return [textNode(`[${label === "" ? escapeKMarkdown(el.attrs.href) : label}](${el.attrs.href})`), ...nonText(children)];
1152
+ }).register("at", (el) => {
1153
+ switch (el.attrs.type) {
1154
+ case "user": return el.attrs.id === void 0 ? textNode(escapeKMarkdown(`@${el.attrs.name ?? ""}`)) : textNode(`(met)${el.attrs.id}(met)`);
1155
+ case "all": return textNode("(met)all(met)");
1156
+ case "here": return textNode("(met)here(met)");
1157
+ case "role": return el.attrs.id === void 0 ? textNode(escapeKMarkdown(`@${el.attrs.name ?? ""}`)) : textNode(`(rol)${el.attrs.id}(rol)`);
1158
+ }
1159
+ }, { variants: [
1160
+ "user",
1161
+ "all",
1162
+ "here",
1163
+ "role"
1164
+ ] }).register("channel", (el) => textNode(`(chn)${el.attrs.id}(chn)`)).register("emoji", (el) => {
1165
+ const name = el.attrs.name ?? "";
1166
+ return el.attrs.id === "" || name === "" ? textNode(`:${name}:`) : textNode(`(emj)${name}(emj)[${el.attrs.id}]`);
1167
+ }).register("h1", (el, ctx) => heading(ctx.render(el.children))).register("h2", (el, ctx) => heading(ctx.render(el.children))).register("h3", (el, ctx) => heading(ctx.render(el.children))).register("h4", (el, ctx) => heading(ctx.render(el.children))).register("h5", (el, ctx) => heading(ctx.render(el.children))).register("h6", (el, ctx) => heading(ctx.render(el.children))).register("ul", (el, ctx) => [
1168
+ BREAK,
1169
+ ...ctx.render(el.children),
1170
+ BREAK
1171
+ ]).register("ol", (el, ctx) => [
1172
+ BREAK,
1173
+ ...ctx.render(el.children),
1174
+ BREAK
1175
+ ]).register("li", (el, ctx) => {
1176
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
1177
+ if (parent?.type !== "ol") return [
1178
+ textNode("• "),
1179
+ ...withoutLeadingBreaks(ctx.render(el.children)),
1180
+ BREAK
1181
+ ];
1182
+ const index = Math.max(parent.children.indexOf(el), 0);
1183
+ return [
1184
+ textNode(`${(parent.attrs.start ?? 1) + index}. `),
1185
+ ...withoutLeadingBreaks(ctx.render(el.children)),
1186
+ BREAK
1187
+ ];
1188
+ }).register("blockquote", (el, ctx) => quoteLines(ctx.render(el.children))).register("hr", () => ({ type: "divider" })).register("img", (el, ctx) => mediaNode(el, ctx), { variants: ["inline"] }).register("audio", (el, ctx) => mediaNode(el, ctx)).register("video", (el, ctx) => mediaNode(el, ctx)).register("file", (el, ctx) => mediaNode(el, ctx)).register("button", (el, ctx) => {
1189
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
1190
+ if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
1191
+ tag: "button",
1192
+ reason: "kook-button-lifted",
1193
+ path: ctx.stableId(el)
1194
+ });
1195
+ return {
1196
+ type: "buttons",
1197
+ buttons: [actionButton(el, ctx)]
1198
+ };
1199
+ }, { variants: [
1200
+ "action",
1201
+ "link",
1202
+ "submit",
1203
+ "theme",
1204
+ "inline"
1205
+ ] }).register("button-group", (el, ctx) => {
1206
+ const buttons = [];
1207
+ for (const node of ctx.render(el.children)) if (node.type === "buttons") buttons.push(...node.buttons);
1208
+ return chunk(buttons, KOOK_LIMITS.buttonsPerRow).map((group) => ({
1209
+ type: "buttons",
1210
+ buttons: group
1211
+ }));
1212
+ });
1213
+ return defineMode()({
1214
+ id: "kmarkdown",
1215
+ elements,
1216
+ limits: {
1217
+ "limit.text.chars": KOOK_LIMITS.textChars,
1218
+ "limit.buttons.row": KOOK_LIMITS.buttonsPerRow
1219
+ },
1220
+ assemble: (nodes, _envelope, ctx) => assembleDraft(nodes, ctx),
1221
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx)
1222
+ });
1223
+ }
1224
+ // lib/types/decode.js
1225
+ /**
1226
+ * Inbound decoding: one received KOOK payload becomes an intake `Session`, and one message object becomes an
1227
+ * `InboundMessage`.
1228
+ *
1229
+ * The event kinds the vocabulary can carry are chat messages (types 1/2/3/4/8/9/10), button clicks, deletions and
1230
+ * reactions; everything else is dropped with a debug line. A card is decoded module by module because KOOK now sends
1231
+ * file messages as cards, so skipping a card would lose the file; an unknown module keeps a text placeholder instead
1232
+ * of the whole card.
1233
+ */
1234
+ function asRecord$1(value) {
1235
+ return typeof value === "object" && value !== null ? value : void 0;
1236
+ }
1237
+ function asString$1(value) {
1238
+ return typeof value === "string" ? value : void 0;
1239
+ }
1240
+ function asNumber(value) {
1241
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1242
+ }
1243
+ function asArray(value) {
1244
+ return Array.isArray(value) ? value : [];
1245
+ }
1246
+ /** A timestamp in milliseconds, from the event or the clock. */
1247
+ function timeOf(data) {
1248
+ return data.msg_timestamp || Date.now();
1249
+ }
1250
+ /**
1251
+ * The chat one message event belongs to.
1252
+ *
1253
+ * A group message names its channel in `target_id`; a private one names the conversation (`chat_code`) in
1254
+ * `extra.code`, which is the id `/user-chat/create-msg` addresses. That field is the adapter's riskiest assumption on
1255
+ * the wire, so it is decoded exactly as the upstream adapter does.
1256
+ */
1257
+ function chatOfMessage(data, extra, bot) {
1258
+ const channelType = data.channel_type;
1259
+ if (channelType === "GROUP") return {
1260
+ id: data.target_id,
1261
+ type: "group",
1262
+ ...extra.channel_name === void 0 || extra.channel_name === "" ? {} : { name: extra.channel_name }
1263
+ };
1264
+ if (channelType === "BROADCAST") {
1265
+ bot.ctx.logger.debug("kook: a BROADCAST message arrives as a group message");
1266
+ return {
1267
+ id: data.target_id,
1268
+ type: "group"
1269
+ };
1270
+ }
1271
+ return {
1272
+ id: extra.code ?? "",
1273
+ type: "direct"
1274
+ };
1275
+ }
1276
+ /** The first non-empty name: an empty guild nickname falls back to the account name. */
1277
+ function nameOf(...names) {
1278
+ for (const name of names) if (name !== void 0 && name !== "") return name;
1279
+ }
1280
+ /** A user reference: the id a mention addresses, the name people see, and whether the account is a bot. */
1281
+ function userRefOf(user) {
1282
+ if (user === void 0) return { id: "" };
1283
+ const name = nameOf(user.nickname, user.username);
1284
+ return {
1285
+ id: String(user.id ?? ""),
1286
+ ...name === void 0 ? {} : { name },
1287
+ ...user.bot === true ? { isBot: true } : {}
1288
+ };
1289
+ }
1290
+ /** A user reference from one untyped wire record (`user_info`, `target_info`). */
1291
+ function userRefFromRecord(record) {
1292
+ const id = asString$1(record.id) ?? "";
1293
+ const name = nameOf(asString$1(record.nickname), asString$1(record.username));
1294
+ return {
1295
+ id,
1296
+ ...name === void 0 ? {} : { name },
1297
+ ...record.bot === true ? { isBot: true } : {}
1298
+ };
1299
+ }
1300
+ /** The referrer of one message, handed back as `Target.referrer` so a reply can name the message it answers. */
1301
+ function referrerOf(chat, messageId, guildId) {
1302
+ return {
1303
+ chatId: chat.id,
1304
+ channelType: chat.type === "group" ? "GROUP" : "PERSON",
1305
+ messageId,
1306
+ ...guildId === void 0 || guildId === "" ? {} : { guildId }
1307
+ };
1308
+ }
1309
+ /** The mention names KOOK reported alongside a kmarkdown message. */
1310
+ function mentionNames(meta) {
1311
+ const kmarkdown = meta?.kmarkdown;
1312
+ if (kmarkdown === void 0) return {};
1313
+ return {
1314
+ ...kmarkdown.mention_part === void 0 ? {} : { users: kmarkdown.mention_part },
1315
+ ...kmarkdown.mention_role_part === void 0 ? {} : { roles: kmarkdown.mention_role_part }
1316
+ };
1317
+ }
1318
+ /**
1319
+ * Decode the body of one message by its platform type.
1320
+ * @param base - the `type`/`content` pair of the message (an event or a read row).
1321
+ * @param meta - the metadata carrying attachments, mention names and the quote.
1322
+ * @returns the content nodes, in platform order.
1323
+ */
1324
+ function decodeContent(base, meta) {
1325
+ const attachment = meta?.attachments;
1326
+ const name = attachment?.name;
1327
+ switch (base.type) {
1328
+ case Type.text: return parseTextMentions(base.content);
1329
+ case Type.image: {
1330
+ const width = asNumber(attachment?.width);
1331
+ const height = asNumber(attachment?.height);
1332
+ return [h("img", {
1333
+ src: base.content,
1334
+ ...name === void 0 ? {} : { alt: name },
1335
+ ...width === void 0 ? {} : { width },
1336
+ ...height === void 0 ? {} : { height }
1337
+ })];
1338
+ }
1339
+ case Type.video: {
1340
+ const duration = asNumber(attachment?.duration);
1341
+ return [h("video", {
1342
+ src: base.content,
1343
+ ...name === void 0 ? {} : { name },
1344
+ ...duration === void 0 ? {} : { duration }
1345
+ })];
1346
+ }
1347
+ case Type.file: {
1348
+ const size = asNumber(attachment?.size);
1349
+ return [h("file", {
1350
+ src: base.content,
1351
+ ...name === void 0 ? {} : { name },
1352
+ ...size === void 0 ? {} : { size }
1353
+ })];
1354
+ }
1355
+ case Type.audio: {
1356
+ const duration = asNumber(attachment?.duration);
1357
+ return [h("audio", {
1358
+ src: base.content,
1359
+ ...name === void 0 ? {} : { name },
1360
+ ...duration === void 0 ? {} : { duration }
1361
+ })];
1362
+ }
1363
+ case Type.kmarkdown: return parseKMarkdown(base.content, mentionNames(meta));
1364
+ case Type.card: return decodeCard(base.content);
1365
+ default: return base.content === "" ? [] : [h.text(base.content)];
1366
+ }
1367
+ }
1368
+ /**
1369
+ * Parse the mentions of a plain-text message: `@name#id`, `@全体成员`, `@在线成员`, `@role:<id>;` and
1370
+ * `#channel:<id>;`.
1371
+ *
1372
+ * The upstream pattern had no `g` flag, so only the first mention of a message was decoded; every occurrence is
1373
+ * decoded here so the model sees the whole mention list.
1374
+ *
1375
+ * @param content - `d.content` of a type-1 message.
1376
+ * @returns the decoded content nodes.
1377
+ */
1378
+ function parseTextMentions(content) {
1379
+ const pattern = /@role:(\d+);|#channel:(\d+);|@全体成员|@在线成员|@(.+?)#(\d+)/g;
1380
+ const elements = [];
1381
+ let last = 0;
1382
+ for (let match = pattern.exec(content); match !== null; match = pattern.exec(content)) {
1383
+ if (match.index > last) elements.push(h.text(content.slice(last, match.index)));
1384
+ const whole = match[0] ?? "";
1385
+ const role = match[1];
1386
+ const channel = match[2];
1387
+ const name = match[3];
1388
+ const id = match[4];
1389
+ if (whole === "@全体成员") elements.push(h("at", { type: "all" }));
1390
+ else if (whole === "@在线成员") elements.push(h("at", { type: "here" }));
1391
+ else if (role !== void 0) elements.push(h("at", {
1392
+ type: "role",
1393
+ id: role
1394
+ }));
1395
+ else if (channel !== void 0) elements.push(h("channel", { id: channel }));
1396
+ else elements.push(h("at", {
1397
+ type: "user",
1398
+ id: id ?? "",
1399
+ ...name === void 0 ? {} : { name }
1400
+ }));
1401
+ last = match.index + whole.length;
1402
+ }
1403
+ if (last < content.length) elements.push(h.text(content.slice(last)));
1404
+ return elements;
1405
+ }
1406
+ /**
1407
+ * Decode a card message body (`type: 10`).
1408
+ *
1409
+ * @param content - the card JSON array, serialized as a string.
1410
+ * @returns the decoded content nodes; the raw text when the body is not JSON.
1411
+ */
1412
+ function decodeCard(content) {
1413
+ let parsed;
1414
+ try {
1415
+ parsed = JSON.parse(content);
1416
+ } catch (error) {
1417
+ return content === "" ? [] : [h.text(content)];
1418
+ }
1419
+ const cards = Array.isArray(parsed) ? parsed : [parsed];
1420
+ const nodes = [];
1421
+ for (const card of cards) {
1422
+ const record = asRecord$1(card);
1423
+ if (record === void 0) continue;
1424
+ for (const module of asArray(record.modules)) nodes.push(...decodeModule(module));
1425
+ }
1426
+ return nodes;
1427
+ }
1428
+ /** The content nodes of one card module. */
1429
+ function decodeModule(raw) {
1430
+ const module = asRecord$1(raw);
1431
+ if (module === void 0) return [];
1432
+ const type = asString$1(module.type);
1433
+ switch (type) {
1434
+ case "section": {
1435
+ const nodes = decodeCardText(module.text);
1436
+ const accessory = asRecord$1(module.accessory);
1437
+ if (accessory !== void 0) nodes.push(...decodeAccessory(accessory));
1438
+ return nodes;
1439
+ }
1440
+ case "header": {
1441
+ const text = cardPlainText(module.text);
1442
+ return text === "" ? [] : [h("p", h("b", text))];
1443
+ }
1444
+ case "container":
1445
+ case "image-group":
1446
+ case "context":
1447
+ case "action-group": return asArray(module.elements).flatMap((element) => decodeAccessory(element));
1448
+ case "divider": return [h("hr")];
1449
+ case "file":
1450
+ case "audio":
1451
+ case "video": {
1452
+ const src = asString$1(module.src) ?? "";
1453
+ if (src === "") return [];
1454
+ const title = asString$1(module.title) ?? "";
1455
+ return [h(type, {
1456
+ src,
1457
+ ...title === "" ? {} : { name: title }
1458
+ })];
1459
+ }
1460
+ case "countdown": return [h.text("[倒计时]")];
1461
+ case "invite": return [h.text("[邀请]")];
1462
+ default: return type === void 0 ? [] : [h.text(`[${type}]`)];
1463
+ }
1464
+ }
1465
+ /** The content nodes of a card `section.text` (a text object or a `paragraph` of fields). */
1466
+ function decodeCardText(raw) {
1467
+ const text = asRecord$1(raw);
1468
+ if (text === void 0) return [];
1469
+ if (text.type === "paragraph") {
1470
+ const nodes = [];
1471
+ for (const field of asArray(text.fields)) {
1472
+ if (nodes.length > 0) nodes.push(h.text("\n"));
1473
+ nodes.push(...decodeCardText(field));
1474
+ }
1475
+ return nodes;
1476
+ }
1477
+ const content = asString$1(text.content) ?? "";
1478
+ if (content === "") return [];
1479
+ return text.type === "plain-text" ? [h.text(content)] : parseKMarkdown(content);
1480
+ }
1481
+ /** The plain text of a card text object. */
1482
+ function cardPlainText(raw) {
1483
+ const text = asRecord$1(raw);
1484
+ return text === void 0 ? "" : asString$1(text.content) ?? "";
1485
+ }
1486
+ /** The content nodes of one card accessory (image or button). */
1487
+ function decodeAccessory(raw) {
1488
+ const accessory = asRecord$1(raw);
1489
+ if (accessory === void 0) return [];
1490
+ if (accessory.type === "plain-text" || accessory.type === "kmarkdown") return decodeCardText(accessory);
1491
+ if (accessory.type === "image") {
1492
+ const src = asString$1(accessory.src) ?? "";
1493
+ return src === "" ? [] : [h("img", { src })];
1494
+ }
1495
+ if (accessory.type === "button") {
1496
+ const label = asString$1(asRecord$1(accessory.text)?.content) ?? "";
1497
+ const value = asString$1(accessory.value) ?? "";
1498
+ return [accessory.click === "link" ? h("button", {
1499
+ type: "link",
1500
+ href: value
1501
+ }, label === "" ? value : label) : h("button", {
1502
+ type: "action",
1503
+ id: value
1504
+ }, label === "" ? value : label)];
1505
+ }
1506
+ const type = asString$1(accessory.type);
1507
+ return type === void 0 ? [] : [h.text(`[${type}]`)];
1508
+ }
1509
+ /** Collect what one decoded message mentions, from the decoded content and the platform's own mention lists. */
1510
+ function collectMentions(bot, content, meta) {
1511
+ const users = [];
1512
+ const seen = /* @__PURE__ */ new Set();
1513
+ const mentions = {
1514
+ self: false,
1515
+ all: meta?.mention_all === true,
1516
+ users
1517
+ };
1518
+ const add = (user) => {
1519
+ if (user.id === "") return;
1520
+ if (user.id === bot.selfId) mentions.self = true;
1521
+ if (seen.has(user.id)) return;
1522
+ seen.add(user.id);
1523
+ users.push(user);
1524
+ };
1525
+ const walk = (element) => {
1526
+ if (element.type === "at") {
1527
+ if (element.attrs.type === "all") mentions.all = true;
1528
+ else if (element.attrs.type === "user" && element.attrs.id !== void 0) add({
1529
+ id: element.attrs.id,
1530
+ ...element.attrs.name === void 0 ? {} : { name: element.attrs.name }
1531
+ });
1532
+ }
1533
+ for (const child of element.children) walk(child);
1534
+ };
1535
+ walk(content);
1536
+ const names = mentionNames(meta).users ?? [];
1537
+ for (const id of meta?.mention ?? []) {
1538
+ const name = names.find((user) => user.id === id)?.username;
1539
+ add({
1540
+ id,
1541
+ ...name === void 0 ? {} : { name }
1542
+ });
1543
+ }
1544
+ if (meta?.mention_here === true) bot.ctx.logger.debug("kook: mention_here is not represented in DSH mentions");
1545
+ return mentions;
1546
+ }
1547
+ /** A bounded description of a body that decoded to no content, so `<raw>` stays small. */
1548
+ function rawPreview(content) {
1549
+ return content.length > 500 ? `${content.slice(0, 500)}…` : content;
1550
+ }
1551
+ /** Decode one message row into an `InboundMessage` for the given chat. */
1552
+ function messageOf$3(bot, base, meta, chat, id, time) {
1553
+ const nodes = decodeContent(base, meta);
1554
+ const content = normalize(nodes.length > 0 ? nodes : [h("raw", {
1555
+ platform: "kook",
1556
+ type: String(base.type),
1557
+ data: rawPreview(base.content)
1558
+ }, "")]);
1559
+ const quote = meta?.quote;
1560
+ const quoteNodes = quote === void 0 ? [] : decodeContent(quote, quote);
1561
+ const quoteAuthor = quote?.author;
1562
+ return {
1563
+ id,
1564
+ chat,
1565
+ sender: userRefOf(meta?.author),
1566
+ content,
1567
+ ...quote === void 0 ? {} : { quote: {
1568
+ id: quote.id || quote.rong_id || "",
1569
+ ...quoteAuthor === void 0 ? {} : { sender: userRefOf(quoteAuthor) },
1570
+ ...quoteNodes.length === 0 ? {} : { content: normalize(quoteNodes) }
1571
+ } },
1572
+ mentions: collectMentions(bot, content, meta),
1573
+ time,
1574
+ referrer: referrerOf(chat, id, meta?.guild_id),
1575
+ raw: base
1576
+ };
1577
+ }
1578
+ /**
1579
+ * Decode one event message (`d.type !== 255`).
1580
+ * @param bot - the receiving adapter.
1581
+ * @param data - the event payload.
1582
+ * @returns the decoded inbound message.
1583
+ */
1584
+ function decodeInboundMessage(bot, data) {
1585
+ const extra = data.extra ?? {};
1586
+ return messageOf$3(bot, data, extra, chatOfMessage(data, extra, bot), data.msg_id, timeOf(data));
1587
+ }
1588
+ /**
1589
+ * Decode one message read by id (`/message/view`, `/user-chat/view`).
1590
+ *
1591
+ * @param bot - the adapter that read the message.
1592
+ * @param message - the message row.
1593
+ * @param chat - the chat the caller asked about; the read answer does not name its type, so the request stands.
1594
+ * @returns the decoded inbound message.
1595
+ */
1596
+ function decodeMessage(bot, message, chat) {
1597
+ return messageOf$3(bot, message, message, chat, message.id ?? "", Date.now());
1598
+ }
1599
+ /** The chat of a deletion or reaction notice. */
1600
+ function chatOfNotice(body) {
1601
+ const channelId = asString$1(body.channel_id) ?? "";
1602
+ if (channelId !== "") return {
1603
+ id: channelId,
1604
+ type: "group"
1605
+ };
1606
+ return {
1607
+ id: asString$1(body.chat_code) ?? "",
1608
+ type: "direct"
1609
+ };
1610
+ }
1611
+ /**
1612
+ * The chat of a button click.
1613
+ *
1614
+ * `data.channel_type` is always `PERSON` on a click, even in a guild, so the notice body decides: an explicit
1615
+ * `GROUP`, or a missing type with a `target_id`, is a group; otherwise the click came from a direct chat, whose id is
1616
+ * the chat code.
1617
+ */
1618
+ function chatOfButton(body) {
1619
+ const channelType = asString$1(body.channel_type);
1620
+ const targetId = asString$1(body.target_id) ?? "";
1621
+ if (channelType === "GROUP" || channelType === void 0 && targetId !== "") {
1622
+ const channelId = asString$1(body.channel_id) ?? "";
1623
+ return {
1624
+ id: channelId !== "" ? channelId : targetId,
1625
+ type: "group"
1626
+ };
1627
+ }
1628
+ return {
1629
+ id: asString$1(body.chat_code) ?? "",
1630
+ type: "direct"
1631
+ };
1632
+ }
1633
+ /** Decode one system event: a button click, a deletion or a reaction. */
1634
+ function decodeNotice(bot, data) {
1635
+ const notice = asRecord$1(data.extra);
1636
+ const type = asString$1(notice?.type);
1637
+ const body = asRecord$1(notice?.body);
1638
+ if (notice === void 0 || type === void 0 || body === void 0) return void 0;
1639
+ const time = data.msg_timestamp || asNumber(body.event_time) || Date.now();
1640
+ switch (type) {
1641
+ case "message_btn_click": {
1642
+ const value = asString$1(body.value) ?? "";
1643
+ const messageId = asString$1(body.msg_id) ?? "";
1644
+ const userId = asString$1(body.user_id) ?? asString$1(body.author_id) ?? "";
1645
+ const chat = chatOfButton(body);
1646
+ const info = asRecord$1(body.user_info);
1647
+ const user = info === void 0 ? { id: userId } : userRefFromRecord(info);
1648
+ return bot.session({
1649
+ type: "interaction/button",
1650
+ id: `button:${messageId}:${userId}:${value}`,
1651
+ timestamp: time,
1652
+ button: {
1653
+ bot,
1654
+ id: value,
1655
+ user,
1656
+ chat,
1657
+ message: {
1658
+ id: messageId,
1659
+ chat
1660
+ },
1661
+ referrer: referrerOf(chat, messageId, asString$1(body.guild_id)),
1662
+ time
1663
+ },
1664
+ raw: data
1665
+ });
1666
+ }
1667
+ case "deleted_message":
1668
+ case "deleted_private_message": {
1669
+ const messageId = asString$1(body.msg_id) ?? "";
1670
+ const chat = chatOfNotice(body);
1671
+ return bot.session({
1672
+ type: "message-deleted",
1673
+ id: `delete:${messageId}`,
1674
+ timestamp: time,
1675
+ deleted: {
1676
+ id: messageId,
1677
+ chat
1678
+ },
1679
+ raw: data
1680
+ });
1681
+ }
1682
+ case "added_reaction":
1683
+ case "private_added_reaction":
1684
+ case "deleted_reaction":
1685
+ case "private_deleted_reaction": {
1686
+ const messageId = asString$1(body.msg_id) ?? "";
1687
+ const userId = asString$1(body.user_id) ?? "";
1688
+ const emoji = asString$1(asRecord$1(body.emoji)?.id) ?? "";
1689
+ const chat = chatOfNotice(body);
1690
+ const added = type.includes("added");
1691
+ return bot.session({
1692
+ type: added ? "reaction-added" : "reaction-removed",
1693
+ id: `reaction:${added ? "add" : "remove"}:${messageId}:${userId}:${emoji}`,
1694
+ timestamp: time,
1695
+ reaction: {
1696
+ message: {
1697
+ id: messageId,
1698
+ chat
1699
+ },
1700
+ emoji,
1701
+ ...userId === "" ? {} : { user: { id: userId } }
1702
+ },
1703
+ raw: data
1704
+ });
1705
+ }
1706
+ case "updated_message":
1707
+ case "updated_private_message":
1708
+ bot.ctx.logger.debug("kook: ignored an edited-message event");
1709
+ return;
1710
+ default:
1711
+ bot.ctx.logger.debug("kook: ignored the %s system event", type);
1712
+ return;
1713
+ }
1714
+ }
1715
+ /**
1716
+ * Decode one received payload.
1717
+ *
1718
+ * @param bot - the receiving adapter, whose `selfId` marks the bot's own mentions.
1719
+ * @param data - the payload's `d` field.
1720
+ * @returns the session to publish, or undefined for an event this adapter does not carry.
1721
+ */
1722
+ function decodeEvent(bot, data) {
1723
+ if (data.type === Type.system) return decodeNotice(bot, data);
1724
+ const message = decodeInboundMessage(bot, data);
1725
+ return bot.session({
1726
+ type: "message",
1727
+ id: message.id,
1728
+ timestamp: message.time,
1729
+ message,
1730
+ raw: data
1731
+ });
1732
+ }
1733
+ // lib/types/send.js
1734
+ /**
1735
+ * Outbound hooks: the send pipeline's payload, deletion, member reads and message reads.
1736
+ *
1737
+ * A channel message goes to `/message/create` (or `/message/view`, `/message/delete`); a direct one goes to the
1738
+ * upstream adapter's `/user-chat/*` routes. The two are told apart exactly as upstream tells them apart: a channel id
1739
+ * is 16–19 digits and a direct chat code is 32 hexadecimal characters, so the longer id is the direct chat.
1740
+ */
1741
+ /** Whether a chat id names a direct chat: a `chat_code` (32 hex characters) is longer than a channel id. */
1742
+ function isDirectChannel(chatId) {
1743
+ return chatId.length > 30;
1744
+ }
1745
+ /** The platform path of one message operation, by chat kind. */
1746
+ function pathOf(chatId, channel, direct) {
1747
+ return isDirectChannel(chatId) ? direct : channel;
1748
+ }
1749
+ /** The published part of one sent message. */
1750
+ function partOf(receipt, kind, target) {
1751
+ if (receipt?.msg_id === void 0 || receipt.msg_id === "") throw new PlatformError("invalid", "kook: the platform answered without a msg_id", { published: "unknown" });
1752
+ const referrer = {
1753
+ chatId: target.chat.id,
1754
+ channelType: target.chat.type === "group" ? "GROUP" : "PERSON",
1755
+ messageId: receipt.msg_id
1756
+ };
1757
+ return {
1758
+ id: receipt.msg_id,
1759
+ kind,
1760
+ time: receipt.msg_timestamp === void 0 ? Date.now() : receipt.msg_timestamp,
1761
+ referrer
1762
+ };
1763
+ }
1764
+ /**
1765
+ * Send one serialized payload.
1766
+ *
1767
+ * @param request - endpoints for this bot.
1768
+ * @param payload - the serialized draft (`type: 9` text or `type: 10` card).
1769
+ * @param target - the chat the payload goes to.
1770
+ * @param _ctx - part index and quote, already applied by `serialize`.
1771
+ * @returns the published part.
1772
+ */
1773
+ async function sendPayload(request, payload, target, _ctx) {
1774
+ if (typeof target.thread === "string") throw new PlatformError("invalid", "kook has no message threads", { published: "no" });
1775
+ const direct = isDirectChannel(target.chat.id);
1776
+ const body = {
1777
+ type: payload.type,
1778
+ content: payload.content
1779
+ };
1780
+ if (direct) body.chat_code = target.chat.id;
1781
+ else body.target_id = target.chat.id;
1782
+ if (payload.quote !== void 0) body.quote = payload.quote;
1783
+ return partOf(await invoke(request, "POST", direct ? "/user-chat/create-msg" : "/message/create", body), payload.kind, target);
1784
+ }
1785
+ /**
1786
+ * Recall one published part.
1787
+ * @param request - endpoints for this bot.
1788
+ * @param part - the part to recall.
1789
+ * @param handle - the message the part belongs to, which names the chat.
1790
+ */
1791
+ async function deletePart(request, part, handle) {
1792
+ await invoke(request, "POST", pathOf(handle.target.chat.id, "/message/delete", "/user-chat/delete-msg"), { msg_id: part.id });
1793
+ }
1794
+ /** The page number a cursor names; anything unreadable starts at the first page. */
1795
+ function pageOf(cursor) {
1796
+ const page = Number(cursor ?? "");
1797
+ return Number.isFinite(page) && page >= 1 ? Math.floor(page) : 1;
1798
+ }
1799
+ /**
1800
+ * List the members of a chat.
1801
+ *
1802
+ * A group chat pages `/guild/user-list`; the guild id comes from `/channel/view` because the chat only knows its
1803
+ * channel. A direct chat has exactly one member, which `/user-chat/view` reports.
1804
+ *
1805
+ * @param request - endpoints for this bot.
1806
+ * @param chat - the chat the caller asked about.
1807
+ * @param cursor - page number of the previous page's `next`.
1808
+ * @param limit - page size the platform should use (at most 50).
1809
+ * @returns one page of members.
1810
+ */
1811
+ async function members(request, chat, cursor, limit) {
1812
+ if (isDirectChannel(chat.id)) {
1813
+ const target = (await invoke(request, "GET", "/user-chat/view", { chat_code: chat.id }))?.target_info;
1814
+ return { data: target === void 0 ? [] : [userRefOf(target)] };
1815
+ }
1816
+ const page = pageOf(cursor);
1817
+ const pageSize = Math.max(1, Math.min(limit ?? KOOK_LIMITS.membersPageSize, KOOK_LIMITS.membersPageSize));
1818
+ const channel = await invoke(request, "GET", "/channel/view", { target_id: chat.id });
1819
+ if (channel?.guild_id === void 0 || channel.guild_id === "") throw new PlatformError("not-found", `kook: channel ${chat.id} names no guild`, { published: "no" });
1820
+ const list = await invoke(request, "GET", "/guild/user-list", {
1821
+ guild_id: channel.guild_id,
1822
+ page,
1823
+ page_size: pageSize
1824
+ });
1825
+ return {
1826
+ data: list.items.map((member) => userRefOf(member)),
1827
+ ...page < (list.meta?.page_total ?? page) ? { next: String(page + 1) } : {}
1828
+ };
1829
+ }
1830
+ /**
1831
+ * Read one message by id.
1832
+ *
1833
+ * The read answer names the channel but not its type, so the requested chat is what the decoded message reports; the
1834
+ * host verifies that its id matches the chat it asked about.
1835
+ *
1836
+ * @param request - endpoints for this bot.
1837
+ * @param bot - the adapter, needed to decode the answer.
1838
+ * @param chat - the chat the caller asked about.
1839
+ * @param id - platform message id.
1840
+ * @returns the decoded message.
1841
+ */
1842
+ async function getMessage(request, bot, chat, id) {
1843
+ const raw = await invoke(request, "GET", isDirectChannel(chat.id) ? "/user-chat/view" : "/message/view", { msg_id: id });
1844
+ if (raw === void 0 || raw === null || typeof raw !== "object") throw new PlatformError("not-found", `kook: message ${id} is not in ${chat.id}`, { published: "no" });
1845
+ return decodeMessage(bot, raw, chat);
1846
+ }
1847
+ // lib/types/webhook.js
1848
+ /**
1849
+ * Webhook transport (`protocol: 'http'`).
1850
+ *
1851
+ * The profile's `webServer` owns the listener, so this transport only registers one anonymous route at `path` and
1852
+ * checks every request itself: `verify_token` must match the platform-issued token, and the challenge handshake is
1853
+ * answered within the one second KOOK allows.
1854
+ *
1855
+ * The platform is confirmed only after `bot.receive` accepted the frame; a failure answers `500`, which makes KOOK
1856
+ * redeliver (2/4/8/16/32/64 s, at most five times). The cost is that a slow intake occasionally exceeds the one-second
1857
+ * challenge budget and triggers a redelivery, which the host de-duplicates on `msg_id`.
1858
+ *
1859
+ * KOOK only configures callbacks in the developer console, so there is nothing to register with the platform here and
1860
+ * no `publicUrl` option; the operator must append `?compress=0` to the callback URL because v1 does not decompress
1861
+ * bodies.
1862
+ */
1863
+ function asRecord(value) {
1864
+ return typeof value === "object" && value !== null ? value : void 0;
1865
+ }
1866
+ function asString(value) {
1867
+ return typeof value === "string" ? value : void 0;
1868
+ }
1869
+ /** Read a request body to its end. The adapter imposes no size limit, as the upstream plugin does not. */
1870
+ async function readBody(request) {
1871
+ const chunks = [];
1872
+ for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1873
+ return Buffer.concat(chunks).toString("utf8");
1874
+ }
1875
+ /** Answer one request without a body. */
1876
+ function writeStatus(response, status, headers = {}) {
1877
+ response.writeHead(status, headers);
1878
+ response.end();
1879
+ }
1880
+ /** Message of any caught value, for a log line. */
1881
+ function messageOf$2(error) {
1882
+ return error instanceof Error ? error.message : String(error);
1883
+ }
1884
+ /** The Webhook transport of one bot. */
1885
+ var KookWebhook = class {
1886
+ bot;
1887
+ dispose;
1888
+ constructor(bot) {
1889
+ this.bot = bot;
1890
+ }
1891
+ /** Register the route; a profile without a web server fails with an actionable message. */
1892
+ async start() {
1893
+ const webServer = this.bot.ctx.get("webServer");
1894
+ if (webServer === void 0) throw this.failStart("kook: protocol \"http\" needs a profile-provided webServer; use protocol \"ws\" instead");
1895
+ this.dispose = webServer.register({
1896
+ kind: "exact",
1897
+ path: routePath(this.bot.config.path),
1898
+ auth: "anonymous",
1899
+ handler: (request, response) => this.handle(request, response)
1900
+ });
1901
+ this.bot.online();
1902
+ }
1903
+ /** Release the route. The platform keeps posting to it until the console's callback URL changes. */
1904
+ async stop() {
1905
+ this.dispose?.();
1906
+ this.dispose = void 0;
1907
+ }
1908
+ /**
1909
+ * Log a fatal start failure before the caller throws it, because `Bot.start` only stores a connect failure on
1910
+ * `bot.error`.
1911
+ * @param message - error text that also names the corrective action.
1912
+ * @returns the error for the caller to throw.
1913
+ */
1914
+ failStart(message) {
1915
+ this.bot.ctx.logger.error(message);
1916
+ return new Error(message);
1917
+ }
1918
+ async handle(request, response) {
1919
+ try {
1920
+ if (request.method !== "POST") {
1921
+ writeStatus(response, 405, { allow: "POST" });
1922
+ return;
1923
+ }
1924
+ const body = await readBody(request);
1925
+ let parsed;
1926
+ try {
1927
+ parsed = JSON.parse(body);
1928
+ } catch (error) {
1929
+ this.bot.ctx.logger.warn("kook: cannot parse a webhook body: %s", messageOf$2(error));
1930
+ writeStatus(response, 400);
1931
+ return;
1932
+ }
1933
+ const frame = asRecord(parsed);
1934
+ const data = asRecord(frame?.d);
1935
+ if (frame === void 0 || data === void 0) {
1936
+ writeStatus(response, 400);
1937
+ return;
1938
+ }
1939
+ if (asString(data.verify_token) !== this.bot.config.verifyToken) {
1940
+ writeStatus(response, 403);
1941
+ return;
1942
+ }
1943
+ const challenge = asString(data.challenge);
1944
+ if (challenge !== void 0 && challenge !== "") {
1945
+ response.writeHead(200, { "content-type": "application/json" });
1946
+ response.end(JSON.stringify({ challenge }));
1947
+ return;
1948
+ }
1949
+ const rawData = frame.d;
1950
+ const session = decodeEvent(this.bot, rawData);
1951
+ if (session !== void 0) await this.bot.receive(session);
1952
+ writeStatus(response, 200);
1953
+ } catch (error) {
1954
+ this.bot.ctx.logger.warn("kook: webhook delivery failed: %s", messageOf$2(error));
1955
+ if (!response.headersSent) writeStatus(response, 500);
1956
+ else response.end();
1957
+ }
1958
+ }
1959
+ };
1960
+ // lib/types/ws.js
1961
+ /**
1962
+ * Gateway WebSocket transport (`protocol: 'ws'`).
1963
+ *
1964
+ * The adapter fetches `/gateway/index?compress=0` before **every** dial (KOOK hands out a fresh gateway URL), dials it
1965
+ * with the `http` service and keeps dialing forever: `ws.retryTimes` is a fast-retry budget, not a give-up count.
1966
+ * Resume is not implemented — the platform would replay the offline window only for a client that keeps its session,
1967
+ * and the upstream adapter never did — so a dropped connection loses the events it missed and the bot says so in its
1968
+ * logs.
1969
+ *
1970
+ * The `sn` heartbeat confirmation is the platform's ACK: the `sn` a PING carries is the last message `bot.receive`
1971
+ * accepted, so a receive that fails leaves the event unconfirmed and the platform retransmits it on the next heartbeat.
1972
+ */
1973
+ /** The platform requires HELLO within 6 s of the connection opening. */
1974
+ const HELLO_TIMEOUT = 6e3;
1975
+ /** The platform requires PONG within 6 s of a PING. */
1976
+ const PONG_TIMEOUT = 6e3;
1977
+ /** Heartbeat interval, 30 s plus a random ±5 s as the platform asks. */
1978
+ const HEARTBEAT_BASE = 3e4;
1979
+ const HEARTBEAT_JITTER = 5e3;
1980
+ /** Waitable sleep that resolves early on abort. */
1981
+ function sleep(ms, signal) {
1982
+ return new Promise((resolve) => {
1983
+ if (signal.aborted) {
1984
+ resolve();
1985
+ return;
1986
+ }
1987
+ const timer = setTimeout(() => {
1988
+ signal.removeEventListener("abort", onAbort);
1989
+ resolve();
1990
+ }, ms);
1991
+ const onAbort = () => {
1992
+ clearTimeout(timer);
1993
+ resolve();
1994
+ };
1995
+ signal.addEventListener("abort", onAbort, { once: true });
1996
+ });
1997
+ }
1998
+ /** Text of one WebSocket frame. */
1999
+ function frameText(data) {
2000
+ return typeof data === "string" ? data : String(data);
2001
+ }
2002
+ /** One JSON field of one frame, when it is an object. */
2003
+ function recordOf(value) {
2004
+ return typeof value === "object" && value !== null ? value : void 0;
2005
+ }
2006
+ /** One number field of one frame. */
2007
+ function numberOf(value) {
2008
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2009
+ }
2010
+ /** The platform refused the connection for a reason only a corrected configuration can fix. */
2011
+ var KookGatewayFatalError = class extends Error {
2012
+ constructor(message) {
2013
+ super(message);
2014
+ this.name = "KookGatewayFatalError";
2015
+ }
2016
+ };
2017
+ /**
2018
+ * The Gateway client of one bot.
2019
+ *
2020
+ * `start()` returns after starting the reconnect loop, never after the first HELLO: `Bot.start` awaits `connect()`,
2021
+ * and holding plugin initialization open until KOOK is reachable would block the whole profile.
2022
+ */
2023
+ var KookWsTransport = class {
2024
+ bot;
2025
+ controller;
2026
+ running;
2027
+ socket;
2028
+ heartbeatTimer;
2029
+ pongTimer;
2030
+ constructor(bot) {
2031
+ this.bot = bot;
2032
+ }
2033
+ /** Start the reconnect loop. */
2034
+ async start() {
2035
+ this.controller = new AbortController();
2036
+ this.running = this.loop(this.controller.signal);
2037
+ }
2038
+ /** Stop the loop and wait for it to unwind. */
2039
+ async stop() {
2040
+ this.controller?.abort();
2041
+ this.controller = void 0;
2042
+ this.closeSocket();
2043
+ await this.running?.catch(() => void 0);
2044
+ this.running = void 0;
2045
+ }
2046
+ /** Delay before the next dial: the fast interval while the failure budget lasts, the lazy one after it. */
2047
+ intervalOf(failures) {
2048
+ const { ws } = this.bot.config;
2049
+ return failures < ws.retryTimes ? ws.retryInterval : ws.retryLazy;
2050
+ }
2051
+ async loop(signal) {
2052
+ let failures = 0;
2053
+ while (!signal.aborted) try {
2054
+ const socket = await this.open(signal);
2055
+ const greeted = await this.accept(socket, signal);
2056
+ if (signal.aborted) return;
2057
+ failures = greeted ? 0 : failures + 1;
2058
+ this.bot.ctx.logger.warn("kook: the gateway connection closed; reconnecting");
2059
+ this.bot.status = Status.RECONNECT;
2060
+ await sleep(this.intervalOf(failures), signal);
2061
+ } catch (error) {
2062
+ if (signal.aborted) return;
2063
+ if (error instanceof KookGatewayFatalError) {
2064
+ this.bot.ctx.logger.error(error.message);
2065
+ this.bot.offline(error);
2066
+ return;
2067
+ }
2068
+ failures += 1;
2069
+ this.bot.ctx.logger.warn("kook: %s; reconnecting", messageOf$1(error));
2070
+ this.bot.status = Status.RECONNECT;
2071
+ await sleep(this.intervalOf(failures), signal);
2072
+ }
2073
+ }
2074
+ /** Fetch a fresh gateway URL and dial it, resolving once the socket opens. */
2075
+ async open(signal) {
2076
+ const url = (await invoke(this.bot.request, "GET", "/gateway/index", { compress: 0 }, signal))?.url;
2077
+ if (url === void 0 || url === "") throw new Error("kook: /gateway/index answered without a url");
2078
+ return await this.dial(url, signal);
2079
+ }
2080
+ /** Dial one gateway URL and resolve once the socket is open. */
2081
+ dial(url, signal) {
2082
+ const socket = this.bot.ctx.http.ws(url, { headers: { authorization: `Bot ${this.bot.config.token}` } });
2083
+ return new Promise((resolve, reject) => {
2084
+ const cleanup = () => {
2085
+ socket.removeEventListener("open", onOpen);
2086
+ socket.removeEventListener("error", onError);
2087
+ socket.removeEventListener("close", onClose);
2088
+ signal.removeEventListener("abort", onAbort);
2089
+ };
2090
+ const onOpen = () => {
2091
+ cleanup();
2092
+ resolve(socket);
2093
+ };
2094
+ const onError = (event) => {
2095
+ cleanup();
2096
+ reject(/* @__PURE__ */ new Error(`kook: WebSocket error${event.message === void 0 ? "" : `: ${event.message}`}`));
2097
+ };
2098
+ const onClose = (event) => {
2099
+ cleanup();
2100
+ reject(/* @__PURE__ */ new Error(`kook: WebSocket closed before opening (code ${event.code})`));
2101
+ };
2102
+ const onAbort = () => {
2103
+ cleanup();
2104
+ reject(signal.reason ?? /* @__PURE__ */ new Error("kook: adapter stopped"));
2105
+ };
2106
+ if (signal.aborted) {
2107
+ onAbort();
2108
+ return;
2109
+ }
2110
+ socket.addEventListener("open", onOpen);
2111
+ socket.addEventListener("error", onError);
2112
+ socket.addEventListener("close", onClose);
2113
+ signal.addEventListener("abort", onAbort, { once: true });
2114
+ });
2115
+ }
2116
+ /**
2117
+ * Serve one open connection until it closes.
2118
+ * @param socket - the open socket.
2119
+ * @param signal - cancellation of the loop.
2120
+ * @returns whether HELLO arrived, i.e. whether the connection ever worked.
2121
+ */
2122
+ async accept(socket, signal) {
2123
+ this.socket = socket;
2124
+ let greeted = false;
2125
+ let sn = 0;
2126
+ let queue = Promise.resolve();
2127
+ let helloCode;
2128
+ let helloDone = false;
2129
+ let settleHello;
2130
+ const hello = new Promise((resolve) => {
2131
+ settleHello = resolve;
2132
+ });
2133
+ const settle = (code) => {
2134
+ if (helloDone) return;
2135
+ helloDone = true;
2136
+ helloCode = code;
2137
+ settleHello?.();
2138
+ };
2139
+ const closed = new Promise((resolve) => {
2140
+ socket.addEventListener("close", () => {
2141
+ settle(void 0);
2142
+ resolve();
2143
+ });
2144
+ });
2145
+ socket.addEventListener("message", (event) => {
2146
+ let parsed;
2147
+ try {
2148
+ parsed = JSON.parse(frameText(event.data));
2149
+ } catch (error) {
2150
+ this.bot.ctx.logger.warn("kook: cannot parse a gateway frame: %s", messageOf$1(error));
2151
+ return;
2152
+ }
2153
+ switch (parsed.s) {
2154
+ case Signal.event:
2155
+ queue = queue.then(async () => {
2156
+ try {
2157
+ const session = decodeEvent(this.bot, parsed.d);
2158
+ if (session !== void 0) await this.bot.receive(session);
2159
+ const frameSn = numberOf(parsed.sn);
2160
+ if (frameSn !== void 0) sn = Math.max(sn, frameSn);
2161
+ } catch (error) {
2162
+ this.bot.ctx.logger.error("kook: intake failed: %s", messageOf$1(error));
2163
+ }
2164
+ });
2165
+ break;
2166
+ case Signal.hello:
2167
+ settle(numberOf(recordOf(parsed.d)?.code) ?? 0);
2168
+ break;
2169
+ case Signal.pong:
2170
+ this.clearPong();
2171
+ break;
2172
+ case Signal.resume: {
2173
+ const code = numberOf(recordOf(parsed.d)?.code);
2174
+ this.bot.ctx.logger.info("kook: the platform asked for a reconnect%s", code === void 0 ? "" : ` (code ${code})`);
2175
+ if (isResumeCode(code)) this.bot.ctx.logger.warn("kook: the platform refused the session (%s); resume is not implemented, so the offline window is lost", code);
2176
+ this.closeSocket();
2177
+ break;
2178
+ }
2179
+ default: this.bot.ctx.logger.debug("kook: ignored a gateway frame with s=%s", String(parsed.s));
2180
+ }
2181
+ });
2182
+ const deadline = setTimeout(() => {
2183
+ settle(NaN);
2184
+ }, HELLO_TIMEOUT);
2185
+ const onAbort = () => {
2186
+ settle(NaN);
2187
+ this.closeSocket();
2188
+ };
2189
+ signal.addEventListener("abort", onAbort, { once: true });
2190
+ try {
2191
+ await hello;
2192
+ clearTimeout(deadline);
2193
+ if (signal.aborted) return false;
2194
+ if (helloCode === void 0) throw new Error("kook: the gateway connection closed before HELLO");
2195
+ if (Number.isNaN(helloCode)) {
2196
+ this.closeSocket();
2197
+ throw new Error(`kook: HELLO did not arrive within ${HELLO_TIMEOUT / 1e3} s`);
2198
+ }
2199
+ if (helloCode !== 0) {
2200
+ this.closeSocket();
2201
+ if (isPermanentHelloCode(helloCode)) throw new KookGatewayFatalError(`kook: the gateway refused the connection (code ${helloCode}); fix token/selfId and restart`);
2202
+ throw new Error(`kook: the gateway HELLO failed with code ${helloCode}`);
2203
+ }
2204
+ greeted = true;
2205
+ this.bot.online();
2206
+ this.scheduleHeartbeat(socket, () => sn, signal);
2207
+ await closed;
2208
+ await queue;
2209
+ return greeted;
2210
+ } finally {
2211
+ clearTimeout(deadline);
2212
+ signal.removeEventListener("abort", onAbort);
2213
+ this.stopHeartbeat();
2214
+ if (this.socket === socket) this.socket = void 0;
2215
+ }
2216
+ }
2217
+ /** One heartbeat at 30 s ± 5 s, then another; a missing PONG within 6 s closes the socket for the reconnect loop. */
2218
+ scheduleHeartbeat(socket, sn, signal) {
2219
+ this.stopHeartbeat();
2220
+ this.queueHeartbeat(socket, sn, signal);
2221
+ }
2222
+ /** Arm the next heartbeat without dropping the PONG deadline of the one already sent. */
2223
+ queueHeartbeat(socket, sn, signal) {
2224
+ const delay = HEARTBEAT_BASE + Math.round((Math.random() * 2 - 1) * HEARTBEAT_JITTER);
2225
+ this.heartbeatTimer = setTimeout(() => {
2226
+ if (signal.aborted || this.socket !== socket) return;
2227
+ try {
2228
+ socket.send(JSON.stringify({
2229
+ s: Signal.ping,
2230
+ sn: sn()
2231
+ }));
2232
+ } catch (error) {
2233
+ this.bot.ctx.logger.warn("kook: could not send a heartbeat: %s", messageOf$1(error));
2234
+ this.closeSocket();
2235
+ return;
2236
+ }
2237
+ this.pongTimer = setTimeout(() => {
2238
+ if (this.socket !== socket) return;
2239
+ this.bot.ctx.logger.warn("kook: the gateway did not answer the heartbeat within %s s; reconnecting", PONG_TIMEOUT / 1e3);
2240
+ this.closeSocket();
2241
+ }, PONG_TIMEOUT);
2242
+ this.queueHeartbeat(socket, sn, signal);
2243
+ }, delay);
2244
+ }
2245
+ clearPong() {
2246
+ if (this.pongTimer !== void 0) clearTimeout(this.pongTimer);
2247
+ this.pongTimer = void 0;
2248
+ }
2249
+ stopHeartbeat() {
2250
+ if (this.heartbeatTimer !== void 0) clearTimeout(this.heartbeatTimer);
2251
+ this.heartbeatTimer = void 0;
2252
+ this.clearPong();
2253
+ }
2254
+ closeSocket() {
2255
+ const socket = this.socket;
2256
+ this.socket = void 0;
2257
+ this.stopHeartbeat();
2258
+ try {
2259
+ socket?.close(1e3, "adapter stopped");
2260
+ } catch (error) {}
2261
+ }
2262
+ };
2263
+ /** Message of any caught value, for a log line. */
2264
+ function messageOf$1(error) {
2265
+ return error instanceof Error ? error.message : String(error);
2266
+ }
2267
+ // lib/types/bot.js
2268
+ /** MIME type by file extension for the multipart part name of an upload. */
2269
+ const EXTENSIONS = {
2270
+ "image/png": ".png",
2271
+ "image/jpeg": ".jpg",
2272
+ "image/gif": ".gif",
2273
+ "image/webp": ".webp",
2274
+ "video/mp4": ".mp4",
2275
+ "video/quicktime": ".mov",
2276
+ "audio/mpeg": ".mp3",
2277
+ "audio/ogg": ".ogg",
2278
+ "audio/wav": ".wav",
2279
+ "application/pdf": ".pdf",
2280
+ "text/plain": ".txt"
2281
+ };
2282
+ /** Message of any caught value, for a log line. */
2283
+ function messageOf(error) {
2284
+ return error instanceof Error ? error.message : String(error);
2285
+ }
2286
+ /** The file extension a MIME type names, when it has one worth adding to the upload name. */
2287
+ function extensionOf(mime) {
2288
+ return mime === void 0 ? "" : EXTENSIONS[mime] ?? "";
2289
+ }
2290
+ /**
2291
+ * KOOK adapter.
2292
+ *
2293
+ * Identity is the configured `selfId`, checked against `/user/me` on connect; the Gateway WebSocket and the Webhook are
2294
+ * the two transports; `kmarkdown` is the only mode, because a KOOK message is either KMarkdown text or a card and the
2295
+ * mode chooses between them per message. Outbound media goes through `/asset/create` because card images must be
2296
+ * uploaded by this bot.
2297
+ */
2298
+ var KookBot = class extends Adapter {
2299
+ /** The adapter needs the Satori service and the isolated `http` service. */
2300
+ static inject = ["satori", "http"];
2301
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
2302
+ static Config = Config;
2303
+ modes = { kmarkdown: createKmarkdownMode() };
2304
+ modeOrder = ["kmarkdown"];
2305
+ /** Endpoints shared by every API call of this bot. */
2306
+ request;
2307
+ /** Full typed KOOK API surface registered by the migrated declarations. */
2308
+ internal;
2309
+ transport;
2310
+ constructor(ctx, config) {
2311
+ const invalid = configError(config);
2312
+ if (invalid !== void 0) throw invalid;
2313
+ super(ctx, config, {
2314
+ id: `kook:${config.selfId}`,
2315
+ platform: "kook",
2316
+ adapter: "kook"
2317
+ });
2318
+ this.selfId = config.selfId;
2319
+ this.request = createKookRequest(ctx, config.apiBaseUrl, config.token);
2320
+ this.internal = new Internal(this.request);
2321
+ }
2322
+ async connect() {
2323
+ try {
2324
+ const user = await verifyIdentity(this.request, this.config.selfId);
2325
+ this.user = {
2326
+ id: this.selfId,
2327
+ name: user.username === void 0 || user.username === "" ? this.selfId : user.username,
2328
+ ...user.avatar === void 0 || user.avatar === "" ? {} : { avatar: user.avatar },
2329
+ isBot: true
2330
+ };
2331
+ } catch (error) {
2332
+ this.ctx.logger.error("kook: connect failed: %s", messageOf(error));
2333
+ throw error;
2334
+ }
2335
+ this.transport = this.config.protocol === "http" ? new KookWebhook(this) : new KookWsTransport(this);
2336
+ await this.transport.start();
2337
+ }
2338
+ async disconnect() {
2339
+ const transport = this.transport;
2340
+ this.transport = void 0;
2341
+ await transport?.stop();
2342
+ }
2343
+ /**
2344
+ * Upload one outbound attachment to `/asset/create`.
2345
+ *
2346
+ * The platform requires card images to be uploaded by the bot itself ("图片必须由你的机器人上传"), so every media
2347
+ * element is uploaded and the returned URL is what the card carries; an external link is never used.
2348
+ */
2349
+ async upload(ref, _scope, ctx) {
2350
+ const fetched = await ctx.fetch(ref.src, ctx.signal);
2351
+ const mime = ref.meta.mime ?? fetched.mime ?? "application/octet-stream";
2352
+ const name = ref.meta.name ?? fetched.name ?? `kook-${ref.kind}${extensionOf(mime)}`;
2353
+ const form = new FormData();
2354
+ form.append("file", new Blob([fetched.data], { type: mime }), name);
2355
+ const url = (await invoke(this.request, "POST", "/asset/create", form))?.url;
2356
+ if (url === void 0 || url === "") throw new PlatformError("invalid", "kook: /asset/create answered without a url", { published: "no" });
2357
+ return { key: url };
2358
+ }
2359
+ resourceScope(_target, _kind) {
2360
+ return this.id;
2361
+ }
2362
+ async sendPayload(payload, target, ctx) {
2363
+ return await sendPayload(this.request, payload, target, ctx);
2364
+ }
2365
+ async deletePart(part, handle) {
2366
+ await deletePart(this.request, part, handle);
2367
+ }
2368
+ async members(chat, cursor, limit) {
2369
+ return await members(this.request, chat, cursor, limit);
2370
+ }
2371
+ async getMessage(chat, id) {
2372
+ return await getMessage(this.request, this, chat, id);
2373
+ }
2374
+ classify(error) {
2375
+ return classifyKookError(error);
2376
+ }
2377
+ };
2378
+ export { Config, Internal, KOOK_LIMITS, types_exports as Kook, KookApiError, KookBot, KookBot as default, KookIdentityError, KookWebhook, KookWsTransport, assembleDraft, chatOfMessage, chunk, classifyKookError, configError, createKmarkdownMode, createKookRequest, decodeCard, decodeContent, decodeEvent, decodeInboundMessage, decodeMessage, deletePart, escapeKMarkdown, fileName, getMessage, groupImages, invoke, isDirectChannel, isPermanentHelloCode, isResumeCode, mediaNode, members, parseKMarkdown, parseTextMentions, referrerOf, retryAfterOf, routePath, sendPayload, serializeDraft, splitKMarkdown, textNode, textOf, themeOf, unescapeKMarkdown, userRefOf, verifyIdentity, visibleLength, withMark };
2379
+
2380
+ //# sourceMappingURL=index.js.map