@effect-ak/tg-bot-client 0.6.4 → 1.0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ClientFileService: () => ClientFileService,
34
+ MESSAGE_EFFECTS: () => MESSAGE_EFFECTS,
35
+ TG_BOT_API_URL: () => TG_BOT_API_URL,
36
+ TgBotApiBaseUrl: () => TgBotApiBaseUrl,
37
+ TgBotApiToken: () => TgBotApiToken,
38
+ TgBotClientError: () => TgBotClientError,
39
+ executeTgBotMethod: () => executeTgBotMethod,
40
+ isFileContent: () => isFileContent,
41
+ isMessageEffect: () => isMessageEffect,
42
+ isTgBotApiResponse: () => isTgBotApiResponse,
43
+ isTgBotApiUpdate: () => isTgBotApiUpdate,
44
+ makePayload: () => makePayload,
45
+ makeTgBotClient: () => makeTgBotClient,
46
+ messageEffectIdCodes: () => messageEffectIdCodes
47
+ });
48
+ module.exports = __toCommonJS(index_exports);
49
+
50
+ // src/execute.ts
51
+ var String = __toESM(require("effect/String"), 1);
52
+ var Micro = __toESM(require("effect/Micro"), 1);
53
+
54
+ // src/errors.ts
55
+ var Data = __toESM(require("effect/Data"), 1);
56
+ var TgBotClientError = class extends Data.TaggedError("TgBotClientError") {
57
+ };
58
+
59
+ // src/guards.ts
60
+ var isFileContent = (input) => typeof input == "object" && input != null && "file_content" in input && input.file_content instanceof Uint8Array && "file_name" in input && typeof input.file_name == "string";
61
+ var isTgBotApiResponse = (input) => typeof input == "object" && input != null && "ok" in input && typeof input.ok == "boolean";
62
+ var isTgBotApiUpdate = (input) => typeof input == "object" && input != null && "update_id" in input && typeof input.update_id == "number";
63
+
64
+ // src/config.ts
65
+ var Context = __toESM(require("effect/Context"), 1);
66
+
67
+ // src/const.ts
68
+ var TG_BOT_API_URL = "https://api.telegram.org";
69
+ var MESSAGE_EFFECTS = {
70
+ "\u{1F525}": "5104841245755180586",
71
+ "\u{1F44D}": "5107584321108051014",
72
+ "\u{1F44E}": "5104858069142078462",
73
+ "\u2764\uFE0F": "5159385139981059251",
74
+ "\u{1F389}": "5046509860389126442",
75
+ "\u{1F4A9}": "5046589136895476101"
76
+ };
77
+ var messageEffectIdCodes = Object.keys(
78
+ MESSAGE_EFFECTS
79
+ );
80
+ var isMessageEffect = (input) => {
81
+ return typeof input === "string" && input in MESSAGE_EFFECTS;
82
+ };
83
+
84
+ // src/config.ts
85
+ var TgBotApiBaseUrl = class extends Context.Reference()(
86
+ "TgBotApiBaseUrl",
87
+ { defaultValue: () => TG_BOT_API_URL }
88
+ ) {
89
+ };
90
+ var TgBotApiToken = class extends Context.Tag("TgBotApiToken")() {
91
+ };
92
+
93
+ // src/execute.ts
94
+ var executeTgBotMethod = (method, input) => Micro.gen(function* () {
95
+ const botToken = yield* Micro.service(TgBotApiToken);
96
+ const baseUrl = yield* Micro.service(TgBotApiBaseUrl);
97
+ const httpResponse = yield* Micro.tryPromise({
98
+ try: () => fetch(`${baseUrl}/bot${botToken}/${String.snakeToCamel(method)}`, {
99
+ body: makePayload(input) ?? null,
100
+ method: "POST"
101
+ }),
102
+ catch: (cause) => new TgBotClientError({
103
+ cause: { _tag: "ClientInternalError", cause }
104
+ })
105
+ });
106
+ const response = yield* Micro.tryPromise({
107
+ try: () => httpResponse.json(),
108
+ catch: () => new TgBotClientError({
109
+ cause: { _tag: "NotJsonResponse", response: httpResponse }
110
+ })
111
+ });
112
+ if (!isTgBotApiResponse(response)) {
113
+ return yield* Micro.fail(
114
+ new TgBotClientError({
115
+ cause: { _tag: "UnexpectedResponse", response }
116
+ })
117
+ );
118
+ }
119
+ if (!httpResponse.ok) {
120
+ return yield* Micro.fail(
121
+ new TgBotClientError({
122
+ cause: {
123
+ _tag: "NotOkResponse",
124
+ ...response.error_code ? { errorCode: response.error_code } : void 0,
125
+ ...response.description ? { details: response.description } : void 0
126
+ }
127
+ })
128
+ );
129
+ }
130
+ return response.result;
131
+ });
132
+ var makePayload = (body) => {
133
+ const entries = Object.entries(body);
134
+ if (entries.length == 0) return void 0;
135
+ const result = new FormData();
136
+ for (const [key, value] of entries) {
137
+ if (!value) continue;
138
+ if (typeof value != "object") {
139
+ result.append(key, `${value}`);
140
+ } else if (isFileContent(value)) {
141
+ result.append(key, new Blob([value.file_content]), value.file_name);
142
+ } else {
143
+ result.append(key, JSON.stringify(value));
144
+ }
145
+ }
146
+ return result;
147
+ };
148
+
149
+ // src/client-file.ts
150
+ var Micro2 = __toESM(require("effect/Micro"), 1);
151
+ var Context2 = __toESM(require("effect/Context"), 1);
152
+ var ClientFileService = class _ClientFileService extends Context2.Tag("ClientFileService")() {
153
+ static live = () => {
154
+ return _ClientFileService.context({
155
+ getFile
156
+ });
157
+ };
158
+ };
159
+ var getFile = ({ fileId, type }) => getFileBytes(fileId).pipe(
160
+ Micro2.andThen(
161
+ ({ content, file_name }) => new File([content], file_name, {
162
+ ...type ? { type } : void 0
163
+ })
164
+ )
165
+ );
166
+ var getFileBytes = (fileId) => Micro2.gen(function* () {
167
+ const response = yield* executeTgBotMethod("get_file", { file_id: fileId });
168
+ const file_path = response.file_path;
169
+ if (!file_path || file_path.length == 0) {
170
+ return yield* Micro2.fail(
171
+ new TgBotClientError({
172
+ cause: {
173
+ _tag: "UnableToGetFile",
174
+ cause: "File path not defined"
175
+ }
176
+ })
177
+ );
178
+ }
179
+ const file_name = file_path.replaceAll("/", "-");
180
+ const baseUrl = yield* Micro2.service(TgBotApiBaseUrl);
181
+ const botToken = yield* Micro2.service(TgBotApiToken);
182
+ const url = `${baseUrl}/file/bot${botToken}/${file_path}`;
183
+ const content = yield* Micro2.tryPromise({
184
+ try: () => fetch(url).then((_) => _.arrayBuffer()),
185
+ catch: (cause) => new TgBotClientError({
186
+ cause: { _tag: "UnableToGetFile", cause }
187
+ })
188
+ });
189
+ return {
190
+ content,
191
+ file_name
192
+ };
193
+ });
194
+
195
+ // src/client.ts
196
+ var Micro3 = __toESM(require("effect/Micro"), 1);
197
+ var Context3 = __toESM(require("effect/Context"), 1);
198
+ function makeTgBotClient(config) {
199
+ return createEffect(config).pipe(Micro3.runSync);
200
+ }
201
+ var createEffect = ({ bot_token }) => Micro3.gen(function* () {
202
+ const file = yield* Micro3.service(ClientFileService);
203
+ const context = Context3.make(TgBotApiToken, bot_token);
204
+ const execute = (method, input) => executeTgBotMethod(method, input).pipe(
205
+ Micro3.provideContext(context),
206
+ Micro3.runPromise
207
+ );
208
+ const getFile2 = (input) => file.getFile(input).pipe(Micro3.provideContext(context), Micro3.runPromise);
209
+ return {
210
+ execute,
211
+ getFile: getFile2
212
+ };
213
+ }).pipe(Micro3.provideContext(ClientFileService.live()));
214
+ // Annotate the CommonJS export names for ESM import in node:
215
+ 0 && (module.exports = {
216
+ ClientFileService,
217
+ MESSAGE_EFFECTS,
218
+ TG_BOT_API_URL,
219
+ TgBotApiBaseUrl,
220
+ TgBotApiToken,
221
+ TgBotClientError,
222
+ executeTgBotMethod,
223
+ isFileContent,
224
+ isMessageEffect,
225
+ isTgBotApiResponse,
226
+ isTgBotApiUpdate,
227
+ makePayload,
228
+ makeTgBotClient,
229
+ messageEffectIdCodes
230
+ });
@@ -0,0 +1,95 @@
1
+ import * as Micro from 'effect/Micro';
2
+ import { Api, Update } from '@effect-ak/tg-bot-api';
3
+ import * as effect_Cause from 'effect/Cause';
4
+ import * as effect_Types from 'effect/Types';
5
+ import * as Data from 'effect/Data';
6
+ import * as Context from 'effect/Context';
7
+
8
+ type ErrorReason = Data.TaggedEnum<{
9
+ NotOkResponse: {
10
+ errorCode?: number;
11
+ details?: string;
12
+ };
13
+ UnexpectedResponse: {
14
+ response: unknown;
15
+ };
16
+ ClientInternalError: {
17
+ cause: unknown;
18
+ };
19
+ UnableToGetFile: {
20
+ cause: unknown;
21
+ };
22
+ BotHandlerError: {
23
+ cause: unknown;
24
+ };
25
+ NotJsonResponse: {
26
+ response: unknown;
27
+ };
28
+ }>;
29
+ declare const TgBotClientError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
30
+ readonly _tag: "TgBotClientError";
31
+ } & Readonly<A>;
32
+ declare class TgBotClientError extends TgBotClientError_base<{
33
+ cause: ErrorReason;
34
+ }> {
35
+ }
36
+
37
+ declare const TgBotApiBaseUrl_base: Context.ReferenceClass<TgBotApiBaseUrl, "TgBotApiBaseUrl", string>;
38
+ declare class TgBotApiBaseUrl extends TgBotApiBaseUrl_base {
39
+ }
40
+ declare const TgBotApiToken_base: Context.TagClass<TgBotApiToken, "TgBotApiToken", string>;
41
+ declare class TgBotApiToken extends TgBotApiToken_base {
42
+ }
43
+
44
+ declare const executeTgBotMethod: <M extends keyof Api>(method: M, input: Parameters<Api[M]>[0]) => Micro.Micro<ReturnType<Api[M]>, TgBotClientError, TgBotApiToken>;
45
+ declare const makePayload: (body: object) => FormData | undefined;
46
+
47
+ declare const ClientFileService_base: Context.TagClass<ClientFileService, "ClientFileService", {
48
+ getFile: (input: GetFile) => ReturnType<typeof getFile>;
49
+ }>;
50
+ declare class ClientFileService extends ClientFileService_base {
51
+ static live: () => Context.Context<ClientFileService>;
52
+ }
53
+ interface GetFile {
54
+ fileId: string;
55
+ type?: string;
56
+ }
57
+ declare const getFile: ({ fileId, type }: GetFile) => Micro.Micro<File, TgBotClientError, TgBotApiToken>;
58
+
59
+ interface TgBotClient {
60
+ readonly execute: <M extends keyof Api>(method: M, input: Parameters<Api[M]>[0]) => Promise<ReturnType<Api[M]>>;
61
+ readonly getFile: (input: GetFile) => Promise<File>;
62
+ }
63
+ interface MakeTgClient {
64
+ bot_token: string;
65
+ }
66
+ declare function makeTgBotClient(config: MakeTgClient): TgBotClient;
67
+
68
+ interface FileContent {
69
+ file_content: Uint8Array<ArrayBuffer>;
70
+ file_name: string;
71
+ }
72
+ declare const isFileContent: (input: unknown) => input is FileContent;
73
+ interface TgBotApiResponseSchema {
74
+ ok: boolean;
75
+ error_code?: number;
76
+ description?: string;
77
+ result?: unknown;
78
+ }
79
+ declare const isTgBotApiResponse: (input: unknown) => input is TgBotApiResponseSchema;
80
+ declare const isTgBotApiUpdate: (input: unknown) => input is Update;
81
+
82
+ declare const TG_BOT_API_URL = "https://api.telegram.org";
83
+ declare const MESSAGE_EFFECTS: {
84
+ readonly "\uD83D\uDD25": "5104841245755180586";
85
+ readonly "\uD83D\uDC4D": "5107584321108051014";
86
+ readonly "\uD83D\uDC4E": "5104858069142078462";
87
+ readonly "\u2764\uFE0F": "5159385139981059251";
88
+ readonly "\uD83C\uDF89": "5046509860389126442";
89
+ readonly "\uD83D\uDCA9": "5046589136895476101";
90
+ };
91
+ type MessageEffect = keyof typeof MESSAGE_EFFECTS;
92
+ declare const messageEffectIdCodes: MessageEffect[];
93
+ declare const isMessageEffect: (input: unknown) => input is MessageEffect;
94
+
95
+ export { ClientFileService, type FileContent, type GetFile, MESSAGE_EFFECTS, type MessageEffect, TG_BOT_API_URL, TgBotApiBaseUrl, type TgBotApiResponseSchema, TgBotApiToken, type TgBotClient, TgBotClientError, executeTgBotMethod, isFileContent, isMessageEffect, isTgBotApiResponse, isTgBotApiUpdate, makePayload, makeTgBotClient, messageEffectIdCodes };
package/dist/index.d.ts CHANGED
@@ -1,49 +1,81 @@
1
1
  import * as Micro from 'effect/Micro';
