gramio 0.2.4 → 0.2.6

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.
package/dist/index.cjs CHANGED
@@ -8,31 +8,10 @@ var files = require('@gramio/files');
8
8
  var format = require('@gramio/format');
9
9
  var debug = require('debug');
10
10
  var inspectable = require('inspectable');
11
+ var utils = require('./utils-BbVj3DtT.cjs');
11
12
  var middlewareIo = require('middleware-io');
12
13
  var keyboards = require('@gramio/keyboards');
13
14
 
14
- const ErrorKind = Symbol("ErrorKind");
15
- class TelegramError extends Error {
16
- /** Name of the API Method */
17
- method;
18
- /** Params that were sent */
19
- params;
20
- /** See {@link TelegramAPIResponseError.error_code}*/
21
- code;
22
- /** Describes why a request was unsuccessful. */
23
- payload;
24
- /** Construct new TelegramError */
25
- constructor(error, method, params) {
26
- super(error.description);
27
- this.name = method;
28
- this.method = method;
29
- this.params = params;
30
- this.code = error.error_code;
31
- if (error.parameters) this.payload = error.parameters;
32
- }
33
- }
34
- TelegramError.constructor[ErrorKind] = "TELEGRAM";
35
-
36
15
  class Composer {
37
16
  composer = middlewareIo.Composer.builder();
38
17
  length = 0;
@@ -197,7 +176,7 @@ class Plugin {
197
176
  * Register custom class-error in plugin
198
177
  **/
199
178
  error(kind, error) {
200
- error[ErrorKind] = kind;
179
+ error[utils.ErrorKind] = kind;
201
180
  this._.errorsDefinitions[kind] = error;
202
181
  return this;
203
182
  }
@@ -316,8 +295,6 @@ _init$1 = __decoratorStart$1();
316
295
  Plugin = __decorateElement$1(_init$1, 0, "Plugin", _Plugin_decorators, Plugin);
317
296
  __runInitializers$1(_init$1, 1, Plugin);
318
297
 
319
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
320
-
321
298
  class UpdateQueue {
322
299
  updateQueue = [];
323
300
  pendingUpdates = /* @__PURE__ */ new Set();
@@ -355,7 +332,7 @@ class UpdateQueue {
355
332
  this.onIdlePromise = new Promise((resolve) => {
356
333
  this.onIdleResolver = resolve;
357
334
  });
358
- await Promise.race([this.onIdlePromise, sleep(timeout)]);
335
+ await Promise.race([this.onIdlePromise, utils.sleep(timeout)]);
359
336
  this.isActive = false;
360
337
  }
361
338
  }
@@ -425,9 +402,9 @@ class Updates {
425
402
  }
426
403
  } catch (error) {
427
404
  console.error("Error received when fetching updates", error);
428
- if (error instanceof TelegramError && error.payload?.retry_after) {
429
- await sleep(error.payload.retry_after * 1e3);
430
- } else await sleep(this.bot.options.api.retryGetUpdatesWait ?? 1e3);
405
+ if (error instanceof utils.TelegramError && error.payload?.retry_after) {
406
+ await utils.sleep(error.payload.retry_after * 1e3);
407
+ } else await utils.sleep(this.bot.options.api.retryGetUpdatesWait ?? 1e3);
431
408
  }
432
409
  }
433
410
  }
