@im-more/dsh-telegram 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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +10 -0
  3. package/lib/index.js +2067 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +70 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +231 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +34 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +41 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +39 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +382 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +33 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +89 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +19 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +34 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +10 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +8 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/media.d.ts +38 -0
  30. package/lib/types/media.d.ts.map +1 -0
  31. package/lib/types/media.js +65 -0
  32. package/lib/types/media.js.map +1 -0
  33. package/lib/types/modes/html.d.ts +16 -0
  34. package/lib/types/modes/html.d.ts.map +1 -0
  35. package/lib/types/modes/html.js +155 -0
  36. package/lib/types/modes/html.js.map +1 -0
  37. package/lib/types/modes/plain.d.ts +14 -0
  38. package/lib/types/modes/plain.d.ts.map +1 -0
  39. package/lib/types/modes/plain.js +56 -0
  40. package/lib/types/modes/plain.js.map +1 -0
  41. package/lib/types/modes/shared.d.ts +140 -0
  42. package/lib/types/modes/shared.d.ts.map +1 -0
  43. package/lib/types/modes/shared.js +405 -0
  44. package/lib/types/modes/shared.js.map +1 -0
  45. package/lib/types/polling.d.ts +26 -0
  46. package/lib/types/polling.d.ts.map +1 -0
  47. package/lib/types/polling.js +149 -0
  48. package/lib/types/polling.js.map +1 -0
  49. package/lib/types/request.d.ts +67 -0
  50. package/lib/types/request.d.ts.map +1 -0
  51. package/lib/types/request.js +158 -0
  52. package/lib/types/request.js.map +1 -0
  53. package/lib/types/secret.d.ts +27 -0
  54. package/lib/types/secret.d.ts.map +1 -0
  55. package/lib/types/secret.js +39 -0
  56. package/lib/types/secret.js.map +1 -0
  57. package/lib/types/send.d.ts +48 -0
  58. package/lib/types/send.d.ts.map +1 -0
  59. package/lib/types/send.js +326 -0
  60. package/lib/types/send.js.map +1 -0
  61. package/lib/types/types/game.d.ts +102 -0
  62. package/lib/types/types/game.d.ts.map +1 -0
  63. package/lib/types/types/game.js +5 -0
  64. package/lib/types/types/game.js.map +1 -0
  65. package/lib/types/types/index.d.ts +2751 -0
  66. package/lib/types/types/index.d.ts.map +1 -0
  67. package/lib/types/types/index.js +88 -0
  68. package/lib/types/types/index.js.map +1 -0
  69. package/lib/types/types/inline.d.ts +796 -0
  70. package/lib/types/types/inline.d.ts.map +1 -0
  71. package/lib/types/types/inline.js +4 -0
  72. package/lib/types/types/inline.js.map +1 -0
  73. package/lib/types/types/internal.d.ts +32 -0
  74. package/lib/types/types/internal.d.ts.map +1 -0
  75. package/lib/types/types/internal.js +30 -0
  76. package/lib/types/types/internal.js.map +1 -0
  77. package/lib/types/types/passport.d.ts +229 -0
  78. package/lib/types/types/passport.d.ts.map +1 -0
  79. package/lib/types/types/passport.js +3 -0
  80. package/lib/types/types/passport.js.map +1 -0
  81. package/lib/types/types/payment.d.ts +285 -0
  82. package/lib/types/types/payment.d.ts.map +1 -0
  83. package/lib/types/types/payment.js +6 -0
  84. package/lib/types/types/payment.js.map +1 -0
  85. package/lib/types/types/sticker.d.ts +221 -0
  86. package/lib/types/types/sticker.d.ts.map +1 -0
  87. package/lib/types/types/sticker.js +11 -0
  88. package/lib/types/types/sticker.js.map +1 -0
  89. package/lib/types/types/update.d.ts +97 -0
  90. package/lib/types/types/update.d.ts.map +1 -0
  91. package/lib/types/types/update.js +6 -0
  92. package/lib/types/types/update.js.map +1 -0
  93. package/lib/types/webhook.d.ts +29 -0
  94. package/lib/types/webhook.d.ts.map +1 -0
  95. package/lib/types/webhook.js +129 -0
  96. package/lib/types/webhook.js.map +1 -0
  97. package/package.json +61 -3
  98. package/src/bot.ts +349 -0
  99. package/src/config.ts +73 -0
  100. package/src/decode.ts +472 -0
  101. package/src/errors.ts +103 -0
  102. package/src/identity.ts +41 -0
  103. package/src/index.ts +14 -0
  104. package/src/media.ts +79 -0
  105. package/src/modes/html.ts +193 -0
  106. package/src/modes/plain.ts +75 -0
  107. package/src/modes/shared.ts +505 -0
  108. package/src/polling.ts +176 -0
  109. package/src/request.ts +224 -0
  110. package/src/secret.ts +46 -0
  111. package/src/send.ts +454 -0
  112. package/src/types/.eslintrc.yml +2 -0
  113. package/src/types/game.ts +112 -0
  114. package/src/types/index.ts +3028 -0
  115. package/src/types/inline.ts +857 -0
  116. package/src/types/internal.ts +64 -0
  117. package/src/types/passport.ts +256 -0
  118. package/src/types/payment.ts +304 -0
  119. package/src/types/sticker.ts +244 -0
  120. package/src/types/update.ts +107 -0
  121. package/src/webhook.ts +168 -0
  122. package/README.md +0 -3