2
- import { A as Api, T as TgBotClientError, a as TgBotApiToken, U as Update } from './config-3uU0YevV.js';
3
- export { bK as AcceptedGiftTypes, c as AddStickerToSetInput, bL as AffiliateInfo, bJ as AllowedUpdateName, bM as Animation, d as AnswerCallbackQueryInput, e as AnswerInlineQueryInput, f as AnswerPreCheckoutQueryInput, g as AnswerShippingQueryInput, h as AnswerWebAppQueryInput, i as ApproveChatJoinRequestInput, j as ApproveSuggestedPostInput, bN as Audio, bO as BackgroundFill, bP as BackgroundFillFreeformGradient, bQ as BackgroundFillGradient, bR as BackgroundFillSolid, bS as BackgroundType, bT as BackgroundTypeChatTheme, bU as BackgroundTypeFill, bV as BackgroundTypePattern, bW as BackgroundTypeWallpaper, B as BanChatMemberInput, k as BanChatSenderChatInput, bX as Birthdate, bY as BotCommand, bZ as BotCommandScope, b_ as BotCommandScopeAllChatAdministrators, b$ as BotCommandScopeAllGroupChats, c0 as BotCommandScopeAllPrivateChats, c1 as BotCommandScopeChat, c2 as BotCommandScopeChatAdministrators, c3 as BotCommandScopeChatMember, c4 as BotCommandScopeDefault, c5 as BotDescription, c6 as BotName, c7 as BotShortDescription, c8 as BusinessBotRights, c9 as BusinessConnection, ca as BusinessIntro, cb as BusinessLocation, cc as BusinessMessagesDeleted, cd as BusinessOpeningHours, ce as BusinessOpeningHoursInterval, cf as CallbackGame, cg as CallbackQuery, ch as Chat, ci as ChatAdministratorRights, cj as ChatBackground, ck as ChatBoost, cl as ChatBoostAdded, cm as ChatBoostRemoved, cn as ChatBoostSource, co as ChatBoostSourceGiftCode, cp as ChatBoostSourceGiveaway, cq as ChatBoostSourcePremium, cr as ChatBoostUpdated, cs as ChatFullInfo, ct as ChatInviteLink, cu as ChatJoinRequest, cv as ChatLocation, cw as ChatMember, cx as ChatMemberAdministrator, cy as ChatMemberBanned, cz as ChatMemberLeft, cA as ChatMemberMember, cB as ChatMemberOwner, cC as ChatMemberRestricted, cD as ChatMemberUpdated, cE as ChatPermissions, cF as ChatPhoto, cG as ChatShared, cH as Checklist, cI as ChecklistTask, cJ as ChecklistTasksAdded, cK as ChecklistTasksDone, cL as ChosenInlineResult, l as CloseForumTopicInput, m as CloseGeneralForumTopicInput, C as CloseInput, cM as Contact, n as ConvertGiftToStarsInput, o as CopyMessageInput, p as CopyMessagesInput, cN as CopyTextButton, q as CreateChatInviteLinkInput, r as CreateChatSubscriptionInviteLinkInput, s as CreateForumTopicInput, t as CreateInvoiceLinkInput, u as CreateNewStickerSetInput, D as DeclineChatJoinRequestInput, v as DeclineSuggestedPostInput, w as DeleteBusinessMessagesInput, x as DeleteChatPhotoInput, y as DeleteChatStickerSetInput, z as DeleteForumTopicInput, E as DeleteMessageInput, F as DeleteMessagesInput, G as DeleteMyCommandsInput, H as DeleteStickerFromSetInput, I as DeleteStickerSetInput, J as DeleteStoryInput, K as DeleteWebhookInput, cO as Dice, cP as DirectMessagePriceChanged, cQ as DirectMessagesTopic, cR as Document, L as EditChatInviteLinkInput, M as EditChatSubscriptionInviteLinkInput, N as EditForumTopicInput, O as EditGeneralForumTopicInput, P as EditMessageCaptionInput, Q as EditMessageChecklistInput, R as EditMessageLiveLocationInput, S as EditMessageMediaInput, V as EditMessageReplyMarkupInput, W as EditMessageTextInput, X as EditStoryInput, Y as EditUserStarSubscriptionInput, cS as EncryptedCredentials, cT as EncryptedPassportElement, Z as ExportChatInviteLinkInput, cU as ExternalReplyInfo, cV as File, cW as ForceReply, cX as ForumTopic, cY as ForumTopicClosed, cZ as ForumTopicCreated, c_ as ForumTopicEdited, c$ as ForumTopicReopened, _ as ForwardMessageInput, $ as ForwardMessagesInput, d0 as Game, d1 as GameHighScore, d2 as GeneralForumTopicHidden, d3 as GeneralForumTopicUnhidden, a0 as GetAvailableGiftsInput, a1 as GetBusinessAccountGiftsInput, a2 as GetBusinessAccountStarBalanceInput, a3 as GetBusinessConnectionInput, a5 as GetChatAdministratorsInput, a4 as GetChatInput, a7 as GetChatMemberCountInput, a6 as GetChatMemberInput, a8 as GetChatMenuButtonInput, a9 as GetCustomEmojiStickersInput, aa as GetFileInput, ab as GetForumTopicIconStickersInput, ac as GetGameHighScoresInput, ad as GetMeInput, ae as GetMyCommandsInput, af as GetMyDefaultAdministratorRightsInput, ag as GetMyDescriptionInput, ah as GetMyNameInput, ai as GetMyShortDescriptionInput, aj as GetMyStarBalanceInput, ak as GetStarTransactionsInput, al as GetStickerSetInput, am as GetUpdatesInput, an as GetUserChatBoostsInput, ao as GetUserProfilePhotosInput, ap as GetWebhookInfoInput, d4 as Gift, d5 as GiftInfo, aq as GiftPremiumSubscriptionInput, d6 as Gifts, d7 as Giveaway, d8 as GiveawayCompleted, d9 as GiveawayCreated, da as GiveawayWinners, ar as HideGeneralForumTopicInput, db as InaccessibleMessage, dc as InlineKeyboardButton, dd as InlineKeyboardMarkup, de as InlineQuery, df as InlineQueryResult, dg as InlineQueryResultArticle, dh as InlineQueryResultAudio, di as InlineQueryResultCachedAudio, dj as InlineQueryResultCachedDocument, dk as InlineQueryResultCachedGif, dl as InlineQueryResultCachedMpeg4Gif, dm as InlineQueryResultCachedPhoto, dn as InlineQueryResultCachedSticker, dp as InlineQueryResultCachedVideo, dq as InlineQueryResultCachedVoice, dr as InlineQueryResultContact, ds as InlineQueryResultDocument, dt as InlineQueryResultGame, du as InlineQueryResultGif, dv as InlineQueryResultLocation, dw as InlineQueryResultMpeg4Gif, dx as InlineQueryResultPhoto, dz as InlineQueryResultVenue, dA as InlineQueryResultVideo, dB as InlineQueryResultVoice, dy as InlineQueryResultsButton, dC as InputChecklist, dD as InputChecklistTask, dE as InputContactMessageContent, dF as InputFile, dG as InputInvoiceMessageContent, dH as InputLocationMessageContent, dI as InputMedia, dJ as InputMediaAnimation, dK as InputMediaAudio, dL as InputMediaDocument, dM as InputMediaPhoto, dN as InputMediaVideo, dO as InputMessageContent, dP as InputPaidMedia, dQ as InputPaidMediaPhoto, dR as InputPaidMediaVideo, dS as InputPollOption, dT as InputProfilePhoto, dU as InputProfilePhotoAnimated, dV as InputProfilePhotoStatic, dW as InputSticker, dX as InputStoryContent, dY as InputStoryContentPhoto, dZ as InputStoryContentVideo, d_ as InputTextMessageContent, d$ as InputVenueMessageContent, e0 as Invoice, e1 as KeyboardButton, e2 as KeyboardButtonPollType, e3 as KeyboardButtonRequestChat, e4 as KeyboardButtonRequestUsers, e5 as LabeledPrice, as as LeaveChatInput, e6 as LinkPreviewOptions, e7 as Location, e8 as LocationAddress, at as LogOutInput, e9 as LoginUrl, ea as MaskPosition, eb as MaybeInaccessibleMessage, ec as MenuButton, ed as MenuButtonCommands, ee as MenuButtonDefault, ef as MenuButtonWebApp, eg as Message, eh as MessageAutoDeleteTimerChanged, ei as MessageEntity, ej as MessageId, ek as MessageOrigin, el as MessageOriginChannel, em as MessageOriginChat, en as MessageOriginHiddenUser, eo as MessageOriginUser, ep as MessageReactionCountUpdated, eq as MessageReactionUpdated, er as OrderInfo, es as OwnedGift, et as OwnedGiftRegular, ev as OwnedGiftUnique, eu as OwnedGifts, ew as PaidMedia, ex as PaidMediaInfo, ey as PaidMediaPhoto, ez as PaidMediaPreview, eA as PaidMediaPurchased, eB as PaidMediaVideo, eC as PaidMessagePriceChanged, eD as PassportData, eE as PassportElementError, eF as PassportElementErrorDataField, eG as PassportElementErrorFile, eH as PassportElementErrorFiles, eI as PassportElementErrorFrontSide, eJ as PassportElementErrorReverseSide, eK as PassportElementErrorSelfie, eL as PassportElementErrorTranslationFile, eM as PassportElementErrorTranslationFiles, eN as PassportElementErrorUnspecified, eO as PassportFile, eP as PhotoSize, au as PinChatMessageInput, eQ as Poll, eR as PollAnswer, eS as PollOption, av as PostStoryInput, eT as PreCheckoutQuery, eU as PreparedInlineMessage, aw as PromoteChatMemberInput, eV as ProximityAlertTriggered, eW as ReactionCount, eX as ReactionType, eY as ReactionTypeCustomEmoji, eZ as ReactionTypeEmoji, e_ as ReactionTypePaid, ax as ReadBusinessMessageInput, ay as RefundStarPaymentInput, e$ as RefundedPayment, az as RemoveBusinessAccountProfilePhotoInput, aA as RemoveChatVerificationInput, aB as RemoveUserVerificationInput, aC as ReopenForumTopicInput, aD as ReopenGeneralForumTopicInput, aE as ReplaceStickerInSetInput, f0 as ReplyKeyboardMarkup, f1 as ReplyKeyboardRemove, f2 as ReplyParameters, f3 as ResponseParameters, aF as RestrictChatMemberInput, f4 as RevenueWithdrawalState, f5 as RevenueWithdrawalStateFailed, f6 as RevenueWithdrawalStatePending, f7 as RevenueWithdrawalStateSucceeded, aG as RevokeChatInviteLinkInput, aH as SavePreparedInlineMessageInput, aI as SendAnimationInput, aJ as SendAudioInput, aK as SendChatActionInput, aL as SendChecklistInput, aM as SendContactInput, aN as SendDiceInput, aO as SendDocumentInput, aP as SendGameInput, aQ as SendGiftInput, aR as SendInvoiceInput, aS as SendLocationInput, aT as SendMediaGroupInput, aU as SendMessageInput, aV as SendPaidMediaInput, aW as SendPhotoInput, aX as SendPollInput, aY as SendStickerInput, aZ as SendVenueInput, a_ as SendVideoInput, a$ as SendVideoNoteInput, b0 as SendVoiceInput, f8 as SentWebAppMessage, b1 as SetBusinessAccountBioInput, b2 as SetBusinessAccountGiftSettingsInput, b3 as SetBusinessAccountNameInput, b4 as SetBusinessAccountProfilePhotoInput, b5 as SetBusinessAccountUsernameInput, b6 as SetChatAdministratorCustomTitleInput, b7 as SetChatDescriptionInput, b8 as SetChatMenuButtonInput, b9 as SetChatPermissionsInput, ba as SetChatPhotoInput, bb as SetChatStickerSetInput, bc as SetChatTitleInput, bd as SetCustomEmojiStickerSetThumbnailInput, be as SetGameScoreInput, bf as SetMessageReactionInput, bg as SetMyCommandsInput, bh as SetMyDefaultAdministratorRightsInput, bi as SetMyDescriptionInput, bj as SetMyNameInput, bk as SetMyShortDescriptionInput, bl as SetPassportDataErrorsInput, bm as SetStickerEmojiListInput, bn as SetStickerKeywordsInput, bo as SetStickerMaskPositionInput, bp as SetStickerPositionInSetInput, bq as SetStickerSetThumbnailInput, br as SetStickerSetTitleInput, bs as SetUserEmojiStatusInput, bt as SetWebhookInput, f9 as SharedUser, fa as ShippingAddress, fb as ShippingOption, fc as ShippingQuery, fd as StarAmount, fe as StarTransaction, ff as StarTransactions, fg as Sticker, fh as StickerSet, bu as StopMessageLiveLocationInput, bv as StopPollInput, fi as Story, fj as StoryArea, fk as StoryAreaPosition, fl as StoryAreaType, fm as StoryAreaTypeLink, fn as StoryAreaTypeLocation, fo as StoryAreaTypeSuggestedReaction, fp as StoryAreaTypeUniqueGift, fq as StoryAreaTypeWeather, fr as SuccessfulPayment, fs as SuggestedPostApprovalFailed, ft as SuggestedPostApproved, fu as SuggestedPostDeclined, fv as SuggestedPostInfo, fw as SuggestedPostPaid, fx as SuggestedPostParameters, fy as SuggestedPostPrice, fz as SuggestedPostRefunded, fA as SwitchInlineQueryChosenChat, fB as TextQuote, b as TgBotApiBaseUrl, fC as TransactionPartner, fD as TransactionPartnerAffiliateProgram, fE as TransactionPartnerChat, fF as TransactionPartnerFragment, fG as TransactionPartnerOther, fH as TransactionPartnerTelegramAds, fI as TransactionPartnerTelegramApi, fJ as TransactionPartnerUser, bw as TransferBusinessAccountStarsInput, bx as TransferGiftInput, by as UnbanChatMemberInput, bz as UnbanChatSenderChatInput, bA as UnhideGeneralForumTopicInput, fK as UniqueGift, fL as UniqueGiftBackdrop, fM as UniqueGiftBackdropColors, fN as UniqueGiftInfo, fO as UniqueGiftModel, fP as UniqueGiftSymbol, bB as UnpinAllChatMessagesInput, bC as UnpinAllForumTopicMessagesInput, bD as UnpinAllGeneralForumTopicMessagesInput, bE as UnpinChatMessageInput, bF as UpgradeGiftInput, bG as UploadStickerFileInput, fQ as User, fR as UserChatBoosts, fS as UserProfilePhotos, fT as UsersShared, fU as Venue, bH as VerifyChatInput, bI as VerifyUserInput, fV as Video, fW as VideoChatEnded, fX as VideoChatParticipantsInvited, fY as VideoChatScheduled, fZ as VideoChatStarted, f_ as VideoNote, f$ as Voice, g0 as WebAppData, g1 as WebAppInfo, g2 as WebhookInfo, g3 as WriteAccessAllowed } from './config-3uU0YevV.js';
4
- import 'effect/Cause';
5
- import 'effect/Types';
6
- import 'effect/Data';
7
- import 'effect/Context';
2
+ import { Api, Update } from '@effect-ak/tg-bot-api';
3
+ import * as effect_Cause from 'effect/Cause';
4
+ import * as effect_Types from 'effect/Types';
5
+ import * as Data from 'effect/Data';
6
+ import * as Context from 'effect/Context';
7
+
8
+ type ErrorReason = Data.TaggedEnum<{
9
+ NotOkResponse: {
10
+ errorCode?: number;
11
+ details?: string;
12
+ };
13
+ UnexpectedResponse: {
14
+ response: unknown;
15
+ };
16
+ ClientInternalError: {
17
+ cause: unknown;
18
+ };
19
+ UnableToGetFile: {
20
+ cause: unknown;
21
+ };
22
+ BotHandlerError: {
23
+ cause: unknown;
24
+ };
25
+ NotJsonResponse: {
26
+ response: unknown;
27
+ };
28
+ }>;
29
+ declare const TgBotClientError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
30
+ readonly _tag: "TgBotClientError";
31
+ } & Readonly<A>;
32
+ declare class TgBotClientError extends TgBotClientError_base<{
33
+ cause: ErrorReason;
34
+ }> {
35
+ }
36
+
37
+ declare const TgBotApiBaseUrl_base: Context.ReferenceClass<TgBotApiBaseUrl, "TgBotApiBaseUrl", string>;
38
+ declare class TgBotApiBaseUrl extends TgBotApiBaseUrl_base {
39
+ }
40
+ declare const TgBotApiToken_base: Context.TagClass<TgBotApiToken, "TgBotApiToken", string>;
41
+ declare class TgBotApiToken extends TgBotApiToken_base {
42
+ }
8
43
 