@@ -512,7 +489,7 @@ class Bot {
512
489
  lazyloadPlugins = [];
513
490
  dependencies = [];
514
491
  errorsDefinitions = {
515
- TELEGRAM: TelegramError
492
+ TELEGRAM: utils.TelegramError
516
493
  };
517
494
  errorHandler(context, error) {
518
495
  if (!this.hooks.onError.length)
@@ -520,7 +497,7 @@ class Bot {
520
497
  return this.runImmutableHooks("onError", {
521
498
  context,
522
499
  //@ts-expect-error ErrorKind exists if user register error-class with .error("kind", SomeError);
523
- kind: error.constructor[ErrorKind] ?? "UNKNOWN",
500
+ kind: error.constructor[utils.ErrorKind] ?? "UNKNOWN",
524
501
  error
525
502
  });
526
503
  }
@@ -574,7 +551,7 @@ class Bot {
574
551
  }
575
552
  async _callApi(method, params = {}) {
576
553
  const debug$api$method = debug$api.extend(method);
577
- const url = `${this.options.api.baseURL}${this.options.token}/${this.options.api.useTest ? "test/" : ""}${method}`;
554
+ let url = `${this.options.api.baseURL}${this.options.token}/${this.options.api.useTest ? "test/" : ""}${method}`;
578
555
  const reqOptions = {
579
556
  method: "POST",
580
557
  ...this.options.api.fetchOptions,
@@ -592,8 +569,18 @@ class Bot {
592
569
  );
593
570
  params = context.params;
594
571
  if (params && files.isMediaUpload(method, params)) {
595
- const formData = await files.convertJsonToFormData(method, params);
596
- reqOptions.body = formData;
572
+ if (utils.IS_BUN) {
573
+ const formData = await files.convertJsonToFormData(method, params);
574
+ reqOptions.body = formData;
575
+ } else {
576
+ const [formData, paramsWithoutFiles] = await files.extractFilesToFormData(
577
+ method,
578
+ params
579
+ );
580
+ reqOptions.body = formData;
581
+ const simplifiedParams = utils.simplifyObject(paramsWithoutFiles);
582
+ url += `?${new URLSearchParams(simplifiedParams).toString()}`;
583
+ }
597
584
  } else {
598
585
  reqOptions.headers.set("Content-Type", "application/json");
599
586
  reqOptions.body = JSON.stringify(params);
@@ -603,7 +590,7 @@ class Bot {
603
590
  const data = await response.json();
604
591
  debug$api$method("response: %j", data);
605
592
  if (!data.ok) {
606
- const err = new TelegramError(data, method, params);
593
+ const err = new utils.TelegramError(data, method, params);
607
594
  this.runImmutableHooks("onResponseError", err, this.api);
608
595
  if (!params?.suppress) throw err;
609
596
  return err;
@@ -674,7 +661,7 @@ class Bot {
674
661
  * ```
675
662
  */
676
663
  error(kind, error) {
677
- error[ErrorKind] = kind;
664
+ error[utils.ErrorKind] = kind;
678
665
  this.errorsDefinitions[kind] = error;
679
666
  return this;
680
667
  }
@@ -1076,7 +1063,7 @@ class Bot {
1076
1063
  const info = await this.api.getMe({
1077
1064
  suppress: true
1078
1065
  });
1079
- if (info instanceof TelegramError) {
1066
+ if (info instanceof utils.TelegramError) {
1080
1067
  if (info.code === 404)
1081
1068
  info.message = "The bot token is incorrect. Check it in BotFather.";
1082
1069
  throw info;
@@ -1105,10 +1092,12 @@ class Bot {
1105
1092
  } = {}) {
1106
1093
  await this.init();
1107
1094
  if (!webhook) {
1108
- await this.api.deleteWebhook({
1109
- drop_pending_updates: dropPendingUpdates
1110
- // suppress: true,
1111
- });
1095
+ await utils.withRetries(
1096
+ () => this.api.deleteWebhook({
1097
+ drop_pending_updates: dropPendingUpdates
1098
+ // suppress: true,
1099
+ })
1100
+ );
1112
1101
  this.updates.startPolling({
1113
1102
  allowed_updates: allowedUpdates
1114
1103
  });
@@ -1121,12 +1110,14 @@ class Bot {
1121
1110
  return this.info;
1122
1111
  }
1123
1112
  if (this.updates.isStarted) this.updates.stopPolling();
1124
- await this.api.setWebhook({
1125
- ...webhook,
1126
- drop_pending_updates: dropPendingUpdates,
1127
- allowed_updates: allowedUpdates
1128
- // suppress: true,
1129
- });
1113
+ await utils.withRetries(
1114
+ async () => this.api.setWebhook({
1115
+ ...webhook,
1116
+ drop_pending_updates: dropPendingUpdates,
1117
+ allowed_updates: allowedUpdates
1118
+ // suppress: true,
1119
+ })
1120
+ );
1130
1121
  this.runImmutableHooks("onStart", {
1131
1122
  plugins: this.dependencies,
1132
1123
  // biome-ignore lint/style/noNonNullAssertion: bot.init() guarantees this.info
@@ -1230,11 +1221,11 @@ function webhookHandler(bot, framework, secretToken) {
1230
1221
 
1231
1222
  Symbol.metadata ??= Symbol("Symbol.metadata");
1232
1223
 
1224
+ exports.ErrorKind = utils.ErrorKind;
1225
+ exports.TelegramError = utils.TelegramError;
1233
1226
  exports.Bot = Bot;
1234
1227
  exports.Composer = Composer;
1235
- exports.ErrorKind = ErrorKind;
1236
1228
  exports.Plugin = Plugin;
1237
- exports.TelegramError = TelegramError;
1238
1229
  exports.Updates = Updates;
1239
1230
  exports.webhookHandler = webhookHandler;
1240
1231
  Object.keys(callbackData).forEach(function (k) {
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CallbackData } from '@gramio/callback-data';
2
2
  export * from '@gramio/callback-data';
3
- import { Context, UpdateName, MaybeArray, ContextType, Attachment } from '@gramio/contexts';
3
+ import { Context, UpdateName, MaybeArray, ContextType, BotLike, Attachment } from '@gramio/contexts';
4
4
  export * from '@gramio/contexts';
5
5
  import { APIMethods, TelegramResponseParameters, TelegramAPIResponseError, TelegramUser, APIMethodParams, APIMethodReturn, TelegramUpdate, TelegramReactionTypeEmojiEmoji, SetMyCommandsParams, TelegramBotCommand } from '@gramio/types';
6
6
  export * from '@gramio/types';
@@ -556,6 +556,9 @@ type FilterDefinitions = Record<string, (...args: any[]) => (context: Context<Bo
556
556
  type AnyBot = Bot<any, any>;
557
557
  /** Type of Bot that accepts any generics */
558
558
  type AnyPlugin = Plugin<any, any>;
559
+ type CallbackQueryShorthandContext<BotType extends BotLike, Trigger extends CallbackData | string | RegExp> = Omit<ContextType<BotType, "callback_query">, "data"> & BotType["__Derives"]["global"] & BotType["__Derives"]["callback_query"] & {
560
+ queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never;
561
+ };
559
562
 
560
563
  declare class UpdateQueue<Data = TelegramUpdate> {
561
564
  private updateQueue;
@@ -888,9 +891,7 @@ declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends DeriveDe
888
891
  * });
889
892
  * ```
890
893
  */
891
- callbackQuery<Trigger extends CallbackData | string | RegExp>(trigger: Trigger, handler: (context: Omit<ContextType<typeof this, "callback_query">, "data"> & Derives["global"] & Derives["callback_query"] & {
892
- queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never;
893
- }) => unknown): this;
894
+ callbackQuery<Trigger extends CallbackData | string | RegExp>(trigger: Trigger, handler: (context: CallbackQueryShorthandContext<typeof this, Trigger>) => unknown): this;
894
895
  /** Register handler to `chosen_inline_result` update */
895
896
  chosenInlineResult<Ctx = ContextType<typeof this, "chosen_inline_result"> & Derives["global"] & Derives["chosen_inline_result"]>(trigger: RegExp | string | ((context: Ctx) => boolean), handler: (context: Ctx & {
896
897
  args: RegExpMatchArray | null;
@@ -944,7 +945,7 @@ declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends DeriveDe
944
945
  * if (context.args) await context.send(`Params ${context.args[1]}`);
945
946
  * });
946
947
  */
947
- hears<Ctx = ContextType<typeof this, "message"> & Derives["global"] & Derives["message"]>(trigger: RegExp | string | ((context: Ctx) => boolean), handler: (context: Ctx & {
948
+ hears<Ctx = ContextType<typeof this, "message"> & Derives["global"] & Derives["message"], Trigger extends RegExp | string | ((context: Ctx) => boolean) = RegExp | string | ((context: Ctx) => boolean)>(trigger: Trigger, handler: (context: Ctx & {
948
949
  args: RegExpMatchArray | null;
949
950
  }) => unknown): this;
950
951
  /**
@@ -1068,4 +1069,4 @@ declare function webhookHandler<Framework extends keyof typeof frameworks>(bot:
1068
1069
  response: () => any;
1069
1070
  } ? (...args: Parameters<(typeof frameworks)[Framework]>) => ReturnType<ReturnType<(typeof frameworks)[Framework]>["response"]> : (...args: Parameters<(typeof frameworks)[Framework]>) => void;
1070
1071
 
1071
- export { type AnyBot, type AnyPlugin, Bot, type BotOptions, Composer, type DeriveDefinitions, type ErrorDefinitions, ErrorKind, type FilterDefinitions, type Handler, Hooks, type MaybePromise, type MaybeSuppressedParams, type MaybeSuppressedReturn, Plugin, type Suppress, type SuppressedAPIMethodParams, type SuppressedAPIMethodReturn, type SuppressedAPIMethods, TelegramError, Updates, type WebhookHandlers, webhookHandler };
1072
+ export { type AnyBot, type AnyPlugin, Bot, type BotOptions, type CallbackQueryShorthandContext, Composer, type DeriveDefinitions, type ErrorDefinitions, ErrorKind, type FilterDefinitions, type Handler, Hooks, type MaybePromise, type MaybeSuppressedParams, type MaybeSuppressedReturn, Plugin, type Suppress, type SuppressedAPIMethodParams, type SuppressedAPIMethodReturn, type SuppressedAPIMethods, TelegramError, Updates, type WebhookHandlers, webhookHandler };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CallbackData } from '@gramio/callback-data';
2
2
  export * from '@gramio/callback-data';
3
- import { Context, UpdateName, MaybeArray, ContextType, Attachment } from '@gramio/contexts';
3
+ import { Context, UpdateName, MaybeArray, ContextType, BotLike, Attachment } from '@gramio/contexts';
4
4
  export * from '@gramio/contexts';
5
5
  import { APIMethods, TelegramResponseParameters, TelegramAPIResponseError, TelegramUser, APIMethodParams, APIMethodReturn, TelegramUpdate, TelegramReactionTypeEmojiEmoji, SetMyCommandsParams, TelegramBotCommand } from '@gramio/types';
6
6
  export * from '@gramio/types';
@@ -556,6 +556,9 @@ type FilterDefinitions = Record<string, (...args: any[]) => (context: Context<Bo
556
556
  type AnyBot = Bot<any, any>;
557
557
  /** Type of Bot that accepts any generics */
558
558
  type AnyPlugin = Plugin<any, any>;
559
+ type CallbackQueryShorthandContext<BotType extends BotLike, Trigger extends CallbackData | string | RegExp> = Omit<ContextType<BotType, "callback_query">, "data"> & BotType["__Derives"]["global"] & BotType["__Derives"]["callback_query"] & {
560
+ queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never;
561
+ };
559
562
 
560
563
  declare class UpdateQueue<Data = TelegramUpdate> {
561
564
  private updateQueue;
@@ -888,9 +891,7 @@ declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends DeriveDe
888
891
  * });
889
892
  * ```
890
893
  */
891
- callbackQuery<Trigger extends CallbackData | string | RegExp>(trigger: Trigger, handler: (context: Omit<ContextType<typeof this, "callback_query">, "data"> & Derives["global"] & Derives["callback_query"] & {
892
- queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never;
893
- }) => unknown): this;
894
+ callbackQuery<Trigger extends CallbackData | string | RegExp>(trigger: Trigger, handler: (context: CallbackQueryShorthandContext<typeof this, Trigger>) => unknown): this;
894
895
  /** Register handler to `chosen_inline_result` update */
895
896
  chosenInlineResult<Ctx = ContextType<typeof this, "chosen_inline_result"> & Derives["global"] & Derives["chosen_inline_result"]>(trigger: RegExp | string | ((context: Ctx) => boolean), handler: (context: Ctx & {
896
897
  args: RegExpMatchArray | null;
@@ -944,7 +945,7 @@ declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends DeriveDe
944
945
  * if (context.args) await context.send(`Params ${context.args[1]}`);
945
946
  * });
946
947
  */
947
- hears<Ctx = ContextType<typeof this, "message"> & Derives["global"] & Derives["message"]>(trigger: RegExp | string | ((context: Ctx) => boolean), handler: (context: Ctx & {
948
+ hears<Ctx = ContextType<typeof this, "message"> & Derives["global"] & Derives["message"], Trigger extends RegExp | string | ((context: Ctx) => boolean) = RegExp | string | ((context: Ctx) => boolean)>(trigger: Trigger, handler: (context: Ctx & {
948
949
  args: RegExpMatchArray | null;
949
950
  }) => unknown): this;
950
951
  /**
@@ -1068,4 +1069,4 @@ declare function webhookHandler<Framework extends keyof typeof frameworks>(bot:
1068
1069
  response: () => any;
1069
1070
  } ? (...args: Parameters<(typeof frameworks)[Framework]>) => ReturnType<ReturnType<(typeof frameworks)[Framework]>["response"]> : (...args: Parameters<(typeof frameworks)[Framework]>) => void;
1070
1071
 
1071
- export { type AnyBot, type AnyPlugin, Bot, type BotOptions, Composer, type DeriveDefinitions, type ErrorDefinitions, ErrorKind, type FilterDefinitions, type Handler, Hooks, type MaybePromise, type MaybeSuppressedParams, type MaybeSuppressedReturn, Plugin, type Suppress, type SuppressedAPIMethodParams, type SuppressedAPIMethodReturn, type SuppressedAPIMethods, TelegramError, Updates, type WebhookHandlers, webhookHandler };
1072
+ export { type AnyBot, type AnyPlugin, Bot, type BotOptions, type CallbackQueryShorthandContext, Composer, type DeriveDefinitions, type ErrorDefinitions, ErrorKind, type FilterDefinitions, type Handler, Hooks, type MaybePromise, type MaybeSuppressedParams, type MaybeSuppressedReturn, Plugin, type Suppress, type SuppressedAPIMethodParams, type SuppressedAPIMethodReturn, type SuppressedAPIMethods, TelegramError, Updates, type WebhookHandlers, webhookHandler };
package/dist/index.js CHANGED
@@ -4,37 +4,16 @@ import { CallbackData } from '@gramio/callback-data';
4
4
  export * from '@gramio/callback-data';
5
5
  import { contextsMappings, PhotoAttachment } from '@gramio/contexts';
6
6
  export * from '@gramio/contexts';
7
- import { isMediaUpload, convertJsonToFormData } from '@gramio/files';
7
+ import { isMediaUpload, convertJsonToFormData, extractFilesToFormData } from '@gramio/files';
8
8
  export * from '@gramio/files';
9
9
  import { FormattableMap } from '@gramio/format';
10
10
  export * from '@gramio/format';
11
11
  import debug from 'debug';
12
12
  import { Inspectable } from 'inspectable';
13
+ import { E as ErrorKind, s as sleep, T as TelegramError, I as IS_BUN, a as simplifyObject, w as withRetries } from './utils-DTFsIb2X.js';
13
14
  import { Composer as Composer$1, noopNext } from 'middleware-io';
14
15
  export * from '@gramio/keyboards';
15
16
 
16
- const ErrorKind = Symbol("ErrorKind");
17
- class TelegramError extends Error {
18
- /** Name of the API Method */
19
- method;
20
- /** Params that were sent */
21
- params;
22
- /** See {@link TelegramAPIResponseError.error_code}*/
23
- code;
24
- /** Describes why a request was unsuccessful. */
25
- payload;
26
- /** Construct new TelegramError */
27
- constructor(error, method, params) {
28
- super(error.description);
29
- this.name = method;
30
- this.method = method;
31
- this.params = params;
32
- this.code = error.error_code;
33
- if (error.parameters) this.payload = error.parameters;
34
- }
35
- }
36
- TelegramError.constructor[ErrorKind] = "TELEGRAM";
37
-
38
17
  class Composer {
39
18
  composer = Composer$1.builder();
40
19
  length = 0;
@@ -318,8 +297,6 @@ _init$1 = __decoratorStart$1();
318
297
  Plugin = __decorateElement$1(_init$1, 0, "Plugin", _Plugin_decorators, Plugin);
319
298
  __runInitializers$1(_init$1, 1, Plugin);
320
299
 
321
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
322
-
323
300
  class UpdateQueue {
324
301
  updateQueue = [];
325
302
  pendingUpdates = /* @__PURE__ */ new Set();
@@ -576,7 +553,7 @@ class Bot {
576
553
  }
577
554
  async _callApi(method, params = {}) {
578
555
  const debug$api$method = debug$api.extend(method);
579
- const url = `${this.options.api.baseURL}${this.options.token}/${this.options.api.useTest ? "test/" : ""}${method}`;
556
+ let url = `${this.options.api.baseURL}${this.options.token}/${this.options.api.useTest ? "test/" : ""}${method}`;
580
557
  const reqOptions = {
581
558
  method: "POST",
582
559
  ...this.options.api.fetchOptions,
@@ -594,8 +571,18 @@ class Bot {
594
571
  );
595
572
  params = context.params;
596
573
  if (params && isMediaUpload(method, params)) {
597
- const formData = await convertJsonToFormData(method, params);
598
- reqOptions.body = formData;
574
+ if (IS_BUN) {
575
+ const formData = await convertJsonToFormData(method, params);
576
+ reqOptions.body = formData;
577
+ } else {
578
+ const [formData, paramsWithoutFiles] = await extractFilesToFormData(
579
+ method,
580
+ params
581
+ );
582
+ reqOptions.body = formData;
583
+ const simplifiedParams = simplifyObject(paramsWithoutFiles);
584
+ url += `?${new URLSearchParams(simplifiedParams).toString()}`;
585
+ }
599
586
  } else {
600
587
  reqOptions.headers.set("Content-Type", "application/json");
601
588
  reqOptions.body = JSON.stringify(params);
@@ -1107,10 +1094,12 @@ class Bot {
1107
1094
  } = {}) {
1108
1095
  await this.init();
1109
1096
  if (!webhook) {
1110
- await this.api.deleteWebhook({
1111
- drop_pending_updates: dropPendingUpdates
1112
- // suppress: true,
1113
- });
1097
+ await withRetries(
1098
+ () => this.api.deleteWebhook({
1099
+ drop_pending_updates: dropPendingUpdates
1100
+ // suppress: true,
1101
+ })
1102
+ );
1114
1103
  this.updates.startPolling({
1115
1104
  allowed_updates: allowedUpdates
1116
1105
  });
@@ -1123,12 +1112,14 @@ class Bot {
1123
1112
  return this.info;
1124
1113
  }
1125
1114
  if (this.updates.isStarted) this.updates.stopPolling();
1126
- await this.api.setWebhook({
1127
- ...webhook,
1128
- drop_pending_updates: dropPendingUpdates,
1129
- allowed_updates: allowedUpdates
1130
- // suppress: true,
1131
- });
1115
+ await withRetries(
1116
+ async () => this.api.setWebhook({
1117
+ ...webhook,
1118
+ drop_pending_updates: dropPendingUpdates,
1119
+ allowed_updates: allowedUpdates
1120
+ // suppress: true,
1121
+ })
1122
+ );
1132
1123
  this.runImmutableHooks("onStart", {
1133
1124
  plugins: this.dependencies,
1134
1125
  // biome-ignore lint/style/noNonNullAssertion: bot.init() guarantees this.info
@@ -0,0 +1,72 @@
1
+ 'use strict';
2
+
3
+ const ErrorKind = Symbol("ErrorKind");
4
+ class TelegramError extends Error {
5
+ /** Name of the API Method */
6
+ method;
7
+ /** Params that were sent */
8
+ params;
9
+ /** See {@link TelegramAPIResponseError.error_code}*/
10
+ code;
11
+ /** Describes why a request was unsuccessful. */
12
+ payload;
13
+ /** Construct new TelegramError */
14
+ constructor(error, method, params) {
15
+ super(error.description);
16
+ this.name = method;
17
+ this.method = method;
18
+ this.params = params;
19
+ this.code = error.error_code;
20
+ if (error.parameters) this.payload = error.parameters;
21
+ }
22
+ }
23
+ TelegramError.constructor[ErrorKind] = "TELEGRAM";
24
+
25
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
26
+ function convertToString(value) {
27
+ const typeOfValue = typeof value;
28
+ if (typeOfValue === "string") return value;
29
+ if (typeOfValue === "object") return JSON.stringify(value);
30
+ return String(value);
31
+ }
32
+ function simplifyObject(obj) {
33
+ const result = {};
34
+ for (const [key, value] of Object.entries(obj)) {
35
+ const typeOfValue = typeof value;
36
+ if (value === void 0 || value === null || typeOfValue === "function")
37
+ continue;
38
+ result[key] = convertToString(value);
39
+ }
40
+ return result;
41
+ }
42
+ const IS_BUN = typeof Bun !== "undefined";
43
+
44
+ async function suppressError(fn) {
45
+ try {
46
+ return [await fn(), false];
47
+ } catch (error) {
48
+ return [error, true];
49
+ }
50
+ }
51
+ async function withRetries(resultPromise) {
52
+ let [result, isFromCatch] = await suppressError(resultPromise);
53
+ while (result instanceof TelegramError) {
54
+ const retryAfter = result.payload?.retry_after;
55
+ if (retryAfter) {
56
+ await sleep(retryAfter * 1e3);
57
+ [result, isFromCatch] = await suppressError(resultPromise);
58
+ } else {
59
+ if (isFromCatch) throw result;
60
+ return result;
61
+ }
62
+ }
63
+ if (result instanceof Error && isFromCatch) throw result;
64
+ return result;
65
+ }
66
+
67
+ exports.ErrorKind = ErrorKind;
68
+ exports.IS_BUN = IS_BUN;
69
+ exports.TelegramError = TelegramError;
70
+ exports.simplifyObject = simplifyObject;
71
+ exports.sleep = sleep;
72
+ exports.withRetries = withRetries;
@@ -0,0 +1,65 @@
1
+ const ErrorKind = Symbol("ErrorKind");
2
+ class TelegramError extends Error {
3
+ /** Name of the API Method */
4
+ method;
5
+ /** Params that were sent */
6
+ params;
7
+ /** See {@link TelegramAPIResponseError.error_code}*/
8
+ code;
9
+ /** Describes why a request was unsuccessful. */
10
+ payload;
11
+ /** Construct new TelegramError */
12
+ constructor(error, method, params) {
13
+ super(error.description);
14
+ this.name = method;
15
+ this.method = method;
16
+ this.params = params;
17
+ this.code = error.error_code;
18
+ if (error.parameters) this.payload = error.parameters;
19
+ }
20
+ }
21
+ TelegramError.constructor[ErrorKind] = "TELEGRAM";
22
+
23
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
+ function convertToString(value) {
25
+ const typeOfValue = typeof value;
26
+ if (typeOfValue === "string") return value;
27
+ if (typeOfValue === "object") return JSON.stringify(value);
28
+ return String(value);
29
+ }
30
+ function simplifyObject(obj) {
31
+ const result = {};
32
+ for (const [key, value] of Object.entries(obj)) {
33
+ const typeOfValue = typeof value;
34
+ if (value === void 0 || value === null || typeOfValue === "function")
35
+ continue;
36
+ result[key] = convertToString(value);
37
+ }
38
+ return result;
39
+ }
40
+ const IS_BUN = typeof Bun !== "undefined";
41
+
42
+ async function suppressError(fn) {
43
+ try {
44
+ return [await fn(), false];
45
+ } catch (error) {
46
+ return [error, true];
47
+ }
48
+ }
49
+ async function withRetries(resultPromise) {
50
+ let [result, isFromCatch] = await suppressError(resultPromise);
51
+ while (result instanceof TelegramError) {
52
+ const retryAfter = result.payload?.retry_after;
53
+ if (retryAfter) {
54
+ await sleep(retryAfter * 1e3);
55
+ [result, isFromCatch] = await suppressError(resultPromise);
56
+ } else {
57
+ if (isFromCatch) throw result;
58
+ return result;
59
+ }
60
+ }
61
+ if (result instanceof Error && isFromCatch) throw result;
62
+ return result;
63
+ }
64
+
65
+ export { ErrorKind as E, IS_BUN as I, TelegramError as T, simplifyObject as a, sleep as s, withRetries as w };
package/dist/utils.cjs ADDED
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ var utils = require('./utils-BbVj3DtT.cjs');
4
+
5
+
6
+
7
+ exports.withRetries = utils.withRetries;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Pack of useful utilities for Telegram Bot API and GramIO
5
+ */
6
+ declare function withRetries<Result extends Promise<unknown>>(resultPromise: () => Result): Promise<Result>;
7
+
8
+ export { withRetries };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Pack of useful utilities for Telegram Bot API and GramIO
5
+ */
6
+ declare function withRetries<Result extends Promise<unknown>>(resultPromise: () => Result): Promise<Result>;
7
+
8
+ export { withRetries };
package/dist/utils.js ADDED
@@ -0,0 +1 @@
1
+ export { w as withRetries } from './utils-DTFsIb2X.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gramio",
3
3
  "type": "module",
4
- "version": "0.2.4",
4
+ "version": "0.2.6",
5
5
  "description": "Powerful, extensible and really type-safe Telegram Bot API framework",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",
@@ -16,6 +16,16 @@
16
16
  "types": "./dist/index.d.cts",
17
17
  "default": "./dist/index.cjs"
18
18
  }
19
+ },
20
+ "./utils": {
21
+ "import": {
22
+ "types": "./dist/utils.d.ts",
23
+ "default": "./dist/utils.js"
24
+ },
25
+ "require": {
26
+ "types": "./dist/utils.d.cts",
27
+ "default": "./dist/utils.cjs"
28
+ }
19
29
  }
20
30
  },
21
31
  "keywords": [
@@ -41,18 +51,18 @@
41
51
  "license": "MIT",
42
52
  "devDependencies": {
43
53
  "@biomejs/biome": "1.9.4",
44
- "@types/bun": "^1.2.2",
54
+ "@types/bun": "^1.2.8",
45
55
  "@types/debug": "^4.1.12",
46
- "pkgroll": "^2.8.2",
47
- "typescript": "^5.7.3"
56
+ "pkgroll": "^2.12.1",
57
+ "typescript": "^5.8.3"
48
58
  },
49
59
  "dependencies": {
50
60
  "@gramio/callback-data": "^0.0.3",
51
- "@gramio/contexts": "^0.1.3",
52
- "@gramio/files": "^0.1.2",
61
+ "@gramio/contexts": "^0.1.5",
62
+ "@gramio/files": "^0.2.0",
53
63
  "@gramio/format": "^0.1.5",
54
64
  "@gramio/keyboards": "^1.1.0",
55
- "@gramio/types": "^8.3.1",
65
+ "@gramio/types": "^8.3.3",
56
66
  "debug": "^4.4.0",
57
67
  "inspectable": "^3.0.2",
58
68
  "middleware-io": "^2.8.1"