@mtkruto/node 0.1.102 → 0.1.104

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 (35) hide show
  1. package/esm/4_constants.d.ts +1 -1
  2. package/esm/4_constants.js +1 -1
  3. package/esm/client/3_types.d.ts +25 -1
  4. package/esm/client/4_client.d.ts +30 -32
  5. package/esm/client/4_client.js +83 -11
  6. package/esm/storage/0_storage.d.ts +3 -1
  7. package/esm/storage/0_storage.js +7 -0
  8. package/esm/storage/0_utilities.d.ts +2 -1
  9. package/esm/storage/0_utilities.js +63 -0
  10. package/esm/storage/1_storage_indexed_db.d.ts +2 -1
  11. package/esm/storage/1_storage_indexed_db.js +18 -1
  12. package/esm/storage/1_storage_local_storage.d.ts +1 -0
  13. package/esm/storage/1_storage_local_storage.js +16 -0
  14. package/esm/storage/1_storage_memory.d.ts +1 -0
  15. package/esm/storage/1_storage_memory.js +14 -1
  16. package/esm/storage/1_storage_session_storage.d.ts +1 -0
  17. package/esm/storage/1_storage_session_storage.js +16 -0
  18. package/package.json +1 -1
  19. package/script/4_constants.d.ts +1 -1
  20. package/script/4_constants.js +1 -1
  21. package/script/client/3_types.d.ts +25 -1
  22. package/script/client/4_client.d.ts +30 -32
  23. package/script/client/4_client.js +83 -11
  24. package/script/storage/0_storage.d.ts +3 -1
  25. package/script/storage/0_storage.js +7 -0
  26. package/script/storage/0_utilities.d.ts +2 -1
  27. package/script/storage/0_utilities.js +65 -1
  28. package/script/storage/1_storage_indexed_db.d.ts +2 -1
  29. package/script/storage/1_storage_indexed_db.js +17 -0
  30. package/script/storage/1_storage_local_storage.d.ts +1 -0
  31. package/script/storage/1_storage_local_storage.js +16 -0
  32. package/script/storage/1_storage_memory.d.ts +1 -0
  33. package/script/storage/1_storage_memory.js +13 -0
  34. package/script/storage/1_storage_session_storage.d.ts +1 -0
  35. package/script/storage/1_storage_session_storage.js +16 -0