9
44
  declare const executeTgBotMethod: <M extends keyof Api>(method: M, input: Parameters<Api[M]>[0]) => Micro.Micro<ReturnType<Api[M]>, TgBotClientError, TgBotApiToken>;
45
+ declare const makePayload: (body: object) => FormData | undefined;
10
46
 
11
- type GetFile = {
47
+ declare const ClientFileService_base: Context.TagClass<ClientFileService, "ClientFileService", {
48
+ getFile: (input: GetFile) => ReturnType<typeof getFile>;
49
+ }>;
50
+ declare class ClientFileService extends ClientFileService_base {
51
+ static live: () => Context.Context<ClientFileService>;
52
+ }
53
+ interface GetFile {
12
54
  fileId: string;
13
55
  type?: string;
14
- };
56
+ }
15
57
  declare const getFile: ({ fileId, type }: GetFile) => Micro.Micro<File, TgBotClientError, TgBotApiToken>;
16
- declare const getFileAsBase64String: ({ fileId, type, }: GetFile & {
17
- type: string;
18
- }) => Micro.Micro<{
19
- encoded: string;
20
- file_name: string;
21
- }, TgBotClientError, TgBotApiToken>;
22
- declare const getFileBytes: (fileId: string) => Micro.Micro<{
23
- content: ArrayBuffer;
24
- file_name: string;
25
- }, TgBotClientError, TgBotApiToken>;
26
58
 
