@wirecat/tg-cli 0.98.0 → 0.100.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 (113) hide show
  1. package/README.md +2 -1
  2. package/dist/bin/tg.js +23 -28
  3. package/dist/bundle/adapter-2LVPMFKF.js +2790 -0
  4. package/dist/bundle/all-profiles-BLTK2AAB.js +255 -0
  5. package/dist/bundle/anthropic-RJE4XEOO.js +71 -0
  6. package/dist/bundle/bot-api-4XM3NVWG.js +39793 -0
  7. package/dist/bundle/bot-history-WVM5GEQN.js +167 -0
  8. package/dist/bundle/bun-UZXO2LRQ.js +169 -0
  9. package/dist/bundle/bun-sqlite-GJLGSQIT.js +70 -0
  10. package/dist/bundle/chunk-2IM4M7Q2.js +98 -0
  11. package/dist/bundle/chunk-2MXQ2EUN.js +1344 -0
  12. package/dist/bundle/chunk-2XUGPE5W.js +73 -0
  13. package/dist/bundle/chunk-3KHKYYCR.js +24782 -0
  14. package/dist/bundle/chunk-3MVHRZWR.js +2 -0
  15. package/dist/bundle/chunk-3N6LXAPE.js +724 -0
  16. package/dist/bundle/chunk-3QDPV34J.js +6668 -0
  17. package/dist/bundle/chunk-3S5CL55R.js +100 -0
  18. package/dist/bundle/chunk-4U7QOFDA.js +33511 -0
  19. package/dist/bundle/chunk-4VBDVZNE.js +524 -0
  20. package/dist/bundle/chunk-4YCLWWZ3.js +277 -0
  21. package/dist/bundle/chunk-66E5QDLH.js +24 -0
  22. package/dist/bundle/chunk-6VEOR6GD.js +166 -0
  23. package/dist/bundle/chunk-6YLT4YVJ.js +45 -0
  24. package/dist/bundle/chunk-7BFO3DY6.js +21 -0
  25. package/dist/bundle/chunk-A7OBVRJV.js +738 -0
  26. package/dist/bundle/chunk-AFV74GK3.js +50 -0
  27. package/dist/bundle/chunk-ASDZHG5I.js +25 -0
  28. package/dist/bundle/chunk-ATZ44Z77.js +3253 -0
  29. package/dist/bundle/chunk-AVWK4NCW.js +24600 -0
  30. package/dist/bundle/chunk-BAIZAZ6Q.js +82 -0
  31. package/dist/bundle/chunk-BJG6JA5U.js +35 -0
  32. package/dist/bundle/chunk-BL36RR34.js +285 -0
  33. package/dist/bundle/chunk-BZANDKWT.js +71 -0
  34. package/dist/bundle/chunk-CV5ASHTW.js +8170 -0
  35. package/dist/bundle/chunk-DN4QUTWU.js +78 -0
  36. package/dist/bundle/chunk-DVOUKGFK.js +1950 -0
  37. package/dist/bundle/chunk-GTURDJJD.js +570 -0
  38. package/dist/bundle/chunk-GYEOQS2D.js +2795 -0
  39. package/dist/bundle/chunk-H3X5LS6U.js +153 -0
  40. package/dist/bundle/chunk-HKT5EOT5.js +6848 -0
  41. package/dist/bundle/chunk-HXTTDIL7.js +82 -0
  42. package/dist/bundle/chunk-I6WZJVRT.js +1123 -0
  43. package/dist/bundle/chunk-JFJVS5JC.js +41 -0
  44. package/dist/bundle/chunk-JSKT5UZX.js +2315 -0
  45. package/dist/bundle/chunk-KE6L2UEG.js +3068 -0
  46. package/dist/bundle/chunk-LI7TXFLS.js +122 -0
  47. package/dist/bundle/chunk-MQNFEVAH.js +58 -0
  48. package/dist/bundle/chunk-MUEXF4ME.js +582 -0
  49. package/dist/bundle/chunk-OOOV3JBZ.js +35527 -0
  50. package/dist/bundle/chunk-OW3COBN5.js +1275 -0
  51. package/dist/bundle/chunk-P26LWFNZ.js +35 -0
  52. package/dist/bundle/chunk-Q26JMPBP.js +215 -0
  53. package/dist/bundle/chunk-QU2FJMFB.js +18282 -0
  54. package/dist/bundle/chunk-QY3YOOTP.js +18 -0
  55. package/dist/bundle/chunk-RDQMV6EU.js +46 -0
  56. package/dist/bundle/chunk-RER6DAHP.js +3514 -0
  57. package/dist/bundle/chunk-SGJYU3SB.js +54 -0
  58. package/dist/bundle/chunk-SMJTL5U7.js +117 -0
  59. package/dist/bundle/chunk-SYPL4PHV.js +76 -0
  60. package/dist/bundle/chunk-THVNP6S6.js +31 -0
  61. package/dist/bundle/chunk-U7LXA4SO.js +1007 -0
  62. package/dist/bundle/chunk-UD4DOZCN.js +886 -0
  63. package/dist/bundle/chunk-UMLPXNJI.js +63 -0
  64. package/dist/bundle/chunk-V4JSVH4M.js +190 -0
  65. package/dist/bundle/chunk-WE3LBRMB.js +2374 -0
  66. package/dist/bundle/chunk-WKOY3POD.js +452 -0
  67. package/dist/bundle/chunk-X4Y2ROJI.js +541 -0
  68. package/dist/bundle/chunk-YG7PNCSW.js +230 -0
  69. package/dist/bundle/chunk-Z2FHEIXN.js +63 -0
  70. package/dist/bundle/chunk-ZZLKX62Z.js +928 -0
  71. package/dist/bundle/command-contract-AIVKJYIR.js +31 -0
  72. package/dist/bundle/dist-RJMT44PL.js +7577 -0
  73. package/dist/bundle/echarts-YHSYUWLY.js +42501 -0
  74. package/dist/bundle/embed-3HGI2XIW.js +35 -0
  75. package/dist/bundle/embedder-2CJMZETJ.js +108 -0
  76. package/dist/bundle/entry-UVE53OV3.js +14 -0
  77. package/dist/bundle/first-run-6GYC2QS3.js +24 -0
  78. package/dist/bundle/first-screen-HRRLVLOG.js +29 -0
  79. package/dist/bundle/identity-HEV5E57G.js +11 -0
  80. package/dist/bundle/instructions-5UVAXSQV.js +9 -0
  81. package/dist/bundle/mcp-NWXBVNUA.js +165 -0
  82. package/dist/bundle/node-IUL5HSYI.js +2340 -0
  83. package/dist/bundle/node-UPPL626U.js +21 -0
  84. package/dist/bundle/node-YHYEGYVE.js +176 -0
  85. package/dist/bundle/node-sqlite-CQ33A3R2.js +46 -0
  86. package/dist/bundle/oauth-OB3JFAD7.js +18 -0
  87. package/dist/bundle/open-JHGZIXU2.js +20 -0
  88. package/dist/bundle/process-PSKS3N5B.js +91 -0
  89. package/dist/bundle/program-RPYVPNRX.js +1060 -0
  90. package/dist/bundle/prompt-7BXUMJGG.js +13 -0
  91. package/dist/bundle/proxy-transport-3EEMW2HW.js +17 -0
  92. package/dist/bundle/recognize-YMZPL47R.js +191 -0
  93. package/dist/bundle/remote-LQ3Q22NG.js +26 -0
  94. package/dist/bundle/rerank-SM7IYVXJ.js +49 -0
  95. package/dist/bundle/serve-GHUEP5H5.js +181 -0
  96. package/dist/bundle/server-A45HVXQY.js +178 -0
  97. package/dist/bundle/server-K2BQPPHN.js +785 -0
  98. package/dist/bundle/state-WIOL52GZ.js +30 -0
  99. package/dist/bundle/store-XE5AKUJZ.js +121 -0
  100. package/dist/bundle/store-maintenance-command-YS5E7VUN.js +46 -0
  101. package/dist/bundle/tg.js +40 -0
  102. package/dist/commands/context.d.ts.map +1 -1
  103. package/dist/commands/context.js +3 -2
  104. package/dist/commands/context.js.map +1 -1
  105. package/dist/telegram/errors.d.ts.map +1 -1
  106. package/dist/telegram/errors.js +1 -1
  107. package/dist/telegram/errors.js.map +1 -1
  108. package/dist/version.d.ts +1 -1
  109. package/dist/version.d.ts.map +1 -1
  110. package/dist/version.js +1 -1
  111. package/dist/version.js.map +1 -1
  112. package/package.json +5 -3
  113. package/skills/tg-cli/SKILL.md +2 -1