package/lib/index.js ADDED
@@ -0,0 +1,2067 @@
1
+ import { Adapter, ElementRegistry, PlatformError, Status, createEditDriver } from "@deepseek-ai/cordis-plugin-im-core";
2
+ import { readFile } from "node:fs/promises";
3
+ import { extname } from "node:path";
4
+ import z from "@deepseek-ai/schemastery";
5
+ import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
6
+ import { h, isPhrasingContainer, normalize } from "@deepseek-ai/satori-element";
7
+ // \0rolldown/runtime.js
8
+ var __defProp = Object.defineProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
18
+ // lib/types/errors.js
19
+ /** One failed Telegram Bot API call, with the fields `classify` needs. */
20
+ var TelegramApiError = class extends Error {
21
+ method;
22
+ status;
23
+ errorCode;
24
+ description;
25
+ retryAfterMs;
26
+ constructor(message, init) {
27
+ super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
28
+ this.name = "TelegramApiError";
29
+ this.method = init.method;
30
+ this.status = init.status;
31
+ this.errorCode = init.errorCode;
32
+ this.description = init.description;
33
+ this.retryAfterMs = init.retryAfterMs;
34
+ }
35
+ };
36
+ /**
37
+ * Map any failure onto the core platform taxonomy.
38
+ *
39
+ * Telegram answers content and permission refusals with a JSON error code, so
40
+ * those are certainly unpublished; transport failures and 5xx answers leave
41
+ * the outcome unknown.
42
+ *
43
+ * @param error - the caught failure.
44
+ * @returns the classified platform error.
45
+ */
46
+ function classifyTelegramError(error) {
47
+ if (error instanceof PlatformError) return error;
48
+ if (error instanceof TelegramApiError) {
49
+ const code = error.errorCode ?? error.status;
50
+ const init = {
51
+ ...code === void 0 ? {} : { code },
52
+ ...error.retryAfterMs === void 0 ? {} : { retryAfterMs: error.retryAfterMs },
53
+ cause: error
54
+ };
55
+ if (code === 429) return new PlatformError("rate-limit", error.message, {
56
+ ...init,
57
+ published: "no"
58
+ });
59
+ if (code === 401 || code === 403) return new PlatformError("permission", error.message, {
60
+ ...init,
61
+ published: "no"
62
+ });
63
+ if (code === 404) return new PlatformError("not-found", error.message, {
64
+ ...init,
65
+ published: "no"
66
+ });
67
+ if (code !== void 0 && code >= 500) return new PlatformError("retryable", error.message, {
68
+ ...init,
69
+ published: "unknown"
70
+ });
71
+ if (code !== void 0 && code >= 400) return new PlatformError("invalid", error.message, {
72
+ ...init,
73
+ published: "no"
74
+ });
75
+ return new PlatformError("retryable", error.message, {
76
+ ...init,
77
+ published: "unknown"
78
+ });
79
+ }
80
+ if (error instanceof Error && error.name === "AbortError") return new PlatformError("fatal", error.message, {
81
+ published: "unknown",
82
+ cause: error
83
+ });
84
+ const message = error instanceof Error ? error.message : String(error);
85
+ return new PlatformError("retryable", `telegram request failed: ${message}`, {
86
+ published: "unknown",
87
+ cause: error
88
+ });
89
+ }
90
+ /** Whether an API failure means the requested edit changed nothing. */
91
+ function isNotModified(error) {
92
+ return error instanceof TelegramApiError && error.errorCode === 400 && (error.description ?? "").includes("message is not modified");
93
+ }
94
+ // lib/types/request.js
95
+ /**
96
+ * Telegram Bot API transport: one POST path for every method, envelope and
97
+ * error handling, multipart bodies, and file download.
98
+ *
99
+ * The typed method surface lives on `Internal`; this module owns the shared
100
+ * wire mechanics so the generated client and the upload paths cannot diverge.
101
+ */
102
+ /**
103
+ * Build the request endpoints for one bot token.
104
+ *
105
+ * @param ctx - context whose `http` service performs requests.
106
+ * @param token - bot token, appended to the API origin.
107
+ * @param apiBaseUrl - Bot API base URL.
108
+ * @param filesBaseUrl - file download base URL.
109
+ * @returns the shared request endpoints.
110
+ */
111
+ function createTelegramRequest(ctx, token, apiBaseUrl, filesBaseUrl) {
112
+ return {
113
+ ctx,
114
+ token,
115
+ origin: `${apiBaseUrl.replace(/\/+$/, "")}/bot${token}`,
116
+ filesBase: filesBaseUrl.replace(/\/+$/, "")
117
+ };
118
+ }
119
+ /**
120
+ * Invoke one Bot API method through the shared envelope and error path.
121
+ *
122
+ * @param request - endpoints for this bot.
123
+ * @param method - Bot API method name.
124
+ * @param payload - JSON body or multipart form.
125
+ * @param signal - cancellation.
126
+ * @returns the method's `result` field.
127
+ */
128
+ async function invoke(request, method, payload, signal) {
129
+ let response;
130
+ try {
131
+ response = await request.ctx.http(`${request.origin}/${method}`, {
132
+ method: "POST",
133
+ data: payload ?? {},
134
+ ...signal === void 0 ? {} : { signal }
135
+ });
136
+ } catch (cause) {
137
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal);
138
+ const failed = responseOf(cause);
139
+ if (failed !== void 0) {
140
+ const failedBody = await failed.json().catch(() => void 0);
141
+ if (failedBody !== void 0 && typeof failedBody === "object") throw failure(method, failed.status, failedBody);
142
+ }
143
+ throw new TelegramApiError(`telegram ${method} request failed`, {
144
+ method,
145
+ cause
146
+ });
147
+ }
148
+ const body = await response.json().catch(() => void 0);
149
+ if (body === void 0 || typeof body !== "object") {
150
+ if (signal?.aborted === true) throw signal.reason;
151
+ throw new TelegramApiError(`telegram ${method} answered ${response.status} without a JSON envelope`, {
152
+ method,
153
+ status: response.status
154
+ });
155
+ }
156
+ if (!body.ok) throw failure(method, response.status, body);
157
+ return body.result;
158
+ }
159
+ /**
160
+ * Download one file the platform hosts.
161
+ *
162
+ * @param request - endpoints for this bot.
163
+ * @param filePath - `file_path` of a `getFile` answer.
164
+ * @param signal - cancellation.
165
+ * @returns the response whose body is the file.
166
+ */
167
+ async function downloadFile(request, filePath, signal) {
168
+ const url = `${request.filesBase}/file/bot${request.token}/${filePath.replace(/^\/+/, "")}`;
169
+ return await request.ctx.http(url, signal === void 0 ? {} : { signal });
170
+ }
171
+ /**
172
+ * Send one multipart media form (`sendPhoto`, `sendVideo`, …).
173
+ *
174
+ * @param request - endpoints for this bot.
175
+ * @param method - Bot API send method.
176
+ * @param form - multipart body.
177
+ * @param signal - cancellation.
178
+ * @returns the sent message.
179
+ */
180
+ function sendMedia(request, method, form, signal) {
181
+ return invoke(request, method, form, signal);
182
+ }
183
+ /**
184
+ * Send one `sendMediaGroup` multipart form.
185
+ *
186
+ * @param request - endpoints for this bot.
187
+ * @param form - multipart body.
188
+ * @param signal - cancellation.
189
+ * @returns the sent messages.
190
+ */
191
+ function sendMediaGroup(request, form, signal) {
192
+ return invoke(request, "sendMediaGroup", form, signal);
193
+ }
194
+ function failure(method, status, body) {
195
+ const retryAfter = body.parameters?.retry_after;
196
+ return new TelegramApiError(`telegram ${method} answered ${body.error_code ?? status}${body.description === void 0 ? "" : `: ${body.description}`}`, {
197
+ method,
198
+ status,
199
+ ...body.error_code === void 0 ? {} : { errorCode: body.error_code },
200
+ ...body.description === void 0 ? {} : { description: body.description },
201
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter * 1e3 }
202
+ });
203
+ }
204
+ /**
205
+ * Whether a failed request was cancelled, either because its signal is aborted or because the failure it produced is
206
+ * an abort.
207
+ *
208
+ * @param cause - the value `ctx.http` rejected with.
209
+ * @param signal - the cancellation signal handed to the request.
210
+ * @returns true when the request was cancelled rather than rejected by the transport.
211
+ */
212
+ function isCancellation(cause, signal) {
213
+ if (signal?.aborted === true) return true;
214
+ if (isAbortError(cause)) return true;
215
+ return signal?.reason !== void 0 && cause === signal.reason;
216
+ }
217
+ /**
218
+ * The value a cancelled request rejects with: the signal's reason, so the classifier recognises the cancellation
219
+ * instead of a wrapped transport failure.
220
+ *
221
+ * @param cause - the value `ctx.http` rejected with.
222
+ * @param signal - the cancellation signal handed to the request.
223
+ * @returns the abort error to rethrow.
224
+ */
225
+ function cancellation(cause, signal) {
226
+ return signal?.aborted === true ? signal.reason : cause;
227
+ }
228
+ /** Whether a caught value is an abort error, including the `DOMException` a signal produces. */
229
+ function isAbortError(cause) {
230
+ return (cause instanceof Error || cause instanceof DOMException) && cause.name === "AbortError";
231
+ }
232
+ /** The HTTP service's failure carries the response it refused; recover it structurally. */
233
+ function responseOf(cause) {
234
+ if (typeof cause !== "object" || cause === null || !("response" in cause)) return void 0;
235
+ const response = cause.response;
236
+ return response instanceof Response ? response : void 0;
237
+ }
238
+ // lib/types/types/internal.js
239
+ /**
240
+ * Client for every Bot API method declared in this directory.
241
+ *
242
+ * Each declaration file ends with `Internal.define('methodName')` calls; this
243
+ * class turns them into prototype methods over the shared transport in
244
+ * `request.ts`, so the full upstream method surface stays callable
245
+ * without duplicating method bodies. The `declare module './internal.ts'`
246
+ * blocks in those files provide the parameter and return types.
247
+ */
248
+ var Internal = class Internal {
249
+ request;
250
+ constructor(request) {
251
+ this.request = request;
252
+ }
253
+ /**
254
+ * Register one Bot API method from a declaration file.
255
+ * @param method - Bot API method name.
256
+ */
257
+ static define(method) {
258
+ Object.defineProperty(Internal.prototype, method, {
259
+ configurable: true,
260
+ writable: true,
261
+ value: async function(data = {}, signal) {
262
+ return await invoke(this.request, method, data, signal);
263
+ }
264
+ });
265
+ }
266
+ };
267
+ // lib/types/types/inline.js
268
+ Internal.define("answerInlineQuery");
269
+ Internal.define("answerWebAppQuery");
270
+ // lib/types/types/game.js
271
+ Internal.define("sendGame");
272
+ Internal.define("setGameScore");
273
+ Internal.define("getGameHighScores");
274
+ // lib/types/types/passport.js
275
+ Internal.define("setPassportDataErrors");
276
+ // lib/types/types/payment.js
277
+ Internal.define("sendInvoice");
278
+ Internal.define("createInvoiceLink");
279
+ Internal.define("answerShippingQuery");
280
+ Internal.define("answerPreCheckoutQuery");
281
+ // lib/types/types/sticker.js
282
+ Internal.define("sendSticker");
283
+ Internal.define("getStickerSet");
284
+ Internal.define("getCustomEmojiStickers");
285
+ Internal.define("uploadStickerFile");
286
+ Internal.define("createNewStickerSet");
287
+ Internal.define("addStickerToSet");
288
+ Internal.define("setStickerPositionInSet");
289
+ Internal.define("deleteStickerFromSet");
290
+ Internal.define("setStickerSetThumb");
291
+ // lib/types/types/update.js
292
+ Internal.define("getUpdates");
293
+ Internal.define("setWebhook");
294
+ Internal.define("deleteWebhook");
295
+ Internal.define("getWebhookInfo");
296
+ // lib/types/types/index.js
297
+ var types_exports = /* @__PURE__ */ __exportAll({ Internal: () => Internal });
298
+ Internal.define("getMe");
299
+ Internal.define("logOut");
300
+ Internal.define("close");
301
+ Internal.define("sendMessage");
302
+ Internal.define("forwardMessage");
303
+ Internal.define("copyMessage");
304
+ Internal.define("sendPhoto");
305
+ Internal.define("sendAudio");
306
+ Internal.define("sendDocument");
307
+ Internal.define("sendVideo");
308
+ Internal.define("sendAnimation");
309
+ Internal.define("sendVoice");
310
+ Internal.define("sendVideoNote");
311
+ Internal.define("sendMediaGroup");
312
+ Internal.define("sendLocation");
313
+ Internal.define("editMessageLiveLocation");
314
+ Internal.define("stopMessageLiveLocation");
315
+ Internal.define("sendVenue");
316
+ Internal.define("sendContact");
317
+ Internal.define("sendPoll");
318
+ Internal.define("sendDice");
319
+ Internal.define("sendChatAction");
320
+ Internal.define("getUserProfilePhotos");
321
+ Internal.define("getFile");
322
+ Internal.define("banChatMember");
323
+ Internal.define("unbanChatMember");
324
+ Internal.define("restrictChatMember");
325
+ Internal.define("promoteChatMember");
326
+ Internal.define("setChatAdministratorCustomTitle");
327
+ Internal.define("banChatSenderChat");
328
+ Internal.define("unbanChatSenderChat");
329
+ Internal.define("setChatPermissions");
330
+ Internal.define("exportChatInviteLink");
331
+ Internal.define("createChatInviteLink");
332
+ Internal.define("editChatInviteLink");
333
+ Internal.define("revokeChatInviteLink");
334
+ Internal.define("approveChatJoinRequest");
335
+ Internal.define("declineChatJoinRequest");
336
+ Internal.define("setChatPhoto");
337
+ Internal.define("deleteChatPhoto");
338
+ Internal.define("setChatTitle");
339
+ Internal.define("setChatDescription");
340
+ Internal.define("pinChatMessage");
341
+ Internal.define("unpinChatMessage");
342
+ Internal.define("unpinAllChatMessages");
343
+ Internal.define("leaveChat");
344
+ Internal.define("getChat");
345
+ Internal.define("getChatAdministrators");
346
+ Internal.define("getChatMemberCount");
347
+ Internal.define("getChatMember");
348
+ Internal.define("setChatStickerSet");
349
+ Internal.define("deleteChatStickerSet");
350
+ Internal.define("getForumTopicIconStickers");
351
+ Internal.define("createForumTopic");
352
+ Internal.define("editForumTopic");
353
+ Internal.define("closeForumTopic");
354
+ Internal.define("reopenForumTopic");
355
+ Internal.define("deleteForumTopic");
356
+ Internal.define("unpinAllForumTopicMessages");
357
+ Internal.define("editGeneralForumTopic");
358
+ Internal.define("closeGeneralForumTopic");
359
+ Internal.define("reopenGeneralForumTopic");
360
+ Internal.define("hideGeneralForumTopic");
361
+ Internal.define("unhideGeneralForumTopic");
362
+ Internal.define("answerCallbackQuery");
363
+ Internal.define("setMyCommands");
364
+ Internal.define("deleteMyCommands");
365
+ Internal.define("getMyCommands");
366
+ Internal.define("setChatMenuButton");
367
+ Internal.define("getChatMenuButton");
368
+ Internal.define("setMyDefaultAdministratorRights");
369
+ Internal.define("getMyDefaultAdministratorRights");
370
+ Internal.define("editMessageText");
371
+ Internal.define("editMessageCaption");
372
+ Internal.define("editMessageMedia");
373
+ Internal.define("editMessageReplyMarkup");
374
+ Internal.define("stopPoll");
375
+ Internal.define("deleteMessage");
376
+ // lib/types/config.js
377
+ /** Validated Telegram adapter configuration. */
378
+ const Config = z.object({
379
+ token: z.string().role("secret").required(),
380
+ transport: z.union(["polling", "webhook"]).default("polling"),
381
+ dropPendingUpdates: z.boolean().default(true),
382
+ apiBaseUrl: z.string().role("url").default("https://api.telegram.org"),
383
+ files: z.object({
384
+ baseUrl: z.string().role("url"),
385
+ local: z.boolean().default(false)
386
+ }).default({}),
387
+ polling: z.object({
388
+ timeoutMs: z.natural().role("ms").default(25e3),
389
+ retryTimes: z.natural().default(6),
390
+ retryIntervalMs: z.natural().role("ms").default(5e3),
391
+ retryLazyMs: z.natural().role("ms").default(6e4),
392
+ mediaGroupWindowMs: z.natural().role("ms").default(1200)
393
+ }).default({}),
394
+ webhook: z.object({
395
+ path: z.string().default("/telegram/webhook"),
396
+ publicUrl: z.string().role("url"),
397
+ maxBodyBytes: z.natural().default(1048576)
398
+ }).default({}),
399
+ media: z.object({
400
+ stagingTtlMs: z.natural().role("ms").default(6e5),
401
+ maxStagedBytes: z.natural().default(67108864)
402
+ }).default({}),
403
+ linkPreview: z.boolean().default(true)
404
+ });
405
+ // lib/types/identity.js
406
+ /** Failure to derive the bot identity from the configured token. */
407
+ var TelegramIdentityError = class extends Error {
408
+ constructor(message) {
409
+ super(message);
410
+ this.name = "TelegramIdentityError";
411
+ }
412
+ };
413
+ /**
414
+ * The bot id encoded in a Bot API token.
415
+ * @param token - `<bot id>:<secret>`.
416
+ * @returns the numeric bot id as text.
417
+ */
418
+ function botIdFromToken(token) {
419
+ const [id] = token.split(":");
420
+ if (id === void 0 || !/^\d+$/.test(id)) throw new TelegramIdentityError("telegram: token must look like \"<bot id>:<secret>\"");
421
+ return id;
422
+ }
423
+ /**
424
+ * Verify a `getMe` answer against the token prefix.
425
+ * @param token - the configured Bot API token.
426
+ * @param user - the `getMe` result.
427
+ * @returns the bot's numeric id.
428
+ */
429
+ function verifyIdentity(token, user) {
430
+ const expected = botIdFromToken(token);
431
+ const actual = String(user.id);
432
+ if (actual !== expected) throw new TelegramIdentityError(`telegram: token belongs to bot ${expected} but getMe returned bot ${actual}`);
433
+ return actual;
434
+ }
435
+ // lib/types/media.js
436
+ /**
437
+ * Bounded in-memory staging for outbound media.
438
+ *
439
+ * Telegram has no standalone upload endpoint: bytes must ride the `sendPhoto`
440
+ * / `sendMediaGroup` multipart request. `upload` fetches and stages them, and
441
+ * `sendPayload` reads them back by key. Entries expire and the whole store is
442
+ * bounded, so a long-lived bot cannot grow without limit; a retried send still
443
+ * finds its bytes until the TTL elapses.
444
+ */
445
+ var MediaStaging = class {
446
+ ttlMs;
447
+ maxBytes;
448
+ entries = /* @__PURE__ */ new Map();
449
+ bytes = 0;
450
+ constructor(ttlMs, maxBytes) {
451
+ this.ttlMs = ttlMs;
452
+ this.maxBytes = maxBytes;
453
+ }
454
+ /**
455
+ * Stage bytes under a fresh opaque key.
456
+ * @param media - the bytes and their display name.
457
+ * @returns the resource key `prepare` hands to `serialize`.
458
+ */
459
+ stage(media) {
460
+ const now = Date.now();
461
+ this.prune(now);
462
+ const key = `tg-media:${randomUUID()}`;
463
+ const bytes = media.data.byteLength;
464
+ this.entries.set(key, {
465
+ media,
466
+ bytes,
467
+ expiresAt: now + this.ttlMs
468
+ });
469
+ this.bytes += bytes;
470
+ this.evict(now);
471
+ return {
472
+ key,
473
+ expiresAt: now + this.ttlMs
474
+ };
475
+ }
476
+ /**
477
+ * Read staged bytes back.
478
+ * @param key - a key returned by {@link stage}.
479
+ * @returns the staged media, or undefined once expired or evicted.
480
+ */
481
+ get(key) {
482
+ this.prune(Date.now());
483
+ return this.entries.get(key)?.media;
484
+ }
485
+ prune(now) {
486
+ for (const [key, entry] of this.entries) {
487
+ if (entry.expiresAt > now) continue;
488
+ this.entries.delete(key);
489
+ this.bytes -= entry.bytes;
490
+ }
491
+ }
492
+ evict(now) {
493
+ while (this.bytes > this.maxBytes) {
494
+ const oldest = this.entries.keys().next();
495
+ if (oldest.done === true) return;
496
+ const entry = this.entries.get(oldest.value);
497
+ this.entries.delete(oldest.value);
498
+ if (entry !== void 0) this.bytes -= entry.bytes;
499
+ }
500
+ this.prune(now);
501
+ }
502
+ };
503
+ // lib/types/modes/shared.js
504
+ /** Telegram's documented bounds, shared by both modes. */
505
+ const TELEGRAM_LIMITS = {
506
+ text: 4096,
507
+ caption: 1024,
508
+ parts: 10,
509
+ buttonsPerRow: 5,
510
+ streamIntervalMs: 1e3,
511
+ deleteWindowMs: 1728e5
512
+ };
513
+ /**
514
+ * Media element → the node of its own platform message.
515
+ *
516
+ * Telegram has no inline media, and a `parse_mode` message carries no attachment, so media never stays inside a
517
+ * text run. Media that stood in phrasing content (`<p>`, a heading, a link, an inline wrapper) is reported as
518
+ * `moved`: the caller sees the message as text plus an extra media message instead of one block.
519
+ *
520
+ * @param el - one of `img`/`audio`/`video`/`file`.
521
+ * @param ctx - render context of the mode.
522
+ * @returns the media node, to be published after the text run it was found in.
523
+ */
524
+ function mediaNode(el, ctx) {
525
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
526
+ if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
527
+ tag: el.type,
528
+ reason: "telegram-media-split",
529
+ path: ctx.stableId(el)
530
+ });
531
+ switch (el.type) {
532
+ case "img": return {
533
+ type: "media",
534
+ ref: ctx.resource("image", el.attrs.src, {}),
535
+ kind: "photo"
536
+ };
537
+ case "video": return {
538
+ type: "media",
539
+ ref: ctx.resource("video", el.attrs.src, {}),
540
+ kind: "video"
541
+ };
542
+ case "audio": return {
543
+ type: "media",
544
+ ref: ctx.resource("audio", el.attrs.src, {}),
545
+ kind: "audio"
546
+ };
547
+ case "file": return {
548
+ type: "media",
549
+ ref: ctx.resource("file", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
550
+ kind: "document"
551
+ };
552
+ }
553
+ }
554
+ /** Escape character data for `parse_mode: HTML`. */
555
+ function escapeHtml(text) {
556
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
557
+ }
558
+ /** Escape one HTML attribute value. */
559
+ function escapeAttribute(text) {
560
+ return escapeHtml(text).replaceAll("\"", "&quot;");
561
+ }
562
+ /**
563
+ * Concatenate the text nodes of a subtree, dropping non-text nodes.
564
+ *
565
+ * Only for a context that holds a label and nothing else (a button caption); content handlers go through
566
+ * {@link textRun} so that a media element reaches `assemble` instead of disappearing.
567
+ */
568
+ function inlineText(nodes) {
569
+ let html = "";
570
+ for (const node of nodes) if (node.type === "text") html += node.html;
571
+ else if (node.type === "button") html += escapeHtml(node.button.text);
572
+ return html;
573
+ }
574
+ /**
575
+ * Split rendered children into the text run of one platform message and the nodes Telegram posts on their own.
576
+ *
577
+ * Inline wrappers (`p`, `b`, `a`, `li`, …) use this instead of concatenating text: a media element of the subtree
578
+ * has to reach `assemble`, which turns it into a media message, rather than being dropped from the run.
579
+ *
580
+ * @param nodes - rendered children.
581
+ * @returns the text HTML of the run and the non-text nodes, both in source order.
582
+ */
583
+ function textRun(nodes) {
584
+ let html = "";
585
+ const rest = [];
586
+ for (const node of nodes) if (node.type === "text") html += node.html;
587
+ else rest.push(node);
588
+ return {
589
+ html,
590
+ nodes: rest
591
+ };
592
+ }
593
+ /** Split markup into tags, entities and code points so cuts never break a tag. */
594
+ function tokenize(html) {
595
+ const tokens = [];
596
+ let i = 0;
597
+ while (i < html.length) {
598
+ const char = html[i];
599
+ if (char === "<") {
600
+ const end = html.indexOf(">", i);
601
+ if (end === -1) {
602
+ tokens.push({
603
+ raw: html.slice(i),
604
+ visible: 0,
605
+ newline: false
606
+ });
607
+ break;
608
+ }
609
+ tokens.push({
610
+ raw: html.slice(i, end + 1),
611
+ visible: 0,
612
+ newline: false
613
+ });
614
+ i = end + 1;
615
+ continue;
616
+ }
617
+ if (char === "&") {
618
+ const end = html.indexOf(";", i);
619
+ if (end !== -1 && end - i <= 10) {
620
+ tokens.push({
621
+ raw: html.slice(i, end + 1),
622
+ visible: 1,
623
+ newline: false
624
+ });
625
+ i = end + 1;
626
+ continue;
627
+ }
628
+ }
629
+ const codePoint = html.codePointAt(i);
630
+ const raw = String.fromCodePoint(codePoint);
631
+ tokens.push({
632
+ raw,
633
+ visible: 1,
634
+ newline: raw === "\n"
635
+ });
636
+ i += raw.length;
637
+ }
638
+ return tokens;
639
+ }
640
+ /** Visible (after entity parsing) length of rendered HTML. */
641
+ function visibleLength(html) {
642
+ let length = 0;
643
+ for (const token of tokenize(html)) length += token.visible;
644
+ return length;
645
+ }
646
+ /** Tag name of an opening tag, or undefined for a closing/self-closing tag. */
647
+ function openTagName(raw) {
648
+ if (!raw.startsWith("<") || raw.startsWith("</") || raw.startsWith("<!")) return void 0;
649
+ return (/^<([a-zA-Z][\w-]*)/.exec(raw)?.[1])?.toLowerCase();
650
+ }
651
+ /**
652
+ * Split rendered HTML into chunks no longer than `limit` visible characters,
653
+ * closing and reopening inline tags at every cut so each message parses alone.
654
+ */
655
+ function splitHtml(html, limit) {
656
+ if (visibleLength(html) <= limit) return [html];
657
+ const chunks = [];
658
+ let current = "";
659
+ let visible = 0;
660
+ const stack = [];
661
+ const closeAll = () => stack.map((tag) => `</${tag.name}>`).reverse().join("");
662
+ const reopenAll = () => stack.map((tag) => tag.open).join("");
663
+ const flush = () => {
664
+ if (current === "") return;
665
+ chunks.push(current + closeAll());
666
+ current = reopenAll();
667
+ visible = 0;
668
+ };
669
+ for (const token of tokenize(html)) {
670
+ if (token.visible > 0 && visible + token.visible > limit) flush();
671
+ current += token.raw;
672
+ visible += token.visible;
673
+ const name = openTagName(token.raw);
674
+ if (name !== void 0 && !token.raw.endsWith("/>")) stack.push({
675
+ name,
676
+ open: token.raw
677
+ });
678
+ else if (token.raw.startsWith("</")) stack.pop();
679
+ }
680
+ if (current !== "") chunks.push(current + closeAll());
681
+ return chunks;
682
+ }
683
+ /** Group consecutive media into albums Telegram accepts. */
684
+ function groupMedia(items) {
685
+ const groups = [];
686
+ for (const item of items) {
687
+ const current = groups[groups.length - 1];
688
+ const mixable = (a, b) => {
689
+ const visual = (kind) => kind === "photo" || kind === "video" || kind === "animation";
690
+ return visual(a) && visual(b) || a === b;
691
+ };
692
+ if (current === void 0 || current.length >= TELEGRAM_LIMITS.parts || !current.every((other) => mixable(other.kind, item.kind))) groups.push([item]);
693
+ else current.push(item);
694
+ }
695
+ return groups;
696
+ }
697
+ /** Lay buttons into rows of at most five. */
698
+ function layoutButtons(buttons) {
699
+ const rows = [];
700
+ let row = [];
701
+ for (const button of buttons) {
702
+ if (row.length >= TELEGRAM_LIMITS.buttonsPerRow) {
703
+ rows.push(row);
704
+ row = [];
705
+ }
706
+ row.push(button);
707
+ }
708
+ if (row.length > 0) rows.push(row);
709
+ return rows;
710
+ }
711
+ /**
712
+ * Fold a node stream into platform messages.
713
+ *
714
+ * Text before a media element becomes its caption when it fits; otherwise it
715
+ * stays a text message. Consecutive media are grouped into albums, and all
716
+ * buttons are attached to the last message.
717
+ */
718
+ function assembleDraft(nodes) {
719
+ const drafts = [];
720
+ let text = "";
721
+ let media = [];
722
+ let caption;
723
+ let buttons = [];
724
+ const flushText = () => {
725
+ const trimmed = text.trim();
726
+ if (trimmed === "") {
727
+ text = "";
728
+ return;
729
+ }
730
+ for (const chunk of splitHtml(trimmed, TELEGRAM_LIMITS.text)) drafts.push({
731
+ text: chunk,
732
+ media: [],
733
+ buttons: []
734
+ });
735
+ text = "";
736
+ };
737
+ const flushMedia = () => {
738
+ if (media.length === 0) return;
739
+ const groups = groupMedia(media);
740
+ for (const [index, group] of groups.entries()) drafts.push({
741
+ text: index === 0 ? caption ?? "" : "",
742
+ media: group,
743
+ buttons: []
744
+ });
745
+ media = [];
746
+ caption = void 0;
747
+ };
748
+ for (const node of nodes) switch (node.type) {
749
+ case "text":
750
+ if (media.length > 0) {
751
+ if (text.trim() !== "") flushText();
752
+ flushMedia();
753
+ }
754
+ text += node.html;
755
+ break;
756
+ case "media":
757
+ if (media.length === 0) {
758
+ if (text.trim() !== "") {
759
+ if (visibleLength(text.trim()) <= TELEGRAM_LIMITS.caption) {
760
+ caption = text.trim();
761
+ text = "";
762
+ } else flushText();
763
+ }
764
+ }
765
+ media.push({
766
+ ref: node.ref,
767
+ kind: node.kind
768
+ });
769
+ break;
770
+ case "button": buttons.push(node.button);
771
+ }
772
+ flushMedia();
773
+ flushText();
774
+ const rows = layoutButtons(buttons);
775
+ if (rows.length > 0) {
776
+ const last = drafts[drafts.length - 1];
777
+ if (last !== void 0) last.buttons = rows;
778
+ else drafts.push({
779
+ text: "⁠",
780
+ media: [],
781
+ buttons: rows
782
+ });
783
+ }
784
+ return drafts;
785
+ }
786
+ /** Resolve one media key from `prepared.resolved`. */
787
+ function resolvedKey(prepared, ref) {
788
+ const resolved = prepared.resolved.get(ref);
789
+ if (resolved === void 0) throw new Error("telegram: media was not prepared before serialize");
790
+ return resolved.key;
791
+ }
792
+ /** Build the request payload of one draft. */
793
+ function serializeDraft(prepared, ctx, parseMode) {
794
+ const { draft } = prepared;
795
+ const threadId = typeof ctx.target.thread === "string" && /^\d+$/.test(ctx.target.thread) ? Number(ctx.target.thread) : void 0;
796
+ const replyTo = ctx.index === 0 && ctx.quote !== void 0 && /^\d+$/.test(ctx.quote) ? Number(ctx.quote) : void 0;
797
+ const buttons = draft.buttons.length === 0 ? void 0 : draft.buttons.map((row) => row.map(toWireButton));
798
+ if (draft.media.length === 0) return {
799
+ kind: "text",
800
+ chatId: ctx.target.chat.id,
801
+ ...threadId === void 0 ? {} : { threadId },
802
+ ...replyTo === void 0 ? {} : { replyTo },
803
+ ...parseMode === void 0 ? {} : { parseMode },
804
+ text: draft.text,
805
+ ...buttons === void 0 ? {} : { buttons }
806
+ };
807
+ const media = draft.media.map((item) => ({
808
+ kind: item.kind,
809
+ key: resolvedKey(prepared, item.ref),
810
+ name: item.ref.meta.name ?? ""
811
+ }));
812
+ return {
813
+ kind: media.length > 1 ? "album" : "media",
814
+ chatId: ctx.target.chat.id,
815
+ ...threadId === void 0 ? {} : { threadId },
816
+ ...replyTo === void 0 ? {} : { replyTo },
817
+ ...parseMode === void 0 ? {} : { parseMode },
818
+ ...draft.text.trim() === "" ? {} : { caption: draft.text.trim() },
819
+ media,
820
+ ...buttons === void 0 ? {} : { buttons }
821
+ };
822
+ }
823
+ /**
824
+ * Hard platform limits of one draft, checked before any request.
825
+ *
826
+ * Only `callback_data` can fail here. The three other bounds the platform
827
+ * documents are unreachable by construction: `splitHtml` cuts text at
828
+ * `TELEGRAM_LIMITS.text`, `assembleDraft` keeps a caption only when it fits
829
+ * `TELEGRAM_LIMITS.caption` (longer text stays a text message), and
830
+ * `groupMedia` caps an album at `TELEGRAM_LIMITS.parts`.
831
+ *
832
+ * @param draft - the assembled draft.
833
+ * @returns every violation the platform would refuse.
834
+ */
835
+ function checkDraft(draft) {
836
+ const violations = [];
837
+ for (const row of draft.buttons) for (const button of row) {
838
+ if (button.kind !== "callback") continue;
839
+ const bytes = Buffer.byteLength(button.data ?? "", "utf8");
840
+ if (bytes <= 64) continue;
841
+ violations.push({
842
+ kind: "size",
843
+ key: "limit.payload.bytes",
844
+ limit: 64,
845
+ actual: bytes,
846
+ message: `Telegram callback_data accepts 64 bytes, got ${bytes}`
847
+ });
848
+ }
849
+ return violations;
850
+ }
851
+ /** Convert one collected button into Telegram's wire shape. */
852
+ function toWireButton(button) {
853
+ return button.kind === "link" ? {
854
+ text: button.text,
855
+ url: button.url ?? ""
856
+ } : {
857
+ text: button.text,
858
+ callback_data: button.data ?? ""
859
+ };
860
+ }
861
+ // lib/types/modes/html.js
862
+ /**
863
+ * `html` mode: Telegram's `parse_mode: HTML`.
864
+ *
865
+ * Native tags are the documented subset (`b`/`i`/`u`/`s`/`a`/`code`/`pre`/
866
+ * `blockquote`/`tg-spoiler`); everything else either becomes text inside a
867
+ * draft or takes the core fallback. Media is sent as separate media messages
868
+ * (albums for consecutive items) — including media that stood inside an inline
869
+ * wrapper, which is lifted out of the text run and reported as moved — and
870
+ * action, link and submit buttons become an inline keyboard. An `input` button
871
+ * has no native form control here, so it takes the core fallback.
872
+ */
873
+ /** Wrap the text of `children` in one inline tag; media of the subtree follows as its own message. */
874
+ function wrap(tag, ctx, children) {
875
+ const { html, nodes } = textRun(ctx.render(children));
876
+ return [...html === "" ? [] : [{
877
+ type: "text",
878
+ html: `<${tag}>${html}</${tag}>`
879
+ }], ...nodes];
880
+ }
881
+ /** Render a heading as a bold line, then the media of the heading, then the paragraph break. */
882
+ function heading(ctx, children) {
883
+ const { html, nodes } = textRun(ctx.render(children));
884
+ return [
885
+ ...html === "" ? [] : [{
886
+ type: "text",
887
+ html: `<b>${html}</b>`
888
+ }],
889
+ ...nodes,
890
+ {
891
+ type: "text",
892
+ html: "\n\n"
893
+ }
894
+ ];
895
+ }
896
+ /** Build the `html` mode. */
897
+ function createHtmlMode() {
898
+ return {
899
+ id: "html",
900
+ elements: new ElementRegistry().register("text", (el) => ({
901
+ type: "text",
902
+ html: escapeHtml(el.attrs.content)
903
+ })).register("br", () => ({
904
+ type: "text",
905
+ html: "\n"
906
+ })).register("p", (el, ctx) => [...ctx.render(el.children), {
907
+ type: "text",
908
+ html: "\n\n"
909
+ }]).register("b", (el, ctx) => wrap("b", ctx, el.children)).register("i", (el, ctx) => wrap("i", ctx, el.children)).register("u", (el, ctx) => wrap("u", ctx, el.children)).register("s", (el, ctx) => wrap("s", ctx, el.children)).register("spoiler", (el, ctx) => wrap("tg-spoiler", ctx, el.children)).register("blockquote", (el, ctx) => wrap("blockquote", ctx, el.children)).register("code", (el, ctx) => ({
910
+ type: "text",
911
+ html: `<code>${escapeHtml(ctx.text(el.children))}</code>`
912
+ })).register("pre", (el, ctx) => {
913
+ const text = escapeHtml(ctx.text(el.children));
914
+ const language = el.attrs.lang;
915
+ return {
916
+ type: "text",
917
+ html: language === void 0 ? `<pre>${text}</pre>` : `<pre><code class="language-${escapeAttribute(language)}">${text}</code></pre>`
918
+ };
919
+ }).register("a", (el, ctx) => {
920
+ const { html, nodes } = textRun(ctx.render(el.children));
921
+ const label = html === "" ? escapeHtml(el.attrs.href) : html;
922
+ return [{
923
+ type: "text",
924
+ html: `<a href="${escapeAttribute(el.attrs.href)}">${label}</a>`
925
+ }, ...nodes];
926
+ }).register("at", (el) => {
927
+ if (el.attrs.id !== void 0 && el.attrs.type === "user") {
928
+ const label = escapeHtml(el.attrs.name ?? el.attrs.id);
929
+ return {
930
+ type: "text",
931
+ html: `<a href="tg://user?id=${escapeAttribute(el.attrs.id)}">${label}</a>`
932
+ };
933
+ }
934
+ return {
935
+ type: "text",
936
+ html: escapeHtml(`@${el.attrs.name ?? el.attrs.type}`)
937
+ };
938
+ }, { variants: [
939
+ "user",
940
+ "all",
941
+ "here",
942
+ "role"
943
+ ] }).register("h1", (el, ctx) => heading(ctx, el.children)).register("h2", (el, ctx) => heading(ctx, el.children)).register("h3", (el, ctx) => heading(ctx, el.children)).register("h4", (el, ctx) => heading(ctx, el.children)).register("h5", (el, ctx) => heading(ctx, el.children)).register("h6", (el, ctx) => heading(ctx, el.children)).register("ul", (el, ctx) => ctx.render(el.children)).register("ol", (el, ctx) => ctx.render(el.children)).register("li", (el, ctx) => {
944
+ const { html, nodes } = textRun(ctx.render(el.children));
945
+ return [
946
+ ...html === "" ? [] : [{
947
+ type: "text",
948
+ html: `• ${html}`
949
+ }],
950
+ ...nodes,
951
+ {
952
+ type: "text",
953
+ html: "\n"
954
+ }
955
+ ];
956
+ }).register("hr", () => ({
957
+ type: "text",
958
+ html: "\n—\n"
959
+ })).register("img", (el, ctx) => mediaNode(el, ctx), { variants: ["inline"] }).register("video", (el, ctx) => mediaNode(el, ctx)).register("audio", (el, ctx) => mediaNode(el, ctx)).register("file", (el, ctx) => mediaNode(el, ctx)).register("emoji", (el) => ({
960
+ type: "text",
961
+ html: escapeHtml(el.attrs.name ?? "")
962
+ })).register("channel", (el) => ({
963
+ type: "text",
964
+ html: escapeHtml(el.attrs.name ?? "")
965
+ })).register("small", (el, ctx) => ctx.render(el.children)).register("button", (el, ctx) => {
966
+ if (el.attrs.type === "link") return {
967
+ type: "button",
968
+ button: {
969
+ kind: "link",
970
+ text: ctx.text(el.children).trim() || el.attrs.href,
971
+ url: el.attrs.href
972
+ }
973
+ };
974
+ if (el.attrs.type === "input") return {
975
+ type: "text",
976
+ html: escapeHtml(ctx.text(el.children).trim() || el.attrs.text)
977
+ };
978
+ return {
979
+ type: "button",
980
+ button: {
981
+ kind: "callback",
982
+ text: ctx.text(el.children).trim() || el.attrs.id,
983
+ data: el.attrs.id
984
+ }
985
+ };
986
+ }, { variants: [
987
+ "action",
988
+ "link",
989
+ "submit"
990
+ ] }),
991
+ limits: {
992
+ "limit.text.chars": TELEGRAM_LIMITS.text,
993
+ "limit.buttons.row": TELEGRAM_LIMITS.buttonsPerRow,
994
+ "limit.stream.interval": TELEGRAM_LIMITS.streamIntervalMs,
995
+ "limit.message.parts": TELEGRAM_LIMITS.parts,
996
+ "limit.delete.window": TELEGRAM_LIMITS.deleteWindowMs
997
+ },
998
+ assemble: (nodes) => assembleDraft(nodes),
999
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx, "HTML"),
1000
+ check: (draft) => checkDraft(draft)
1001
+ };
1002
+ }
1003
+ // lib/types/modes/plain.js
1004
+ /**
1005
+ * `plain` mode: no `parse_mode`, no formatting, no inline keyboard.
1006
+ *
1007
+ * Text is sent verbatim; links keep only their label, mentions become
1008
+ * `@name`, and buttons degrade to text lines. Media still goes out as media
1009
+ * messages — including media that stood inside an inline wrapper, which is
1010
+ * lifted out of the text run and reported as moved — so a platform that
1011
+ * refuses HTML can still receive the content.
1012
+ */
1013
+ /** Build the `plain` mode. */
1014
+ function createPlainMode() {
1015
+ return {
1016
+ id: "plain",
1017
+ elements: new ElementRegistry().register("text", (el) => ({
1018
+ type: "text",
1019
+ html: el.attrs.content
1020
+ })).register("br", () => ({
1021
+ type: "text",
1022
+ html: "\n"
1023
+ })).register("p", (el, ctx) => [...ctx.render(el.children), {
1024
+ type: "text",
1025
+ html: "\n\n"
1026
+ }]).register("a", (el, ctx) => {
1027
+ const { html, nodes } = textRun(ctx.render(el.children));
1028
+ return [{
1029
+ type: "text",
1030
+ html: html === "" ? el.attrs.href : html
1031
+ }, ...nodes];
1032
+ }).register("at", (el) => ({
1033
+ type: "text",
1034
+ html: `@${el.attrs.name ?? (el.attrs.type === "user" ? el.attrs.id : void 0) ?? el.attrs.type}`
1035
+ }), { variants: [
1036
+ "user",
1037
+ "all",
1038
+ "here",
1039
+ "role"
1040
+ ] }).register("img", (el, ctx) => mediaNode(el, ctx), { variants: ["inline"] }).register("video", (el, ctx) => mediaNode(el, ctx)).register("audio", (el, ctx) => mediaNode(el, ctx)).register("file", (el, ctx) => mediaNode(el, ctx)).register("button", (el, ctx) => ({
1041
+ type: "text",
1042
+ html: `[${inlineText(ctx.render(el.children)).trim() || (el.attrs.type === "link" ? el.attrs.href : el.attrs.type === "input" ? el.attrs.text : el.attrs.id)}]\n`
1043
+ }), { variants: [
1044
+ "action",
1045
+ "link",
1046
+ "submit"
1047
+ ] }),
1048
+ limits: {
1049
+ "limit.text.chars": TELEGRAM_LIMITS.text,
1050
+ "limit.stream.interval": TELEGRAM_LIMITS.streamIntervalMs,
1051
+ "limit.message.parts": TELEGRAM_LIMITS.parts,
1052
+ "limit.delete.window": TELEGRAM_LIMITS.deleteWindowMs
1053
+ },
1054
+ assemble: (nodes) => assembleDraft(nodes),
1055
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx, void 0),
1056
+ check: (draft) => checkDraft(draft)
1057
+ };
1058
+ }
1059
+ // lib/types/decode.js
1060
+ /**
1061
+ * Inbound decoding: one Telegram update becomes either an intake `Session`
1062
+ * (`message`) or a button interaction session.
1063
+ *
1064
+ * Text runs through `entities` into the element vocabulary (bold, italic,
1065
+ * links, mentions, code, spoilers, quotes), media becomes resource elements
1066
+ * whose `src` is the bot's `satori:` file route, and everything the vocabulary
1067
+ * cannot express degrades to readable text. Only `message` and `callback_query`
1068
+ * updates are decoded; other update families are ignored.
1069
+ */
1070
+ /** Display name of a Telegram user. */
1071
+ function userName(user) {
1072
+ const name = [user.first_name, user.last_name].filter((part) => part !== void 0 && part !== "").join(" ");
1073
+ return name !== "" ? name : user.username ?? String(user.id);
1074
+ }
1075
+ /** Platform user reference. */
1076
+ function userRef(user) {
1077
+ return {
1078
+ id: String(user.id),
1079
+ name: userName(user),
1080
+ isBot: user.is_bot
1081
+ };
1082
+ }
1083
+ /** Chat reference; forum messages are `topic`, everything else is `group`. */
1084
+ function chatRef(chat, message) {
1085
+ const name = chat.title ?? [chat.first_name, chat.last_name].filter((part) => part !== void 0).join(" ");
1086
+ if (chat.type === "private") return {
1087
+ id: String(chat.id),
1088
+ type: "direct",
1089
+ ...name === "" ? {} : { name }
1090
+ };
1091
+ return {
1092
+ id: String(chat.id),
1093
+ type: message.is_topic_message === true ? "topic" : "group",
1094
+ ...name === "" ? {} : { name }
1095
+ };
1096
+ }
1097
+ /** Whether an entity type is one the vocabulary renders. */
1098
+ function entityTag(type) {
1099
+ switch (type) {
1100
+ case "bold": return "b";
1101
+ case "italic": return "i";
1102
+ case "underline": return "u";
1103
+ case "strikethrough": return "s";
1104
+ case "spoiler": return "spoiler";
1105
+ case "blockquote":
1106
+ case "expandable_blockquote": return "blockquote";
1107
+ case "code": return "code";
1108
+ case "pre": return "pre";
1109
+ default: return;
1110
+ }
1111
+ }
1112
+ /** Render a text range with its nested entities. */
1113
+ function renderRange(input, entities, from, to) {
1114
+ const nodes = [];
1115
+ let cursor = from;
1116
+ for (const entity of entities) {
1117
+ const start = entity.offset;
1118
+ const end = start + entity.length;
1119
+ if (start < cursor || end > to) continue;
1120
+ if (start > cursor) nodes.push(input.text.slice(cursor, start));
1121
+ const inner = renderRange(input, entities.filter((other) => other !== entity), start, end);
1122
+ const tag = entityTag(entity.type);
1123
+ if (tag !== void 0) switch (tag) {
1124
+ case "b":
1125
+ nodes.push(h("b", {}, ...inner));
1126
+ break;
1127
+ case "i":
1128
+ nodes.push(h("i", {}, ...inner));
1129
+ break;
1130
+ case "u":
1131
+ nodes.push(h("u", {}, ...inner));
1132
+ break;
1133
+ case "s":
1134
+ nodes.push(h("s", {}, ...inner));
1135
+ break;
1136
+ case "spoiler":
1137
+ nodes.push(h("spoiler", {}, ...inner));
1138
+ break;
1139
+ case "blockquote":
1140
+ nodes.push(h("blockquote", {}, ...inner));
1141
+ break;
1142
+ case "code":
1143
+ nodes.push(h("code", {}, ...inner));
1144
+ break;
1145
+ case "pre": nodes.push(h("pre", entity.language === void 0 ? {} : { lang: entity.language }, ...inner));
1146
+ }
1147
+ else if (entity.type === "text_link" && entity.url !== void 0) nodes.push(h("a", { href: entity.url }, ...inner));
1148
+ else if (entity.type === "text_mention" && entity.user !== void 0) nodes.push(h("at", {
1149
+ type: "user",
1150
+ id: String(entity.user.id),
1151
+ name: userName(entity.user)
1152
+ }));
1153
+ else nodes.push(...inner);
1154
+ cursor = end;
1155
+ }
1156
+ if (cursor < to) nodes.push(input.text.slice(cursor, to));
1157
+ return nodes;
1158
+ }
1159
+ /** Element tree of one text body. */
1160
+ function textNodes(input) {
1161
+ if (input.text === "") return [];
1162
+ return renderRange(input, [...input.entities ?? []].filter((entity) => entity.offset >= 0 && entity.length > 0 && entity.offset + entity.length <= input.text.length).sort((a, b) => a.offset - b.offset || b.length - a.length), 0, input.text.length);
1163
+ }
1164
+ /** The best photo size of a message (the last one is the largest). */
1165
+ function photoSize(message) {
1166
+ return message.photo?.[message.photo.length - 1];
1167
+ }
1168
+ /** One `satori:` URL for a Telegram file id. */
1169
+ function fileUrl(bot, fileId) {
1170
+ return bot.getInternalUrl(`/files/${encodeURIComponent(fileId)}`);
1171
+ }
1172
+ /** Media elements of one message. */
1173
+ function mediaNodes(bot, message) {
1174
+ const nodes = [];
1175
+ const photo = photoSize(message);
1176
+ if (photo !== void 0) nodes.push(h("img", { src: fileUrl(bot, photo.file_id) }));
1177
+ if (message.sticker !== void 0) {
1178
+ if (message.sticker.is_animated && message.sticker.thumbnail === void 0) nodes.push("[动画表情]");
1179
+ else {
1180
+ const fileId = message.sticker.thumbnail?.file_id ?? message.sticker.file_id;
1181
+ nodes.push(h("img", { src: fileUrl(bot, fileId) }));
1182
+ }
1183
+ }
1184
+ if (message.animation !== void 0) nodes.push(h("video", {
1185
+ src: fileUrl(bot, message.animation.file_id),
1186
+ ...message.animation.file_name === void 0 ? {} : { name: message.animation.file_name },
1187
+ duration: message.animation.duration
1188
+ }));
1189
+ if (message.video !== void 0) nodes.push(h("video", {
1190
+ src: fileUrl(bot, message.video.file_id),
1191
+ ...message.video.file_name === void 0 ? {} : { name: message.video.file_name },
1192
+ duration: message.video.duration
1193
+ }));
1194
+ if (message.voice !== void 0) nodes.push(h("audio", {
1195
+ src: fileUrl(bot, message.voice.file_id),
1196
+ name: "voice",
1197
+ duration: message.voice.duration
1198
+ }));
1199
+ if (message.audio !== void 0) nodes.push(h("audio", {
1200
+ src: fileUrl(bot, message.audio.file_id),
1201
+ ...message.audio.file_name === void 0 ? {} : { name: message.audio.file_name },
1202
+ duration: message.audio.duration
1203
+ }));
1204
+ if (message.document !== void 0) nodes.push(h("file", {
1205
+ src: fileUrl(bot, message.document.file_id),
1206
+ ...message.document.file_name === void 0 ? {} : { name: message.document.file_name }
1207
+ }));
1208
+ if (message.venue !== void 0) nodes.push(`[位置: ${message.venue.title} — ${message.venue.address}]`);
1209
+ else if (message.location !== void 0) nodes.push(`[位置: ${message.location.latitude}, ${message.location.longitude}]`);
1210
+ if (message.contact !== void 0) {
1211
+ const name = [message.contact.first_name, message.contact.last_name].filter((part) => part !== void 0).join(" ");
1212
+ nodes.push(`[联系人: ${name} ${message.contact.phone_number}]`);
1213
+ }
1214
+ return nodes;
1215
+ }
1216
+ /** Message body: caption/text entities plus media. */
1217
+ function contentNodes(bot, message) {
1218
+ const nodes = [...textNodes({
1219
+ text: message.text ?? message.caption ?? "",
1220
+ entities: message.entities ?? message.caption_entities
1221
+ }), ...mediaNodes(bot, message)];
1222
+ return nodes.length > 0 ? nodes : [h("raw", {
1223
+ platform: "telegram",
1224
+ type: "message",
1225
+ data: message
1226
+ })];
1227
+ }
1228
+ /** Mention flags and mentioned users of a message. */
1229
+ function mentionsOf(bot, message) {
1230
+ const users = [];
1231
+ let self = false;
1232
+ const username = bot.username?.toLowerCase();
1233
+ for (const entity of [...message.entities ?? [], ...message.caption_entities ?? []]) if (entity.type === "text_mention" && entity.user !== void 0) {
1234
+ const ref = userRef(entity.user);
1235
+ users.push(ref);
1236
+ if (ref.id === bot.selfId) self = true;
1237
+ } else if (entity.type === "mention") {
1238
+ const name = (message.text ?? message.caption ?? "").slice(entity.offset, entity.offset + entity.length).replace(/^@/, "");
1239
+ if (name === "") continue;
1240
+ users.push({
1241
+ id: name,
1242
+ name: `@${name}`
1243
+ });
1244
+ if (username !== void 0 && name.toLowerCase() === username) self = true;
1245
+ }
1246
+ if (!self && username !== void 0) {
1247
+ const body = message.text ?? message.caption ?? "";
1248
+ if (new RegExp(`(^|\\s)@${username}(\\s|$)`, "i").test(body)) self = true;
1249
+ }
1250
+ return {
1251
+ self,
1252
+ all: false,
1253
+ users
1254
+ };
1255
+ }
1256
+ /**
1257
+ * Decode one message into `InboundMessage`.
1258
+ * @param bot - the receiving adapter.
1259
+ * @param messages - one message, or every message of a merged media group (in order).
1260
+ * @returns the normalized inbound message.
1261
+ */
1262
+ function decodeMessage(bot, messages) {
1263
+ const [primary] = messages;
1264
+ if (primary === void 0) throw new Error("telegram: decodeMessage requires at least one message");
1265
+ const senderUser = primary.from ?? primary.sender_chat;
1266
+ const sender = senderUser === void 0 ? {
1267
+ id: "unknown",
1268
+ name: "unknown"
1269
+ } : "is_bot" in senderUser ? userRef(senderUser) : {
1270
+ id: String(senderUser.id),
1271
+ name: ("title" in senderUser ? senderUser.title : void 0) ?? String(senderUser.id)
1272
+ };
1273
+ const content = normalize(messages.flatMap((message) => contentNodes(bot, message)));
1274
+ const threadId = primary.message_thread_id;
1275
+ const date = primary.date * 1e3;
1276
+ const referrer = {
1277
+ chatId: String(primary.chat.id),
1278
+ messageId: String(primary.message_id),
1279
+ date,
1280
+ ...threadId === void 0 ? {} : { threadId: String(threadId) }
1281
+ };
1282
+ const ids = messages.map((message) => String(message.message_id));
1283
+ return {
1284
+ id: String(Math.min(...messages.map((message) => message.message_id))),
1285
+ ...ids.length < 2 ? {} : { aliases: ids.slice(1) },
1286
+ chat: chatRef(primary.chat, primary),
1287
+ ...threadId === void 0 || primary.is_topic_message !== true ? {} : { thread: { id: String(threadId) } },
1288
+ sender,
1289
+ content,
1290
+ ...primary.reply_to_message === void 0 || "forum_topic_created" in primary.reply_to_message ? {} : { quote: { id: String(primary.reply_to_message.message_id) } },
1291
+ mentions: mentionsOf(bot, primary),
1292
+ time: date,
1293
+ referrer,
1294
+ raw: messages.length === 1 ? primary : messages
1295
+ };
1296
+ }
1297
+ /**
1298
+ * Decode one Telegram update.
1299
+ * @param bot - the receiving adapter.
1300
+ * @param update - the update envelope.
1301
+ * @returns the session to publish, or undefined for an ignored update.
1302
+ */
1303
+ function decodeUpdate(bot, update) {
1304
+ if (update.message !== void 0) {
1305
+ const message = decodeMessage(bot, [update.message]);
1306
+ return bot.session({
1307
+ type: "message",
1308
+ id: message.id,
1309
+ timestamp: message.time,
1310
+ message,
1311
+ raw: update
1312
+ });
1313
+ }
1314
+ if (update.callback_query !== void 0) return decodeCallback(bot, update.callback_query);
1315
+ }
1316
+ /** Decode one button click. */
1317
+ function decodeCallback(bot, query) {
1318
+ if (query === void 0 || query.message === void 0) return void 0;
1319
+ const message = query.message;
1320
+ const chat = chatRef(message.chat, message);
1321
+ const referrer = {
1322
+ chatId: String(message.chat.id),
1323
+ messageId: String(message.message_id),
1324
+ date: message.date * 1e3,
1325
+ ...message.message_thread_id === void 0 ? {} : { threadId: String(message.message_thread_id) },
1326
+ callbackQueryId: query.id
1327
+ };
1328
+ const button = {
1329
+ id: query.data ?? "",
1330
+ ...query.data === void 0 ? {} : { data: query.data },
1331
+ referrer,
1332
+ time: Date.now(),
1333
+ bot,
1334
+ user: userRef(query.from),
1335
+ chat,
1336
+ message: {
1337
+ id: String(message.message_id),
1338
+ chat
1339
+ },
1340
+ respond: async (answer) => {
1341
+ await bot.internal.answerCallbackQuery({
1342
+ callback_query_id: query.id,
1343
+ ...answer.toast === void 0 ? {} : {
1344
+ text: answer.toast.content,
1345
+ show_alert: false
1346
+ }
1347
+ });
1348
+ }
1349
+ };
1350
+ return bot.session({
1351
+ type: "interaction/button",
1352
+ id: query.id,
1353
+ timestamp: Date.now(),
1354
+ button,
1355
+ raw: query
1356
+ });
1357
+ }
1358
+ // lib/types/polling.js
1359
+ /** Update families the adapter consumes */
1360
+ const ALLOWED_UPDATES = ["message", "callback_query"];
1361
+ /** Waitable sleep that resolves early on abort. */
1362
+ function sleep(ms, signal) {
1363
+ return new Promise((resolve) => {
1364
+ if (signal.aborted) {
1365
+ resolve();
1366
+ return;
1367
+ }
1368
+ const timer = setTimeout(() => {
1369
+ signal.removeEventListener("abort", onAbort);
1370
+ resolve();
1371
+ }, ms);
1372
+ const onAbort = () => {
1373
+ clearTimeout(timer);
1374
+ resolve();
1375
+ };
1376
+ signal.addEventListener("abort", onAbort, { once: true });
1377
+ });
1378
+ }
1379
+ /**
1380
+ * `getUpdates` long polling.
1381
+ *
1382
+ * The offset is the next update to fetch. It advances only after
1383
+ * `bot.receive` accepted an update, so a crash or a failed intake leaves the
1384
+ * update unacknowledged and Telegram redelivers it; the host's event dedupe
1385
+ * covers the frames already stored.
1386
+ */
1387
+ var TelegramPolling = class {
1388
+ bot;
1389
+ controller;
1390
+ running;
1391
+ offset = 0;
1392
+ constructor(bot) {
1393
+ this.bot = bot;
1394
+ }
1395
+ /** Register nothing; establish the offset and start the loop. */
1396
+ async start() {
1397
+ const { internal, config } = this.bot;
1398
+ try {
1399
+ if ((await internal.getWebhookInfo()).url !== "") {
1400
+ this.bot.ctx.logger.warn("telegram: removing the existing webhook so polling can receive updates");
1401
+ await internal.setWebhook({ url: "" });
1402
+ }
1403
+ if (config.dropPendingUpdates) {
1404
+ const highest = (await internal.getUpdates({
1405
+ offset: -1,
1406
+ limit: 1,
1407
+ timeout: 0
1408
+ })).reduce((max, update) => Math.max(max, update.update_id), -1);
1409
+ this.offset = highest + 1;
1410
+ }
1411
+ } catch (error) {
1412
+ this.bot.ctx.logger.error("telegram: long polling could not start: %s", error instanceof Error ? error.message : String(error));
1413
+ throw error;
1414
+ }
1415
+ this.controller = new AbortController();
1416
+ this.running = this.loop(this.controller.signal);
1417
+ this.bot.online();
1418
+ }
1419
+ /** Stop polling and wait for the loop to unwind. */
1420
+ async stop() {
1421
+ this.controller?.abort();
1422
+ this.controller = void 0;
1423
+ await this.running?.catch(() => void 0);
1424
+ this.running = void 0;
1425
+ }
1426
+ async loop(signal) {
1427
+ const { internal, config } = this.bot;
1428
+ let failures = 0;
1429
+ while (!signal.aborted) try {
1430
+ const updates = await internal.getUpdates({
1431
+ offset: this.offset,
1432
+ limit: 100,
1433
+ timeout: Math.max(1, Math.ceil(config.polling.timeoutMs / 1e3)),
1434
+ allowed_updates: ALLOWED_UPDATES
1435
+ }, signal);
1436
+ failures = 0;
1437
+ this.bot.online();
1438
+ await this.process(updates, signal);
1439
+ } catch (error) {
1440
+ if (signal.aborted) return;
1441
+ const classified = classifyTelegramError(error);
1442
+ this.bot.ctx.logger.warn("telegram: long polling failed: %s", classified.message);
1443
+ this.bot.status = Status.RECONNECT;
1444
+ const base = failures < config.polling.retryTimes ? config.polling.retryIntervalMs : config.polling.retryLazyMs;
1445
+ await sleep(classified.retryAfterMs ?? base, signal);
1446
+ failures += 1;
1447
+ }
1448
+ }
1449
+ async process(updates, signal) {
1450
+ let index = 0;
1451
+ while (index < updates.length) {
1452
+ const update = updates[index];
1453
+ const groupId = update.message?.media_group_id;
1454
+ if (groupId === void 0) {
1455
+ await this.publish(update);
1456
+ this.offset = update.update_id + 1;
1457
+ index += 1;
1458
+ continue;
1459
+ }
1460
+ const entries = [];
1461
+ while (index < updates.length) {
1462
+ const candidate = updates[index];
1463
+ const message = candidate.message;
1464
+ if (message === void 0 || message.media_group_id !== groupId) break;
1465
+ entries.push({
1466
+ updateId: candidate.update_id,
1467
+ message
1468
+ });
1469
+ index += 1;
1470
+ }
1471
+ await sleep(this.bot.config.polling.mediaGroupWindowMs, signal);
1472
+ if (signal.aborted) return;
1473
+ entries.sort((a, b) => a.message.message_id - b.message.message_id);
1474
+ const inbound = decodeMessage(this.bot, entries.map((entry) => entry.message));
1475
+ await this.bot.receive(this.bot.session({
1476
+ type: "message",
1477
+ id: inbound.id,
1478
+ timestamp: inbound.time,
1479
+ message: inbound
1480
+ }));
1481
+ this.offset = Math.max(this.offset, ...entries.map((entry) => entry.updateId + 1));
1482
+ }
1483
+ }
1484
+ async publish(update) {
1485
+ const session = decodeUpdate(this.bot, update);
1486
+ if (session !== void 0) await this.bot.receive(session);
1487
+ }
1488
+ };
1489
+ // lib/types/send.js
1490
+ /** Telegram method for one single-media payload. */
1491
+ function sendMethod(kind) {
1492
+ switch (kind) {
1493
+ case "photo": return "sendPhoto";
1494
+ case "video": return "sendVideo";
1495
+ case "audio": return "sendAudio";
1496
+ case "animation": return "sendAnimation";
1497
+ default: return "sendDocument";
1498
+ }
1499
+ }
1500
+ /** Multipart field name of one media kind. */
1501
+ function mediaField(kind) {
1502
+ switch (kind) {
1503
+ case "photo": return "photo";
1504
+ case "video": return "video";
1505
+ case "audio": return "audio";
1506
+ case "animation": return "animation";
1507
+ default: return "document";
1508
+ }
1509
+ }
1510
+ /** The inline keyboard a payload carries, if any. */
1511
+ function markupOf(payload) {
1512
+ return payload.buttons === void 0 ? void 0 : { inline_keyboard: payload.buttons };
1513
+ }
1514
+ /** Put the fields every send request shares into a multipart form. */
1515
+ function appendCommon(form, payload, threadId) {
1516
+ form.set("chat_id", payload.chatId);
1517
+ if (threadId !== void 0) form.set("message_thread_id", String(threadId));
1518
+ if (payload.replyTo !== void 0) form.set("reply_parameters", JSON.stringify({
1519
+ message_id: payload.replyTo,
1520
+ allow_sending_without_reply: true
1521
+ }));
1522
+ if (payload.caption !== void 0 && payload.caption !== "") {
1523
+ form.set("caption", payload.caption);
1524
+ if (payload.parseMode !== void 0) form.set("parse_mode", payload.parseMode);
1525
+ }
1526
+ const markup = markupOf(payload);
1527
+ if (markup !== void 0) form.set("reply_markup", JSON.stringify(markup));
1528
+ }
1529
+ /** Wrap staged bytes in a named blob for multipart upload. */
1530
+ function blobOf(staged) {
1531
+ return new Blob([staged.data], staged.mime === void 0 ? {} : { type: staged.mime });
1532
+ }
1533
+ /**
1534
+ * The published part of one sent message.
1535
+ *
1536
+ * @param message - the Telegram message the send answered with.
1537
+ * @param mediaKeys - staged media keys the request carried, when it carried media.
1538
+ * @returns the part, with the media keys recorded in `raw` for a later edit check.
1539
+ */
1540
+ function partOf(message, mediaKeys) {
1541
+ const id = message.message_id;
1542
+ if (id === void 0) throw new PlatformError("invalid", "telegram: the Bot API answered without a message id", { published: "unknown" });
1543
+ return {
1544
+ id: String(id),
1545
+ kind: "message",
1546
+ time: message.date === void 0 ? Date.now() : message.date * 1e3,
1547
+ ...message.message_thread_id === void 0 ? {} : { thread: { id: String(message.message_thread_id) } },
1548
+ ...mediaKeys === void 0 ? {} : { raw: { mediaKeys } }
1549
+ };
1550
+ }
1551
+ /** Media keys recorded in `SentPart.raw` by {@link partOf}, absent on a handle rebuilt after a restart. */
1552
+ function recordedMediaKeys(part) {
1553
+ const raw = part.raw;
1554
+ if (typeof raw !== "object" || raw === null || !("mediaKeys" in raw)) return void 0;
1555
+ const keys = raw.mediaKeys;
1556
+ return Array.isArray(keys) ? keys : void 0;
1557
+ }
1558
+ /** Whether an edit still targets the media the part was published with. */
1559
+ function sameMediaKeys(a, b) {
1560
+ return a.length === b.length && a.every((key, index) => key === b[index]);
1561
+ }
1562
+ /** Look one staged media item up, failing before any request when it expired. */
1563
+ function stagedOf(deps, key) {
1564
+ const staged = deps.staging.get(key);
1565
+ if (staged === void 0) throw new PlatformError("invalid", "telegram: the staged media bytes expired before send; nothing was published", { published: "no" });
1566
+ return staged;
1567
+ }
1568
+ /** Thread id carried by an adapter referrer, when the target asks to follow it. */
1569
+ function referrerThread(referrer) {
1570
+ if (typeof referrer !== "object" || referrer === null || !("threadId" in referrer)) return void 0;
1571
+ const value = referrer.threadId;
1572
+ return typeof value === "string" && /^\d+$/.test(value) ? Number(value) : void 0;
1573
+ }
1574
+ /**
1575
+ * Send one serialized payload.
1576
+ *
1577
+ * @param deps - adapter services.
1578
+ * @param payload - the serialized draft.
1579
+ * @param target - the chat (and thread) the payload goes to.
1580
+ * @param ctx - core send context (signal, part index).
1581
+ * @returns the published part.
1582
+ */
1583
+ async function sendPayload(deps, payload, target, ctx) {
1584
+ const signal = ctx.options.signal;
1585
+ const markup = markupOf(payload);
1586
+ const threadId = payload.threadId ?? (target.thread === true ? referrerThread(target.referrer) : void 0);
1587
+ if (payload.kind === "text") {
1588
+ const linkPreview = deps.config.linkPreview ? {} : { link_preview_options: { is_disabled: true } };
1589
+ return partOf(await deps.internal.sendMessage({
1590
+ chat_id: payload.chatId,
1591
+ text: payload.text ?? "",
1592
+ ...payload.parseMode === void 0 ? {} : { parse_mode: payload.parseMode },
1593
+ ...threadId === void 0 ? {} : { message_thread_id: threadId },
1594
+ ...payload.replyTo === void 0 ? {} : { reply_parameters: {
1595
+ message_id: payload.replyTo,
1596
+ allow_sending_without_reply: true
1597
+ } },
1598
+ ...markup === void 0 ? {} : { reply_markup: markup },
1599
+ ...linkPreview
1600
+ }, signal));
1601
+ }
1602
+ const items = payload.media ?? [];
1603
+ const first = items[0];
1604
+ if (first === void 0) throw new PlatformError("invalid", "telegram: media payload without media", { published: "no" });
1605
+ if (payload.kind === "album") {
1606
+ const form = new FormData();
1607
+ const media = items.map((item, index) => {
1608
+ form.append(`file${index}`, blobOf(stagedOf(deps, item.key)), item.name || `file${index}`);
1609
+ return {
1610
+ type: item.kind,
1611
+ media: `attach://file${index}`,
1612
+ ...index !== 0 || payload.caption === void 0 || payload.caption === "" ? {} : {
1613
+ caption: payload.caption,
1614
+ ...payload.parseMode === void 0 ? {} : { parse_mode: payload.parseMode }
1615
+ }
1616
+ };
1617
+ });
1618
+ form.set("chat_id", payload.chatId);
1619
+ if (threadId !== void 0) form.set("message_thread_id", String(threadId));
1620
+ if (payload.replyTo !== void 0) form.set("reply_parameters", JSON.stringify({
1621
+ message_id: payload.replyTo,
1622
+ allow_sending_without_reply: true
1623
+ }));
1624
+ form.set("media", JSON.stringify(media));
1625
+ const messages = await deps.sendMediaGroup(form, signal);
1626
+ const head = messages[0];
1627
+ if (head === void 0) throw new PlatformError("invalid", "telegram: sendMediaGroup returned no messages");
1628
+ const part = partOf(head, items.map((item) => item.key));
1629
+ const headId = head.message_id;
1630
+ const aliases = messages.slice(1).flatMap((message) => message.message_id === void 0 ? [] : [String(message.message_id)]);
1631
+ if (payload.buttons !== void 0 && payload.buttons.length > 0) {
1632
+ let keyboard;
1633
+ try {
1634
+ keyboard = await deps.internal.sendMessage({
1635
+ chat_id: payload.chatId,
1636
+ text: "⁠",
1637
+ ...payload.parseMode === void 0 ? {} : { parse_mode: payload.parseMode },
1638
+ ...threadId === void 0 ? {} : { message_thread_id: threadId },
1639
+ reply_parameters: {
1640
+ message_id: headId,
1641
+ allow_sending_without_reply: true
1642
+ },
1643
+ reply_markup: { inline_keyboard: payload.buttons }
1644
+ }, signal);
1645
+ } catch (error) {
1646
+ const cause = classifyTelegramError(error);
1647
+ throw new PlatformError(cause.kind, cause.message, {
1648
+ ...cause.code === void 0 ? {} : { code: cause.code },
1649
+ ...cause.retryAfterMs === void 0 ? {} : { retryAfterMs: cause.retryAfterMs },
1650
+ published: "unknown",
1651
+ cause
1652
+ });
1653
+ }
1654
+ aliases.push(String(keyboard.message_id));
1655
+ }
1656
+ return aliases.length === 0 ? part : {
1657
+ ...part,
1658
+ aliases
1659
+ };
1660
+ }
1661
+ const form = new FormData();
1662
+ appendCommon(form, payload, threadId);
1663
+ form.append(mediaField(first.kind), blobOf(stagedOf(deps, first.key)), first.name || "file");
1664
+ return partOf(await deps.sendMedia(sendMethod(first.kind), form, signal), [first.key]);
1665
+ }
1666
+ /**
1667
+ * Edit one published message in place.
1668
+ *
1669
+ * Text messages use `editMessageText`; media messages edit their caption. An
1670
+ * edit cannot replace the media, and a caption edit without a caption or a
1671
+ * keyboard would publish nothing, so both are refused for the caller to
1672
+ * withdraw and resend.
1673
+ *
1674
+ * @param deps - adapter services.
1675
+ * @param part - the published part.
1676
+ * @param payload - the freshly serialized draft.
1677
+ * @param handle - the message handle (carries the target chat).
1678
+ * @param signal - cancellation.
1679
+ */
1680
+ async function editPayload(deps, part, payload, handle, signal) {
1681
+ const messageId = Number(part.id);
1682
+ if (!Number.isSafeInteger(messageId)) throw new PlatformError("invalid", `telegram: "${part.id}" is not a Telegram message id`);
1683
+ const markup = payload.buttons === void 0 ? { inline_keyboard: [] } : { inline_keyboard: payload.buttons };
1684
+ try {
1685
+ if (payload.kind === "text") {
1686
+ await deps.internal.editMessageText({
1687
+ chat_id: handle.target.chat.id,
1688
+ message_id: messageId,
1689
+ text: payload.text ?? "",
1690
+ ...payload.parseMode === void 0 ? {} : { parse_mode: payload.parseMode },
1691
+ reply_markup: markup,
1692
+ ...deps.config.linkPreview ? {} : { link_preview_options: { is_disabled: true } }
1693
+ }, signal);
1694
+ return;
1695
+ }
1696
+ const caption = payload.caption ?? "";
1697
+ const recorded = recordedMediaKeys(part);
1698
+ if (recorded !== void 0) {
1699
+ if (!sameMediaKeys(recorded, (payload.media ?? []).map((item) => item.key))) throw new PlatformError("invalid", "telegram: an edit cannot replace media; withdraw and resend the message instead", { published: "no" });
1700
+ }
1701
+ if (caption === "" && (payload.buttons === void 0 || payload.buttons.length === 0)) throw new PlatformError("invalid", "telegram: a media edit needs a caption or a keyboard; withdraw and resend the message instead", { published: "no" });
1702
+ await deps.internal.editMessageCaption({
1703
+ chat_id: handle.target.chat.id,
1704
+ message_id: messageId,
1705
+ caption,
1706
+ ...payload.parseMode === void 0 ? {} : { parse_mode: payload.parseMode },
1707
+ reply_markup: markup
1708
+ }, signal);
1709
+ } catch (error) {
1710
+ if (isNotModified(error)) return;
1711
+ throw error;
1712
+ }
1713
+ }
1714
+ /**
1715
+ * Delete one published message.
1716
+ *
1717
+ * @param deps - adapter services.
1718
+ * @param part - the published part.
1719
+ * @param handle - the message handle (carries the target chat).
1720
+ */
1721
+ async function deletePart(deps, part, handle) {
1722
+ const messageId = Number(part.id);
1723
+ if (!Number.isSafeInteger(messageId)) throw new PlatformError("invalid", `telegram: "${part.id}" is not a Telegram message id`);
1724
+ await deps.internal.deleteMessage({
1725
+ chat_id: handle.target.chat.id,
1726
+ message_id: messageId
1727
+ });
1728
+ }
1729
+ // lib/types/secret.js
1730
+ /**
1731
+ * Domain-separation label for the derived webhook secret token. Changing it
1732
+ * invalidates every already-configured webhook, so treat it as a wire constant.
1733
+ */
1734
+ const WEBHOOK_SECRET_LABEL = "dsh-im-more/telegram/webhook/secret-token/v1";
1735
+ /**
1736
+ * Derive the `secret_token` Telegram echoes in
1737
+ * `X-Telegram-Bot-Api-Secret-Token`.
1738
+ *
1739
+ * The value is an HMAC of a fixed label keyed by the Bot API token: it is
1740
+ * stable for one bot, never exposes the token, and stays inside Telegram's
1741
+ * 1–256 character `A-Z a-z 0-9 _ -` alphabet because base64url uses that set.
1742
+ *
1743
+ * @param botToken - the Bot API token (`<bot_id>:<secret>`).
1744
+ * @returns a 43-character base64url secret token.
1745
+ */
1746
+ function deriveWebhookSecret(botToken) {
1747
+ return createHmac("sha256", botToken).update(WEBHOOK_SECRET_LABEL).digest("base64url");
1748
+ }
1749
+ /**
1750
+ * Compare a received secret-token header with the derived value in constant
1751
+ * time.
1752
+ *
1753
+ * @param expected - the derived secret token.
1754
+ * @param received - the header value, if the request carried one.
1755
+ * @returns whether the header matches.
1756
+ */
1757
+ function matchesWebhookSecret(expected, received) {
1758
+ if (received === void 0) return false;
1759
+ const expectedBytes = Buffer.from(expected);
1760
+ const receivedBytes = Buffer.from(received);
1761
+ return expectedBytes.length === receivedBytes.length && timingSafeEqual(expectedBytes, receivedBytes);
1762
+ }
1763
+ // lib/types/webhook.js
1764
+ /** Header Telegram echoes the configured secret token in. */
1765
+ const SECRET_HEADER = "x-telegram-bot-api-secret-token";
1766
+ /** Route path Telegram posts to: leading slash, no trailing slash. */
1767
+ function routePath(path) {
1768
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
1769
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
1770
+ }
1771
+ /** One request's bounded body. */
1772
+ async function readBody(request, limit) {
1773
+ const chunks = [];
1774
+ let size = 0;
1775
+ for await (const chunk of request) {
1776
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1777
+ size += buffer.byteLength;
1778
+ if (size > limit) return void 0;
1779
+ chunks.push(buffer);
1780
+ }
1781
+ return Buffer.concat(chunks).toString("utf8");
1782
+ }
1783
+ /**
1784
+ * Webhook transport over the profile's `ctx.webServer`.
1785
+ *
1786
+ * The route is anonymous at the Web server layer and authenticated by
1787
+ * Telegram's secret-token header, whose value the adapter derives from the
1788
+ * Bot API token. `connect` registers the route and calls `setWebhook`, so a
1789
+ * profile without `webServer` fails with an actionable message instead of
1790
+ * silently receiving nothing.
1791
+ */
1792
+ var TelegramWebhook = class {
1793
+ bot;
1794
+ dispose;
1795
+ constructor(bot) {
1796
+ this.bot = bot;
1797
+ }
1798
+ /** Register the route and point Telegram at it. */
1799
+ async start() {
1800
+ const webServer = this.bot.ctx.get("webServer");
1801
+ if (webServer === void 0) throw this.failStart("telegram: the webhook transport needs a profile-provided webServer; use transport \"polling\" instead");
1802
+ const publicUrl = this.bot.config.webhook.publicUrl;
1803
+ if (publicUrl === void 0 || publicUrl === null || publicUrl === "") throw this.failStart("telegram: webhook.publicUrl is required for the webhook transport");
1804
+ if (new URL(publicUrl).protocol !== "https:") throw this.failStart("telegram: webhook.publicUrl must be an https URL (Telegram refuses plain HTTP webhooks)");
1805
+ const path = routePath(this.bot.config.webhook.path);
1806
+ this.dispose = webServer.register({
1807
+ kind: "exact",
1808
+ path,
1809
+ auth: "anonymous",
1810
+ handler: (request, response) => this.handle(request, response)
1811
+ });
1812
+ try {
1813
+ await this.bot.internal.setWebhook({
1814
+ url: `${publicUrl.replace(/\/+$/, "")}${path}`,
1815
+ secret_token: deriveWebhookSecret(this.bot.config.token),
1816
+ drop_pending_updates: this.bot.config.dropPendingUpdates,
1817
+ allowed_updates: [...ALLOWED_UPDATES]
1818
+ });
1819
+ } catch (error) {
1820
+ this.dispose();
1821
+ this.dispose = void 0;
1822
+ this.bot.ctx.logger.error("telegram: setWebhook failed: %s", error instanceof Error ? error.message : String(error));
1823
+ throw error;
1824
+ }
1825
+ this.bot.online();
1826
+ }
1827
+ /** Release the route. The webhook itself stays registered so Telegram keeps retrying. */
1828
+ async stop() {
1829
+ this.dispose?.();
1830
+ this.dispose = void 0;
1831
+ }
1832
+ /**
1833
+ * Log a fatal start failure before the caller throws it, because `Bot.start`
1834
+ * only stores a connect failure on `bot.error`.
1835
+ *
1836
+ * @param message - error text that also names the corrective action.
1837
+ * @returns the error for the caller to throw.
1838
+ */
1839
+ failStart(message) {
1840
+ this.bot.ctx.logger.error(message);
1841
+ return new Error(message);
1842
+ }
1843
+ async handle(request, response) {
1844
+ try {
1845
+ if (request.method !== "POST") {
1846
+ response.writeHead(405, { allow: "POST" });
1847
+ response.end();
1848
+ return;
1849
+ }
1850
+ const expected = deriveWebhookSecret(this.bot.config.token);
1851
+ const received = request.headers[SECRET_HEADER];
1852
+ if (!matchesWebhookSecret(expected, typeof received === "string" ? received : void 0)) {
1853
+ response.writeHead(401);
1854
+ response.end();
1855
+ return;
1856
+ }
1857
+ const body = await readBody(request, this.bot.config.webhook.maxBodyBytes);
1858
+ if (body === void 0) {
1859
+ response.writeHead(413);
1860
+ response.end();
1861
+ return;
1862
+ }
1863
+ const update = JSON.parse(body);
1864
+ const session = decodeUpdate(this.bot, update);
1865
+ if (session !== void 0) await this.bot.receive(session);
1866
+ response.writeHead(200, { "content-type": "text/plain" });
1867
+ response.end("OK");
1868
+ } catch (error) {
1869
+ this.bot.ctx.logger.warn("telegram: webhook delivery failed: %s", error instanceof Error ? error.message : String(error));
1870
+ if (!response.headersSent) response.writeHead(500);
1871
+ response.end();
1872
+ }
1873
+ }
1874
+ };
1875
+ // lib/types/bot.js
1876
+ /** File extension of a MIME type, for the multipart part name. */
1877
+ function extensionOf(mime) {
1878
+ switch (mime) {
1879
+ case "image/png": return ".png";
1880
+ case "image/jpeg": return ".jpg";
1881
+ case "image/webp": return ".webp";
1882
+ case "image/gif": return ".gif";
1883
+ case "video/mp4": return ".mp4";
1884
+ case "video/webm": return ".webm";
1885
+ case "audio/mpeg": return ".mp3";
1886
+ case "audio/ogg": return ".ogg";
1887
+ case "application/pdf": return ".pdf";
1888
+ default: return "";
1889
+ }
1890
+ }
1891
+ /** MIME type by file extension for `files.local` reads; unknown extensions are binary. */
1892
+ const LOCAL_MIME_TYPES = {
1893
+ ".gif": "image/gif",
1894
+ ".jpeg": "image/jpeg",
1895
+ ".jpg": "image/jpeg",
1896
+ ".json": "application/json",
1897
+ ".m4a": "audio/mp4",
1898
+ ".mp3": "audio/mpeg",
1899
+ ".mp4": "video/mp4",
1900
+ ".oga": "audio/ogg",
1901
+ ".ogg": "audio/ogg",
1902
+ ".pdf": "application/pdf",
1903
+ ".png": "image/png",
1904
+ ".txt": "text/plain",
1905
+ ".wav": "audio/wav",
1906
+ ".webm": "video/webm",
1907
+ ".webp": "image/webp"
1908
+ };
1909
+ /** Content type of a locally stored Bot API file. */
1910
+ function localMimeType(filePath) {
1911
+ return LOCAL_MIME_TYPES[extname(filePath).toLowerCase()] ?? "application/octet-stream";
1912
+ }
1913
+ /** Whether a filesystem failure means the file does not exist. */
1914
+ function isMissingFile(error) {
1915
+ return error instanceof Error && error.code === "ENOENT";
1916
+ }
1917
+ /**
1918
+ * Telegram Bot API adapter.
1919
+ *
1920
+ * Identity comes from `getMe`; polling and webhook are the two transports;
1921
+ * `html` and `plain` are the two modes; outbound media is staged in memory and
1922
+ * sent as multipart, because Telegram has no standalone upload endpoint.
1923
+ */
1924
+ var TelegramBot = class extends Adapter {
1925
+ /** The adapter needs the Satori service and the isolated `http` service (official adapters declare `http` with `@Inject('http')`). */
1926
+ static inject = ["satori", "http"];
1927
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
1928
+ static Config = Config;
1929
+ modes = {
1930
+ html: createHtmlMode(),
1931
+ plain: createPlainMode()
1932
+ };
1933
+ modeOrder = ["html", "plain"];
1934
+ /** Endpoints shared by the Bot API client and file downloads. */
1935
+ request;
1936
+ /** Full typed Bot API surface registered by the vendored type declarations. */
1937
+ internal;
1938
+ /** Outbound media bytes between `prepare` and `sendPayload`. */
1939
+ staging;
1940
+ /** `@username` of the bot, once `getMe` answered. */
1941
+ username;
1942
+ transport;
1943
+ constructor(ctx, config) {
1944
+ super(ctx, config, {
1945
+ id: `telegram:${botIdFromToken(config.token)}`,
1946
+ platform: "telegram",
1947
+ adapter: "telegram"
1948
+ });
1949
+ this.request = createTelegramRequest(ctx, config.token, config.apiBaseUrl, config.files.baseUrl ?? config.apiBaseUrl);
1950
+ this.internal = new Internal(this.request);
1951
+ this.staging = new MediaStaging(config.media.stagingTtlMs, config.media.maxStagedBytes);
1952
+ this.defineInternalRoute("/files/:fileId", async ({ params }) => this.serveFile(params.fileId));
1953
+ }
1954
+ async connect() {
1955
+ try {
1956
+ const me = await this.internal.getMe();
1957
+ this.selfId = verifyIdentity(this.config.token, me);
1958
+ this.username = me.username;
1959
+ this.user = {
1960
+ id: this.selfId,
1961
+ name: me.username ?? me.first_name,
1962
+ isBot: true
1963
+ };
1964
+ } catch (error) {
1965
+ this.ctx.logger.error("telegram: connect failed: %s", error instanceof Error ? error.message : String(error));
1966
+ throw error;
1967
+ }
1968
+ this.transport = this.config.transport === "webhook" ? new TelegramWebhook(this) : new TelegramPolling(this);
1969
+ await this.transport.start();
1970
+ }
1971
+ async disconnect() {
1972
+ const transport = this.transport;
1973
+ this.transport = void 0;
1974
+ await transport?.stop();
1975
+ }
1976
+ async upload(ref, _scope, ctx) {
1977
+ const fetched = await ctx.fetch(ref.src, ctx.signal);
1978
+ const mime = ref.meta.mime ?? fetched.mime;
1979
+ const name = ref.meta.name ?? fetched.name ?? `telegram-${ref.kind}${extensionOf(mime)}`;
1980
+ return this.staging.stage({
1981
+ data: fetched.data,
1982
+ name,
1983
+ ...mime === void 0 ? {} : { mime }
1984
+ });
1985
+ }
1986
+ resourceScope(_target, _kind) {
1987
+ return this.id;
1988
+ }
1989
+ async sendPayload(payload, target, ctx) {
1990
+ return await sendPayload(this.sendDeps(), payload, target, ctx);
1991
+ }
1992
+ async editPayload(part, payload, handle, signal) {
1993
+ await editPayload(this.sendDeps(), part, payload, handle, signal);
1994
+ }
1995
+ async deletePart(part, handle) {
1996
+ await deletePart(this.sendDeps(), part, handle);
1997
+ }
1998
+ streamDriver(_mode, _target) {
1999
+ return createEditDriver(this);
2000
+ }
2001
+ classify(error) {
2002
+ return classifyTelegramError(error);
2003
+ }
2004
+ /**
2005
+ * Resolve one `satori:` file route.
2006
+ *
2007
+ * `files.local` reads the Bot API server's host filesystem; otherwise the
2008
+ * file is downloaded from the configured file endpoint.
2009
+ */
2010
+ async serveFile(fileId) {
2011
+ if (this.config.files.local) return await this.serveLocalFile(fileId);
2012
+ try {
2013
+ const file = await this.internal.getFile({ file_id: fileId });
2014
+ if (file.file_path === void 0) return new Response(null, { status: 404 });
2015
+ const response = await downloadFile(this.request, file.file_path);
2016
+ const headers = new Headers();
2017
+ const mime = response.headers.get("content-type");
2018
+ if (mime !== null) headers.set("content-type", mime);
2019
+ return new Response(response.body, {
2020
+ status: response.status,
2021
+ headers
2022
+ });
2023
+ } catch (error) {
2024
+ this.ctx.logger.warn("telegram: file %s could not be served: %s", fileId, error instanceof Error ? error.message : String(error));
2025
+ return new Response(null, { status: 502 });
2026
+ }
2027
+ }
2028
+ /**
2029
+ * Serve one file from the local Bot API server's filesystem, where
2030
+ * `file_path` is an absolute host path instead of a URL segment.
2031
+ */
2032
+ async serveLocalFile(fileId) {
2033
+ try {
2034
+ const file = await this.internal.getFile({ file_id: fileId });
2035
+ if (file.file_path === void 0) return new Response(null, { status: 404 });
2036
+ const data = await readFile(file.file_path);
2037
+ return new Response(data, {
2038
+ status: 200,
2039
+ headers: { "content-type": localMimeType(file.file_path) }
2040
+ });
2041
+ } catch (error) {
2042
+ if (isMissingFile(error)) return new Response(null, { status: 404 });
2043
+ this.ctx.logger.warn("telegram: file %s could not be served: %s", fileId, error instanceof Error ? error.message : String(error));
2044
+ return new Response(null, { status: 502 });
2045
+ }
2046
+ }
2047
+ sendDeps() {
2048
+ return {
2049
+ internal: this.internal,
2050
+ config: this.config,
2051
+ staging: this.staging,
2052
+ sendMedia: (method, form, signal) => this.sendMediaForm(method, form, signal),
2053
+ sendMediaGroup: (form, signal) => this.sendMediaGroupForm(form, signal)
2054
+ };
2055
+ }
2056
+ /** Send one multipart media form; overridable so send tests never touch the network. */
2057
+ sendMediaForm(method, form, signal) {
2058
+ return sendMedia(this.request, method, form, signal);
2059
+ }
2060
+ /** Send one `sendMediaGroup` multipart form. */
2061
+ sendMediaGroupForm(form, signal) {
2062
+ return sendMediaGroup(this.request, form, signal);
2063
+ }
2064
+ };
2065
+ export { Config, Internal, types_exports as Telegram, TelegramApiError, TelegramBot, TelegramBot as default, classifyTelegramError, deriveWebhookSecret, matchesWebhookSecret };
2066
+
2067
+ //# sourceMappingURL=index.js.map