27
59
  interface TgBotClient {
28
60
  readonly execute: <M extends keyof Api>(method: M, input: Parameters<Api[M]>[0]) => Promise<ReturnType<Api[M]>>;
29
61
  readonly getFile: (input: GetFile) => Promise<File>;
30
62
  }
31
- type MakeTgClient = {
63
+ interface MakeTgClient {
32
64
  bot_token: string;
33
- };
65
+ }
34
66
  declare function makeTgBotClient(config: MakeTgClient): TgBotClient;
35
67
 
36
- type FileContent = {
37
- file_content: Uint8Array;
68
+ interface FileContent {
69
+ file_content: Uint8Array<ArrayBuffer>;
38
70
  file_name: string;
39
- };
71
+ }
40
72
  declare const isFileContent: (input: unknown) => input is FileContent;
41
- type TgBotApiResponseSchema = {
73
+ interface TgBotApiResponseSchema {
42
74
  ok: boolean;
43
75
  error_code?: number;
44
76
  description?: string;
45
77
  result?: unknown;
46
- };
78
+ }
47
79
  declare const isTgBotApiResponse: (input: unknown) => input is TgBotApiResponseSchema;
48
80
  declare const isTgBotApiUpdate: (input: unknown) => input is Update;
49
81
 
@@ -60,4 +92,4 @@ type MessageEffect = keyof typeof MESSAGE_EFFECTS;
60
92
  declare const messageEffectIdCodes: MessageEffect[];
