@im-more/dsh-onebot 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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +11 -0
  3. package/lib/index.js +2003 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +55 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +140 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +40 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +33 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/cqcode.d.ts +29 -0
  14. package/lib/types/cqcode.d.ts.map +1 -0
  15. package/lib/types/cqcode.js +73 -0
  16. package/lib/types/cqcode.js.map +1 -0
  17. package/lib/types/decode.d.ts +106 -0
  18. package/lib/types/decode.d.ts.map +1 -0
  19. package/lib/types/decode.js +433 -0
  20. package/lib/types/decode.js.map +1 -0
  21. package/lib/types/errors.d.ts +32 -0
  22. package/lib/types/errors.d.ts.map +1 -0
  23. package/lib/types/errors.js +117 -0
  24. package/lib/types/errors.js.map +1 -0
  25. package/lib/types/identity.d.ts +18 -0
  26. package/lib/types/identity.d.ts.map +1 -0
  27. package/lib/types/identity.js +27 -0
  28. package/lib/types/identity.js.map +1 -0
  29. package/lib/types/index.d.ts +7 -0
  30. package/lib/types/index.d.ts.map +1 -0
  31. package/lib/types/index.js +6 -0
  32. package/lib/types/index.js.map +1 -0
  33. package/lib/types/modes/segment.d.ts +16 -0
  34. package/lib/types/modes/segment.d.ts.map +1 -0
  35. package/lib/types/modes/segment.js +80 -0
  36. package/lib/types/modes/segment.js.map +1 -0
  37. package/lib/types/modes/shared.d.ts +101 -0
  38. package/lib/types/modes/shared.d.ts.map +1 -0
  39. package/lib/types/modes/shared.js +208 -0
  40. package/lib/types/modes/shared.js.map +1 -0
  41. package/lib/types/request.d.ts +64 -0
  42. package/lib/types/request.d.ts.map +1 -0
  43. package/lib/types/request.js +108 -0
  44. package/lib/types/request.js.map +1 -0
  45. package/lib/types/send.d.ts +93 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +161 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/transport/http.d.ts +29 -0
  50. package/lib/types/transport/http.d.ts.map +1 -0
  51. package/lib/types/transport/http.js +158 -0
  52. package/lib/types/transport/http.js.map +1 -0
  53. package/lib/types/transport/shared.d.ts +48 -0
  54. package/lib/types/transport/shared.d.ts.map +1 -0
  55. package/lib/types/transport/shared.js +75 -0
  56. package/lib/types/transport/shared.js.map +1 -0
  57. package/lib/types/transport/ws-reverse.d.ts +42 -0
  58. package/lib/types/transport/ws-reverse.d.ts.map +1 -0
  59. package/lib/types/transport/ws-reverse.js +178 -0
  60. package/lib/types/transport/ws-reverse.js.map +1 -0
  61. package/lib/types/transport/ws.d.ts +40 -0
  62. package/lib/types/transport/ws.d.ts.map +1 -0
  63. package/lib/types/transport/ws.js +233 -0
  64. package/lib/types/transport/ws.js.map +1 -0
  65. package/lib/types/types.d.ts +495 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +191 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/package.json +68 -3
  70. package/src/bot.ts +230 -0
  71. package/src/config.ts +66 -0
  72. package/src/cqcode.ts +85 -0
  73. package/src/decode.ts +524 -0
  74. package/src/errors.ts +134 -0
  75. package/src/identity.ts +34 -0
  76. package/src/index.ts +18 -0
  77. package/src/modes/segment.ts +109 -0
  78. package/src/modes/shared.ts +277 -0
  79. package/src/request.ts +128 -0
  80. package/src/send.ts +233 -0
  81. package/src/transport/http.ts +221 -0
  82. package/src/transport/shared.ts +98 -0
  83. package/src/transport/ws-reverse.ts +236 -0
  84. package/src/transport/ws.ts +286 -0
  85. package/src/types.ts +743 -0
  86. package/README.md +0 -3
