@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/src/decode.ts ADDED
@@ -0,0 +1,524 @@
1
+ /**
2
+ * Inbound decoding: one OneBot 11 event becomes an intake `Session`.
3
+ *
4
+ * Message events and the two recall notices are decoded; every other `post_type` is ignored. Segment content keeps
5
+ * its text: a segment the vocabulary cannot express becomes a readable placeholder instead of disappearing, and an
6
+ * event that carries no segment at all becomes an inbound `<raw>` element, because `InboundMessage.content` may not
7
+ * be empty.
8
+ */
9
+
10
+ import {
11
+ type ChatRef,
12
+ type Element,
13
+ h,
14
+ type InboundMessage,
15
+ normalize,
16
+ PlatformError,
17
+ type Session,
18
+ type UserRef,
19
+ } from '@deepseek-ai/cordis-plugin-im-core'
20
+ import type { Dict } from '@deepseek-ai/cosmokit'
21
+ import type { OneBotBot } from './bot.ts'
22
+ import { type CQCode, parseCqCode } from './cqcode.ts'
23
+ import { GROUP_PREFIX, PRIVATE_PREFIX } from './modes/shared.ts'
24
+ import type { AnonymousInfo, Payload, SenderInfo } from './types.ts'
25
+
26
+ /** Adapter-private context carried through `Target.referrer`. */
27
+ export interface OneBotReferrer {
28
+ chatId: string
29
+ messageId: string
30
+ time: number
31
+ }
32
+
33
+ /**
34
+ * The fields decoding reads: a `message` event, a `get_msg` answer, or the content of one forwarded node.
35
+ * Every field is optional because those three wire shapes differ in which ones they carry.
36
+ */
37
+ export interface MessageLike {
38
+ message_id?: number
39
+ real_id?: number
40
+ time?: number
41
+ post_type?: string
42
+ notice_type?: string
43
+ message_type?: 'private' | 'group' | 'guild'
44
+ sub_type?: string
45
+ sender?: Partial<SenderInfo>
46
+ user_id?: number
47
+ target_id?: number
48
+ group_id?: number
49
+ message?: unknown
50
+ raw_message?: string
51
+ anonymous?: AnonymousInfo
52
+ }
53
+
54
+ /** Text of a segment that has no element of its own. */
55
+ function placeholderOf(type: string, data: Dict<string>): string | undefined {
56
+ switch (type) {
57
+ case 'poke':
58
+ return '[戳一戳]'
59
+ case 'rps':
60
+ return '[猜拳]'
61
+ case 'dice':
62
+ return '[骰子]'
63
+ case 'shake':
64
+ return '[抖动]'
65
+ case 'anonymous':
66
+ return '[匿名消息]'
67
+ case 'contact':
68
+ return '[名片]'
69
+ case 'music':
70
+ return '[音乐]'
71
+ case 'tts':
72
+ return '[语音]'
73
+ case 'mface':
74
+ return '[表情]'
75
+ case 'markdown':
76
+ return '[Markdown]'
77
+ case 'keyboard':
78
+ return '[按钮]'
79
+ case 'node':
80
+ return '[合并转发节点]'
81
+ case 'location':
82
+ return `[位置 ${data.lat ?? '?'},${data.lon ?? '?'}]`
83
+ default:
84
+ return undefined
85
+ }
86
+ }
87
+
88
+ /** The title of a JSON/XML card, when it carries one; the card body itself is not printed. */
89
+ function cardTitle(source: string): string | undefined {
90
+ let parsed: unknown
91
+ try {
92
+ parsed = JSON.parse(source)
93
+ } catch (error) {
94
+ // Not JSON: an XML card or a malformed payload, nothing to extract.
95
+ void error
96
+ return undefined
97
+ }
98
+ if (typeof parsed !== 'object' || parsed === null) return undefined
99
+ const meta = (parsed as { meta?: unknown }).meta
100
+ if (typeof meta === 'object' && meta !== null) {
101
+ const detail = (meta as Record<string, unknown>).detail_1
102
+ if (typeof detail === 'object' && detail !== null) {
103
+ const title = (detail as Record<string, unknown>).title
104
+ if (typeof title === 'string' && title !== '') return title
105
+ }
106
+ }
107
+ const prompt = (parsed as { prompt?: unknown }).prompt
108
+ if (typeof prompt === 'string' && prompt !== '') return prompt
109
+ return undefined
110
+ }
111
+
112
+ /**
113
+ * Validate one wire segment list.
114
+ *
115
+ * The array message format is JSON from another process, so every field is checked: a segment without a string `type`
116
+ * is dropped, and parameter values are kept only when they are strings or numbers.
117
+ *
118
+ * @param value - a `message` field or a forwarded node's `content`.
119
+ * @returns the segments that can be decoded.
120
+ */
121
+ export function normalizeSegments(value: unknown): CQCode[] {
122
+ if (typeof value === 'string') return parseCqCode(value)
123
+ if (!Array.isArray(value)) return []
124
+ const segments: CQCode[] = []
125
+ for (const item of value) {
126
+ if (typeof item !== 'object' || item === null) continue
127
+ const type = (item as { type?: unknown }).type
128
+ if (typeof type !== 'string' || type === '') continue
129
+ const source = (item as { data?: unknown }).data
130
+ const data: Dict<string> = {}
131
+ if (typeof source === 'object' && source !== null) {
132
+ for (const [key, entry] of Object.entries(source)) {
133
+ if (typeof entry === 'string') data[key] = entry
134
+ else if (typeof entry === 'number') data[key] = String(entry)
135
+ }
136
+ }
137
+ segments.push({ type, data })
138
+ }
139
+ return segments
140
+ }
141
+
142
+ /** The segments of one message: the `message` field by value, else the CQ string in `raw_message`. */
143
+ function segmentsOf(data: MessageLike): CQCode[] {
144
+ if (data.message !== undefined && data.message !== null) {
145
+ const segments = normalizeSegments(data.message)
146
+ if (segments.length > 0) return segments
147
+ }
148
+ return typeof data.raw_message === 'string'
149
+ ? parseCqCode(data.raw_message)
150
+ : []
151
+ }
152
+
153
+ /** What one segment list decodes to. */
154
+ interface ContentParts {
155
+ nodes: Element[]
156
+ quote: string | undefined
157
+ mentions: { self: boolean; all: boolean; users: UserRef[] }
158
+ }
159
+
160
+ /**
161
+ * Decode one message's segments into the element vocabulary.
162
+ *
163
+ * @param bot - the receiving adapter (its `selfId` decides `mentions.self`).
164
+ * @param segments - validated segments.
165
+ * @returns the content nodes, the quoted message id and the mentions.
166
+ */
167
+ export function decodeSegments(
168
+ bot: OneBotBot,
169
+ segments: readonly CQCode[],
170
+ ): ContentParts {
171
+ const nodes: Element[] = []
172
+ const mentions: ContentParts['mentions'] = {
173
+ self: false,
174
+ all: false,
175
+ users: [],
176
+ }
177
+ let quote: string | undefined
178
+
179
+ for (const segment of segments) {
180
+ const data = segment.data
181
+ switch (segment.type) {
182
+ case 'text':
183
+ nodes.push(h.text(data.text ?? ''))
184
+ break
185
+ case 'face':
186
+ nodes.push(
187
+ h('emoji', {
188
+ id: data.id ?? '',
189
+ ...(data.name === undefined ? {} : { name: data.name }),
190
+ }),
191
+ )
192
+ break
193
+ case 'image':
194
+ // The implementation's `url` or `file` is the source as-is; a bare file name is left for the host to skip.
195
+ nodes.push(h('img', { src: data.url || data.file || '' }))
196
+ if (data.type === 'flash') nodes.push(h.text('[闪照]'))
197
+ break
198
+ case 'record':
199
+ nodes.push(h('audio', { src: data.url || data.file || '' }))
200
+ break
201
+ case 'video':
202
+ nodes.push(h('video', { src: data.url || data.file || '' }))
203
+ break
204
+ case 'file':
205
+ nodes.push(
206
+ h('file', {
207
+ src: data.url || data.file || '',
208
+ ...(data.name === undefined ? {} : { name: data.name }),
209
+ }),
210
+ )
211
+ break
212
+ case 'at': {
213
+ const qq = data.qq ?? ''
214
+ if (qq === 'all') {
215
+ mentions.all = true
216
+ nodes.push(h('at', { type: 'all' }))
217
+ break
218
+ }
219
+ mentions.users.push({
220
+ id: qq,
221
+ ...(data.name === undefined ? {} : { name: data.name }),
222
+ })
223
+ if (qq === bot.selfId) mentions.self = true
224
+ nodes.push(
225
+ h('at', {
226
+ type: 'user',
227
+ id: qq,
228
+ ...(data.name === undefined ? {} : { name: data.name }),
229
+ }),
230
+ )
231
+ break
232
+ }
233
+ case 'reply':
234
+ // The quoted message is an id only; the host formats the reply from what it stored.
235
+ quote = data.id ?? ''
236
+ break
237
+ case 'forward':
238
+ nodes.push(h('forward', { id: data.id ?? '' }))
239
+ break
240
+ case 'share':
241
+ nodes.push(h('a', { href: data.url ?? '' }, data.title ?? ''))
242
+ break
243
+ case 'json':
244
+ case 'xml': {
245
+ const title = cardTitle(data.data ?? '')
246
+ nodes.push(h.text(title === undefined ? '[卡片]' : `[卡片] ${title}`))
247
+ break
248
+ }
249
+ default: {
250
+ const placeholder = placeholderOf(segment.type, data)
251
+ if (placeholder !== undefined) {
252
+ nodes.push(h.text(placeholder))
253
+ break
254
+ }
255
+ const text = data.text
256
+ nodes.push(
257
+ h.text(
258
+ text !== undefined && text !== '' ? text : `[${segment.type}]`,
259
+ ),
260
+ )
261
+ break
262
+ }
263
+ }
264
+ }
265
+
266
+ return { nodes, quote, mentions }
267
+ }
268
+
269
+ /** A bounded description of an event that decoded to no content, so `<raw>` stays small. */
270
+ function rawPreview(data: MessageLike): Dict<string> {
271
+ const preview: Dict<string> = {}
272
+ for (const key of [
273
+ 'post_type',
274
+ 'message_type',
275
+ 'notice_type',
276
+ 'sub_type',
277
+ 'message_id',
278
+ 'group_id',
279
+ 'user_id',
280
+ ] as const) {
281
+ const value = data[key]
282
+ if (value !== undefined) preview[key] = String(value)
283
+ }
284
+ return preview
285
+ }
286
+
287
+ /** The chat a message was sent in. */
288
+ export function chatOfMessage(data: MessageLike): ChatRef {
289
+ if (
290
+ data.message_type === 'group' ||
291
+ (data.message_type === undefined && data.group_id !== undefined)
292
+ ) {
293
+ return { id: `${GROUP_PREFIX}${data.group_id ?? 0}`, type: 'group' }
294
+ }
295
+ const userId = data.sender?.user_id ?? data.user_id ?? data.target_id ?? 0
296
+ return { id: `${PRIVATE_PREFIX}${userId}`, type: 'direct' }
297
+ }
298
+
299
+ /** The sender of one message; an anonymous group message has no usable sender, so its anonymous id stands in. */
300
+ function senderOf(data: MessageLike): UserRef {
301
+ if (data.anonymous !== undefined) {
302
+ return { id: String(data.anonymous.id), name: '匿名用户' }
303
+ }
304
+ const sender = data.sender ?? {}
305
+ const name = sender.card || sender.nickname
306
+ return {
307
+ id: String(sender.user_id ?? data.user_id ?? 0),
308
+ ...(name === undefined || name === '' ? {} : { name }),
309
+ ...(sender.role === undefined ? {} : { role: sender.role }),
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Decode one message payload.
315
+ * @param bot - the receiving adapter.
316
+ * @param data - a message event, or a `get_msg` answer.
317
+ * @param chat - the chat to report; a `get_msg` answer carries no group id, so the caller passes its own.
318
+ * @returns the inbound message.
319
+ */
320
+ export function decodeMessage(
321
+ bot: OneBotBot,
322
+ data: MessageLike,
323
+ chat: ChatRef = chatOfMessage(data),
324
+ ): InboundMessage {
325
+ const parts = decodeSegments(bot, segmentsOf(data))
326
+ const id = String(data.message_id ?? 0)
327
+ const time = (data.time ?? Math.floor(Date.now() / 1_000)) * 1_000
328
+ const content = normalize(
329
+ parts.nodes.length > 0
330
+ ? parts.nodes
331
+ : [
332
+ h(
333
+ 'raw',
334
+ {
335
+ platform: 'onebot',
336
+ type: data.post_type ?? 'message',
337
+ data: rawPreview(data),
338
+ },
339
+ h.text(''),
340
+ ),
341
+ ],
342
+ )
343
+ const realId = data.real_id
344
+ return {
345
+ id,
346
+ ...(realId === undefined || String(realId) === id
347
+ ? {}
348
+ : { aliases: [String(realId)] }),
349
+ chat,
350
+ sender: senderOf(data),
351
+ content,
352
+ ...(parts.quote === undefined ? {} : { quote: { id: parts.quote } }),
353
+ mentions: parts.mentions,
354
+ time,
355
+ referrer: { chatId: chat.id, messageId: id, time } satisfies OneBotReferrer,
356
+ raw: data,
357
+ }
358
+ }
359
+
360
+ /** One `notice` that reports a recalled message. */
361
+ function deletedSession(bot: OneBotBot, data: Payload): Session {
362
+ const group = data.notice_type === 'group_recall'
363
+ const chat: ChatRef = group
364
+ ? { id: `${GROUP_PREFIX}${data.group_id ?? 0}`, type: 'group' }
365
+ : {
366
+ id: `${PRIVATE_PREFIX}${data.user_id ?? data.target_id ?? 0}`,
367
+ type: 'direct',
368
+ }
369
+ const time = (data.time ?? Math.floor(Date.now() / 1_000)) * 1_000
370
+ return bot.session({
371
+ type: 'message-deleted',
372
+ id: `notice:${data.notice_type}:${data.time}:${data.message_id}`,
373
+ timestamp: time,
374
+ deleted: {
375
+ id: String(data.message_id),
376
+ chat,
377
+ ...(data.operator_id === undefined
378
+ ? {}
379
+ : { operator: { id: String(data.operator_id) } }),
380
+ },
381
+ raw: data,
382
+ })
383
+ }
384
+
385
+ /**
386
+ * Decode one platform event.
387
+ *
388
+ * The event id is synthesized because OneBot events carry none, and the host dedupes on it: `message_id` alone would
389
+ * collide with the ids some implementations restart from zero.
390
+ *
391
+ * @param bot - the receiving adapter.
392
+ * @param data - the event payload.
393
+ * @returns the session to publish, or undefined for an ignored event.
394
+ */
395
+ export function decodePayload(
396
+ bot: OneBotBot,
397
+ data: Payload,
398
+ ): Session | undefined {
399
+ if (data.post_type === 'message') {
400
+ if (data.message_type !== 'private' && data.message_type !== 'group') {
401
+ return undefined
402
+ }
403
+ const message = decodeMessage(bot, data)
404
+ return bot.session({
405
+ type: 'message',
406
+ id: `message:${data.message_id}:${data.time}`,
407
+ timestamp: message.time,
408
+ message,
409
+ raw: data,
410
+ })
411
+ }
412
+ if (data.post_type === 'notice') {
413
+ if (
414
+ data.notice_type === 'group_recall' ||
415
+ data.notice_type === 'friend_recall'
416
+ ) {
417
+ return deletedSession(bot, data)
418
+ }
419
+ }
420
+ return undefined
421
+ }
422
+
423
+ /**
424
+ * Whether a parsed frame is one platform event.
425
+ * @param value - a parsed JSON frame from the implementation.
426
+ * @returns whether it is an event rather than an action answer.
427
+ */
428
+ export function isPayload(value: unknown): value is Payload {
429
+ if (typeof value !== 'object' || value === null) return false
430
+ return typeof (value as { post_type?: unknown }).post_type === 'string'
431
+ }
432
+
433
+ /** One node of a `get_forward_msg` answer. */
434
+ interface ForwardNode {
435
+ nickname: string
436
+ content: unknown
437
+ }
438
+
439
+ /** Read the node list of a `get_forward_msg` answer; the standard calls it `message`, go-cqhttp `messages`. */
440
+ function forwardNodesOf(source: unknown): ForwardNode[] {
441
+ if (typeof source !== 'object' || source === null) return []
442
+ const record = source as { messages?: unknown; message?: unknown }
443
+ const list = Array.isArray(record.messages)
444
+ ? record.messages
445
+ : Array.isArray(record.message)
446
+ ? record.message
447
+ : []
448
+ const nodes: ForwardNode[] = []
449
+ for (const entry of list) {
450
+ if (typeof entry !== 'object' || entry === null) continue
451
+ if ((entry as { type?: unknown }).type !== 'node') continue
452
+ const data = (entry as { data?: unknown }).data
453
+ if (typeof data !== 'object' || data === null) continue
454
+ const fields = data as {
455
+ nickname?: unknown
456
+ name?: unknown
457
+ content?: unknown
458
+ }
459
+ const nickname =
460
+ typeof fields.nickname === 'string'
461
+ ? fields.nickname
462
+ : typeof fields.name === 'string'
463
+ ? fields.name
464
+ : ''
465
+ nodes.push({ nickname, content: fields.content })
466
+ }
467
+ return nodes
468
+ }
469
+
470
+ /** Collect the empty `forward` placeholders of a decoded message. */
471
+ function collectForwards(content: Element): Element<'forward'>[] {
472
+ const found: Element<'forward'>[] = []
473
+ const walk = (element: Element): void => {
474
+ if (element.type === 'forward') {
475
+ if (element.children.length === 0) found.push(element)
476
+ return
477
+ }
478
+ for (const child of element.children) walk(child)
479
+ }
480
+ walk(content)
481
+ return found
482
+ }
483
+
484
+ /**
485
+ * Expand the merged forwards of one message into phrasing content, as the host's `im_read` expects.
486
+ *
487
+ * One forwarded node renders as its author in bold, a colon, the node content and a line break. The content model of
488
+ * `<forward>` is phrasing, so no block element may be inserted.
489
+ *
490
+ * @param bot - the adapter, used for the `get_forward_msg` call.
491
+ * @param message - the decoded message.
492
+ * @returns the same message with every `forward` element expanded.
493
+ */
494
+ export async function expandForward(
495
+ bot: OneBotBot,
496
+ message: InboundMessage,
497
+ ): Promise<InboundMessage> {
498
+ const forwards = collectForwards(message.content)
499
+ if (forwards.length === 0) return message
500
+ const request = bot.internal._request
501
+ if (request === undefined) {
502
+ throw new PlatformError(
503
+ 'retryable',
504
+ 'onebot: cannot read the forwarded message while the transport is not connected',
505
+ { published: 'unknown' },
506
+ )
507
+ }
508
+ for (const element of forwards) {
509
+ const response = await request('get_forward_msg', {
510
+ message_id: element.attrs.id,
511
+ })
512
+ if (response.retcode !== 0) continue
513
+ const children: Element[] = []
514
+ for (const node of forwardNodesOf(response.data)) {
515
+ children.push(h('b', {}, h.text(node.nickname)), h.text(': '))
516
+ children.push(
517
+ ...decodeSegments(bot, normalizeSegments(node.content)).nodes,
518
+ )
519
+ children.push(h('br'))
520
+ }
521
+ element.children = children
522
+ }
523
+ return message
524
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,134 @@
1
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
2
+ import { TimeoutError } from './types.ts'
3
+
4
+ /**
5
+ * A failed `protocol: 'http'` API call: the status the implementation answered with, or `0` when the request never
6
+ * produced a response.
7
+ */
8
+ export class OneBotHttpError extends Error {
9
+ constructor(
10
+ message: string,
11
+ readonly status: number,
12
+ options: { cause?: unknown } = {},
13
+ ) {
14
+ super(
15
+ message,
16
+ options.cause === undefined ? undefined : { cause: options.cause },
17
+ )
18
+ this.name = 'OneBotHttpError'
19
+ }
20
+ }
21
+
22
+ /** Whether a caught value is the abort error of a cancelled request. */
23
+ function isAbortError(error: unknown): boolean {
24
+ return (
25
+ (error instanceof Error || error instanceof DOMException) &&
26
+ error.name === 'AbortError'
27
+ )
28
+ }
29
+
30
+ /**
31
+ * The `retcode` a failed action carries.
32
+ *
33
+ * The upstream `SenderError` attaches `code` with `Object.defineProperties` and is not exported, so the classifier
34
+ * reads the field structurally. A transport failure carries a string `code` (`ECONNREFUSED`, …) and is not one.
35
+ *
36
+ * @param error - the caught failure.
37
+ * @returns the numeric `retcode`, or undefined when the failure is not an action refusal.
38
+ */
39
+ export function senderCodeOf(error: unknown): number | undefined {
40
+ if (typeof error !== 'object' || error === null) return undefined
41
+ const code = (error as { code?: unknown }).code
42
+ return typeof code === 'number' ? code : undefined
43
+ }
44
+
45
+ /**
46
+ * Map any OneBot failure onto the core platform taxonomy.
47
+ *
48
+ * A refusal the implementation answered with is certainly unpublished; transport failures, timeouts and the
49
+ * `status: 'async'` acknowledgement leave the outcome unknown.
50
+ *
51
+ * @param error - the caught failure.
52
+ * @returns the classified platform error.
53
+ */
54
+ export function classifyOneBotError(error: unknown): PlatformError {
55
+ if (error instanceof PlatformError) return error
56
+
57
+ // A `DOMException` carries a numeric `code` too (20 for `AbortError`), so cancellation is recognised before the
58
+ // retcode branch can read it as an implementation refusal.
59
+ if (isAbortError(error))
60
+ return new PlatformError(
61
+ 'fatal',
62
+ error instanceof Error ? error.message : 'onebot request aborted',
63
+ { published: 'unknown', cause: error },
64
+ )
65
+
66
+ const retcode = senderCodeOf(error)
67
+ if (retcode !== undefined) {
68
+ const message = error instanceof Error ? error.message : String(error)
69
+ const init = { code: retcode, cause: error }
70
+ // 0 never reaches the classifier (`Internal._get` returns it as success); 1 is `status: 'async'`.
71
+ if (retcode === 1)
72
+ return new PlatformError('retryable', message, {
73
+ ...init,
74
+ published: 'unknown',
75
+ })
76
+ if (retcode === 1401 || retcode === 1403)
77
+ return new PlatformError('permission', message, {
78
+ ...init,
79
+ published: 'no',
80
+ })
81
+ if (retcode === 1404)
82
+ return new PlatformError('not-found', message, {
83
+ ...init,
84
+ published: 'no',
85
+ })
86
+ if (retcode === 1400)
87
+ return new PlatformError('invalid', message, { ...init, published: 'no' })
88
+ // Implementation-specific codes (go-cqhttp 100/103/120/200/1500, …) have no standard meaning.
89
+ return new PlatformError('retryable', message, {
90
+ ...init,
91
+ published: 'unknown',
92
+ })
93
+ }
94
+
95
+ if (error instanceof OneBotHttpError) {
96
+ const init = { cause: error }
97
+ if (error.status === 401 || error.status === 403)
98
+ return new PlatformError('permission', error.message, {
99
+ ...init,
100
+ published: 'no',
101
+ })
102
+ if (error.status === 404)
103
+ return new PlatformError('not-found', error.message, {
104
+ ...init,
105
+ published: 'no',
106
+ })
107
+ if (error.status >= 500)
108
+ return new PlatformError('retryable', error.message, {
109
+ ...init,
110
+ published: 'unknown',
111
+ })
112
+ if (error.status >= 400)
113
+ return new PlatformError('invalid', error.message, {
114
+ ...init,
115
+ published: 'no',
116
+ })
117
+ return new PlatformError('retryable', error.message, {
118
+ ...init,
119
+ published: 'unknown',
120
+ })
121
+ }
122
+
123
+ if (error instanceof TimeoutError)
124
+ return new PlatformError('retryable', error.message, {
125
+ published: 'unknown',
126
+ cause: error,
127
+ })
128
+
129
+ const message = error instanceof Error ? error.message : String(error)
130
+ return new PlatformError('retryable', `onebot request failed: ${message}`, {
131
+ published: 'unknown',
132
+ cause: error,
133
+ })
134
+ }
@@ -0,0 +1,34 @@
1
+ import type { AccountInfo, Internal } from './types.ts'
2
+
3
+ /** The configured `selfId` and the account the implementation reports disagree. */
4
+ export class OneBotIdentityError extends Error {
5
+ constructor(message: string) {
6
+ super(message)
7
+ this.name = 'OneBotIdentityError'
8
+ }
9
+ }
10
+
11
+ /**
12
+ * Compare `get_login_info.user_id` with the configured account.
13
+ *
14
+ * A mismatch is a configuration error: reconnecting cannot change it, so the caller stops the reconnect loop instead
15
+ * of retrying.
16
+ *
17
+ * @param internal - the account's action client.
18
+ * @param selfId - the configured account.
19
+ * @returns the login info of the matching account.
20
+ * @throws OneBotIdentityError when the implementation reports another account.
21
+ */
22
+ export async function verifyIdentity(
23
+ internal: Internal,
24
+ selfId: string,
25
+ ): Promise<AccountInfo> {
26
+ const info = await internal.getLoginInfo()
27
+ const actual = String(info.user_id)
28
+ if (actual !== selfId) {
29
+ throw new OneBotIdentityError(
30
+ `onebot: selfId is configured as ${selfId} but the implementation reports account ${actual}; fix selfId and restart`,
31
+ )
32
+ }
33
+ return info
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ export { OneBotBot, OneBotBot as default, type OneBotModes } from './bot.ts'
2
+ export {
3
+ Config,
4
+ type Config as OneBotConfig,
5
+ type OneBotProtocol,
6
+ } from './config.ts'
7
+ export { OneBotHttpError, classifyOneBotError, senderCodeOf } from './errors.ts'
8
+ export { OneBotIdentityError, verifyIdentity } from './identity.ts'
9
+ export type {
10
+ OneBotDraft,
11
+ OneBotFilePayload,
12
+ OneBotMessagePayload,
13
+ OneBotModeTypes,
14
+ OneBotNode,
15
+ OneBotPayload,
16
+ OneBotSegment,
17
+ } from './modes/shared.ts'
18
+ export { Internal, TimeoutError } from './types.ts'