61
93
  declare const isMessageEffect: (input: unknown) => input is MessageEffect;
62
94
 
63
- export { Api, type FileContent, type GetFile, MESSAGE_EFFECTS, type MessageEffect, TG_BOT_API_URL, type TgBotApiResponseSchema, TgBotApiToken, type TgBotClient, TgBotClientError, Update, executeTgBotMethod, getFile, getFileAsBase64String, getFileBytes, isFileContent, isMessageEffect, isTgBotApiResponse, isTgBotApiUpdate, makeTgBotClient, messageEffectIdCodes };
95
+ export { ClientFileService, type FileContent, type GetFile, MESSAGE_EFFECTS, type MessageEffect, TG_BOT_API_URL, TgBotApiBaseUrl, type TgBotApiResponseSchema, TgBotApiToken, type TgBotClient, TgBotClientError, executeTgBotMethod, isFileContent, isMessageEffect, isTgBotApiResponse, isTgBotApiUpdate, makePayload, makeTgBotClient, messageEffectIdCodes };
package/dist/index.js CHANGED
@@ -1 +1,180 @@
1
- "use strict";var P=Object.create;var y=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var D=(e,o)=>{for(var t in o)y(e,t,{get:o[t],enumerable:!0})},b=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of $(o))!O.call(e,r)&&r!==t&&y(e,r,{get:()=>o[r],enumerable:!(n=v(o,r))||n.enumerable});return e};var l=(e,o,t)=>(t=e!=null?P(j(e)):{},b(o||!e||!e.__esModule?y(t,"default",{value:e,enumerable:!0}):t,e)),I=e=>b(y({},"__esModule",{value:!0}),e);var q={};D(q,{MESSAGE_EFFECTS:()=>_,TG_BOT_API_URL:()=>F,TgBotApiBaseUrl:()=>d,TgBotApiToken:()=>f,TgBotClientError:()=>p,executeTgBotMethod:()=>g,getFile:()=>B,getFileAsBase64String:()=>H,getFileBytes:()=>C,isFileContent:()=>T,isMessageEffect:()=>L,isTgBotApiResponse:()=>k,isTgBotApiUpdate:()=>N,makeTgBotClient:()=>V,messageEffectIdCodes:()=>J});module.exports=I(q);var R=l(require("effect/String")),c=l(require("effect/Micro"));var E=l(require("effect/Data")),p=class extends E.TaggedError("TgBotClientError"){};var T=e=>typeof e=="object"&&e!=null&&"file_content"in e&&e.file_content instanceof Uint8Array&&"file_name"in e&&typeof e.file_name=="string",k=e=>typeof e=="object"&&e!=null&&"ok"in e&&typeof e.ok=="boolean",N=e=>typeof e=="object"&&e!=null&&"update_id"in e&&typeof e.update_id=="number";var x=l(require("effect/Context"));var F="https://api.telegram.org",_={"\u{1F525}":"5104841245755180586","\u{1F44D}":"5107584321108051014","\u{1F44E}":"5104858069142078462","\u2764\uFE0F":"5159385139981059251","\u{1F389}":"5046509860389126442","\u{1F4A9}":"5046589136895476101"},J=Object.keys(_),L=e=>typeof e=="string"&&e in _;var d=class extends x.Reference()("TgBotApiBaseUrl",{defaultValue:()=>F}){},f=class extends x.Tag("TgBotApiToken")(){};var h=e=>{let o=Object.entries(e);if(o.length==0)return;let t=new FormData;for(let[n,r]of o)r&&(typeof r!="object"?t.append(n,`${r}`):T(r)?t.append(n,new Blob([r.file_content]),r.file_name):t.append(n,JSON.stringify(r)));return t};var g=(e,o)=>c.gen(function*(){let t=yield*c.service(f),n=yield*c.service(d),r=yield*c.tryPromise({try:()=>fetch(`${n}/bot${t}/${R.snakeToCamel(e)}`,{body:h(o)??null,method:"POST"}),catch:m=>new p({cause:{_tag:"ClientInternalError",cause:m}})}),a=yield*c.tryPromise({try:()=>r.json(),catch:()=>new p({cause:{_tag:"NotJsonResponse",response:r}})});return k(a)?r.ok?a.result:yield*c.fail(new p({cause:{_tag:"NotOkResponse",...a.error_code?{errorCode:a.error_code}:void 0,...a.description?{details:a.description}:void 0}})):yield*c.fail(new p({cause:{_tag:"UnexpectedResponse",response:a}}))});var s=l(require("effect/Micro"));var B=({fileId:e,type:o})=>C(e).pipe(s.andThen(({content:t,file_name:n})=>new File([t],n,{...o?{type:o}:void 0}))),H=({fileId:e,type:o})=>C(e).pipe(s.andThen(({content:t,file_name:n})=>{let r=Buffer.from(t).toString("base64");return{encoded:`data:${o};base64,${r}`,file_name:n}})),C=e=>s.gen(function*(){let t=(yield*g("get_file",{file_id:e})).file_path;if(!t||t.length==0)return yield*s.fail(new p({cause:{_tag:"UnableToGetFile",cause:"File path not defined"}}));let n=t.replaceAll("/","-"),r=yield*s.service(d),a=yield*s.service(f),m=`${r}/file/bot${a}/${t}`;return{content:yield*s.tryPromise({try:()=>fetch(m).then(M=>M.arrayBuffer()),catch:M=>new p({cause:{_tag:"UnableToGetFile",cause:M}})}),file_name:n}});var i=l(require("effect/Micro")),G=l(require("effect/Context"));var S=l(require("effect/Micro")),w=l(require("effect/Context"));var u=class extends w.Tag("ClientFileService")(){},U=S.gen(function*(){return{getFile:B}});function V(e){return i.gen(function*(){let t=yield*i.service(u),n=G.make(f,e.bot_token);return{execute:(m,A)=>g(m,A).pipe(i.provideContext(n),i.runPromise),getFile:m=>t.getFile(m).pipe(i.provideContext(n),i.runPromise)}}).pipe(i.provideServiceEffect(u,U),i.runSync)}0&&(module.exports={MESSAGE_EFFECTS,TG_BOT_API_URL,TgBotApiBaseUrl,TgBotApiToken,TgBotClientError,executeTgBotMethod,getFile,getFileAsBase64String,getFileBytes,isFileContent,isMessageEffect,isTgBotApiResponse,isTgBotApiUpdate,makeTgBotClient,messageEffectIdCodes});
1
+ // src/execute.ts
2
+ import * as String from "effect/String";
3
+ import * as Micro from "effect/Micro";
4
+
5
+ // src/errors.ts
6
+ import * as Data from "effect/Data";
7
+ var TgBotClientError = class extends Data.TaggedError("TgBotClientError") {
8
+ };
9
+
10
+ // src/guards.ts
11
+ var isFileContent = (input) => typeof input == "object" && input != null && "file_content" in input && input.file_content instanceof Uint8Array && "file_name" in input && typeof input.file_name == "string";
12
+ var isTgBotApiResponse = (input) => typeof input == "object" && input != null && "ok" in input && typeof input.ok == "boolean";
13
+ var isTgBotApiUpdate = (input) => typeof input == "object" && input != null && "update_id" in input && typeof input.update_id == "number";
14
+
15
+ // src/config.ts
16
+ import * as Context from "effect/Context";
17
+
18
+ // src/const.ts
19
+ var TG_BOT_API_URL = "https://api.telegram.org";
20
+ var MESSAGE_EFFECTS = {
21
+ "\u{1F525}": "5104841245755180586",
22
+ "\u{1F44D}": "5107584321108051014",
23
+ "\u{1F44E}": "5104858069142078462",
24
+ "\u2764\uFE0F": "5159385139981059251",
25
+ "\u{1F389}": "5046509860389126442",
26
+ "\u{1F4A9}": "5046589136895476101"
27
+ };
28
+ var messageEffectIdCodes = Object.keys(
29
+ MESSAGE_EFFECTS
30
+ );
31
+ var isMessageEffect = (input) => {
32
+ return typeof input === "string" && input in MESSAGE_EFFECTS;
33
+ };
34
+
35
+ // src/config.ts
36
+ var TgBotApiBaseUrl = class extends Context.Reference()(
37
+ "TgBotApiBaseUrl",
38
+ { defaultValue: () => TG_BOT_API_URL }
39
+ ) {
40
+ };
41
+ var TgBotApiToken = class extends Context.Tag("TgBotApiToken")() {
42
+ };
43
+
44
+ // src/execute.ts
45
+ var executeTgBotMethod = (method, input) => Micro.gen(function* () {
46
+ const botToken = yield* Micro.service(TgBotApiToken);
47
+ const baseUrl = yield* Micro.service(TgBotApiBaseUrl);
48
+ const httpResponse = yield* Micro.tryPromise({
49
+ try: () => fetch(`${baseUrl}/bot${botToken}/${String.snakeToCamel(method)}`, {
50
+ body: makePayload(input) ?? null,
51
+ method: "POST"
52
+ }),
53
+ catch: (cause) => new TgBotClientError({
54
+ cause: { _tag: "ClientInternalError", cause }
55
+ })
56
+ });
57
+ const response = yield* Micro.tryPromise({
58
+ try: () => httpResponse.json(),
59
+ catch: () => new TgBotClientError({
60
+ cause: { _tag: "NotJsonResponse", response: httpResponse }
61
+ })
62
+ });
63
+ if (!isTgBotApiResponse(response)) {
64
+ return yield* Micro.fail(
65
+ new TgBotClientError({
66
+ cause: { _tag: "UnexpectedResponse", response }
67
+ })
68
+ );
69
+ }
70
+ if (!httpResponse.ok) {
71
+ return yield* Micro.fail(
72
+ new TgBotClientError({
73
+ cause: {
74
+ _tag: "NotOkResponse",
75
+ ...response.error_code ? { errorCode: response.error_code } : void 0,
76
+ ...response.description ? { details: response.description } : void 0
77
+ }
78
+ })
79
+ );
80
+ }
81
+ return response.result;
82
+ });
83
+ var makePayload = (body) => {
84
+ const entries = Object.entries(body);
85
+ if (entries.length == 0) return void 0;
86
+ const result = new FormData();
87
+ for (const [key, value] of entries) {
88
+ if (!value) continue;
89
+ if (typeof value != "object") {
90
+ result.append(key, `${value}`);
91
+ } else if (isFileContent(value)) {
92
+ result.append(key, new Blob([value.file_content]), value.file_name);
93
+ } else {
94
+ result.append(key, JSON.stringify(value));
95
+ }
96
+ }
97
+ return result;
98
+ };
99
+
100
+ // src/client-file.ts
101
+ import * as Micro2 from "effect/Micro";
102
+ import * as Context2 from "effect/Context";
103
+ var ClientFileService = class _ClientFileService extends Context2.Tag("ClientFileService")() {
104
+ static live = () => {
105
+ return _ClientFileService.context({
106
+ getFile
107
+ });
108
+ };
109
+ };
110
+ var getFile = ({ fileId, type }) => getFileBytes(fileId).pipe(
111
+ Micro2.andThen(
112
+ ({ content, file_name }) => new File([content], file_name, {
113
+ ...type ? { type } : void 0
114
+ })
115
+ )
116
+ );
117
+ var getFileBytes = (fileId) => Micro2.gen(function* () {
118
+ const response = yield* executeTgBotMethod("get_file", { file_id: fileId });
119
+ const file_path = response.file_path;
120
+ if (!file_path || file_path.length == 0) {
121
+ return yield* Micro2.fail(
122
+ new TgBotClientError({
123
+ cause: {
124
+ _tag: "UnableToGetFile",
125
+ cause: "File path not defined"
126
+ }
127
+ })
128
+ );
129
+ }
130
+ const file_name = file_path.replaceAll("/", "-");
131
+ const baseUrl = yield* Micro2.service(TgBotApiBaseUrl);
132
+ const botToken = yield* Micro2.service(TgBotApiToken);
133
+ const url = `${baseUrl}/file/bot${botToken}/${file_path}`;
134
+ const content = yield* Micro2.tryPromise({
135
+ try: () => fetch(url).then((_) => _.arrayBuffer()),
136
+ catch: (cause) => new TgBotClientError({
137
+ cause: { _tag: "UnableToGetFile", cause }
138
+ })
139
+ });
140
+ return {
141
+ content,
142
+ file_name
143
+ };
144
+ });
145
+
146
+ // src/client.ts
147
+ import * as Micro3 from "effect/Micro";
148
+ import * as Context3 from "effect/Context";
149
+ function makeTgBotClient(config) {
150
+ return createEffect(config).pipe(Micro3.runSync);
151
+ }
152
+ var createEffect = ({ bot_token }) => Micro3.gen(function* () {
153
+ const file = yield* Micro3.service(ClientFileService);
154
+ const context = Context3.make(TgBotApiToken, bot_token);
155
+ const execute = (method, input) => executeTgBotMethod(method, input).pipe(
156
+ Micro3.provideContext(context),
157
+ Micro3.runPromise
158
+ );
159
+ const getFile2 = (input) => file.getFile(input).pipe(Micro3.provideContext(context), Micro3.runPromise);
160
+ return {
161
+ execute,
162
+ getFile: getFile2
163
+ };
164
+ }).pipe(Micro3.provideContext(ClientFileService.live()));
165
+ export {
166
+ ClientFileService,
167
+ MESSAGE_EFFECTS,
168
+ TG_BOT_API_URL,
169
+ TgBotApiBaseUrl,
170
+ TgBotApiToken,
171
+ TgBotClientError,
172
+ executeTgBotMethod,
173
+ isFileContent,
174
+ isMessageEffect,
175
+ isTgBotApiResponse,
176
+ isTgBotApiUpdate,
177
+ makePayload,
178
+ makeTgBotClient,
179
+ messageEffectIdCodes
180
+ };