package/lib/index.js ADDED
@@ -0,0 +1,2003 @@
1
+ import { Adapter, ElementRegistry, PlatformError, Status, h, normalize } from "@deepseek-ai/cordis-plugin-im-core";
2
+ import { fileURLToPath } from "node:url";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { camelize } from "@deepseek-ai/cosmokit";
5
+ import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
6
+ import { WebSocketServer } from "ws";
7
+ // lib/types/config.js
8
+ /** Validated OneBot 11 adapter configuration. */
9
+ const Config = z.object({
10
+ selfId: z.string().required(),
11
+ token: z.string().role("secret").default(""),
12
+ secret: z.string().role("secret").default(""),
13
+ protocol: z.union([
14
+ "http",
15
+ "ws",
16
+ "ws-reverse"
17
+ ]).default("ws-reverse"),
18
+ endpoint: z.string().role("url").default(""),
19
+ path: z.string().default("/onebot"),
20
+ ws: z.object({
21
+ retryTimes: z.natural().default(6),
22
+ retryInterval: z.natural().role("ms").default(5e3),
23
+ retryLazy: z.natural().role("ms").default(6e4),
24
+ responseTimeout: z.natural().role("ms").default(6e4)
25
+ }).default({}),
26
+ advanced: z.object({ splitMixedContent: z.boolean().default(true) }).default({})
27
+ });
28
+ /**
29
+ * Normalize an inbound route path: absolute, no trailing slash.
30
+ * @param path - the configured `path`.
31
+ * @returns the pathname to register.
32
+ */
33
+ function routePath(path) {
34
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
35
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
36
+ }
37
+ // lib/types/types.js
38
+ var SafetyLevel;
39
+ (function(SafetyLevel) {
40
+ SafetyLevel[SafetyLevel["safe"] = 0] = "safe";
41
+ SafetyLevel[SafetyLevel["unknown"] = 1] = "unknown";
42
+ SafetyLevel[SafetyLevel["danger"] = 2] = "danger";
43
+ })(SafetyLevel || (SafetyLevel = {}));
44
+ var TimeoutError = class extends Error {
45
+ constructor(args, url) {
46
+ super(`Timeout with request ${url}, args: ${JSON.stringify(args)}`);
47
+ Object.defineProperties(this, {
48
+ args: { value: args },
49
+ url: { value: url }
50
+ });
51
+ }
52
+ };
53
+ var SenderError = class extends Error {
54
+ constructor(args, url, retcode) {
55
+ super(`Error with request ${url}, args: ${JSON.stringify(args)}, retcode: ${retcode}`);
56
+ Object.defineProperties(this, {
57
+ code: { value: retcode },
58
+ args: { value: args },
59
+ url: { value: url }
60
+ });
61
+ }
62
+ };
63
+ var Internal = class Internal {
64
+ bot;
65
+ constructor(bot) {
66
+ this.bot = bot;
67
+ }
68
+ async _get(action, params = {}) {
69
+ this.bot.ctx.logger.debug("[request] %s %o", action, params);
70
+ const response = await this._request(action, params);
71
+ this.bot.ctx.logger.debug("[response] %o", response);
72
+ const { data, retcode } = response;
73
+ if (retcode === 0) return data;
74
+ throw new SenderError(params, action, retcode);
75
+ }
76
+ async setGroupAnonymousBan(group_id, meta, duration) {
77
+ const args = {
78
+ group_id,
79
+ duration
80
+ };
81
+ args[typeof meta === "string" ? "flag" : "anonymous"] = meta;
82
+ await this._get("set_group_anonymous_ban", args);
83
+ }
84
+ async setGroupAnonymousBanAsync(group_id, meta, duration) {
85
+ const args = {
86
+ group_id,
87
+ duration
88
+ };
89
+ args[typeof meta === "string" ? "flag" : "anonymous"] = meta;
90
+ await this._get("set_group_anonymous_ban_async", args);
91
+ }
92
+ static asyncPrefixes = [
93
+ "set",
94
+ "send",
95
+ "delete",
96
+ "create",
97
+ "upload",
98
+ "move",
99
+ "rename"
100
+ ];
101
+ static prepareMethod(name) {
102
+ const prop = camelize(name.replace(/^[_.]/, ""));
103
+ return [prop, Internal.asyncPrefixes.some((prefix) => prop.startsWith(prefix))];
104
+ }
105
+ static prepareArg(name, params, args) {
106
+ const fixedArg = Object.fromEntries(params.map((name, index) => [name, args[index]]));
107
+ for (const key in fixedArg) if (!name.includes("guild") && key.endsWith("_id")) {
108
+ const value = +fixedArg[key];
109
+ if (Math.abs(value) < 4294967296) fixedArg[key] = value;
110
+ }
111
+ return fixedArg;
112
+ }
113
+ static define(name, ...params) {
114
+ const [prop, isAsync] = Internal.prepareMethod(name);
115
+ Internal.prototype[prop] = async function(...args) {
116
+ const data = await this._get(name, Internal.prepareArg(name, params, args));
117
+ if (!isAsync) return data;
118
+ };
119
+ isAsync && (Internal.prototype[prop + "Async"] = async function(...args) {
120
+ await this._get(name + "_async", Internal.prepareArg(name, params, args));
121
+ });
122
+ }
123
+ static defineExtract(name, key, ...params) {
124
+ const [prop, isAsync] = Internal.prepareMethod(name);
125
+ Internal.prototype[prop] = async function(...args) {
126
+ return (await this._get(name, Internal.prepareArg(name, params, args)))[key];
127
+ };
128
+ isAsync && (Internal.prototype[prop + "Async"] = async function(...args) {
129
+ await this._get(name + "_async", Internal.prepareArg(name, params, args));
130
+ });
131
+ }
132
+ };
133
+ Internal.defineExtract("send_msg", "message_id", "user_id", "group_id", "message", "auto_escape");
134
+ Internal.defineExtract("send_private_msg", "message_id", "user_id", "message", "auto_escape");
135
+ Internal.defineExtract("send_group_msg", "message_id", "group_id", "message", "auto_escape");
136
+ Internal.defineExtract("send_group_forward_msg", "message_id", "group_id", "messages");
137
+ Internal.defineExtract("send_private_forward_msg", "message_id", "user_id", "messages");
138
+ Internal.define("delete_msg", "message_id");
139
+ Internal.define("mark_msg_as_read", "message_id");
140
+ Internal.define("set_essence_msg", "message_id");
141
+ Internal.define("delete_essence_msg", "message_id");
142
+ Internal.define("send_group_sign", "group_id");
143
+ Internal.define("send_like", "user_id", "times");
144
+ Internal.define("get_msg", "message_id");
145
+ Internal.define("get_essence_msg_list", "group_id");
146
+ Internal.define("ocr_image", "image");
147
+ Internal.defineExtract("get_forward_msg", "messages", "message_id");
148
+ Internal.defineExtract(".get_word_slices", "slices", "content");
149
+ Internal.define("get_group_msg_history", "group_id", "message_seq");
150
+ Internal.defineExtract("get_friend_msg_history", "messages", "user_id", "message_seq", "count", "reverseOrder");
151
+ Internal.define("set_friend_add_request", "flag", "approve", "remark");
152
+ Internal.define("set_group_add_request", "flag", "sub_type", "approve", "reason");
153
+ Internal.defineExtract("_get_model_show", "variants", "model");
154
+ Internal.define("_set_model_show", "model", "model_show");
155
+ Internal.define("set_group_kick", "group_id", "user_id", "reject_add_request");
156
+ Internal.define("set_group_ban", "group_id", "user_id", "duration");
157
+ Internal.define("set_group_whole_ban", "group_id", "enable");
158
+ Internal.define("set_group_admin", "group_id", "user_id", "enable");
159
+ Internal.define("set_group_anonymous", "group_id", "enable");
160
+ Internal.define("set_group_card", "group_id", "user_id", "card");
161
+ Internal.define("set_group_leave", "group_id", "is_dismiss");
162
+ Internal.define("set_group_special_title", "group_id", "user_id", "special_title", "duration");
163
+ Internal.define("set_group_name", "group_id", "group_name");
164
+ Internal.define("set_group_portrait", "group_id", "file", "cache");
165
+ Internal.define("_send_group_notice", "group_id", "content", "image", "pinned", "confirm_required");
166
+ Internal.define("_get_group_notice", "group_id");
167
+ Internal.define("_del_group_notice", "group_id", "notice_id");
168
+ Internal.define("get_group_at_all_remain", "group_id");
169
+ Internal.define("get_login_info");
170
+ Internal.define("qidian_get_login_info");
171
+ Internal.define("set_qq_profile", "nickname", "company", "email", "college", "personal_note");
172
+ Internal.define("set_qq_avatar", "file");
173
+ Internal.define("set_online_status", "status", "ext_status", "battery_status");
174
+ Internal.define("get_stranger_info", "user_id", "no_cache");
175
+ Internal.define("_get_vip_info", "user_id");
176
+ Internal.define("get_friend_list");
177
+ Internal.define("get_unidirectional_friend_list");
178
+ Internal.define("delete_friend", "user_id");
179
+ Internal.define("delete_unidirectional_friend", "user_id");
180
+ Internal.define("get_group_info", "group_id", "no_cache");
181
+ Internal.define("get_group_list", "no_cache");
182
+ Internal.define("get_group_member_info", "group_id", "user_id", "no_cache");
183
+ Internal.define("get_group_member_list", "group_id");
184
+ Internal.define("get_group_honor_info", "group_id", "type");
185
+ Internal.define("get_group_system_msg");
186
+ Internal.define("get_group_file_system_info", "group_id");
187
+ Internal.define("get_group_root_files", "group_id");
188
+ Internal.define("get_group_files_by_folder", "group_id", "folder_id");
189
+ Internal.define("upload_private_file", "user_id", "file", "name");
190
+ Internal.define("upload_group_file", "group_id", "file", "name", "folder");
191
+ Internal.define("create_group_file_folder", "group_id", "folder_id", "name");
192
+ Internal.define("delete_group_folder", "group_id", "folder_id");
193
+ Internal.define("delete_group_file", "group_id", "folder_id", "file_id", "busid");
194
+ Internal.defineExtract("get_group_file_url", "url", "group_id", "file_id", "busid");
195
+ Internal.defineExtract("download_file", "file", "url", "headers", "thread_count");
196
+ Internal.defineExtract("get_online_clients", "clients", "no_cache");
197
+ Internal.defineExtract("check_url_safely", "level", "url");
198
+ Internal.define("get_group_signed_list", "group_id");
199
+ Internal.defineExtract("get_cookies", "cookies", "domain");
200
+ Internal.defineExtract("get_csrf_token", "token");
201
+ Internal.define("get_credentials", "domain");
202
+ Internal.define("get_record", "file", "out_format", "full_path");
203
+ Internal.define("get_image", "file");
204
+ Internal.defineExtract("can_send_image", "yes");
205
+ Internal.defineExtract("can_send_record", "yes");
206
+ Internal.define("get_status");
207
+ Internal.define("get_version_info");
208
+ Internal.define("set_restart", "delay");
209
+ Internal.define("reload_event_filter");
210
+ Internal.define("clean_cache");
211
+ Internal.define("get_guild_service_profile");
212
+ Internal.define("get_guild_list");
213
+ Internal.define("get_guild_meta_by_guest", "guild_id");
214
+ Internal.define("get_guild_channel_list", "guild_id", "no_cache");
215
+ Internal.define("get_guild_member_list", "guild_id", "next_token");
216
+ Internal.define("get_guild_member_profile", "guild_id", "user_id");
217
+ Internal.defineExtract("send_guild_channel_msg", "message_id", "guild_id", "channel_id", "message");
218
+ Internal.define("upload_image", "file");
219
+ Internal.defineExtract("get_private_file_url", "url", "user_id", "file_id", "file_hash");
220
+ Internal.define("move_group_file", "group_id", "file_id", "parent_directory", "target_directory");
221
+ Internal.define("delete_group_file_folder", "group_id", "folder_id");
222
+ Internal.define("rename_group_file_folder", "group_id", "folder_id", "new_folder_name");
223
+ Internal.define("set_msg_emoji_like", "message_id", "emoji_id", "set");
224
+ // lib/types/errors.js
225
+ /**
226
+ * A failed `protocol: 'http'` API call: the status the implementation answered with, or `0` when the request never
227
+ * produced a response.
228
+ */
229
+ var OneBotHttpError = class extends Error {
230
+ status;
231
+ constructor(message, status, options = {}) {
232
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
233
+ this.status = status;
234
+ this.name = "OneBotHttpError";
235
+ }
236
+ };
237
+ /** Whether a caught value is the abort error of a cancelled request. */
238
+ function isAbortError(error) {
239
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
240
+ }
241
+ /**
242
+ * The `retcode` a failed action carries.
243
+ *
244
+ * The upstream `SenderError` attaches `code` with `Object.defineProperties` and is not exported, so the classifier
245
+ * reads the field structurally. A transport failure carries a string `code` (`ECONNREFUSED`, …) and is not one.
246
+ *
247
+ * @param error - the caught failure.
248
+ * @returns the numeric `retcode`, or undefined when the failure is not an action refusal.
249
+ */
250
+ function senderCodeOf(error) {
251
+ if (typeof error !== "object" || error === null) return void 0;
252
+ const code = error.code;
253
+ return typeof code === "number" ? code : void 0;
254
+ }
255
+ /**
256
+ * Map any OneBot failure onto the core platform taxonomy.
257
+ *
258
+ * A refusal the implementation answered with is certainly unpublished; transport failures, timeouts and the
259
+ * `status: 'async'` acknowledgement leave the outcome unknown.
260
+ *
261
+ * @param error - the caught failure.
262
+ * @returns the classified platform error.
263
+ */
264
+ function classifyOneBotError(error) {
265
+ if (error instanceof PlatformError) return error;
266
+ if (isAbortError(error)) return new PlatformError("fatal", error instanceof Error ? error.message : "onebot request aborted", {
267
+ published: "unknown",
268
+ cause: error
269
+ });
270
+ const retcode = senderCodeOf(error);
271
+ if (retcode !== void 0) {
272
+ const message = error instanceof Error ? error.message : String(error);
273
+ const init = {
274
+ code: retcode,
275
+ cause: error
276
+ };
277
+ if (retcode === 1) return new PlatformError("retryable", message, {
278
+ ...init,
279
+ published: "unknown"
280
+ });
281
+ if (retcode === 1401 || retcode === 1403) return new PlatformError("permission", message, {
282
+ ...init,
283
+ published: "no"
284
+ });
285
+ if (retcode === 1404) return new PlatformError("not-found", message, {
286
+ ...init,
287
+ published: "no"
288
+ });
289
+ if (retcode === 1400) return new PlatformError("invalid", message, {
290
+ ...init,
291
+ published: "no"
292
+ });
293
+ return new PlatformError("retryable", message, {
294
+ ...init,
295
+ published: "unknown"
296
+ });
297
+ }
298
+ if (error instanceof OneBotHttpError) {
299
+ const init = { cause: error };
300
+ if (error.status === 401 || error.status === 403) return new PlatformError("permission", error.message, {
301
+ ...init,
302
+ published: "no"
303
+ });
304
+ if (error.status === 404) return new PlatformError("not-found", error.message, {
305
+ ...init,
306
+ published: "no"
307
+ });
308
+ if (error.status >= 500) return new PlatformError("retryable", error.message, {
309
+ ...init,
310
+ published: "unknown"
311
+ });
312
+ if (error.status >= 400) return new PlatformError("invalid", error.message, {
313
+ ...init,
314
+ published: "no"
315
+ });
316
+ return new PlatformError("retryable", error.message, {
317
+ ...init,
318
+ published: "unknown"
319
+ });
320
+ }
321
+ if (error instanceof TimeoutError) return new PlatformError("retryable", error.message, {
322
+ published: "unknown",
323
+ cause: error
324
+ });
325
+ const message = error instanceof Error ? error.message : String(error);
326
+ return new PlatformError("retryable", `onebot request failed: ${message}`, {
327
+ published: "unknown",
328
+ cause: error
329
+ });
330
+ }
331
+ // lib/types/modes/shared.js
332
+ /** Group chat id prefix; the private prefix is the upstream one. */
333
+ const GROUP_PREFIX = "group:";
334
+ /** Private chat id prefix, unchanged from the upstream adapter. */
335
+ const PRIVATE_PREFIX = "private:";
336
+ /** A text segment node. */
337
+ function textNode(text) {
338
+ return {
339
+ kind: "segment",
340
+ segment: {
341
+ type: "text",
342
+ data: { text }
343
+ }
344
+ };
345
+ }
346
+ /** The accumulated text of a draft's last item, when it is a text segment. */
347
+ function trailingText(items) {
348
+ const last = items[items.length - 1];
349
+ if (last === void 0 || last.kind !== "segment") return void 0;
350
+ return last.segment.type === "text" ? last.segment : void 0;
351
+ }
352
+ /** Drop the whitespace-only ends of a draft and the blank text segments around them. */
353
+ function trimItems(input) {
354
+ const items = [...input];
355
+ const textAt = (index) => {
356
+ const item = items[index];
357
+ if (item === void 0 || item.kind !== "segment") return void 0;
358
+ return item.segment.type === "text" ? item.segment : void 0;
359
+ };
360
+ while (items.length > 0) {
361
+ const first = textAt(0);
362
+ if (first === void 0) break;
363
+ const text = String(first.data.text).trimStart();
364
+ if (text !== "") {
365
+ first.data.text = text;
366
+ break;
367
+ }
368
+ items.shift();
369
+ }
370
+ while (items.length > 0) {
371
+ const last = textAt(items.length - 1);
372
+ if (last === void 0) break;
373
+ const text = String(last.data.text).trimEnd();
374
+ if (text !== "") {
375
+ last.data.text = text;
376
+ break;
377
+ }
378
+ items.pop();
379
+ }
380
+ return items.length > 0 ? items : void 0;
381
+ }
382
+ /**
383
+ * Fold the rendered node stream into platform messages.
384
+ *
385
+ * Consecutive inline nodes share one message segment array; `audio` / `video` / `file` start a new message first, as
386
+ * the upstream encoder flushes before them. Paragraph breaks collapse into one newline so `<p>a</p><p>b</p>` becomes
387
+ * `a\nb`. With `splitMixedContent` a space is kept between text and an image, in both directions. The ends of every
388
+ * message are trimmed and an all-whitespace message is dropped.
389
+ *
390
+ * @param nodes - rendered nodes in document order.
391
+ * @param splitMixedContent - the `advanced.splitMixedContent` setting.
392
+ * @returns one draft per platform message; empty when the content renders nothing.
393
+ */
394
+ function assembleDraft(nodes, splitMixedContent) {
395
+ const drafts = [];
396
+ let items = [];
397
+ let pendingSpace = false;
398
+ const flush = () => {
399
+ const trimmed = trimItems(items);
400
+ if (trimmed !== void 0) drafts.push({
401
+ kind: "message",
402
+ items: trimmed
403
+ });
404
+ items = [];
405
+ pendingSpace = false;
406
+ };
407
+ const pushText = (source) => {
408
+ let text = source;
409
+ if (text === "") return;
410
+ if (pendingSpace) {
411
+ pendingSpace = false;
412
+ if (!/^\s/.test(text)) text = ` ${text}`;
413
+ }
414
+ const last = trailingText(items);
415
+ if (last === void 0) {
416
+ items.push({
417
+ kind: "segment",
418
+ segment: {
419
+ type: "text",
420
+ data: { text }
421
+ }
422
+ });
423
+ return;
424
+ }
425
+ last.data.text = `${String(last.data.text)}${text}`;
426
+ };
427
+ const ensureNewline = () => {
428
+ pendingSpace = false;
429
+ const last = trailingText(items);
430
+ if (last === void 0) {
431
+ items.push({
432
+ kind: "segment",
433
+ segment: {
434
+ type: "text",
435
+ data: { text: "\n" }
436
+ }
437
+ });
438
+ return;
439
+ }
440
+ const text = String(last.data.text);
441
+ if (!text.endsWith("\n")) last.data.text = `${text}\n`;
442
+ };
443
+ const pushMedia = (type, ref) => {
444
+ if (splitMixedContent) {
445
+ const last = trailingText(items);
446
+ if (last !== void 0 && !/\s$/.test(String(last.data.text))) last.data.text = `${String(last.data.text)} `;
447
+ pendingSpace = true;
448
+ }
449
+ items.push({
450
+ kind: "media",
451
+ type,
452
+ ref
453
+ });
454
+ };
455
+ for (const node of nodes) switch (node.kind) {
456
+ case "newline":
457
+ ensureNewline();
458
+ break;
459
+ case "segment":
460
+ if (node.segment.type === "text") pushText(String(node.segment.data.text ?? ""));
461
+ else items.push({
462
+ kind: "segment",
463
+ segment: node.segment
464
+ });
465
+ break;
466
+ case "media":
467
+ if (node.type !== "image") flush();
468
+ pushMedia(node.type, node.ref);
469
+ break;
470
+ case "file":
471
+ flush();
472
+ drafts.push({
473
+ kind: "file",
474
+ ref: node.ref,
475
+ name: node.name
476
+ });
477
+ }
478
+ flush();
479
+ return drafts;
480
+ }
481
+ /** The platform key `prepare` resolved for one placeholder. */
482
+ function resolvedKey(prepared, ref) {
483
+ const resolved = prepared.resolved.get(ref);
484
+ if (resolved === void 0) throw new Error("onebot: the resource was not prepared before serialize");
485
+ return resolved.key;
486
+ }
487
+ /**
488
+ * Build the exact request data of one draft.
489
+ *
490
+ * Nothing is escaped: the array message format carries every field value literally. Only the first part answers the
491
+ * quoted message, because a split message would otherwise repeat the quote on every part.
492
+ *
493
+ * @param prepared - the draft with its resources resolved.
494
+ * @param ctx - serialize context (target chat, part index, quote).
495
+ * @returns the request data of one platform message or file upload.
496
+ */
497
+ function serializeDraft(prepared, ctx) {
498
+ const { draft } = prepared;
499
+ const chat = ctx.target.chat;
500
+ if (draft.kind === "file") return {
501
+ kind: "file",
502
+ chat,
503
+ key: resolvedKey(prepared, draft.ref),
504
+ name: draft.name
505
+ };
506
+ const replyTo = ctx.index === 0 && ctx.quote !== void 0 ? ctx.quote : void 0;
507
+ const segments = replyTo === void 0 ? [] : [{
508
+ type: "reply",
509
+ data: { id: replyTo }
510
+ }];
511
+ for (const item of draft.items) if (item.kind === "segment") segments.push(item.segment);
512
+ else segments.push({
513
+ type: item.type,
514
+ data: {
515
+ file: resolvedKey(prepared, item.ref),
516
+ cache: 0
517
+ }
518
+ });
519
+ return {
520
+ kind: "message",
521
+ chat,
522
+ segments,
523
+ ...replyTo === void 0 ? {} : { replyTo }
524
+ };
525
+ }
526
+ /**
527
+ * The file name of an outbound `<file>` element.
528
+ * @param name - the element's `name` attribute, when set.
529
+ * @param src - the element's source.
530
+ * @returns the declared name, else the last path segment of the source, else `file`.
531
+ */
532
+ function fileName(name, src) {
533
+ if (name !== void 0 && name !== "") return name;
534
+ try {
535
+ const path = new URL(src).pathname;
536
+ const segment = path.slice(path.lastIndexOf("/") + 1);
537
+ if (segment !== "") return decodeURIComponent(segment);
538
+ } catch {
539
+ if (src !== "" && !src.includes("/")) return src;
540
+ }
541
+ return "file";
542
+ }
543
+ // lib/types/modes/segment.js
544
+ /**
545
+ * `segment` mode: the OneBot 11 array message format.
546
+ *
547
+ * Native tags are the ones the upstream encoder produces (`text`, `p`, `br`, `at`, `emoji`, `channel`, `a`, `img`,
548
+ * `audio`, `video`, `file`); everything else takes the core fallback, which keeps its text. There is no second mode:
549
+ * the platform has no other way to render a message.
550
+ */
551
+ /**
552
+ * Build the `segment` mode.
553
+ * @param splitMixedContent - pad a space around mixed text and images (`advanced.splitMixedContent`).
554
+ * @returns the only mode of this adapter.
555
+ */
556
+ function createSegmentMode(splitMixedContent) {
557
+ return {
558
+ id: "segment",
559
+ elements: new ElementRegistry().register("text", (el) => textNode(el.attrs.content)).register("p", (el, ctx) => [
560
+ { kind: "newline" },
561
+ ...ctx.render(el.children),
562
+ { kind: "newline" }
563
+ ]).register("br", () => ({ kind: "newline" })).register("at", (el) => el.attrs.type === "all" ? {
564
+ kind: "segment",
565
+ segment: {
566
+ type: "at",
567
+ data: { qq: "all" }
568
+ }
569
+ } : {
570
+ kind: "segment",
571
+ segment: {
572
+ type: "at",
573
+ data: {
574
+ qq: el.attrs.id ?? "",
575
+ ...el.attrs.name === void 0 ? {} : { name: el.attrs.name }
576
+ }
577
+ }
578
+ }, { variants: ["user", "all"] }).register("emoji", (el) => /^\d+$/.test(el.attrs.id) ? {
579
+ kind: "segment",
580
+ segment: {
581
+ type: "face",
582
+ data: { id: el.attrs.id }
583
+ }
584
+ } : textNode(el.attrs.name ?? "")).register("channel", (el) => textNode(el.attrs.id)).register("a", (el, ctx) => [...ctx.render(el.children), textNode(`(${el.attrs.href})`)]).register("img", (el, ctx) => ({
585
+ kind: "media",
586
+ type: "image",
587
+ ref: ctx.resource("image", el.attrs.src, {})
588
+ }), { variants: ["inline"] }).register("audio", (el, ctx) => ({
589
+ kind: "media",
590
+ type: "record",
591
+ ref: ctx.resource("audio", el.attrs.src, {})
592
+ })).register("video", (el, ctx) => ({
593
+ kind: "media",
594
+ type: "video",
595
+ ref: ctx.resource("video", el.attrs.src, {})
596
+ })).register("file", (el, ctx) => ({
597
+ kind: "file",
598
+ name: fileName(el.attrs.name, el.attrs.src),
599
+ ref: ctx.resource("file", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name })
600
+ })),
601
+ limits: {},
602
+ assemble: (nodes) => assembleDraft(nodes, splitMixedContent),
603
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx)
604
+ };
605
+ }
606
+ // lib/types/cqcode.js
607
+ /** Segment types are `\w+` in CQ code; anything else is literal text. */
608
+ const TYPE = /^[A-Za-z0-9_.-]+$/;
609
+ /**
610
+ * Undo the CQ code escapes of text outside segments and of one parameter value.
611
+ * @param source - escaped text.
612
+ * @returns the text with `&#91;`, `&#93;`, `&#44;` and `&amp;` restored.
613
+ */
614
+ function unescapeCQ(source) {
615
+ return source.replaceAll("&#91;", "[").replaceAll("&#93;", "]").replaceAll("&#44;", ",").replaceAll("&amp;", "&");
616
+ }
617
+ /** Parse the parameter list after `[CQ:type`; a value may itself contain `=`. */
618
+ function parseParams(body) {
619
+ const data = {};
620
+ if (body === "") return data;
621
+ for (const pair of body.split(",")) {
622
+ const equals = pair.indexOf("=");
623
+ if (equals <= 0) continue;
624
+ data[pair.slice(0, equals)] = unescapeCQ(pair.slice(equals + 1));
625
+ }
626
+ return data;
627
+ }
628
+ /**
629
+ * Parse a string-format (CQ code) message into segments.
630
+ *
631
+ * Text outside segments becomes a `text` segment with its escapes undone. A `[CQ:` that does not open a well-formed
632
+ * segment stays literal text. Only the first `]` closes a segment: `]` inside a value is escaped as `&#93;`.
633
+ *
634
+ * @param source - the raw `message` string (or `raw_message`).
635
+ * @returns the segments in order; empty for an empty input.
636
+ */
637
+ function parseCqCode(source) {
638
+ const segments = [];
639
+ let cursor = 0;
640
+ let search = 0;
641
+ const flushText = (end) => {
642
+ if (end <= cursor) return;
643
+ const text = unescapeCQ(source.slice(cursor, end));
644
+ if (text !== "") segments.push({
645
+ type: "text",
646
+ data: { text }
647
+ });
648
+ };
649
+ while (search < source.length) {
650
+ const start = source.indexOf("[CQ:", search);
651
+ if (start < 0) break;
652
+ const end = source.indexOf("]", start + 4);
653
+ if (end < 0) break;
654
+ const body = source.slice(start + 4, end);
655
+ const comma = body.indexOf(",");
656
+ const type = comma < 0 ? body : body.slice(0, comma);
657
+ if (!TYPE.test(type)) {
658
+ search = start + 4;
659
+ continue;
660
+ }
661
+ flushText(start);
662
+ segments.push({
663
+ type,
664
+ data: parseParams(comma < 0 ? "" : body.slice(comma + 1))
665
+ });
666
+ cursor = end + 1;
667
+ search = cursor;
668
+ }
669
+ flushText(source.length);
670
+ return segments;
671
+ }
672
+ // lib/types/decode.js
673
+ /**
674
+ * Inbound decoding: one OneBot 11 event becomes an intake `Session`.
675
+ *
676
+ * Message events and the two recall notices are decoded; every other `post_type` is ignored. Segment content keeps
677
+ * its text: a segment the vocabulary cannot express becomes a readable placeholder instead of disappearing, and an
678
+ * event that carries no segment at all becomes an inbound `<raw>` element, because `InboundMessage.content` may not
679
+ * be empty.
680
+ */
681
+ /** Text of a segment that has no element of its own. */
682
+ function placeholderOf(type, data) {
683
+ switch (type) {
684
+ case "poke": return "[戳一戳]";
685
+ case "rps": return "[猜拳]";
686
+ case "dice": return "[骰子]";
687
+ case "shake": return "[抖动]";
688
+ case "anonymous": return "[匿名消息]";
689
+ case "contact": return "[名片]";
690
+ case "music": return "[音乐]";
691
+ case "tts": return "[语音]";
692
+ case "mface": return "[表情]";
693
+ case "markdown": return "[Markdown]";
694
+ case "keyboard": return "[按钮]";
695
+ case "node": return "[合并转发节点]";
696
+ case "location": return `[位置 ${data.lat ?? "?"},${data.lon ?? "?"}]`;
697
+ default: return;
698
+ }
699
+ }
700
+ /** The title of a JSON/XML card, when it carries one; the card body itself is not printed. */
701
+ function cardTitle(source) {
702
+ let parsed;
703
+ try {
704
+ parsed = JSON.parse(source);
705
+ } catch (error) {
706
+ return;
707
+ }
708
+ if (typeof parsed !== "object" || parsed === null) return void 0;
709
+ const meta = parsed.meta;
710
+ if (typeof meta === "object" && meta !== null) {
711
+ const detail = meta.detail_1;
712
+ if (typeof detail === "object" && detail !== null) {
713
+ const title = detail.title;
714
+ if (typeof title === "string" && title !== "") return title;
715
+ }
716
+ }
717
+ const prompt = parsed.prompt;
718
+ if (typeof prompt === "string" && prompt !== "") return prompt;
719
+ }
720
+ /**
721
+ * Validate one wire segment list.
722
+ *
723
+ * The array message format is JSON from another process, so every field is checked: a segment without a string `type`
724
+ * is dropped, and parameter values are kept only when they are strings or numbers.
725
+ *
726
+ * @param value - a `message` field or a forwarded node's `content`.
727
+ * @returns the segments that can be decoded.
728
+ */
729
+ function normalizeSegments(value) {
730
+ if (typeof value === "string") return parseCqCode(value);
731
+ if (!Array.isArray(value)) return [];
732
+ const segments = [];
733
+ for (const item of value) {
734
+ if (typeof item !== "object" || item === null) continue;
735
+ const type = item.type;
736
+ if (typeof type !== "string" || type === "") continue;
737
+ const source = item.data;
738
+ const data = {};
739
+ if (typeof source === "object" && source !== null) {
740
+ for (const [key, entry] of Object.entries(source)) if (typeof entry === "string") data[key] = entry;
741
+ else if (typeof entry === "number") data[key] = String(entry);
742
+ }
743
+ segments.push({
744
+ type,
745
+ data
746
+ });
747
+ }
748
+ return segments;
749
+ }
750
+ /** The segments of one message: the `message` field by value, else the CQ string in `raw_message`. */
751
+ function segmentsOf(data) {
752
+ if (data.message !== void 0 && data.message !== null) {
753
+ const segments = normalizeSegments(data.message);
754
+ if (segments.length > 0) return segments;
755
+ }
756
+ return typeof data.raw_message === "string" ? parseCqCode(data.raw_message) : [];
757
+ }
758
+ /**
759
+ * Decode one message's segments into the element vocabulary.
760
+ *
761
+ * @param bot - the receiving adapter (its `selfId` decides `mentions.self`).
762
+ * @param segments - validated segments.
763
+ * @returns the content nodes, the quoted message id and the mentions.
764
+ */
765
+ function decodeSegments(bot, segments) {
766
+ const nodes = [];
767
+ const mentions = {
768
+ self: false,
769
+ all: false,
770
+ users: []
771
+ };
772
+ let quote;
773
+ for (const segment of segments) {
774
+ const data = segment.data;
775
+ switch (segment.type) {
776
+ case "text":
777
+ nodes.push(h.text(data.text ?? ""));
778
+ break;
779
+ case "face":
780
+ nodes.push(h("emoji", {
781
+ id: data.id ?? "",
782
+ ...data.name === void 0 ? {} : { name: data.name }
783
+ }));
784
+ break;
785
+ case "image":
786
+ nodes.push(h("img", { src: data.url || data.file || "" }));
787
+ if (data.type === "flash") nodes.push(h.text("[闪照]"));
788
+ break;
789
+ case "record":
790
+ nodes.push(h("audio", { src: data.url || data.file || "" }));
791
+ break;
792
+ case "video":
793
+ nodes.push(h("video", { src: data.url || data.file || "" }));
794
+ break;
795
+ case "file":
796
+ nodes.push(h("file", {
797
+ src: data.url || data.file || "",
798
+ ...data.name === void 0 ? {} : { name: data.name }
799
+ }));
800
+ break;
801
+ case "at": {
802
+ const qq = data.qq ?? "";
803
+ if (qq === "all") {
804
+ mentions.all = true;
805
+ nodes.push(h("at", { type: "all" }));
806
+ break;
807
+ }
808
+ mentions.users.push({
809
+ id: qq,
810
+ ...data.name === void 0 ? {} : { name: data.name }
811
+ });
812
+ if (qq === bot.selfId) mentions.self = true;
813
+ nodes.push(h("at", {
814
+ type: "user",
815
+ id: qq,
816
+ ...data.name === void 0 ? {} : { name: data.name }
817
+ }));
818
+ break;
819
+ }
820
+ case "reply":
821
+ quote = data.id ?? "";
822
+ break;
823
+ case "forward":
824
+ nodes.push(h("forward", { id: data.id ?? "" }));
825
+ break;
826
+ case "share":
827
+ nodes.push(h("a", { href: data.url ?? "" }, data.title ?? ""));
828
+ break;
829
+ case "json":
830
+ case "xml": {
831
+ const title = cardTitle(data.data ?? "");
832
+ nodes.push(h.text(title === void 0 ? "[卡片]" : `[卡片] ${title}`));
833
+ break;
834
+ }
835
+ default: {
836
+ const placeholder = placeholderOf(segment.type, data);
837
+ if (placeholder !== void 0) {
838
+ nodes.push(h.text(placeholder));
839
+ break;
840
+ }
841
+ const text = data.text;
842
+ nodes.push(h.text(text !== void 0 && text !== "" ? text : `[${segment.type}]`));
843
+ break;
844
+ }
845
+ }
846
+ }
847
+ return {
848
+ nodes,
849
+ quote,
850
+ mentions
851
+ };
852
+ }
853
+ /** A bounded description of an event that decoded to no content, so `<raw>` stays small. */
854
+ function rawPreview(data) {
855
+ const preview = {};
856
+ for (const key of [
857
+ "post_type",
858
+ "message_type",
859
+ "notice_type",
860
+ "sub_type",
861
+ "message_id",
862
+ "group_id",
863
+ "user_id"
864
+ ]) {
865
+ const value = data[key];
866
+ if (value !== void 0) preview[key] = String(value);
867
+ }
868
+ return preview;
869
+ }
870
+ /** The chat a message was sent in. */
871
+ function chatOfMessage(data) {
872
+ if (data.message_type === "group" || data.message_type === void 0 && data.group_id !== void 0) return {
873
+ id: `${GROUP_PREFIX}${data.group_id ?? 0}`,
874
+ type: "group"
875
+ };
876
+ const userId = data.sender?.user_id ?? data.user_id ?? data.target_id ?? 0;
877
+ return {
878
+ id: `${PRIVATE_PREFIX}${userId}`,
879
+ type: "direct"
880
+ };
881
+ }
882
+ /** The sender of one message; an anonymous group message has no usable sender, so its anonymous id stands in. */
883
+ function senderOf(data) {
884
+ if (data.anonymous !== void 0) return {
885
+ id: String(data.anonymous.id),
886
+ name: "匿名用户"
887
+ };
888
+ const sender = data.sender ?? {};
889
+ const name = sender.card || sender.nickname;
890
+ return {
891
+ id: String(sender.user_id ?? data.user_id ?? 0),
892
+ ...name === void 0 || name === "" ? {} : { name },
893
+ ...sender.role === void 0 ? {} : { role: sender.role }
894
+ };
895
+ }
896
+ /**
897
+ * Decode one message payload.
898
+ * @param bot - the receiving adapter.
899
+ * @param data - a message event, or a `get_msg` answer.
900
+ * @param chat - the chat to report; a `get_msg` answer carries no group id, so the caller passes its own.
901
+ * @returns the inbound message.
902
+ */
903
+ function decodeMessage(bot, data, chat = chatOfMessage(data)) {
904
+ const parts = decodeSegments(bot, segmentsOf(data));
905
+ const id = String(data.message_id ?? 0);
906
+ const time = (data.time ?? Math.floor(Date.now() / 1e3)) * 1e3;
907
+ const content = normalize(parts.nodes.length > 0 ? parts.nodes : [h("raw", {
908
+ platform: "onebot",
909
+ type: data.post_type ?? "message",
910
+ data: rawPreview(data)
911
+ }, h.text(""))]);
912
+ const realId = data.real_id;
913
+ return {
914
+ id,
915
+ ...realId === void 0 || String(realId) === id ? {} : { aliases: [String(realId)] },
916
+ chat,
917
+ sender: senderOf(data),
918
+ content,
919
+ ...parts.quote === void 0 ? {} : { quote: { id: parts.quote } },
920
+ mentions: parts.mentions,
921
+ time,
922
+ referrer: {
923
+ chatId: chat.id,
924
+ messageId: id,
925
+ time
926
+ },
927
+ raw: data
928
+ };
929
+ }
930
+ /** One `notice` that reports a recalled message. */
931
+ function deletedSession(bot, data) {
932
+ const chat = data.notice_type === "group_recall" ? {
933
+ id: `${GROUP_PREFIX}${data.group_id ?? 0}`,
934
+ type: "group"
935
+ } : {
936
+ id: `${PRIVATE_PREFIX}${data.user_id ?? data.target_id ?? 0}`,
937
+ type: "direct"
938
+ };
939
+ const time = (data.time ?? Math.floor(Date.now() / 1e3)) * 1e3;
940
+ return bot.session({
941
+ type: "message-deleted",
942
+ id: `notice:${data.notice_type}:${data.time}:${data.message_id}`,
943
+ timestamp: time,
944
+ deleted: {
945
+ id: String(data.message_id),
946
+ chat,
947
+ ...data.operator_id === void 0 ? {} : { operator: { id: String(data.operator_id) } }
948
+ },
949
+ raw: data
950
+ });
951
+ }
952
+ /**
953
+ * Decode one platform event.
954
+ *
955
+ * The event id is synthesized because OneBot events carry none, and the host dedupes on it: `message_id` alone would
956
+ * collide with the ids some implementations restart from zero.
957
+ *
958
+ * @param bot - the receiving adapter.
959
+ * @param data - the event payload.
960
+ * @returns the session to publish, or undefined for an ignored event.
961
+ */
962
+ function decodePayload(bot, data) {
963
+ if (data.post_type === "message") {
964
+ if (data.message_type !== "private" && data.message_type !== "group") return;
965
+ const message = decodeMessage(bot, data);
966
+ return bot.session({
967
+ type: "message",
968
+ id: `message:${data.message_id}:${data.time}`,
969
+ timestamp: message.time,
970
+ message,
971
+ raw: data
972
+ });
973
+ }
974
+ if (data.post_type === "notice") {
975
+ if (data.notice_type === "group_recall" || data.notice_type === "friend_recall") return deletedSession(bot, data);
976
+ }
977
+ }
978
+ /**
979
+ * Whether a parsed frame is one platform event.
980
+ * @param value - a parsed JSON frame from the implementation.
981
+ * @returns whether it is an event rather than an action answer.
982
+ */
983
+ function isPayload(value) {
984
+ if (typeof value !== "object" || value === null) return false;
985
+ return typeof value.post_type === "string";
986
+ }
987
+ /** Read the node list of a `get_forward_msg` answer; the standard calls it `message`, go-cqhttp `messages`. */
988
+ function forwardNodesOf(source) {
989
+ if (typeof source !== "object" || source === null) return [];
990
+ const record = source;
991
+ const list = Array.isArray(record.messages) ? record.messages : Array.isArray(record.message) ? record.message : [];
992
+ const nodes = [];
993
+ for (const entry of list) {
994
+ if (typeof entry !== "object" || entry === null) continue;
995
+ if (entry.type !== "node") continue;
996
+ const data = entry.data;
997
+ if (typeof data !== "object" || data === null) continue;
998
+ const fields = data;
999
+ const nickname = typeof fields.nickname === "string" ? fields.nickname : typeof fields.name === "string" ? fields.name : "";
1000
+ nodes.push({
1001
+ nickname,
1002
+ content: fields.content
1003
+ });
1004
+ }
1005
+ return nodes;
1006
+ }
1007
+ /** Collect the empty `forward` placeholders of a decoded message. */
1008
+ function collectForwards(content) {
1009
+ const found = [];
1010
+ const walk = (element) => {
1011
+ if (element.type === "forward") {
1012
+ if (element.children.length === 0) found.push(element);
1013
+ return;
1014
+ }
1015
+ for (const child of element.children) walk(child);
1016
+ };
1017
+ walk(content);
1018
+ return found;
1019
+ }
1020
+ /**
1021
+ * Expand the merged forwards of one message into phrasing content, as the host's `im_read` expects.
1022
+ *
1023
+ * One forwarded node renders as its author in bold, a colon, the node content and a line break. The content model of
1024
+ * `<forward>` is phrasing, so no block element may be inserted.
1025
+ *
1026
+ * @param bot - the adapter, used for the `get_forward_msg` call.
1027
+ * @param message - the decoded message.
1028
+ * @returns the same message with every `forward` element expanded.
1029
+ */
1030
+ async function expandForward(bot, message) {
1031
+ const forwards = collectForwards(message.content);
1032
+ if (forwards.length === 0) return message;
1033
+ const request = bot.internal._request;
1034
+ if (request === void 0) throw new PlatformError("retryable", "onebot: cannot read the forwarded message while the transport is not connected", { published: "unknown" });
1035
+ for (const element of forwards) {
1036
+ const response = await request("get_forward_msg", { message_id: element.attrs.id });
1037
+ if (response.retcode !== 0) continue;
1038
+ const children = [];
1039
+ for (const node of forwardNodesOf(response.data)) {
1040
+ children.push(h("b", {}, h.text(node.nickname)), h.text(": "));
1041
+ children.push(...decodeSegments(bot, normalizeSegments(node.content)).nodes);
1042
+ children.push(h("br"));
1043
+ }
1044
+ element.children = children;
1045
+ }
1046
+ return message;
1047
+ }
1048
+ // lib/types/send.js
1049
+ /**
1050
+ * Outbound hooks: the send pipeline's payload, deletion, member reads, message reads and reactions.
1051
+ *
1052
+ * Requests go through the migrated `Internal` surface, so the action names and parameter order are the upstream ones.
1053
+ * Images, records and videos travel as the source string itself; a `<file>` becomes `download_file` plus
1054
+ * `upload_group_file` / `upload_private_file`, because those actions accept only a path on the implementation's host.
1055
+ */
1056
+ /**
1057
+ * Split a DSH chat id into the OneBot action family and the platform id.
1058
+ * @param chat - the target chat.
1059
+ * @returns kind and raw id.
1060
+ * @throws PlatformError `invalid` for a chat id this adapter did not produce.
1061
+ */
1062
+ function chatTarget(chat) {
1063
+ if (chat.id.startsWith("group:")) return {
1064
+ kind: "group",
1065
+ id: chat.id.slice(6)
1066
+ };
1067
+ if (chat.id.startsWith("private:")) return {
1068
+ kind: "private",
1069
+ id: chat.id.slice(8)
1070
+ };
1071
+ throw new PlatformError("invalid", `onebot: chat id "${chat.id}" must start with "group:" or "private:"`);
1072
+ }
1073
+ /** Data URI prefix of an inline image; the implementation wants the `base64://` form instead. */
1074
+ const DATA_URL = /^data:([\w/.+-]+);base64,/;
1075
+ /**
1076
+ * Normalize one media source without fetching it.
1077
+ *
1078
+ * A `data:` URI becomes the `base64://` form the implementation decodes; every other source (an `http(s)` URL, a
1079
+ * `base64://` payload, a path) is passed through unchanged, because the implementation fetches it itself.
1080
+ *
1081
+ * @param src - the element's source.
1082
+ * @returns the string to put in the segment's `file` field.
1083
+ */
1084
+ function normalizeSource(src) {
1085
+ const match = DATA_URL.exec(src);
1086
+ return match === null ? src : `base64://${src.slice(match[0].length)}`;
1087
+ }
1088
+ /**
1089
+ * Send one serialized payload.
1090
+ * @param deps - the action client.
1091
+ * @param payload - the mode's request data.
1092
+ * @param target - the target chat.
1093
+ * @param ctx - part index, quote and options.
1094
+ * @returns the published part.
1095
+ */
1096
+ async function sendPayload(deps, payload, _target, _ctx) {
1097
+ if (payload.kind === "file") {
1098
+ const chat = chatTarget(payload.chat);
1099
+ if (chat.kind === "group") await deps.internal.uploadGroupFile(chat.id, payload.key, payload.name);
1100
+ else await deps.internal.uploadPrivateFile(chat.id, payload.key, payload.name);
1101
+ const id = `onebot-file:${randomUUID()}`;
1102
+ return {
1103
+ id,
1104
+ kind: "file",
1105
+ time: Date.now(),
1106
+ referrer: {
1107
+ chatId: payload.chat.id,
1108
+ messageId: id
1109
+ }
1110
+ };
1111
+ }
1112
+ const chat = chatTarget(payload.chat);
1113
+ const segments = payload.segments;
1114
+ const messageId = chat.kind === "group" ? await deps.internal.sendGroupMsg(chat.id, segments) : await deps.internal.sendPrivateMsg(chat.id, segments);
1115
+ if (messageId === void 0) throw new PlatformError("invalid", "onebot: the implementation answered a send without message_id", { published: "unknown" });
1116
+ const id = String(messageId);
1117
+ return {
1118
+ id,
1119
+ kind: "message",
1120
+ time: Date.now(),
1121
+ referrer: {
1122
+ chatId: payload.chat.id,
1123
+ messageId: id
1124
+ }
1125
+ };
1126
+ }
1127
+ /**
1128
+ * Recall one published part.
1129
+ *
1130
+ * A file part carries a synthesized id that no platform message answers, so it is skipped instead of recalling an
1131
+ * unrelated message.
1132
+ *
1133
+ * @param deps - the action client.
1134
+ * @param part - the part to recall.
1135
+ */
1136
+ async function deletePart(deps, part) {
1137
+ if (part.kind === "file") return;
1138
+ await deps.internal.deleteMsg(part.id);
1139
+ }
1140
+ /**
1141
+ * List the members of one group.
1142
+ * @param deps - the action client.
1143
+ * @param chat - the group chat.
1144
+ * @returns the whole member list; the standard offers no paging.
1145
+ */
1146
+ async function members(deps, chat) {
1147
+ const target = chatTarget(chat);
1148
+ if (target.kind !== "group") throw new PlatformError("invalid", "onebot: members() is only available in a group chat");
1149
+ return { data: (await deps.internal.getGroupMemberList(target.id)).map((member) => {
1150
+ const name = member.card || member.nickname;
1151
+ return {
1152
+ id: String(member.user_id),
1153
+ ...name === "" ? {} : { name },
1154
+ ...member.role === void 0 ? {} : { role: member.role }
1155
+ };
1156
+ }) };
1157
+ }
1158
+ /**
1159
+ * Read one message, expanding any merged forward it carries.
1160
+ * @param deps - the action client.
1161
+ * @param bot - the adapter, needed by the forward expansion.
1162
+ * @param chat - the chat the caller asked about; the answer carries no chat, so it is reused verbatim.
1163
+ * @param id - platform message id.
1164
+ * @returns the decoded message, with the same `chat.id` the caller passed.
1165
+ */
1166
+ async function getMessage(deps, bot, chat, id) {
1167
+ return expandForward(bot, decodeMessage(bot, await deps.internal.getMsg(id), chat));
1168
+ }
1169
+ /**
1170
+ * Add one reaction to a published message.
1171
+ * @param deps - the action client.
1172
+ * @param message - the message to react to.
1173
+ * @param emoji - platform emoji id.
1174
+ */
1175
+ async function createReaction(deps, message, emoji) {
1176
+ await deps.internal.setMsgEmojiLike(message.id, emoji, true);
1177
+ }
1178
+ /**
1179
+ * Remove one reaction from a published message.
1180
+ * @param deps - the action client.
1181
+ * @param message - the message to react to.
1182
+ * @param emoji - platform emoji id.
1183
+ */
1184
+ async function deleteReaction(deps, message, emoji) {
1185
+ await deps.internal.setMsgEmojiLike(message.id, emoji, false);
1186
+ }
1187
+ // lib/types/request.js
1188
+ /**
1189
+ * Action calls over one WebSocket connection.
1190
+ *
1191
+ * The implementation answers an action with the envelope it was sent, in `echo`; the pending table is per connection
1192
+ * so a reconnect can never deliver an answer to the previous socket. A request that is not answered within
1193
+ * `ws.responseTimeout` is rejected with the upstream `TimeoutError` and forgotten, and closing the connection rejects
1194
+ * everything still waiting.
1195
+ */
1196
+ var ActionRequests = class {
1197
+ send;
1198
+ timeoutMs;
1199
+ echo = 0;
1200
+ pending = /* @__PURE__ */ new Map();
1201
+ closed;
1202
+ constructor(send, timeoutMs) {
1203
+ this.send = send;
1204
+ this.timeoutMs = timeoutMs;
1205
+ }
1206
+ /**
1207
+ * Send one action and wait for its answer.
1208
+ * @param action - OneBot 11 action name (`send_group_msg`, …).
1209
+ * @param params - action parameters.
1210
+ * @returns the answer envelope (the caller reads `retcode` / `data`).
1211
+ */
1212
+ request = (action, params) => {
1213
+ if (this.closed !== void 0) return Promise.reject(this.closed);
1214
+ const echo = ++this.echo;
1215
+ const frame = {
1216
+ action,
1217
+ params,
1218
+ echo
1219
+ };
1220
+ return new Promise((resolve, reject) => {
1221
+ const timer = setTimeout(() => {
1222
+ this.pending.delete(echo);
1223
+ reject(new TimeoutError(params, action));
1224
+ }, this.timeoutMs);
1225
+ this.pending.set(echo, {
1226
+ resolve,
1227
+ reject,
1228
+ timer
1229
+ });
1230
+ try {
1231
+ this.send(frame);
1232
+ } catch (error) {
1233
+ this.settle(echo, error);
1234
+ }
1235
+ });
1236
+ };
1237
+ /**
1238
+ * Deliver one answer to its waiting call.
1239
+ * @param response - the parsed frame.
1240
+ * @returns whether an outstanding call was waiting for it.
1241
+ */
1242
+ resolve(response) {
1243
+ if (typeof response.echo !== "number") return false;
1244
+ const pending = this.pending.get(response.echo);
1245
+ if (pending === void 0) return false;
1246
+ this.pending.delete(response.echo);
1247
+ clearTimeout(pending.timer);
1248
+ pending.resolve(response);
1249
+ return true;
1250
+ }
1251
+ /**
1252
+ * Refuse every waiting call; calls made afterwards fail immediately.
1253
+ * @param error - the failure to reject with.
1254
+ */
1255
+ rejectAll(error) {
1256
+ this.closed = error;
1257
+ for (const [echo, pending] of this.pending) {
1258
+ this.pending.delete(echo);
1259
+ clearTimeout(pending.timer);
1260
+ pending.reject(error);
1261
+ }
1262
+ }
1263
+ settle(echo, error) {
1264
+ const pending = this.pending.get(echo);
1265
+ if (pending === void 0) return;
1266
+ this.pending.delete(echo);
1267
+ clearTimeout(pending.timer);
1268
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
1269
+ }
1270
+ };
1271
+ /**
1272
+ * Make a connection's `request` the bot's action entry point (`bot.internal._request`).
1273
+ * @param bot - the adapter instance.
1274
+ * @param request - action caller of the live connection.
1275
+ */
1276
+ function installRequest(bot, request) {
1277
+ bot.internal._request = request;
1278
+ }
1279
+ /**
1280
+ * Make every action call of the bot fail without a connection.
1281
+ * @param bot - the adapter instance.
1282
+ * @param error - the failure calls report.
1283
+ */
1284
+ function rejectRequests(bot, error) {
1285
+ bot.internal._request = () => Promise.reject(error);
1286
+ }
1287
+ /**
1288
+ * Whether a parsed frame is one action answer.
1289
+ * @param value - a parsed JSON frame from the implementation.
1290
+ * @returns whether it carries an `echo`.
1291
+ */
1292
+ function isResponse(value) {
1293
+ if (typeof value !== "object" || value === null) return false;
1294
+ return typeof value.echo === "number";
1295
+ }
1296
+ // lib/types/transport/shared.js
1297
+ /**
1298
+ * Compare a received credential with the configured one without leaking its length through early exits.
1299
+ * @param expected - the configured secret or token.
1300
+ * @param received - the presented value, when one was sent.
1301
+ * @returns whether they are equal.
1302
+ */
1303
+ function matchesSecret(expected, received) {
1304
+ if (received === void 0) return false;
1305
+ const left = Buffer.from(expected, "utf8");
1306
+ const right = Buffer.from(received, "utf8");
1307
+ if (left.length !== right.length) return false;
1308
+ return timingSafeEqual(left, right);
1309
+ }
1310
+ /**
1311
+ * One header of an inbound request, when it arrived exactly once.
1312
+ * @param request - the inbound request.
1313
+ * @param name - lower-case header name.
1314
+ * @returns the header value, or undefined when absent or repeated.
1315
+ */
1316
+ function headerOf(request, name) {
1317
+ const value = request.headers[name];
1318
+ return typeof value === "string" ? value : void 0;
1319
+ }
1320
+ /**
1321
+ * Read a request body to its end. The adapter imposes no size limit, as the upstream plugin does not.
1322
+ * @param request - the inbound request.
1323
+ * @returns the decoded body.
1324
+ */
1325
+ async function readBody(request) {
1326
+ const chunks = [];
1327
+ for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1328
+ return Buffer.concat(chunks).toString("utf8");
1329
+ }
1330
+ /**
1331
+ * Answer an inbound request with an empty response.
1332
+ * @param response - the server response.
1333
+ * @param status - HTTP status code.
1334
+ * @param headers - extra response headers.
1335
+ */
1336
+ function writeStatus(response, status, headers = {}) {
1337
+ response.writeHead(status, headers);
1338
+ response.end();
1339
+ }
1340
+ /**
1341
+ * Refuse an HTTP upgrade that the adapter does not accept, before handing the socket to a WebSocket server.
1342
+ * @param socket - the raw connection.
1343
+ * @param status - HTTP status code.
1344
+ * @param reason - reason phrase.
1345
+ */
1346
+ function rejectUpgrade(socket, status, reason) {
1347
+ socket.write(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
1348
+ socket.destroy();
1349
+ }
1350
+ /**
1351
+ * The `X-Signature` value of one event report.
1352
+ *
1353
+ * The upstream plugin signs the re-serialized parsed body rather than the raw bytes; this keeps that behaviour because
1354
+ * it is what implementations in the field have been verifying against for years.
1355
+ *
1356
+ * @param secret - the configured `secret`.
1357
+ * @param body - the parsed event payload.
1358
+ * @returns `sha1=<hex digest>`.
1359
+ */
1360
+ function signatureOf(secret, body) {
1361
+ return `sha1=${createHmac("sha1", secret).update(JSON.stringify(body)).digest("hex")}`;
1362
+ }
1363
+ // lib/types/transport/http.js
1364
+ /**
1365
+ * HTTP transport (`protocol: 'http'`): an outbound `POST {endpoint}/{action}` client and an inbound event route.
1366
+ *
1367
+ * Both directions run at once, as in the upstream plugin. The outbound call authenticates with the standard
1368
+ * `Authorization: Bearer` header; the inbound route checks `X-Signature` (HMAC-SHA1 over the re-serialized parsed body,
1369
+ * the upstream behaviour implementations in the field verify) and `X-Self-ID`, and answers `204` only after the host
1370
+ * accepted the event.
1371
+ */
1372
+ /** The HTTP service's failure carries the response it refused; recover it structurally. */
1373
+ function responseOf(cause) {
1374
+ if (typeof cause !== "object" || cause === null || !("response" in cause)) return void 0;
1375
+ const response = cause.response;
1376
+ return response instanceof Response ? response : void 0;
1377
+ }
1378
+ /** The HTTP transport of one bot. */
1379
+ var OneBotHttp = class {
1380
+ bot;
1381
+ dispose;
1382
+ warnedNoSecret = false;
1383
+ constructor(bot) {
1384
+ this.bot = bot;
1385
+ }
1386
+ /**
1387
+ * Claim the event route and install the action caller.
1388
+ */
1389
+ async start() {
1390
+ const webServer = this.bot.ctx.get("webServer");
1391
+ if (webServer === void 0) throw this.fail("onebot: protocol \"http\" needs a profile-provided webServer to receive event reports");
1392
+ const path = routePath(this.bot.config.path);
1393
+ try {
1394
+ this.dispose = webServer.register({
1395
+ kind: "exact",
1396
+ path,
1397
+ auth: "anonymous",
1398
+ handler: (request, response) => this.handle(request, response)
1399
+ });
1400
+ } catch (error) {
1401
+ throw this.fail(`onebot: cannot claim the http event route ${path}: ${error instanceof Error ? error.message : String(error)}`);
1402
+ }
1403
+ const endpoint = this.bot.config.endpoint;
1404
+ installRequest(this.bot, (action, params) => this.call(endpoint, action, params));
1405
+ this.bot.user = {
1406
+ id: this.bot.config.selfId,
1407
+ name: this.bot.config.selfId,
1408
+ isBot: true
1409
+ };
1410
+ this.bot.online();
1411
+ }
1412
+ /** Release the event route. */
1413
+ async stop() {
1414
+ this.dispose?.();
1415
+ this.dispose = void 0;
1416
+ }
1417
+ /** Log a start failure before throwing it, because `Bot.start` only stores a connect failure on `bot.error`. */
1418
+ fail(message) {
1419
+ this.bot.ctx.logger.error(message);
1420
+ return new Error(message);
1421
+ }
1422
+ /** One action call against `{endpoint}/{action}`. */
1423
+ async call(endpoint, action, params) {
1424
+ const url = `${endpoint.replace(/\/+$/, "")}/${action}`;
1425
+ const { token } = this.bot.config;
1426
+ let response;
1427
+ try {
1428
+ response = await this.bot.ctx.http(url, {
1429
+ method: "POST",
1430
+ data: params,
1431
+ ...token === "" ? {} : { headers: { Authorization: `Bearer ${token}` } }
1432
+ });
1433
+ } catch (cause) {
1434
+ const refused = responseOf(cause);
1435
+ if (refused !== void 0) {
1436
+ const body = await refused.text().catch(() => "");
1437
+ throw new OneBotHttpError(`onebot: ${action} was refused with HTTP ${refused.status}${body === "" ? "" : `: ${body.slice(0, 200)}`}`, refused.status, { cause });
1438
+ }
1439
+ throw new OneBotHttpError(`onebot: ${action} request failed: ${cause instanceof Error ? cause.message : String(cause)}`, 0, { cause });
1440
+ }
1441
+ let body;
1442
+ try {
1443
+ body = await response.json();
1444
+ } catch (cause) {
1445
+ throw new OneBotHttpError(`onebot: ${action} answered with a body that is not JSON`, response.status, { cause });
1446
+ }
1447
+ if (typeof body !== "object" || body === null) throw new OneBotHttpError(`onebot: ${action} answered with a body that is not an action envelope`, response.status);
1448
+ return body;
1449
+ }
1450
+ /** Check and deliver one event report. */
1451
+ async handle(request, response) {
1452
+ try {
1453
+ if (request.method !== "POST") {
1454
+ writeStatus(response, 405, { allow: "POST" });
1455
+ return;
1456
+ }
1457
+ const { secret } = this.bot.config;
1458
+ const signature = headerOf(request, "x-signature");
1459
+ if (secret === "") {
1460
+ if (!this.warnedNoSecret) {
1461
+ this.warnedNoSecret = true;
1462
+ this.bot.ctx.logger.warn("onebot: secret is empty, so event reports are accepted without X-Signature");
1463
+ }
1464
+ } else if (signature === void 0 || signature === "") {
1465
+ writeStatus(response, 401);
1466
+ return;
1467
+ }
1468
+ const body = await readBody(request);
1469
+ let parsed;
1470
+ try {
1471
+ parsed = JSON.parse(body);
1472
+ } catch (error) {
1473
+ this.bot.ctx.logger.debug("onebot: event report is not JSON: %s", error instanceof Error ? error.message : String(error));
1474
+ writeStatus(response, 400);
1475
+ return;
1476
+ }
1477
+ if (secret !== "" && !matchesSecret(signatureOf(secret, parsed), signature)) {
1478
+ writeStatus(response, 403);
1479
+ return;
1480
+ }
1481
+ if (headerOf(request, "x-self-id") !== this.bot.config.selfId) {
1482
+ writeStatus(response, 403);
1483
+ return;
1484
+ }
1485
+ if (typeof parsed !== "object" || parsed === null) {
1486
+ writeStatus(response, 400);
1487
+ return;
1488
+ }
1489
+ const session = decodePayload(this.bot, parsed);
1490
+ if (session !== void 0) await this.bot.receive(session);
1491
+ writeStatus(response, 204);
1492
+ } catch (error) {
1493
+ this.bot.ctx.logger.warn("onebot: event report failed: %s", error instanceof Error ? error.message : String(error));
1494
+ if (!response.headersSent) writeStatus(response, 500);
1495
+ else response.end();
1496
+ }
1497
+ }
1498
+ };
1499
+ // lib/types/transport/ws-reverse.js
1500
+ /**
1501
+ * Reverse WebSocket transport (`protocol: 'ws-reverse'`).
1502
+ *
1503
+ * The implementation dials the harness; the adapter owns the endpoint through the profile's `webServer` and keeps
1504
+ * listening between connections. A connection that fails the handshake checks is refused and dropped, because the
1505
+ * implementation's configuration can change without a restart of this process.
1506
+ */
1507
+ /** The reverse WebSocket server of one bot. */
1508
+ var OneBotWsServer = class {
1509
+ bot;
1510
+ server;
1511
+ dispose;
1512
+ connection;
1513
+ requests;
1514
+ warnedNoToken = false;
1515
+ constructor(bot) {
1516
+ this.bot = bot;
1517
+ }
1518
+ /**
1519
+ * Claim the upgrade route. The endpoint then stays available across implementation restarts.
1520
+ */
1521
+ async start() {
1522
+ const webServer = this.bot.ctx.get("webServer");
1523
+ if (webServer === void 0) throw this.fail("onebot: protocol \"ws-reverse\" needs a profile-provided webServer; use protocol \"ws\" instead");
1524
+ const path = routePath(this.bot.config.path);
1525
+ const server = new WebSocketServer({ noServer: true });
1526
+ try {
1527
+ this.dispose = webServer.registerUpgrade({
1528
+ path,
1529
+ auth: "anonymous",
1530
+ handler: (request, socket, head) => {
1531
+ this.upgrade(server, request, socket, head);
1532
+ }
1533
+ });
1534
+ } catch (error) {
1535
+ server.close();
1536
+ throw this.fail(`onebot: cannot claim the ws-reverse route ${path}: ${error instanceof Error ? error.message : String(error)}`);
1537
+ }
1538
+ this.server = server;
1539
+ }
1540
+ /** Release the route and close the connected implementation. */
1541
+ async stop() {
1542
+ this.dispose?.();
1543
+ this.dispose = void 0;
1544
+ this.closeConnection();
1545
+ const server = this.server;
1546
+ this.server = void 0;
1547
+ if (server !== void 0) await new Promise((resolve) => server.close(() => resolve()));
1548
+ }
1549
+ /** Log a start failure before throwing it, because `Bot.start` only stores a connect failure on `bot.error`. */
1550
+ fail(message) {
1551
+ this.bot.ctx.logger.error(message);
1552
+ return new Error(message);
1553
+ }
1554
+ /** Validate one upgrade request and hand the accepted socket to `ws`. */
1555
+ upgrade(server, request, socket, head) {
1556
+ const { token } = this.bot.config;
1557
+ if (token === "") {
1558
+ if (!this.warnedNoToken) {
1559
+ this.warnedNoToken = true;
1560
+ this.bot.ctx.logger.warn("onebot: token is empty, so reverse WebSocket connections are accepted without Authorization");
1561
+ }
1562
+ } else {
1563
+ const presented = headerOf(request, "authorization")?.replace(/^Bearer\s+/i, "");
1564
+ if (!matchesSecret(token, presented)) {
1565
+ rejectUpgrade(socket, 401, "Unauthorized");
1566
+ return;
1567
+ }
1568
+ }
1569
+ if (headerOf(request, "x-client-role") !== "Universal") {
1570
+ rejectUpgrade(socket, 403, "Forbidden");
1571
+ return;
1572
+ }
1573
+ if (headerOf(request, "x-self-id") !== this.bot.config.selfId) {
1574
+ rejectUpgrade(socket, 403, "Forbidden");
1575
+ return;
1576
+ }
1577
+ server.handleUpgrade(request, socket, head, (ws) => {
1578
+ this.accept(ws);
1579
+ });
1580
+ }
1581
+ /**
1582
+ * Take over one accepted socket. A newer connection replaces the previous one.
1583
+ * @param socket - the upgraded WebSocket connection of the implementation.
1584
+ */
1585
+ accept(socket) {
1586
+ this.closeConnection(1008, "replaced by a new connection");
1587
+ this.connection = socket;
1588
+ const requests = new ActionRequests((frame) => socket.send(JSON.stringify(frame)), this.bot.config.ws.responseTimeout);
1589
+ this.requests = requests;
1590
+ installRequest(this.bot, requests.request);
1591
+ socket.on("message", (raw) => {
1592
+ this.dispatch(raw.toString(), requests);
1593
+ });
1594
+ socket.on("close", () => {
1595
+ this.drop(socket);
1596
+ });
1597
+ this.bot.user = {
1598
+ id: this.bot.config.selfId,
1599
+ name: this.bot.config.selfId,
1600
+ isBot: true
1601
+ };
1602
+ this.bot.online();
1603
+ }
1604
+ closeConnection(code = 1e3, reason = "adapter stopped") {
1605
+ const socket = this.connection;
1606
+ const requests = this.requests;
1607
+ this.connection = void 0;
1608
+ this.requests = void 0;
1609
+ requests?.rejectAll(/* @__PURE__ */ new Error("onebot: the reverse WebSocket connection has closed"));
1610
+ try {
1611
+ socket?.close(code, reason);
1612
+ } catch (error) {}
1613
+ }
1614
+ /** The current connection closed: refuse its pending calls and wait for the implementation to dial again. */
1615
+ drop(socket) {
1616
+ if (this.connection !== socket) return;
1617
+ this.connection = void 0;
1618
+ const failure = /* @__PURE__ */ new Error("onebot: the reverse WebSocket connection has closed");
1619
+ this.requests?.rejectAll(failure);
1620
+ this.requests = void 0;
1621
+ rejectRequests(this.bot, failure);
1622
+ this.bot.status = Status.RECONNECT;
1623
+ }
1624
+ /** Dispatch one received frame: an event, an action answer, or noise. */
1625
+ dispatch(text, requests) {
1626
+ let parsed;
1627
+ try {
1628
+ parsed = JSON.parse(text);
1629
+ } catch (error) {
1630
+ this.bot.ctx.logger.warn("onebot: cannot parse a WebSocket frame: %s", error instanceof Error ? error.message : String(error));
1631
+ return;
1632
+ }
1633
+ if (isPayload(parsed)) {
1634
+ this.receive(parsed);
1635
+ return;
1636
+ }
1637
+ if (isResponse(parsed) && requests.resolve(parsed)) return;
1638
+ }
1639
+ /** Publish one event; a failed intake is logged because the platform will not redeliver it. */
1640
+ async receive(data) {
1641
+ if (data.post_type === "meta_event") {
1642
+ this.bot.ctx.logger.debug("onebot: %s heartbeat ignored", data.meta_event_type ?? "meta");
1643
+ return;
1644
+ }
1645
+ const session = decodePayload(this.bot, data);
1646
+ if (session === void 0) {
1647
+ this.bot.ctx.logger.debug("onebot: ignored %s event", data.post_type ?? "unknown");
1648
+ return;
1649
+ }
1650
+ try {
1651
+ await this.bot.receive(session);
1652
+ } catch (error) {
1653
+ this.bot.ctx.logger.error("onebot: intake failed: %s", error instanceof Error ? error.message : String(error));
1654
+ }
1655
+ }
1656
+ };
1657
+ // lib/types/identity.js
1658
+ /** The configured `selfId` and the account the implementation reports disagree. */
1659
+ var OneBotIdentityError = class extends Error {
1660
+ constructor(message) {
1661
+ super(message);
1662
+ this.name = "OneBotIdentityError";
1663
+ }
1664
+ };
1665
+ /**
1666
+ * Compare `get_login_info.user_id` with the configured account.
1667
+ *
1668
+ * A mismatch is a configuration error: reconnecting cannot change it, so the caller stops the reconnect loop instead
1669
+ * of retrying.
1670
+ *
1671
+ * @param internal - the account's action client.
1672
+ * @param selfId - the configured account.
1673
+ * @returns the login info of the matching account.
1674
+ * @throws OneBotIdentityError when the implementation reports another account.
1675
+ */
1676
+ async function verifyIdentity(internal, selfId) {
1677
+ const info = await internal.getLoginInfo();
1678
+ const actual = String(info.user_id);
1679
+ if (actual !== selfId) throw new OneBotIdentityError(`onebot: selfId is configured as ${selfId} but the implementation reports account ${actual}; fix selfId and restart`);
1680
+ return info;
1681
+ }
1682
+ // lib/types/transport/ws.js
1683
+ /**
1684
+ * Forward WebSocket transport (`protocol: 'ws'`).
1685
+ *
1686
+ * The adapter dials the implementation's WebSocket endpoint and dials again forever: `ws.retryTimes` is a fast-retry
1687
+ * budget, not a give-up count, so an implementation that starts after the harness still comes online without a
1688
+ * restart. Configuration failures are the caller's to fix and throw out of `connect()`; transport failures retry.
1689
+ */
1690
+ /** Waitable sleep that resolves early on abort. */
1691
+ function sleep(ms, signal) {
1692
+ return new Promise((resolve) => {
1693
+ if (signal.aborted) {
1694
+ resolve();
1695
+ return;
1696
+ }
1697
+ const timer = setTimeout(() => {
1698
+ signal.removeEventListener("abort", onAbort);
1699
+ resolve();
1700
+ }, ms);
1701
+ const onAbort = () => {
1702
+ clearTimeout(timer);
1703
+ resolve();
1704
+ };
1705
+ signal.addEventListener("abort", onAbort, { once: true });
1706
+ });
1707
+ }
1708
+ /** Text of one WebSocket frame. */
1709
+ function frameText(data) {
1710
+ return typeof data === "string" ? data : String(data);
1711
+ }
1712
+ /** The forward WebSocket client of one bot. */
1713
+ var OneBotWsClient = class {
1714
+ bot;
1715
+ controller;
1716
+ running;
1717
+ socket;
1718
+ constructor(bot) {
1719
+ this.bot = bot;
1720
+ }
1721
+ /**
1722
+ * Validate the endpoint and start the reconnect loop.
1723
+ *
1724
+ * Returning before the first dial is deliberate: `Bot.start` awaits `connect()`, so waiting here would hold up
1725
+ * plugin initialization for as long as the implementation is late.
1726
+ */
1727
+ async start() {
1728
+ const endpoint = this.bot.config.endpoint;
1729
+ if (endpoint === "") throw this.fail("onebot: protocol \"ws\" needs endpoint (the implementation's ws:// URL)");
1730
+ this.controller = new AbortController();
1731
+ this.running = this.loop(endpoint, this.controller.signal);
1732
+ }
1733
+ /** Stop the loop and wait for it to unwind. */
1734
+ async stop() {
1735
+ this.controller?.abort();
1736
+ this.controller = void 0;
1737
+ this.closeSocket();
1738
+ await this.running?.catch(() => void 0);
1739
+ this.running = void 0;
1740
+ }
1741
+ /** Log a start failure before throwing it, because `Bot.start` only stores a connect failure on `bot.error`. */
1742
+ fail(message) {
1743
+ this.bot.ctx.logger.error(message);
1744
+ return new Error(message);
1745
+ }
1746
+ closeSocket() {
1747
+ const socket = this.socket;
1748
+ this.socket = void 0;
1749
+ try {
1750
+ socket?.close(1e3, "adapter stopped");
1751
+ } catch (error) {}
1752
+ }
1753
+ async loop(endpoint, signal) {
1754
+ const { config } = this.bot;
1755
+ let failures = 0;
1756
+ while (!signal.aborted) try {
1757
+ const socket = await this.dial(endpoint, signal);
1758
+ failures = 0;
1759
+ await this.accept(socket, signal);
1760
+ if (signal.aborted) return;
1761
+ this.bot.ctx.logger.warn("onebot: the WebSocket connection closed; reconnecting");
1762
+ this.bot.status = Status.RECONNECT;
1763
+ await sleep(config.ws.retryInterval, signal);
1764
+ } catch (error) {
1765
+ if (signal.aborted) return;
1766
+ if (error instanceof OneBotIdentityError) {
1767
+ this.bot.ctx.logger.error("onebot: %s", error.message);
1768
+ this.bot.offline(error);
1769
+ return;
1770
+ }
1771
+ const message = error instanceof Error ? error.message : String(error);
1772
+ this.bot.ctx.logger.warn("onebot: %s; reconnecting", message);
1773
+ this.bot.status = Status.RECONNECT;
1774
+ const base = failures < config.ws.retryTimes ? config.ws.retryInterval : config.ws.retryLazy;
1775
+ failures += 1;
1776
+ await sleep(base, signal);
1777
+ }
1778
+ }
1779
+ /** Dial the endpoint and resolve once the socket is open. */
1780
+ dial(endpoint, signal) {
1781
+ const { token } = this.bot.config;
1782
+ const socket = this.bot.ctx.http.ws(endpoint, token === "" ? {} : { headers: { Authorization: `Bearer ${token}` } });
1783
+ return new Promise((resolve, reject) => {
1784
+ const cleanup = () => {
1785
+ socket.removeEventListener("open", onOpen);
1786
+ socket.removeEventListener("error", onError);
1787
+ socket.removeEventListener("close", onClose);
1788
+ signal.removeEventListener("abort", onAbort);
1789
+ };
1790
+ const onOpen = () => {
1791
+ cleanup();
1792
+ resolve(socket);
1793
+ };
1794
+ const onError = (event) => {
1795
+ cleanup();
1796
+ reject(/* @__PURE__ */ new Error(`onebot: WebSocket error${event.message === void 0 ? "" : `: ${event.message}`}`));
1797
+ };
1798
+ const onClose = (event) => {
1799
+ cleanup();
1800
+ reject(/* @__PURE__ */ new Error(`onebot: WebSocket closed before opening (code ${event.code})`));
1801
+ };
1802
+ const onAbort = () => {
1803
+ cleanup();
1804
+ reject(signal.reason ?? /* @__PURE__ */ new Error("onebot: adapter stopped"));
1805
+ };
1806
+ if (signal.aborted) {
1807
+ onAbort();
1808
+ return;
1809
+ }
1810
+ socket.addEventListener("open", onOpen);
1811
+ socket.addEventListener("error", onError);
1812
+ socket.addEventListener("close", onClose);
1813
+ signal.addEventListener("abort", onAbort, { once: true });
1814
+ });
1815
+ }
1816
+ /**
1817
+ * Take over one open socket: install the action caller, check the identity, publish events until the socket closes.
1818
+ */
1819
+ async accept(socket, signal) {
1820
+ this.socket = socket;
1821
+ const requests = new ActionRequests((frame) => socket.send(JSON.stringify(frame)), this.bot.config.ws.responseTimeout);
1822
+ installRequest(this.bot, requests.request);
1823
+ const closed = new Promise((resolve) => {
1824
+ socket.addEventListener("close", () => resolve());
1825
+ });
1826
+ socket.addEventListener("message", (event) => {
1827
+ this.dispatch(frameText(event.data), requests);
1828
+ });
1829
+ const onAbort = () => {
1830
+ requests.rejectAll(/* @__PURE__ */ new Error("onebot: adapter stopped"));
1831
+ this.closeSocket();
1832
+ };
1833
+ signal.addEventListener("abort", onAbort, { once: true });
1834
+ try {
1835
+ const login = await verifyIdentity(this.bot.internal, this.bot.config.selfId);
1836
+ this.bot.user = {
1837
+ id: String(login.user_id),
1838
+ name: login.nickname,
1839
+ isBot: true
1840
+ };
1841
+ this.bot.online();
1842
+ } catch (error) {
1843
+ const failure = error instanceof Error ? error : new Error(String(error));
1844
+ requests.rejectAll(failure);
1845
+ rejectRequests(this.bot, failure);
1846
+ this.closeSocket();
1847
+ throw failure;
1848
+ } finally {
1849
+ signal.removeEventListener("abort", onAbort);
1850
+ }
1851
+ await closed;
1852
+ const failure = /* @__PURE__ */ new Error("onebot: the WebSocket connection has closed");
1853
+ requests.rejectAll(failure);
1854
+ rejectRequests(this.bot, failure);
1855
+ this.socket = void 0;
1856
+ }
1857
+ /** Dispatch one received frame: an event, an action answer, or noise. */
1858
+ dispatch(text, requests) {
1859
+ let parsed;
1860
+ try {
1861
+ parsed = JSON.parse(text);
1862
+ } catch (error) {
1863
+ this.bot.ctx.logger.warn("onebot: cannot parse a WebSocket frame: %s", error instanceof Error ? error.message : String(error));
1864
+ return;
1865
+ }
1866
+ if (isPayload(parsed)) {
1867
+ this.receive(parsed);
1868
+ return;
1869
+ }
1870
+ if (isResponse(parsed) && requests.resolve(parsed)) return;
1871
+ }
1872
+ /** Publish one event; a failed intake is logged because the platform will not redeliver it. */
1873
+ async receive(data) {
1874
+ if (data.post_type === "meta_event") {
1875
+ this.bot.ctx.logger.debug("onebot: %s heartbeat ignored", data.meta_event_type ?? "meta");
1876
+ return;
1877
+ }
1878
+ const session = decodePayload(this.bot, data);
1879
+ if (session === void 0) {
1880
+ this.bot.ctx.logger.debug("onebot: ignored %s event", data.post_type ?? "unknown");
1881
+ return;
1882
+ }
1883
+ try {
1884
+ await this.bot.receive(session);
1885
+ } catch (error) {
1886
+ this.bot.ctx.logger.error("onebot: intake failed: %s", error instanceof Error ? error.message : String(error));
1887
+ }
1888
+ }
1889
+ };
1890
+ // lib/types/bot.js
1891
+ /**
1892
+ * OneBot 11 adapter.
1893
+ *
1894
+ * The implementation is a third-party process; this adapter is the framework side of the protocol. Identity is the
1895
+ * configured `selfId`, verified with `get_login_info` on the forward WebSocket, and the transports are the three
1896
+ * `protocol` values of the upstream plugin.
1897
+ */
1898
+ var OneBotBot = class extends Adapter {
1899
+ /** The adapter needs the Satori service and the isolated `http` service. */
1900
+ static inject = ["satori", "http"];
1901
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
1902
+ static Config = Config;
1903
+ modes;
1904
+ modeOrder = ["segment"];
1905
+ /** Full typed OneBot 11 action surface registered by the migrated declarations. */
1906
+ internal;
1907
+ transport;
1908
+ constructor(ctx, config) {
1909
+ super(ctx, config, {
1910
+ id: `onebot:${config.selfId}`,
1911
+ platform: "onebot",
1912
+ adapter: "onebot"
1913
+ });
1914
+ this.selfId = config.selfId;
1915
+ this.modes = { segment: createSegmentMode(config.advanced.splitMixedContent) };
1916
+ this.internal = new Internal(this);
1917
+ }
1918
+ async connect() {
1919
+ this.validate();
1920
+ const transport = this.createTransport();
1921
+ this.transport = transport;
1922
+ try {
1923
+ await transport.start();
1924
+ } catch (error) {
1925
+ this.transport = void 0;
1926
+ throw error;
1927
+ }
1928
+ }
1929
+ async disconnect() {
1930
+ const transport = this.transport;
1931
+ this.transport = void 0;
1932
+ await transport?.stop();
1933
+ }
1934
+ /**
1935
+ * Resolve one outbound resource.
1936
+ *
1937
+ * OneBot has no upload endpoint: an image, record or video segment carries its source, which the implementation
1938
+ * fetches itself. A `<file>` needs a path on the implementation's host, so a local `file:` source is used directly
1939
+ * and anything else is handed to `download_file`.
1940
+ */
1941
+ async upload(ref, _scope, _ctx) {
1942
+ if (ref.kind !== "file") return { key: normalizeSource(ref.src) };
1943
+ if (ref.src.startsWith("file:")) return { key: fileURLToPath(ref.src) };
1944
+ const downloaded = await this.internal.downloadFile(ref.src);
1945
+ if (downloaded === void 0) throw new PlatformError("not-found", `onebot: download_file returned no path for ${ref.src}`);
1946
+ return { key: downloaded };
1947
+ }
1948
+ resourceScope(_target, _kind) {
1949
+ return this.id;
1950
+ }
1951
+ async sendPayload(payload, target, ctx) {
1952
+ return await sendPayload(this.sendDeps(), payload, target, ctx);
1953
+ }
1954
+ async deletePart(part) {
1955
+ await deletePart(this.sendDeps(), part);
1956
+ }
1957
+ async members(chat, _cursor, _limit) {
1958
+ return await members(this.sendDeps(), chat);
1959
+ }
1960
+ async getMessage(chat, id) {
1961
+ return await getMessage(this.sendDeps(), this, chat, id);
1962
+ }
1963
+ async createReaction(message, emoji) {
1964
+ await createReaction(this.sendDeps(), message, emoji);
1965
+ }
1966
+ async deleteReaction(message, emoji) {
1967
+ await deleteReaction(this.sendDeps(), message, emoji);
1968
+ }
1969
+ classify(error) {
1970
+ return classifyOneBotError(error);
1971
+ }
1972
+ sendDeps() {
1973
+ return { internal: this.internal };
1974
+ }
1975
+ /** Reject a configuration the selected transport cannot work from; such a failure is not retryable. */
1976
+ validate() {
1977
+ const { protocol, endpoint } = this.config;
1978
+ if (protocol === "ws-reverse") return;
1979
+ if (endpoint === "") throw this.fail(`onebot: protocol "${protocol}" needs endpoint (the implementation's ${protocol === "ws" ? "ws" : "http"}:// URL)`);
1980
+ let url;
1981
+ try {
1982
+ url = new URL(endpoint);
1983
+ } catch {
1984
+ throw this.fail(`onebot: endpoint "${endpoint}" is not a valid URL`);
1985
+ }
1986
+ const accepted = protocol === "ws" ? ["ws:", "wss:"] : ["http:", "https:"];
1987
+ if (!accepted.includes(url.protocol)) throw this.fail(`onebot: endpoint "${endpoint}" must be a ${accepted.join(" or ")} URL for protocol "${protocol}"`);
1988
+ }
1989
+ fail(message) {
1990
+ this.ctx.logger.error(message);
1991
+ return new Error(message);
1992
+ }
1993
+ createTransport() {
1994
+ switch (this.config.protocol) {
1995
+ case "ws": return new OneBotWsClient(this);
1996
+ case "ws-reverse": return new OneBotWsServer(this);
1997
+ case "http": return new OneBotHttp(this);
1998
+ }
1999
+ }
2000
+ };
2001
+ export { Config, Internal, OneBotBot, OneBotBot as default, OneBotHttpError, OneBotIdentityError, TimeoutError, classifyOneBotError, senderCodeOf, verifyIdentity };
2002
+
2003
+ //# sourceMappingURL=index.js.map