@@ -80,7 +80,7 @@ exports.PUBLIC_KEYS = Object.freeze([
80
80
  exports.VECTOR_CONSTRUCTOR = 0x1CB5C415;
81
81
  exports.INITIAL_DC = "2-test";
82
82
  exports.LAYER = 161;
83
- exports.APP_VERSION = "MTKruto 0.1.102";
83
+ exports.APP_VERSION = "MTKruto 0.1.104";
84
84
  // @ts-ignore: lib
85
85
  exports.DEVICE_MODEL = typeof dntShim.Deno === "undefined" ? typeof navigator === "undefined" ? typeof process === "undefined" ? "Unknown" : process.platform + "-" + process.arch : navigator.userAgent.split(" ")[0] : dntShim.Deno.build.os + "-" + dntShim.Deno.build.arch;
86
86
  exports.LANG_CODE = typeof navigator === "undefined" ? "en" : navigator.language.split("-")[0];
@@ -1,6 +1,6 @@
1
1
  import { MaybePromise } from "../1_utilities.js";
2
2
  import { functions, types } from "../2_tl.js";
3
- import { CallbackQuery, ChatID, ForceReply, InlineKeyboardMarkup, InlineQuery, Message, MessageEntity, ReplyKeyboardMarkup, ReplyKeyboardRemove } from "../3_types.js";
3
+ import { BotCommandScope, CallbackQuery, ChatID, ForceReply, InlineKeyboardMarkup, InlineQuery, InlineQueryResultButton, Message, MessageEntity, ReplyKeyboardMarkup, ReplyKeyboardRemove } from "../3_types.js";
4
4
  import { With } from "./0_utilities.js";
5
5
  import { ClientPlainParams } from "./2_client_plain.js";
6
6
  export type ParseMode = "HTML" | null;
@@ -194,6 +194,30 @@ export interface SendPollParams {
194
194
  */
195
195
  protectContent?: boolean;
196
196
  }
197
+ export interface DownloadParams {
198
+ /** Size of each download chunk in bytes. */
199
+ chunkSize?: number;
200
+ }
201
+ export interface UploadParams {
202
+ /** The file name to assign. */
203
+ fileName?: string;
204
+ /** Size of each upload chunk in bytes. */
205
+ chunkSize?: number;
206
+ /** Upload abort signal. */
207
+ signal?: AbortSignal | null;
208
+ }
209
+ export interface AnswerInlineQueryParams {
210
+ cacheTime?: number;
211
+ isPersonal?: boolean;
212
+ nextOffset?: string;
213
+ isGallery?: boolean;
214
+ button?: InlineQueryResultButton;
215
+ }
216
+ export interface SetMyCommandsParams {
217
+ languageCode?: string;
218
+ scope?: BotCommandScope;
219
+ }
220
+ export type GetMyCommandsParams = SetMyCommandsParams;
197
221
  export type ConnectionState = "notConnected" | "updating" | "ready";
198
222
  export type AuthorizationState = {
199
223
  authorized: boolean;
@@ -2,11 +2,11 @@ import { MaybePromise } from "../1_utilities.js";
2
2
  import { functions, ReadObject, types } from "../2_tl.js";
3
3
  import { Storage } from "../3_storage.js";
4
4
  import { DC } from "../3_transport.js";
5
- import { BotCommand, BotCommandScope, ChatAction, ChatID, InlineQueryResult, InlineQueryResultButton, Message } from "../3_types.js";
5
+ import { BotCommand, ChatAction, ChatID, InlineQueryResult, Message } from "../3_types.js";
6
6
  import { Migrate } from "../4_errors.js";
7
7
  import { With } from "./0_utilities.js";
8
8
  import { ClientAbstract } from "./1_client_abstract.js";
9
- import { AnswerCallbackQueryParams, AuthorizeUserParams, ClientParams, EditMessageParams, FilterableUpdates, FilterUpdate, ForwardMessagesParams, Handler, ParseMode, SendMessagesParams, SendPollParams, Update } from "./3_types.js";
9
+ import { AnswerCallbackQueryParams, AnswerInlineQueryParams, AuthorizeUserParams, ClientParams, DownloadParams, EditMessageParams, FilterableUpdates, FilterUpdate, ForwardMessagesParams, GetMyCommandsParams, Handler, ParseMode, SendMessagesParams, SendPollParams, SetMyCommandsParams, Update, UploadParams } from "./3_types.js";
10
10
  export declare const getEntity: unique symbol;
11
11
  export declare const getStickerSetName: unique symbol;
12
12
  export declare const handleMigrationError: unique symbol;
@@ -70,6 +70,8 @@ export declare class Client extends ClientAbstract {
70
70
  private initConnection;
71
71
  private lastPropagatedAuthorizationState;
72
72
  private propagateAuthorizationState;
73
+ private selfId;
74
+ private getSelfId;
73
75
  /**
74
76
  * Calls [initConnection](1) and authorizes the client with one of the following:
75
77
  *
@@ -168,9 +170,7 @@ export declare class Client extends ClientAbstract {
168
170
  *
169
171
  * @param fileId The identifier of the file to download.
170
172
  */
171
- download(fileId: string, params?: {
172
- chunkSize?: number;
173
- }): Promise<AsyncGenerator<Uint8Array, void, unknown>>;
173
+ download(fileId: string, params?: DownloadParams): Promise<AsyncGenerator<Uint8Array, void, unknown>>;
174
174
  [getStickerSetName](inputStickerSet: types.InputStickerSetID, hash?: number): Promise<string>;
175
175
  /**
176
176
  * Forward multiple messages.
@@ -223,49 +223,47 @@ export declare class Client extends ClientAbstract {
223
223
  *
224
224
  * @param contents The contents of the file.
225
225
  */
226
- upload(contents: Uint8Array, params?: {
227
- fileName?: string;
228
- chunkSize?: number;
229
- signal?: AbortSignal | null;
230
- }): Promise<types.InputFile | types.InputFileBig>;
231
- setMyCommands(commands: BotCommand[], params?: {
232
- languageCode?: string;
233
- scope?: BotCommandScope;
234
- }): Promise<void>;
235
- getMyCommands(params?: {
236
- languageCode?: string;
237
- scope?: BotCommandScope;
238
- }): Promise<BotCommand[]>;
239
- answerInlineQuery(id: string, results: InlineQueryResult[], params?: {
240
- cacheTime?: number;
241
- isPersonal?: boolean;
242
- nextOffset?: string;
243
- isGallery?: boolean;
244
- button: InlineQueryResultButton;
245
- }): Promise<void>;
226
+ upload(contents: Uint8Array, params?: UploadParams): Promise<types.InputFile | types.InputFileBig>;
227
+ /**
228
+ * Set the bot's commands in the given scope and/or language. Bot-only.
229
+ *
230
+ * @param commands The commands to set.
231
+ */
232
+ setMyCommands(commands: BotCommand[], params?: SetMyCommandsParams): Promise<void>;
233
+ /**
234
+ * Get the bot's commands in the given scope and/or language. Bot-only.
235
+ */
236
+ getMyCommands(params?: GetMyCommandsParams): Promise<BotCommand[]>;
237
+ /**
238
+ * Answer an inline query. Bot-only.
239
+ *
240
+ * @param id The ID of the inline query to answer.
241
+ * @param results The results to answer with.
242
+ */
243
+ answerInlineQuery(id: string, results: InlineQueryResult[], params?: AnswerInlineQueryParams): Promise<void>;
246
244
  private handle;
247
245
  use(handler: Handler): void;
248
246
  branch(predicate: (upd: Update) => MaybePromise<boolean>, trueHandler: Handler, falseHandler: Handler): void;
249
247
  filter<D extends Update>(predicate: (update: Update) => update is D, handler: Handler<D>): void;
250
248
  filter(predicate: (update: Update) => MaybePromise<boolean>, handler: Handler): void;
251
249
  on<T extends keyof Update, F extends keyof NonNullable<Update[T]>>(filter: T extends FilterableUpdates ? T | [T, F, ...F[]] : T, handler: Handler<FilterUpdate<Update, T, F>>): void;
252
- setMyInfo(info: Omit<ConstructorParameters<typeof functions["BotsSetBotInfo"]>[0], "bot">): Promise<void>;
250
+ private setMyInfo;
253
251
  /**
254
- * Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
252
+ * Set the bot's description in the given language. Bot-only.
255
253
  */
256
254
  setMyDescription({ description, languageCode }: {
257
255
  description?: string;
258
256
  languageCode?: string;
259
257
  }): Promise<void>;
260
258
  /**
261
- * Use this method to change the bot's name.
259
+ * Set the bot's name in the given language. Bot-only.
262
260
  */
263
261
  setMyName({ name, languageCode }: {
264
262
  name?: string;
265
263
  languageCode?: string;
266
264
  }): Promise<void>;
267
265
  /**
268
- * Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot.
266
+ * Set the bot's short description in the given language. Bot-only.
269
267
  */
270
268
  setMyShortDescription({ shortDescription: about, languageCode }: {
271
269
  shortDescription?: string;
@@ -273,15 +271,15 @@ export declare class Client extends ClientAbstract {
273
271
  }): Promise<void>;
274
272
  private getMyInfo;
275
273
  /**
276
- * Use this method to get the current bot description for the given user language.
274
+ * Get the bot's description in the given language. Bot-only.
277
275
  */
278
276
  getMyDescription(languageCode?: string): Promise<string>;
279
277
  /**
280
- * Use this method to get the current bot name for the given user language.
278
+ * Set the bot's name in the given language. Bot-only.
281
279
  */
282
280
  getMyName(languageCode?: string): Promise<string>;
283
281
  /**
284
- * Use this method to get the current bot short description for the given user language.
282
+ * Get the bot's short description in the given language. Bot-only.
285
283
  */
286
284
  getMyShortDescription(languageCode?: string): Promise<string>;
287
285
  }
@@ -202,6 +202,12 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
202
202
  writable: true,
203
203
  value: null
204
204
  });
205
+ Object.defineProperty(this, "selfId", {
206
+ enumerable: true,
207
+ configurable: true,
208
+ writable: true,
209
+ value: null
210
+ });
205
211
  Object.defineProperty(this, "pingLoopStarted", {
206
212
  enumerable: true,
207
213
  configurable: true,
@@ -384,6 +390,12 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
384
390
  this.lastPropagatedAuthorizationState = authorized;
385
391
  }
386
392
  }
393
+ async getSelfId() {
394
+ if (this.selfId == null) {
395
+ this.selfId = await this.getMe().then((v) => v.id);
396
+ }
397
+ return this.selfId;
398
+ }
387
399
  /**
388
400
  * Calls [initConnection](1) and authorizes the client with one of the following:
389
401
  *
@@ -433,7 +445,8 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
433
445
  if (typeof params === "string") {
434
446
  while (true) {
435
447
  try {
436
- await this.invoke(new _2_tl_js_1.functions.AuthImportBotAuthorization({ apiId: this.apiId, apiHash: this.apiHash, botAuthToken: params, flags: 0 }));
448
+ const auth = await this.invoke(new _2_tl_js_1.functions.AuthImportBotAuthorization({ apiId: this.apiId, apiHash: this.apiHash, botAuthToken: params, flags: 0 }));
449
+ this.selfId = Number(auth[_2_tl_js_1.as](_2_tl_js_1.types.AuthAuthorization).user.id);
437
450
  await this.storage.setAccountType("bot");
438
451
  break;
439
452
  }
@@ -498,11 +511,12 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
498
511
  while (true) {
499
512
  const code = typeof params.code === "string" ? params.code : await params.code();
500
513
  try {
501
- await this.invoke(new _2_tl_js_1.functions.AuthSignIn({
514
+ const auth = await this.invoke(new _2_tl_js_1.functions.AuthSignIn({
502
515
  phoneNumber: phone,
503
516
  phoneCode: code,
504
517
  phoneCodeHash: sentCode.phoneCodeHash,
505
518
  }));
519
+ this.selfId = Number(auth[_2_tl_js_1.as](_2_tl_js_1.types.AuthAuthorization).user.id);
506
520
  await this.storage.setAccountType("user");
507
521
  dAuth("authorized as user");
508
522
  await this.propagateAuthorizationState(true);
@@ -530,7 +544,8 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
530
544
  try {
531
545
  const password = typeof params.password === "string" ? params.password : await params.password(ap.hint ?? null);
532
546
  const input = await (0, _0_password_js_1.checkPassword)(password, ap);
533
- await this.invoke(new _2_tl_js_1.functions.AuthCheckPassword({ password: input }));
547
+ const auth = await this.invoke(new _2_tl_js_1.functions.AuthCheckPassword({ password: input }));
548
+ this.selfId = Number(auth[_2_tl_js_1.as](_2_tl_js_1.types.AuthAuthorization).user.id);
534
549
  await this.storage.setAccountType("user");
535
550
  dAuth("authorized as user");
536
551
  await this.propagateAuthorizationState(true);
@@ -990,8 +1005,7 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
990
1005
  }
991
1006
  }
992
1007
  else if (difference instanceof _2_tl_js_1.types.UpdatesDifferenceTooLong) {
993
- // TODO: we actually do now
994
- // stored messages should be invalidated in case we store messages in the future
1008
+ await this.storage.deleteMessages();
995
1009
  state.pts = difference.pts;
996
1010
  dGap("received differenceTooLong");
997
1011
  }
@@ -1485,6 +1499,50 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1485
1499
  }
1486
1500
  // TODO: log errors
1487
1501
  async handleUpdate(update) {
1502
+ if (update instanceof _2_tl_js_1.types.UpdateShortMessage) {
1503
+ update = new _2_tl_js_1.types.UpdateNewMessage({
1504
+ message: new _2_tl_js_1.types.Message({
1505
+ out: update.out,
1506
+ mentioned: update.mentioned,
1507
+ mediaUnread: update.mediaUnread,
1508
+ silent: update.silent,
1509
+ id: update.id,
1510
+ fromId: update.out ? new _2_tl_js_1.types.PeerUser({ userId: await this.getSelfId().then(BigInt) }) : new _2_tl_js_1.types.PeerUser({ userId: update.userId }),
1511
+ peerId: new _2_tl_js_1.types.PeerChat({ chatId: update.userId }),
1512
+ message: update.message,
1513
+ date: update.date,
1514
+ fwdFrom: update.fwdFrom,
1515
+ viaBotId: update.viaBotId,
1516
+ replyTo: update.replyTo,
1517
+ entities: update.entities,
1518
+ ttlPeriod: update.ttlPeriod,
1519
+ }),
1520
+ pts: update.pts,
1521
+ ptsCount: update.ptsCount,
1522
+ });
1523
+ }
1524
+ else if (update instanceof _2_tl_js_1.types.UpdateShortChatMessage) {
1525
+ update = new _2_tl_js_1.types.UpdateNewMessage({
1526
+ message: new _2_tl_js_1.types.Message({
1527
+ out: update.out,
1528
+ mentioned: update.mentioned,
1529
+ mediaUnread: update.mediaUnread,
1530
+ silent: update.silent,
1531
+ id: update.id,
1532
+ fromId: new _2_tl_js_1.types.PeerUser({ userId: update.fromId }),
1533
+ peerId: new _2_tl_js_1.types.PeerChat({ chatId: update.chatId }),
1534
+ fwdFrom: update.fwdFrom,
1535
+ viaBotId: update.viaBotId,
1536
+ replyTo: update.replyTo,
1537
+ date: update.date,
1538
+ message: update.message,
1539
+ entities: update.entities,
1540
+ ttlPeriod: update.ttlPeriod,
1541
+ }),
1542
+ pts: update.pts,
1543
+ ptsCount: update.ptsCount,
1544
+ });
1545
+ }
1488
1546
  if (update instanceof _2_tl_js_1.types.UpdateNewMessage || update instanceof _2_tl_js_1.types.UpdateNewMessage || update instanceof _2_tl_js_1.types.UpdateNewChannelMessage || update instanceof _2_tl_js_1.types.UpdateNewChannelMessage) {
1489
1547
  if (update.message instanceof _2_tl_js_1.types.Message || update.message instanceof _2_tl_js_1.types.MessageService) {
1490
1548
  await this.storage.setMessage((0, _2_tl_js_1.peerToChatId)(update.message.peerId), update.message.id, update.message);
@@ -1751,6 +1809,11 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1751
1809
  return new _2_tl_js_1.types.InputFile({ id: fileId, name, parts: part, md5Checksum: "" });
1752
1810
  }
1753
1811
  }
1812
+ /**
1813
+ * Set the bot's commands in the given scope and/or language. Bot-only.
1814
+ *
1815
+ * @param commands The commands to set.
1816
+ */
1754
1817
  async setMyCommands(commands, params) {
1755
1818
  await this.invoke(new _2_tl_js_1.functions.BotsSetBotCommands({
1756
1819
  commands: commands.map((v) => new _2_tl_js_1.types.BotCommand(v)),
@@ -1758,6 +1821,9 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1758
1821
  scope: await (0, _3_types_js_1.botCommandScopeToTlObject)(params?.scope ?? { type: "default" }, this.getInputPeer.bind(this)),
1759
1822
  }));
1760
1823
  }
1824
+ /**
1825
+ * Get the bot's commands in the given scope and/or language. Bot-only.
1826
+ */
1761
1827
  async getMyCommands(params) {
1762
1828
  const commands_ = await this.invoke(new _2_tl_js_1.functions.BotsGetBotCommands({
1763
1829
  langCode: params?.languageCode ?? "",
@@ -1765,6 +1831,12 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1765
1831
  }));
1766
1832
  return commands_.map((v) => ({ command: v.command, description: v.description }));
1767
1833
  }
1834
+ /**
1835
+ * Answer an inline query. Bot-only.
1836
+ *
1837
+ * @param id The ID of the inline query to answer.
1838
+ * @param results The results to answer with.
1839
+ */
1768
1840
  async answerInlineQuery(id, results, params) {
1769
1841
  await this.invoke(new _2_tl_js_1.functions.MessagesSetInlineBotResults({
1770
1842
  queryId: BigInt(id),
@@ -1827,21 +1899,21 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1827
1899
  await this.invoke(new _2_tl_js_1.functions.BotsSetBotInfo({ bot: new _2_tl_js_1.types.InputUserSelf(), ...info }));
1828
1900
  }
1829
1901
  /**
1830
- * Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
1902
+ * Set the bot's description in the given language. Bot-only.
1831
1903
  */
1832
1904
  async setMyDescription({ description, languageCode }) {
1833
1905
  await this.assertBot("setMyDescription");
1834
1906
  await this.setMyInfo({ description, langCode: languageCode ?? "" });
1835
1907
  }
1836
1908
  /**
1837
- * Use this method to change the bot's name.
1909
+ * Set the bot's name in the given language. Bot-only.
1838
1910
  */
1839
1911
  async setMyName({ name, languageCode }) {
1840
1912
  await this.assertBot("setMyName");
1841
1913
  await this.setMyInfo({ name, langCode: languageCode ?? "" });
1842
1914
  }
1843
1915
  /**
1844
- * Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot.
1916
+ * Set the bot's short description in the given language. Bot-only.
1845
1917
  */
1846
1918
  async setMyShortDescription({ shortDescription: about, languageCode }) {
1847
1919
  await this.assertBot("setMyShortDescription");
@@ -1851,21 +1923,21 @@ class Client extends _1_client_abstract_js_1.ClientAbstract {
1851
1923
  return this.invoke(new _2_tl_js_1.functions.BotsGetBotInfo({ bot: new _2_tl_js_1.types.InputUserSelf(), langCode: languageCode ?? "" }));
1852
1924
  }
1853
1925
  /**
1854
- * Use this method to get the current bot description for the given user language.
1926
+ * Get the bot's description in the given language. Bot-only.
1855
1927
  */
1856
1928
  async getMyDescription(languageCode) {
1857
1929
  await this.assertBot("getMyDescription");
1858
1930
  return await this.getMyInfo(languageCode).then((v) => v.description);
1859
1931
  }
1860
1932
  /**
1861
- * Use this method to get the current bot name for the given user language.
1933
+ * Set the bot's name in the given language. Bot-only.
1862
1934
  */
1863
1935
  async getMyName(languageCode) {
1864
1936
  await this.assertBot("getMyName");
1865
1937
  return await this.getMyInfo(languageCode).then((v) => v.description);
1866
1938
  }
1867
1939
  /**
1868
- * Use this method to get the current bot short description for the given user language.
1940
+ * Get the bot's short description in the given language. Bot-only.
1869
1941
  */
1870
1942
  async getMyShortDescription(languageCode) {
1871
1943
  await this.assertBot("getMyShortDescription");
@@ -1,12 +1,13 @@
1
1
  import { MaybePromise } from "../1_utilities.js";
2
2
  import { TLObject, types } from "../2_tl.js";
3
3
  import { DC } from "../3_transport.js";
4
- export type StorageKeyPart = string | number | bigint | Uint8Array;
4
+ export type StorageKeyPart = string | number | bigint;
5
5
  export declare abstract class Storage {
6
6
  private _authKeyId;
7
7
  abstract init(): MaybePromise<void>;
8
8
  abstract set(key: readonly StorageKeyPart[], value: unknown): MaybePromise<void>;
9
9
  abstract get<T>(key: readonly StorageKeyPart[]): MaybePromise<T | null>;
10
+ abstract getMany<T>(prefix: readonly StorageKeyPart[]): MaybePromise<Generator<[readonly StorageKeyPart[], T]> | AsyncGenerator<[readonly StorageKeyPart[], T]>>;
10
11
  setDc(dc: DC | null): MaybePromise<void>;
11
12
  getDc(): MaybePromise<DC | null>;
12
13
  private resetAuthKeyId;
@@ -24,6 +25,7 @@ export declare abstract class Storage {
24
25
  setState(state: types.UpdatesState): Promise<void>;
25
26
  getState(): Promise<types.UpdatesState | null>;
26
27
  setMessage(chatId: number, messageId: number, message: types.TypeMessage | null): Promise<void>;
28
+ deleteMessages(): Promise<void>;
27
29
  getMessageChat(messageId: number): MaybePromise<number | null>;
28
30
  getMessage(chatId: number, messageId: number): Promise<types.TypeMessage | null>;
29
31
  setChannelPts(channelId: bigint, pts: number): Promise<void>;
@@ -107,6 +107,13 @@ class Storage {
107
107
  }
108
108
  await this.setTlObject(KPARTS_MESSAGE(chatId, messageId), message);
109
109
  }
110
+ async deleteMessages() {
111
+ const maybePromises = new Array();
112
+ for await (const [k, o] of await this.getMany(["messageRefs"])) {
113
+ maybePromises.push(Promise.all([this.set(k, null), o == null ? Promise.resolve() : this.set(KPARTS_MESSAGE(o, k[1]), null)]).then(() => { }));
114
+ }
115
+ await Promise.all(maybePromises.filter((v) => v instanceof Promise));
116
+ }
110
117
  getMessageChat(messageId) {
111
118
  return this.get(KPARTS_MESSAGE_REF(messageId));
112
119
  }
@@ -10,4 +10,5 @@ export declare enum ValueType {
10
10
  }
11
11
  export declare function toString(value: unknown): string;
12
12
  export declare function fromString<T>(string: string): any;
13
- export declare function fixKey(key: StorageKeyPart[]): (string | number | Uint8Array)[];
13
+ export declare function fixKey(key: readonly StorageKeyPart[]): (string | number)[];
14
+ export declare function getPrefixKeyRange(prefix: any): IDBKeyRange;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fixKey = exports.fromString = exports.toString = exports.ValueType = void 0;
3
+ exports.getPrefixKeyRange = exports.fixKey = exports.fromString = exports.toString = exports.ValueType = void 0;
4
4
  const _0_deps_js_1 = require("../0_deps.js");
5
5
  const _1_utilities_js_1 = require("../1_utilities.js");
6
6
  var ValueType;
@@ -66,3 +66,67 @@ function fixKey(key) {
66
66
  return key.map((v) => typeof v === "bigint" ? String(v) : v);
67
67
  }
68
68
  exports.fixKey = fixKey;
69
+ // Source: https://gist.github.com/inexorabletash/5462871
70
+ // deno-lint-ignore no-explicit-any
71
+ function getPrefixKeyRange(prefix) {
72
+ // Ensure prefix is a valid key itself:
73
+ if (indexedDB.cmp(prefix, prefix) !== 0)
74
+ throw new TypeError();
75
+ const upperKey = successor(prefix);
76
+ if (upperKey === undefined)
77
+ return IDBKeyRange.lowerBound(prefix);
78
+ return IDBKeyRange.bound(prefix, upperKey, false, true);
79
+ }
80
+ exports.getPrefixKeyRange = getPrefixKeyRange;
81
+ const MAX_DATE_VALUE = 8640000000000000;
82
+ const UPPER_BOUND = {
83
+ NUMBER: new Date(-MAX_DATE_VALUE),
84
+ DATE: "",
85
+ STRING: [],
86
+ ARRAY: undefined,
87
+ };
88
+ // deno-lint-ignore no-explicit-any
89
+ function successor(key) {
90
+ if (typeof key === "number") {
91
+ if (key === Infinity)
92
+ return UPPER_BOUND.NUMBER;
93
+ if (key === -Infinity)
94
+ return -Number.MAX_VALUE;
95
+ if (key === 0)
96
+ return Number.MIN_VALUE;
97
+ let epsilon = Math.abs(key);
98
+ while (key + epsilon / 2 !== key)
99
+ epsilon = epsilon / 2;
100
+ return key + epsilon;
101
+ }
102
+ if (key instanceof Date) {
103
+ if (key.valueOf() + 1 > MAX_DATE_VALUE)
104
+ return UPPER_BOUND.DATE;
105
+ return new Date(key.valueOf() + 1);
106
+ }
107
+ if (typeof key === "string") {
108
+ let len = key.length;
109
+ while (len > 0) {
110
+ const head = key.substring(0, len - 1), tail = key.charCodeAt(len - 1);
111
+ if (tail !== 0xffff)
112
+ return head + String.fromCharCode(tail + 1);
113
+ key = head;
114
+ --len;
115
+ }
116
+ return UPPER_BOUND.STRING;
117
+ }
118
+ if (Array.isArray(key)) {
119
+ key = key.slice(); // Operate on a copy.
120
+ let len = key.length;
121
+ while (len > 0) {
122
+ const tail = successor(key.pop());
123
+ if (tail !== undefined) {
124
+ key.push(tail);
125
+ return key;
126
+ }
127
+ --len;
128
+ }
129
+ return UPPER_BOUND.ARRAY;
130
+ }
131
+ throw new TypeError();
132
+ }
@@ -5,5 +5,6 @@ export declare class StorageIndexedDB extends Storage {
5
5
  constructor(name: string);
6
6
  init(): Promise<void>;
7
7
  set(k: StorageKeyPart[], v: unknown): Promise<void>;
8
- get<T>(k: StorageKeyPart[]): Promise<T | null>;
8
+ get<T>(k: readonly StorageKeyPart[]): Promise<T | null>;
9
+ getMany<T>(prefix: readonly StorageKeyPart[]): AsyncGenerator<[readonly StorageKeyPart[], T], void, unknown>;
9
10
  }
@@ -75,5 +75,22 @@ class StorageIndexedDB extends _0_storage_js_1.Storage {
75
75
  };
76
76
  });
77
77
  }
78
+ async *getMany(prefix) {
79
+ if (!this.database) {
80
+ throw new Error("Not initialized");
81
+ }
82
+ const keys = await new Promise((res, rej) => {
83
+ const tx = this.database.transaction(KV_OBJECT_STORE, "readonly")
84
+ .objectStore(KV_OBJECT_STORE)
85
+ .getAllKeys((0, _0_utilities_js_1.getPrefixKeyRange)(prefix));
86
+ tx.onerror = rej;
87
+ tx.onsuccess = () => {
88
+ res(tx.result);
89
+ };
90
+ });
91
+ for (const key of keys) {
92
+ yield [key, await this.get(key)];
93
+ }
94
+ }
78
95
  }
79
96
  exports.StorageIndexedDB = StorageIndexedDB;
@@ -5,5 +5,6 @@ export declare class StorageLocalStorage extends Storage implements Storage {
5
5
  constructor(prefix: string);
6
6
  init(): void;
7
7
  get(key_: readonly StorageKeyPart[]): any;
8
+ getMany<T>(prefix: readonly StorageKeyPart[]): Generator<[readonly StorageKeyPart[], T], void, unknown>;
8
9
  set(key_: readonly StorageKeyPart[], value: unknown): MaybePromise<void>;
9
10
  }
@@ -34,6 +34,22 @@ class StorageLocalStorage extends _0_storage_js_1.Storage {
34
34
  return null;
35
35
  }
36
36
  }
37
+ *getMany(prefix) {
38
+ for (let [key, value] of Object.entries(localStorage)) {
39
+ if (key.startsWith(this.prefix)) {
40
+ key = key.slice(this.prefix.length);
41
+ }
42
+ const parts = (0, _0_utilities_js_1.fromString)(key);
43
+ if (Array.isArray(parts)) {
44
+ for (const [i, p] of prefix.entries()) {
45
+ if ((0, _0_utilities_js_1.toString)(p) != (0, _0_utilities_js_1.toString)(parts[i])) {
46
+ continue;
47
+ }
48
+ yield [parts, (0, _0_utilities_js_1.fromString)(value)];
49
+ }
50
+ }
51
+ }
52
+ }
37
53
  set(key_, value) {
38
54
  const key = this.prefix + (0, _0_utilities_js_1.toString)(key_);
39
55
  if (value != null) {
@@ -4,5 +4,6 @@ export declare class StorageMemory extends Storage implements Storage {
4
4
  protected map: Map<string, unknown>;
5
5
  init(): void;
6
6
  get<T>(key: readonly StorageKeyPart[]): NonNullable<T> | null;
7
+ getMany<T>(prefix: readonly StorageKeyPart[]): Generator<[readonly StorageKeyPart[], T], void, unknown>;
7
8
  set(key_: readonly StorageKeyPart[], value: unknown): MaybePromise<void>;
8
9
  }
@@ -18,6 +18,19 @@ class StorageMemory extends _0_storage_js_1.Storage {
18
18
  get(key) {
19
19
  return this.map.get((0, _0_utilities_js_1.toString)(key)) ?? null;
20
20
  }
21
+ *getMany(prefix) {
22
+ for (const [key, value] of this.map.entries()) {
23
+ const parts = (0, _0_utilities_js_1.fromString)(key);
24
+ if (Array.isArray(parts)) {
25
+ for (const [i, p] of prefix.entries()) {
26
+ if ((0, _0_utilities_js_1.toString)(p) != (0, _0_utilities_js_1.toString)(parts[i])) {
27
+ continue;
28
+ }
29
+ yield [parts, value];
30
+ }
31
+ }
32
+ }
33
+ }
21
34
  set(key_, value) {
22
35
  const key = (0, _0_utilities_js_1.toString)(key_);
23
36
  if (value != null) {
@@ -5,5 +5,6 @@ export declare class StorageSessionStorage extends Storage implements Storage {
5
5
  constructor(prefix: string);
6
6
  init(): void;
7
7
  get(key_: readonly StorageKeyPart[]): any;
8
+ getMany<T>(prefix: readonly StorageKeyPart[]): Generator<[readonly StorageKeyPart[], T], void, unknown>;
8
9
  set(key_: readonly StorageKeyPart[], value: unknown): MaybePromise<void>;
9
10
  }
@@ -34,6 +34,22 @@ class StorageSessionStorage extends _0_storage_js_1.Storage {
34
34
  return null;
35
35
  }
36
36
  }
37
+ *getMany(prefix) {
38
+ for (let [key, value] of Object.entries(localStorage)) {
39
+ if (key.startsWith(this.prefix)) {
40
+ key = key.slice(this.prefix.length);
41
+ }
42
+ const parts = (0, _0_utilities_js_1.fromString)(key);
43
+ if (Array.isArray(parts)) {
44
+ for (const [i, p] of prefix.entries()) {
45
+ if ((0, _0_utilities_js_1.toString)(p) != (0, _0_utilities_js_1.toString)(parts[i])) {
46
+ continue;
47
+ }
48
+ yield [parts, (0, _0_utilities_js_1.fromString)(value)];
49
+ }
50
+ }
51
+ }
52
+ }
37
53
  set(key_, value) {
38
54
  const key = this.prefix + (0, _0_utilities_js_1.toString)(key_);
39
55
  if (value != null) {