@effect-ak/tg-bot-client 0.4.2 → 0.5.1

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.mjs CHANGED
@@ -1,530 +1,22 @@
1
- // src/bot/factory/_service.ts
2
- import * as Micro6 from "effect/Micro";
3
- import * as Context4 from "effect/Context";
4
-
5
- // src/bot/message-handler/_service.ts
6
- import * as Context from "effect/Context";
7
- var BotMessageHandler = class extends Context.Tag("BotMessageHandler")() {
8
- };
9
-
10
- // src/bot/update-poller/_service.ts
11
- import * as Micro4 from "effect/Micro";
12
- import * as Context3 from "effect/Context";
13
-
14
- // src/bot/update-poller/poll-updates.ts
15
- import * as Micro3 from "effect/Micro";
16
-
17
- // src/bot/update-poller/settings.ts
18
- var makeSettingsFrom = (input) => {
19
- let limit = input.batch_size ?? 10;
20
- let timeout = input.timeout ?? 10;
21
- let max_empty_responses = input.max_empty_responses;
22
- let log_level = input.log_level;
23
- let on_error = input.on_error;
24
- if (limit < 10 || limit > 100) {
25
- console.warn("Wrong limit, must be in [10..100], using 10 instead");
26
- limit = 10;
27
- }
28
- if (timeout < 2 || timeout > 10) {
29
- console.warn("Wrong timeout, must be in [2..10], using 2 instead");
30
- limit = 10;
31
- }
32
- if (max_empty_responses && max_empty_responses < 2) {
33
- console.warn("Wrong max_empty_responses, must be in [2..infinity], using infinity");
34
- max_empty_responses = void 0;
35
- }
36
- if (max_empty_responses && max_empty_responses < 2) {
37
- console.warn("Wrong max_empty_responses, must be in [2..infinity], using infinity");
38
- max_empty_responses = void 0;
39
- }
40
- if (!log_level) {
41
- log_level = "info";
42
- }
43
- if (!on_error) {
44
- on_error = "stop";
45
- }
46
- const config = {
47
- limit,
48
- timeout,
49
- max_empty_responses,
50
- log_level,
51
- on_error
52
- };
53
- console.log("bot configuration", config);
54
- return config;
55
- };
56
-
57
- // src/bot/update-poller/fetch-and-handle.ts
58
- import * as Micro2 from "effect/Micro";
59
- import * as Data from "effect/Data";
60
-
61
- // src/bot/message-handler/types.ts
62
- import { TaggedClass } from "effect/Data";
63
- var BotResponse = class _BotResponse extends TaggedClass("BotResponse") {
64
- static make(result) {
65
- return new _BotResponse({ response: result });
66
- }
67
- static ignore = new _BotResponse({});
68
- };
69
-
70
- // src/bot/message-handler/utils.ts
71
- var extractUpdate = (input) => {
72
- for (const [field, value] of Object.entries(input)) {
73
- if (field == "update_id") {
74
- continue;
75
- }
76
- return {
77
- type: field,
78
- ...value
79
- };
80
- }
81
- return;
82
- };
83
-
84
- // src/client/execute-request/execute.ts
85
- import * as Micro from "effect/Micro";
86
- import * as String from "effect/String";
87
-
88
- // src/client/errors.ts
89
- import { TaggedError } from "effect/Data";
90
- var TgBotClientError = class _TgBotClientError extends TaggedError("TgBotClientError") {
91
- static missingSuccess = new _TgBotClientError({
92
- reason: {
93
- type: "ClientInternalError",
94
- cause: "Expected 'success' to be defined"
95
- }
96
- });
97
- };
98
-
99
- // src/client/config.ts
100
- import * as Context2 from "effect/Context";
101
-
102
- // src/const.ts
103
- var defaultBaseUrl = "https://api.telegram.org";
104
- var MESSAGE_EFFECTS = {
105
- "\u{1F525}": "5104841245755180586",
106
- "\u{1F44D}": "5107584321108051014",
107
- "\u{1F44E}": "5104858069142078462",
108
- "\u2764\uFE0F": "5159385139981059251",
109
- "\u{1F389}": "5046509860389126442",
110
- "\u{1F4A9}": "5046589136895476101"
111
- };
112
- var messageEffectIdCodes = Object.keys(MESSAGE_EFFECTS);
113
- var isMessageEffect = (input) => {
114
- return typeof input === "string" && input in MESSAGE_EFFECTS;
115
- };
116
-
117
- // src/client/config.ts
118
- var makeTgBotClientConfig = (input) => TgBotClientConfig.of({
119
- ...input,
120
- base_url: input.base_url ?? defaultBaseUrl
121
- });
122
- var TgBotClientConfig = class extends Context2.Tag("TgBotClientConfig")() {
123
- };
124
-
125
- // src/client/guards.ts
126
- 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");
127
- var isTgBotApiResponse = (input) => typeof input == "object" && input != null && ("ok" in input && typeof input.ok == "boolean");
128
- var isTgBotClientSettingsInput = (input) => typeof input == "object" && input != null && ("bot_token" in input && typeof input.bot_token == "string");
129
-
130
- // src/client/execute-request/payload.ts
131
- var makePayload = (body) => {
132
- const entries = Object.entries(body);
133
- if (entries.length == 0) return void 0;
134
- const result = new FormData();
135
- for (const [key, value] of entries) {
136
- if (!value) continue;
137
- if (typeof value != "object") {
138
- result.append(key, `${value}`);
139
- } else if (isFileContent(value)) {
140
- result.append(key, new Blob([value.file_content]), value.file_name);
141
- } else {
142
- result.append(key, JSON.stringify(value));
143
- }
144
- }
145
- return result;
146
- };
147
-
148
- // src/client/execute-request/execute.ts
149
- var execute = (method, input) => Micro.gen(function* () {
150
- const config = yield* Micro.service(TgBotClientConfig);
151
- const httpResponse = yield* Micro.tryPromise({
152
- try: () => fetch(
153
- `${config.base_url}/bot${config.bot_token}/${String.snakeToCamel(method)}`,
154
- {
155
- body: makePayload(input) ?? null,
156
- method: "POST"
157
- }
158
- ),
159
- catch: (cause) => new TgBotClientError({
160
- reason: { type: "ClientInternalError", cause }
161
- })
162
- });
163
- const response = yield* Micro.tryPromise({
164
- try: () => httpResponse.json(),
165
- catch: () => new TgBotClientError({
166
- reason: { type: "UnexpectedResponse", response: httpResponse }
167
- })
168
- });
169
- if (!isTgBotApiResponse(response)) {
170
- return yield* Micro.fail(new TgBotClientError({
171
- reason: { type: "UnexpectedResponse", response }
172
- }));
173
- }
174
- if (!httpResponse.ok) {
175
- return yield* Micro.fail(new TgBotClientError({
176
- reason: {
177
- type: "NotOkResponse",
178
- ...response.error_code ? { errorCode: response.error_code } : void 0,
179
- ...response.description ? { details: response.description } : void 0
180
- }
181
- }));
182
- }
183
- return response.result;
184
- });
185
-
186
- // src/bot/update-poller/fetch-and-handle.ts
187
- var HandleUpdateError = class extends Data.TaggedError("HandleUpdateError") {
188
- };
189
- var fetchAndHandle = ({ state, settings, handlers }) => Micro2.gen(function* () {
190
- const updateId = state.lastUpdateId;
191
- if (settings.log_level == "debug") {
192
- console.debug("getting updates", state);
193
- }
194
- const updates = yield* execute("get_updates", {
195
- ...settings,
196
- ...updateId ? { offset: updateId } : void 0
197
- }).pipe(
198
- Micro2.andThen((_) => _.sort((_2) => _2.update_id))
199
- );
200
- if (updates.length) {
201
- console.debug(`got a batch of updates (${updates.length})`);
202
- }
203
- const lastUpdateId = updates.map((_) => _.update_id).sort().at(-1);
204
- if (!lastUpdateId) return { updates: [], lastUpdateId: void 0 };
205
- const hasError = yield* Micro2.forEach(
206
- updates,
207
- (update) => handleUpdate(update, settings, handlers).pipe(
208
- Micro2.catchAll((error) => {
209
- console.log("error", {
210
- updateId: update.update_id,
211
- updateKey: Object.keys(update).at(1),
212
- name: error._tag
213
- });
214
- return Micro2.succeed(void 0);
215
- })
216
- ),
217
- {
218
- concurrency: 10
219
- }
220
- ).pipe(
221
- Micro2.andThen((batchResult) => {
222
- if (settings.log_level == "debug") {
223
- console.debug("handle batch result", batchResult);
224
- }
225
- return !batchResult.every((error) => error == null);
226
- })
227
- );
228
- if (lastUpdateId) {
229
- yield* execute("get_updates", {
230
- offset: lastUpdateId,
231
- limit: 0
232
- });
233
- if (settings.log_level == "debug") {
234
- console.debug("committed offset", lastUpdateId);
235
- }
236
- }
237
- return { updates, lastUpdateId, hasError };
238
- });
239
- var handleUpdate = (updateObject, settings, handlers) => Micro2.gen(function* () {
240
- const update = extractUpdate(updateObject);
241
- if (!update) {
242
- return yield* Micro2.fail(
243
- new HandleUpdateError({
244
- name: "UnknownUpdate",
245
- update: updateObject
246
- })
247
- );
248
- }
249
- const handler = handlers[`on_${update.type}`];
250
- if (!handler) {
251
- return yield* Micro2.fail(
252
- new HandleUpdateError({
253
- name: "HandlerNotDefined",
254
- update: updateObject
255
- })
256
- );
257
- }
258
- if (update.type == "message" && "text" in update) {
259
- console.info("Got a new text message", {
260
- chatId: update.chat.id,
261
- chatType: update.chat.type,
262
- message: `${update.text.slice(0, 5)}...`
263
- });
264
- }
265
- let handleUpdateError;
266
- const handleResult = yield* Micro2.try({
267
- try: () => handler(update),
268
- catch: (error) => new HandleUpdateError({
269
- name: "BotHandlerError",
270
- update: updateObject,
271
- cause: error
272
- })
273
- }).pipe(
274
- Micro2.andThen((handleResult2) => {
275
- if (handleResult2 instanceof Promise) {
276
- return Micro2.tryPromise({
277
- try: () => handleResult2,
278
- catch: (error) => new HandleUpdateError({
279
- name: "BotHandlerError",
280
- update: updateObject,
281
- cause: error
282
- })
283
- });
284
- }
285
- return Micro2.succeed(handleResult2);
286
- }),
287
- Micro2.catchAll((error) => {
288
- handleUpdateError = error;
289
- console.log("error", {
290
- updateId: updateObject.update_id,
291
- updateKey: Object.keys(update).at(1),
292
- name: error._tag
293
- });
294
- return Micro2.succeed(
295
- BotResponse.make({
296
- type: "message",
297
- text: `Some internal error has happend(${error.name}) while handling this message`,
298
- message_effect_id: MESSAGE_EFFECTS["\u{1F4A9}"],
299
- ...updateObject.message?.message_id ? {
300
- reply_parameters: {
301
- message_id: updateObject.message?.message_id
302
- }
303
- } : void 0
304
- })
305
- );
306
- })
307
- );
308
- if (!handleResult && settings.log_level == "debug") {
309
- console.log(`Bot response is undefined for update with ID #${updateObject.update_id}.`);
310
- return;
311
- }
312
- ;
313
- if ("chat" in update && handleResult.response) {
314
- const response = yield* execute(`send_${handleResult.response.type}`, {
315
- ...handleResult.response,
316
- chat_id: update.chat.id
317
- });
318
- if (settings.log_level == "debug" && "text") {
319
- console.debug("bot response", response);
320
- }
321
- }
322
- return handleUpdateError;
323
- });
324
-
325
- // src/bot/update-poller/poll-updates.ts
326
- var pollUpdates = (input) => {
327
- const state = {
328
- lastUpdateId: void 0,
329
- emptyResponses: 0
330
- };
331
- const settings = makeSettingsFrom(input.settings);
332
- return Micro3.delay(1e3)(
333
- fetchAndHandle({
334
- state,
335
- settings,
336
- handlers: input.settings
337
- })
338
- ).pipe(
339
- Micro3.repeat({
340
- while: ({ updates, lastUpdateId, hasError }) => {
341
- if (hasError === true && settings.on_error == "stop") {
342
- console.info("Could not handle some messages, quitting");
343
- return false;
344
- }
345
- if (updates.length == 0) {
346
- state.emptyResponses += 1;
347
- if (settings.max_empty_responses && state.emptyResponses > settings.max_empty_responses) {
348
- console.info("too many empty responses, quitting");
349
- return false;
350
- }
351
- } else {
352
- state.emptyResponses = 0;
353
- }
354
- ;
355
- if (lastUpdateId) {
356
- state.lastUpdateId = lastUpdateId + 1;
357
- }
358
- return true;
359
- }
360
- })
361
- );
362
- };
363
-
364
- // src/bot/update-poller/_service.ts
365
- var BotUpdatePollerService = class extends Context3.Tag("BotUpdatePollerService")() {
366
- };
367
- var BotUpdatesPollerServiceDefault = Micro4.gen(function* () {
368
- console.log("Initiating BotUpdatesPollerServiceDefault");
369
- const state = {
370
- fiber: void 0
371
- };
372
- const runBot = Micro4.gen(function* () {
373
- console.log("run bot");
374
- const messageHandler = yield* Micro4.service(BotMessageHandler);
375
- const startFiber = pollUpdates({
376
- settings: messageHandler
377
- }).pipe(
378
- Micro4.forkDaemon,
379
- Micro4.tap(
380
- (fiber) => fiber.addObserver((exit) => {
381
- console.log("bot's fiber has been closed", exit);
382
- })
383
- )
384
- );
385
- if (state.fiber) {
386
- console.log("killing previous bot's fiber");
387
- yield* Micro4.fiberInterrupt(state.fiber);
388
- }
389
- state.fiber = yield* startFiber;
390
- console.log("Fetching bot updates via long polling...");
391
- });
392
- return {
393
- runBot,
394
- getFiber: () => state.fiber
395
- };
396
- });
397
-
398
- // src/bot/factory/client-config.ts
399
- import * as Micro5 from "effect/Micro";
400
- var makeClientConfigFrom = (input) => Micro5.gen(function* () {
401
- if (input.type == "config") {
402
- return makeTgBotClientConfig(input);
403
- }
404
- const config = yield* Micro5.tryPromise({
405
- try: async () => {
406
- const { readFileSync } = await import("fs");
407
- return JSON.parse(await readFileSync("config.json", "utf-8"));
408
- },
409
- catch: (error) => {
410
- console.warn("invalid tg bot config", error);
411
- return "ReadingConfigError";
412
- }
413
- });
414
- if (!isTgBotClientSettingsInput(config)) {
415
- return yield* Micro5.fail("InvalidConfig");
416
- }
417
- return makeTgBotClientConfig(config);
418
- });
419
-
420
- // src/bot/factory/_service.ts
421
- var BotFactoryService = class extends Context4.Tag("BotFactoryService")() {
422
- };
423
- var BotFactoryServiceDefault = {
424
- runBot: (input) => Micro6.gen(function* () {
425
- const client = Context4.make(TgBotClientConfig, yield* makeClientConfigFrom(input));
426
- const poller = yield* BotUpdatesPollerServiceDefault.pipe(
427
- Micro6.provideContext(client)
428
- );
429
- yield* poller.runBot.pipe(
430
- Micro6.provideService(BotMessageHandler, input),
431
- Micro6.provideContext(client)
432
- );
433
- const reload = (input2) => poller.runBot.pipe(
434
- Micro6.provideService(BotMessageHandler, input2),
435
- Micro6.provideContext(client),
436
- Micro6.runPromise
437
- );
438
- return {
439
- reload,
440
- fiber: poller.getFiber
441
- };
442
- })
443
- };
444
-
445
- // src/bot/run.ts
446
- import * as Micro7 from "effect/Micro";
447
- var runTgChatBot = (input) => BotFactoryServiceDefault.runBot(input).pipe(
448
- Micro7.provideService(BotMessageHandler, input),
449
- Micro7.runPromise
450
- );
451
-
452
- // src/client/_client.ts
453
- import * as Micro10 from "effect/Micro";
454
-
455
- // src/client/file/_service.ts
456
- import * as Micro9 from "effect/Micro";
457
- import * as Context5 from "effect/Context";
458
-
459
- // src/client/file/get-file.ts
460
- import * as Micro8 from "effect/Micro";
461
- var getFile = (fileId) => Micro8.gen(function* () {
462
- const response = yield* execute("get_file", { file_id: fileId });
463
- const config = yield* Micro8.service(TgBotClientConfig);
464
- const file_path = response.file_path;
465
- if (!file_path || file_path.length == 0) {
466
- return yield* Micro8.fail(
467
- new TgBotClientError({
468
- reason: {
469
- type: "UnableToGetFile",
470
- cause: "File path not defined"
471
- }
472
- })
473
- );
474
- }
475
- const file_name = file_path.replaceAll("/", "-");
476
- const url = `${config.base_url}/file/bot${config.bot_token}/${file_path}`;
477
- const fileContent = yield* Micro8.tryPromise({
478
- try: () => fetch(url).then((_) => _.arrayBuffer()),
479
- catch: (cause) => new TgBotClientError({
480
- reason: { type: "UnableToGetFile", cause }
481
- })
482
- });
483
- const file = new File([new Uint8Array(fileContent)], file_name);
484
- return file;
485
- });
486
-
487
- // src/client/file/_service.ts
488
- var ClientFileService = class extends Context5.Tag("ClientFileService")() {
489
- };
490
- var ClientFileServiceDefault = Micro9.gen(function* () {
491
- return {
492
- getFile: (input) => getFile(input.file_id)
493
- };
494
- });
495
-
496
- // src/client/_client.ts
497
- var makeTgBotClient = (input) => {
498
- const config = makeTgBotClientConfig(input);
499
- const client = Micro10.gen(function* () {
500
- const file = yield* Micro10.service(ClientFileService);
501
- return {
502
- execute: (method, input2) => execute(method, input2).pipe(
503
- Micro10.provideService(TgBotClientConfig, config),
504
- Micro10.runPromise
505
- ),
506
- getFile: (input2) => file.getFile(input2).pipe(
507
- Micro10.provideService(TgBotClientConfig, config),
508
- Micro10.runPromise
509
- )
510
- };
511
- }).pipe(
512
- Micro10.provideServiceEffect(ClientFileService, ClientFileServiceDefault),
513
- Micro10.provideService(TgBotClientConfig, config),
514
- Micro10.runSync
515
- );
516
- return client;
517
- };
518
- export {
519
- BotFactoryService,
520
- BotFactoryServiceDefault,
521
- BotResponse,
522
- BotUpdatePollerService,
523
- BotUpdatesPollerServiceDefault,
524
- MESSAGE_EFFECTS,
525
- defaultBaseUrl,
526
- isMessageEffect,
527
- makeTgBotClient,
528
- messageEffectIdCodes,
529
- runTgChatBot
530
- };
1
+ var Ze=t=>typeof t=="function",u=function(t,e){if(typeof t=="function")return function(){return t(arguments)?e.apply(this,arguments):r=>e(r,...arguments)};switch(t){case 0:case 1:throw new RangeError(`Invalid arity ${t}`);case 2:return function(r,o){return arguments.length>=2?e(r,o):function(n){return e(n,r)}};case 3:return function(r,o,n){return arguments.length>=3?e(r,o,n):function(s){return e(s,r,o)}};case 4:return function(r,o,n,s){return arguments.length>=4?e(r,o,n,s):function(i){return e(i,r,o,n)}};case 5:return function(r,o,n,s,i){return arguments.length>=5?e(r,o,n,s,i):function(c){return e(c,r,o,n,s)}};default:return function(){if(arguments.length>=t)return e.apply(this,arguments);let r=arguments;return function(o){return e(o,...r)}}}};var R=t=>t;var Qe=t=>()=>t,fe=Qe(!0),Xe=Qe(!1);var tr=Qe(void 0),oo=tr;function b(t,e,r,o,n,s,i,c,a){switch(arguments.length){case 1:return t;case 2:return e(t);case 3:return r(e(t));case 4:return o(r(e(t)));case 5:return n(o(r(e(t))));case 6:return s(n(o(r(e(t)))));case 7:return i(s(n(o(r(e(t))))));case 8:return c(i(s(n(o(r(e(t)))))));case 9:return a(c(i(s(n(o(r(e(t))))))));default:{let p=arguments[0];for(let h=1;h<arguments.length;h++)p=arguments[h](p);return p}}}var no=t=>(e,r)=>e===r||t(e,r);var Ls="3.12.0",de=()=>Ls;var rr=Symbol.for(`effect/GlobalValue/globalStoreId/${de()}`);rr in globalThis||(globalThis[rr]=new Map);var er=globalThis[rr],B=(t,e)=>(er.has(t)||er.set(t,e()),er.get(t));var zt=Ze;var Hs=t=>typeof t=="object"&&t!==null,or=t=>Hs(t)||zt(t),_=u(2,(t,e)=>or(t)&&e in t),nr=u(2,(t,e)=>_(t,"_tag")&&t._tag===e);var Jt=t=>`BUG: ${t} - please report an issue at https://github.com/Effect-TS/effect/issues`;var io=Symbol.for("effect/Gen/GenKind");var co=class{value;constructor(e){this.value=e}get _F(){return R}get _R(){return e=>e}get _O(){return e=>e}get _E(){return e=>e}[io]=io;[Symbol.iterator](){return new xt(this)}},xt=class t{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new t(this.self)}};var sr=Symbol.for("effect/Utils/YieldWrap"),z=class{#t;constructor(e){this.#t=e}[sr](){return this.#t}};function ao(t){if(typeof t=="object"&&t!==null&&sr in t)return t[sr]();throw new Error(Jt("yieldWrapGet"))}var N=B("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0}));var Vc=function*(){}.constructor;var ir=B(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),f=Symbol.for("effect/Hash"),l=t=>{if(N.enabled===!0)return 0;switch(typeof t){case"number":return me(t);case"bigint":return q(t.toString(10));case"boolean":return q(String(t));case"symbol":return q(String(t));case"string":return q(t);case"undefined":return q("undefined");case"function":case"object":return t===null?q("null"):t instanceof Date?l(t.toISOString()):Bs(t)?t[f]():It(t);default:throw new Error(`BUG: unhandled typeof ${typeof t} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},It=t=>(ir.has(t)||ir.set(t,me(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER))),ir.get(t)),M=t=>e=>e*53^t,he=t=>t&3221225471|t>>>1&1073741824,Bs=t=>_(t,f),me=t=>{if(t!==t||t===1/0)return 0;let e=t|0;for(e!==t&&(e^=t*4294967295);t>4294967295;)e^=t/=4294967295;return he(e)},q=t=>{let e=5381,r=t.length;for(;r;)e=e*33^t.charCodeAt(--r);return he(e)},qs=(t,e)=>{let r=12289;for(let o=0;o<e.length;o++)r^=b(q(e[o]),M(l(t[e[o]])));return he(r)},po=t=>qs(t,Object.keys(t)),xe=t=>{let e=6151;for(let r=0;r<t.length;r++)e=b(e,M(l(t[r])));return he(e)},S=function(){if(arguments.length===1){let r=arguments[0];return function(o){return Object.defineProperty(r,f,{value(){return o},enumerable:!1}),o}}let t=arguments[0],e=arguments[1];return Object.defineProperty(t,f,{value(){return e},enumerable:!1}),e};var m=Symbol.for("effect/Equal");function x(){return arguments.length===1?t=>ge(t,arguments[0]):ge(arguments[0],arguments[1])}function ge(t,e){if(t===e)return!0;let r=typeof t;if(r!==typeof e)return!1;if(r==="object"||r==="function"){if(t!==null&&e!==null){if(uo(t)&&uo(e))return l(t)===l(e)&&t[m](e)?!0:N.enabled&&N.tester?N.tester(t,e):!1;if(t instanceof Date&&e instanceof Date)return t.toISOString()===e.toISOString()}if(N.enabled){if(Array.isArray(t)&&Array.isArray(e))return t.length===e.length&&t.every((o,n)=>ge(o,e[n]));if(Object.getPrototypeOf(t)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let o=Object.keys(t),n=Object.keys(e);if(o.length===n.length){for(let s of o)if(!(s in e&&ge(t[s],e[s])))return N.tester?N.tester(t,e):!1;return!0}}return N.tester?N.tester(t,e):!1}}return N.enabled&&N.tester?N.tester(t,e):!1}var uo=t=>_(t,m);var y=Symbol.for("nodejs.util.inspect.custom"),O=t=>{try{if(_(t,"toJSON")&&zt(t.toJSON)&&t.toJSON.length===0)return t.toJSON();if(Array.isArray(t))return t.map(O)}catch{return{}}return Ds(t)},E=t=>JSON.stringify(t,null,2),na={toJSON(){return O(this)},[y](){return this.toJSON()},toString(){return E(this.toJSON())}},lo=class{[y](){return this.toJSON()}toString(){return E(this.toJSON())}},fo=(t,e=2)=>{if(typeof t=="string")return t;try{return typeof t=="object"?cr(t,e):String(t)}catch{return String(t)}},cr=(t,e)=>{let r=[],o=JSON.stringify(t,(n,s)=>typeof s=="object"&&s!==null?r.includes(s)?void 0:r.push(s)&&(_e.fiberRefs!==void 0&&ho(s)?s[ar](_e.fiberRefs):s):s,e);return r=void 0,o},ar=Symbol.for("effect/Inspectable/Redactable"),ho=t=>typeof t=="object"&&t!==null&&ar in t,_e=B("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}));var Ds=t=>ho(t)&&_e.fiberRefs!==void 0?t[ar](_e.fiberRefs):t;var C=(t,e)=>{switch(e.length){case 0:return t;case 1:return e[0](t);case 2:return e[1](e[0](t));case 3:return e[2](e[1](e[0](t)));case 4:return e[3](e[2](e[1](e[0](t))));case 5:return e[4](e[3](e[2](e[1](e[0](t)))));case 6:return e[5](e[4](e[3](e[2](e[1](e[0](t))))));case 7:return e[6](e[5](e[4](e[3](e[2](e[1](e[0](t)))))));case 8:return e[7](e[6](e[5](e[4](e[3](e[2](e[1](e[0](t))))))));case 9:return e[8](e[7](e[6](e[5](e[4](e[3](e[2](e[1](e[0](t)))))))));default:{let r=t;for(let o=0,n=e.length;o<n;o++)r=e[o](r);return r}}};var pr="Commit",mo="Failure";var xo="WithRuntime";var _o=Symbol.for("effect/Effect"),yo=Symbol.for("effect/Stream"),Oo=Symbol.for("effect/Sink"),So=Symbol.for("effect/Channel"),ct={_R:t=>t,_E:t=>t,_A:t=>t,_V:de()},js={_A:t=>t,_In:t=>t,_L:t=>t,_E:t=>t,_R:t=>t},Ws={_Env:t=>t,_InErr:t=>t,_InElem:t=>t,_InDone:t=>t,_OutErr:t=>t,_OutElem:t=>t,_OutDone:t=>t},Z={[_o]:ct,[yo]:ct,[Oo]:js,[So]:Ws,[m](t){return this===t},[f](){return S(this,It(this))},[Symbol.iterator](){return new xt(new z(this))},pipe(){return C(this,arguments)}},ur={[f](){return S(this,po(this))},[m](t){let e=Object.keys(this),r=Object.keys(t);if(e.length!==r.length)return!1;for(let o of e)if(!(o in t&&x(this[o],t[o])))return!1;return!0}},lr={...Z,_op:pr},fr={...lr,...ur};var bo=Symbol.for("effect/Option"),Eo={...Z,[bo]:{_A:t=>t},[y](){return this.toJSON()},toString(){return E(this.toJSON())}},zs=Object.assign(Object.create(Eo),{_tag:"Some",_op:"Some",[m](t){return dr(t)&&mr(t)&&x(this.value,t.value)},[f](){return S(this,M(l(this._tag))(l(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:O(this.value)}}}),Js=l("None"),$s=Object.assign(Object.create(Eo),{_tag:"None",_op:"None",[m](t){return dr(t)&&hr(t)},[f](){return Js},toJSON(){return{_id:"Option",_tag:this._tag}}}),dr=t=>_(t,bo),hr=t=>t._tag==="None",mr=t=>t._tag==="Some",Co=Object.create($s),ko=t=>{let e=Object.create(zs);return e.value=t,e};var xr=Symbol.for("effect/Either"),Io={...Z,[xr]:{_R:t=>t},[y](){return this.toJSON()},toString(){return E(this.toJSON())}},Ys=Object.assign(Object.create(Io),{_tag:"Right",_op:"Right",[m](t){return gr(t)&&Ao(t)&&x(this.right,t.right)},[f](){return M(l(this._tag))(l(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:O(this.right)}}}),Ks=Object.assign(Object.create(Io),{_tag:"Left",_op:"Left",[m](t){return gr(t)&&vo(t)&&x(this.left,t.left)},[f](){return M(l(this._tag))(l(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:O(this.left)}}}),gr=t=>_(t,xr),vo=t=>t._tag==="Left",Ao=t=>t._tag==="Right",Mo=t=>{let e=Object.create(Ks);return e.left=t,e},wo=t=>{let e=Object.create(Ys);return e.right=t,e};var $t=wo,_r=Mo;var F=()=>Co,Q=ko;var U=hr,at=mr;var To=u(2,(t,e)=>U(t)?e():t.value);var Ro=To(tr);var Yt=t=>Array.isArray(t)?t:Array.from(t);var Sa=Array.isArray;var yr=t=>Array.from(t).reverse();var Or=u(3,(t,e,r)=>Yt(t).reduce((o,n,s)=>r(o,n,s),e));var Fo=Symbol.for("effect/Context/Tag"),ye=Symbol.for("effect/Context/Reference"),Xs="effect/STM",ti=Symbol.for(Xs),Po={...Z,_op:"Tag",[ti]:ct,[Fo]:{_Service:t=>t,_Identifier:t=>t},toString(){return E(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[y](){return this.toJSON()},of(t){return t},context(t){return Cr(this,t)}},ei={...Po,[ye]:ye};var No=t=>()=>{let e=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=new Error;Error.stackTraceLimit=e;function o(){}return Object.setPrototypeOf(o,Po),o.key=t,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},Uo=()=>(t,e)=>{let r=Error.stackTraceLimit;Error.stackTraceLimit=2;let o=new Error;Error.stackTraceLimit=r;function n(){}return Object.setPrototypeOf(n,ei),n.key=t,n.defaultValue=e.defaultValue,Object.defineProperty(n,"stack",{get(){return o.stack}}),n},Er=Symbol.for("effect/Context"),ri={[Er]:{_Services:t=>t},[m](t){if(Lo(t)&&this.unsafeMap.size===t.unsafeMap.size){for(let e of this.unsafeMap.keys())if(!t.unsafeMap.has(e)||!x(this.unsafeMap.get(e),t.unsafeMap.get(e)))return!1;return!0}return!1},[f](){return S(this,me(this.unsafeMap.size))},pipe(){return C(this,arguments)},toString(){return E(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(O)}},[y](){return this.toJSON()}},Oe=t=>{let e=Object.create(ri);return e.unsafeMap=t,e},oi=t=>{let e=new Error(`Service not found${t.key?`: ${String(t.key)}`:""}`);if(t.stack){let r=t.stack.split(`
2
+ `);if(r.length>2){let o=r[2].match(/at (.*)/);o&&(e.message=e.message+` (defined at ${o[1]})`)}}if(e.stack){let r=e.stack.split(`
3
+ `);r.splice(1,3),e.stack=r.join(`
4
+ `)}return e},Lo=t=>_(t,Er);var Cr=(t,e)=>Oe(new Map([[t.key,e]])),Ho=u(3,(t,e,r)=>{let o=new Map(t.unsafeMap);return o.set(e.key,r),Oe(o)}),br=B("effect/Context/defaultValueCache",()=>new Map),Bo=t=>{if(br.has(t.key))return br.get(t.key);let e=t.defaultValue();return br.set(t.key,e),e},qo=(t,e)=>t.unsafeMap.has(e.key)?t.unsafeMap.get(e.key):Bo(e),Do=u(2,(t,e)=>{if(!t.unsafeMap.has(e.key)){if(ye in e)return Bo(e);throw oi(e)}return t.unsafeMap.get(e.key)});var jo=u(2,(t,e)=>{let r=new Map(t.unsafeMap);for(let[o,n]of e.unsafeMap)r.set(o,n);return Oe(r)});var Go=Cr,zo=Ho;var Jo=Do;var $o=jo;var vt=No,J=Uo;var Vo=Z;var Xo=Symbol.for("effect/Micro"),Se=Symbol.for("effect/Micro/MicroExit"),Kt=t=>typeof t=="object"&&t!==null&&Xo in t,Yo=Symbol.for("effect/Micro/MicroCause");var si={_E:R},Zt=class extends globalThis.Error{_tag;traces;[Yo];constructor(e,r,o){let n=`MicroCause.${e}`,s,i,c;if(r instanceof globalThis.Error){s=`(${n}) ${r.name}`,i=r.message;let a=i.split(`
5
+ `).length;c=r.stack?`(${n}) ${r.stack.split(`
6
+ `).slice(0,a+3).join(`
7
+ `)}`:`${s}: ${i}`}else s=n,i=fo(r,0),c=`${s}: ${i}`;o.length>0&&(c+=`
8
+ ${o.join(`
9
+ `)}`),super(i),this._tag=e,this.traces=o,this[Yo]=si,this.name=s,this.stack=c}pipe(){return C(this,arguments)}toString(){return this.stack}[y](){return this.stack}},Ir=class extends Zt{error;constructor(e,r=[]){super("Fail",e,r),this.error=e}},ii=(t,e=[])=>new Ir(t,e),vr=class extends Zt{defect;constructor(e,r=[]){super("Die",e,r),this.defect=e}},ci=(t,e=[])=>new vr(t,e),Ar=class extends Zt{constructor(e=[]){super("Interrupt","interrupted",e)}},ai=(t=[])=>new Ar(t),pi=t=>t._tag==="Fail";var tn=t=>t._tag==="Interrupt";var Ko=Symbol.for("effect/Micro/MicroFiber"),ui={_A:R,_E:R},be=class{context;interruptible;[Ko];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,r=!0){this.context=e,this.interruptible=r,this[Ko]=ui}getRef(e){return qo(this.context,e)}addObserver(e){return this._exit?(e(this._exit),oo):(this._observers.push(e),()=>{let r=this._observers.indexOf(e);r>=0&&this._observers.splice(r,1)})}_interrupted=!1;unsafeInterrupt(){this._exit||(this._interrupted=!0,this.interruptible&&this.evaluate(Pr))}unsafePoll(){return this._exit}evaluate(e){if(this._exit)return;if(this._yielded!==void 0){let n=this._yielded;this._yielded=void 0,n()}let r=this.runLoop(e);if(r===At)return;let o=Zo.interruptChildren&&Zo.interruptChildren(this);if(o!==void 0)return this.evaluate(L(o,()=>r));this._exit=r;for(let n=0;n<this._observers.length;n++)this._observers[n](r);this._observers.length=0}runLoop(e){let r=!1,o=e;this.currentOpCount=0;try{for(;;){if(this.currentOpCount++,!r&&this.getRef(Tt).shouldYield(this)){r=!0;let n=o;o=L(nn,()=>n)}if(o=o[Mr](this),o===At){let n=this._yielded;return Se in n?(this._yielded=void 0,n):At}}}catch(n){return _(o,Mr)?Qt(n):Qt(`MicroFiber.runLoop: Not a valid effect: ${String(o)}`)}}getCont(e){for(;;){let r=this._stack.pop();if(!r)return;let o=r[Ee]&&r[Ee](this);if(o)return{[e]:o};if(r[e])return r}}_yielded=void 0;yieldWith(e){return this._yielded=e,At}children(){return this._children??=new Set}},Zo=B("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0}));var li=t=>Ce(e=>wt(t.addObserver(r=>e(k(r)))));var en=t=>tt(()=>(t.unsafeInterrupt(),yi(li(t)))),fi=t=>tt(()=>{for(let o of t)o.unsafeInterrupt();let e=t[Symbol.iterator](),r=tt(()=>{let o=e.next();for(;!o.done;){if(o.value.unsafePoll()){o=e.next();continue}let n=o.value;return Ce(s=>{n.addObserver(i=>{s(r)})})}return yt});return r}),rn=Symbol.for("effect/Micro/identifier"),d=Symbol.for("effect/Micro/args"),Mr=Symbol.for("effect/Micro/evaluate"),X=Symbol.for("effect/Micro/successCont"),gt=Symbol.for("effect/Micro/failureCont"),Ee=Symbol.for("effect/Micro/ensureCont"),At=Symbol.for("effect/Micro/Yield"),di={_A:R,_E:R,_R:R},hi={...Vo,_op:"Micro",[Xo]:di,pipe(){return C(this,arguments)},[Symbol.iterator](){return new xt(new z(this))},toJSON(){return{_id:"Micro",op:this[rn],...d in this?{args:this[d]}:void 0}},toString(){return E(this)},[y](){return E(this)}};function mi(t){return Qt("Micro.evaluate: Not implemented")}var te=t=>({...hi,[rn]:t.op,[Mr]:t.eval??mi,[X]:t.contA,[gt]:t.contE,[Ee]:t.ensure}),et=t=>{let e=te(t);return function(){let r=Object.create(e);return r[d]=t.single===!1?arguments:arguments[0],r}},on=t=>{let e={...te(t),[Se]:Se,_tag:t.op,get[t.prop](){return this[d]},toJSON(){return{_id:"MicroExit",_tag:t.op,[t.prop]:this[d]}},[m](r){return bi(r)&&r._tag===t.op&&x(this[d],r[d])},[f](){return S(this,M(q(t.op))(l(this[d])))}};return function(r){let o=Object.create(e);return o[d]=r,o[X]=void 0,o[gt]=void 0,o[Ee]=void 0,o}},k=on({op:"Success",prop:"value",eval(t){let e=t.getCont(X);return e?e[X](this[d],t):t.yieldWith(this)}}),Mt=on({op:"Failure",prop:"cause",eval(t){let e=t.getCont(gt);for(;tn(this[d])&&e&&t.interruptible;)e=t.getCont(gt);return e?e[gt](this[d],t):t.yieldWith(this)}}),P=t=>Mt(ii(t)),wt=et({op:"Sync",eval(t){let e=this[d](),r=t.getCont(X);return r?r[X](e,t):t.yieldWith(ke(e))}}),tt=et({op:"Suspend",eval(t){return this[d]()}}),xi=et({op:"Yield",eval(t){let e=!1;return t.getRef(Tt).scheduleTask(()=>{e||t.evaluate(yt)},this[d]??0),t.yieldWith(()=>{e=!0})}}),nn=xi(0);var _t=k(void 0);var Fr=t=>tt(()=>{try{return k(t.try())}catch(e){return P(t.catch(e))}});var $=t=>sn(function(e,r){try{t.try(r).then(o=>e(k(o)),o=>e(P(t.catch(o))))}catch(o){e(P(t.catch(o)))}},t.try.length!==0),Rt=et({op:"WithMicroFiber",eval(t){return this[d](t)}});var sn=et({op:"Async",single:!1,eval(t){let e=this[d][0],r=!1,o=!1,n=this[d][1]?new AbortController:void 0,s=e(i=>{r||(r=!0,o?t.evaluate(i):o=i)},n?.signal);return o!==!1?o:(o=!0,t._yielded=()=>{r=!0},n===void 0&&s===void 0||t._stack.push(gi(()=>(r=!0,n?.abort(),s??yt))),At)}}),gi=et({op:"AsyncFinalizer",ensure(t){t.interruptible&&(t.interruptible=!1,t._stack.push(Ur(!0)))},contE(t,e){return tn(t)?L(this[d](),()=>Mt(t)):Mt(t)}}),Ce=t=>sn(t,t.length>=2);var I=(...t)=>tt(()=>_i(t.length===1?t[0]():t[1].call(t[0]))),_i=et({op:"Iterator",contA(t,e){let r=this[d].next(t);return r.done?k(r.value):(e._stack.push(this),ao(r.value))},eval(t){return this[X](void 0,t)}}),cn=u(2,(t,e)=>Si(t,r=>e));var j=u(2,(t,e)=>L(t,r=>{let o=Kt(e)?e:typeof e=="function"?e(r):e;return Kt(o)?o:k(o)})),ee=u(2,(t,e)=>L(t,r=>{let o=Kt(e)?e:typeof e=="function"?e(r):e;return Kt(o)?cn(o,r):k(r)})),yi=t=>L(t,e=>yt),an=t=>wi(t,{onFailure:Ie,onSuccess:ke});var L=u(2,(t,e)=>{let r=Object.create(Oi);return r[d]=t,r[X]=e,r}),Oi=te({op:"OnSuccess",eval(t){return t._stack.push(this),this[d]}});var Si=u(2,(t,e)=>L(t,r=>k(e(r)))),bi=t=>_(t,Se),ke=k,Ie=Mt,Pr=Ie(ai());var Qt=t=>Ie(ci(t));var yt=ke(void 0),Ei=t=>{for(let e of t)if(e._tag==="Failure")return e;return yt},Ci="setImmediate"in globalThis?globalThis.setImmediate:t=>setTimeout(t,0),Xt=class{tasks=[];running=!1;scheduleTask(e,r){this.tasks.push(e),this.running||(this.running=!0,Ci(this.afterScheduled))}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let e=this.tasks;this.tasks=[];for(let r=0,o=e.length;r<o;r++)e[r]()}shouldYield(e){return e.currentOpCount>=e.getRef(wr)}flush(){for(;this.tasks.length>0;)this.runTasks()}},w=t=>Rt(e=>k(Jo(e.context,t)));var pn=u(2,(t,e)=>Rt(r=>{let o=r.context;return r.context=e(o),Ti(t,()=>(r.context=o,_t))}));var Nr=u(2,(t,e)=>pn(t,$o(e))),rt=u(3,(t,e,r)=>pn(t,zo(e,r))),un=u(3,(t,e,r)=>L(r,o=>rt(t,e,o))),wr=class extends J()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){},Tr=class extends J()("effect/Micro/currentConcurrency",{defaultValue:()=>"unbounded"}){},Tt=class extends J()("effect/Micro/currentScheduler",{defaultValue:()=>new Xt}){};var ki=u(2,(t,e)=>tt(()=>{let r=e.schedule?Date.now():0,o=0,n=L(an(t),s=>{if(e.while!==void 0&&!e.while(s))return s;if(e.times!==void 0&&o>=e.times)return s;o++;let i=nn;if(e.schedule!==void 0){let c=Date.now()-r,a=e.schedule(o,c);if(U(a))return s;i=dn(a.value)}return L(i,()=>n)});return n})),ln=u(t=>Kt(t[0]),(t,e)=>ki(t,{...e,while:r=>r._tag==="Success"&&(e?.while===void 0||e.while(r.value))}));var Ii=u(2,(t,e)=>{let r=Object.create(vi);return r[d]=t,r[gt]=e,r}),vi=te({op:"OnFailure",eval(t){return t._stack.push(this),this[d]}}),Ai=u(3,(t,e,r)=>Ii(t,o=>e(o)?r(o):Mt(o))),ve=u(2,(t,e)=>Ai(t,pi,r=>e(r.error)));var fn=u(2,(t,e)=>{let r=Object.create(Mi);return r[d]=t,r[X]=e.onSuccess,r[gt]=e.onFailure,r}),Mi=te({op:"OnSuccessAndFailure",eval(t){return t._stack.push(this),this[d]}}),wi=u(2,(t,e)=>fn(t,{onFailure:r=>wt(()=>e.onFailure(r)),onSuccess:r=>wt(()=>e.onSuccess(r))}));var dn=t=>Ce(e=>{let r=setTimeout(()=>{e(_t)},t);return wt(()=>{clearTimeout(r)})}),hn=u(2,(t,e)=>j(dn(e),t));var kr=Symbol.for("effect/Micro/MicroScope");var Qo=class t{[kr];state={_tag:"Open",finalizers:new Set};constructor(){this[kr]=kr}unsafeAddFinalizer(e){this.state._tag==="Open"&&this.state.finalizers.add(e)}addFinalizer(e){return tt(()=>this.state._tag==="Open"?(this.state.finalizers.add(e),_t):e(this.state.exit))}unsafeRemoveFinalizer(e){this.state._tag==="Open"&&this.state.finalizers.delete(e)}close(e){return tt(()=>{if(this.state._tag==="Open"){let r=Array.from(this.state.finalizers).reverse();return this.state={_tag:"Closed",exit:e},L(Lr(r,o=>an(o(e))),Ei)}return _t})}get fork(){return wt(()=>{let e=new t;if(this.state._tag==="Closed")return e.state=this.state,e;function r(o){return e.close(o)}return this.state.finalizers.add(r),e.unsafeAddFinalizer(o=>wt(()=>this.unsafeRemoveFinalizer(r))),e})}};var Ti=u(2,(t,e)=>Fi(r=>fn(r(t),{onFailure:o=>L(e(Ie(o)),()=>Mt(o)),onSuccess:o=>L(e(ke(o)),()=>k(o))})));var Ur=et({op:"SetInterruptible",ensure(t){if(t.interruptible=this[d],t._interrupted&&t.interruptible)return()=>Pr}}),Ri=t=>Rt(e=>e.interruptible?t:(e.interruptible=!0,e._stack.push(Ur(!1)),e._interrupted?Pr:t)),Fi=t=>Rt(e=>e.interruptible?(e.interruptible=!1,e._stack.push(Ur(!0)),t(Ri)):t(R));var Pi=et({op:"While",contA(t,e){return this[d].step(t),this[d].while()?(e._stack.push(this),this[d].body()):yt},eval(t){return this[d].while()?(t._stack.push(this),this[d].body()):yt}}),Lr=(t,e,r)=>Rt(o=>{let n=r?.concurrency==="inherit"?o.getRef(Tr):r?.concurrency??1,s=n==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,n),i=Yt(t),c=i.length;if(c===0)return r?.discard?_t:k([]);let a=r?.discard?void 0:new Array(c),p=0;return s===1?cn(Pi({while:()=>p<i.length,body:()=>e(i[p],p),step:a?h=>a[p++]=h:h=>p++}),a):Ce(h=>{let g=new Set,A,v=0,jt=0,ft=!1,dt=!1;function ht(){for(ft=!0;v<s&&p<c;){let mt=p,Fs=i[mt];p++,v++;try{let Wt=mn(o,e(Fs,mt),!0,!0);g.add(Wt),Wt.addObserver(Gt=>{g.delete(Wt),!dt&&(Gt._tag==="Failure"?A===void 0&&(A=Gt,c=p,g.forEach(Ps=>Ps.unsafeInterrupt())):a!==void 0&&(a[mt]=Gt.value),jt++,v--,jt===c?h(A??k(a)):!ft&&v<s&&ht())})}catch(Wt){A=Qt(Wt),c=p,g.forEach(Gt=>Gt.unsafeInterrupt())}}ft=!1}return ht(),tt(()=>(dt=!0,p=c,fi(g)))})});var mn=(t,e,r=!1,o=!1)=>{let n=new be(t.context,t.interruptible);return o||(t.children().add(n),n.addObserver(()=>t.children().delete(n))),r?n.evaluate(e):t.getRef(Tt).scheduleTask(()=>n.evaluate(e),0),n},xn=t=>Rt(e=>k(mn(e,t,!1,!0)));var gn=(t,e)=>{let r=new be(Tt.context(e?.scheduler??new Xt));if(r.evaluate(t),e?.signal)if(e.signal.aborted)r.unsafeInterrupt();else{let o=()=>r.unsafeInterrupt();e.signal.addEventListener("abort",o,{once:!0}),r.addObserver(()=>e.signal.removeEventListener("abort",o))}return r},Ni=(t,e)=>new Promise((r,o)=>{gn(t,e).addObserver(r)}),Ot=(t,e)=>Ni(t,e).then(r=>{if(r._tag==="Failure")throw r.cause;return r.value}),Ui=t=>{let e=new Xt,r=gn(t,{scheduler:e});return e.flush(),r._exit??Qt(r)},_n=t=>{let e=Ui(t);if(e._tag==="Failure")throw e.cause;return e.value};var yn="https://api.telegram.org",Ae={"\u{1F525}":"5104841245755180586","\u{1F44D}":"5107584321108051014","\u{1F44E}":"5104858069142078462","\u2764\uFE0F":"5159385139981059251","\u{1F389}":"5046509860389126442","\u{1F4A9}":"5046589136895476101"},Ka=Object.keys(Ae),Za=t=>typeof t=="string"&&t in Ae;var re=t=>H.of({...t,base_url:t.base_url??yn}),H=class extends vt("TgBotClientConfig")(){};var On=Symbol.for("effect/Chunk");function Li(t,e,r,o,n){for(let s=e;s<Math.min(t.length,e+n);s++)r[o+s-e]=t[s];return r}var Sn=[],Hi=t=>no((e,r)=>e.length===r.length&&Ft(e).every((o,n)=>t(o,Pt(r,n)))),Bi=Hi(x),qi={[On]:{_A:t=>t},toString(){return E(this.toJSON())},toJSON(){return{_id:"Chunk",values:Ft(this).map(O)}},[y](){return this.toJSON()},[m](t){return bn(t)&&Bi(this,t)},[f](){return S(this,xe(Ft(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return Sn[Symbol.iterator]();default:return Ft(this)[Symbol.iterator]()}},pipe(){return C(this,arguments)}},T=t=>{let e=Object.create(qi);switch(e.backing=t,t._tag){case"IEmpty":{e.length=0,e.depth=0,e.left=e,e.right=e;break}case"IConcat":{e.length=t.left.length+t.right.length,e.depth=1+Math.max(t.left.depth,t.right.depth),e.left=t.left,e.right=t.right;break}case"IArray":{e.length=t.array.length,e.depth=0,e.left=ot,e.right=ot;break}case"ISingleton":{e.length=1,e.depth=0,e.left=ot,e.right=ot;break}case"ISlice":{e.length=t.length,e.depth=t.chunk.depth+1,e.left=ot,e.right=ot;break}}return e},bn=t=>_(t,On),ot=T({_tag:"IEmpty"}),St=()=>ot,ne=(...t)=>t.length===1?bt(t[0]):Wi(t),bt=t=>T({_tag:"ISingleton",a:t}),En=t=>bn(t)?t:T({_tag:"IArray",array:Yt(t)}),Hr=(t,e,r)=>{switch(t.backing._tag){case"IArray":{Li(t.backing.array,0,e,r,t.length);break}case"IConcat":{Hr(t.left,e,r),Hr(t.right,e,r+t.left.length);break}case"ISingleton":{e[r]=t.backing.a;break}case"ISlice":{let o=0,n=r;for(;o<t.length;)e[n]=Pt(t,o),o+=1,n+=1;break}}};var Di=t=>{switch(t.backing._tag){case"IEmpty":return Sn;case"IArray":return t.backing.array;default:{let e=new Array(t.length);return Hr(t,e,0),t.backing={_tag:"IArray",array:e},t.left=ot,t.right=ot,t.depth=0,e}}},Ft=Di,ji=t=>{switch(t.backing._tag){case"IEmpty":case"ISingleton":return t;case"IArray":return T({_tag:"IArray",array:yr(t.backing.array)});case"IConcat":return T({_tag:"IConcat",left:oe(t.backing.right),right:oe(t.backing.left)});case"ISlice":return Cn(yr(Ft(t)))}},oe=ji;var Cn=t=>T({_tag:"IArray",array:t}),Wi=t=>Cn(t),Pt=u(2,(t,e)=>{switch(t.backing._tag){case"IEmpty":throw new Error("Index out of bounds");case"ISingleton":{if(e!==0)throw new Error("Index out of bounds");return t.backing.a}case"IArray":{if(e>=t.length||e<0)throw new Error("Index out of bounds");return t.backing.array[e]}case"IConcat":return e<t.left.length?Pt(t.left,e):Pt(t.right,e-t.left.length);case"ISlice":return Pt(t.backing.chunk,e+t.backing.offset)}});var Me=u(2,(t,e)=>nt(bt(e),t));var nt=u(2,(t,e)=>{if(t.backing._tag==="IEmpty")return e;if(e.backing._tag==="IEmpty")return t;let r=e.depth-t.depth;if(Math.abs(r)<=1)return T({_tag:"IConcat",left:t,right:e});if(r<-1)if(t.left.depth>=t.right.depth){let o=nt(t.right,e);return T({_tag:"IConcat",left:t.left,right:o})}else{let o=nt(t.right.right,e);if(o.depth===t.depth-3){let n=T({_tag:"IConcat",left:t.right.left,right:o});return T({_tag:"IConcat",left:t.left,right:n})}else{let n=T({_tag:"IConcat",left:t.left,right:t.right.left});return T({_tag:"IConcat",left:n,right:o})}}else if(e.right.depth>=e.left.depth){let o=nt(t,e.left);return T({_tag:"IConcat",left:o,right:e.right})}else{let o=nt(t,e.left.left);if(o.depth===e.depth-3){let n=T({_tag:"IConcat",left:o,right:e.left.right});return T({_tag:"IConcat",left:n,right:e.right})}else{let n=T({_tag:"IConcat",left:e.left.right,right:e.right});return T({_tag:"IConcat",left:o,right:n})}}});var kn=t=>t.length===0,we=t=>t.length>0;var In=t=>Pt(t,0),Te=In;var Br=Math.pow(2,5),An=Br-1,Mn=Br/2,wn=Br/4;function Gi(t){return t-=t>>1&1431655765,t=(t&858993459)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,t&127}function ut(t,e){return e>>>t&An}function lt(t){return 1<<t}function Re(t,e){return Gi(t&e-1)}var Tn=(t,e)=>({value:t,previous:e});function Et(t,e,r,o){let n=o;if(!t){let s=o.length;n=new Array(s);for(let i=0;i<s;++i)n[i]=o[i]}return n[e]=r,n}function qr(t,e,r){let o=r.length-1,n=0,s=0,i=r;if(t)n=s=e;else for(i=new Array(o);n<e;)i[s++]=r[n++];for(++n;n<=o;)i[s++]=r[n++];return t&&(i.length=o),i}function Rn(t,e,r,o){let n=o.length;if(t){let a=n;for(;a>=e;)o[a--]=o[a];return o[e]=r,o}let s=0,i=0,c=new Array(n+1);for(;s<e;)c[i++]=o[s++];for(c[e]=r;s<n;)c[++i]=o[s++];return c}var st=class t{_tag="EmptyNode";modify(e,r,o,n,s,i){let c=o(F());return U(c)?new t:(++i.value,new Nt(e,n,s,c))}};function G(t){return nr(t,"EmptyNode")}function Ji(t){return G(t)||t._tag==="LeafNode"||t._tag==="CollisionNode"}function Fe(t,e){return G(t)?!1:e===t.edit}var Nt=class t{edit;hash;key;value;_tag="LeafNode";constructor(e,r,o,n){this.edit=e,this.hash=r,this.key=o,this.value=n}modify(e,r,o,n,s,i){if(x(s,this.key)){let a=o(this.value);return a===this.value?this:U(a)?(--i.value,new st):Fe(this,e)?(this.value=a,this):new t(e,n,s,a)}let c=o(F());return U(c)?this:(++i.value,Fn(e,r,this.hash,this,n,new t(e,n,s,c)))}},Dr=class t{edit;hash;children;_tag="CollisionNode";constructor(e,r,o){this.edit=e,this.hash=r,this.children=o}modify(e,r,o,n,s,i){if(n===this.hash){let a=Fe(this,e),p=this.updateCollisionList(a,e,this.hash,this.children,o,s,i);return p===this.children?this:p.length>1?new t(e,this.hash,p):p[0]}let c=o(F());return U(c)?this:(++i.value,Fn(e,r,this.hash,this,n,new Nt(e,n,s,c)))}updateCollisionList(e,r,o,n,s,i,c){let a=n.length;for(let h=0;h<a;++h){let g=n[h];if("key"in g&&x(i,g.key)){let A=g.value,v=s(A);return v===A?n:U(v)?(--c.value,qr(e,h,n)):Et(e,h,new Nt(r,o,i,v),n)}}let p=s(F());return U(p)?n:(++c.value,Et(e,a,new Nt(r,o,i,p),n))}},se=class t{edit;mask;children;_tag="IndexedNode";constructor(e,r,o){this.edit=e,this.mask=r,this.children=o}modify(e,r,o,n,s,i){let c=this.mask,a=this.children,p=ut(r,n),h=lt(p),g=Re(c,h),A=c&h,v=Fe(this,e);if(!A){let mt=new st().modify(e,r+5,o,n,s,i);return mt?a.length>=Mn?Vi(e,p,mt,c,a):new t(e,c|h,Rn(v,g,mt,a)):this}let jt=a[g],ft=jt.modify(e,r+5,o,n,s,i);if(jt===ft)return this;let dt=c,ht;if(G(ft)){if(dt&=~h,!dt)return new st;if(a.length<=2&&Ji(a[g^1]))return a[g^1];ht=qr(v,g,a)}else ht=Et(v,g,ft,a);return v?(this.mask=dt,this.children=ht,this):new t(e,dt,ht)}},jr=class t{edit;size;children;_tag="ArrayNode";constructor(e,r,o){this.edit=e,this.size=r,this.children=o}modify(e,r,o,n,s,i){let c=this.size,a=this.children,p=ut(r,n),h=a[p],g=(h||new st).modify(e,r+5,o,n,s,i);if(h===g)return this;let A=Fe(this,e),v;if(G(h)&&!G(g))++c,v=Et(A,p,g,a);else if(!G(h)&&G(g)){if(--c,c<=wn)return $i(e,c,p,a);v=Et(A,p,new st,a)}else v=Et(A,p,g,a);return A?(this.size=c,this.children=v,this):new t(e,c,v)}};function $i(t,e,r,o){let n=new Array(e-1),s=0,i=0;for(let c=0,a=o.length;c<a;++c)if(c!==r){let p=o[c];p&&!G(p)&&(n[s++]=p,i|=1<<c)}return new se(t,i,n)}function Vi(t,e,r,o,n){let s=[],i=o,c=0;for(let a=0;i;++a)i&1&&(s[a]=n[c++]),i>>>=1;return s[e]=r,new jr(t,c+1,s)}function Yi(t,e,r,o,n,s){if(r===n)return new Dr(t,r,[s,o]);let i=ut(e,r),c=ut(e,n);if(i===c)return a=>new se(t,lt(i)|lt(c),[a]);{let a=i<c?[o,s]:[s,o];return new se(t,lt(i)|lt(c),a)}}function Fn(t,e,r,o,n,s){let i,c=e;for(;;){let a=Yi(t,c,r,o,n,s);if(typeof a=="function")i=Tn(a,i),c=c+5;else{let p=a;for(;i!=null;)p=i.value(p),i=i.previous;return p}}}var Pn="effect/HashMap",Wr=Symbol.for(Pn),Zi={[Wr]:Wr,[Symbol.iterator](){return new Pe(this,(t,e)=>[t,e])},[f](){let t=l(Pn);for(let e of this)t^=b(l(e[0]),M(l(e[1])));return S(this,t)},[m](t){if(Xi(t)){if(t._size!==this._size)return!1;for(let e of this){let r=b(t,tc(e[0],l(e[0])));if(U(r))return!1;if(!x(e[1],r.value))return!1}return!0}return!1},toString(){return E(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(O)}},[y](){return this.toJSON()},pipe(){return C(this,arguments)}},Gr=(t,e,r,o)=>{let n=Object.create(Zi);return n._editable=t,n._edit=e,n._root=r,n._size=o,n},Pe=class t{map;f;v;constructor(e,r){this.map=e,this.f=r,this.v=Nn(this.map._root,this.f,void 0)}next(){if(U(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=Ne(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new t(this.map,this.f)}},Ne=t=>t?Un(t[0],t[1],t[2],t[3],t[4]):F(),Nn=(t,e,r=void 0)=>{switch(t._tag){case"LeafNode":return at(t.value)?Q({value:e(t.key,t.value.value),cont:r}):Ne(r);case"CollisionNode":case"ArrayNode":case"IndexedNode":{let o=t.children;return Un(o.length,o,0,e,r)}default:return Ne(r)}},Un=(t,e,r,o,n)=>{for(;r<t;){let s=e[r++];if(s&&!G(s))return Nn(s,o,[t,e,r,o,n])}return Ne(n)},Qi=Gr(!1,0,new st,0),Ln=()=>Qi;var Xi=t=>_(t,Wr);var tc=u(3,(t,e,r)=>{let o=t._root,n=0;for(;;)switch(o._tag){case"LeafNode":return x(e,o.key)?o.value:F();case"CollisionNode":{if(r===o.hash){let s=o.children;for(let i=0,c=s.length;i<c;++i){let a=s[i];if("key"in a&&x(e,a.key))return a.value}}return F()}case"IndexedNode":{let s=ut(n,r),i=lt(s);if(o.mask&i){o=o.children[Re(o.mask,i)],n+=5;break}return F()}case"ArrayNode":{if(o=o.children[ut(n,r)],o){n+=5;break}return F()}default:return F()}});var zr=u(3,(t,e,r)=>rc(t,e,()=>Q(r))),ec=u(3,(t,e,r)=>t._editable?(t._root=e,t._size=r,t):e===t._root?t:Gr(t._editable,t._edit,e,r)),Hn=t=>new Pe(t,e=>e);var Ue=t=>t._size,Bn=t=>Gr(!0,t._edit+1,t._root,t._size);var rc=u(3,(t,e,r)=>oc(t,e,l(e),r)),oc=u(4,(t,e,r,o)=>{let n={value:t._size},s=t._root.modify(t._editable?t._edit:NaN,0,o,r,e,n);return b(t,ec(s,n.value))});var qn=u(2,(t,e)=>Dn(t,void 0,(r,o,n)=>e(o,n))),Dn=u(3,(t,e,r)=>{let o=t._root;if(o._tag==="LeafNode")return at(o.value)?r(e,o.value.value,o.key):e;if(o._tag==="EmptyNode")return e;let n=[o.children],s;for(;s=n.pop();)for(let i=0,c=s.length;i<c;){let a=s[i++];a&&!G(a)&&(a._tag==="LeafNode"?at(a.value)&&(e=r(e,a.value.value,a.key)):n.push(a.children))}return e});var jn="effect/HashSet",Le=Symbol.for(jn),sc={[Le]:Le,[Symbol.iterator](){return Hn(this._keyMap)},[f](){return S(this,M(l(this._keyMap))(l(jn)))},[m](t){return Wn(t)?Ue(this._keyMap)===Ue(t._keyMap)&&x(this._keyMap,t._keyMap):!1},toString(){return E(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(O)}},[y](){return this.toJSON()},pipe(){return C(this,arguments)}},Jr=t=>{let e=Object.create(sc);return e._keyMap=t,e},Wn=t=>_(t,Le),ic=Jr(Ln()),$r=()=>ic;var Gn=t=>Ue(t._keyMap),zn=t=>Jr(Bn(t._keyMap)),Jn=t=>(t._keyMap._editable=!1,t),$n=u(2,(t,e)=>{let r=zn(t);return e(r),Jn(r)}),He=u(2,(t,e)=>t._keyMap._editable?(zr(e,!0)(t._keyMap),t):Jr(zr(e,!0)(t._keyMap)));var Vn=u(2,(t,e)=>$n($r(),r=>{Yn(t,o=>He(r,o));for(let o of e)He(r,o)}));var Yn=u(2,(t,e)=>qn(t._keyMap,(r,o)=>e(o)));var ie=$r;var Kn=Gn;var Be=He;var qe=Vn;var pc=Object.assign(Object.create(Array.prototype),{[f](){return S(this,xe(this))},[m](t){return Array.isArray(t)&&this.length===t.length?this.every((e,r)=>x(e,t[r])):!1}}),Zn=function(){function t(e){e&&Object.assign(this,e)}return t.prototype=ur,t}();var Vr="Die",De="Empty",je="Fail",Yr="Interrupt",Lt="Parallel",Ht="Sequential";var rs="effect/Cause",os=Symbol.for(rs),fc={_E:t=>t},Zr={[os]:fc,[f](){return b(l(rs),M(l(mc(this))),S(this))},[m](t){return dc(t)&&hc(this,t)},pipe(){return C(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:O(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:O(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:O(this.left),right:O(this.right)}}},toString(){return Qr(this)},[y](){return this.toJSON()}};var Ge=t=>{let e=Object.create(Zr);return e._tag=je,e.error=t,e};var ns=(t,e)=>{let r=Object.create(Zr);return r._tag=Lt,r.left=t,r.right=e,r},ce=(t,e)=>{let r=Object.create(Zr);return r._tag=Ht,r.left=t,r.right=e,r},dc=t=>_(t,os);var ss=t=>is(void 0,gc)(t);var hc=(t,e)=>{let r=bt(t),o=bt(e);for(;we(r)&&we(o);){let[n,s]=b(Te(r),ts([ie(),St()],([a,p],h)=>{let[g,A]=Kr(h);return Q([b(a,qe(g)),b(p,nt(A))])})),[i,c]=b(Te(o),ts([ie(),St()],([a,p],h)=>{let[g,A]=Kr(h);return Q([b(a,qe(g)),b(p,nt(A))])}));if(!x(n,i))return!1;r=s,o=c}return!0},mc=t=>xc(bt(t),St()),xc=(t,e)=>{for(;;){let[r,o]=b(t,Or([ie(),St()],([s,i],c)=>{let[a,p]=Kr(c);return[b(s,qe(a)),b(i,nt(p))]})),n=Kn(r)>0?b(e,Me(r)):e;if(kn(o))return oe(n);t=o,e=n}throw new Error(Jt("Cause.flattenCauseLoop"))};var Kr=t=>{let e=t,r=[],o=ie(),n=St();for(;e!==void 0;)switch(e._tag){case De:{if(r.length===0)return[o,n];e=r.pop();break}case je:{if(o=Be(o,ne(e._tag,e.error)),r.length===0)return[o,n];e=r.pop();break}case Vr:{if(o=Be(o,ne(e._tag,e.defect)),r.length===0)return[o,n];e=r.pop();break}case Yr:{if(o=Be(o,ne(e._tag,e.fiberId)),r.length===0)return[o,n];e=r.pop();break}case Ht:{switch(e.left._tag){case De:{e=e.right;break}case Ht:{e=ce(e.left.left,ce(e.left.right,e.right));break}case Lt:{e=ns(ce(e.left.left,e.right),ce(e.left.right,e.right));break}default:{n=Me(n,e.right),e=e.left;break}}break}case Lt:{r.push(e.right),e=e.left;break}}throw new Error(Jt("Cause.evaluateCauseLoop"))};var gc={emptyCase:fe,failCase:Xe,dieCase:Xe,interruptCase:fe,sequentialCase:(t,e,r)=>e&&r,parallelCase:(t,e,r)=>e&&r};var Qn="SequentialCase",Xn="ParallelCase";var ts=u(3,(t,e,r)=>{let o=e,n=t,s=[];for(;n!==void 0;){let i=r(o,n);switch(o=at(i)?i.value:o,n._tag){case Ht:{s.push(n.right),n=n.left;break}case Lt:{s.push(n.right),n=n.left;break}default:{n=void 0;break}}n===void 0&&s.length>0&&(n=s.pop())}return o}),is=u(3,(t,e,r)=>{let o=[t],n=[];for(;o.length>0;){let i=o.pop();switch(i._tag){case De:{n.push($t(r.emptyCase(e)));break}case je:{n.push($t(r.failCase(e,i.error)));break}case Vr:{n.push($t(r.dieCase(e,i.defect)));break}case Yr:{n.push($t(r.interruptCase(e,i.fiberId)));break}case Ht:{o.push(i.right),o.push(i.left),n.push(_r({_tag:Qn}));break}case Lt:{o.push(i.right),o.push(i.left),n.push(_r({_tag:Xn}));break}}}let s=[];for(;n.length>0;){let i=n.pop();switch(i._tag){case"Left":{switch(i.left._tag){case Qn:{let c=s.pop(),a=s.pop(),p=r.sequentialCase(e,c,a);s.push(p);break}case Xn:{let c=s.pop(),a=s.pop(),p=r.parallelCase(e,c,a);s.push(p);break}}break}case"Right":{s.push(i.right);break}}}if(s.length===0)throw new Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return s.pop()}),Qr=(t,e)=>ss(t)?"All fibers interrupted without errors.":bc(t).map(function(r){return e?.renderErrorCause!==!0||r.cause===void 0?r.stack:`${r.stack} {
10
+ ${cs(r.cause," ")}
11
+ }`}).join(`
12
+ `),cs=(t,e)=>{let r=t.stack.split(`
13
+ `),o=`${e}[cause]: ${r[0]}`;for(let n=1,s=r.length;n<s;n++)o+=`
14
+ ${e}${r[n]}`;return t.cause&&(o+=` {
15
+ ${cs(t.cause,`${e} `)}
16
+ ${e}}`),o},We=class t extends globalThis.Error{span=void 0;constructor(e){let r=typeof e=="object"&&e!==null,o=Error.stackTraceLimit;Error.stackTraceLimit=1,super(_c(e),r&&"cause"in e&&typeof e.cause<"u"?{cause:new t(e.cause)}:void 0),this.message===""&&(this.message="An error has occurred"),Error.stackTraceLimit=o,this.name=e instanceof Error?e.name:"Error",r&&(es in e&&(this.span=e[es]),Object.keys(e).forEach(n=>{n in this||(this[n]=e[n])})),this.stack=Sc(`${this.name}: ${this.message}`,e instanceof Error&&e.stack?e.stack:"",this.span)}},_c=t=>{if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&t instanceof Error)return t.message;try{if(_(t,"toString")&&zt(t.toString)&&t.toString!==Object.prototype.toString&&t.toString!==globalThis.Array.prototype.toString)return t.toString()}catch{}return cr(t)},yc=/\((.*)\)/g,Oc=B("effect/Tracer/spanToTrace",()=>new WeakMap),Sc=(t,e,r)=>{let o=[t],n=e.startsWith(t)?e.slice(t.length).split(`
17
+ `):e.split(`
18
+ `);for(let s=1;s<n.length&&!n[s].includes("Generator.next");s++){if(n[s].includes("effect_internal_function")){o.pop();break}o.push(n[s].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(r){let s=r,i=0;for(;s&&s._tag==="Span"&&i<10;){let c=Oc.get(s);if(typeof c=="function"){let a=c();if(typeof a=="string"){let p=a.matchAll(yc),h=!1;for(let[,g]of p)h=!0,o.push(` at ${s.name} (${g})`);h||o.push(` at ${s.name} (${a.replace(/^at /,"")})`)}else o.push(` at ${s.name}`)}else o.push(` at ${s.name}`);s=Ro(s.parent),i++}}return o.join(`
19
+ `)},es=Symbol.for("effect/SpanAnnotation"),bc=t=>is(t,void 0,{emptyCase:()=>[],dieCase:(e,r)=>[new We(r)],failCase:(e,r)=>[new We(r)],interruptCase:()=>[],parallelCase:(e,r,o)=>[...r,...o],sequentialCase:(e,r,o)=>[...r,...o]});var Bt=class t{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new t(this.self)}};var ze=Symbol.for("effect/Effect");var Xr=class{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ze]=ct;constructor(e){this._op=e}[m](e){return this===e}[f](){return S(this,It(this))}pipe(){return C(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:O(this.effect_instruction_i0),effect_instruction_i1:O(this.effect_instruction_i1),effect_instruction_i2:O(this.effect_instruction_i2)}}toString(){return E(this.toJSON())}[y](){return this.toJSON()}[Symbol.iterator](){return new Bt(new z(this))}},to=class{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ze]=ct;constructor(e){this._op=e,this._tag=e}[m](e){return Os(e)&&e._op==="Failure"&&x(this.effect_instruction_i0,e.effect_instruction_i0)}[f](){return b(q(this._tag),M(l(this.effect_instruction_i0)),S(this))}get cause(){return this.effect_instruction_i0}pipe(){return C(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return E(this.toJSON())}[y](){return this.toJSON()}[Symbol.iterator](){return new Bt(new z(this))}},as=class{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ze]=ct;constructor(e){this._op=e,this._tag=e}[m](e){return Os(e)&&e._op==="Success"&&x(this.effect_instruction_i0,e.effect_instruction_i0)}[f](){return b(q(this._tag),M(l(this.effect_instruction_i0)),S(this))}get value(){return this.effect_instruction_i0}pipe(){return C(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:O(this.value)}}toString(){return E(this.toJSON())}[y](){return this.toJSON()}[Symbol.iterator](){return new Bt(new z(this))}},Cc=t=>_(t,ze),kc=t=>{let e=new Xr(xo);return e.effect_instruction_i0=t,e};var eo=Symbol.for("effect/SpanAnnotation"),ps=Symbol.for("effect/OriginalAnnotation");var Ic=(t,e)=>at(e)?new Proxy(t,{has(r,o){return o===eo||o===ps||o in r},get(r,o){return o===eo?e.value:o===ps?t:r[o]}}):t;var vc=t=>or(t)&&!(eo in t)?kc(e=>us(Ge(Ic(t,Tc(e))))):us(Ge(t));var us=t=>{let e=new to(mo);return e.effect_instruction_i0=t,e};var al={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return C(this,arguments)}};var pl={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return C(this,arguments)}};var Ac="effect/RequestResolver",ys=Symbol.for(Ac),Mc={_A:t=>t,_R:t=>t},ls=class t{runAll;target;[ys]=Mc;constructor(e,r){this.runAll=e,this.target=r}[f](){return S(this,this.target?l(this.target):It(this))}[m](e){return this.target?wc(e)&&x(this.target,e.target):this===e}identified(...e){return new t(this.runAll,En(e))}pipe(){return C(this,arguments)}},wc=t=>_(t,ys);var ro=function(){class t extends globalThis.Error{commit(){return vc(this)}toJSON(){return{...this}}[y](){return this.toString!==globalThis.Error.prototype.toString?this.stack?`${this.toString()}
20
+ ${this.stack.split(`
21
+ `).slice(1).join(`
22
+ `)}`:this.toString():"Bun"in globalThis?Qr(Ge(this),{renderErrorCause:!0}):this}}return Object.assign(t.prototype,fr),t}(),Ct=(t,e)=>{class r extends ro{_tag=e}return Object.assign(r.prototype,t),r.prototype.name=e,r},fs=Symbol.for("effect/Cause/errors/RuntimeException"),ul=Ct({[fs]:fs},"RuntimeException");var ds=Symbol.for("effect/Cause/errors/InterruptedException"),ll=Ct({[ds]:ds},"InterruptedException");var hs=Symbol.for("effect/Cause/errors/IllegalArgument"),fl=Ct({[hs]:hs},"IllegalArgumentException");var ms=Symbol.for("effect/Cause/errors/NoSuchElement"),dl=Ct({[ms]:ms},"NoSuchElementException");var xs=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),hl=Ct({[xs]:xs},"InvalidPubSubCapacityException"),gs=Symbol.for("effect/Cause/errors/ExceededCapacityException"),ml=Ct({[gs]:gs},"ExceededCapacityException");var _s=Symbol.for("effect/Cause/errors/Timeout"),xl=Ct({[_s]:_s},"TimeoutException");var Os=t=>Cc(t)&&"_tag"in t&&(t._tag==="Success"||t._tag==="Failure");var Tc=t=>{let e=t.currentSpan;return e!==void 0&&e._tag==="Span"?Q(e):F()};var ae=Zn,Ss=t=>{class e extends ae{_tag=t}return e};var Fc=function(){let t=Symbol.for("effect/Data/Error/plainArgs");return class extends ro{constructor(r){super(r?.message,r?.cause?{cause:r.cause}:void 0),r&&(Object.assign(this,r),Object.defineProperty(this,t,{value:r,enumerable:!1}))}toJSON(){return{...this[t],...this}}}}(),qt=t=>{class e extends Fc{_tag=t}return e.prototype.name=t,e};var $e=class t extends Ss("BotResponse"){static make(e){return new t({response:e})}static ignore=new t({})},kt=class extends vt("BotUpdateHandlers")(){};var bs=t=>{for(let[e,r]of Object.entries(t))if(e!="update_id")return{type:e,...r}};var Es=t=>{let e=t[0];for(let r=1;r<t.length;r++)e+=t[r]==="_"?t[++r].toUpperCase():t[r];return e};var Y=class t extends qt("TgBotClientError"){static missingSuccess=new t({reason:{type:"ClientInternalError",cause:"Expected 'success' to be defined"}})};var Cs=t=>typeof t=="object"&&t!=null&&"file_content"in t&&t.file_content instanceof Uint8Array&&"file_name"in t&&typeof t.file_name=="string",ks=t=>typeof t=="object"&&t!=null&&"ok"in t&&typeof t.ok=="boolean",Is=t=>typeof t=="object"&&t!=null&&"bot_token"in t&&typeof t.bot_token=="string";var vs=t=>{let e=Object.entries(t);if(e.length==0)return;let r=new FormData;for(let[o,n]of e)n&&(typeof n!="object"?r.append(o,`${n}`):Cs(n)?r.append(o,new Blob([n.file_content]),n.file_name):r.append(o,JSON.stringify(n)));return r};var it=(t,e)=>I(function*(){let r=yield*w(H),o=yield*$({try:()=>fetch(`${r.base_url}/bot${r.bot_token}/${Es(t)}`,{body:vs(e)??null,method:"POST"}),catch:s=>new Y({reason:{type:"ClientInternalError",cause:s}})}),n=yield*$({try:()=>o.json(),catch:()=>new Y({reason:{type:"UnexpectedResponse",response:o}})});return ks(n)?o.ok?n.result:yield*P(new Y({reason:{type:"NotOkResponse",...n.error_code?{errorCode:n.error_code}:void 0,...n.description?{details:n.description}:void 0}})):yield*P(new Y({reason:{type:"UnexpectedResponse",response:n}}))});var pe=class t extends ae{static make(e){let r=e.batch_size??10,o=e.poll_timeout??10,n=e.max_empty_responses,s=e.log_level??"info",i=e.on_error;(r<10||r>100)&&(console.warn("Wrong batch_size, must be in [10..100], using 10 instead"),r=10),(o<2||o>10)&&(console.warn("Wrong poll_timeout, must be in [2..10], using 2 instead"),o=10),n&&n<2&&(console.warn("Wrong max_empty_responses, must be in [2..infinity], using infinity"),n=void 0),s||(s="info"),i||(i="stop");let c=new t({batch_size:r,poll_timeout:o,max_empty_responses:n,log_level:s,on_error:i});return console.log("bot poll settings",c),c}},K=class extends J()("BotSettings",{defaultValue(){return pe.make({})}}){};var ue=class extends ae{},As=t=>I(function*(){let e=yield*w(K),r=yield*w(kt);return r.type=="single"?yield*Uc(t,r,e):yield*Nc(t,r,e)}),Nc=(t,e,r)=>Fr({try:()=>e.on_batch(t),catch:o=>o}).pipe(j(o=>o instanceof Promise?$({try:()=>o,catch:n=>n}):k(o)),j(o=>new ue({hasErrors:!o,updates:t})),ve(o=>(console.log("handle batch error",{errorMessage:o instanceof Error?o.message:void 0,updates:t.map(n=>Object.keys(n).at(1))}),k(new ue({hasErrors:!0,updates:t}))))),Dt=class extends qt("HandleUpdateError"){},Uc=(t,e,r)=>Lr(t,o=>Lc(o,e).pipe(ve(n=>(console.log("update handle error",{updateId:o.update_id,updateKey:Object.keys(o).at(1),name:n._tag,...n.cause instanceof Error?{error:n.cause.message}:void 0}),k(n)))),{concurrency:10}).pipe(j(o=>(r.log_level=="debug"&&console.debug("handle batch result",o),new ue({hasErrors:!o.every(n=>n==null),updates:t})))),Lc=(t,e)=>I(function*(){let r=bs(t);if(!r)return yield*P(new Dt({name:"UnknownUpdate",update:t}));let o=e[`on_${r.type}`];if(!o)return yield*P(new Dt({name:"HandlerNotDefined",update:t}));r.type=="message"&&"text"in r&&console.info("Got a new text message",{chatId:r.chat.id,chatType:r.chat.type,message:`${r.text.slice(0,5)}...`});let n,s=yield*Fr({try:()=>o(r),catch:c=>new Dt({name:"BotHandlerError",update:t,cause:c})}).pipe(j(c=>c instanceof Promise?$({try:()=>c,catch:a=>new Dt({name:"BotHandlerError",update:t,cause:a})}):k(c)),ve(c=>(n=c,console.log("error",{updateId:t.update_id,updateKey:Object.keys(t).at(1),name:c._tag,...c.cause instanceof Error?{error:c.cause.message}:void 0}),k($e.make({type:"message",text:`Some internal error has happend(${c.name}) while handling this message`,message_effect_id:Ae["\u{1F4A9}"],...t.message?.message_id?{reply_parameters:{message_id:t.message?.message_id}}:void 0}))))),i=yield*w(K);if(!s&&i.log_level=="debug"){console.log(`Bot response is undefined for update with ID #${t.update_id}.`);return}if("chat"in r&&s.response){let c=yield*it(`send_${s.response.type}`,{...s.response,chat_id:r.chat.id});i.log_level=="debug"&&console.debug("bot response",c)}return n});var Ve=class extends J()("BotFetchUpdatesService",{defaultValue:()=>{let e={lastUpdateId:void 0,emptyResponses:0},r=Hc(e).pipe(ee(n=>{let s=n.map(i=>i.update_id).sort().at(-1);console.log("updating last update id",s),e.lastUpdateId=s?s+1:void 0,console.log(e)})),o=Bc(e);return{state:e,fetchUpdates:r,commit:o}}}){},Ye=class extends qt("FetchUpdatesError"){},Hc=t=>I(function*(){let e=yield*w(K);if(e.max_empty_responses&&t.emptyResponses==e.max_empty_responses)return yield*P(new Ye({name:"TooManyEmptyResponses"}));let r=t.lastUpdateId;e.log_level=="debug"&&console.debug("getting updates",t);let o=yield*it("get_updates",{timeout:e.poll_timeout,...r?{offset:r}:void 0}).pipe(j(n=>n.sort(s=>s.update_id)));return o.length?(console.debug(`got a batch of updates (${o.length})`),t.emptyResponses=0,o):(t.emptyResponses+=1,[])}),Bc=t=>I(function*(){return console.log("commit",{pollState:t}),t.lastUpdateId?yield*it("get_updates",{offset:t.lastUpdateId,limit:0}).pipe(j(j(w(K),e=>{e.log_level=="debug"&&console.debug("committed offset",t)}))):yield*P(new Ye({name:"NoUpdatesToCommit"}))});var Ke=class extends J()("BotRunService",{defaultValue:()=>{console.log("Initiating BotRunService");let e={fiber:void 0};return{runBotInBackground:qc(e),getFiber:()=>e.fiber}}}){},qc=t=>I(function*(){console.log("run bot");let e=yield*w(Ve),r=hn(1e3)(e.fetchUpdates.pipe(j(o=>As(o)),ee(({updates:o})=>o.length>0?e.commit:_t))).pipe(ln({while:o=>!o.hasErrors}),xn,ee(o=>o.addObserver(n=>{console.log("bot's fiber has been closed",n)})));t.fiber&&(console.log("killing previous bot's fiber"),yield*en(t.fiber)),t.fiber=yield*r,console.log("Fetching bot updates via long polling...")});var Ms=t=>I(function*(){if(t.type=="config")return re(t);let e=yield*$({try:async()=>{let{readFileSync:r}=await import("fs");return JSON.parse(await r("config.json","utf-8"))},catch:r=>(console.warn("invalid tg bot config",r),"ReadingConfigError")});return Is(e)?re(e):yield*P("InvalidConfig")});var ws=t=>I(function*(){let e=Go(H,yield*Ms(t)),r=yield*w(Ke);return yield*r.runBotInBackground.pipe(Nr(e),rt(kt,t.mode),rt(K,pe.make(t.poll??{}))),{reload:n=>r.runBotInBackground.pipe(rt(kt,n),Nr(e),Ot),fiber:r.getFiber}});var pf=t=>ws(t).pipe(Ot),uf=t=>(Object.keys(t).length==0&&console.warn("No handlers are defined for bot"),t);var Ts=t=>I(function*(){let e=yield*it("get_file",{file_id:t}),r=yield*w(H),o=e.file_path;if(!o||o.length==0)return yield*P(new Y({reason:{type:"UnableToGetFile",cause:"File path not defined"}}));let n=o.replaceAll("/","-"),s=`${r.base_url}/file/bot${r.bot_token}/${o}`,i=yield*$({try:()=>fetch(s).then(a=>a.arrayBuffer()),catch:a=>new Y({reason:{type:"UnableToGetFile",cause:a}})});return new File([new Uint8Array(i)],n)});var le=class extends vt("ClientFileService")(){},Rs=I(function*(){return{getFile:t=>Ts(t.file_id)}});var bf=t=>{let e=re(t);return I(function*(){let o=yield*w(le);return{execute:(n,s)=>it(n,s).pipe(rt(H,e),Ot),getFile:n=>o.getFile(n).pipe(rt(H,e),Ot)}}).pipe(un(le,Rs),rt(H,e),_n)};export{$e as BotResponse,Ke as BotRunService,kt as BotUpdateHandlersTag,Ae as MESSAGE_EFFECTS,yn as defaultBaseUrl,uf as defineBot,Za as isMessageEffect,ws as launchBot,bf as makeTgBotClient,Ka as messageEffectIdCodes,pf as runTgChatBot};