@effect-ak/tg-bot 1.2.4 → 1.3.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.
Files changed (5) hide show
  1. package/dist/index.cjs +396 -3971
  2. package/dist/index.d.ts +110 -81
  3. package/dist/index.js +391 -3955
  4. package/package.json +16 -12
  5. package/readme.md +34 -465
package/dist/index.js CHANGED
@@ -1,3556 +1,34 @@
1
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Function.js
2
- var isFunction = (input) => typeof input === "function";
3
- var dual = function(arity, body) {
4
- if (typeof arity === "function") {
5
- return function() {
6
- if (arity(arguments)) {
7
- return body.apply(this, arguments);
8
- }
9
- return (self) => body(self, ...arguments);
10
- };
11
- }
12
- switch (arity) {
13
- case 0:
14
- case 1:
15
- throw new RangeError(`Invalid arity ${arity}`);
16
- case 2:
17
- return function(a, b) {
18
- if (arguments.length >= 2) {
19
- return body(a, b);
20
- }
21
- return function(self) {
22
- return body(self, a);
23
- };
24
- };
25
- case 3:
26
- return function(a, b, c) {
27
- if (arguments.length >= 3) {
28
- return body(a, b, c);
29
- }
30
- return function(self) {
31
- return body(self, a, b);
32
- };
33
- };
34
- case 4:
35
- return function(a, b, c, d) {
36
- if (arguments.length >= 4) {
37
- return body(a, b, c, d);
38
- }
39
- return function(self) {
40
- return body(self, a, b, c);
41
- };
42
- };
43
- case 5:
44
- return function(a, b, c, d, e) {
45
- if (arguments.length >= 5) {
46
- return body(a, b, c, d, e);
47
- }
48
- return function(self) {
49
- return body(self, a, b, c, d);
50
- };
51
- };
52
- default:
53
- return function() {
54
- if (arguments.length >= arity) {
55
- return body.apply(this, arguments);
56
- }
57
- const args2 = arguments;
58
- return function(self) {
59
- return body(self, ...args2);
60
- };
61
- };
62
- }
63
- };
64
- var identity = (a) => a;
65
- var constant = (value) => () => value;
66
- var constTrue = /* @__PURE__ */ constant(true);
67
- var constFalse = /* @__PURE__ */ constant(false);
68
- var constUndefined = /* @__PURE__ */ constant(void 0);
69
- var constVoid = constUndefined;
70
- function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {
71
- switch (arguments.length) {
72
- case 1:
73
- return a;
74
- case 2:
75
- return ab(a);
76
- case 3:
77
- return bc(ab(a));
78
- case 4:
79
- return cd(bc(ab(a)));
80
- case 5:
81
- return de(cd(bc(ab(a))));
82
- case 6:
83
- return ef(de(cd(bc(ab(a)))));
84
- case 7:
85
- return fg(ef(de(cd(bc(ab(a))))));
86
- case 8:
87
- return gh(fg(ef(de(cd(bc(ab(a)))))));
88
- case 9:
89
- return hi(gh(fg(ef(de(cd(bc(ab(a))))))));
90
- default: {
91
- let ret = arguments[0];
92
- for (let i = 1; i < arguments.length; i++) {
93
- ret = arguments[i](ret);
94
- }
95
- return ret;
96
- }
97
- }
98
- }
99
-
100
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Equivalence.js
101
- var make = (isEquivalent) => (self, that) => self === that || isEquivalent(self, that);
102
-
103
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/GlobalValue.js
104
- var globalStoreId = `effect/GlobalValue`;
105
- var globalStore;
106
- var globalValue = (id, compute) => {
107
- if (!globalStore) {
108
- globalThis[globalStoreId] ??= /* @__PURE__ */ new Map();
109
- globalStore = globalThis[globalStoreId];
110
- }
111
- if (!globalStore.has(id)) {
112
- globalStore.set(id, compute());
113
- }
114
- return globalStore.get(id);
115
- };
116
-
117
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Predicate.js
118
- var isFunction2 = isFunction;
119
- var isRecordOrArray = (input) => typeof input === "object" && input !== null;
120
- var isObject = (input) => isRecordOrArray(input) || isFunction2(input);
121
- var hasProperty = /* @__PURE__ */ dual(2, (self, property) => isObject(self) && property in self);
122
- var isTagged = /* @__PURE__ */ dual(2, (self, tag) => hasProperty(self, "_tag") && self["_tag"] === tag);
123
-
124
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/errors.js
125
- var getBugErrorMessage = (message) => `BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`;
126
-
127
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Utils.js
128
- var GenKindTypeId = /* @__PURE__ */ Symbol.for("effect/Gen/GenKind");
129
- var GenKindImpl = class {
130
- value;
131
- constructor(value) {
132
- this.value = value;
133
- }
134
- /**
135
- * @since 2.0.0
136
- */
137
- get _F() {
138
- return identity;
139
- }
140
- /**
141
- * @since 2.0.0
142
- */
143
- get _R() {
144
- return (_) => _;
145
- }
146
- /**
147
- * @since 2.0.0
148
- */
149
- get _O() {
150
- return (_) => _;
151
- }
152
- /**
153
- * @since 2.0.0
154
- */
155
- get _E() {
156
- return (_) => _;
157
- }
158
- /**
159
- * @since 2.0.0
160
- */
161
- [GenKindTypeId] = GenKindTypeId;
162
- /**
163
- * @since 2.0.0
164
- */
165
- [Symbol.iterator]() {
166
- return new SingleShotGen(this);
167
- }
168
- };
169
- var SingleShotGen = class _SingleShotGen {
170
- self;
171
- called = false;
172
- constructor(self) {
173
- this.self = self;
174
- }
175
- /**
176
- * @since 2.0.0
177
- */
178
- next(a) {
179
- return this.called ? {
180
- value: a,
181
- done: true
182
- } : (this.called = true, {
183
- value: this.self,
184
- done: false
185
- });
186
- }
187
- /**
188
- * @since 2.0.0
189
- */
190
- return(a) {
191
- return {
192
- value: a,
193
- done: true
194
- };
195
- }
196
- /**
197
- * @since 2.0.0
198
- */
199
- throw(e) {
200
- throw e;
201
- }
202
- /**
203
- * @since 2.0.0
204
- */
205
- [Symbol.iterator]() {
206
- return new _SingleShotGen(this.self);
207
- }
208
- };
209
- var MUL_HI = 1481765933 >>> 0;
210
- var MUL_LO = 1284865837 >>> 0;
211
- var YieldWrapTypeId = /* @__PURE__ */ Symbol.for("effect/Utils/YieldWrap");
212
- var YieldWrap = class {
213
- /**
214
- * @since 3.0.6
215
- */
216
- #value;
217
- constructor(value) {
218
- this.#value = value;
219
- }
220
- /**
221
- * @since 3.0.6
222
- */
223
- [YieldWrapTypeId]() {
224
- return this.#value;
225
- }
226
- };
227
- function yieldWrapGet(self) {
228
- if (typeof self === "object" && self !== null && YieldWrapTypeId in self) {
229
- return self[YieldWrapTypeId]();
230
- }
231
- throw new Error(getBugErrorMessage("yieldWrapGet"));
232
- }
233
- var structuralRegionState = /* @__PURE__ */ globalValue("effect/Utils/isStructuralRegion", () => ({
234
- enabled: false,
235
- tester: void 0
236
- }));
237
- var standard = {
238
- effect_internal_function: (body) => {
239
- return body();
240
- }
241
- };
242
- var forced = {
243
- effect_internal_function: (body) => {
244
- try {
245
- return body();
246
- } finally {
247
- }
248
- }
249
- };
250
- var isNotOptimizedAway = /* @__PURE__ */ standard.effect_internal_function(() => new Error().stack)?.includes("effect_internal_function") === true;
251
- var internalCall = isNotOptimizedAway ? standard.effect_internal_function : forced.effect_internal_function;
252
- var genConstructor = function* () {
253
- }.constructor;
254
-
255
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Hash.js
256
- var randomHashCache = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Hash/randomHashCache"), () => /* @__PURE__ */ new WeakMap());
257
- var symbol = /* @__PURE__ */ Symbol.for("effect/Hash");
258
- var hash = (self) => {
259
- if (structuralRegionState.enabled === true) {
260
- return 0;
261
- }
262
- switch (typeof self) {
263
- case "number":
264
- return number(self);
265
- case "bigint":
266
- return string(self.toString(10));
267
- case "boolean":
268
- return string(String(self));
269
- case "symbol":
270
- return string(String(self));
271
- case "string":
272
- return string(self);
273
- case "undefined":
274
- return string("undefined");
275
- case "function":
276
- case "object": {
277
- if (self === null) {
278
- return string("null");
279
- } else if (self instanceof Date) {
280
- if (Number.isNaN(self.getTime())) {
281
- return string("Invalid Date");
282
- }
283
- return hash(self.toISOString());
284
- } else if (self instanceof URL) {
285
- return hash(self.href);
286
- } else if (isHash(self)) {
287
- return self[symbol]();
288
- } else {
289
- return random(self);
290
- }
291
- }
292
- default:
293
- throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`);
294
- }
295
- };
296
- var random = (self) => {
297
- if (!randomHashCache.has(self)) {
298
- randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)));
299
- }
300
- return randomHashCache.get(self);
301
- };
302
- var combine = (b) => (self) => self * 53 ^ b;
303
- var optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824;
304
- var isHash = (u) => hasProperty(u, symbol);
305
- var number = (n) => {
306
- if (n !== n || n === Infinity) {
307
- return 0;
308
- }
309
- let h = n | 0;
310
- if (h !== n) {
311
- h ^= n * 4294967295;
312
- }
313
- while (n > 4294967295) {
314
- h ^= n /= 4294967295;
315
- }
316
- return optimize(h);
317
- };
318
- var string = (str) => {
319
- let h = 5381, i = str.length;
320
- while (i) {
321
- h = h * 33 ^ str.charCodeAt(--i);
322
- }
323
- return optimize(h);
324
- };
325
- var structureKeys = (o, keys2) => {
326
- let h = 12289;
327
- for (let i = 0; i < keys2.length; i++) {
328
- h ^= pipe(string(keys2[i]), combine(hash(o[keys2[i]])));
329
- }
330
- return optimize(h);
331
- };
332
- var structure = (o) => structureKeys(o, Object.keys(o));
333
- var array = (arr) => {
334
- let h = 6151;
335
- for (let i = 0; i < arr.length; i++) {
336
- h = pipe(h, combine(hash(arr[i])));
337
- }
338
- return optimize(h);
339
- };
340
- var cached = function() {
341
- if (arguments.length === 1) {
342
- const self2 = arguments[0];
343
- return function(hash3) {
344
- Object.defineProperty(self2, symbol, {
345
- value() {
346
- return hash3;
347
- },
348
- enumerable: false
349
- });
350
- return hash3;
351
- };
352
- }
353
- const self = arguments[0];
354
- const hash2 = arguments[1];
355
- Object.defineProperty(self, symbol, {
356
- value() {
357
- return hash2;
358
- },
359
- enumerable: false
360
- });
361
- return hash2;
362
- };
363
-
364
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Equal.js
365
- var symbol2 = /* @__PURE__ */ Symbol.for("effect/Equal");
366
- function equals() {
367
- if (arguments.length === 1) {
368
- return (self) => compareBoth(self, arguments[0]);
369
- }
370
- return compareBoth(arguments[0], arguments[1]);
371
- }
372
- function compareBoth(self, that) {
373
- if (self === that) {
374
- return true;
375
- }
376
- const selfType = typeof self;
377
- if (selfType !== typeof that) {
378
- return false;
379
- }
380
- if (selfType === "object" || selfType === "function") {
381
- if (self !== null && that !== null) {
382
- if (isEqual(self) && isEqual(that)) {
383
- if (hash(self) === hash(that) && self[symbol2](that)) {
384
- return true;
385
- } else {
386
- return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
387
- }
388
- } else if (self instanceof Date && that instanceof Date) {
389
- const t1 = self.getTime();
390
- const t2 = that.getTime();
391
- return t1 === t2 || Number.isNaN(t1) && Number.isNaN(t2);
392
- } else if (self instanceof URL && that instanceof URL) {
393
- return self.href === that.href;
394
- }
395
- }
396
- if (structuralRegionState.enabled) {
397
- if (Array.isArray(self) && Array.isArray(that)) {
398
- return self.length === that.length && self.every((v, i) => compareBoth(v, that[i]));
399
- }
400
- if (Object.getPrototypeOf(self) === Object.prototype && Object.getPrototypeOf(self) === Object.prototype) {
401
- const keysSelf = Object.keys(self);
402
- const keysThat = Object.keys(that);
403
- if (keysSelf.length === keysThat.length) {
404
- for (const key of keysSelf) {
405
- if (!(key in that && compareBoth(self[key], that[key]))) {
406
- return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
407
- }
408
- }
409
- return true;
410
- }
411
- }
412
- return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
413
- }
414
- }
415
- return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
416
- }
417
- var isEqual = (u) => hasProperty(u, symbol2);
418
-
419
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Inspectable.js
420
- var NodeInspectSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
421
- var toJSON = (x) => {
422
- try {
423
- if (hasProperty(x, "toJSON") && isFunction2(x["toJSON"]) && x["toJSON"].length === 0) {
424
- return x.toJSON();
425
- } else if (Array.isArray(x)) {
426
- return x.map(toJSON);
427
- }
428
- } catch {
429
- return {};
430
- }
431
- return redact(x);
432
- };
433
- var format = (x) => JSON.stringify(x, null, 2);
434
- var BaseProto = {
435
- toJSON() {
436
- return toJSON(this);
437
- },
438
- [NodeInspectSymbol]() {
439
- return this.toJSON();
440
- },
441
- toString() {
442
- return format(this.toJSON());
443
- }
444
- };
445
- var Class = class {
446
- /**
447
- * @since 2.0.0
448
- */
449
- [NodeInspectSymbol]() {
450
- return this.toJSON();
451
- }
452
- /**
453
- * @since 2.0.0
454
- */
455
- toString() {
456
- return format(this.toJSON());
457
- }
458
- };
459
- var toStringUnknown = (u, whitespace = 2) => {
460
- if (typeof u === "string") {
461
- return u;
462
- }
463
- try {
464
- return typeof u === "object" ? stringifyCircular(u, whitespace) : String(u);
465
- } catch {
466
- return String(u);
467
- }
468
- };
469
- var stringifyCircular = (obj, whitespace) => {
470
- let cache = [];
471
- const retVal = JSON.stringify(obj, (_key, value) => typeof value === "object" && value !== null ? cache.includes(value) ? void 0 : cache.push(value) && (redactableState.fiberRefs !== void 0 && isRedactable(value) ? value[symbolRedactable](redactableState.fiberRefs) : value) : value, whitespace);
472
- cache = void 0;
473
- return retVal;
474
- };
475
- var symbolRedactable = /* @__PURE__ */ Symbol.for("effect/Inspectable/Redactable");
476
- var isRedactable = (u) => typeof u === "object" && u !== null && symbolRedactable in u;
477
- var redactableState = /* @__PURE__ */ globalValue("effect/Inspectable/redactableState", () => ({
478
- fiberRefs: void 0
479
- }));
480
- var redact = (u) => {
481
- if (isRedactable(u) && redactableState.fiberRefs !== void 0) {
482
- return u[symbolRedactable](redactableState.fiberRefs);
483
- }
484
- return u;
485
- };
486
-
487
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Pipeable.js
488
- var pipeArguments = (self, args2) => {
489
- switch (args2.length) {
490
- case 0:
491
- return self;
492
- case 1:
493
- return args2[0](self);
494
- case 2:
495
- return args2[1](args2[0](self));
496
- case 3:
497
- return args2[2](args2[1](args2[0](self)));
498
- case 4:
499
- return args2[3](args2[2](args2[1](args2[0](self))));
500
- case 5:
501
- return args2[4](args2[3](args2[2](args2[1](args2[0](self)))));
502
- case 6:
503
- return args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self))))));
504
- case 7:
505
- return args2[6](args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self)))))));
506
- case 8:
507
- return args2[7](args2[6](args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self))))))));
508
- case 9:
509
- return args2[8](args2[7](args2[6](args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self)))))))));
510
- default: {
511
- let ret = self;
512
- for (let i = 0, len = args2.length; i < len; i++) {
513
- ret = args2[i](ret);
514
- }
515
- return ret;
516
- }
517
- }
518
- };
519
-
520
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/opCodes/effect.js
521
- var OP_COMMIT = "Commit";
522
- var OP_FAILURE = "Failure";
523
- var OP_WITH_RUNTIME = "WithRuntime";
524
-
525
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/version.js
526
- var moduleVersion = "3.19.13";
527
- var getCurrentVersion = () => moduleVersion;
528
-
529
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/effectable.js
530
- var EffectTypeId = /* @__PURE__ */ Symbol.for("effect/Effect");
531
- var StreamTypeId = /* @__PURE__ */ Symbol.for("effect/Stream");
532
- var SinkTypeId = /* @__PURE__ */ Symbol.for("effect/Sink");
533
- var ChannelTypeId = /* @__PURE__ */ Symbol.for("effect/Channel");
534
- var effectVariance = {
535
- /* c8 ignore next */
536
- _R: (_) => _,
537
- /* c8 ignore next */
538
- _E: (_) => _,
539
- /* c8 ignore next */
540
- _A: (_) => _,
541
- _V: /* @__PURE__ */ getCurrentVersion()
542
- };
543
- var sinkVariance = {
544
- /* c8 ignore next */
545
- _A: (_) => _,
546
- /* c8 ignore next */
547
- _In: (_) => _,
548
- /* c8 ignore next */
549
- _L: (_) => _,
550
- /* c8 ignore next */
551
- _E: (_) => _,
552
- /* c8 ignore next */
553
- _R: (_) => _
554
- };
555
- var channelVariance = {
556
- /* c8 ignore next */
557
- _Env: (_) => _,
558
- /* c8 ignore next */
559
- _InErr: (_) => _,
560
- /* c8 ignore next */
561
- _InElem: (_) => _,
562
- /* c8 ignore next */
563
- _InDone: (_) => _,
564
- /* c8 ignore next */
565
- _OutErr: (_) => _,
566
- /* c8 ignore next */
567
- _OutElem: (_) => _,
568
- /* c8 ignore next */
569
- _OutDone: (_) => _
570
- };
571
- var EffectPrototype = {
572
- [EffectTypeId]: effectVariance,
573
- [StreamTypeId]: effectVariance,
574
- [SinkTypeId]: sinkVariance,
575
- [ChannelTypeId]: channelVariance,
576
- [symbol2](that) {
577
- return this === that;
578
- },
579
- [symbol]() {
580
- return cached(this, random(this));
581
- },
582
- [Symbol.iterator]() {
583
- return new SingleShotGen(new YieldWrap(this));
584
- },
585
- pipe() {
586
- return pipeArguments(this, arguments);
587
- }
588
- };
589
- var StructuralPrototype = {
590
- [symbol]() {
591
- return cached(this, structure(this));
592
- },
593
- [symbol2](that) {
594
- const selfKeys = Object.keys(this);
595
- const thatKeys = Object.keys(that);
596
- if (selfKeys.length !== thatKeys.length) {
597
- return false;
598
- }
599
- for (const key of selfKeys) {
600
- if (!(key in that && equals(this[key], that[key]))) {
601
- return false;
602
- }
603
- }
604
- return true;
605
- }
606
- };
607
- var CommitPrototype = {
608
- ...EffectPrototype,
609
- _op: OP_COMMIT
610
- };
611
- var StructuralCommitPrototype = {
612
- ...CommitPrototype,
613
- ...StructuralPrototype
614
- };
615
-
616
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/option.js
617
- var TypeId = /* @__PURE__ */ Symbol.for("effect/Option");
618
- var CommonProto = {
619
- ...EffectPrototype,
620
- [TypeId]: {
621
- _A: (_) => _
622
- },
623
- [NodeInspectSymbol]() {
624
- return this.toJSON();
625
- },
626
- toString() {
627
- return format(this.toJSON());
628
- }
629
- };
630
- var SomeProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
631
- _tag: "Some",
632
- _op: "Some",
633
- [symbol2](that) {
634
- return isOption(that) && isSome(that) && equals(this.value, that.value);
635
- },
636
- [symbol]() {
637
- return cached(this, combine(hash(this._tag))(hash(this.value)));
638
- },
639
- toJSON() {
640
- return {
641
- _id: "Option",
642
- _tag: this._tag,
643
- value: toJSON(this.value)
644
- };
645
- }
646
- });
647
- var NoneHash = /* @__PURE__ */ hash("None");
648
- var NoneProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
649
- _tag: "None",
650
- _op: "None",
651
- [symbol2](that) {
652
- return isOption(that) && isNone(that);
653
- },
654
- [symbol]() {
655
- return NoneHash;
656
- },
657
- toJSON() {
658
- return {
659
- _id: "Option",
660
- _tag: this._tag
661
- };
662
- }
663
- });
664
- var isOption = (input) => hasProperty(input, TypeId);
665
- var isNone = (fa) => fa._tag === "None";
666
- var isSome = (fa) => fa._tag === "Some";
667
- var none = /* @__PURE__ */ Object.create(NoneProto);
668
- var some = (value) => {
669
- const a = Object.create(SomeProto);
670
- a.value = value;
671
- return a;
672
- };
673
-
674
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/either.js
675
- var TypeId2 = /* @__PURE__ */ Symbol.for("effect/Either");
676
- var CommonProto2 = {
677
- ...EffectPrototype,
678
- [TypeId2]: {
679
- _R: (_) => _
680
- },
681
- [NodeInspectSymbol]() {
682
- return this.toJSON();
683
- },
684
- toString() {
685
- return format(this.toJSON());
686
- }
687
- };
688
- var RightProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
689
- _tag: "Right",
690
- _op: "Right",
691
- [symbol2](that) {
692
- return isEither(that) && isRight(that) && equals(this.right, that.right);
693
- },
694
- [symbol]() {
695
- return combine(hash(this._tag))(hash(this.right));
696
- },
697
- toJSON() {
698
- return {
699
- _id: "Either",
700
- _tag: this._tag,
701
- right: toJSON(this.right)
702
- };
703
- }
704
- });
705
- var LeftProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
706
- _tag: "Left",
707
- _op: "Left",
708
- [symbol2](that) {
709
- return isEither(that) && isLeft(that) && equals(this.left, that.left);
710
- },
711
- [symbol]() {
712
- return combine(hash(this._tag))(hash(this.left));
713
- },
714
- toJSON() {
715
- return {
716
- _id: "Either",
717
- _tag: this._tag,
718
- left: toJSON(this.left)
719
- };
720
- }
721
- });
722
- var isEither = (input) => hasProperty(input, TypeId2);
723
- var isLeft = (ma) => ma._tag === "Left";
724
- var isRight = (ma) => ma._tag === "Right";
725
- var left = (left3) => {
726
- const a = Object.create(LeftProto);
727
- a.left = left3;
728
- return a;
729
- };
730
- var right = (right3) => {
731
- const a = Object.create(RightProto);
732
- a.right = right3;
733
- return a;
734
- };
735
-
736
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Either.js
737
- var right2 = right;
738
- var left2 = left;
739
-
740
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Option.js
741
- var none2 = () => none;
742
- var some2 = some;
743
- var isNone2 = isNone;
744
- var isSome2 = isSome;
745
- var getOrElse = /* @__PURE__ */ dual(2, (self, onNone) => isNone2(self) ? onNone() : self.value);
746
- var getOrUndefined = /* @__PURE__ */ getOrElse(constUndefined);
747
-
748
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Array.js
749
- var fromIterable = (collection) => Array.isArray(collection) ? collection : Array.from(collection);
750
- var isArray = Array.isArray;
751
- var reverse = (self) => Array.from(self).reverse();
752
- var reduce = /* @__PURE__ */ dual(3, (self, b, f) => fromIterable(self).reduce((b2, a, i) => f(b2, a, i), b));
753
-
754
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Chunk.js
755
- var TypeId3 = /* @__PURE__ */ Symbol.for("effect/Chunk");
756
- function copy(src, srcPos, dest, destPos, len) {
757
- for (let i = srcPos; i < Math.min(src.length, srcPos + len); i++) {
758
- dest[destPos + i - srcPos] = src[i];
759
- }
760
- return dest;
761
- }
762
- var emptyArray = [];
763
- var getEquivalence = (isEquivalent) => make((self, that) => self.length === that.length && toReadonlyArray(self).every((value, i) => isEquivalent(value, unsafeGet(that, i))));
764
- var _equivalence = /* @__PURE__ */ getEquivalence(equals);
765
- var ChunkProto = {
766
- [TypeId3]: {
767
- _A: (_) => _
768
- },
769
- toString() {
770
- return format(this.toJSON());
771
- },
772
- toJSON() {
773
- return {
774
- _id: "Chunk",
775
- values: toReadonlyArray(this).map(toJSON)
776
- };
777
- },
778
- [NodeInspectSymbol]() {
779
- return this.toJSON();
780
- },
781
- [symbol2](that) {
782
- return isChunk(that) && _equivalence(this, that);
783
- },
784
- [symbol]() {
785
- return cached(this, array(toReadonlyArray(this)));
786
- },
787
- [Symbol.iterator]() {
788
- switch (this.backing._tag) {
789
- case "IArray": {
790
- return this.backing.array[Symbol.iterator]();
791
- }
792
- case "IEmpty": {
793
- return emptyArray[Symbol.iterator]();
794
- }
795
- default: {
796
- return toReadonlyArray(this)[Symbol.iterator]();
797
- }
798
- }
799
- },
800
- pipe() {
801
- return pipeArguments(this, arguments);
802
- }
803
- };
804
- var makeChunk = (backing) => {
805
- const chunk = Object.create(ChunkProto);
806
- chunk.backing = backing;
807
- switch (backing._tag) {
808
- case "IEmpty": {
809
- chunk.length = 0;
810
- chunk.depth = 0;
811
- chunk.left = chunk;
812
- chunk.right = chunk;
813
- break;
814
- }
815
- case "IConcat": {
816
- chunk.length = backing.left.length + backing.right.length;
817
- chunk.depth = 1 + Math.max(backing.left.depth, backing.right.depth);
818
- chunk.left = backing.left;
819
- chunk.right = backing.right;
820
- break;
821
- }
822
- case "IArray": {
823
- chunk.length = backing.array.length;
824
- chunk.depth = 0;
825
- chunk.left = _empty;
826
- chunk.right = _empty;
827
- break;
828
- }
829
- case "ISingleton": {
830
- chunk.length = 1;
831
- chunk.depth = 0;
832
- chunk.left = _empty;
833
- chunk.right = _empty;
834
- break;
835
- }
836
- case "ISlice": {
837
- chunk.length = backing.length;
838
- chunk.depth = backing.chunk.depth + 1;
839
- chunk.left = _empty;
840
- chunk.right = _empty;
841
- break;
842
- }
843
- }
844
- return chunk;
845
- };
846
- var isChunk = (u) => hasProperty(u, TypeId3);
847
- var _empty = /* @__PURE__ */ makeChunk({
848
- _tag: "IEmpty"
849
- });
850
- var empty = () => _empty;
851
- var make2 = (...as2) => unsafeFromNonEmptyArray(as2);
852
- var of = (a) => makeChunk({
853
- _tag: "ISingleton",
854
- a
855
- });
856
- var fromIterable2 = (self) => isChunk(self) ? self : unsafeFromArray(fromIterable(self));
857
- var copyToArray = (self, array2, initial) => {
858
- switch (self.backing._tag) {
859
- case "IArray": {
860
- copy(self.backing.array, 0, array2, initial, self.length);
861
- break;
862
- }
863
- case "IConcat": {
864
- copyToArray(self.left, array2, initial);
865
- copyToArray(self.right, array2, initial + self.left.length);
866
- break;
867
- }
868
- case "ISingleton": {
869
- array2[initial] = self.backing.a;
870
- break;
871
- }
872
- case "ISlice": {
873
- let i = 0;
874
- let j = initial;
875
- while (i < self.length) {
876
- array2[j] = unsafeGet(self, i);
877
- i += 1;
878
- j += 1;
879
- }
880
- break;
881
- }
882
- }
883
- };
884
- var toReadonlyArray_ = (self) => {
885
- switch (self.backing._tag) {
886
- case "IEmpty": {
887
- return emptyArray;
888
- }
889
- case "IArray": {
890
- return self.backing.array;
891
- }
892
- default: {
893
- const arr = new Array(self.length);
894
- copyToArray(self, arr, 0);
895
- self.backing = {
896
- _tag: "IArray",
897
- array: arr
898
- };
899
- self.left = _empty;
900
- self.right = _empty;
901
- self.depth = 0;
902
- return arr;
903
- }
904
- }
905
- };
906
- var toReadonlyArray = toReadonlyArray_;
907
- var reverseChunk = (self) => {
908
- switch (self.backing._tag) {
909
- case "IEmpty":
910
- case "ISingleton":
911
- return self;
912
- case "IArray": {
913
- return makeChunk({
914
- _tag: "IArray",
915
- array: reverse(self.backing.array)
916
- });
917
- }
918
- case "IConcat": {
919
- return makeChunk({
920
- _tag: "IConcat",
921
- left: reverse2(self.backing.right),
922
- right: reverse2(self.backing.left)
923
- });
924
- }
925
- case "ISlice":
926
- return unsafeFromArray(reverse(toReadonlyArray(self)));
927
- }
928
- };
929
- var reverse2 = reverseChunk;
930
- var unsafeFromArray = (self) => self.length === 0 ? empty() : self.length === 1 ? of(self[0]) : makeChunk({
931
- _tag: "IArray",
932
- array: self
933
- });
934
- var unsafeFromNonEmptyArray = (self) => unsafeFromArray(self);
935
- var unsafeGet = /* @__PURE__ */ dual(2, (self, index) => {
936
- switch (self.backing._tag) {
937
- case "IEmpty": {
938
- throw new Error(`Index out of bounds`);
939
- }
940
- case "ISingleton": {
941
- if (index !== 0) {
942
- throw new Error(`Index out of bounds`);
943
- }
944
- return self.backing.a;
945
- }
946
- case "IArray": {
947
- if (index >= self.length || index < 0) {
948
- throw new Error(`Index out of bounds`);
949
- }
950
- return self.backing.array[index];
951
- }
952
- case "IConcat": {
953
- return index < self.left.length ? unsafeGet(self.left, index) : unsafeGet(self.right, index - self.left.length);
954
- }
955
- case "ISlice": {
956
- return unsafeGet(self.backing.chunk, index + self.backing.offset);
957
- }
958
- }
959
- });
960
- var prepend = /* @__PURE__ */ dual(2, (self, elem) => appendAll(of(elem), self));
961
- var appendAll = /* @__PURE__ */ dual(2, (self, that) => {
962
- if (self.backing._tag === "IEmpty") {
963
- return that;
964
- }
965
- if (that.backing._tag === "IEmpty") {
966
- return self;
967
- }
968
- const diff = that.depth - self.depth;
969
- if (Math.abs(diff) <= 1) {
970
- return makeChunk({
971
- _tag: "IConcat",
972
- left: self,
973
- right: that
974
- });
975
- } else if (diff < -1) {
976
- if (self.left.depth >= self.right.depth) {
977
- const nr = appendAll(self.right, that);
978
- return makeChunk({
979
- _tag: "IConcat",
980
- left: self.left,
981
- right: nr
982
- });
983
- } else {
984
- const nrr = appendAll(self.right.right, that);
985
- if (nrr.depth === self.depth - 3) {
986
- const nr = makeChunk({
987
- _tag: "IConcat",
988
- left: self.right.left,
989
- right: nrr
990
- });
991
- return makeChunk({
992
- _tag: "IConcat",
993
- left: self.left,
994
- right: nr
995
- });
996
- } else {
997
- const nl = makeChunk({
998
- _tag: "IConcat",
999
- left: self.left,
1000
- right: self.right.left
1001
- });
1002
- return makeChunk({
1003
- _tag: "IConcat",
1004
- left: nl,
1005
- right: nrr
1006
- });
1007
- }
1008
- }
1009
- } else {
1010
- if (that.right.depth >= that.left.depth) {
1011
- const nl = appendAll(self, that.left);
1012
- return makeChunk({
1013
- _tag: "IConcat",
1014
- left: nl,
1015
- right: that.right
1016
- });
1017
- } else {
1018
- const nll = appendAll(self, that.left.left);
1019
- if (nll.depth === that.depth - 3) {
1020
- const nl = makeChunk({
1021
- _tag: "IConcat",
1022
- left: nll,
1023
- right: that.left.right
1024
- });
1025
- return makeChunk({
1026
- _tag: "IConcat",
1027
- left: nl,
1028
- right: that.right
1029
- });
1030
- } else {
1031
- const nr = makeChunk({
1032
- _tag: "IConcat",
1033
- left: that.left.right,
1034
- right: that.right
1035
- });
1036
- return makeChunk({
1037
- _tag: "IConcat",
1038
- left: nll,
1039
- right: nr
1040
- });
1041
- }
1042
- }
1043
- }
1044
- });
1045
- var isEmpty = (self) => self.length === 0;
1046
- var isNonEmpty = (self) => self.length > 0;
1047
- var unsafeHead = (self) => unsafeGet(self, 0);
1048
- var headNonEmpty = unsafeHead;
1049
-
1050
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/context.js
1051
- var TagTypeId = /* @__PURE__ */ Symbol.for("effect/Context/Tag");
1052
- var ReferenceTypeId = /* @__PURE__ */ Symbol.for("effect/Context/Reference");
1053
- var STMSymbolKey = "effect/STM";
1054
- var STMTypeId = /* @__PURE__ */ Symbol.for(STMSymbolKey);
1055
- var TagProto = {
1056
- ...EffectPrototype,
1057
- _op: "Tag",
1058
- [STMTypeId]: effectVariance,
1059
- [TagTypeId]: {
1060
- _Service: (_) => _,
1061
- _Identifier: (_) => _
1062
- },
1063
- toString() {
1064
- return format(this.toJSON());
1065
- },
1066
- toJSON() {
1067
- return {
1068
- _id: "Tag",
1069
- key: this.key,
1070
- stack: this.stack
1071
- };
1072
- },
1073
- [NodeInspectSymbol]() {
1074
- return this.toJSON();
1075
- },
1076
- of(self) {
1077
- return self;
1078
- },
1079
- context(self) {
1080
- return make3(this, self);
1081
- }
1082
- };
1083
- var ReferenceProto = {
1084
- ...TagProto,
1085
- [ReferenceTypeId]: ReferenceTypeId
1086
- };
1087
- var Tag = (id) => () => {
1088
- const limit = Error.stackTraceLimit;
1089
- Error.stackTraceLimit = 2;
1090
- const creationError = new Error();
1091
- Error.stackTraceLimit = limit;
1092
- function TagClass() {
1093
- }
1094
- Object.setPrototypeOf(TagClass, TagProto);
1095
- TagClass.key = id;
1096
- Object.defineProperty(TagClass, "stack", {
1097
- get() {
1098
- return creationError.stack;
1099
- }
1100
- });
1101
- return TagClass;
1102
- };
1103
- var Reference = () => (id, options) => {
1104
- const limit = Error.stackTraceLimit;
1105
- Error.stackTraceLimit = 2;
1106
- const creationError = new Error();
1107
- Error.stackTraceLimit = limit;
1108
- function ReferenceClass() {
1109
- }
1110
- Object.setPrototypeOf(ReferenceClass, ReferenceProto);
1111
- ReferenceClass.key = id;
1112
- ReferenceClass.defaultValue = options.defaultValue;
1113
- Object.defineProperty(ReferenceClass, "stack", {
1114
- get() {
1115
- return creationError.stack;
1116
- }
1117
- });
1118
- return ReferenceClass;
1119
- };
1120
- var TypeId4 = /* @__PURE__ */ Symbol.for("effect/Context");
1121
- var ContextProto = {
1122
- [TypeId4]: {
1123
- _Services: (_) => _
1124
- },
1125
- [symbol2](that) {
1126
- if (isContext(that)) {
1127
- if (this.unsafeMap.size === that.unsafeMap.size) {
1128
- for (const k of this.unsafeMap.keys()) {
1129
- if (!that.unsafeMap.has(k) || !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))) {
1130
- return false;
1131
- }
1132
- }
1133
- return true;
1134
- }
1135
- }
1136
- return false;
1137
- },
1138
- [symbol]() {
1139
- return cached(this, number(this.unsafeMap.size));
1140
- },
1141
- pipe() {
1142
- return pipeArguments(this, arguments);
1143
- },
1144
- toString() {
1145
- return format(this.toJSON());
1146
- },
1147
- toJSON() {
1148
- return {
1149
- _id: "Context",
1150
- services: Array.from(this.unsafeMap).map(toJSON)
1151
- };
1152
- },
1153
- [NodeInspectSymbol]() {
1154
- return this.toJSON();
1155
- }
1156
- };
1157
- var makeContext = (unsafeMap) => {
1158
- const context = Object.create(ContextProto);
1159
- context.unsafeMap = unsafeMap;
1160
- return context;
1161
- };
1162
- var serviceNotFoundError = (tag) => {
1163
- const error = new Error(`Service not found${tag.key ? `: ${String(tag.key)}` : ""}`);
1164
- if (tag.stack) {
1165
- const lines = tag.stack.split("\n");
1166
- if (lines.length > 2) {
1167
- const afterAt = lines[2].match(/at (.*)/);
1168
- if (afterAt) {
1169
- error.message = error.message + ` (defined at ${afterAt[1]})`;
1170
- }
1171
- }
1172
- }
1173
- if (error.stack) {
1174
- const lines = error.stack.split("\n");
1175
- lines.splice(1, 3);
1176
- error.stack = lines.join("\n");
1177
- }
1178
- return error;
1179
- };
1180
- var isContext = (u) => hasProperty(u, TypeId4);
1181
- var make3 = (tag, service2) => makeContext(/* @__PURE__ */ new Map([[tag.key, service2]]));
1182
- var add = /* @__PURE__ */ dual(3, (self, tag, service2) => {
1183
- const map7 = new Map(self.unsafeMap);
1184
- map7.set(tag.key, service2);
1185
- return makeContext(map7);
1186
- });
1187
- var defaultValueCache = /* @__PURE__ */ globalValue("effect/Context/defaultValueCache", () => /* @__PURE__ */ new Map());
1188
- var getDefaultValue = (tag) => {
1189
- if (defaultValueCache.has(tag.key)) {
1190
- return defaultValueCache.get(tag.key);
1191
- }
1192
- const value = tag.defaultValue();
1193
- defaultValueCache.set(tag.key, value);
1194
- return value;
1195
- };
1196
- var unsafeGetReference = (self, tag) => {
1197
- return self.unsafeMap.has(tag.key) ? self.unsafeMap.get(tag.key) : getDefaultValue(tag);
1198
- };
1199
- var unsafeGet2 = /* @__PURE__ */ dual(2, (self, tag) => {
1200
- if (!self.unsafeMap.has(tag.key)) {
1201
- if (ReferenceTypeId in tag) return getDefaultValue(tag);
1202
- throw serviceNotFoundError(tag);
1203
- }
1204
- return self.unsafeMap.get(tag.key);
1205
- });
1206
- var merge = /* @__PURE__ */ dual(2, (self, that) => {
1207
- const map7 = new Map(self.unsafeMap);
1208
- for (const [tag, s] of that.unsafeMap) {
1209
- map7.set(tag, s);
1210
- }
1211
- return makeContext(map7);
1212
- });
1213
-
1214
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Context.js
1215
- var make4 = make3;
1216
- var add2 = add;
1217
- var unsafeGet3 = unsafeGet2;
1218
- var merge2 = merge;
1219
- var Tag2 = Tag;
1220
- var Reference2 = Reference;
1221
-
1222
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/hashMap/config.js
1223
- var SIZE = 5;
1224
- var BUCKET_SIZE = /* @__PURE__ */ Math.pow(2, SIZE);
1225
- var MASK = BUCKET_SIZE - 1;
1226
- var MAX_INDEX_NODE = BUCKET_SIZE / 2;
1227
- var MIN_ARRAY_NODE = BUCKET_SIZE / 4;
1228
-
1229
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/hashMap/bitwise.js
1230
- function popcount(x) {
1231
- x -= x >> 1 & 1431655765;
1232
- x = (x & 858993459) + (x >> 2 & 858993459);
1233
- x = x + (x >> 4) & 252645135;
1234
- x += x >> 8;
1235
- x += x >> 16;
1236
- return x & 127;
1237
- }
1238
- function hashFragment(shift, h) {
1239
- return h >>> shift & MASK;
1240
- }
1241
- function toBitmap(x) {
1242
- return 1 << x;
1243
- }
1244
- function fromBitmap(bitmap, bit) {
1245
- return popcount(bitmap & bit - 1);
1246
- }
1247
-
1248
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/stack.js
1249
- var make5 = (value, previous) => ({
1250
- value,
1251
- previous
1252
- });
1253
-
1254
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/hashMap/array.js
1255
- function arrayUpdate(mutate2, at, v, arr) {
1256
- let out = arr;
1257
- if (!mutate2) {
1258
- const len = arr.length;
1259
- out = new Array(len);
1260
- for (let i = 0; i < len; ++i) out[i] = arr[i];
1261
- }
1262
- out[at] = v;
1263
- return out;
1264
- }
1265
- function arraySpliceOut(mutate2, at, arr) {
1266
- const newLen = arr.length - 1;
1267
- let i = 0;
1268
- let g = 0;
1269
- let out = arr;
1270
- if (mutate2) {
1271
- i = g = at;
1272
- } else {
1273
- out = new Array(newLen);
1274
- while (i < at) out[g++] = arr[i++];
1275
- }
1276
- ++i;
1277
- while (i <= newLen) out[g++] = arr[i++];
1278
- if (mutate2) {
1279
- out.length = newLen;
1280
- }
1281
- return out;
1282
- }
1283
- function arraySpliceIn(mutate2, at, v, arr) {
1284
- const len = arr.length;
1285
- if (mutate2) {
1286
- let i2 = len;
1287
- while (i2 >= at) arr[i2--] = arr[i2];
1288
- arr[at] = v;
1289
- return arr;
1290
- }
1291
- let i = 0, g = 0;
1292
- const out = new Array(len + 1);
1293
- while (i < at) out[g++] = arr[i++];
1294
- out[at] = v;
1295
- while (i < len) out[++g] = arr[i++];
1296
- return out;
1297
- }
1298
-
1299
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/hashMap/node.js
1300
- var EmptyNode = class _EmptyNode {
1301
- _tag = "EmptyNode";
1302
- modify(edit, _shift, f, hash2, key, size4) {
1303
- const v = f(none2());
1304
- if (isNone2(v)) return new _EmptyNode();
1305
- ++size4.value;
1306
- return new LeafNode(edit, hash2, key, v);
1307
- }
1308
- };
1309
- function isEmptyNode(a) {
1310
- return isTagged(a, "EmptyNode");
1311
- }
1312
- function isLeafNode(node) {
1313
- return isEmptyNode(node) || node._tag === "LeafNode" || node._tag === "CollisionNode";
1314
- }
1315
- function canEditNode(node, edit) {
1316
- return isEmptyNode(node) ? false : edit === node.edit;
1317
- }
1318
- var LeafNode = class _LeafNode {
1319
- edit;
1320
- hash;
1321
- key;
1322
- value;
1323
- _tag = "LeafNode";
1324
- constructor(edit, hash2, key, value) {
1325
- this.edit = edit;
1326
- this.hash = hash2;
1327
- this.key = key;
1328
- this.value = value;
1329
- }
1330
- modify(edit, shift, f, hash2, key, size4) {
1331
- if (equals(key, this.key)) {
1332
- const v2 = f(this.value);
1333
- if (v2 === this.value) return this;
1334
- else if (isNone2(v2)) {
1335
- --size4.value;
1336
- return new EmptyNode();
1337
- }
1338
- if (canEditNode(this, edit)) {
1339
- this.value = v2;
1340
- return this;
1341
- }
1342
- return new _LeafNode(edit, hash2, key, v2);
1343
- }
1344
- const v = f(none2());
1345
- if (isNone2(v)) return this;
1346
- ++size4.value;
1347
- return mergeLeaves(edit, shift, this.hash, this, hash2, new _LeafNode(edit, hash2, key, v));
1348
- }
1349
- };
1350
- var CollisionNode = class _CollisionNode {
1351
- edit;
1352
- hash;
1353
- children;
1354
- _tag = "CollisionNode";
1355
- constructor(edit, hash2, children) {
1356
- this.edit = edit;
1357
- this.hash = hash2;
1358
- this.children = children;
1359
- }
1360
- modify(edit, shift, f, hash2, key, size4) {
1361
- if (hash2 === this.hash) {
1362
- const canEdit = canEditNode(this, edit);
1363
- const list = this.updateCollisionList(canEdit, edit, this.hash, this.children, f, key, size4);
1364
- if (list === this.children) return this;
1365
- return list.length > 1 ? new _CollisionNode(edit, this.hash, list) : list[0];
1366
- }
1367
- const v = f(none2());
1368
- if (isNone2(v)) return this;
1369
- ++size4.value;
1370
- return mergeLeaves(edit, shift, this.hash, this, hash2, new LeafNode(edit, hash2, key, v));
1371
- }
1372
- updateCollisionList(mutate2, edit, hash2, list, f, key, size4) {
1373
- const len = list.length;
1374
- for (let i = 0; i < len; ++i) {
1375
- const child = list[i];
1376
- if ("key" in child && equals(key, child.key)) {
1377
- const value = child.value;
1378
- const newValue2 = f(value);
1379
- if (newValue2 === value) return list;
1380
- if (isNone2(newValue2)) {
1381
- --size4.value;
1382
- return arraySpliceOut(mutate2, i, list);
1383
- }
1384
- return arrayUpdate(mutate2, i, new LeafNode(edit, hash2, key, newValue2), list);
1385
- }
1386
- }
1387
- const newValue = f(none2());
1388
- if (isNone2(newValue)) return list;
1389
- ++size4.value;
1390
- return arrayUpdate(mutate2, len, new LeafNode(edit, hash2, key, newValue), list);
1391
- }
1392
- };
1393
- var IndexedNode = class _IndexedNode {
1394
- edit;
1395
- mask;
1396
- children;
1397
- _tag = "IndexedNode";
1398
- constructor(edit, mask, children) {
1399
- this.edit = edit;
1400
- this.mask = mask;
1401
- this.children = children;
1402
- }
1403
- modify(edit, shift, f, hash2, key, size4) {
1404
- const mask = this.mask;
1405
- const children = this.children;
1406
- const frag = hashFragment(shift, hash2);
1407
- const bit = toBitmap(frag);
1408
- const indx = fromBitmap(mask, bit);
1409
- const exists = mask & bit;
1410
- const canEdit = canEditNode(this, edit);
1411
- if (!exists) {
1412
- const _newChild = new EmptyNode().modify(edit, shift + SIZE, f, hash2, key, size4);
1413
- if (!_newChild) return this;
1414
- return children.length >= MAX_INDEX_NODE ? expand(edit, frag, _newChild, mask, children) : new _IndexedNode(edit, mask | bit, arraySpliceIn(canEdit, indx, _newChild, children));
1415
- }
1416
- const current = children[indx];
1417
- const child = current.modify(edit, shift + SIZE, f, hash2, key, size4);
1418
- if (current === child) return this;
1419
- let bitmap = mask;
1420
- let newChildren;
1421
- if (isEmptyNode(child)) {
1422
- bitmap &= ~bit;
1423
- if (!bitmap) return new EmptyNode();
1424
- if (children.length <= 2 && isLeafNode(children[indx ^ 1])) {
1425
- return children[indx ^ 1];
1426
- }
1427
- newChildren = arraySpliceOut(canEdit, indx, children);
1428
- } else {
1429
- newChildren = arrayUpdate(canEdit, indx, child, children);
1430
- }
1431
- if (canEdit) {
1432
- this.mask = bitmap;
1433
- this.children = newChildren;
1434
- return this;
1435
- }
1436
- return new _IndexedNode(edit, bitmap, newChildren);
1437
- }
1438
- };
1439
- var ArrayNode = class _ArrayNode {
1440
- edit;
1441
- size;
1442
- children;
1443
- _tag = "ArrayNode";
1444
- constructor(edit, size4, children) {
1445
- this.edit = edit;
1446
- this.size = size4;
1447
- this.children = children;
1448
- }
1449
- modify(edit, shift, f, hash2, key, size4) {
1450
- let count = this.size;
1451
- const children = this.children;
1452
- const frag = hashFragment(shift, hash2);
1453
- const child = children[frag];
1454
- const newChild = (child || new EmptyNode()).modify(edit, shift + SIZE, f, hash2, key, size4);
1455
- if (child === newChild) return this;
1456
- const canEdit = canEditNode(this, edit);
1457
- let newChildren;
1458
- if (isEmptyNode(child) && !isEmptyNode(newChild)) {
1459
- ++count;
1460
- newChildren = arrayUpdate(canEdit, frag, newChild, children);
1461
- } else if (!isEmptyNode(child) && isEmptyNode(newChild)) {
1462
- --count;
1463
- if (count <= MIN_ARRAY_NODE) {
1464
- return pack(edit, count, frag, children);
1465
- }
1466
- newChildren = arrayUpdate(canEdit, frag, new EmptyNode(), children);
1467
- } else {
1468
- newChildren = arrayUpdate(canEdit, frag, newChild, children);
1469
- }
1470
- if (canEdit) {
1471
- this.size = count;
1472
- this.children = newChildren;
1473
- return this;
1474
- }
1475
- return new _ArrayNode(edit, count, newChildren);
1476
- }
1477
- };
1478
- function pack(edit, count, removed, elements) {
1479
- const children = new Array(count - 1);
1480
- let g = 0;
1481
- let bitmap = 0;
1482
- for (let i = 0, len = elements.length; i < len; ++i) {
1483
- if (i !== removed) {
1484
- const elem = elements[i];
1485
- if (elem && !isEmptyNode(elem)) {
1486
- children[g++] = elem;
1487
- bitmap |= 1 << i;
1488
- }
1489
- }
1490
- }
1491
- return new IndexedNode(edit, bitmap, children);
1492
- }
1493
- function expand(edit, frag, child, bitmap, subNodes) {
1494
- const arr = [];
1495
- let bit = bitmap;
1496
- let count = 0;
1497
- for (let i = 0; bit; ++i) {
1498
- if (bit & 1) arr[i] = subNodes[count++];
1499
- bit >>>= 1;
1500
- }
1501
- arr[frag] = child;
1502
- return new ArrayNode(edit, count + 1, arr);
1503
- }
1504
- function mergeLeavesInner(edit, shift, h1, n1, h2, n2) {
1505
- if (h1 === h2) return new CollisionNode(edit, h1, [n2, n1]);
1506
- const subH1 = hashFragment(shift, h1);
1507
- const subH2 = hashFragment(shift, h2);
1508
- if (subH1 === subH2) {
1509
- return (child) => new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child]);
1510
- } else {
1511
- const children = subH1 < subH2 ? [n1, n2] : [n2, n1];
1512
- return new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), children);
1513
- }
1514
- }
1515
- function mergeLeaves(edit, shift, h1, n1, h2, n2) {
1516
- let stack = void 0;
1517
- let currentShift = shift;
1518
- while (true) {
1519
- const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2);
1520
- if (typeof res === "function") {
1521
- stack = make5(res, stack);
1522
- currentShift = currentShift + SIZE;
1523
- } else {
1524
- let final = res;
1525
- while (stack != null) {
1526
- final = stack.value(final);
1527
- stack = stack.previous;
1528
- }
1529
- return final;
1530
- }
1531
- }
1532
- }
1533
-
1534
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/hashMap.js
1535
- var HashMapSymbolKey = "effect/HashMap";
1536
- var HashMapTypeId = /* @__PURE__ */ Symbol.for(HashMapSymbolKey);
1537
- var HashMapProto = {
1538
- [HashMapTypeId]: HashMapTypeId,
1539
- [Symbol.iterator]() {
1540
- return new HashMapIterator(this, (k, v) => [k, v]);
1541
- },
1542
- [symbol]() {
1543
- let hash2 = hash(HashMapSymbolKey);
1544
- for (const item of this) {
1545
- hash2 ^= pipe(hash(item[0]), combine(hash(item[1])));
1546
- }
1547
- return cached(this, hash2);
1548
- },
1549
- [symbol2](that) {
1550
- if (isHashMap(that)) {
1551
- if (that._size !== this._size) {
1552
- return false;
1553
- }
1554
- for (const item of this) {
1555
- const elem = pipe(that, getHash(item[0], hash(item[0])));
1556
- if (isNone2(elem)) {
1557
- return false;
1558
- } else {
1559
- if (!equals(item[1], elem.value)) {
1560
- return false;
1561
- }
1562
- }
1563
- }
1564
- return true;
1565
- }
1566
- return false;
1567
- },
1568
- toString() {
1569
- return format(this.toJSON());
1570
- },
1571
- toJSON() {
1572
- return {
1573
- _id: "HashMap",
1574
- values: Array.from(this).map(toJSON)
1575
- };
1576
- },
1577
- [NodeInspectSymbol]() {
1578
- return this.toJSON();
1579
- },
1580
- pipe() {
1581
- return pipeArguments(this, arguments);
1582
- }
1583
- };
1584
- var makeImpl = (editable, edit, root, size4) => {
1585
- const map7 = Object.create(HashMapProto);
1586
- map7._editable = editable;
1587
- map7._edit = edit;
1588
- map7._root = root;
1589
- map7._size = size4;
1590
- return map7;
1591
- };
1592
- var HashMapIterator = class _HashMapIterator {
1593
- map;
1594
- f;
1595
- v;
1596
- constructor(map7, f) {
1597
- this.map = map7;
1598
- this.f = f;
1599
- this.v = visitLazy(this.map._root, this.f, void 0);
1600
- }
1601
- next() {
1602
- if (isNone2(this.v)) {
1603
- return {
1604
- done: true,
1605
- value: void 0
1606
- };
1607
- }
1608
- const v0 = this.v.value;
1609
- this.v = applyCont(v0.cont);
1610
- return {
1611
- done: false,
1612
- value: v0.value
1613
- };
1614
- }
1615
- [Symbol.iterator]() {
1616
- return new _HashMapIterator(this.map, this.f);
1617
- }
1618
- };
1619
- var applyCont = (cont) => cont ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4]) : none2();
1620
- var visitLazy = (node, f, cont = void 0) => {
1621
- switch (node._tag) {
1622
- case "LeafNode": {
1623
- if (isSome2(node.value)) {
1624
- return some2({
1625
- value: f(node.key, node.value.value),
1626
- cont
1627
- });
1628
- }
1629
- return applyCont(cont);
1630
- }
1631
- case "CollisionNode":
1632
- case "ArrayNode":
1633
- case "IndexedNode": {
1634
- const children = node.children;
1635
- return visitLazyChildren(children.length, children, 0, f, cont);
1636
- }
1637
- default: {
1638
- return applyCont(cont);
1639
- }
1640
- }
1641
- };
1642
- var visitLazyChildren = (len, children, i, f, cont) => {
1643
- while (i < len) {
1644
- const child = children[i++];
1645
- if (child && !isEmptyNode(child)) {
1646
- return visitLazy(child, f, [len, children, i, f, cont]);
1647
- }
1648
- }
1649
- return applyCont(cont);
1650
- };
1651
- var _empty2 = /* @__PURE__ */ makeImpl(false, 0, /* @__PURE__ */ new EmptyNode(), 0);
1652
- var empty3 = () => _empty2;
1653
- var isHashMap = (u) => hasProperty(u, HashMapTypeId);
1654
- var getHash = /* @__PURE__ */ dual(3, (self, key, hash2) => {
1655
- let node = self._root;
1656
- let shift = 0;
1657
- while (true) {
1658
- switch (node._tag) {
1659
- case "LeafNode": {
1660
- return equals(key, node.key) ? node.value : none2();
1661
- }
1662
- case "CollisionNode": {
1663
- if (hash2 === node.hash) {
1664
- const children = node.children;
1665
- for (let i = 0, len = children.length; i < len; ++i) {
1666
- const child = children[i];
1667
- if ("key" in child && equals(key, child.key)) {
1668
- return child.value;
1669
- }
1670
- }
1671
- }
1672
- return none2();
1673
- }
1674
- case "IndexedNode": {
1675
- const frag = hashFragment(shift, hash2);
1676
- const bit = toBitmap(frag);
1677
- if (node.mask & bit) {
1678
- node = node.children[fromBitmap(node.mask, bit)];
1679
- shift += SIZE;
1680
- break;
1681
- }
1682
- return none2();
1683
- }
1684
- case "ArrayNode": {
1685
- node = node.children[hashFragment(shift, hash2)];
1686
- if (node) {
1687
- shift += SIZE;
1688
- break;
1689
- }
1690
- return none2();
1691
- }
1692
- default:
1693
- return none2();
1694
- }
1695
- }
1696
- });
1697
- var set = /* @__PURE__ */ dual(3, (self, key, value) => modifyAt(self, key, () => some2(value)));
1698
- var setTree = /* @__PURE__ */ dual(3, (self, newRoot, newSize) => {
1699
- if (self._editable) {
1700
- ;
1701
- self._root = newRoot;
1702
- self._size = newSize;
1703
- return self;
1704
- }
1705
- return newRoot === self._root ? self : makeImpl(self._editable, self._edit, newRoot, newSize);
1706
- });
1707
- var keys = (self) => new HashMapIterator(self, (key) => key);
1708
- var size = (self) => self._size;
1709
- var beginMutation = (self) => makeImpl(true, self._edit + 1, self._root, self._size);
1710
- var modifyAt = /* @__PURE__ */ dual(3, (self, key, f) => modifyHash(self, key, hash(key), f));
1711
- var modifyHash = /* @__PURE__ */ dual(4, (self, key, hash2, f) => {
1712
- const size4 = {
1713
- value: self._size
1714
- };
1715
- const newRoot = self._root.modify(self._editable ? self._edit : NaN, 0, f, hash2, key, size4);
1716
- return pipe(self, setTree(newRoot, size4.value));
1717
- });
1718
- var forEach = /* @__PURE__ */ dual(2, (self, f) => reduce2(self, void 0, (_, value, key) => f(value, key)));
1719
- var reduce2 = /* @__PURE__ */ dual(3, (self, zero, f) => {
1720
- const root = self._root;
1721
- if (root._tag === "LeafNode") {
1722
- return isSome2(root.value) ? f(zero, root.value.value, root.key) : zero;
1723
- }
1724
- if (root._tag === "EmptyNode") {
1725
- return zero;
1726
- }
1727
- const toVisit = [root.children];
1728
- let children;
1729
- while (children = toVisit.pop()) {
1730
- for (let i = 0, len = children.length; i < len; ) {
1731
- const child = children[i++];
1732
- if (child && !isEmptyNode(child)) {
1733
- if (child._tag === "LeafNode") {
1734
- if (isSome2(child.value)) {
1735
- zero = f(zero, child.value.value, child.key);
1736
- }
1737
- } else {
1738
- toVisit.push(child.children);
1739
- }
1740
- }
1741
- }
1742
- }
1743
- return zero;
1744
- });
1745
-
1746
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/hashSet.js
1747
- var HashSetSymbolKey = "effect/HashSet";
1748
- var HashSetTypeId = /* @__PURE__ */ Symbol.for(HashSetSymbolKey);
1749
- var HashSetProto = {
1750
- [HashSetTypeId]: HashSetTypeId,
1751
- [Symbol.iterator]() {
1752
- return keys(this._keyMap);
1753
- },
1754
- [symbol]() {
1755
- return cached(this, combine(hash(this._keyMap))(hash(HashSetSymbolKey)));
1756
- },
1757
- [symbol2](that) {
1758
- if (isHashSet(that)) {
1759
- return size(this._keyMap) === size(that._keyMap) && equals(this._keyMap, that._keyMap);
1760
- }
1761
- return false;
1762
- },
1763
- toString() {
1764
- return format(this.toJSON());
1765
- },
1766
- toJSON() {
1767
- return {
1768
- _id: "HashSet",
1769
- values: Array.from(this).map(toJSON)
1770
- };
1771
- },
1772
- [NodeInspectSymbol]() {
1773
- return this.toJSON();
1774
- },
1775
- pipe() {
1776
- return pipeArguments(this, arguments);
1777
- }
1778
- };
1779
- var makeImpl2 = (keyMap) => {
1780
- const set2 = Object.create(HashSetProto);
1781
- set2._keyMap = keyMap;
1782
- return set2;
1783
- };
1784
- var isHashSet = (u) => hasProperty(u, HashSetTypeId);
1785
- var _empty3 = /* @__PURE__ */ makeImpl2(/* @__PURE__ */ empty3());
1786
- var empty4 = () => _empty3;
1787
- var size2 = (self) => size(self._keyMap);
1788
- var beginMutation2 = (self) => makeImpl2(beginMutation(self._keyMap));
1789
- var endMutation = (self) => {
1790
- ;
1791
- self._keyMap._editable = false;
1792
- return self;
1793
- };
1794
- var mutate = /* @__PURE__ */ dual(2, (self, f) => {
1795
- const transient = beginMutation2(self);
1796
- f(transient);
1797
- return endMutation(transient);
1798
- });
1799
- var add3 = /* @__PURE__ */ dual(2, (self, value) => self._keyMap._editable ? (set(value, true)(self._keyMap), self) : makeImpl2(set(value, true)(self._keyMap)));
1800
- var union2 = /* @__PURE__ */ dual(2, (self, that) => mutate(empty4(), (set2) => {
1801
- forEach2(self, (value) => add3(set2, value));
1802
- for (const value of that) {
1803
- add3(set2, value);
1804
- }
1805
- }));
1806
- var forEach2 = /* @__PURE__ */ dual(2, (self, f) => forEach(self._keyMap, (_, k) => f(k)));
1807
-
1808
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/HashSet.js
1809
- var empty5 = empty4;
1810
- var size3 = size2;
1811
- var add4 = add3;
1812
- var union3 = union2;
1813
-
1814
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/data.js
1815
- var ArrayProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(Array.prototype), {
1816
- [symbol]() {
1817
- return cached(this, array(this));
1818
- },
1819
- [symbol2](that) {
1820
- if (Array.isArray(that) && this.length === that.length) {
1821
- return this.every((v, i) => equals(v, that[i]));
1822
- } else {
1823
- return false;
1824
- }
1825
- }
1826
- });
1827
- var Structural = /* @__PURE__ */ function() {
1828
- function Structural2(args2) {
1829
- if (args2) {
1830
- Object.assign(this, args2);
1831
- }
1832
- }
1833
- Structural2.prototype = StructuralPrototype;
1834
- return Structural2;
1835
- }();
1836
-
1837
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/opCodes/cause.js
1838
- var OP_DIE = "Die";
1839
- var OP_EMPTY = "Empty";
1840
- var OP_FAIL = "Fail";
1841
- var OP_INTERRUPT = "Interrupt";
1842
- var OP_PARALLEL = "Parallel";
1843
- var OP_SEQUENTIAL = "Sequential";
1844
-
1845
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/cause.js
1846
- var CauseSymbolKey = "effect/Cause";
1847
- var CauseTypeId = /* @__PURE__ */ Symbol.for(CauseSymbolKey);
1848
- var variance = {
1849
- /* c8 ignore next */
1850
- _E: (_) => _
1851
- };
1852
- var proto = {
1853
- [CauseTypeId]: variance,
1854
- [symbol]() {
1855
- return pipe(hash(CauseSymbolKey), combine(hash(flattenCause(this))), cached(this));
1856
- },
1857
- [symbol2](that) {
1858
- return isCause(that) && causeEquals(this, that);
1859
- },
1860
- pipe() {
1861
- return pipeArguments(this, arguments);
1862
- },
1863
- toJSON() {
1864
- switch (this._tag) {
1865
- case "Empty":
1866
- return {
1867
- _id: "Cause",
1868
- _tag: this._tag
1869
- };
1870
- case "Die":
1871
- return {
1872
- _id: "Cause",
1873
- _tag: this._tag,
1874
- defect: toJSON(this.defect)
1875
- };
1876
- case "Interrupt":
1877
- return {
1878
- _id: "Cause",
1879
- _tag: this._tag,
1880
- fiberId: this.fiberId.toJSON()
1881
- };
1882
- case "Fail":
1883
- return {
1884
- _id: "Cause",
1885
- _tag: this._tag,
1886
- failure: toJSON(this.error)
1887
- };
1888
- case "Sequential":
1889
- case "Parallel":
1890
- return {
1891
- _id: "Cause",
1892
- _tag: this._tag,
1893
- left: toJSON(this.left),
1894
- right: toJSON(this.right)
1895
- };
1896
- }
1897
- },
1898
- toString() {
1899
- return pretty(this);
1900
- },
1901
- [NodeInspectSymbol]() {
1902
- return this.toJSON();
1903
- }
1904
- };
1905
- var fail = (error) => {
1906
- const o = Object.create(proto);
1907
- o._tag = OP_FAIL;
1908
- o.error = error;
1909
- return o;
1910
- };
1911
- var parallel = (left3, right3) => {
1912
- const o = Object.create(proto);
1913
- o._tag = OP_PARALLEL;
1914
- o.left = left3;
1915
- o.right = right3;
1916
- return o;
1917
- };
1918
- var sequential = (left3, right3) => {
1919
- const o = Object.create(proto);
1920
- o._tag = OP_SEQUENTIAL;
1921
- o.left = left3;
1922
- o.right = right3;
1923
- return o;
1924
- };
1925
- var isCause = (u) => hasProperty(u, CauseTypeId);
1926
- var isInterruptedOnly = (self) => reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self);
1927
- var causeEquals = (left3, right3) => {
1928
- let leftStack = of(left3);
1929
- let rightStack = of(right3);
1930
- while (isNonEmpty(leftStack) && isNonEmpty(rightStack)) {
1931
- const [leftParallel, leftSequential] = pipe(headNonEmpty(leftStack), reduce4([empty5(), empty()], ([parallel2, sequential2], cause) => {
1932
- const [par, seq] = evaluateCause(cause);
1933
- return some2([pipe(parallel2, union3(par)), pipe(sequential2, appendAll(seq))]);
1934
- }));
1935
- const [rightParallel, rightSequential] = pipe(headNonEmpty(rightStack), reduce4([empty5(), empty()], ([parallel2, sequential2], cause) => {
1936
- const [par, seq] = evaluateCause(cause);
1937
- return some2([pipe(parallel2, union3(par)), pipe(sequential2, appendAll(seq))]);
1938
- }));
1939
- if (!equals(leftParallel, rightParallel)) {
1940
- return false;
1941
- }
1942
- leftStack = leftSequential;
1943
- rightStack = rightSequential;
1944
- }
1945
- return true;
1946
- };
1947
- var flattenCause = (cause) => {
1948
- return flattenCauseLoop(of(cause), empty());
1949
- };
1950
- var flattenCauseLoop = (causes, flattened) => {
1951
- while (1) {
1952
- const [parallel2, sequential2] = pipe(causes, reduce([empty5(), empty()], ([parallel3, sequential3], cause) => {
1953
- const [par, seq] = evaluateCause(cause);
1954
- return [pipe(parallel3, union3(par)), pipe(sequential3, appendAll(seq))];
1955
- }));
1956
- const updated = size3(parallel2) > 0 ? pipe(flattened, prepend(parallel2)) : flattened;
1957
- if (isEmpty(sequential2)) {
1958
- return reverse2(updated);
1959
- }
1960
- causes = sequential2;
1961
- flattened = updated;
1962
- }
1963
- throw new Error(getBugErrorMessage("Cause.flattenCauseLoop"));
1964
- };
1965
- var evaluateCause = (self) => {
1966
- let cause = self;
1967
- const stack = [];
1968
- let _parallel = empty5();
1969
- let _sequential = empty();
1970
- while (cause !== void 0) {
1971
- switch (cause._tag) {
1972
- case OP_EMPTY: {
1973
- if (stack.length === 0) {
1974
- return [_parallel, _sequential];
1975
- }
1976
- cause = stack.pop();
1977
- break;
1978
- }
1979
- case OP_FAIL: {
1980
- _parallel = add4(_parallel, make2(cause._tag, cause.error));
1981
- if (stack.length === 0) {
1982
- return [_parallel, _sequential];
1983
- }
1984
- cause = stack.pop();
1985
- break;
1986
- }
1987
- case OP_DIE: {
1988
- _parallel = add4(_parallel, make2(cause._tag, cause.defect));
1989
- if (stack.length === 0) {
1990
- return [_parallel, _sequential];
1991
- }
1992
- cause = stack.pop();
1993
- break;
1994
- }
1995
- case OP_INTERRUPT: {
1996
- _parallel = add4(_parallel, make2(cause._tag, cause.fiberId));
1997
- if (stack.length === 0) {
1998
- return [_parallel, _sequential];
1999
- }
2000
- cause = stack.pop();
2001
- break;
2002
- }
2003
- case OP_SEQUENTIAL: {
2004
- switch (cause.left._tag) {
2005
- case OP_EMPTY: {
2006
- cause = cause.right;
2007
- break;
2008
- }
2009
- case OP_SEQUENTIAL: {
2010
- cause = sequential(cause.left.left, sequential(cause.left.right, cause.right));
2011
- break;
2012
- }
2013
- case OP_PARALLEL: {
2014
- cause = parallel(sequential(cause.left.left, cause.right), sequential(cause.left.right, cause.right));
2015
- break;
2016
- }
2017
- default: {
2018
- _sequential = prepend(_sequential, cause.right);
2019
- cause = cause.left;
2020
- break;
2021
- }
2022
- }
2023
- break;
2024
- }
2025
- case OP_PARALLEL: {
2026
- stack.push(cause.right);
2027
- cause = cause.left;
2028
- break;
2029
- }
2030
- }
2031
- }
2032
- throw new Error(getBugErrorMessage("Cause.evaluateCauseLoop"));
2033
- };
2034
- var IsInterruptedOnlyCauseReducer = {
2035
- emptyCase: constTrue,
2036
- failCase: constFalse,
2037
- dieCase: constFalse,
2038
- interruptCase: constTrue,
2039
- sequentialCase: (_, left3, right3) => left3 && right3,
2040
- parallelCase: (_, left3, right3) => left3 && right3
2041
- };
2042
- var OP_SEQUENTIAL_CASE = "SequentialCase";
2043
- var OP_PARALLEL_CASE = "ParallelCase";
2044
- var reduce4 = /* @__PURE__ */ dual(3, (self, zero, pf) => {
2045
- let accumulator = zero;
2046
- let cause = self;
2047
- const causes = [];
2048
- while (cause !== void 0) {
2049
- const option = pf(accumulator, cause);
2050
- accumulator = isSome2(option) ? option.value : accumulator;
2051
- switch (cause._tag) {
2052
- case OP_SEQUENTIAL: {
2053
- causes.push(cause.right);
2054
- cause = cause.left;
2055
- break;
2056
- }
2057
- case OP_PARALLEL: {
2058
- causes.push(cause.right);
2059
- cause = cause.left;
2060
- break;
2061
- }
2062
- default: {
2063
- cause = void 0;
2064
- break;
2065
- }
2066
- }
2067
- if (cause === void 0 && causes.length > 0) {
2068
- cause = causes.pop();
2069
- }
2070
- }
2071
- return accumulator;
2072
- });
2073
- var reduceWithContext = /* @__PURE__ */ dual(3, (self, context, reducer) => {
2074
- const input = [self];
2075
- const output = [];
2076
- while (input.length > 0) {
2077
- const cause = input.pop();
2078
- switch (cause._tag) {
2079
- case OP_EMPTY: {
2080
- output.push(right2(reducer.emptyCase(context)));
2081
- break;
2082
- }
2083
- case OP_FAIL: {
2084
- output.push(right2(reducer.failCase(context, cause.error)));
2085
- break;
2086
- }
2087
- case OP_DIE: {
2088
- output.push(right2(reducer.dieCase(context, cause.defect)));
2089
- break;
2090
- }
2091
- case OP_INTERRUPT: {
2092
- output.push(right2(reducer.interruptCase(context, cause.fiberId)));
2093
- break;
2094
- }
2095
- case OP_SEQUENTIAL: {
2096
- input.push(cause.right);
2097
- input.push(cause.left);
2098
- output.push(left2({
2099
- _tag: OP_SEQUENTIAL_CASE
2100
- }));
2101
- break;
2102
- }
2103
- case OP_PARALLEL: {
2104
- input.push(cause.right);
2105
- input.push(cause.left);
2106
- output.push(left2({
2107
- _tag: OP_PARALLEL_CASE
2108
- }));
2109
- break;
2110
- }
2111
- }
2112
- }
2113
- const accumulator = [];
2114
- while (output.length > 0) {
2115
- const either = output.pop();
2116
- switch (either._tag) {
2117
- case "Left": {
2118
- switch (either.left._tag) {
2119
- case OP_SEQUENTIAL_CASE: {
2120
- const left3 = accumulator.pop();
2121
- const right3 = accumulator.pop();
2122
- const value = reducer.sequentialCase(context, left3, right3);
2123
- accumulator.push(value);
2124
- break;
2125
- }
2126
- case OP_PARALLEL_CASE: {
2127
- const left3 = accumulator.pop();
2128
- const right3 = accumulator.pop();
2129
- const value = reducer.parallelCase(context, left3, right3);
2130
- accumulator.push(value);
2131
- break;
2132
- }
2133
- }
2134
- break;
2135
- }
2136
- case "Right": {
2137
- accumulator.push(either.right);
2138
- break;
2139
- }
2140
- }
2141
- }
2142
- if (accumulator.length === 0) {
2143
- throw new Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");
2144
- }
2145
- return accumulator.pop();
2146
- });
2147
- var pretty = (cause, options) => {
2148
- if (isInterruptedOnly(cause)) {
2149
- return "All fibers interrupted without errors.";
2150
- }
2151
- return prettyErrors(cause).map(function(e) {
2152
- if (options?.renderErrorCause !== true || e.cause === void 0) {
2153
- return e.stack;
2154
- }
2155
- return `${e.stack} {
2156
- ${renderErrorCause(e.cause, " ")}
2157
- }`;
2158
- }).join("\n");
2159
- };
2160
- var renderErrorCause = (cause, prefix) => {
2161
- const lines = cause.stack.split("\n");
2162
- let stack = `${prefix}[cause]: ${lines[0]}`;
2163
- for (let i = 1, len = lines.length; i < len; i++) {
2164
- stack += `
2165
- ${prefix}${lines[i]}`;
2166
- }
2167
- if (cause.cause) {
2168
- stack += ` {
2169
- ${renderErrorCause(cause.cause, `${prefix} `)}
2170
- ${prefix}}`;
2171
- }
2172
- return stack;
2173
- };
2174
- var PrettyError = class _PrettyError extends globalThis.Error {
2175
- span = void 0;
2176
- constructor(originalError) {
2177
- const originalErrorIsObject = typeof originalError === "object" && originalError !== null;
2178
- const prevLimit = Error.stackTraceLimit;
2179
- Error.stackTraceLimit = 1;
2180
- super(prettyErrorMessage(originalError), originalErrorIsObject && "cause" in originalError && typeof originalError.cause !== "undefined" ? {
2181
- cause: new _PrettyError(originalError.cause)
2182
- } : void 0);
2183
- if (this.message === "") {
2184
- this.message = "An error has occurred";
2185
- }
2186
- Error.stackTraceLimit = prevLimit;
2187
- this.name = originalError instanceof Error ? originalError.name : "Error";
2188
- if (originalErrorIsObject) {
2189
- if (spanSymbol in originalError) {
2190
- this.span = originalError[spanSymbol];
2191
- }
2192
- Object.keys(originalError).forEach((key) => {
2193
- if (!(key in this)) {
2194
- this[key] = originalError[key];
2195
- }
2196
- });
2197
- }
2198
- this.stack = prettyErrorStack(`${this.name}: ${this.message}`, originalError instanceof Error && originalError.stack ? originalError.stack : "", this.span);
2199
- }
2200
- };
2201
- var prettyErrorMessage = (u) => {
2202
- if (typeof u === "string") {
2203
- return u;
2204
- }
2205
- if (typeof u === "object" && u !== null && u instanceof Error) {
2206
- return u.message;
2207
- }
2208
- try {
2209
- if (hasProperty(u, "toString") && isFunction2(u["toString"]) && u["toString"] !== Object.prototype.toString && u["toString"] !== globalThis.Array.prototype.toString) {
2210
- return u["toString"]();
2211
- }
2212
- } catch {
2213
- }
2214
- return stringifyCircular(u);
2215
- };
2216
- var locationRegex = /\((.*)\)/g;
2217
- var spanToTrace = /* @__PURE__ */ globalValue("effect/Tracer/spanToTrace", () => /* @__PURE__ */ new WeakMap());
2218
- var prettyErrorStack = (message, stack, span) => {
2219
- const out = [message];
2220
- const lines = stack.startsWith(message) ? stack.slice(message.length).split("\n") : stack.split("\n");
2221
- for (let i = 1; i < lines.length; i++) {
2222
- if (lines[i].includes(" at new BaseEffectError") || lines[i].includes(" at new YieldableError")) {
2223
- i++;
2224
- continue;
2225
- }
2226
- if (lines[i].includes("Generator.next")) {
2227
- break;
2228
- }
2229
- if (lines[i].includes("effect_internal_function")) {
2230
- break;
2231
- }
2232
- out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/, "at $1").replace(/EffectPrimitive\.\w+/, "<anonymous>"));
2233
- }
2234
- if (span) {
2235
- let current = span;
2236
- let i = 0;
2237
- while (current && current._tag === "Span" && i < 10) {
2238
- const stackFn = spanToTrace.get(current);
2239
- if (typeof stackFn === "function") {
2240
- const stack2 = stackFn();
2241
- if (typeof stack2 === "string") {
2242
- const locationMatchAll = stack2.matchAll(locationRegex);
2243
- let match2 = false;
2244
- for (const [, location] of locationMatchAll) {
2245
- match2 = true;
2246
- out.push(` at ${current.name} (${location})`);
2247
- }
2248
- if (!match2) {
2249
- out.push(` at ${current.name} (${stack2.replace(/^at /, "")})`);
2250
- }
2251
- } else {
2252
- out.push(` at ${current.name}`);
2253
- }
2254
- } else {
2255
- out.push(` at ${current.name}`);
2256
- }
2257
- current = getOrUndefined(current.parent);
2258
- i++;
2259
- }
2260
- }
2261
- return out.join("\n");
2262
- };
2263
- var spanSymbol = /* @__PURE__ */ Symbol.for("effect/SpanAnnotation");
2264
- var prettyErrors = (cause) => reduceWithContext(cause, void 0, {
2265
- emptyCase: () => [],
2266
- dieCase: (_, unknownError) => {
2267
- return [new PrettyError(unknownError)];
2268
- },
2269
- failCase: (_, error) => {
2270
- return [new PrettyError(error)];
2271
- },
2272
- interruptCase: () => [],
2273
- parallelCase: (_, l, r) => [...l, ...r],
2274
- sequentialCase: (_, l, r) => [...l, ...r]
2275
- });
2276
-
2277
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/singleShotGen.js
2278
- var SingleShotGen2 = class _SingleShotGen {
2279
- self;
2280
- called = false;
2281
- constructor(self) {
2282
- this.self = self;
2283
- }
2284
- next(a) {
2285
- return this.called ? {
2286
- value: a,
2287
- done: true
2288
- } : (this.called = true, {
2289
- value: this.self,
2290
- done: false
2291
- });
2292
- }
2293
- return(a) {
2294
- return {
2295
- value: a,
2296
- done: true
2297
- };
2298
- }
2299
- throw(e) {
2300
- throw e;
2301
- }
2302
- [Symbol.iterator]() {
2303
- return new _SingleShotGen(this.self);
2304
- }
2305
- };
2306
-
2307
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/internal/core.js
2308
- var EffectTypeId2 = /* @__PURE__ */ Symbol.for("effect/Effect");
2309
- var EffectPrimitive = class {
2310
- _op;
2311
- effect_instruction_i0 = void 0;
2312
- effect_instruction_i1 = void 0;
2313
- effect_instruction_i2 = void 0;
2314
- trace = void 0;
2315
- [EffectTypeId2] = effectVariance;
2316
- constructor(_op) {
2317
- this._op = _op;
2318
- }
2319
- [symbol2](that) {
2320
- return this === that;
2321
- }
2322
- [symbol]() {
2323
- return cached(this, random(this));
2324
- }
2325
- pipe() {
2326
- return pipeArguments(this, arguments);
2327
- }
2328
- toJSON() {
2329
- return {
2330
- _id: "Effect",
2331
- _op: this._op,
2332
- effect_instruction_i0: toJSON(this.effect_instruction_i0),
2333
- effect_instruction_i1: toJSON(this.effect_instruction_i1),
2334
- effect_instruction_i2: toJSON(this.effect_instruction_i2)
2335
- };
2336
- }
2337
- toString() {
2338
- return format(this.toJSON());
2339
- }
2340
- [NodeInspectSymbol]() {
2341
- return this.toJSON();
2342
- }
2343
- [Symbol.iterator]() {
2344
- return new SingleShotGen2(new YieldWrap(this));
2345
- }
2346
- };
2347
- var EffectPrimitiveFailure = class {
2348
- _op;
2349
- effect_instruction_i0 = void 0;
2350
- effect_instruction_i1 = void 0;
2351
- effect_instruction_i2 = void 0;
2352
- trace = void 0;
2353
- [EffectTypeId2] = effectVariance;
2354
- constructor(_op) {
2355
- this._op = _op;
2356
- this._tag = _op;
2357
- }
2358
- [symbol2](that) {
2359
- return exitIsExit(that) && that._op === "Failure" && // @ts-expect-error
2360
- equals(this.effect_instruction_i0, that.effect_instruction_i0);
2361
- }
2362
- [symbol]() {
2363
- return pipe(
2364
- // @ts-expect-error
2365
- string(this._tag),
2366
- // @ts-expect-error
2367
- combine(hash(this.effect_instruction_i0)),
2368
- cached(this)
2369
- );
2370
- }
2371
- get cause() {
2372
- return this.effect_instruction_i0;
2373
- }
2374
- pipe() {
2375
- return pipeArguments(this, arguments);
2376
- }
2377
- toJSON() {
2378
- return {
2379
- _id: "Exit",
2380
- _tag: this._op,
2381
- cause: this.cause.toJSON()
2382
- };
2383
- }
2384
- toString() {
2385
- return format(this.toJSON());
2386
- }
2387
- [NodeInspectSymbol]() {
2388
- return this.toJSON();
2389
- }
2390
- [Symbol.iterator]() {
2391
- return new SingleShotGen2(new YieldWrap(this));
2392
- }
2393
- };
2394
- var EffectPrimitiveSuccess = class {
2395
- _op;
2396
- effect_instruction_i0 = void 0;
2397
- effect_instruction_i1 = void 0;
2398
- effect_instruction_i2 = void 0;
2399
- trace = void 0;
2400
- [EffectTypeId2] = effectVariance;
2401
- constructor(_op) {
2402
- this._op = _op;
2403
- this._tag = _op;
2404
- }
2405
- [symbol2](that) {
2406
- return exitIsExit(that) && that._op === "Success" && // @ts-expect-error
2407
- equals(this.effect_instruction_i0, that.effect_instruction_i0);
2408
- }
2409
- [symbol]() {
2410
- return pipe(
2411
- // @ts-expect-error
2412
- string(this._tag),
2413
- // @ts-expect-error
2414
- combine(hash(this.effect_instruction_i0)),
2415
- cached(this)
2416
- );
2417
- }
2418
- get value() {
2419
- return this.effect_instruction_i0;
2420
- }
2421
- pipe() {
2422
- return pipeArguments(this, arguments);
2423
- }
2424
- toJSON() {
2425
- return {
2426
- _id: "Exit",
2427
- _tag: this._op,
2428
- value: toJSON(this.value)
2429
- };
2430
- }
2431
- toString() {
2432
- return format(this.toJSON());
2433
- }
2434
- [NodeInspectSymbol]() {
2435
- return this.toJSON();
2436
- }
2437
- [Symbol.iterator]() {
2438
- return new SingleShotGen2(new YieldWrap(this));
2439
- }
2440
- };
2441
- var isEffect = (u) => hasProperty(u, EffectTypeId2);
2442
- var withFiberRuntime = (withRuntime) => {
2443
- const effect = new EffectPrimitive(OP_WITH_RUNTIME);
2444
- effect.effect_instruction_i0 = withRuntime;
2445
- return effect;
2446
- };
2447
- var originalSymbol = /* @__PURE__ */ Symbol.for("effect/OriginalAnnotation");
2448
- var capture = (obj, span) => {
2449
- if (isSome2(span)) {
2450
- return new Proxy(obj, {
2451
- has(target, p) {
2452
- return p === spanSymbol || p === originalSymbol || p in target;
2453
- },
2454
- get(target, p) {
2455
- if (p === spanSymbol) {
2456
- return span.value;
2457
- }
2458
- if (p === originalSymbol) {
2459
- return obj;
2460
- }
2461
- return target[p];
2462
- }
2463
- });
2464
- }
2465
- return obj;
2466
- };
2467
- var fail2 = (error) => isObject(error) && !(spanSymbol in error) ? withFiberRuntime((fiber) => failCause(fail(capture(error, currentSpanFromFiber(fiber))))) : failCause(fail(error));
2468
- var failCause = (cause) => {
2469
- const effect = new EffectPrimitiveFailure(OP_FAILURE);
2470
- effect.effect_instruction_i0 = cause;
2471
- return effect;
2472
- };
2473
- var logLevelAll = {
2474
- _tag: "All",
2475
- syslog: 0,
2476
- label: "ALL",
2477
- ordinal: Number.MIN_SAFE_INTEGER,
2478
- pipe() {
2479
- return pipeArguments(this, arguments);
2480
- }
2481
- };
2482
- var logLevelNone = {
2483
- _tag: "None",
2484
- syslog: 7,
2485
- label: "OFF",
2486
- ordinal: Number.MAX_SAFE_INTEGER,
2487
- pipe() {
2488
- return pipeArguments(this, arguments);
2489
- }
2490
- };
2491
- var RequestResolverSymbolKey = "effect/RequestResolver";
2492
- var RequestResolverTypeId = /* @__PURE__ */ Symbol.for(RequestResolverSymbolKey);
2493
- var requestResolverVariance = {
2494
- /* c8 ignore next */
2495
- _A: (_) => _,
2496
- /* c8 ignore next */
2497
- _R: (_) => _
2498
- };
2499
- var RequestResolverImpl = class _RequestResolverImpl {
2500
- runAll;
2501
- target;
2502
- [RequestResolverTypeId] = requestResolverVariance;
2503
- constructor(runAll, target) {
2504
- this.runAll = runAll;
2505
- this.target = target;
2506
- }
2507
- [symbol]() {
2508
- return cached(this, this.target ? hash(this.target) : random(this));
2509
- }
2510
- [symbol2](that) {
2511
- return this.target ? isRequestResolver(that) && equals(this.target, that.target) : this === that;
2512
- }
2513
- identified(...ids) {
2514
- return new _RequestResolverImpl(this.runAll, fromIterable2(ids));
2515
- }
2516
- pipe() {
2517
- return pipeArguments(this, arguments);
2518
- }
2519
- };
2520
- var isRequestResolver = (u) => hasProperty(u, RequestResolverTypeId);
2521
- var YieldableError = /* @__PURE__ */ function() {
2522
- class YieldableError2 extends globalThis.Error {
2523
- commit() {
2524
- return fail2(this);
2525
- }
2526
- toJSON() {
2527
- const obj = {
2528
- ...this
2529
- };
2530
- if (this.message) obj.message = this.message;
2531
- if (this.cause) obj.cause = this.cause;
2532
- return obj;
2533
- }
2534
- [NodeInspectSymbol]() {
2535
- if (this.toString !== globalThis.Error.prototype.toString) {
2536
- return this.stack ? `${this.toString()}
2537
- ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
2538
- } else if ("Bun" in globalThis) {
2539
- return pretty(fail(this), {
2540
- renderErrorCause: true
2541
- });
2542
- }
2543
- return this;
2544
- }
2545
- }
2546
- Object.assign(YieldableError2.prototype, StructuralCommitPrototype);
2547
- return YieldableError2;
2548
- }();
2549
- var makeException = (proto2, tag) => {
2550
- class Base2 extends YieldableError {
2551
- _tag = tag;
2552
- }
2553
- Object.assign(Base2.prototype, proto2);
2554
- Base2.prototype.name = tag;
2555
- return Base2;
2556
- };
2557
- var RuntimeExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/RuntimeException");
2558
- var RuntimeException = /* @__PURE__ */ makeException({
2559
- [RuntimeExceptionTypeId]: RuntimeExceptionTypeId
2560
- }, "RuntimeException");
2561
- var InterruptedExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/InterruptedException");
2562
- var InterruptedException = /* @__PURE__ */ makeException({
2563
- [InterruptedExceptionTypeId]: InterruptedExceptionTypeId
2564
- }, "InterruptedException");
2565
- var IllegalArgumentExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/IllegalArgument");
2566
- var IllegalArgumentException = /* @__PURE__ */ makeException({
2567
- [IllegalArgumentExceptionTypeId]: IllegalArgumentExceptionTypeId
2568
- }, "IllegalArgumentException");
2569
- var NoSuchElementExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/NoSuchElement");
2570
- var NoSuchElementException = /* @__PURE__ */ makeException({
2571
- [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId
2572
- }, "NoSuchElementException");
2573
- var InvalidPubSubCapacityExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException");
2574
- var InvalidPubSubCapacityException = /* @__PURE__ */ makeException({
2575
- [InvalidPubSubCapacityExceptionTypeId]: InvalidPubSubCapacityExceptionTypeId
2576
- }, "InvalidPubSubCapacityException");
2577
- var ExceededCapacityExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/ExceededCapacityException");
2578
- var ExceededCapacityException = /* @__PURE__ */ makeException({
2579
- [ExceededCapacityExceptionTypeId]: ExceededCapacityExceptionTypeId
2580
- }, "ExceededCapacityException");
2581
- var TimeoutExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/Timeout");
2582
- var TimeoutException = /* @__PURE__ */ makeException({
2583
- [TimeoutExceptionTypeId]: TimeoutExceptionTypeId
2584
- }, "TimeoutException");
2585
- var exitIsExit = (u) => isEffect(u) && "_tag" in u && (u._tag === "Success" || u._tag === "Failure");
2586
- var currentSpanFromFiber = (fiber) => {
2587
- const span = fiber.currentSpan;
2588
- return span !== void 0 && span._tag === "Span" ? some2(span) : none2();
2589
- };
2590
-
2591
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Data.js
2592
- var Class2 = Structural;
2593
- var TaggedClass = (tag) => {
2594
- class Base2 extends Class2 {
2595
- _tag = tag;
2596
- }
2597
- return Base2;
2598
- };
2599
- var Error2 = /* @__PURE__ */ function() {
2600
- const plainArgsSymbol = /* @__PURE__ */ Symbol.for("effect/Data/Error/plainArgs");
2601
- const O = {
2602
- BaseEffectError: class extends YieldableError {
2603
- constructor(args2) {
2604
- super(args2?.message, args2?.cause ? {
2605
- cause: args2.cause
2606
- } : void 0);
2607
- if (args2) {
2608
- Object.assign(this, args2);
2609
- Object.defineProperty(this, plainArgsSymbol, {
2610
- value: args2,
2611
- enumerable: false
2612
- });
2613
- }
2614
- }
2615
- toJSON() {
2616
- return {
2617
- ...this[plainArgsSymbol],
2618
- ...this
2619
- };
2620
- }
2621
- }
2622
- };
2623
- return O.BaseEffectError;
2624
- }();
2625
- var TaggedError = (tag) => {
2626
- const O = {
2627
- BaseEffectError: class extends Error2 {
2628
- _tag = tag;
2629
- }
2630
- };
2631
- O.BaseEffectError.prototype.name = tag;
2632
- return O.BaseEffectError;
2633
- };
2634
-
2635
- // src/internal/bot-response.ts
2636
- var BotResponse = class _BotResponse extends TaggedClass("BotResponse") {
2637
- static make(result) {
2638
- return new _BotResponse({ response: result });
2639
- }
2640
- static ignore = new _BotResponse({});
2641
- };
2642
-
2643
- // src/internal/bot-context.ts
2644
- var extractCommand = (update) => {
2645
- if (typeof update !== "object" || update === null) return void 0;
2646
- const u = update;
2647
- if (!u.entities || !u.text) return void 0;
2648
- const entity = u.entities.find((e) => e.type === "bot_command");
2649
- if (!entity) return void 0;
2650
- return u.text.slice(entity.offset, entity.offset + entity.length);
2651
- };
2652
- var createBotContext = (update) => {
2653
- const command = extractCommand(update);
2654
- return {
2655
- command,
2656
- reply: (text, options) => BotResponse.make({ type: "message", text, ...options }),
2657
- replyWithDocument: (document, options) => BotResponse.make({ type: "document", document, ...options }),
2658
- replyWithPhoto: (photo, options) => BotResponse.make({ type: "photo", photo, ...options }),
2659
- ignore: BotResponse.ignore
2660
- };
2661
- };
2662
-
2663
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Effectable.js
2664
- var EffectPrototype2 = EffectPrototype;
2665
-
2666
- // ../../node_modules/.pnpm/effect@3.19.13/node_modules/effect/dist/esm/Micro.js
2667
- var TypeId5 = /* @__PURE__ */ Symbol.for("effect/Micro");
2668
- var MicroExitTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroExit");
2669
- var isMicro = (u) => typeof u === "object" && u !== null && TypeId5 in u;
2670
- var MicroCauseTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroCause");
2671
- var microCauseVariance = {
2672
- _E: identity
2673
- };
2674
- var MicroCauseImpl = class extends globalThis.Error {
2675
- _tag;
2676
- traces;
2677
- [MicroCauseTypeId];
2678
- constructor(_tag, originalError, traces) {
2679
- const causeName = `MicroCause.${_tag}`;
2680
- let name;
2681
- let message;
2682
- let stack;
2683
- if (originalError instanceof globalThis.Error) {
2684
- name = `(${causeName}) ${originalError.name}`;
2685
- message = originalError.message;
2686
- const messageLines = message.split("\n").length;
2687
- stack = originalError.stack ? `(${causeName}) ${originalError.stack.split("\n").slice(0, messageLines + 3).join("\n")}` : `${name}: ${message}`;
2688
- } else {
2689
- name = causeName;
2690
- message = toStringUnknown(originalError, 0);
2691
- stack = `${name}: ${message}`;
2692
- }
2693
- if (traces.length > 0) {
2694
- stack += `
2695
- ${traces.join("\n ")}`;
2696
- }
2697
- super(message);
2698
- this._tag = _tag;
2699
- this.traces = traces;
2700
- this[MicroCauseTypeId] = microCauseVariance;
2701
- this.name = name;
2702
- this.stack = stack;
2703
- }
2704
- pipe() {
2705
- return pipeArguments(this, arguments);
2706
- }
2707
- toString() {
2708
- return this.stack;
2709
- }
2710
- [NodeInspectSymbol]() {
2711
- return this.stack;
2712
- }
2713
- };
2714
- var Fail = class extends MicroCauseImpl {
2715
- error;
2716
- constructor(error, traces = []) {
2717
- super("Fail", error, traces);
2718
- this.error = error;
2719
- }
2720
- };
2721
- var causeFail = (error, traces = []) => new Fail(error, traces);
2722
- var Die = class extends MicroCauseImpl {
2723
- defect;
2724
- constructor(defect, traces = []) {
2725
- super("Die", defect, traces);
2726
- this.defect = defect;
2727
- }
2728
- };
2729
- var causeDie = (defect, traces = []) => new Die(defect, traces);
2730
- var Interrupt = class extends MicroCauseImpl {
2731
- constructor(traces = []) {
2732
- super("Interrupt", "interrupted", traces);
2733
- }
2734
- };
2735
- var causeInterrupt = (traces = []) => new Interrupt(traces);
2736
- var causeIsFail = (self) => self._tag === "Fail";
2737
- var causeIsInterrupt = (self) => self._tag === "Interrupt";
2738
- var MicroFiberTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroFiber");
2739
- var fiberVariance = {
2740
- _A: identity,
2741
- _E: identity
2742
- };
2743
- var MicroFiberImpl = class {
2744
- context;
2745
- interruptible;
2746
- [MicroFiberTypeId];
2747
- _stack = [];
2748
- _observers = [];
2749
- _exit;
2750
- _children;
2751
- currentOpCount = 0;
2752
- constructor(context, interruptible2 = true) {
2753
- this.context = context;
2754
- this.interruptible = interruptible2;
2755
- this[MicroFiberTypeId] = fiberVariance;
2756
- }
2757
- getRef(ref) {
2758
- return unsafeGetReference(this.context, ref);
2759
- }
2760
- addObserver(cb) {
2761
- if (this._exit) {
2762
- cb(this._exit);
2763
- return constVoid;
2764
- }
2765
- this._observers.push(cb);
2766
- return () => {
2767
- const index = this._observers.indexOf(cb);
2768
- if (index >= 0) {
2769
- this._observers.splice(index, 1);
2770
- }
2771
- };
2772
- }
2773
- _interrupted = false;
2774
- unsafeInterrupt() {
2775
- if (this._exit) {
2776
- return;
2777
- }
2778
- this._interrupted = true;
2779
- if (this.interruptible) {
2780
- this.evaluate(exitInterrupt);
2781
- }
2782
- }
2783
- unsafePoll() {
2784
- return this._exit;
2785
- }
2786
- evaluate(effect) {
2787
- if (this._exit) {
2788
- return;
2789
- } else if (this._yielded !== void 0) {
2790
- const yielded = this._yielded;
2791
- this._yielded = void 0;
2792
- yielded();
2793
- }
2794
- const exit2 = this.runLoop(effect);
2795
- if (exit2 === Yield) {
2796
- return;
2797
- }
2798
- const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this);
2799
- if (interruptChildren !== void 0) {
2800
- return this.evaluate(flatMap3(interruptChildren, () => exit2));
2801
- }
2802
- this._exit = exit2;
2803
- for (let i = 0; i < this._observers.length; i++) {
2804
- this._observers[i](exit2);
2805
- }
2806
- this._observers.length = 0;
2807
- }
2808
- runLoop(effect) {
2809
- let yielding = false;
2810
- let current = effect;
2811
- this.currentOpCount = 0;
2812
- try {
2813
- while (true) {
2814
- this.currentOpCount++;
2815
- if (!yielding && this.getRef(CurrentScheduler).shouldYield(this)) {
2816
- yielding = true;
2817
- const prev = current;
2818
- current = flatMap3(yieldNow, () => prev);
2819
- }
2820
- current = current[evaluate](this);
2821
- if (current === Yield) {
2822
- const yielded = this._yielded;
2823
- if (MicroExitTypeId in yielded) {
2824
- this._yielded = void 0;
2825
- return yielded;
2826
- }
2827
- return Yield;
2828
- }
2829
- }
2830
- } catch (error) {
2831
- if (!hasProperty(current, evaluate)) {
2832
- return exitDie(`MicroFiber.runLoop: Not a valid effect: ${String(current)}`);
2833
- }
2834
- return exitDie(error);
2835
- }
2836
- }
2837
- getCont(symbol3) {
2838
- while (true) {
2839
- const op = this._stack.pop();
2840
- if (!op) return void 0;
2841
- const cont = op[ensureCont] && op[ensureCont](this);
2842
- if (cont) return {
2843
- [symbol3]: cont
2844
- };
2845
- if (op[symbol3]) return op;
2846
- }
2847
- }
2848
- // cancel the yielded operation, or for the yielded exit value
2849
- _yielded = void 0;
2850
- yieldWith(value) {
2851
- this._yielded = value;
2852
- return Yield;
2853
- }
2854
- children() {
2855
- return this._children ??= /* @__PURE__ */ new Set();
2856
- }
2857
- };
2858
- var fiberMiddleware = /* @__PURE__ */ globalValue("effect/Micro/fiberMiddleware", () => ({
2859
- interruptChildren: void 0
2860
- }));
2861
- var fiberAwait = (self) => async((resume) => sync(self.addObserver((exit2) => resume(succeed(exit2)))));
2862
- var fiberInterrupt = (self) => suspend(() => {
2863
- self.unsafeInterrupt();
2864
- return asVoid(fiberAwait(self));
2865
- });
2866
- var fiberInterruptAll = (fibers) => suspend(() => {
2867
- for (const fiber of fibers) fiber.unsafeInterrupt();
2868
- const iter = fibers[Symbol.iterator]();
2869
- const wait = suspend(() => {
2870
- let result = iter.next();
2871
- while (!result.done) {
2872
- if (result.value.unsafePoll()) {
2873
- result = iter.next();
2874
- continue;
2875
- }
2876
- const fiber = result.value;
2877
- return async((resume) => {
2878
- fiber.addObserver((_) => {
2879
- resume(wait);
2880
- });
2881
- });
2882
- }
2883
- return exitVoid;
2884
- });
2885
- return wait;
2886
- });
2887
- var identifier = /* @__PURE__ */ Symbol.for("effect/Micro/identifier");
2888
- var args = /* @__PURE__ */ Symbol.for("effect/Micro/args");
2889
- var evaluate = /* @__PURE__ */ Symbol.for("effect/Micro/evaluate");
2890
- var successCont = /* @__PURE__ */ Symbol.for("effect/Micro/successCont");
2891
- var failureCont = /* @__PURE__ */ Symbol.for("effect/Micro/failureCont");
2892
- var ensureCont = /* @__PURE__ */ Symbol.for("effect/Micro/ensureCont");
2893
- var Yield = /* @__PURE__ */ Symbol.for("effect/Micro/Yield");
2894
- var microVariance = {
2895
- _A: identity,
2896
- _E: identity,
2897
- _R: identity
2898
- };
2899
- var MicroProto = {
2900
- ...EffectPrototype2,
2901
- _op: "Micro",
2902
- [TypeId5]: microVariance,
2903
- pipe() {
2904
- return pipeArguments(this, arguments);
2905
- },
2906
- [Symbol.iterator]() {
2907
- return new SingleShotGen(new YieldWrap(this));
2908
- },
2909
- toJSON() {
2910
- return {
2911
- _id: "Micro",
2912
- op: this[identifier],
2913
- ...args in this ? {
2914
- args: this[args]
2915
- } : void 0
2916
- };
2917
- },
2918
- toString() {
2919
- return format(this);
2920
- },
2921
- [NodeInspectSymbol]() {
2922
- return format(this);
2923
- }
2924
- };
2925
- function defaultEvaluate(_fiber) {
2926
- return exitDie(`Micro.evaluate: Not implemented`);
2927
- }
2928
- var makePrimitiveProto = (options) => ({
2929
- ...MicroProto,
2930
- [identifier]: options.op,
2931
- [evaluate]: options.eval ?? defaultEvaluate,
2932
- [successCont]: options.contA,
2933
- [failureCont]: options.contE,
2934
- [ensureCont]: options.ensure
2935
- });
2936
- var makePrimitive = (options) => {
2937
- const Proto = makePrimitiveProto(options);
2938
- return function() {
2939
- const self = Object.create(Proto);
2940
- self[args] = options.single === false ? arguments : arguments[0];
2941
- return self;
2942
- };
2943
- };
2944
- var makeExit = (options) => {
2945
- const Proto = {
2946
- ...makePrimitiveProto(options),
2947
- [MicroExitTypeId]: MicroExitTypeId,
2948
- _tag: options.op,
2949
- get [options.prop]() {
2950
- return this[args];
2951
- },
2952
- toJSON() {
2953
- return {
2954
- _id: "MicroExit",
2955
- _tag: options.op,
2956
- [options.prop]: this[args]
2957
- };
2958
- },
2959
- [symbol2](that) {
2960
- return isMicroExit(that) && that._tag === options.op && equals(this[args], that[args]);
2961
- },
2962
- [symbol]() {
2963
- return cached(this, combine(string(options.op))(hash(this[args])));
2964
- }
2965
- };
2966
- return function(value) {
2967
- const self = Object.create(Proto);
2968
- self[args] = value;
2969
- self[successCont] = void 0;
2970
- self[failureCont] = void 0;
2971
- self[ensureCont] = void 0;
2972
- return self;
2973
- };
2974
- };
2975
- var succeed = /* @__PURE__ */ makeExit({
2976
- op: "Success",
2977
- prop: "value",
2978
- eval(fiber) {
2979
- const cont = fiber.getCont(successCont);
2980
- return cont ? cont[successCont](this[args], fiber) : fiber.yieldWith(this);
2981
- }
2982
- });
2983
- var failCause2 = /* @__PURE__ */ makeExit({
2984
- op: "Failure",
2985
- prop: "cause",
2986
- eval(fiber) {
2987
- let cont = fiber.getCont(failureCont);
2988
- while (causeIsInterrupt(this[args]) && cont && fiber.interruptible) {
2989
- cont = fiber.getCont(failureCont);
2990
- }
2991
- return cont ? cont[failureCont](this[args], fiber) : fiber.yieldWith(this);
2992
- }
2993
- });
2994
- var fail3 = (error) => failCause2(causeFail(error));
2995
- var sync = /* @__PURE__ */ makePrimitive({
2996
- op: "Sync",
2997
- eval(fiber) {
2998
- const value = this[args]();
2999
- const cont = fiber.getCont(successCont);
3000
- return cont ? cont[successCont](value, fiber) : fiber.yieldWith(exitSucceed(value));
3001
- }
3002
- });
3003
- var suspend = /* @__PURE__ */ makePrimitive({
3004
- op: "Suspend",
3005
- eval(_fiber) {
3006
- return this[args]();
3007
- }
3008
- });
3009
- var yieldNowWith = /* @__PURE__ */ makePrimitive({
3010
- op: "Yield",
3011
- eval(fiber) {
3012
- let resumed = false;
3013
- fiber.getRef(CurrentScheduler).scheduleTask(() => {
3014
- if (resumed) return;
3015
- fiber.evaluate(exitVoid);
3016
- }, this[args] ?? 0);
3017
- return fiber.yieldWith(() => {
3018
- resumed = true;
3019
- });
3020
- }
3021
- });
3022
- var yieldNow = /* @__PURE__ */ yieldNowWith(0);
3023
- var void_ = /* @__PURE__ */ succeed(void 0);
3024
- var try_ = (options) => suspend(() => {
3025
- try {
3026
- return succeed(options.try());
3027
- } catch (err) {
3028
- return fail3(options.catch(err));
3029
- }
3030
- });
3031
- var tryPromise = (options) => asyncOptions(function(resume, signal) {
3032
- try {
3033
- options.try(signal).then((a) => resume(succeed(a)), (e) => resume(fail3(options.catch(e))));
3034
- } catch (err) {
3035
- resume(fail3(options.catch(err)));
3036
- }
3037
- }, options.try.length !== 0);
3038
- var withMicroFiber = /* @__PURE__ */ makePrimitive({
3039
- op: "WithMicroFiber",
3040
- eval(fiber) {
3041
- return this[args](fiber);
3042
- }
3043
- });
3044
- var asyncOptions = /* @__PURE__ */ makePrimitive({
3045
- op: "Async",
3046
- single: false,
3047
- eval(fiber) {
3048
- const register = this[args][0];
3049
- let resumed = false;
3050
- let yielded = false;
3051
- const controller = this[args][1] ? new AbortController() : void 0;
3052
- const onCancel = register((effect) => {
3053
- if (resumed) return;
3054
- resumed = true;
3055
- if (yielded) {
3056
- fiber.evaluate(effect);
3057
- } else {
3058
- yielded = effect;
3059
- }
3060
- }, controller?.signal);
3061
- if (yielded !== false) return yielded;
3062
- yielded = true;
3063
- fiber._yielded = () => {
3064
- resumed = true;
3065
- };
3066
- if (controller === void 0 && onCancel === void 0) {
3067
- return Yield;
3068
- }
3069
- fiber._stack.push(asyncFinalizer(() => {
3070
- resumed = true;
3071
- controller?.abort();
3072
- return onCancel ?? exitVoid;
3073
- }));
3074
- return Yield;
3075
- }
3076
- });
3077
- var asyncFinalizer = /* @__PURE__ */ makePrimitive({
3078
- op: "AsyncFinalizer",
3079
- ensure(fiber) {
3080
- if (fiber.interruptible) {
3081
- fiber.interruptible = false;
3082
- fiber._stack.push(setInterruptible(true));
3083
- }
3084
- },
3085
- contE(cause, _fiber) {
3086
- return causeIsInterrupt(cause) ? flatMap3(this[args](), () => failCause2(cause)) : failCause2(cause);
3087
- }
3088
- });
3089
- var async = (register) => asyncOptions(register, register.length >= 2);
3090
- var gen = (...args2) => suspend(() => fromIterator(args2.length === 1 ? args2[0]() : args2[1].call(args2[0])));
3091
- var fromIterator = /* @__PURE__ */ makePrimitive({
3092
- op: "Iterator",
3093
- contA(value, fiber) {
3094
- const state = this[args].next(value);
3095
- if (state.done) return succeed(state.value);
3096
- fiber._stack.push(this);
3097
- return yieldWrapGet(state.value);
3098
- },
3099
- eval(fiber) {
3100
- return this[successCont](void 0, fiber);
3101
- }
3102
- });
3103
- var as = /* @__PURE__ */ dual(2, (self, value) => map6(self, (_) => value));
3104
- var andThen = /* @__PURE__ */ dual(2, (self, f) => flatMap3(self, (a) => {
3105
- const value = isMicro(f) ? f : typeof f === "function" ? f(a) : f;
3106
- return isMicro(value) ? value : succeed(value);
3107
- }));
3108
- var tap = /* @__PURE__ */ dual(2, (self, f) => flatMap3(self, (a) => {
3109
- const value = isMicro(f) ? f : typeof f === "function" ? f(a) : f;
3110
- return isMicro(value) ? as(value, a) : succeed(a);
3111
- }));
3112
- var asVoid = (self) => flatMap3(self, (_) => exitVoid);
3113
- var exit = (self) => matchCause(self, {
3114
- onFailure: exitFailCause,
3115
- onSuccess: exitSucceed
3116
- });
3117
- var flatMap3 = /* @__PURE__ */ dual(2, (self, f) => {
3118
- const onSuccess = Object.create(OnSuccessProto);
3119
- onSuccess[args] = self;
3120
- onSuccess[successCont] = f;
3121
- return onSuccess;
3122
- });
3123
- var OnSuccessProto = /* @__PURE__ */ makePrimitiveProto({
3124
- op: "OnSuccess",
3125
- eval(fiber) {
3126
- fiber._stack.push(this);
3127
- return this[args];
3128
- }
3129
- });
3130
- var map6 = /* @__PURE__ */ dual(2, (self, f) => flatMap3(self, (a) => succeed(f(a))));
3131
- var isMicroExit = (u) => hasProperty(u, MicroExitTypeId);
3132
- var exitSucceed = succeed;
3133
- var exitFailCause = failCause2;
3134
- var exitInterrupt = /* @__PURE__ */ exitFailCause(/* @__PURE__ */ causeInterrupt());
3135
- var exitDie = (defect) => exitFailCause(causeDie(defect));
3136
- var exitVoid = /* @__PURE__ */ exitSucceed(void 0);
3137
- var exitVoidAll = (exits) => {
3138
- for (const exit2 of exits) {
3139
- if (exit2._tag === "Failure") {
3140
- return exit2;
3141
- }
1
+ // src/types.ts
2
+ var BotResponse = class _BotResponse {
3
+ response;
4
+ constructor(response) {
5
+ this.response = response;
3142
6
  }
3143
- return exitVoid;
3144
- };
3145
- var setImmediate = "setImmediate" in globalThis ? globalThis.setImmediate : (f) => setTimeout(f, 0);
3146
- var MicroSchedulerDefault = class {
3147
- tasks = [];
3148
- running = false;
3149
- /**
3150
- * @since 3.5.9
3151
- */
3152
- scheduleTask(task, _priority) {
3153
- this.tasks.push(task);
3154
- if (!this.running) {
3155
- this.running = true;
3156
- setImmediate(this.afterScheduled);
3157
- }
3158
- }
3159
- /**
3160
- * @since 3.5.9
3161
- */
3162
- afterScheduled = () => {
3163
- this.running = false;
3164
- this.runTasks();
3165
- };
3166
- /**
3167
- * @since 3.5.9
3168
- */
3169
- runTasks() {
3170
- const tasks = this.tasks;
3171
- this.tasks = [];
3172
- for (let i = 0, len = tasks.length; i < len; i++) {
3173
- tasks[i]();
3174
- }
3175
- }
3176
- /**
3177
- * @since 3.5.9
3178
- */
3179
- shouldYield(fiber) {
3180
- return fiber.currentOpCount >= fiber.getRef(MaxOpsBeforeYield);
3181
- }
3182
- /**
3183
- * @since 3.5.9
3184
- */
3185
- flush() {
3186
- while (this.tasks.length > 0) {
3187
- this.runTasks();
3188
- }
7
+ static make(result) {
8
+ return new _BotResponse(result);
3189
9
  }
10
+ static ignore = new _BotResponse();
3190
11
  };
3191
- var service = (tag) => withMicroFiber((fiber) => succeed(unsafeGet3(fiber.context, tag)));
3192
- var updateContext = /* @__PURE__ */ dual(2, (self, f) => withMicroFiber((fiber) => {
3193
- const prev = fiber.context;
3194
- fiber.context = f(prev);
3195
- return onExit(self, () => {
3196
- fiber.context = prev;
3197
- return void_;
3198
- });
3199
- }));
3200
- var provideContext = /* @__PURE__ */ dual(2, (self, provided) => updateContext(self, merge2(provided)));
3201
- var provideService = /* @__PURE__ */ dual(3, (self, tag, service2) => updateContext(self, add2(tag, service2)));
3202
- var MaxOpsBeforeYield = class extends (/* @__PURE__ */ Reference2()("effect/Micro/currentMaxOpsBeforeYield", {
3203
- defaultValue: () => 2048
3204
- })) {
3205
- };
3206
- var CurrentConcurrency = class extends (/* @__PURE__ */ Reference2()("effect/Micro/currentConcurrency", {
3207
- defaultValue: () => "unbounded"
3208
- })) {
3209
- };
3210
- var CurrentScheduler = class extends (/* @__PURE__ */ Reference2()("effect/Micro/currentScheduler", {
3211
- defaultValue: () => new MicroSchedulerDefault()
3212
- })) {
12
+ var extractCommand = (update) => {
13
+ if (typeof update !== "object" || update === null) return void 0;
14
+ const u = update;
15
+ if (!u.entities || !u.text) return void 0;
16
+ const entity = u.entities.find((e) => e.type === "bot_command");
17
+ if (!entity) return void 0;
18
+ return u.text.slice(entity.offset, entity.offset + entity.length);
3213
19
  };
3214
- var repeatExit = /* @__PURE__ */ dual(2, (self, options) => suspend(() => {
3215
- const startedAt = options.schedule ? Date.now() : 0;
3216
- let attempt = 0;
3217
- const loop = flatMap3(exit(self), (exit2) => {
3218
- if (options.while !== void 0 && !options.while(exit2)) {
3219
- return exit2;
3220
- } else if (options.times !== void 0 && attempt >= options.times) {
3221
- return exit2;
3222
- }
3223
- attempt++;
3224
- let delayEffect = yieldNow;
3225
- if (options.schedule !== void 0) {
3226
- const elapsed = Date.now() - startedAt;
3227
- const duration = options.schedule(attempt, elapsed);
3228
- if (isNone2(duration)) {
3229
- return exit2;
3230
- }
3231
- delayEffect = sleep(duration.value);
3232
- }
3233
- return flatMap3(delayEffect, () => loop);
3234
- });
3235
- return loop;
3236
- }));
3237
- var repeat = /* @__PURE__ */ dual((args2) => isMicro(args2[0]), (self, options) => repeatExit(self, {
3238
- ...options,
3239
- while: (exit2) => exit2._tag === "Success" && (options?.while === void 0 || options.while(exit2.value))
3240
- }));
3241
- var catchAllCause = /* @__PURE__ */ dual(2, (self, f) => {
3242
- const onFailure = Object.create(OnFailureProto);
3243
- onFailure[args] = self;
3244
- onFailure[failureCont] = f;
3245
- return onFailure;
3246
- });
3247
- var OnFailureProto = /* @__PURE__ */ makePrimitiveProto({
3248
- op: "OnFailure",
3249
- eval(fiber) {
3250
- fiber._stack.push(this);
3251
- return this[args];
3252
- }
3253
- });
3254
- var catchCauseIf = /* @__PURE__ */ dual(3, (self, predicate, f) => catchAllCause(self, (cause) => predicate(cause) ? f(cause) : failCause2(cause)));
3255
- var catchAll = /* @__PURE__ */ dual(2, (self, f) => catchCauseIf(self, causeIsFail, (cause) => f(cause.error)));
3256
- var matchCauseEffect = /* @__PURE__ */ dual(2, (self, options) => {
3257
- const primitive = Object.create(OnSuccessAndFailureProto);
3258
- primitive[args] = self;
3259
- primitive[successCont] = options.onSuccess;
3260
- primitive[failureCont] = options.onFailure;
3261
- return primitive;
3262
- });
3263
- var OnSuccessAndFailureProto = /* @__PURE__ */ makePrimitiveProto({
3264
- op: "OnSuccessAndFailure",
3265
- eval(fiber) {
3266
- fiber._stack.push(this);
3267
- return this[args];
3268
- }
3269
- });
3270
- var matchCause = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, {
3271
- onFailure: (cause) => sync(() => options.onFailure(cause)),
3272
- onSuccess: (value) => sync(() => options.onSuccess(value))
3273
- }));
3274
- var sleep = (millis) => async((resume) => {
3275
- const timeout = setTimeout(() => {
3276
- resume(void_);
3277
- }, millis);
3278
- return sync(() => {
3279
- clearTimeout(timeout);
3280
- });
3281
- });
3282
- var delay = /* @__PURE__ */ dual(2, (self, millis) => andThen(sleep(millis), self));
3283
- var MicroScopeTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroScope");
3284
- var MicroScopeImpl = class _MicroScopeImpl {
3285
- [MicroScopeTypeId];
3286
- state = {
3287
- _tag: "Open",
3288
- finalizers: /* @__PURE__ */ new Set()
20
+ var createBotContext = (update) => {
21
+ const command = extractCommand(update);
22
+ return {
23
+ command,
24
+ reply: (text, options) => BotResponse.make({ type: "message", text, ...options }),
25
+ replyWithDocument: (document, options) => BotResponse.make({ type: "document", document, ...options }),
26
+ replyWithPhoto: (photo, options) => BotResponse.make({ type: "photo", photo, ...options }),
27
+ ignore: BotResponse.ignore
3289
28
  };
3290
- constructor() {
3291
- this[MicroScopeTypeId] = MicroScopeTypeId;
3292
- }
3293
- unsafeAddFinalizer(finalizer) {
3294
- if (this.state._tag === "Open") {
3295
- this.state.finalizers.add(finalizer);
3296
- }
3297
- }
3298
- addFinalizer(finalizer) {
3299
- return suspend(() => {
3300
- if (this.state._tag === "Open") {
3301
- this.state.finalizers.add(finalizer);
3302
- return void_;
3303
- }
3304
- return finalizer(this.state.exit);
3305
- });
3306
- }
3307
- unsafeRemoveFinalizer(finalizer) {
3308
- if (this.state._tag === "Open") {
3309
- this.state.finalizers.delete(finalizer);
3310
- }
3311
- }
3312
- close(microExit) {
3313
- return suspend(() => {
3314
- if (this.state._tag === "Open") {
3315
- const finalizers = Array.from(this.state.finalizers).reverse();
3316
- this.state = {
3317
- _tag: "Closed",
3318
- exit: microExit
3319
- };
3320
- return flatMap3(forEach3(finalizers, (finalizer) => exit(finalizer(microExit))), exitVoidAll);
3321
- }
3322
- return void_;
3323
- });
3324
- }
3325
- get fork() {
3326
- return sync(() => {
3327
- const newScope = new _MicroScopeImpl();
3328
- if (this.state._tag === "Closed") {
3329
- newScope.state = this.state;
3330
- return newScope;
3331
- }
3332
- function fin(exit2) {
3333
- return newScope.close(exit2);
3334
- }
3335
- this.state.finalizers.add(fin);
3336
- newScope.unsafeAddFinalizer((_) => sync(() => this.unsafeRemoveFinalizer(fin)));
3337
- return newScope;
3338
- });
3339
- }
3340
- };
3341
- var onExit = /* @__PURE__ */ dual(2, (self, f) => uninterruptibleMask((restore) => matchCauseEffect(restore(self), {
3342
- onFailure: (cause) => flatMap3(f(exitFailCause(cause)), () => failCause2(cause)),
3343
- onSuccess: (a) => flatMap3(f(exitSucceed(a)), () => succeed(a))
3344
- })));
3345
- var setInterruptible = /* @__PURE__ */ makePrimitive({
3346
- op: "SetInterruptible",
3347
- ensure(fiber) {
3348
- fiber.interruptible = this[args];
3349
- if (fiber._interrupted && fiber.interruptible) {
3350
- return () => exitInterrupt;
3351
- }
3352
- }
3353
- });
3354
- var interruptible = (self) => withMicroFiber((fiber) => {
3355
- if (fiber.interruptible) return self;
3356
- fiber.interruptible = true;
3357
- fiber._stack.push(setInterruptible(false));
3358
- if (fiber._interrupted) return exitInterrupt;
3359
- return self;
3360
- });
3361
- var uninterruptibleMask = (f) => withMicroFiber((fiber) => {
3362
- if (!fiber.interruptible) return f(identity);
3363
- fiber.interruptible = false;
3364
- fiber._stack.push(setInterruptible(true));
3365
- return f(interruptible);
3366
- });
3367
- var whileLoop = /* @__PURE__ */ makePrimitive({
3368
- op: "While",
3369
- contA(value, fiber) {
3370
- this[args].step(value);
3371
- if (this[args].while()) {
3372
- fiber._stack.push(this);
3373
- return this[args].body();
3374
- }
3375
- return exitVoid;
3376
- },
3377
- eval(fiber) {
3378
- if (this[args].while()) {
3379
- fiber._stack.push(this);
3380
- return this[args].body();
3381
- }
3382
- return exitVoid;
3383
- }
3384
- });
3385
- var forEach3 = (iterable, f, options) => withMicroFiber((parent) => {
3386
- const concurrencyOption = options?.concurrency === "inherit" ? parent.getRef(CurrentConcurrency) : options?.concurrency ?? 1;
3387
- const concurrency = concurrencyOption === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrencyOption);
3388
- const items = fromIterable(iterable);
3389
- let length = items.length;
3390
- if (length === 0) {
3391
- return options?.discard ? void_ : succeed([]);
3392
- }
3393
- const out = options?.discard ? void 0 : new Array(length);
3394
- let index = 0;
3395
- if (concurrency === 1) {
3396
- return as(whileLoop({
3397
- while: () => index < items.length,
3398
- body: () => f(items[index], index),
3399
- step: out ? (b) => out[index++] = b : (_) => index++
3400
- }), out);
3401
- }
3402
- return async((resume) => {
3403
- const fibers = /* @__PURE__ */ new Set();
3404
- let result = void 0;
3405
- let inProgress = 0;
3406
- let doneCount = 0;
3407
- let pumping = false;
3408
- let interrupted = false;
3409
- function pump() {
3410
- pumping = true;
3411
- while (inProgress < concurrency && index < length) {
3412
- const currentIndex = index;
3413
- const item = items[currentIndex];
3414
- index++;
3415
- inProgress++;
3416
- try {
3417
- const child = unsafeFork(parent, f(item, currentIndex), true, true);
3418
- fibers.add(child);
3419
- child.addObserver((exit2) => {
3420
- fibers.delete(child);
3421
- if (interrupted) {
3422
- return;
3423
- } else if (exit2._tag === "Failure") {
3424
- if (result === void 0) {
3425
- result = exit2;
3426
- length = index;
3427
- fibers.forEach((fiber) => fiber.unsafeInterrupt());
3428
- }
3429
- } else if (out !== void 0) {
3430
- out[currentIndex] = exit2.value;
3431
- }
3432
- doneCount++;
3433
- inProgress--;
3434
- if (doneCount === length) {
3435
- resume(result ?? succeed(out));
3436
- } else if (!pumping && inProgress < concurrency) {
3437
- pump();
3438
- }
3439
- });
3440
- } catch (err) {
3441
- result = exitDie(err);
3442
- length = index;
3443
- fibers.forEach((fiber) => fiber.unsafeInterrupt());
3444
- }
3445
- }
3446
- pumping = false;
3447
- }
3448
- pump();
3449
- return suspend(() => {
3450
- interrupted = true;
3451
- index = length;
3452
- return fiberInterruptAll(fibers);
3453
- });
3454
- });
3455
- });
3456
- var unsafeFork = (parent, effect, immediate = false, daemon = false) => {
3457
- const child = new MicroFiberImpl(parent.context, parent.interruptible);
3458
- if (!daemon) {
3459
- parent.children().add(child);
3460
- child.addObserver(() => parent.children().delete(child));
3461
- }
3462
- if (immediate) {
3463
- child.evaluate(effect);
3464
- } else {
3465
- parent.getRef(CurrentScheduler).scheduleTask(() => child.evaluate(effect), 0);
3466
- }
3467
- return child;
3468
- };
3469
- var forkDaemon = (self) => withMicroFiber((fiber) => succeed(unsafeFork(fiber, self, false, true)));
3470
- var runFork = (effect, options) => {
3471
- const fiber = new MicroFiberImpl(CurrentScheduler.context(options?.scheduler ?? new MicroSchedulerDefault()));
3472
- fiber.evaluate(effect);
3473
- if (options?.signal) {
3474
- if (options.signal.aborted) {
3475
- fiber.unsafeInterrupt();
3476
- } else {
3477
- const abort = () => fiber.unsafeInterrupt();
3478
- options.signal.addEventListener("abort", abort, {
3479
- once: true
3480
- });
3481
- fiber.addObserver(() => options.signal.removeEventListener("abort", abort));
3482
- }
3483
- }
3484
- return fiber;
3485
- };
3486
- var runPromiseExit = (effect, options) => new Promise((resolve, _reject) => {
3487
- const handle = runFork(effect, options);
3488
- handle.addObserver(resolve);
3489
- });
3490
- var runPromise = (effect, options) => runPromiseExit(effect, options).then((exit2) => {
3491
- if (exit2._tag === "Failure") {
3492
- throw exit2.cause;
3493
- }
3494
- return exit2.value;
3495
- });
3496
-
3497
- // src/internal/handle-update.ts
3498
- import { MESSAGE_EFFECTS } from "@effect-ak/tg-bot-client";
3499
-
3500
- // src/internal/poll-settings.ts
3501
- var BotUpdateHandlersTag = class extends Tag2("BotUpdateHandlers")() {
3502
- };
3503
- var BotTgClientTag = class extends Tag2("BotTgClient")() {
3504
- };
3505
- var BotPollSettings = class _BotPollSettings extends Class2 {
3506
- static make(input) {
3507
- let batch_size = input.batch_size ?? 10;
3508
- let poll_timeout = input.poll_timeout ?? 10;
3509
- let max_empty_responses = input.max_empty_responses;
3510
- let log_level = input.log_level ?? "info";
3511
- let on_error = input.on_error;
3512
- if (batch_size < 10 || batch_size > 100) {
3513
- console.warn("Wrong batch_size, must be in [10..100], using 10 instead");
3514
- batch_size = 10;
3515
- }
3516
- if (poll_timeout < 2 || poll_timeout > 120) {
3517
- console.warn("Wrong poll_timeout, must be in [2..120], using 20 instead");
3518
- poll_timeout = 20;
3519
- }
3520
- if (max_empty_responses && max_empty_responses < 2) {
3521
- console.warn(
3522
- "Wrong max_empty_responses, must be in [2..infinity], using infinity"
3523
- );
3524
- max_empty_responses = void 0;
3525
- }
3526
- if (!log_level) {
3527
- log_level = "info";
3528
- }
3529
- if (!on_error) {
3530
- on_error = "stop";
3531
- }
3532
- const config = new _BotPollSettings({
3533
- batch_size,
3534
- poll_timeout,
3535
- max_empty_responses,
3536
- log_level,
3537
- on_error
3538
- });
3539
- console.log("bot poll settings", config);
3540
- return config;
3541
- }
3542
- };
3543
- var BotPollSettingsTag = class extends Reference2()(
3544
- "BotSettings",
3545
- {
3546
- defaultValue() {
3547
- return BotPollSettings.make({});
3548
- }
3549
- }
3550
- ) {
3551
29
  };
3552
30
 
3553
- // src/internal/handle-update.ts
31
+ // src/bot-processor.ts
3554
32
  var isGuardedHandler = (handler) => typeof handler === "object" && handler !== null && "handle" in handler;
3555
33
  var executeSingleGuard = async (guard, update, ctx) => {
3556
34
  const input = { update, ctx };
@@ -3567,454 +45,296 @@ var executeGuards = async (guards, update, ctx) => {
3567
45
  }
3568
46
  return BotResponse.ignore;
3569
47
  };
3570
- var executeHandler = (handler, update, ctx) => {
48
+ var executeHandler = async (handler, update, ctx) => {
3571
49
  if (typeof handler === "function") {
3572
- return handler(update);
50
+ return await handler(update);
3573
51
  }
3574
52
  if (Array.isArray(handler)) {
3575
- return executeGuards(handler, update, ctx);
53
+ return await executeGuards(handler, update, ctx);
3576
54
  }
3577
55
  if (isGuardedHandler(handler)) {
3578
- return executeSingleGuard(handler, update, ctx).then(
3579
- (r) => r ?? BotResponse.ignore
3580
- );
56
+ const result = await executeSingleGuard(handler, update, ctx);
57
+ return result ?? BotResponse.ignore;
3581
58
  }
3582
59
  return BotResponse.ignore;
3583
60
  };
3584
61
  var extractUpdate = (input) => {
3585
62
  for (const [field, value] of Object.entries(input)) {
3586
- if (field == "update_id") {
3587
- continue;
3588
- }
3589
- return {
3590
- type: field,
3591
- ...value
3592
- };
63
+ if (field === "update_id") continue;
64
+ return { type: field, ...value };
3593
65
  }
3594
- return;
3595
- };
3596
- var BatchUpdateResult = class extends Class2 {
66
+ return void 0;
3597
67
  };
3598
- var handleUpdates = (updates) => gen(function* () {
3599
- const pollSettings = yield* service(BotPollSettingsTag);
3600
- const updateHandler = yield* service(BotUpdateHandlersTag);
3601
- if (updateHandler.type == "single") {
3602
- return yield* handleOneByOne(updates, updateHandler, pollSettings);
3603
- } else {
3604
- return yield* handleEntireBatch(updates, updateHandler);
68
+ var handleUpdates = async (updates, behavior, client, settings, log, onHandleResult) => {
69
+ if (behavior.type === "single") {
70
+ return handleOneByOne(updates, behavior, client, settings, log, onHandleResult);
3605
71
  }
3606
- });
3607
- var handleEntireBatch = (updates, handlers) => try_({
3608
- try: () => handlers.on_batch(updates),
3609
- catch: identity
3610
- }).pipe(
3611
- andThen((result) => {
3612
- if (result instanceof Promise) {
3613
- return tryPromise({
3614
- try: () => result,
3615
- catch: identity
3616
- });
3617
- } else {
3618
- return succeed(result);
3619
- }
3620
- }),
3621
- andThen(
3622
- (doNext) => new BatchUpdateResult({
3623
- hasErrors: !doNext,
3624
- updates
3625
- })
3626
- ),
3627
- catchAll((error) => {
3628
- console.warn("handle batch error", {
72
+ return handleEntireBatch(updates, behavior, log);
73
+ };
74
+ var handleEntireBatch = async (updates, handlers, log) => {
75
+ try {
76
+ const doNext = await handlers.on_batch(updates);
77
+ return { hasErrors: !doNext, updates };
78
+ } catch (error) {
79
+ log.warn("handle batch error", {
3629
80
  errorMessage: error instanceof Error ? error.message : void 0,
3630
81
  updates: updates.map((_) => Object.keys(_).at(1)),
3631
82
  error
3632
83
  });
3633
- return succeed(
3634
- new BatchUpdateResult({
3635
- hasErrors: true,
3636
- updates
3637
- })
3638
- );
3639
- })
3640
- );
3641
- var HandleUpdateError = class extends TaggedError("HandleUpdateError") {
3642
- logInfo() {
3643
- return {
3644
- updateId: this.update.update_id,
3645
- updateKey: Object.keys(this.update).at(1),
3646
- name: this._tag,
3647
- ...this.cause instanceof Error && { error: this.cause.message }
3648
- };
84
+ return { hasErrors: true, updates };
3649
85
  }
3650
86
  };
3651
- var handleOneByOne = (updates, handlers, pollSettings) => forEach3(
3652
- updates,
3653
- (update) => handleOneUpdate(update, handlers).pipe(
3654
- catchAll((error) => {
3655
- if (error instanceof HandleUpdateError) {
3656
- console.warn("update handle error", error.logInfo());
3657
- } else {
3658
- console.warn("unknown error", error);
3659
- }
3660
- return succeed(error);
3661
- })
3662
- ),
3663
- {
3664
- concurrency: 10
87
+ var handleOneByOne = async (updates, handlers, client, settings, log, onHandleResult) => {
88
+ const results = await Promise.allSettled(
89
+ updates.map((update) => handleOneUpdate(update, handlers, client, settings, log, onHandleResult))
90
+ );
91
+ const hasErrors = results.some(
92
+ (r) => r.status === "rejected" || r.status === "fulfilled" && r.value !== void 0
93
+ );
94
+ if (settings.log_level === "debug") {
95
+ log.debug("handle batch result", results);
3665
96
  }
3666
- ).pipe(
3667
- andThen((batchResult) => {
3668
- if (pollSettings.log_level == "debug") {
3669
- console.debug("handle batch result", batchResult);
3670
- }
3671
- return new BatchUpdateResult({
3672
- hasErrors: !batchResult.every((error) => error == null),
3673
- updates
3674
- });
3675
- })
3676
- );
3677
- var handleOneUpdate = (updateObject, handlers) => gen(function* () {
97
+ return { hasErrors, updates };
98
+ };
99
+ var handleOneUpdate = async (updateObject, handlers, client, settings, log, onHandleResult) => {
3678
100
  const update = extractUpdate(updateObject);
3679
101
  if (!update) {
3680
- return yield* fail3(
3681
- new HandleUpdateError({
3682
- name: "UnknownUpdate",
3683
- update: updateObject
3684
- })
3685
- );
102
+ log.warn("update handle error", {
103
+ updateId: updateObject.update_id,
104
+ name: "UnknownUpdate"
105
+ });
106
+ return "UnknownUpdate";
3686
107
  }
3687
108
  const handler = handlers[`on_${update.type}`];
3688
109
  if (!handler) {
3689
- return yield* fail3(
3690
- new HandleUpdateError({
3691
- name: "HandlerNotDefined",
3692
- update: updateObject
3693
- })
3694
- );
3695
- }
3696
- if (update.type == "message" && "text" in update) {
3697
- console.info("Got a new text message", {
3698
- chatId: update.chat.id,
3699
- chatType: update.chat.type,
3700
- message: `${update.text.slice(0, 5)}...`
110
+ onHandleResult?.({
111
+ update: updateObject,
112
+ updateType: update.type,
113
+ status: "no_handler",
114
+ duration: 0
3701
115
  });
116
+ return "HandlerNotDefined";
3702
117
  }
3703
118
  const ctx = createBotContext(update);
3704
- let handleUpdateError;
3705
- const handleResult = yield* try_({
3706
- try: () => executeHandler(handler, update, ctx),
3707
- catch: (error) => new HandleUpdateError({
119
+ const startTime = performance.now();
120
+ let handleResult;
121
+ let hasError = false;
122
+ let errorMessage;
123
+ try {
124
+ handleResult = await executeHandler(handler, update, ctx);
125
+ } catch (error) {
126
+ hasError = true;
127
+ errorMessage = error instanceof Error ? error.message : String(error);
128
+ const errorInfo = {
129
+ updateId: updateObject.update_id,
130
+ updateKey: Object.keys(updateObject).at(1),
3708
131
  name: "BotHandlerError",
132
+ ...error instanceof Error && { error: error.message }
133
+ };
134
+ log.warn("error", errorInfo);
135
+ handleResult = BotResponse.make({
136
+ type: "message",
137
+ text: `Some internal error has happened (BotHandlerError) while handling this message`,
138
+ message_effect_id: "\u{1F4A9}",
139
+ ...updateObject.message?.message_id ? { reply_parameters: { message_id: updateObject.message.message_id } } : void 0
140
+ });
141
+ }
142
+ const duration = Math.round(performance.now() - startTime);
143
+ if (!handleResult) {
144
+ if (settings.log_level === "debug") {
145
+ log.debug(`Bot response is undefined for update #${updateObject.update_id}`);
146
+ }
147
+ onHandleResult?.({
3709
148
  update: updateObject,
3710
- cause: error
3711
- })
3712
- }).pipe(
3713
- andThen((handleResult2) => {
3714
- if (handleResult2 instanceof Promise) {
3715
- return tryPromise({
3716
- try: () => handleResult2,
3717
- catch: (error) => new HandleUpdateError({
3718
- name: "BotHandlerError",
3719
- update: updateObject,
3720
- cause: error
3721
- })
3722
- });
3723
- }
3724
- return succeed(handleResult2);
3725
- }),
3726
- catchAll((error) => {
3727
- handleUpdateError = error;
3728
- console.warn("error", error.logInfo());
3729
- return succeed(
3730
- BotResponse.make({
3731
- type: "message",
3732
- text: `Some internal error has happend(${error.name}) while handling this message`,
3733
- message_effect_id: MESSAGE_EFFECTS["\u{1F4A9}"],
3734
- ...updateObject.message?.message_id ? {
3735
- reply_parameters: {
3736
- message_id: updateObject.message?.message_id
3737
- }
3738
- } : void 0
3739
- })
3740
- );
3741
- })
3742
- );
3743
- const pollSettings = yield* service(BotPollSettingsTag);
3744
- if (!handleResult && pollSettings.log_level == "debug") {
3745
- console.log(
3746
- `Bot response is undefined for update with ID #${updateObject.update_id}.`
3747
- );
3748
- return;
149
+ updateType: update.type,
150
+ status: "ignored",
151
+ duration
152
+ });
153
+ return void 0;
3749
154
  }
3750
155
  if ("chat" in update && handleResult.response) {
3751
- const client = yield* service(BotTgClientTag);
3752
156
  const responsePayload = handleResult.response;
3753
- const response = yield* tryPromise({
3754
- try: () => client.execute(`send_${responsePayload.type}`, {
3755
- ...responsePayload,
3756
- chat_id: update.chat.id
3757
- }),
3758
- catch: (error) => error
157
+ const result = await client.execute(`send_${responsePayload.type}`, {
158
+ ...responsePayload,
159
+ chat_id: update.chat.id
3759
160
  });
3760
- if (pollSettings.log_level == "debug" && "text") {
3761
- console.debug("bot response", response);
3762
- }
3763
- }
3764
- return handleUpdateError;
3765
- });
3766
-
3767
- // src/service/fetch-updates.ts
3768
- var BotFetchUpdatesService = class extends Reference2()(
3769
- "BotFetchUpdatesService",
3770
- {
3771
- defaultValue: () => {
3772
- const state = {
3773
- lastUpdateId: void 0,
3774
- emptyResponses: 0
3775
- };
3776
- const fetchUpdates = _fetchUpdates(state).pipe(
3777
- tap((updates) => {
3778
- const id = updates.map((_) => _.update_id).sort().at(-1);
3779
- console.log("updating last update id", id);
3780
- state.lastUpdateId = id ? id + 1 : void 0;
3781
- console.log(state);
3782
- })
3783
- );
3784
- const commit = _commitLastBatch(state);
3785
- return {
3786
- state,
3787
- fetchUpdates,
3788
- commit
3789
- };
3790
- }
3791
- }
3792
- ) {
3793
- };
3794
- var FetchUpdatesError = class extends TaggedError("FetchUpdatesError") {
161
+ if (!result.ok) {
162
+ log.warn("failed to send response", result.error);
163
+ } else if (settings.log_level === "debug") {
164
+ log.debug("bot response", result.data);
165
+ }
166
+ }
167
+ onHandleResult?.({
168
+ update: updateObject,
169
+ updateType: update.type,
170
+ status: hasError ? "error" : handleResult.response ? "handled" : "ignored",
171
+ ...handleResult.response ? { responseType: handleResult.response.type } : {},
172
+ ...errorMessage ? { error: errorMessage } : {},
173
+ duration
174
+ });
175
+ return void 0;
3795
176
  };
3796
- var _fetchUpdates = (pollState) => gen(function* () {
3797
- const pollSettings = yield* service(BotPollSettingsTag);
3798
- const client = yield* service(BotTgClientTag);
3799
- if (pollSettings.max_empty_responses && pollState.emptyResponses == pollSettings.max_empty_responses) {
3800
- return yield* fail3(
3801
- new FetchUpdatesError({ name: "TooManyEmptyResponses" })
3802
- );
3803
- }
3804
- const updateId = pollState.lastUpdateId;
3805
- if (pollSettings.log_level == "debug") {
3806
- console.debug("getting updates", pollState);
3807
- }
3808
- const updates = yield* tryPromise({
3809
- try: () => client.execute("get_updates", {
3810
- timeout: pollSettings.poll_timeout,
3811
- ...updateId ? { offset: updateId } : void 0
3812
- }),
3813
- catch: (error) => error
3814
- }).pipe(andThen((_) => _.sort((_2) => _2.update_id)));
3815
- if (updates.length) {
3816
- console.debug(`got a batch of updates (${updates.length})`);
3817
- pollState.emptyResponses = 0;
3818
- return updates;
3819
- } else {
3820
- pollState.emptyResponses += 1;
3821
- return [];
3822
- }
3823
- });
3824
- var _commitLastBatch = (pollState) => gen(function* () {
3825
- console.log("commit", { pollState });
3826
- if (pollState.lastUpdateId) {
3827
- const client = yield* service(BotTgClientTag);
3828
- const offset = pollState.lastUpdateId;
3829
- return yield* tryPromise({
3830
- try: () => client.execute("get_updates", {
3831
- offset,
3832
- limit: 0
3833
- }),
3834
- catch: (error) => error
3835
- }).pipe(
3836
- andThen(
3837
- andThen(service(BotPollSettingsTag), (pollSettings) => {
3838
- if (pollSettings.log_level == "debug") {
3839
- console.debug("committed offset", pollState);
3840
- }
3841
- })
3842
- )
3843
- );
3844
- } else {
3845
- return yield* fail3(
3846
- new FetchUpdatesError({
3847
- name: "NoUpdatesToCommit"
3848
- })
177
+
178
+ // src/run.ts
179
+ import { makeTgBotClient } from "@effect-ak/tg-bot-client";
180
+
181
+ // src/polling.ts
182
+ function makePollSettings(input, log) {
183
+ let batch_size = input.batch_size ?? 10;
184
+ let poll_timeout = input.poll_timeout ?? 10;
185
+ let max_empty_responses = input.max_empty_responses;
186
+ let log_level = input.log_level ?? "info";
187
+ let on_error = input.on_error ?? "stop";
188
+ if (batch_size < 10 || batch_size > 100) {
189
+ log.warn("Wrong batch_size, must be in [10..100], using 10 instead");
190
+ batch_size = 10;
191
+ }
192
+ if (poll_timeout < 2 || poll_timeout > 120) {
193
+ log.warn("Wrong poll_timeout, must be in [2..120], using 20 instead");
194
+ poll_timeout = 20;
195
+ }
196
+ if (max_empty_responses && max_empty_responses < 2) {
197
+ log.warn(
198
+ "Wrong max_empty_responses, must be in [2..infinity], using infinity"
3849
199
  );
200
+ max_empty_responses = void 0;
201
+ }
202
+ const settings = {
203
+ batch_size,
204
+ poll_timeout,
205
+ max_empty_responses,
206
+ log_level,
207
+ on_error
208
+ };
209
+ log.debug("bot poll settings", settings);
210
+ return settings;
211
+ }
212
+ var UpdateFetcher = class {
213
+ constructor(client, settings) {
214
+ this.client = client;
215
+ this.settings = settings;
216
+ }
217
+ lastUpdateId;
218
+ emptyResponses = 0;
219
+ async fetchUpdates() {
220
+ if (this.settings.max_empty_responses && this.emptyResponses >= this.settings.max_empty_responses) {
221
+ throw new Error("TooManyEmptyResponses");
222
+ }
223
+ if (this.settings.log_level === "debug") {
224
+ console.debug("getting updates", {
225
+ lastUpdateId: this.lastUpdateId,
226
+ emptyResponses: this.emptyResponses
227
+ });
228
+ }
229
+ const result = await this.client.execute("get_updates", {
230
+ timeout: this.settings.poll_timeout,
231
+ ...this.lastUpdateId ? { offset: this.lastUpdateId } : void 0
232
+ });
233
+ if (!result.ok) {
234
+ throw new Error(`Failed to fetch updates: ${result.error._tag}`);
235
+ }
236
+ const sorted = result.data.sort((a, b) => a.update_id - b.update_id);
237
+ if (sorted.length > 0) {
238
+ const lastId = sorted[sorted.length - 1].update_id;
239
+ if (this.settings.log_level === "debug") {
240
+ console.debug("updating last update id", lastId);
241
+ }
242
+ this.lastUpdateId = lastId + 1;
243
+ this.emptyResponses = 0;
244
+ } else {
245
+ this.emptyResponses += 1;
246
+ }
247
+ return sorted;
3850
248
  }
3851
- });
3852
-
3853
- // src/service/run.ts
3854
- var BotRunService = class extends Reference2()(
3855
- "BotRunService",
3856
- {
3857
- defaultValue: () => {
3858
- console.log("Initiating BotRunService");
3859
- const state = {
3860
- fiber: void 0
3861
- };
3862
- const runBotInBackground = _runBotDaemon(state);
3863
- const getFiber = () => state.fiber;
3864
- return {
3865
- runBotInBackground,
3866
- getFiber
3867
- };
249
+ async commit() {
250
+ if (!this.lastUpdateId) return;
251
+ if (this.settings.log_level === "debug") {
252
+ console.debug("committing offset", this.lastUpdateId);
253
+ }
254
+ const result = await this.client.execute("get_updates", {
255
+ offset: this.lastUpdateId,
256
+ limit: 0
257
+ });
258
+ if (!result.ok) {
259
+ throw new Error(`Failed to commit offset: ${result.error._tag}`);
260
+ }
261
+ if (this.settings.log_level === "debug") {
262
+ console.debug("committed offset", this.lastUpdateId);
3868
263
  }
3869
264
  }
3870
- ) {
3871
265
  };
3872
- var _runBotDaemon = (state) => gen(function* () {
3873
- console.log("running telegram chat bot");
3874
- const fetchService = yield* service(BotFetchUpdatesService);
3875
- const settings = yield* service(BotPollSettingsTag);
3876
- const continueOnError = (hasError) => {
3877
- if (settings.on_error == "continue") return true;
3878
- return !hasError;
3879
- };
3880
- const startFiber = delay(1e3)(
3881
- fetchService.fetchUpdates.pipe(
3882
- andThen(handleUpdates),
3883
- tap((result) => {
3884
- const hasUpdates = result.updates.length > 0;
3885
- return hasUpdates && continueOnError(result.hasErrors) ? fetchService.commit : void_;
3886
- })
3887
- )
3888
- ).pipe(
3889
- repeat({
3890
- while: (_) => continueOnError(_.hasErrors)
3891
- }),
3892
- forkDaemon,
3893
- tap(
3894
- (fiber) => fiber.addObserver((exit2) => {
3895
- console.log("bot's fiber has been closed", exit2);
3896
- })
3897
- )
3898
- );
3899
- if (state.fiber) {
3900
- console.log("killing previous bot's fiber");
3901
- yield* fiberInterrupt(state.fiber);
3902
- }
3903
- state.fiber = yield* startFiber;
3904
- console.log("Fetching bot updates via long polling...");
3905
- });
3906
266
 
3907
- // src/internal/launch.ts
3908
- import { makeTgBotClient } from "@effect-ak/tg-bot-client";
3909
- var extractMode = (input) => {
267
+ // src/run.ts
268
+ var consoleLogger = {
269
+ debug: (msg, data) => console.debug(msg, ...data !== void 0 ? [data] : []),
270
+ info: (msg, data) => console.log(msg, ...data !== void 0 ? [data] : []),
271
+ warn: (msg, data) => console.warn(msg, ...data !== void 0 ? [data] : []),
272
+ error: (msg, data) => console.error(msg, ...data !== void 0 ? [data] : [])
273
+ };
274
+ var delay = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
275
+ var extractBehavior = (input) => {
3910
276
  if (input.mode === "batch") {
3911
277
  return { type: "batch", on_batch: input.on_batch };
3912
278
  }
3913
- const { bot_token, mode, poll, ...handlers } = input;
279
+ const { bot_token, mode, poll, onUpdate: _, onHandleResult: __, logger: ___, ...handlers } = input;
3914
280
  return { type: "single", ...handlers };
3915
281
  };
3916
- var launchBot = (input) => gen(function* () {
3917
- const service2 = yield* service(BotRunService);
282
+ var runBot = async (input) => {
283
+ const log = input.logger ?? consoleLogger;
284
+ const settings = makePollSettings(input.poll ?? {}, log);
3918
285
  const client = makeTgBotClient({ bot_token: input.bot_token });
3919
- const contextWithClient = make4(BotTgClientTag, client);
3920
- const mode = extractMode(input);
3921
- yield* service2.runBotInBackground.pipe(
3922
- provideService(BotUpdateHandlersTag, mode),
3923
- provideService(
3924
- BotPollSettingsTag,
3925
- BotPollSettings.make(input.poll ?? {})
3926
- ),
3927
- provideContext(contextWithClient)
3928
- );
3929
- const reload = (mode2) => service2.runBotInBackground.pipe(
3930
- provideService(BotUpdateHandlersTag, mode2),
3931
- provideContext(contextWithClient),
3932
- runPromise
3933
- );
286
+ const fetcher = new UpdateFetcher(client, settings);
287
+ let behavior = extractBehavior(input);
288
+ const abortController = new AbortController();
289
+ const poll = async () => {
290
+ if (settings.log_level === "debug") {
291
+ log.debug("running telegram chat bot");
292
+ log.debug("Fetching bot updates via long polling...");
293
+ }
294
+ while (!abortController.signal.aborted) {
295
+ try {
296
+ const updates = await fetcher.fetchUpdates();
297
+ if (input.onUpdate) {
298
+ for (const u of updates) input.onUpdate(u);
299
+ }
300
+ const result = await handleUpdates(updates, behavior, client, settings, log, input.onHandleResult);
301
+ if (updates.length > 0 && !result.hasErrors) {
302
+ await fetcher.commit();
303
+ }
304
+ if (result.hasErrors && settings.on_error === "stop") {
305
+ log.warn("stopping bot due to error (on_error=stop)");
306
+ break;
307
+ }
308
+ } catch (error) {
309
+ log.error("polling error", error instanceof Error ? error.message : error);
310
+ if (settings.on_error === "stop") break;
311
+ }
312
+ await delay(1e3);
313
+ }
314
+ if (settings.log_level === "debug") {
315
+ log.debug("bot polling stopped");
316
+ }
317
+ };
318
+ poll();
3934
319
  return {
3935
- reload,
3936
- fiber: service2.getFiber
320
+ stop: () => abortController.abort(),
321
+ reload: (newBehavior) => {
322
+ behavior = newBehavior;
323
+ }
3937
324
  };
3938
- });
3939
-
3940
- // src/run.ts
3941
- var runTgChatBot = (input) => launchBot(input).pipe(runPromise);
325
+ };
3942
326
  var defineBot = (input) => {
3943
- if (Object.keys(input).length == 0)
327
+ if (Object.keys(input).length === 0)
3944
328
  console.warn("No handlers are defined for bot");
3945
329
  return input;
3946
330
  };
3947
-
3948
- // src/webhook.ts
3949
- import { makeTgBotClient as makeTgBotClient2 } from "@effect-ak/tg-bot-client";
3950
- var isGuardedHandler2 = (handler) => typeof handler === "object" && handler !== null && "handle" in handler;
3951
- var executeSingleGuard2 = async (guard, update, ctx) => {
3952
- const input = { update, ctx };
3953
- if (guard.match) {
3954
- const matched = await guard.match(input);
3955
- if (!matched) return null;
3956
- }
3957
- return await guard.handle(input);
3958
- };
3959
- var executeGuards2 = async (guards, update, ctx) => {
3960
- for (const guard of guards) {
3961
- const result = await executeSingleGuard2(guard, update, ctx);
3962
- if (result !== null) return result;
3963
- }
3964
- return BotResponse.ignore;
3965
- };
3966
- var executeHandler2 = async (handler, update, ctx) => {
3967
- if (typeof handler === "function") {
3968
- return await handler(update);
3969
- }
3970
- if (Array.isArray(handler)) {
3971
- return await executeGuards2(handler, update, ctx);
3972
- }
3973
- if (isGuardedHandler2(handler)) {
3974
- const result = await executeSingleGuard2(handler, update, ctx);
3975
- return result ?? BotResponse.ignore;
3976
- }
3977
- return BotResponse.ignore;
3978
- };
3979
- var extractUpdate2 = (input) => {
3980
- for (const [field, value] of Object.entries(input)) {
3981
- if (field === "update_id") continue;
3982
- return { type: field, ...value };
3983
- }
3984
- return void 0;
3985
- };
3986
- var processUpdate = async (updateObject, handlers, client) => {
3987
- const update = extractUpdate2(updateObject);
3988
- if (!update) {
3989
- console.warn("Unknown update format", updateObject);
3990
- return;
3991
- }
3992
- const handlerKey = `on_${update.type}`;
3993
- const handler = handlers[handlerKey];
3994
- if (!handler) {
3995
- return;
3996
- }
3997
- const ctx = createBotContext(update);
3998
- try {
3999
- const result = await executeHandler2(handler, update, ctx);
4000
- if (result.response && "chat" in update) {
4001
- const responsePayload = result.response;
4002
- await client.execute(`send_${responsePayload.type}`, {
4003
- ...responsePayload,
4004
- chat_id: update.chat.id
4005
- });
4006
- }
4007
- } catch (error) {
4008
- console.error("Error handling update", {
4009
- updateId: updateObject.update_id,
4010
- error: error instanceof Error ? error.message : error
4011
- });
4012
- }
4013
- };
4014
- var createWebhookHandler = (config) => {
4015
- const client = makeTgBotClient2({ bot_token: config.bot_token });
331
+ var createWebhook = (config) => {
332
+ const { bot_token, onHandleResult, logger, ...handlers } = config;
333
+ const log = logger ?? consoleLogger;
334
+ const client = makeTgBotClient({ bot_token });
335
+ const settings = makePollSettings({}, log);
4016
336
  const handleUpdate = async (update) => {
4017
- await processUpdate(update, config, client);
337
+ await handleUpdates([update], { type: "single", ...handlers }, client, settings, log, onHandleResult);
4018
338
  };
4019
339
  const handler = async (request) => {
4020
340
  try {
@@ -4022,30 +342,146 @@ var createWebhookHandler = (config) => {
4022
342
  await handleUpdate(update);
4023
343
  return new Response("ok", { status: 200 });
4024
344
  } catch (error) {
4025
- console.error("Webhook error", error);
345
+ log.error("Webhook error", error);
4026
346
  return new Response("error", { status: 500 });
4027
347
  }
4028
348
  };
4029
349
  handler.handleUpdate = handleUpdate;
4030
350
  return handler;
4031
351
  };
352
+
353
+ // src/bot-builder.ts
354
+ function makeMessageHelpers() {
355
+ return {
356
+ command: (cmd, handler) => ({
357
+ match: ({ ctx }) => ctx.command === cmd,
358
+ handle: handler
359
+ }),
360
+ text: (handler) => ({
361
+ match: ({ update }) => !!update.text,
362
+ handle: handler
363
+ }),
364
+ photo: (handler) => ({
365
+ match: ({ update }) => !!update.photo,
366
+ handle: handler
367
+ }),
368
+ document: (handler) => ({
369
+ match: ({ update }) => !!update.document,
370
+ handle: handler
371
+ }),
372
+ sticker: (handler) => ({
373
+ match: ({ update }) => !!update.sticker,
374
+ handle: handler
375
+ }),
376
+ fallback: (handler) => ({ handle: handler })
377
+ };
378
+ }
379
+ function makeCallbackQueryHelpers() {
380
+ return {
381
+ data: (pattern, handler) => ({
382
+ match: ({ update }) => typeof pattern === "string" ? update.data === pattern : pattern.test(update.data ?? ""),
383
+ handle: handler
384
+ }),
385
+ fallback: (handler) => ({ handle: handler })
386
+ };
387
+ }
388
+ function makeInlineQueryHelpers() {
389
+ return {
390
+ query: (pattern, handler) => ({
391
+ match: ({ update }) => typeof pattern === "string" ? update.query === pattern : pattern.test(update.query),
392
+ handle: handler
393
+ }),
394
+ fallback: (handler) => ({ handle: handler })
395
+ };
396
+ }
397
+ function makeGenericHelpers() {
398
+ return {
399
+ fallback: (handler) => ({ handle: handler })
400
+ };
401
+ }
402
+ function resolve(makeHelpers, input) {
403
+ if (typeof input === "function") {
404
+ return input(makeHelpers());
405
+ }
406
+ return input;
407
+ }
408
+ function createBot() {
409
+ const handlers = /* @__PURE__ */ new Map();
410
+ function register(type, guards) {
411
+ const existing = handlers.get(type) ?? [];
412
+ handlers.set(type, [...existing, ...guards]);
413
+ }
414
+ function collectHandlers() {
415
+ const result = {};
416
+ for (const [type, guards] of handlers) {
417
+ result[`on_${type}`] = guards;
418
+ }
419
+ return result;
420
+ }
421
+ const bot = {
422
+ onMessage(input) {
423
+ register("message", resolve(makeMessageHelpers, input));
424
+ return bot;
425
+ },
426
+ onEditedMessage(input) {
427
+ register("edited_message", resolve(makeGenericHelpers, input));
428
+ return bot;
429
+ },
430
+ onChannelPost(input) {
431
+ register("channel_post", resolve(makeGenericHelpers, input));
432
+ return bot;
433
+ },
434
+ onEditedChannelPost(input) {
435
+ register("edited_channel_post", resolve(makeGenericHelpers, input));
436
+ return bot;
437
+ },
438
+ onBusinessMessage(input) {
439
+ register("business_message", resolve(makeGenericHelpers, input));
440
+ return bot;
441
+ },
442
+ onEditedBusinessMessage(input) {
443
+ register("edited_business_message", resolve(makeGenericHelpers, input));
444
+ return bot;
445
+ },
446
+ onCallbackQuery(input) {
447
+ register("callback_query", resolve(makeCallbackQueryHelpers, input));
448
+ return bot;
449
+ },
450
+ onInlineQuery(input) {
451
+ register("inline_query", resolve(makeInlineQueryHelpers, input));
452
+ return bot;
453
+ },
454
+ on(type, input) {
455
+ register(type, resolve(makeGenericHelpers, input));
456
+ return bot;
457
+ },
458
+ async run(config) {
459
+ const collected = collectHandlers();
460
+ if (handlers.size === 0) {
461
+ console.warn("No handlers are defined for bot");
462
+ }
463
+ return runBot({
464
+ ...config,
465
+ mode: "single",
466
+ ...collected
467
+ });
468
+ },
469
+ webhook(config) {
470
+ const collected = collectHandlers();
471
+ return createWebhook({
472
+ ...config,
473
+ ...collected
474
+ });
475
+ }
476
+ };
477
+ return bot;
478
+ }
4032
479
  export {
4033
- BatchUpdateResult,
4034
- BotPollSettings,
4035
- BotPollSettingsTag,
4036
480
  BotResponse,
4037
- BotRunService,
4038
- BotTgClientTag,
4039
- BotUpdateHandlersTag,
4040
- HandleUpdateError,
481
+ createBot,
4041
482
  createBotContext,
4042
- createWebhookHandler,
483
+ createWebhook,
4043
484
  defineBot,
4044
485
  extractUpdate,
4045
- handleEntireBatch,
4046
- handleOneByOne,
4047
- handleOneUpdate,
4048
- handleUpdates,
4049
- launchBot,
4050
- runTgChatBot
486
+ runBot
4051
487
  };