@@ -0,0 +1,738 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ openCache
5
+ } from "./chunk-3S5CL55R.js";
6
+ import {
7
+ CliError,
8
+ isCliError
9
+ } from "./chunk-WE3LBRMB.js";
10
+ import {
11
+ __name
12
+ } from "./chunk-AFV74GK3.js";
13
+
14
+ // dist/telegram/map.js
15
+ import { extname } from "node:path";
16
+ import { getMarkedPeerId, InputMedia, MessageReactions, PeersIndex, Message as TgMessage } from "@mtcute/node";
17
+
18
+ // dist/telegram/folder-rules.js
19
+ var KINDS = {
20
+ contacts: "contacts",
21
+ "non-contacts": "nonContacts",
22
+ groups: "groups",
23
+ channels: "broadcasts",
24
+ bots: "bots"
25
+ };
26
+ var SKIPS = { muted: "excludeMuted", read: "excludeRead", archived: "excludeArchived" };
27
+ var ruleFlags = /* @__PURE__ */ __name(({ include, skip }) => ({
28
+ ...include === void 0 ? {} : Object.fromEntries(Object.entries(KINDS).map(([kind, flag]) => [flag, include.includes(kind)])),
29
+ ...skip === void 0 ? {} : Object.fromEntries(Object.entries(SKIPS).map(([which, flag]) => [flag, skip.includes(which)]))
30
+ }), "ruleFlags");
31
+ var rulesOf = /* @__PURE__ */ __name((filter) => {
32
+ const include = Object.keys(KINDS).filter((kind) => filter[KINDS[kind]]);
33
+ const skip = Object.keys(SKIPS).filter((which) => filter[SKIPS[which]]);
34
+ return { ...include.length > 0 ? { include } : {}, ...skip.length > 0 ? { skip } : {} };
35
+ }, "rulesOf");
36
+
37
+ // dist/telegram/map.js
38
+ var seconds = /* @__PURE__ */ __name((at) => at > 0 ? new Date(at * 1e3).toISOString() : null, "seconds");
39
+ var toAccountSession = /* @__PURE__ */ __name((session) => ({
40
+ current: session.current === true,
41
+ client: [session.appName, session.appVersion].filter(Boolean).join(" ") || null,
42
+ device: [session.deviceModel, session.platform, session.systemVersion].filter(Boolean).join(", ") || null,
43
+ location: [session.region, session.country].filter(Boolean).join(", ") || null,
44
+ lastActiveAt: seconds(session.dateActive),
45
+ createdAt: seconds(session.dateCreated)
46
+ }), "toAccountSession");
47
+ var toTopic = /* @__PURE__ */ __name((topic) => ({
48
+ id: String(topic.id),
49
+ title: topic.title,
50
+ closed: topic.isClosed,
51
+ pinned: topic.isPinned,
52
+ unreadCount: topic.unreadCount,
53
+ lastMessageAt: topic.lastMessage?.date.toISOString() ?? null,
54
+ createdAt: topic.date.toISOString()
55
+ }), "toTopic");
56
+ var toInvitePreview = /* @__PURE__ */ __name((preview) => ({
57
+ kind: preview.type === "channel" ? "channel" : "group",
58
+ title: preview.title,
59
+ id: null,
60
+ username: null,
61
+ participantsCount: preview.memberCount,
62
+ description: null,
63
+ member: false,
64
+ approvalNeeded: preview.withApproval
65
+ }), "toInvitePreview");
66
+ var toLinkChat = /* @__PURE__ */ __name((chat) => ({
67
+ kind: chat.chatType === "channel" ? "channel" : "group",
68
+ title: chat.title,
69
+ id: String(chat.id),
70
+ username: chat.username,
71
+ participantsCount: groupMembersCount(chat),
72
+ description: chat.bio || null,
73
+ member: chat.isMember
74
+ }), "toLinkChat");
75
+ var toGroupMember = /* @__PURE__ */ __name((member) => ({
76
+ ...toMember(member.user),
77
+ role: member.status === "creator" ? "owner" : member.status === "admin" ? "admin" : "member",
78
+ lastSeenAt: member.user.lastOnline?.toISOString() ?? null,
79
+ joinedAt: member.joinedDate?.toISOString() ?? null,
80
+ invitedBy: member.invitedBy ? String(member.invitedBy.id) : null,
81
+ isBot: member.user.isBot,
82
+ deleted: member.user.isDeleted,
83
+ ...member.user.isScam ? { flagged: "scam" } : member.user.isFake ? { flagged: "fake" } : {},
84
+ hasPhoto: member.user.photo !== null
85
+ }), "toGroupMember");
86
+ var toMember = /* @__PURE__ */ __name((user) => ({
87
+ id: String(user.id),
88
+ name: user.displayName || null,
89
+ username: user.username
90
+ }), "toMember");
91
+ var toAccount = /* @__PURE__ */ __name((user) => ({
92
+ id: String(user.id),
93
+ name: user.displayName || null,
94
+ username: user.username
95
+ }), "toAccount");
96
+ var groupMembersCount = /* @__PURE__ */ __name((peer) => {
97
+ if (peer.type !== "chat")
98
+ return null;
99
+ return peer.membersCount || (peer.raw?._ === "chat" ? peer.raw.participantsCount : 0) || null;
100
+ }, "groupMembersCount");
101
+ var kindOf = /* @__PURE__ */ __name((peer) => {
102
+ if (peer.type === "user")
103
+ return peer.isSelf ? "saved" : "dialog";
104
+ if (peer.chatType === "channel")
105
+ return "channel";
106
+ return "group";
107
+ }, "kindOf");
108
+ var peerToChat = /* @__PURE__ */ __name((peer, extra = {}) => {
109
+ const metadata = compact({
110
+ isBot: peer.type === "user" ? peer.isBot || null : void 0,
111
+ isForum: peer.type === "chat" ? peer.isForum || null : void 0,
112
+ chatType: peer.type === "chat" ? peer.chatType : void 0,
113
+ username: peer.username ?? null,
114
+ ...extra
115
+ });
116
+ return {
117
+ id: String(peer.id),
118
+ title: peer.type === "user" && peer.isSelf ? "Saved Messages" : peer.displayName || null,
119
+ kind: kindOf(peer),
120
+ unreadCount: null,
121
+ lastMessageAt: null,
122
+ participantsCount: groupMembersCount(peer),
123
+ ...metadata ? { providerMetadata: metadata } : {}
124
+ };
125
+ }, "peerToChat");
126
+ var toChat = /* @__PURE__ */ __name((dialog) => ({
127
+ ...peerToChat(dialog.peer, { pinned: dialog.isPinned || null }),
128
+ unreadCount: dialog.unreadCount,
129
+ lastMessageAt: dialog.lastMessage?.date.toISOString() ?? null,
130
+ ...dialog.isMuted === null ? {} : { muted: dialog.isMuted },
131
+ archived: dialog.isArchived,
132
+ unreadMentions: dialog.unreadMentionsCount
133
+ }), "toChat");
134
+ var buttonOf = /* @__PURE__ */ __name(({ text, type }) => {
135
+ const kind = (() => {
136
+ switch (type._) {
137
+ case "inlineButtonTypeCallback":
138
+ return type.requiresPassword ? "other" : "callback";
139
+ case "inlineButtonTypeUrl":
140
+ return "link";
141
+ case "inlineButtonTypeWebView":
142
+ return "app";
143
+ case "inlineButtonTypeCopy":
144
+ return "clipboard";
145
+ default:
146
+ return "other";
147
+ }
148
+ })();
149
+ return { kind, text, ...type._ === "inlineButtonTypeUrl" ? { url: type.url } : {} };
150
+ }, "buttonOf");
151
+ var toButtons = /* @__PURE__ */ __name((markup) => markup?.type === "inline" && markup.buttons.some((row) => row.length > 0) ? markup.buttons.map((row) => row.map(buttonOf)) : void 0, "toButtons");
152
+ var toMessage = /* @__PURE__ */ __name((message) => {
153
+ const reply = message.replyToMessage;
154
+ const buttons = toButtons(message.markup);
155
+ const metadata = compact({
156
+ views: message.views ?? void 0,
157
+ forwards: message.forwards ?? void 0,
158
+ comments: message.replies?.hasComments ? message.replies.count : void 0,
159
+ groupedId: message.groupedIdUnique ?? void 0,
160
+ action: message.action?.type,
161
+ poll: message.media?.type === "poll" ? pollMetadata(message.media) : void 0,
162
+ link: linkOf(message),
163
+ graph: {
164
+ version: 1,
165
+ ...reply === null ? { reply: null } : reply?.id != null && !(reply.isForumTopic && reply.id === reply.threadId) ? { reply: { chatId: String(reply.chat?.id ?? message.chat.id), messageId: String(reply.id) } } : {},
166
+ ...message.replies?.hasComments && message.replies.discussion != null ? { discussionChatId: String(message.replies.discussion) } : {},
167
+ ...message.isAutomaticForward && message.forward?.raw.savedFromPeer && message.forward.raw.savedFromMsgId != null ? {
168
+ discussionSource: {
169
+ chatId: String(getMarkedPeerId(message.forward.raw.savedFromPeer)),
170
+ messageId: String(message.forward.raw.savedFromMsgId)
171
+ }
172
+ } : {}
173
+ }
174
+ });
175
+ return {
176
+ id: String(message.id),
177
+ chatId: String(message.chat.id),
178
+ senderId: String(message.sender.id),
179
+ senderName: message.sender.displayName || null,
180
+ ...message.sender.type === "chat" ? { senderIsChat: true } : {},
181
+ ...message.sender.type === "user" && message.sender.username ? { senderUsername: message.sender.username } : {},
182
+ timestamp: message.date.toISOString(),
183
+ editedAt: message.editDate?.toISOString() ?? null,
184
+ text: message.text,
185
+ outgoing: message.isOutgoing,
186
+ attachments: attachmentsOf(message.media),
187
+ replyTo: null,
188
+ ...reply?.id != null ? { replyToId: String(reply.id) } : {},
189
+ forwardedFrom: message.forward ? forwardOf(message) : null,
190
+ ...message.isTopicMessage && reply?.threadId != null ? { threadId: String(reply.threadId) } : {},
191
+ reactions: message.reactions ? reactionsOf(message.reactions) : null,
192
+ ...buttons ? { buttons } : {},
193
+ ...message.isScheduled ? { scheduledFor: message.date.toISOString() } : {},
194
+ ...metadata ? { providerMetadata: metadata } : {},
195
+ ...mentionsOf(message)
196
+ };
197
+ }, "toMessage");
198
+ var pollMetadata = /* @__PURE__ */ __name((poll) => {
199
+ const { question, voters, answers } = toPoll("", "", poll);
200
+ return { question, voters, answers: answers.map(({ text, voters: voters2 }) => ({ text, voters: voters2 })) };
201
+ }, "pollMetadata");
202
+ var toHistoryChannel = /* @__PURE__ */ __name((chats, id) => {
203
+ const chat = chats.find((one) => one._ === "channel" && one.id === id);
204
+ return chat?._ === "channel" && chat.accessHash ? { _: "inputChannel", channelId: chat.id, accessHash: chat.accessHash } : void 0;
205
+ }, "toHistoryChannel");
206
+ var toHistoryMessages = /* @__PURE__ */ __name((page) => {
207
+ const peers = PeersIndex.from(page);
208
+ return page.messages.filter((message) => message._ !== "messageEmpty").map((message) => toMessage(new TgMessage(message, peers)));
209
+ }, "toHistoryMessages");
210
+ var mentionsOf = /* @__PURE__ */ __name((message) => {
211
+ const ids = message.entities.flatMap(({ params }) => params.kind === "text_mention" ? [String(params.userId)] : []);
212
+ return ids.length > 0 ? { mentions: [...new Set(ids)] } : {};
213
+ }, "mentionsOf");
214
+ var linkOf = /* @__PURE__ */ __name((message) => {
215
+ try {
216
+ return message.link;
217
+ } catch {
218
+ return void 0;
219
+ }
220
+ }, "linkOf");
221
+ var forwardOf = /* @__PURE__ */ __name((message) => {
222
+ const forward = message.forward;
223
+ const sender = forward?.sender;
224
+ return {
225
+ id: forward?.fromMessageId != null ? String(forward.fromMessageId) : "",
226
+ senderId: sender && sender.type !== "anonymous" ? String(sender.id) : null,
227
+ senderName: sender?.displayName || null,
228
+ timestamp: forward?.date.toISOString() ?? null,
229
+ // The text of a forward is the message's own text in Telegram; a second copy would print twice.
230
+ text: "",
231
+ attachments: [],
232
+ outgoing: null
233
+ };
234
+ }, "forwardOf");
235
+ var reactionsOf = /* @__PURE__ */ __name((reactions) => {
236
+ const counts = reactions.reactions.map((one) => ({
237
+ reaction: typeof one.emoji === "string" ? one.emoji : `custom:${String(one.emoji)}`,
238
+ count: one.count,
239
+ mine: one.order !== null
240
+ }));
241
+ return {
242
+ counts: counts.map(({ reaction, count }) => ({ reaction, count })),
243
+ mine: counts.find((one) => one.mine)?.reaction ?? null,
244
+ total: counts.reduce((sum, one) => sum + one.count, 0)
245
+ };
246
+ }, "reactionsOf");
247
+ var attachmentsOf = /* @__PURE__ */ __name((media) => {
248
+ if (!media)
249
+ return [];
250
+ const read = /* @__PURE__ */ __name((name2) => {
251
+ if (!(name2 in media))
252
+ return void 0;
253
+ const value = media[name2];
254
+ return value === null || value === "" ? void 0 : value;
255
+ }, "read");
256
+ const attachment = { kind: media.type };
257
+ const name = read("fileName");
258
+ const mime = read("mimeType");
259
+ const size = read("fileSize");
260
+ const width = read("width");
261
+ const height = read("height");
262
+ const duration = read("duration");
263
+ if (typeof width === "number")
264
+ attachment.width = width;
265
+ if (typeof height === "number")
266
+ attachment.height = height;
267
+ if (name !== void 0)
268
+ attachment.name = name;
269
+ if (typeof size === "number")
270
+ attachment.size = size;
271
+ if (mime !== void 0)
272
+ attachment.mime = mime;
273
+ if (typeof duration === "number")
274
+ attachment.duration = duration;
275
+ return [attachment];
276
+ }, "attachmentsOf");
277
+ var compact = /* @__PURE__ */ __name((fields) => {
278
+ const kept = Object.entries(fields).filter(([, value]) => value !== void 0);
279
+ return kept.length > 0 ? Object.fromEntries(kept) : void 0;
280
+ }, "compact");
281
+ var eventOf = /* @__PURE__ */ __name((message) => {
282
+ const { action } = message;
283
+ const by = message.sender.id;
284
+ switch (action?.type) {
285
+ case "users_added":
286
+ return { event: "add", by, people: [...action.users] };
287
+ case "user_left":
288
+ return { event: "leave", by, people: [by] };
289
+ case "user_removed":
290
+ return { event: "remove", by, people: [action.user] };
291
+ case "user_joined_link":
292
+ return { event: "join", by: action.inviter, people: [by] };
293
+ case "user_joined_approved":
294
+ return { event: "join", by, people: [by] };
295
+ case "chat_created":
296
+ return { event: "create", by, people: [...action.users], title: action.title };
297
+ case "channel_created":
298
+ return { event: "create", by, people: [], title: action.title };
299
+ case "title_changed":
300
+ return { event: "title", by, people: [], title: action.title };
301
+ case "message_pinned":
302
+ return { event: "pin", by, people: [] };
303
+ default:
304
+ return null;
305
+ }
306
+ }, "eventOf");
307
+ var toMessageHit = /* @__PURE__ */ __name((message) => ({
308
+ ...toMessage(message),
309
+ chatTitle: peerToChat(message.chat).title
310
+ }), "toMessageHit");
311
+ var toDeletions = /* @__PURE__ */ __name((update) => {
312
+ const chatId = update.channelId === null ? null : String(getMarkedPeerId(update.channelId, "channel"));
313
+ return update.messageIds.map((id) => ({ event: "delete", chatId, chatTitle: null, messageId: String(id) }));
314
+ }, "toDeletions");
315
+ var toReactionChange = /* @__PURE__ */ __name(({ update, peers }) => {
316
+ if (update._ !== "updateMessageReactions")
317
+ return void 0;
318
+ const chatId = getMarkedPeerId(update.peer);
319
+ return {
320
+ event: "reaction",
321
+ chatId: String(chatId),
322
+ chatTitle: null,
323
+ messageId: String(update.msgId),
324
+ reactions: reactionsOf(new MessageReactions(update.msgId, chatId, update.reactions, peers))
325
+ };
326
+ }, "toReactionChange");
327
+ var ENTITIES = {
328
+ bold: "messageEntityBold",
329
+ italic: "messageEntityItalic",
330
+ strike: "messageEntityStrike",
331
+ code: "messageEntityCode"
332
+ };
333
+ var toFormatted = /* @__PURE__ */ __name((text, markup) => ({
334
+ text,
335
+ entities: markup.map((span) => {
336
+ const base = { offset: span.from, length: span.length };
337
+ switch (span.type) {
338
+ case "bold":
339
+ case "italic":
340
+ case "strike":
341
+ case "code":
342
+ return { _: ENTITIES[span.type], ...base };
343
+ case "underline":
344
+ return { _: "messageEntityUnderline", ...base };
345
+ case "spoiler":
346
+ return { _: "messageEntitySpoiler", ...base };
347
+ case "blockquote":
348
+ return { _: "messageEntityBlockquote", ...base };
349
+ case "pre":
350
+ return { _: "messageEntityPre", ...base, language: span.language ?? "" };
351
+ case "link":
352
+ if (!span.url)
353
+ throw new CliError("validation_error", "a formatted link needs a URL");
354
+ return { _: "messageEntityTextUrl", ...base, url: span.url };
355
+ default:
356
+ throw new CliError("validation_error", "Telegram does not support this formatting span");
357
+ }
358
+ })
359
+ }), "toFormatted");
360
+ var VIDEO = { ".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime" };
361
+ var videoMime = /* @__PURE__ */ __name(({ kind, name, asFile }) => kind === "file" && !asFile ? VIDEO[extname(name).toLowerCase()] : void 0, "videoMime");
362
+ var toUploadParams = /* @__PURE__ */ __name((upload) => {
363
+ const mime = upload.kind === "voice" ? "audio/ogg" : videoMime(upload);
364
+ return {
365
+ fileName: upload.name,
366
+ ...mime ? { fileMime: mime } : {},
367
+ ...upload.kind === "photo" ? { requireFileSize: true, requireExtension: true } : {}
368
+ };
369
+ }, "toUploadParams");
370
+ var checkSpoiler = /* @__PURE__ */ __name((upload) => {
371
+ if (upload.kind !== "photo" && !videoMime(upload))
372
+ throw new CliError("validation_error", "--spoiler hides a photo or a video only");
373
+ }, "checkSpoiler");
374
+ var toInputMedia = /* @__PURE__ */ __name((upload, caption, file, { spoiler = false } = {}) => {
375
+ const { kind, name } = upload;
376
+ const hidden = spoiler ? { spoiler } : {};
377
+ if (kind === "photo")
378
+ return InputMedia.photo(file, { fileName: name, caption, ...hidden });
379
+ if (kind === "voice")
380
+ return InputMedia.voice(file, { fileMime: "audio/ogg", caption });
381
+ const video = videoMime(upload);
382
+ return video ? InputMedia.video(file, { fileName: name, fileMime: video, caption, supportsStreaming: true, ...hidden }) : InputMedia.document(file, { fileName: name, caption });
383
+ }, "toInputMedia");
384
+ var answerId = /* @__PURE__ */ __name((data) => Buffer.from(data).toString("base64url"), "answerId");
385
+ var toPoll = /* @__PURE__ */ __name((chatId, messageId, poll) => {
386
+ const counted = poll.isClosed || poll.answers.some((answer) => answer.chosen);
387
+ return {
388
+ chatId,
389
+ messageId,
390
+ question: poll.question,
391
+ answers: poll.answers.map((answer) => ({
392
+ id: answerId(answer.data),
393
+ text: answer.text,
394
+ voters: counted ? answer.voters : null,
395
+ chosen: answer.chosen
396
+ })),
397
+ closed: poll.isClosed,
398
+ multiple: poll.isMultiple,
399
+ anonymous: !poll.isPublic,
400
+ voters: counted ? poll.voters : poll.results?.totalVoters ?? null,
401
+ quiz: poll.isQuiz,
402
+ revote: !poll.isRevotingDisabled,
403
+ creator: poll.isCreator
404
+ };
405
+ }, "toPoll");
406
+ var toInputPoll = /* @__PURE__ */ __name(({ question, answers, multiple, anonymous, revote, quiz, closeAfter }) => {
407
+ const closing = closeAfter === void 0 ? {} : { closePeriod: closeAfter };
408
+ return quiz ? InputMedia.quiz({
409
+ question,
410
+ answers,
411
+ public: !anonymous,
412
+ correct: quiz.correct,
413
+ ...quiz.solution === void 0 ? {} : { solution: quiz.solution },
414
+ ...closing
415
+ }) : InputMedia.poll({ question, answers, multiple, public: !anonymous, disableRevoting: revote !== true, ...closing });
416
+ }, "toInputPoll");
417
+ var toGroupCard = /* @__PURE__ */ __name((full) => {
418
+ const defaults = full.defaultPermissions;
419
+ return {
420
+ ...peerToChat(full),
421
+ description: full.bio || null,
422
+ link: full.inviteLink?.link ?? null,
423
+ settings: {
424
+ allCanPin: defaults ? defaults.canPinMessages : null,
425
+ onlyAdminsAdd: defaults ? !defaults.canInviteUsers : null,
426
+ onlyAdminsCall: null,
427
+ onlyOwnerEditsInfo: null,
428
+ membersSeeLink: null,
429
+ joinApproval: full.hasJoinRequests
430
+ }
431
+ };
432
+ }, "toGroupCard");
433
+ var toInviteLink = /* @__PURE__ */ __name((made) => ({
434
+ link: made.link,
435
+ approval: made.approvalNeeded,
436
+ expiresAt: made.endDate?.toISOString() ?? null,
437
+ maxUses: Number.isFinite(made.usageLimit) ? made.usageLimit : null,
438
+ primary: made.isPrimary,
439
+ revoked: made.isRevoked,
440
+ pending: made.pendingApprovals,
441
+ joined: made.usage
442
+ }), "toInviteLink");
443
+ var idsOf = /* @__PURE__ */ __name((peers) => [...new Set(peers.map((peer) => String(getMarkedPeerId(peer))))], "idsOf");
444
+ var toFolder = /* @__PURE__ */ __name((filter) => {
445
+ if (filter._ === "dialogFilterDefault")
446
+ return null;
447
+ const folder = {
448
+ id: String(filter.id),
449
+ title: filter.title.text,
450
+ chatIds: idsOf([...filter.pinnedPeers, ...filter.includePeers])
451
+ };
452
+ if (filter.emoticon)
453
+ folder.emoji = filter.emoticon;
454
+ if (filter.pinnedPeers.length > 0)
455
+ folder.pinnedChatIds = idsOf(filter.pinnedPeers);
456
+ if (filter._ === "dialogFilter") {
457
+ Object.assign(folder, rulesOf(filter));
458
+ if (filter.excludePeers.length > 0)
459
+ folder.excludedChatIds = idsOf(filter.excludePeers);
460
+ }
461
+ return folder;
462
+ }, "toFolder");
463
+
464
+ // dist/telegram/errors.js
465
+ import { MtArgumentError, MtcuteError, MtEmptyError, MtInvalidPeerTypeError, MtMessageNotFoundError, MtPeerNotFoundError, MtSecurityError, MtTimeoutError, MtTypeAssertionError, MtUnsupportedError, tl } from "@mtcute/node";
466
+ var { RpcError } = tl;
467
+ var NOT_FOUND = /* @__PURE__ */ new Set([
468
+ "PEER_ID_INVALID",
469
+ "CHANNEL_INVALID",
470
+ "CHAT_ID_INVALID",
471
+ "USERNAME_INVALID",
472
+ "USERNAME_NOT_OCCUPIED",
473
+ "MSG_ID_INVALID",
474
+ "MESSAGE_ID_INVALID"
475
+ ]);
476
+ var pollClosed = /* @__PURE__ */ __name((words) => `this poll is closed; ${words("polls.show")} has its result`, "pollClosed");
477
+ var EXPLAINED = {
478
+ CHANNEL_PRIVATE: ["permission_error", "you cannot access this channel or supergroup"],
479
+ CHAT_DISCUSSION_UNALLOWED: ["validation_error", "a linked discussion group cannot enable forum topics"],
480
+ CHANNEL_FORUM_MISSING: ["validation_error", "enable forum topics before creating a topic"],
481
+ TOPIC_CLOSED: ["permission_error", "that forum topic is closed; choose an open topic"],
482
+ TOPIC_DELETED: ["not_found", "that forum topic was deleted; check `topics list`"],
483
+ TOPIC_ID_INVALID: ["not_found", "that forum topic does not exist; check `topics list`"],
484
+ MSG_VOICE_MISSING: ["validation_error", "that message is not a voice or video note"],
485
+ MSG_VOICE_TOO_LONG: ["validation_error", "the voice message is too long for Telegram to transcribe"],
486
+ PREMIUM_ACCOUNT_REQUIRED: ["permission_error", "that needs Telegram Premium on this account"],
487
+ TRANSCRIPTION_FAILED: ["provider_error", "Telegram could not transcribe this voice message"],
488
+ PHONE_NOT_OCCUPIED: ["not_found", "nobody Telegram lets you find has this number"],
489
+ USER_NOT_MUTUAL_CONTACT: [
490
+ "permission_error",
491
+ (words) => `Telegram lets you add someone who left or was removed only if you are each other's contacts \u2014 send them the invite link instead (${words("chats.links.show", "<chat>")})`
492
+ ],
493
+ USER_PRIVACY_RESTRICTED: ["permission_error", "their privacy settings do not let you add them to a group"],
494
+ CHAT_ADMIN_REQUIRED: ["permission_error", "only an admin of this chat may do that"],
495
+ MESSAGE_AUTHOR_REQUIRED: ["permission_error", "only whoever sent that message may change it"],
496
+ CHAT_SEND_POLL_FORBIDDEN: ["permission_error", "this chat's admins have turned polls off"],
497
+ BROADCAST_PUBLIC_VOTERS_FORBIDDEN: [
498
+ "validation_error",
499
+ "a channel's polls cannot show who voted \u2014 create it with --anonymous"
500
+ ],
501
+ MESSAGE_POLL_CLOSED: ["validation_error", pollClosed],
502
+ REVOTE_NOT_ALLOWED: ["validation_error", "this poll takes one vote, and yours is final \u2014 it cannot be changed"],
503
+ OPTIONS_TOO_MUCH: ["validation_error", "this poll takes one answer; give one id"],
504
+ OPTION_INVALID: [
505
+ "validation_error",
506
+ (words) => `that is not an answer of this poll \u2014 ${words("polls.show")} lists them`
507
+ ],
508
+ POLL_VOTE_REQUIRED: ["permission_error", "Telegram shows who voted only once you have voted in this poll"],
509
+ BROADCAST_FORBIDDEN: ["permission_error", "a channel does not show who voted in its polls"],
510
+ POLL_ANSWERS_INVALID: ["validation_error", "Telegram refused how many answers this poll has"],
511
+ POLL_ANSWER_INVALID: ["validation_error", "an answer is empty or too long for Telegram"],
512
+ POLL_OPTION_INVALID: ["validation_error", "an answer is empty or too long for Telegram"],
513
+ POLL_OPTION_DUPLICATE: ["validation_error", "two answers are the same; each must differ"],
514
+ POLL_QUESTION_INVALID: ["validation_error", "the question is empty or too long for Telegram"],
515
+ QUIZ_CORRECT_ANSWERS_EMPTY: ["validation_error", "a quiz needs its right answer: --correct <n>"],
516
+ QUIZ_CORRECT_ANSWERS_TOO_MUCH: ["validation_error", "a quiz takes one right answer"],
517
+ QUIZ_CORRECT_ANSWER_INVALID: ["validation_error", "--correct names no answer of this quiz"],
518
+ QUIZ_MULTIPLE_INVALID: ["validation_error", "a quiz takes one answer; not with --multiple"],
519
+ CHAT_PUBLIC_REQUIRED: [
520
+ "validation_error",
521
+ (words) => "Telegram would not make this group ask everyone for approval \u2014 make an invite link that needs it: " + words("chats.links.create", "<chat> --approval")
522
+ ],
523
+ MEGAGROUP_REQUIRED: ["validation_error", "that works only in a supergroup"],
524
+ BROADCAST_REQUIRED: ["validation_error", "that works only in a channel"]
525
+ };
526
+ var revoked = /* @__PURE__ */ __name((login) => ["authentication_error", `Telegram ended this login \u2014 run ${login}`, "revoked"], "revoked");
527
+ var frozen = /* @__PURE__ */ __name((_login, words) => [
528
+ "permission_error",
529
+ `Telegram froze this account: it can read but not write \u2014 ${words("doctor", "--online")} shows until when, and where to appeal`,
530
+ "frozen"
531
+ ], "frozen");
532
+ var STANDINGS = {
533
+ AUTH_KEY_UNREGISTERED: revoked,
534
+ SESSION_REVOKED: revoked,
535
+ SESSION_EXPIRED: revoked,
536
+ USER_DEACTIVATED: /* @__PURE__ */ __name(() => [
537
+ "authentication_error",
538
+ "this Telegram account was deleted \u2014 a new login cannot bring it back",
539
+ "deactivated"
540
+ ], "USER_DEACTIVATED"),
541
+ USER_DEACTIVATED_BAN: /* @__PURE__ */ __name(() => [
542
+ "permission_error",
543
+ "Telegram banned this account \u2014 a new login cannot lift it; only Telegram can",
544
+ "banned"
545
+ ], "USER_DEACTIVATED_BAN"),
546
+ FROZEN_METHOD_INVALID: frozen,
547
+ FROZEN_PARTICIPANT_MISSING: frozen,
548
+ // Not a wait: retrying is what made it. `limited` makes cli-core hold every write for a while.
549
+ PEER_FLOOD: /* @__PURE__ */ __name(() => [
550
+ "permission_error",
551
+ "Telegram limited this account's messages as spam (PEER_FLOOD) \u2014 it can still read; message @SpamBot in a Telegram app to see until when",
552
+ "limited"
553
+ ], "PEER_FLOOD")
554
+ };
555
+ var ARGUMENT_KINDS = [
556
+ [/^You haven't joined /, "you are not a member of that chat"],
557
+ [/^Invalid message link/, "that is not a message link Telegram understands"],
558
+ [/^Invalid invite link/, "that is not an invite link Telegram understands"],
559
+ [
560
+ /^Invalid phone number|^phone should only contain digits|is an invalid test phone number$/,
561
+ "that phone number is not valid"
562
+ ],
563
+ [/^Provided code was invalid/, "the login code was wrong"],
564
+ [/^Provided password was invalid/, "the two-step verification password was wrong"],
565
+ [/^You can forward no more than 100 messages/, "Telegram forwards at most 100 messages at once"]
566
+ ];
567
+ var argumentKind = /* @__PURE__ */ __name((message) => ARGUMENT_KINDS.find(([pattern]) => pattern.test(message))?.[1] ?? "Telegram refused an argument this command passed", "argumentKind");
568
+ var toCliError = /* @__PURE__ */ __name((error, words, login = words("session.start")) => {
569
+ if (isCliError(error))
570
+ return error;
571
+ if (RpcError.is(error, "FLOOD_WAIT_%d")) {
572
+ return new CliError("rate_limited", `Telegram asks to wait ${error.seconds} s before the next request`, {
573
+ retry_after_ms: error.seconds * 1e3,
574
+ provider_error: "FLOOD_WAIT"
575
+ });
576
+ }
577
+ if (RpcError.is(error)) {
578
+ const details = { provider_error: error.text, status: error.code };
579
+ if (error.text === "AUTH_KEY_DUPLICATED") {
580
+ return new CliError("authentication_error", `Telegram ended this login because two connections used it at once (tg serve, tg mcp, tg watch or a command beside them) \u2014 run ${login}`, { ...details, reason: "login.duplicated" });
581
+ }
582
+ const standing = STANDINGS[error.text];
583
+ if (standing) {
584
+ const [code2, message, state] = standing(login, words);
585
+ const reason = state === "revoked" ? "login.revoked" : `account.${state}`;
586
+ return new CliError(code2, message, { ...details, reason, standing: { state, hint: message } });
587
+ }
588
+ if (error.code === RpcError.UNAUTHORIZED) {
589
+ return new CliError("authentication_error", `not logged in, or the session was ended \u2014 run ${login}, or sign in from WireCat Desktop (Tools \u2192 Telegram \u2192 Manage)`, details);
590
+ }
591
+ const explained = EXPLAINED[error.text];
592
+ if (explained) {
593
+ const [code2, message] = explained;
594
+ return new CliError(code2, typeof message === "string" ? message : message(words), details);
595
+ }
596
+ if (NOT_FOUND.has(error.text))
597
+ return new CliError("not_found", `Telegram does not know that (${error.text})`, details);
598
+ if (error.code === RpcError.FORBIDDEN)
599
+ return new CliError("permission_error", `Telegram refused: ${error.text}`, details);
600
+ if (error.code === RpcError.FLOOD)
601
+ return new CliError("rate_limited", `Telegram refused: ${error.text}`, details);
602
+ if (error.code >= 500)
603
+ return new CliError("provider_unavailable", `Telegram failed: ${error.text}`, details);
604
+ return new CliError("provider_error", `Telegram refused: ${error.text}`, details);
605
+ }
606
+ if (error instanceof MtTimeoutError)
607
+ return new CliError("timeout", "Telegram did not answer in time");
608
+ if (error instanceof MtArgumentError)
609
+ return new CliError("validation_error", argumentKind(error.message));
610
+ if (error instanceof MtPeerNotFoundError) {
611
+ return new CliError("not_found", "Telegram does not know that chat or user \u2014 a person's id works only once this account has seen them; name them by @username, or read a chat they are in first");
612
+ }
613
+ if (error instanceof MtMessageNotFoundError) {
614
+ return new CliError("not_found", `there is no message ${error.messageId} in that chat`);
615
+ }
616
+ if (error instanceof MtInvalidPeerTypeError) {
617
+ return new CliError("validation_error", "that chat is not the kind this command works on");
618
+ }
619
+ if (error instanceof MtUnsupportedError) {
620
+ return new CliError("provider_error", "Telegram answered with something tg cannot handle yet");
621
+ }
622
+ if (error instanceof MtTypeAssertionError || error instanceof MtEmptyError || error instanceof MtSecurityError) {
623
+ return new CliError("invalid_response", `Telegram answered with something unexpected (${error.constructor.name})`);
624
+ }
625
+ if (error instanceof MtcuteError)
626
+ return new CliError("provider_error", `Telegram failed (${error.constructor.name})`);
627
+ const code = error?.code;
628
+ if (typeof code === "string" && /^(ECONN|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH)/.test(code)) {
629
+ return new CliError("network_error", `cannot reach Telegram (${code})`);
630
+ }
631
+ return error;
632
+ }, "toCliError");
633
+ var backgroundError = /* @__PURE__ */ __name((write, verbose, words) => (error) => {
634
+ if (!verbose)
635
+ return;
636
+ const mapped = toCliError(error, words);
637
+ const message = mapped instanceof Error ? mapped.message : String(mapped);
638
+ write(`[client] ${message.split("\n", 1)[0]}`);
639
+ }, "backgroundError");
640
+ var withCause = /* @__PURE__ */ __name((error, cause) => Object.assign(error, { cause }), "withCause");
641
+
642
+ // dist/telegram/storage.js
643
+ import { chmodSync, closeSync, existsSync, openSync } from "node:fs";
644
+ import { BaseSqliteStorage, BaseSqliteStorageDriver } from "@mtcute/node";
645
+ var RuntimeSqliteDriver = class extends BaseSqliteStorageDriver {
646
+ static {
647
+ __name(this, "RuntimeSqliteDriver");
648
+ }
649
+ #database;
650
+ constructor(database) {
651
+ super();
652
+ this.#database = database;
653
+ }
654
+ // mtcute's exit hook closes the database on SIGINT/SIGTERM while the command is still running, and
655
+ // `client.destroy()` then flushes the writes queued since into a closed database: "database is not
656
+ // open" (BUG-148). The command closes the client on every exit path, so it is the only owner.
657
+ setup(...[log, platform]) {
658
+ super.setup(log, Object.assign(Object.create(platform), { beforeExit: /* @__PURE__ */ __name(() => () => {
659
+ }, "beforeExit") }));
660
+ }
661
+ _createDatabase() {
662
+ const database = this.#database;
663
+ return {
664
+ exec: /* @__PURE__ */ __name((sql) => database.exec(sql), "exec"),
665
+ close: /* @__PURE__ */ __name(() => database.close(), "close"),
666
+ prepare: /* @__PURE__ */ __name((sql) => {
667
+ const statement = database.prepare(sql);
668
+ return {
669
+ run: /* @__PURE__ */ __name((...parameters) => {
670
+ statement.run(...parameters);
671
+ }, "run"),
672
+ get: /* @__PURE__ */ __name((...parameters) => statement.get(...parameters), "get"),
673
+ all: /* @__PURE__ */ __name((...parameters) => statement.all(...parameters), "all")
674
+ };
675
+ }, "prepare"),
676
+ // better-sqlite3's shape: the function comes back wrapped, and runs in one transaction when called.
677
+ // biome-ignore lint/suspicious/noExplicitAny: mtcute's own signature
678
+ transaction: /* @__PURE__ */ __name((work) => ((...args) => {
679
+ database.exec("BEGIN IMMEDIATE");
680
+ try {
681
+ const result = work(...args);
682
+ database.exec("COMMIT");
683
+ return result;
684
+ } catch (error) {
685
+ database.exec("ROLLBACK");
686
+ throw error;
687
+ }
688
+ }), "transaction")
689
+ };
690
+ }
691
+ };
692
+ var openSessionStorage = /* @__PURE__ */ __name(async (path) => {
693
+ closeSync(openSync(path, "a", 384));
694
+ for (const file of [path, `${path}-wal`, `${path}-shm`]) {
695
+ if (existsSync(file))
696
+ chmodSync(file, 384);
697
+ }
698
+ return new BaseSqliteStorage(new RuntimeSqliteDriver(await openCache(path)));
699
+ }, "openSessionStorage");
700
+
701
+ export {
702
+ ruleFlags,
703
+ toAccountSession,
704
+ toTopic,
705
+ toInvitePreview,
706
+ toLinkChat,
707
+ toGroupMember,
708
+ toMember,
709
+ toAccount,
710
+ groupMembersCount,
711
+ peerToChat,
712
+ toChat,
713
+ toButtons,
714
+ toMessage,
715
+ toHistoryChannel,
716
+ toHistoryMessages,
717
+ attachmentsOf,
718
+ eventOf,
719
+ toMessageHit,
720
+ toDeletions,
721
+ toReactionChange,
722
+ toFormatted,
723
+ videoMime,
724
+ toUploadParams,
725
+ checkSpoiler,
726
+ toInputMedia,
727
+ answerId,
728
+ toPoll,
729
+ toInputPoll,
730
+ toGroupCard,
731
+ toInviteLink,
732
+ toFolder,
733
+ pollClosed,
734
+ toCliError,
735
+ backgroundError,
736
+ withCause,
737
+ openSessionStorage
738
+ };