miniflare 0.0.0-ecef68635 → 0.0.0-ee305dd67

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.
@@ -0,0 +1,1927 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __commonJS = (cb, mod) => function() {
7
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from == "object" || typeof from == "function")
11
+ for (let key of __getOwnPropNames(from))
12
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ return to;
14
+ };
15
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
16
+ // If the importer is in node compatibility mode or this is not an ESM
17
+ // file that has been converted to a CommonJS file using a Babel-
18
+ // compatible transform (i.e. "__esModule" has not been set), then set
19
+ // "default" to the CommonJS "module.exports" for node compatibility.
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
21
+ mod
22
+ ));
23
+
24
+ // ../../node_modules/.pnpm/heap-js@2.5.0/node_modules/heap-js/dist/heap-js.umd.js
25
+ var require_heap_js_umd = __commonJS({
26
+ "../../node_modules/.pnpm/heap-js@2.5.0/node_modules/heap-js/dist/heap-js.umd.js"(exports, module) {
27
+ (function(global, factory) {
28
+ typeof exports == "object" && typeof module < "u" ? factory(exports) : typeof define == "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis < "u" ? globalThis : global || self, factory(global.heap = {}));
29
+ })(exports, function(exports2) {
30
+ "use strict";
31
+ var __awaiter = function(thisArg, _arguments, P, generator) {
32
+ function adopt(value) {
33
+ return value instanceof P ? value : new P(function(resolve) {
34
+ resolve(value);
35
+ });
36
+ }
37
+ return new (P || (P = Promise))(function(resolve, reject) {
38
+ function fulfilled(value) {
39
+ try {
40
+ step(generator.next(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ }
45
+ function rejected(value) {
46
+ try {
47
+ step(generator.throw(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ }
52
+ function step(result) {
53
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
54
+ }
55
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
56
+ });
57
+ }, __generator$1 = function(thisArg, body) {
58
+ var _ = { label: 0, sent: function() {
59
+ if (t[0] & 1)
60
+ throw t[1];
61
+ return t[1];
62
+ }, trys: [], ops: [] }, f, y, t, g;
63
+ return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
64
+ return this;
65
+ }), g;
66
+ function verb(n2) {
67
+ return function(v) {
68
+ return step([n2, v]);
69
+ };
70
+ }
71
+ function step(op) {
72
+ if (f)
73
+ throw new TypeError("Generator is already executing.");
74
+ for (; g && (g = 0, op[0] && (_ = 0)), _; )
75
+ try {
76
+ if (f = 1, y && (t = op[0] & 2 ? y.return : op[0] ? y.throw || ((t = y.return) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
77
+ return t;
78
+ switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
79
+ case 0:
80
+ case 1:
81
+ t = op;
82
+ break;
83
+ case 4:
84
+ return _.label++, { value: op[1], done: !1 };
85
+ case 5:
86
+ _.label++, y = op[1], op = [0];
87
+ continue;
88
+ case 7:
89
+ op = _.ops.pop(), _.trys.pop();
90
+ continue;
91
+ default:
92
+ if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
93
+ _ = 0;
94
+ continue;
95
+ }
96
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
97
+ _.label = op[1];
98
+ break;
99
+ }
100
+ if (op[0] === 6 && _.label < t[1]) {
101
+ _.label = t[1], t = op;
102
+ break;
103
+ }
104
+ if (t && _.label < t[2]) {
105
+ _.label = t[2], _.ops.push(op);
106
+ break;
107
+ }
108
+ t[2] && _.ops.pop(), _.trys.pop();
109
+ continue;
110
+ }
111
+ op = body.call(thisArg, _);
112
+ } catch (e) {
113
+ op = [6, e], y = 0;
114
+ } finally {
115
+ f = t = 0;
116
+ }
117
+ if (op[0] & 5)
118
+ throw op[1];
119
+ return { value: op[0] ? op[1] : void 0, done: !0 };
120
+ }
121
+ }, __read$1 = function(o, n2) {
122
+ var m = typeof Symbol == "function" && o[Symbol.iterator];
123
+ if (!m)
124
+ return o;
125
+ var i = m.call(o), r2, ar = [], e;
126
+ try {
127
+ for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; )
128
+ ar.push(r2.value);
129
+ } catch (error) {
130
+ e = { error };
131
+ } finally {
132
+ try {
133
+ r2 && !r2.done && (m = i.return) && m.call(i);
134
+ } finally {
135
+ if (e)
136
+ throw e.error;
137
+ }
138
+ }
139
+ return ar;
140
+ }, __spreadArray$1 = function(to, from, pack) {
141
+ if (pack || arguments.length === 2)
142
+ for (var i = 0, l = from.length, ar; i < l; i++)
143
+ (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
144
+ return to.concat(ar || Array.prototype.slice.call(from));
145
+ }, __values = function(o) {
146
+ var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
147
+ if (m)
148
+ return m.call(o);
149
+ if (o && typeof o.length == "number")
150
+ return {
151
+ next: function() {
152
+ return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
153
+ }
154
+ };
155
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
156
+ }, HeapAsync = (
157
+ /** @class */
158
+ function() {
159
+ function HeapAsync2(compare) {
160
+ compare === void 0 && (compare = HeapAsync2.minComparator);
161
+ var _this = this;
162
+ this.compare = compare, this.heapArray = [], this._limit = 0, this.offer = this.add, this.element = this.peek, this.poll = this.pop, this._invertedCompare = function(a, b) {
163
+ return _this.compare(a, b).then(function(res) {
164
+ return -1 * res;
165
+ });
166
+ };
167
+ }
168
+ return HeapAsync2.getChildrenIndexOf = function(idx) {
169
+ return [idx * 2 + 1, idx * 2 + 2];
170
+ }, HeapAsync2.getParentIndexOf = function(idx) {
171
+ if (idx <= 0)
172
+ return -1;
173
+ var whichChildren = idx % 2 ? 1 : 2;
174
+ return Math.floor((idx - whichChildren) / 2);
175
+ }, HeapAsync2.getSiblingIndexOf = function(idx) {
176
+ if (idx <= 0)
177
+ return -1;
178
+ var whichChildren = idx % 2 ? 1 : -1;
179
+ return idx + whichChildren;
180
+ }, HeapAsync2.minComparator = function(a, b) {
181
+ return __awaiter(this, void 0, void 0, function() {
182
+ return __generator$1(this, function(_a) {
183
+ return a > b ? [2, 1] : a < b ? [2, -1] : [2, 0];
184
+ });
185
+ });
186
+ }, HeapAsync2.maxComparator = function(a, b) {
187
+ return __awaiter(this, void 0, void 0, function() {
188
+ return __generator$1(this, function(_a) {
189
+ return b > a ? [2, 1] : b < a ? [2, -1] : [2, 0];
190
+ });
191
+ });
192
+ }, HeapAsync2.minComparatorNumber = function(a, b) {
193
+ return __awaiter(this, void 0, void 0, function() {
194
+ return __generator$1(this, function(_a) {
195
+ return [2, a - b];
196
+ });
197
+ });
198
+ }, HeapAsync2.maxComparatorNumber = function(a, b) {
199
+ return __awaiter(this, void 0, void 0, function() {
200
+ return __generator$1(this, function(_a) {
201
+ return [2, b - a];
202
+ });
203
+ });
204
+ }, HeapAsync2.defaultIsEqual = function(a, b) {
205
+ return __awaiter(this, void 0, void 0, function() {
206
+ return __generator$1(this, function(_a) {
207
+ return [2, a === b];
208
+ });
209
+ });
210
+ }, HeapAsync2.print = function(heap) {
211
+ function deep(i2) {
212
+ var pi = HeapAsync2.getParentIndexOf(i2);
213
+ return Math.floor(Math.log2(pi + 1));
214
+ }
215
+ function repeat(str, times) {
216
+ for (var out = ""; times > 0; --times)
217
+ out += str;
218
+ return out;
219
+ }
220
+ for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
221
+ var i = deep(node) + 1;
222
+ node === 0 && (i = 0);
223
+ var nodeText = String(heap.get(node));
224
+ nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
225
+ }
226
+ return lines.map(function(line, i2) {
227
+ var times = Math.pow(2, maxLines - i2) - 1;
228
+ return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
229
+ var half = (maxLength - el.length) / 2;
230
+ return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
231
+ }).join(repeat(" ", times * maxLength));
232
+ }).join(`
233
+ `);
234
+ }, HeapAsync2.heapify = function(arr, compare) {
235
+ return __awaiter(this, void 0, void 0, function() {
236
+ var heap;
237
+ return __generator$1(this, function(_a) {
238
+ switch (_a.label) {
239
+ case 0:
240
+ return heap = new HeapAsync2(compare), heap.heapArray = arr, [4, heap.init()];
241
+ case 1:
242
+ return _a.sent(), [2, heap];
243
+ }
244
+ });
245
+ });
246
+ }, HeapAsync2.heappop = function(heapArr, compare) {
247
+ var heap = new HeapAsync2(compare);
248
+ return heap.heapArray = heapArr, heap.pop();
249
+ }, HeapAsync2.heappush = function(heapArr, item, compare) {
250
+ return __awaiter(this, void 0, void 0, function() {
251
+ var heap;
252
+ return __generator$1(this, function(_a) {
253
+ switch (_a.label) {
254
+ case 0:
255
+ return heap = new HeapAsync2(compare), heap.heapArray = heapArr, [4, heap.push(item)];
256
+ case 1:
257
+ return _a.sent(), [
258
+ 2
259
+ /*return*/
260
+ ];
261
+ }
262
+ });
263
+ });
264
+ }, HeapAsync2.heappushpop = function(heapArr, item, compare) {
265
+ var heap = new HeapAsync2(compare);
266
+ return heap.heapArray = heapArr, heap.pushpop(item);
267
+ }, HeapAsync2.heapreplace = function(heapArr, item, compare) {
268
+ var heap = new HeapAsync2(compare);
269
+ return heap.heapArray = heapArr, heap.replace(item);
270
+ }, HeapAsync2.heaptop = function(heapArr, n2, compare) {
271
+ n2 === void 0 && (n2 = 1);
272
+ var heap = new HeapAsync2(compare);
273
+ return heap.heapArray = heapArr, heap.top(n2);
274
+ }, HeapAsync2.heapbottom = function(heapArr, n2, compare) {
275
+ n2 === void 0 && (n2 = 1);
276
+ var heap = new HeapAsync2(compare);
277
+ return heap.heapArray = heapArr, heap.bottom(n2);
278
+ }, HeapAsync2.nlargest = function(n2, iterable, compare) {
279
+ return __awaiter(this, void 0, void 0, function() {
280
+ var heap;
281
+ return __generator$1(this, function(_a) {
282
+ switch (_a.label) {
283
+ case 0:
284
+ return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
285
+ case 1:
286
+ return _a.sent(), [2, heap.top(n2)];
287
+ }
288
+ });
289
+ });
290
+ }, HeapAsync2.nsmallest = function(n2, iterable, compare) {
291
+ return __awaiter(this, void 0, void 0, function() {
292
+ var heap;
293
+ return __generator$1(this, function(_a) {
294
+ switch (_a.label) {
295
+ case 0:
296
+ return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
297
+ case 1:
298
+ return _a.sent(), [2, heap.bottom(n2)];
299
+ }
300
+ });
301
+ });
302
+ }, HeapAsync2.prototype.add = function(element) {
303
+ return __awaiter(this, void 0, void 0, function() {
304
+ return __generator$1(this, function(_a) {
305
+ switch (_a.label) {
306
+ case 0:
307
+ return [4, this._sortNodeUp(this.heapArray.push(element) - 1)];
308
+ case 1:
309
+ return _a.sent(), this._applyLimit(), [2, !0];
310
+ }
311
+ });
312
+ });
313
+ }, HeapAsync2.prototype.addAll = function(elements) {
314
+ return __awaiter(this, void 0, void 0, function() {
315
+ var i, l, _a;
316
+ return __generator$1(this, function(_b) {
317
+ switch (_b.label) {
318
+ case 0:
319
+ i = this.length, (_a = this.heapArray).push.apply(_a, __spreadArray$1([], __read$1(elements), !1)), l = this.length, _b.label = 1;
320
+ case 1:
321
+ return i < l ? [4, this._sortNodeUp(i)] : [3, 4];
322
+ case 2:
323
+ _b.sent(), _b.label = 3;
324
+ case 3:
325
+ return ++i, [3, 1];
326
+ case 4:
327
+ return this._applyLimit(), [2, !0];
328
+ }
329
+ });
330
+ });
331
+ }, HeapAsync2.prototype.bottom = function(n2) {
332
+ return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
333
+ return __generator$1(this, function(_a) {
334
+ return this.heapArray.length === 0 || n2 <= 0 ? [2, []] : this.heapArray.length === 1 ? [2, [this.heapArray[0]]] : n2 >= this.heapArray.length ? [2, __spreadArray$1([], __read$1(this.heapArray), !1)] : [2, this._bottomN_push(~~n2)];
335
+ });
336
+ });
337
+ }, HeapAsync2.prototype.check = function() {
338
+ return __awaiter(this, void 0, void 0, function() {
339
+ var j, el, children, children_1, children_1_1, ch, e_1_1, e_1, _a;
340
+ return __generator$1(this, function(_b) {
341
+ switch (_b.label) {
342
+ case 0:
343
+ j = 0, _b.label = 1;
344
+ case 1:
345
+ if (!(j < this.heapArray.length))
346
+ return [3, 10];
347
+ el = this.heapArray[j], children = this.getChildrenOf(j), _b.label = 2;
348
+ case 2:
349
+ _b.trys.push([2, 7, 8, 9]), children_1 = (e_1 = void 0, __values(children)), children_1_1 = children_1.next(), _b.label = 3;
350
+ case 3:
351
+ return children_1_1.done ? [3, 6] : (ch = children_1_1.value, [4, this.compare(el, ch)]);
352
+ case 4:
353
+ if (_b.sent() > 0)
354
+ return [2, el];
355
+ _b.label = 5;
356
+ case 5:
357
+ return children_1_1 = children_1.next(), [3, 3];
358
+ case 6:
359
+ return [3, 9];
360
+ case 7:
361
+ return e_1_1 = _b.sent(), e_1 = { error: e_1_1 }, [3, 9];
362
+ case 8:
363
+ try {
364
+ children_1_1 && !children_1_1.done && (_a = children_1.return) && _a.call(children_1);
365
+ } finally {
366
+ if (e_1)
367
+ throw e_1.error;
368
+ }
369
+ return [
370
+ 7
371
+ /*endfinally*/
372
+ ];
373
+ case 9:
374
+ return ++j, [3, 1];
375
+ case 10:
376
+ return [
377
+ 2
378
+ /*return*/
379
+ ];
380
+ }
381
+ });
382
+ });
383
+ }, HeapAsync2.prototype.clear = function() {
384
+ this.heapArray = [];
385
+ }, HeapAsync2.prototype.clone = function() {
386
+ var cloned = new HeapAsync2(this.comparator());
387
+ return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
388
+ }, HeapAsync2.prototype.comparator = function() {
389
+ return this.compare;
390
+ }, HeapAsync2.prototype.contains = function(o, fn) {
391
+ return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
392
+ var _a, _b, el, e_2_1, e_2, _c;
393
+ return __generator$1(this, function(_d) {
394
+ switch (_d.label) {
395
+ case 0:
396
+ _d.trys.push([0, 5, 6, 7]), _a = __values(this.heapArray), _b = _a.next(), _d.label = 1;
397
+ case 1:
398
+ return _b.done ? [3, 4] : (el = _b.value, [4, fn(el, o)]);
399
+ case 2:
400
+ if (_d.sent())
401
+ return [2, !0];
402
+ _d.label = 3;
403
+ case 3:
404
+ return _b = _a.next(), [3, 1];
405
+ case 4:
406
+ return [3, 7];
407
+ case 5:
408
+ return e_2_1 = _d.sent(), e_2 = { error: e_2_1 }, [3, 7];
409
+ case 6:
410
+ try {
411
+ _b && !_b.done && (_c = _a.return) && _c.call(_a);
412
+ } finally {
413
+ if (e_2)
414
+ throw e_2.error;
415
+ }
416
+ return [
417
+ 7
418
+ /*endfinally*/
419
+ ];
420
+ case 7:
421
+ return [2, !1];
422
+ }
423
+ });
424
+ });
425
+ }, HeapAsync2.prototype.init = function(array) {
426
+ return __awaiter(this, void 0, void 0, function() {
427
+ var i;
428
+ return __generator$1(this, function(_a) {
429
+ switch (_a.label) {
430
+ case 0:
431
+ array && (this.heapArray = __spreadArray$1([], __read$1(array), !1)), i = Math.floor(this.heapArray.length), _a.label = 1;
432
+ case 1:
433
+ return i >= 0 ? [4, this._sortNodeDown(i)] : [3, 4];
434
+ case 2:
435
+ _a.sent(), _a.label = 3;
436
+ case 3:
437
+ return --i, [3, 1];
438
+ case 4:
439
+ return this._applyLimit(), [
440
+ 2
441
+ /*return*/
442
+ ];
443
+ }
444
+ });
445
+ });
446
+ }, HeapAsync2.prototype.isEmpty = function() {
447
+ return this.length === 0;
448
+ }, HeapAsync2.prototype.leafs = function() {
449
+ if (this.heapArray.length === 0)
450
+ return [];
451
+ var pi = HeapAsync2.getParentIndexOf(this.heapArray.length - 1);
452
+ return this.heapArray.slice(pi + 1);
453
+ }, Object.defineProperty(HeapAsync2.prototype, "length", {
454
+ /**
455
+ * Length of the heap.
456
+ * @return {Number}
457
+ */
458
+ get: function() {
459
+ return this.heapArray.length;
460
+ },
461
+ enumerable: !1,
462
+ configurable: !0
463
+ }), Object.defineProperty(HeapAsync2.prototype, "limit", {
464
+ /**
465
+ * Get length limit of the heap.
466
+ * @return {Number}
467
+ */
468
+ get: function() {
469
+ return this._limit;
470
+ },
471
+ /**
472
+ * Set length limit of the heap.
473
+ * @return {Number}
474
+ */
475
+ set: function(_l) {
476
+ this._limit = ~~_l, this._applyLimit();
477
+ },
478
+ enumerable: !1,
479
+ configurable: !0
480
+ }), HeapAsync2.prototype.peek = function() {
481
+ return this.heapArray[0];
482
+ }, HeapAsync2.prototype.pop = function() {
483
+ return __awaiter(this, void 0, void 0, function() {
484
+ var last;
485
+ return __generator$1(this, function(_a) {
486
+ return last = this.heapArray.pop(), this.length > 0 && last !== void 0 ? [2, this.replace(last)] : [2, last];
487
+ });
488
+ });
489
+ }, HeapAsync2.prototype.push = function() {
490
+ for (var elements = [], _i = 0; _i < arguments.length; _i++)
491
+ elements[_i] = arguments[_i];
492
+ return __awaiter(this, void 0, void 0, function() {
493
+ return __generator$1(this, function(_a) {
494
+ return elements.length < 1 ? [2, !1] : elements.length === 1 ? [2, this.add(elements[0])] : [2, this.addAll(elements)];
495
+ });
496
+ });
497
+ }, HeapAsync2.prototype.pushpop = function(element) {
498
+ return __awaiter(this, void 0, void 0, function() {
499
+ var _a;
500
+ return __generator$1(this, function(_b) {
501
+ switch (_b.label) {
502
+ case 0:
503
+ return [4, this.compare(this.heapArray[0], element)];
504
+ case 1:
505
+ return _b.sent() < 0 ? (_a = __read$1([this.heapArray[0], element], 2), element = _a[0], this.heapArray[0] = _a[1], [4, this._sortNodeDown(0)]) : [3, 3];
506
+ case 2:
507
+ _b.sent(), _b.label = 3;
508
+ case 3:
509
+ return [2, element];
510
+ }
511
+ });
512
+ });
513
+ }, HeapAsync2.prototype.remove = function(o, fn) {
514
+ return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
515
+ var idx, i;
516
+ return __generator$1(this, function(_a) {
517
+ switch (_a.label) {
518
+ case 0:
519
+ return this.length > 0 ? o !== void 0 ? [3, 2] : [4, this.pop()] : [3, 13];
520
+ case 1:
521
+ return _a.sent(), [2, !0];
522
+ case 2:
523
+ idx = -1, i = 0, _a.label = 3;
524
+ case 3:
525
+ return i < this.heapArray.length ? [4, fn(this.heapArray[i], o)] : [3, 6];
526
+ case 4:
527
+ if (_a.sent())
528
+ return idx = i, [3, 6];
529
+ _a.label = 5;
530
+ case 5:
531
+ return ++i, [3, 3];
532
+ case 6:
533
+ return idx >= 0 ? idx !== 0 ? [3, 8] : [4, this.pop()] : [3, 13];
534
+ case 7:
535
+ return _a.sent(), [3, 12];
536
+ case 8:
537
+ return idx !== this.length - 1 ? [3, 9] : (this.heapArray.pop(), [3, 12]);
538
+ case 9:
539
+ return this.heapArray.splice(idx, 1, this.heapArray.pop()), [4, this._sortNodeUp(idx)];
540
+ case 10:
541
+ return _a.sent(), [4, this._sortNodeDown(idx)];
542
+ case 11:
543
+ _a.sent(), _a.label = 12;
544
+ case 12:
545
+ return [2, !0];
546
+ case 13:
547
+ return [2, !1];
548
+ }
549
+ });
550
+ });
551
+ }, HeapAsync2.prototype.replace = function(element) {
552
+ return __awaiter(this, void 0, void 0, function() {
553
+ var peek;
554
+ return __generator$1(this, function(_a) {
555
+ switch (_a.label) {
556
+ case 0:
557
+ return peek = this.heapArray[0], this.heapArray[0] = element, [4, this._sortNodeDown(0)];
558
+ case 1:
559
+ return _a.sent(), [2, peek];
560
+ }
561
+ });
562
+ });
563
+ }, HeapAsync2.prototype.size = function() {
564
+ return this.length;
565
+ }, HeapAsync2.prototype.top = function(n2) {
566
+ return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
567
+ return __generator$1(this, function(_a) {
568
+ return this.heapArray.length === 0 || n2 <= 0 ? [2, []] : this.heapArray.length === 1 || n2 === 1 ? [2, [this.heapArray[0]]] : n2 >= this.heapArray.length ? [2, __spreadArray$1([], __read$1(this.heapArray), !1)] : [2, this._topN_push(~~n2)];
569
+ });
570
+ });
571
+ }, HeapAsync2.prototype.toArray = function() {
572
+ return __spreadArray$1([], __read$1(this.heapArray), !1);
573
+ }, HeapAsync2.prototype.toString = function() {
574
+ return this.heapArray.toString();
575
+ }, HeapAsync2.prototype.get = function(i) {
576
+ return this.heapArray[i];
577
+ }, HeapAsync2.prototype.getChildrenOf = function(idx) {
578
+ var _this = this;
579
+ return HeapAsync2.getChildrenIndexOf(idx).map(function(i) {
580
+ return _this.heapArray[i];
581
+ }).filter(function(e) {
582
+ return e !== void 0;
583
+ });
584
+ }, HeapAsync2.prototype.getParentOf = function(idx) {
585
+ var pi = HeapAsync2.getParentIndexOf(idx);
586
+ return this.heapArray[pi];
587
+ }, HeapAsync2.prototype[Symbol.iterator] = function() {
588
+ return __generator$1(this, function(_a) {
589
+ switch (_a.label) {
590
+ case 0:
591
+ return this.length ? [4, this.pop()] : [3, 2];
592
+ case 1:
593
+ return _a.sent(), [3, 0];
594
+ case 2:
595
+ return [
596
+ 2
597
+ /*return*/
598
+ ];
599
+ }
600
+ });
601
+ }, HeapAsync2.prototype.iterator = function() {
602
+ return this;
603
+ }, HeapAsync2.prototype._applyLimit = function() {
604
+ if (this._limit && this._limit < this.heapArray.length)
605
+ for (var rm = this.heapArray.length - this._limit; rm; )
606
+ this.heapArray.pop(), --rm;
607
+ }, HeapAsync2.prototype._bottomN_push = function(n2) {
608
+ return __awaiter(this, void 0, void 0, function() {
609
+ var bottomHeap, startAt, parentStartAt, indices, i, arr, i;
610
+ return __generator$1(this, function(_a) {
611
+ switch (_a.label) {
612
+ case 0:
613
+ return bottomHeap = new HeapAsync2(this.compare), bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), [4, bottomHeap.init()];
614
+ case 1:
615
+ for (_a.sent(), startAt = this.heapArray.length - 1 - n2, parentStartAt = HeapAsync2.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
616
+ indices.push(i);
617
+ arr = this.heapArray, _a.label = 2;
618
+ case 2:
619
+ return indices.length ? (i = indices.shift(), [4, this.compare(arr[i], bottomHeap.peek())]) : [3, 6];
620
+ case 3:
621
+ return _a.sent() > 0 ? [4, bottomHeap.replace(arr[i])] : [3, 5];
622
+ case 4:
623
+ _a.sent(), i % 2 && indices.push(HeapAsync2.getParentIndexOf(i)), _a.label = 5;
624
+ case 5:
625
+ return [3, 2];
626
+ case 6:
627
+ return [2, bottomHeap.toArray()];
628
+ }
629
+ });
630
+ });
631
+ }, HeapAsync2.prototype._moveNode = function(j, k) {
632
+ var _a;
633
+ _a = __read$1([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
634
+ }, HeapAsync2.prototype._sortNodeDown = function(i) {
635
+ return __awaiter(this, void 0, void 0, function() {
636
+ var moveIt, self2, getPotentialParent, childrenIdx, bestChildIndex, j, bestChild, _a, _this = this;
637
+ return __generator$1(this, function(_b) {
638
+ switch (_b.label) {
639
+ case 0:
640
+ moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j2) {
641
+ return __awaiter(_this, void 0, void 0, function() {
642
+ var _a2;
643
+ return __generator$1(this, function(_b2) {
644
+ switch (_b2.label) {
645
+ case 0:
646
+ return _a2 = this.heapArray.length > j2, _a2 ? [4, this.compare(this.heapArray[j2], this.heapArray[best])] : [3, 2];
647
+ case 1:
648
+ _a2 = _b2.sent() < 0, _b2.label = 2;
649
+ case 2:
650
+ return _a2 && (best = j2), [2, best];
651
+ }
652
+ });
653
+ });
654
+ }, _b.label = 1;
655
+ case 1:
656
+ if (!moveIt)
657
+ return [3, 8];
658
+ childrenIdx = HeapAsync2.getChildrenIndexOf(i), bestChildIndex = childrenIdx[0], j = 1, _b.label = 2;
659
+ case 2:
660
+ return j < childrenIdx.length ? [4, getPotentialParent(bestChildIndex, childrenIdx[j])] : [3, 5];
661
+ case 3:
662
+ bestChildIndex = _b.sent(), _b.label = 4;
663
+ case 4:
664
+ return ++j, [3, 2];
665
+ case 5:
666
+ return bestChild = this.heapArray[bestChildIndex], _a = typeof bestChild < "u", _a ? [4, this.compare(self2, bestChild)] : [3, 7];
667
+ case 6:
668
+ _a = _b.sent() > 0, _b.label = 7;
669
+ case 7:
670
+ return _a ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1, [3, 1];
671
+ case 8:
672
+ return [
673
+ 2
674
+ /*return*/
675
+ ];
676
+ }
677
+ });
678
+ });
679
+ }, HeapAsync2.prototype._sortNodeUp = function(i) {
680
+ return __awaiter(this, void 0, void 0, function() {
681
+ var moveIt, pi, _a;
682
+ return __generator$1(this, function(_b) {
683
+ switch (_b.label) {
684
+ case 0:
685
+ moveIt = i > 0, _b.label = 1;
686
+ case 1:
687
+ return moveIt ? (pi = HeapAsync2.getParentIndexOf(i), _a = pi >= 0, _a ? [4, this.compare(this.heapArray[pi], this.heapArray[i])] : [3, 3]) : [3, 4];
688
+ case 2:
689
+ _a = _b.sent() > 0, _b.label = 3;
690
+ case 3:
691
+ return _a ? (this._moveNode(i, pi), i = pi) : moveIt = !1, [3, 1];
692
+ case 4:
693
+ return [
694
+ 2
695
+ /*return*/
696
+ ];
697
+ }
698
+ });
699
+ });
700
+ }, HeapAsync2.prototype._topN_push = function(n2) {
701
+ return __awaiter(this, void 0, void 0, function() {
702
+ var topHeap, indices, arr, i;
703
+ return __generator$1(this, function(_a) {
704
+ switch (_a.label) {
705
+ case 0:
706
+ topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, indices = [0], arr = this.heapArray, _a.label = 1;
707
+ case 1:
708
+ return indices.length ? (i = indices.shift(), i < arr.length ? topHeap.length < n2 ? [4, topHeap.push(arr[i])] : [3, 3] : [3, 6]) : [3, 7];
709
+ case 2:
710
+ return _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), [3, 6];
711
+ case 3:
712
+ return [4, this.compare(arr[i], topHeap.peek())];
713
+ case 4:
714
+ return _a.sent() < 0 ? [4, topHeap.replace(arr[i])] : [3, 6];
715
+ case 5:
716
+ _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 6;
717
+ case 6:
718
+ return [3, 1];
719
+ case 7:
720
+ return [2, topHeap.toArray()];
721
+ }
722
+ });
723
+ });
724
+ }, HeapAsync2.prototype._topN_fill = function(n2) {
725
+ return __awaiter(this, void 0, void 0, function() {
726
+ var heapArray, topHeap, branch, indices, i, i;
727
+ return __generator$1(this, function(_a) {
728
+ switch (_a.label) {
729
+ case 0:
730
+ return heapArray = this.heapArray, topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), [4, topHeap.init()];
731
+ case 1:
732
+ for (_a.sent(), branch = HeapAsync2.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
733
+ indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i).filter(function(l) {
734
+ return l < heapArray.length;
735
+ })), !1));
736
+ (n2 - 1) % 2 && indices.push(n2), _a.label = 2;
737
+ case 2:
738
+ return indices.length ? (i = indices.shift(), i < heapArray.length ? [4, this.compare(heapArray[i], topHeap.peek())] : [3, 5]) : [3, 6];
739
+ case 3:
740
+ return _a.sent() < 0 ? [4, topHeap.replace(heapArray[i])] : [3, 5];
741
+ case 4:
742
+ _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 5;
743
+ case 5:
744
+ return [3, 2];
745
+ case 6:
746
+ return [2, topHeap.toArray()];
747
+ }
748
+ });
749
+ });
750
+ }, HeapAsync2.prototype._topN_heap = function(n2) {
751
+ return __awaiter(this, void 0, void 0, function() {
752
+ var topHeap, result, i, _a, _b;
753
+ return __generator$1(this, function(_c) {
754
+ switch (_c.label) {
755
+ case 0:
756
+ topHeap = this.clone(), result = [], i = 0, _c.label = 1;
757
+ case 1:
758
+ return i < n2 ? (_b = (_a = result).push, [4, topHeap.pop()]) : [3, 4];
759
+ case 2:
760
+ _b.apply(_a, [_c.sent()]), _c.label = 3;
761
+ case 3:
762
+ return ++i, [3, 1];
763
+ case 4:
764
+ return [2, result];
765
+ }
766
+ });
767
+ });
768
+ }, HeapAsync2.prototype._topIdxOf = function(list) {
769
+ return __awaiter(this, void 0, void 0, function() {
770
+ var idx, top, i, comp;
771
+ return __generator$1(this, function(_a) {
772
+ switch (_a.label) {
773
+ case 0:
774
+ if (!list.length)
775
+ return [2, -1];
776
+ idx = 0, top = list[idx], i = 1, _a.label = 1;
777
+ case 1:
778
+ return i < list.length ? [4, this.compare(list[i], top)] : [3, 4];
779
+ case 2:
780
+ comp = _a.sent(), comp < 0 && (idx = i, top = list[i]), _a.label = 3;
781
+ case 3:
782
+ return ++i, [3, 1];
783
+ case 4:
784
+ return [2, idx];
785
+ }
786
+ });
787
+ });
788
+ }, HeapAsync2.prototype._topOf = function() {
789
+ for (var list = [], _i = 0; _i < arguments.length; _i++)
790
+ list[_i] = arguments[_i];
791
+ return __awaiter(this, void 0, void 0, function() {
792
+ var heap;
793
+ return __generator$1(this, function(_a) {
794
+ switch (_a.label) {
795
+ case 0:
796
+ return heap = new HeapAsync2(this.compare), [4, heap.init(list)];
797
+ case 1:
798
+ return _a.sent(), [2, heap.peek()];
799
+ }
800
+ });
801
+ });
802
+ }, HeapAsync2;
803
+ }()
804
+ ), __generator = function(thisArg, body) {
805
+ var _ = { label: 0, sent: function() {
806
+ if (t[0] & 1)
807
+ throw t[1];
808
+ return t[1];
809
+ }, trys: [], ops: [] }, f, y, t, g;
810
+ return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
811
+ return this;
812
+ }), g;
813
+ function verb(n2) {
814
+ return function(v) {
815
+ return step([n2, v]);
816
+ };
817
+ }
818
+ function step(op) {
819
+ if (f)
820
+ throw new TypeError("Generator is already executing.");
821
+ for (; g && (g = 0, op[0] && (_ = 0)), _; )
822
+ try {
823
+ if (f = 1, y && (t = op[0] & 2 ? y.return : op[0] ? y.throw || ((t = y.return) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
824
+ return t;
825
+ switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
826
+ case 0:
827
+ case 1:
828
+ t = op;
829
+ break;
830
+ case 4:
831
+ return _.label++, { value: op[1], done: !1 };
832
+ case 5:
833
+ _.label++, y = op[1], op = [0];
834
+ continue;
835
+ case 7:
836
+ op = _.ops.pop(), _.trys.pop();
837
+ continue;
838
+ default:
839
+ if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
840
+ _ = 0;
841
+ continue;
842
+ }
843
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
844
+ _.label = op[1];
845
+ break;
846
+ }
847
+ if (op[0] === 6 && _.label < t[1]) {
848
+ _.label = t[1], t = op;
849
+ break;
850
+ }
851
+ if (t && _.label < t[2]) {
852
+ _.label = t[2], _.ops.push(op);
853
+ break;
854
+ }
855
+ t[2] && _.ops.pop(), _.trys.pop();
856
+ continue;
857
+ }
858
+ op = body.call(thisArg, _);
859
+ } catch (e) {
860
+ op = [6, e], y = 0;
861
+ } finally {
862
+ f = t = 0;
863
+ }
864
+ if (op[0] & 5)
865
+ throw op[1];
866
+ return { value: op[0] ? op[1] : void 0, done: !0 };
867
+ }
868
+ }, __read = function(o, n2) {
869
+ var m = typeof Symbol == "function" && o[Symbol.iterator];
870
+ if (!m)
871
+ return o;
872
+ var i = m.call(o), r2, ar = [], e;
873
+ try {
874
+ for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; )
875
+ ar.push(r2.value);
876
+ } catch (error) {
877
+ e = { error };
878
+ } finally {
879
+ try {
880
+ r2 && !r2.done && (m = i.return) && m.call(i);
881
+ } finally {
882
+ if (e)
883
+ throw e.error;
884
+ }
885
+ }
886
+ return ar;
887
+ }, __spreadArray = function(to, from, pack) {
888
+ if (pack || arguments.length === 2)
889
+ for (var i = 0, l = from.length, ar; i < l; i++)
890
+ (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
891
+ return to.concat(ar || Array.prototype.slice.call(from));
892
+ }, toInt = function(n2) {
893
+ return ~~n2;
894
+ }, Heap2 = (
895
+ /** @class */
896
+ function() {
897
+ function Heap3(compare) {
898
+ compare === void 0 && (compare = Heap3.minComparator);
899
+ var _this = this;
900
+ this.compare = compare, this.heapArray = [], this._limit = 0, this.offer = this.add, this.element = this.peek, this.poll = this.pop, this.removeAll = this.clear, this._invertedCompare = function(a, b) {
901
+ return -1 * _this.compare(a, b);
902
+ };
903
+ }
904
+ return Heap3.getChildrenIndexOf = function(idx) {
905
+ return [idx * 2 + 1, idx * 2 + 2];
906
+ }, Heap3.getParentIndexOf = function(idx) {
907
+ if (idx <= 0)
908
+ return -1;
909
+ var whichChildren = idx % 2 ? 1 : 2;
910
+ return Math.floor((idx - whichChildren) / 2);
911
+ }, Heap3.getSiblingIndexOf = function(idx) {
912
+ if (idx <= 0)
913
+ return -1;
914
+ var whichChildren = idx % 2 ? 1 : -1;
915
+ return idx + whichChildren;
916
+ }, Heap3.minComparator = function(a, b) {
917
+ return a > b ? 1 : a < b ? -1 : 0;
918
+ }, Heap3.maxComparator = function(a, b) {
919
+ return b > a ? 1 : b < a ? -1 : 0;
920
+ }, Heap3.minComparatorNumber = function(a, b) {
921
+ return a - b;
922
+ }, Heap3.maxComparatorNumber = function(a, b) {
923
+ return b - a;
924
+ }, Heap3.defaultIsEqual = function(a, b) {
925
+ return a === b;
926
+ }, Heap3.print = function(heap) {
927
+ function deep(i2) {
928
+ var pi = Heap3.getParentIndexOf(i2);
929
+ return Math.floor(Math.log2(pi + 1));
930
+ }
931
+ function repeat(str, times) {
932
+ for (var out = ""; times > 0; --times)
933
+ out += str;
934
+ return out;
935
+ }
936
+ for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
937
+ var i = deep(node) + 1;
938
+ node === 0 && (i = 0);
939
+ var nodeText = String(heap.get(node));
940
+ nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
941
+ }
942
+ return lines.map(function(line, i2) {
943
+ var times = Math.pow(2, maxLines - i2) - 1;
944
+ return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
945
+ var half = (maxLength - el.length) / 2;
946
+ return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
947
+ }).join(repeat(" ", times * maxLength));
948
+ }).join(`
949
+ `);
950
+ }, Heap3.heapify = function(arr, compare) {
951
+ var heap = new Heap3(compare);
952
+ return heap.heapArray = arr, heap.init(), heap;
953
+ }, Heap3.heappop = function(heapArr, compare) {
954
+ var heap = new Heap3(compare);
955
+ return heap.heapArray = heapArr, heap.pop();
956
+ }, Heap3.heappush = function(heapArr, item, compare) {
957
+ var heap = new Heap3(compare);
958
+ heap.heapArray = heapArr, heap.push(item);
959
+ }, Heap3.heappushpop = function(heapArr, item, compare) {
960
+ var heap = new Heap3(compare);
961
+ return heap.heapArray = heapArr, heap.pushpop(item);
962
+ }, Heap3.heapreplace = function(heapArr, item, compare) {
963
+ var heap = new Heap3(compare);
964
+ return heap.heapArray = heapArr, heap.replace(item);
965
+ }, Heap3.heaptop = function(heapArr, n2, compare) {
966
+ n2 === void 0 && (n2 = 1);
967
+ var heap = new Heap3(compare);
968
+ return heap.heapArray = heapArr, heap.top(n2);
969
+ }, Heap3.heapbottom = function(heapArr, n2, compare) {
970
+ n2 === void 0 && (n2 = 1);
971
+ var heap = new Heap3(compare);
972
+ return heap.heapArray = heapArr, heap.bottom(n2);
973
+ }, Heap3.nlargest = function(n2, iterable, compare) {
974
+ var heap = new Heap3(compare);
975
+ return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.top(n2);
976
+ }, Heap3.nsmallest = function(n2, iterable, compare) {
977
+ var heap = new Heap3(compare);
978
+ return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.bottom(n2);
979
+ }, Heap3.prototype.add = function(element) {
980
+ return this._sortNodeUp(this.heapArray.push(element) - 1), this._applyLimit(), !0;
981
+ }, Heap3.prototype.addAll = function(elements) {
982
+ var _a, i = this.length;
983
+ (_a = this.heapArray).push.apply(_a, __spreadArray([], __read(elements), !1));
984
+ for (var l = this.length; i < l; ++i)
985
+ this._sortNodeUp(i);
986
+ return this._applyLimit(), !0;
987
+ }, Heap3.prototype.bottom = function(n2) {
988
+ return n2 === void 0 && (n2 = 1), this.heapArray.length === 0 || n2 <= 0 ? [] : this.heapArray.length === 1 ? [this.heapArray[0]] : n2 >= this.heapArray.length ? __spreadArray([], __read(this.heapArray), !1) : this._bottomN_push(~~n2);
989
+ }, Heap3.prototype.check = function() {
990
+ var _this = this;
991
+ return this.heapArray.find(function(el, j) {
992
+ return !!_this.getChildrenOf(j).find(function(ch) {
993
+ return _this.compare(el, ch) > 0;
994
+ });
995
+ });
996
+ }, Heap3.prototype.clear = function() {
997
+ this.heapArray = [];
998
+ }, Heap3.prototype.clone = function() {
999
+ var cloned = new Heap3(this.comparator());
1000
+ return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
1001
+ }, Heap3.prototype.comparator = function() {
1002
+ return this.compare;
1003
+ }, Heap3.prototype.contains = function(o, callbackFn) {
1004
+ return callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.indexOf(o, callbackFn) !== -1;
1005
+ }, Heap3.prototype.init = function(array) {
1006
+ array && (this.heapArray = __spreadArray([], __read(array), !1));
1007
+ for (var i = Math.floor(this.heapArray.length); i >= 0; --i)
1008
+ this._sortNodeDown(i);
1009
+ this._applyLimit();
1010
+ }, Heap3.prototype.isEmpty = function() {
1011
+ return this.length === 0;
1012
+ }, Heap3.prototype.indexOf = function(element, callbackFn) {
1013
+ if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
1014
+ return -1;
1015
+ for (var indexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
1016
+ var currentElement = this.heapArray[currentIndex];
1017
+ if (callbackFn(currentElement, element))
1018
+ return currentIndex;
1019
+ this.compare(currentElement, element) <= 0 && indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1)), currentIndex = indexes.shift() || this.heapArray.length;
1020
+ }
1021
+ return -1;
1022
+ }, Heap3.prototype.indexOfEvery = function(element, callbackFn) {
1023
+ if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
1024
+ return [];
1025
+ for (var indexes = [], foundIndexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
1026
+ var currentElement = this.heapArray[currentIndex];
1027
+ callbackFn(currentElement, element) ? (foundIndexes.push(currentIndex), indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1))) : this.compare(currentElement, element) <= 0 && indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1)), currentIndex = indexes.shift() || this.heapArray.length;
1028
+ }
1029
+ return foundIndexes;
1030
+ }, Heap3.prototype.leafs = function() {
1031
+ if (this.heapArray.length === 0)
1032
+ return [];
1033
+ var pi = Heap3.getParentIndexOf(this.heapArray.length - 1);
1034
+ return this.heapArray.slice(pi + 1);
1035
+ }, Object.defineProperty(Heap3.prototype, "length", {
1036
+ /**
1037
+ * Length of the heap. Aliases: {@link size}.
1038
+ * @return {Number}
1039
+ * @see size
1040
+ */
1041
+ get: function() {
1042
+ return this.heapArray.length;
1043
+ },
1044
+ enumerable: !1,
1045
+ configurable: !0
1046
+ }), Object.defineProperty(Heap3.prototype, "limit", {
1047
+ /**
1048
+ * Get length limit of the heap.
1049
+ * Use {@link setLimit} or {@link limit} to set the limit.
1050
+ * @return {Number}
1051
+ * @see setLimit
1052
+ */
1053
+ get: function() {
1054
+ return this._limit;
1055
+ },
1056
+ /**
1057
+ * Set length limit of the heap. Same as using {@link setLimit}.
1058
+ * @description If the heap is longer than the limit, the needed amount of leafs are removed.
1059
+ * @param {Number} _l Limit, defaults to 0 (no limit). Negative, Infinity, or NaN values set the limit to 0.
1060
+ * @see setLimit
1061
+ */
1062
+ set: function(_l) {
1063
+ _l < 0 || isNaN(_l) ? this._limit = 0 : this._limit = ~~_l, this._applyLimit();
1064
+ },
1065
+ enumerable: !1,
1066
+ configurable: !0
1067
+ }), Heap3.prototype.setLimit = function(_l) {
1068
+ return this.limit = _l, _l < 0 || isNaN(_l) ? NaN : this._limit;
1069
+ }, Heap3.prototype.peek = function() {
1070
+ return this.heapArray[0];
1071
+ }, Heap3.prototype.pop = function() {
1072
+ var last = this.heapArray.pop();
1073
+ return this.length > 0 && last !== void 0 ? this.replace(last) : last;
1074
+ }, Heap3.prototype.push = function() {
1075
+ for (var elements = [], _i = 0; _i < arguments.length; _i++)
1076
+ elements[_i] = arguments[_i];
1077
+ return elements.length < 1 ? !1 : elements.length === 1 ? this.add(elements[0]) : this.addAll(elements);
1078
+ }, Heap3.prototype.pushpop = function(element) {
1079
+ var _a;
1080
+ return this.compare(this.heapArray[0], element) < 0 && (_a = __read([this.heapArray[0], element], 2), element = _a[0], this.heapArray[0] = _a[1], this._sortNodeDown(0)), element;
1081
+ }, Heap3.prototype.remove = function(o, callbackFn) {
1082
+ if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.length > 0) {
1083
+ if (o === void 0)
1084
+ return this.pop(), !0;
1085
+ var idx = this.indexOf(o, callbackFn);
1086
+ if (idx >= 0)
1087
+ return idx === 0 ? this.pop() : idx === this.length - 1 ? this.heapArray.pop() : (this.heapArray.splice(idx, 1, this.heapArray.pop()), this._sortNodeUp(idx), this._sortNodeDown(idx)), !0;
1088
+ }
1089
+ return !1;
1090
+ }, Heap3.prototype.replace = function(element) {
1091
+ var peek = this.heapArray[0];
1092
+ return this.heapArray[0] = element, this._sortNodeDown(0), peek;
1093
+ }, Heap3.prototype.size = function() {
1094
+ return this.length;
1095
+ }, Heap3.prototype.top = function(n2) {
1096
+ return n2 === void 0 && (n2 = 1), this.heapArray.length === 0 || n2 <= 0 ? [] : this.heapArray.length === 1 || n2 === 1 ? [this.heapArray[0]] : n2 >= this.heapArray.length ? __spreadArray([], __read(this.heapArray), !1) : this._topN_push(~~n2);
1097
+ }, Heap3.prototype.toArray = function() {
1098
+ return __spreadArray([], __read(this.heapArray), !1);
1099
+ }, Heap3.prototype.toString = function() {
1100
+ return this.heapArray.toString();
1101
+ }, Heap3.prototype.get = function(i) {
1102
+ return this.heapArray[i];
1103
+ }, Heap3.prototype.getChildrenOf = function(idx) {
1104
+ var _this = this;
1105
+ return Heap3.getChildrenIndexOf(idx).map(function(i) {
1106
+ return _this.heapArray[i];
1107
+ }).filter(function(e) {
1108
+ return e !== void 0;
1109
+ });
1110
+ }, Heap3.prototype.getParentOf = function(idx) {
1111
+ var pi = Heap3.getParentIndexOf(idx);
1112
+ return this.heapArray[pi];
1113
+ }, Heap3.prototype[Symbol.iterator] = function() {
1114
+ return __generator(this, function(_a) {
1115
+ switch (_a.label) {
1116
+ case 0:
1117
+ return this.length ? [4, this.pop()] : [3, 2];
1118
+ case 1:
1119
+ return _a.sent(), [3, 0];
1120
+ case 2:
1121
+ return [
1122
+ 2
1123
+ /*return*/
1124
+ ];
1125
+ }
1126
+ });
1127
+ }, Heap3.prototype.iterator = function() {
1128
+ return this.toArray();
1129
+ }, Heap3.prototype._applyLimit = function() {
1130
+ if (this._limit > 0 && this._limit < this.heapArray.length)
1131
+ for (var rm = this.heapArray.length - this._limit; rm; )
1132
+ this.heapArray.pop(), --rm;
1133
+ }, Heap3.prototype._bottomN_push = function(n2) {
1134
+ var bottomHeap = new Heap3(this.compare);
1135
+ bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), bottomHeap.init();
1136
+ for (var startAt = this.heapArray.length - 1 - n2, parentStartAt = Heap3.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
1137
+ indices.push(i);
1138
+ for (var arr = this.heapArray; indices.length; ) {
1139
+ var i = indices.shift();
1140
+ this.compare(arr[i], bottomHeap.peek()) > 0 && (bottomHeap.replace(arr[i]), i % 2 && indices.push(Heap3.getParentIndexOf(i)));
1141
+ }
1142
+ return bottomHeap.toArray();
1143
+ }, Heap3.prototype._moveNode = function(j, k) {
1144
+ var _a;
1145
+ _a = __read([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
1146
+ }, Heap3.prototype._sortNodeDown = function(i) {
1147
+ for (var _this = this, moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j) {
1148
+ return _this.heapArray.length > j && _this.compare(_this.heapArray[j], _this.heapArray[best]) < 0 && (best = j), best;
1149
+ }; moveIt; ) {
1150
+ var childrenIdx = Heap3.getChildrenIndexOf(i), bestChildIndex = childrenIdx.reduce(getPotentialParent, childrenIdx[0]), bestChild = this.heapArray[bestChildIndex];
1151
+ typeof bestChild < "u" && this.compare(self2, bestChild) > 0 ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1;
1152
+ }
1153
+ }, Heap3.prototype._sortNodeUp = function(i) {
1154
+ for (var moveIt = i > 0; moveIt; ) {
1155
+ var pi = Heap3.getParentIndexOf(i);
1156
+ pi >= 0 && this.compare(this.heapArray[pi], this.heapArray[i]) > 0 ? (this._moveNode(i, pi), i = pi) : moveIt = !1;
1157
+ }
1158
+ }, Heap3.prototype._topN_push = function(n2) {
1159
+ var topHeap = new Heap3(this._invertedCompare);
1160
+ topHeap.limit = n2;
1161
+ for (var indices = [0], arr = this.heapArray; indices.length; ) {
1162
+ var i = indices.shift();
1163
+ i < arr.length && (topHeap.length < n2 ? (topHeap.push(arr[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1))) : this.compare(arr[i], topHeap.peek()) < 0 && (topHeap.replace(arr[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1))));
1164
+ }
1165
+ return topHeap.toArray();
1166
+ }, Heap3.prototype._topN_fill = function(n2) {
1167
+ var heapArray = this.heapArray, topHeap = new Heap3(this._invertedCompare);
1168
+ topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), topHeap.init();
1169
+ for (var branch = Heap3.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
1170
+ indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i).filter(function(l) {
1171
+ return l < heapArray.length;
1172
+ })), !1));
1173
+ for ((n2 - 1) % 2 && indices.push(n2); indices.length; ) {
1174
+ var i = indices.shift();
1175
+ i < heapArray.length && this.compare(heapArray[i], topHeap.peek()) < 0 && (topHeap.replace(heapArray[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1)));
1176
+ }
1177
+ return topHeap.toArray();
1178
+ }, Heap3.prototype._topN_heap = function(n2) {
1179
+ for (var topHeap = this.clone(), result = [], i = 0; i < n2; ++i)
1180
+ result.push(topHeap.pop());
1181
+ return result;
1182
+ }, Heap3.prototype._topIdxOf = function(list) {
1183
+ if (!list.length)
1184
+ return -1;
1185
+ for (var idx = 0, top = list[idx], i = 1; i < list.length; ++i) {
1186
+ var comp = this.compare(list[i], top);
1187
+ comp < 0 && (idx = i, top = list[i]);
1188
+ }
1189
+ return idx;
1190
+ }, Heap3.prototype._topOf = function() {
1191
+ for (var list = [], _i = 0; _i < arguments.length; _i++)
1192
+ list[_i] = arguments[_i];
1193
+ var heap = new Heap3(this.compare);
1194
+ return heap.init(list), heap.peek();
1195
+ }, Heap3;
1196
+ }()
1197
+ );
1198
+ exports2.Heap = Heap2, exports2.HeapAsync = HeapAsync, exports2.default = Heap2, exports2.toInt = toInt, Object.defineProperty(exports2, "__esModule", { value: !0 });
1199
+ });
1200
+ }
1201
+ });
1202
+
1203
+ // ../workflows-shared/src/binding.ts
1204
+ import { RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
1205
+
1206
+ // ../workflows-shared/src/instance.ts
1207
+ var INSTANCE_METADATA = "INSTANCE_METADATA";
1208
+ function instanceStatusName(status) {
1209
+ switch (status) {
1210
+ case 0 /* Queued */:
1211
+ return "queued";
1212
+ case 1 /* Running */:
1213
+ return "running";
1214
+ case 2 /* Paused */:
1215
+ return "paused";
1216
+ case 3 /* Errored */:
1217
+ return "errored";
1218
+ case 4 /* Terminated */:
1219
+ return "terminated";
1220
+ case 5 /* Complete */:
1221
+ return "complete";
1222
+ default:
1223
+ return "unknown";
1224
+ }
1225
+ }
1226
+
1227
+ // ../workflows-shared/src/binding.ts
1228
+ var WorkflowBinding = class extends WorkerEntrypoint {
1229
+ async create({
1230
+ id,
1231
+ params
1232
+ }) {
1233
+ id || (id = crypto.randomUUID());
1234
+ let stubId = this.env.ENGINE.idFromName(id), stub = this.env.ENGINE.get(stubId);
1235
+ return stub.init(
1236
+ 0,
1237
+ // accountId: number,
1238
+ {},
1239
+ // workflow: DatabaseWorkflow,
1240
+ {},
1241
+ // version: DatabaseVersion,
1242
+ { id },
1243
+ // instance: DatabaseInstance,
1244
+ {
1245
+ timestamp: /* @__PURE__ */ new Date(),
1246
+ payload: params
1247
+ }
1248
+ ), new WorkflowHandle(id, stub);
1249
+ }
1250
+ async get(id) {
1251
+ let stubId = this.env.ENGINE.idFromName(id), stub = this.env.ENGINE.get(stubId);
1252
+ return new WorkflowHandle(id, stub);
1253
+ }
1254
+ }, WorkflowHandle = class extends RpcTarget {
1255
+ constructor(id, stub) {
1256
+ super();
1257
+ this.id = id;
1258
+ this.stub = stub;
1259
+ }
1260
+ async pause() {
1261
+ throw new Error("Not implemented yet");
1262
+ }
1263
+ async resume() {
1264
+ throw new Error("Not implemented yet");
1265
+ }
1266
+ async terminate() {
1267
+ throw new Error("Not implemented yet");
1268
+ }
1269
+ async restart() {
1270
+ throw new Error("Not implemented yet");
1271
+ }
1272
+ async status() {
1273
+ let status = await this.stub.getStatus(0, this.id), { logs } = await this.stub.readLogs(), output = logs.filter(
1274
+ // @ts-expect-error TODO: Fix this
1275
+ (log) => log.event === 6 /* STEP_SUCCESS */
1276
+ ).map((log) => log.metadata.result);
1277
+ return { status: instanceStatusName(status), output };
1278
+ }
1279
+ };
1280
+
1281
+ // ../workflows-shared/src/engine.ts
1282
+ import { DurableObject } from "cloudflare:workers";
1283
+
1284
+ // ../workflows-shared/src/context.ts
1285
+ import { RpcTarget as RpcTarget2 } from "cloudflare:workers";
1286
+
1287
+ // ../../node_modules/.pnpm/itty-time@1.0.6/node_modules/itty-time/index.mjs
1288
+ var n = { year: 315576e5, month: 2592e6, week: 6048e5, day: 864e5, hour: 36e5, minute: 6e4, second: 1e3, m: 1 }, r = (e) => {
1289
+ if (+e)
1290
+ return +e;
1291
+ let [, t, r2] = e.match(/^([^ ]+) +(\w\w*?)s?$/) || [];
1292
+ return +t * (n[r2] || 1);
1293
+ };
1294
+
1295
+ // ../workflows-shared/src/lib/cache.ts
1296
+ async function computeHash(value) {
1297
+ let msgUint8 = new TextEncoder().encode(value), hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8);
1298
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
1299
+ }
1300
+
1301
+ // ../workflows-shared/src/lib/errors.ts
1302
+ var WorkflowTimeoutError = class extends Error {
1303
+ name = "WorkflowTimeoutError";
1304
+ }, WorkflowInternalError = class extends Error {
1305
+ name = "WorkflowInternalError";
1306
+ }, WorkflowFatalError = class extends Error {
1307
+ name = "WorkflowFatalError";
1308
+ toJSON() {
1309
+ return {
1310
+ name: this.name,
1311
+ message: this.message
1312
+ };
1313
+ }
1314
+ };
1315
+
1316
+ // ../workflows-shared/src/lib/retries.ts
1317
+ function calcRetryDuration(config, stepState) {
1318
+ let { attemptedCount: attemptCount } = stepState, { retries } = config, delay = r(retries.delay);
1319
+ switch (retries.backoff) {
1320
+ case "exponential":
1321
+ return delay * Math.pow(2, attemptCount - 1);
1322
+ case "linear":
1323
+ return delay * attemptCount;
1324
+ case "constant":
1325
+ default:
1326
+ return delay;
1327
+ }
1328
+ }
1329
+
1330
+ // ../workflows-shared/src/lib/validators.ts
1331
+ var CONTROL_CHAR_REGEX = new RegExp("[\0-]");
1332
+ function validateStepName(string) {
1333
+ return string.length > 256 ? !1 : !CONTROL_CHAR_REGEX.test(string);
1334
+ }
1335
+
1336
+ // ../workflows-shared/src/context.ts
1337
+ var defaultConfig = {
1338
+ retries: {
1339
+ limit: 5,
1340
+ delay: 1e3,
1341
+ backoff: "constant"
1342
+ },
1343
+ timeout: "15 minutes"
1344
+ }, Context = class extends RpcTarget2 {
1345
+ #engine;
1346
+ #state;
1347
+ #counters = /* @__PURE__ */ new Map();
1348
+ constructor(engine, state) {
1349
+ super(), this.#engine = engine, this.#state = state;
1350
+ }
1351
+ #getCount(name) {
1352
+ let val = this.#counters.get(name) ?? 0;
1353
+ return val++, this.#counters.set(name, val), val;
1354
+ }
1355
+ async do(name, configOrCallback, callback) {
1356
+ let closure, stepConfig;
1357
+ if (callback ? (closure = callback, stepConfig = configOrCallback) : (closure = configOrCallback, stepConfig = {}), !validateStepName(name)) {
1358
+ let error = new WorkflowFatalError(
1359
+ `Step name "${name}" exceeds max length (${256} chars) or invalid characters found`
1360
+ );
1361
+ throw error.isUserError = !0, error;
1362
+ }
1363
+ let config = {
1364
+ ...defaultConfig,
1365
+ ...stepConfig,
1366
+ retries: {
1367
+ ...defaultConfig.retries,
1368
+ ...stepConfig.retries
1369
+ }
1370
+ }, hash = await computeHash(name), count = this.#getCount("run-" + name), cacheKey = `${hash}-${count}`, valueKey = `${cacheKey}-value`, configKey = `${cacheKey}-config`, stepNameWithCounter = `${name}-${count}`, stepStateKey = `${cacheKey}-metadata`, maybeMap = await this.#state.storage.get([valueKey, configKey]), maybeResult = maybeMap.get(valueKey);
1371
+ if (maybeResult)
1372
+ return maybeResult.value;
1373
+ maybeMap.has(configKey) ? config = maybeMap.get(configKey) : await this.#state.storage.put(configKey, config);
1374
+ let attemptLogs = this.#engine.readLogsFromStep(cacheKey).filter(
1375
+ (val) => [
1376
+ 11 /* ATTEMPT_SUCCESS */,
1377
+ 12 /* ATTEMPT_FAILURE */,
1378
+ 10 /* ATTEMPT_START */
1379
+ ].includes(val.event)
1380
+ );
1381
+ if (attemptLogs.length > 0 && attemptLogs.at(-1)?.event === 10 /* ATTEMPT_START */) {
1382
+ let stepState = await this.#state.storage.get(
1383
+ stepStateKey
1384
+ ) ?? {
1385
+ attemptedCount: 1
1386
+ }, priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, timeoutEntryPQ = this.#engine.priorityQueue.getFirst(
1387
+ (a) => a.hash === priorityQueueHash && a.type === "timeout"
1388
+ );
1389
+ timeoutEntryPQ !== void 0 && this.#engine.priorityQueue.remove(timeoutEntryPQ), this.#engine.writeLog(
1390
+ 12 /* ATTEMPT_FAILURE */,
1391
+ cacheKey,
1392
+ stepNameWithCounter,
1393
+ {
1394
+ attempt: stepState.attemptedCount,
1395
+ error: {
1396
+ name: "WorkflowInternalError",
1397
+ message: "Attempt failed due to internal workflows error"
1398
+ }
1399
+ }
1400
+ ), await this.#state.storage.put(stepStateKey, stepState);
1401
+ }
1402
+ let doWrapper = async (doWrapperClosure) => {
1403
+ let stepState = await this.#state.storage.get(
1404
+ stepStateKey
1405
+ ) ?? {
1406
+ attemptedCount: 0
1407
+ };
1408
+ if (await this.#engine.timeoutHandler.acquire(this.#engine), stepState.attemptedCount == 0)
1409
+ this.#engine.writeLog(
1410
+ 5 /* STEP_START */,
1411
+ cacheKey,
1412
+ stepNameWithCounter,
1413
+ {
1414
+ config
1415
+ }
1416
+ );
1417
+ else {
1418
+ let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, retryEntryPQ = this.#engine.priorityQueue.getFirst(
1419
+ (a) => a.hash === priorityQueueHash && a.type === "retry"
1420
+ );
1421
+ retryEntryPQ !== void 0 && (await this.#engine.timeoutHandler.release(this.#engine), await scheduler.wait(retryEntryPQ.targetTimestamp - Date.now()), await this.#engine.timeoutHandler.acquire(this.#engine), this.#engine.priorityQueue.remove({
1422
+ hash: priorityQueueHash,
1423
+ type: "retry"
1424
+ }));
1425
+ }
1426
+ let result, instanceMetadata = await this.#state.storage.get(INSTANCE_METADATA);
1427
+ if (!instanceMetadata)
1428
+ throw new Error("instanceMetadata is undefined");
1429
+ let { accountId, instance } = instanceMetadata;
1430
+ try {
1431
+ let timeoutPromise = async () => {
1432
+ let priorityQueueHash2 = `${cacheKey}-${stepState.attemptedCount}`, timeout = r(config.timeout);
1433
+ throw await this.#engine.priorityQueue.add({
1434
+ hash: priorityQueueHash2,
1435
+ targetTimestamp: Date.now() + timeout,
1436
+ type: "timeout"
1437
+ }), await scheduler.wait(timeout), await this.#engine.priorityQueue.remove({
1438
+ hash: priorityQueueHash2,
1439
+ type: "timeout"
1440
+ }), new WorkflowTimeoutError(
1441
+ `Execution timed out after ${timeout}ms`
1442
+ );
1443
+ };
1444
+ this.#engine.writeLog(
1445
+ 10 /* ATTEMPT_START */,
1446
+ cacheKey,
1447
+ stepNameWithCounter,
1448
+ {
1449
+ attempt: stepState.attemptedCount + 1
1450
+ }
1451
+ ), stepState.attemptedCount++, await this.#state.storage.put(stepStateKey, stepState);
1452
+ let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`;
1453
+ result = await Promise.race([doWrapperClosure(), timeoutPromise()]), await this.#engine.priorityQueue.remove({
1454
+ hash: priorityQueueHash,
1455
+ type: "timeout"
1456
+ });
1457
+ try {
1458
+ await this.#state.storage.put(valueKey, { value: result });
1459
+ } catch (e) {
1460
+ if (e instanceof Error && e.name === "DataCloneError")
1461
+ this.#engine.writeLog(
1462
+ 12 /* ATTEMPT_FAILURE */,
1463
+ cacheKey,
1464
+ stepNameWithCounter,
1465
+ {
1466
+ attempt: stepState.attemptedCount,
1467
+ error: new WorkflowFatalError(
1468
+ `Value returned from step "${name}" is not serialisable`
1469
+ )
1470
+ }
1471
+ ), this.#engine.writeLog(
1472
+ 7 /* STEP_FAILURE */,
1473
+ cacheKey,
1474
+ stepNameWithCounter,
1475
+ {}
1476
+ ), this.#engine.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
1477
+ error: new WorkflowFatalError(
1478
+ `The execution of the Workflow instance was terminated, as the step "${name}" returned a value which is not serialisable`
1479
+ )
1480
+ }), await this.#engine.setStatus(
1481
+ accountId,
1482
+ instance.id,
1483
+ 3 /* Errored */
1484
+ ), await this.#engine.timeoutHandler.release(this.#engine), await this.#engine.abort("Value is not serialisable");
1485
+ else
1486
+ throw new WorkflowInternalError(
1487
+ `Storage failure for ${valueKey}: ${e} `
1488
+ );
1489
+ return;
1490
+ }
1491
+ this.#engine.writeLog(
1492
+ 11 /* ATTEMPT_SUCCESS */,
1493
+ cacheKey,
1494
+ stepNameWithCounter,
1495
+ {
1496
+ attempt: stepState.attemptedCount
1497
+ }
1498
+ );
1499
+ } catch (e) {
1500
+ let error = e;
1501
+ if (this.#engine.priorityQueue.remove({
1502
+ hash: `${cacheKey}-${stepState.attemptedCount}`,
1503
+ type: "timeout"
1504
+ }), e instanceof Error && error.name === "NonRetryableError")
1505
+ return this.#engine.writeLog(
1506
+ 12 /* ATTEMPT_FAILURE */,
1507
+ cacheKey,
1508
+ stepNameWithCounter,
1509
+ {
1510
+ attempt: stepState.attemptedCount,
1511
+ error: new WorkflowFatalError(
1512
+ `Step threw a NonRetryableError with message "${e.message}"`
1513
+ )
1514
+ }
1515
+ ), this.#engine.writeLog(
1516
+ 7 /* STEP_FAILURE */,
1517
+ cacheKey,
1518
+ stepNameWithCounter,
1519
+ {}
1520
+ ), this.#engine.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
1521
+ error: new WorkflowFatalError(
1522
+ `The execution of the Workflow instance was terminated, as the step "${name}" threw a NonRetryableError`
1523
+ )
1524
+ }), await this.#engine.setStatus(
1525
+ accountId,
1526
+ instance.id,
1527
+ 3 /* Errored */
1528
+ ), await this.#engine.timeoutHandler.release(this.#engine), this.#engine.abort(`Step "${name}" threw a NonRetryableError`);
1529
+ if (this.#engine.writeLog(
1530
+ 12 /* ATTEMPT_FAILURE */,
1531
+ cacheKey,
1532
+ stepNameWithCounter,
1533
+ {
1534
+ attempt: stepState.attemptedCount,
1535
+ error: {
1536
+ name: error.name,
1537
+ message: error.message
1538
+ // TODO (WOR-79): Stacks are all incorrect over RPC and need work
1539
+ // stack: error.stack,
1540
+ }
1541
+ }
1542
+ ), await this.#state.storage.put(stepStateKey, stepState), stepState.attemptedCount <= config.retries.limit) {
1543
+ let durationMs = calcRetryDuration(config, stepState), priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`;
1544
+ return await this.#engine.priorityQueue.add({
1545
+ hash: priorityQueueHash,
1546
+ targetTimestamp: Date.now() + durationMs,
1547
+ type: "retry"
1548
+ }), await this.#engine.timeoutHandler.release(this.#engine), await scheduler.wait(durationMs), this.#engine.priorityQueue.remove({
1549
+ hash: priorityQueueHash,
1550
+ type: "retry"
1551
+ }), doWrapper(doWrapperClosure);
1552
+ } else
1553
+ throw await this.#engine.timeoutHandler.release(this.#engine), this.#engine.writeLog(
1554
+ 7 /* STEP_FAILURE */,
1555
+ cacheKey,
1556
+ stepNameWithCounter,
1557
+ {}
1558
+ ), this.#engine.writeLog(
1559
+ 3 /* WORKFLOW_FAILURE */,
1560
+ cacheKey,
1561
+ null,
1562
+ {}
1563
+ ), await this.#engine.setStatus(
1564
+ accountId,
1565
+ instance.id,
1566
+ 3 /* Errored */
1567
+ ), error;
1568
+ }
1569
+ return this.#engine.writeLog(
1570
+ 6 /* STEP_SUCCESS */,
1571
+ cacheKey,
1572
+ stepNameWithCounter,
1573
+ {
1574
+ // TODO (WOR-86): Add limits, figure out serialization
1575
+ result
1576
+ }
1577
+ ), await this.#engine.timeoutHandler.release(this.#engine), result;
1578
+ };
1579
+ return doWrapper(closure);
1580
+ }
1581
+ async sleep(name, duration) {
1582
+ typeof duration == "string" && (duration = r(duration));
1583
+ let hash = await computeHash(name + duration.toString()), count = this.#getCount("sleep-" + name + duration.toString()), cacheKey = `${hash}-${count}`, sleepNameWithCounter = `${name}-${count}`, sleepKey = `${cacheKey}-value`, sleepLogWrittenKey = `${cacheKey}-log-written`;
1584
+ if (await this.#state.storage.get(sleepKey) != null) {
1585
+ let entryPQ = this.#engine.priorityQueue.getFirst(
1586
+ (a) => a.hash === cacheKey && a.type === "sleep"
1587
+ );
1588
+ entryPQ !== void 0 && (await scheduler.wait(entryPQ.targetTimestamp - Date.now()), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" })), await this.#state.storage.get(sleepLogWrittenKey) == null && (this.#engine.writeLog(
1589
+ 9 /* SLEEP_COMPLETE */,
1590
+ cacheKey,
1591
+ sleepNameWithCounter,
1592
+ {}
1593
+ ), await this.#state.storage.put(sleepLogWrittenKey, !0));
1594
+ return;
1595
+ }
1596
+ if (this.#engine.writeLog(
1597
+ 8 /* SLEEP_START */,
1598
+ cacheKey,
1599
+ sleepNameWithCounter,
1600
+ {
1601
+ durationMs: duration
1602
+ }
1603
+ ), !await this.#state.storage.get(INSTANCE_METADATA))
1604
+ throw new Error("instanceMetadata is undefined");
1605
+ await this.#state.storage.put(sleepKey, !0), await this.#engine.priorityQueue.add({
1606
+ hash: cacheKey,
1607
+ targetTimestamp: Date.now() + duration,
1608
+ type: "sleep"
1609
+ }), await scheduler.wait(duration), this.#engine.writeLog(
1610
+ 9 /* SLEEP_COMPLETE */,
1611
+ cacheKey,
1612
+ sleepNameWithCounter,
1613
+ {}
1614
+ ), await this.#state.storage.put(sleepLogWrittenKey, !0), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" });
1615
+ }
1616
+ async sleepUntil(name, timestamp) {
1617
+ timestamp instanceof Date && (timestamp = timestamp.valueOf());
1618
+ let now = Date.now();
1619
+ if (timestamp < now)
1620
+ throw new Error(
1621
+ "You can't sleep until a time in the past, time-traveler"
1622
+ );
1623
+ return this.sleep(name, timestamp - now);
1624
+ }
1625
+ };
1626
+
1627
+ // ../workflows-shared/src/lib/gracePeriodSemaphore.ts
1628
+ var ENGINE_TIMEOUT = r("5 minutes"), latestGracePeriodTimestamp, GracePeriodSemaphore = class {
1629
+ #counter = 0;
1630
+ callback;
1631
+ timeoutMs;
1632
+ constructor(callback, timeoutMs) {
1633
+ this.callback = callback, this.timeoutMs = timeoutMs;
1634
+ }
1635
+ // acquire takes engine to be the same as release
1636
+ async acquire(_engine) {
1637
+ this.#counter == 0 && (latestGracePeriodTimestamp = void 0), this.#counter += 1;
1638
+ }
1639
+ async release(engine) {
1640
+ this.#counter = Math.max(this.#counter - 1, 0), this.#counter == 0 && this.callback(engine, this.timeoutMs);
1641
+ }
1642
+ isRunningStep() {
1643
+ return this.#counter > 0;
1644
+ }
1645
+ }, startGracePeriod = async (engine, timeoutMs) => {
1646
+ (async () => {
1647
+ let thisTimestamp = (/* @__PURE__ */ new Date()).valueOf();
1648
+ if (!(latestGracePeriodTimestamp === void 0 || latestGracePeriodTimestamp < thisTimestamp))
1649
+ throw new Error(
1650
+ "Can't start grace period since there is already an active one started on " + latestGracePeriodTimestamp
1651
+ );
1652
+ latestGracePeriodTimestamp = thisTimestamp, await scheduler.wait(timeoutMs), !(thisTimestamp !== latestGracePeriodTimestamp || engine.timeoutHandler.isRunningStep()) && (await engine.priorityQueue?.handleNextAlarm(), await engine.abort("Grace period complete"));
1653
+ })();
1654
+ };
1655
+
1656
+ // ../workflows-shared/src/lib/timePriorityQueue.ts
1657
+ var import_heap_js = __toESM(require_heap_js_umd()), wakerPriorityEntryComparator = (a, b) => a.targetTimestamp - b.targetTimestamp;
1658
+ var TimePriorityQueue = class {
1659
+ #heap = new import_heap_js.default(wakerPriorityEntryComparator);
1660
+ // #env: Env;
1661
+ #ctx;
1662
+ #instanceMetadata;
1663
+ constructor(ctx, instanceMetadata) {
1664
+ this.#ctx = ctx, this.#instanceMetadata = instanceMetadata, this.#heap.init(this.getEntries());
1665
+ }
1666
+ popPastEntries() {
1667
+ if (this.#heap.length === 0)
1668
+ return;
1669
+ let res = [], currentTimestamp = (/* @__PURE__ */ new Date()).valueOf();
1670
+ for (; ; ) {
1671
+ let element = this.#heap.peek();
1672
+ if (element === void 0 || element.targetTimestamp > currentTimestamp)
1673
+ break;
1674
+ res.push(element), this.#heap.pop();
1675
+ }
1676
+ return this.#ctx.storage.transactionSync(() => {
1677
+ for (let entry of res)
1678
+ this.removeEntryDB(entry);
1679
+ }), res;
1680
+ }
1681
+ /**
1682
+ * `add` is ran using a transaction so it's race condition free, if it's ran atomically
1683
+ * @param entry
1684
+ */
1685
+ async add(entry) {
1686
+ await this.#ctx.storage.transaction(async () => {
1687
+ this.#heap.add(entry), this.addEntryDB(entry);
1688
+ });
1689
+ }
1690
+ /**
1691
+ * `remove` is ran using a transaction so it's race condition free, if it's ran atomically
1692
+ * @param entry
1693
+ */
1694
+ remove(entry) {
1695
+ this.#ctx.storage.transactionSync(() => {
1696
+ this.removeFirst((e) => e.hash === entry.hash && e.type === entry.type);
1697
+ });
1698
+ }
1699
+ popTypeAll(entryType) {
1700
+ this.#ctx.storage.transactionSync(() => {
1701
+ this.filter((e) => e.type !== entryType);
1702
+ });
1703
+ }
1704
+ // Idempotent, perhaps name should suggest so
1705
+ async handleNextAlarm() {
1706
+ this.#heap.peek();
1707
+ }
1708
+ getFirst(callbackFn) {
1709
+ return structuredClone(this.#heap.toArray().find(callbackFn));
1710
+ }
1711
+ removeFirst(callbackFn) {
1712
+ let elements = this.#heap.toArray(), index = elements.findIndex(callbackFn);
1713
+ if (index === -1)
1714
+ return;
1715
+ let removedEntry = elements.splice(index, 1)[0];
1716
+ this.removeEntryDB(removedEntry), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(elements);
1717
+ }
1718
+ filter(callbackFn) {
1719
+ let filteredElements = this.#heap.toArray().filter(callbackFn), removedElements = this.#heap.toArray().filter((a) => !callbackFn(a));
1720
+ this.#ctx.storage.transactionSync(() => {
1721
+ for (let entry of removedElements)
1722
+ this.removeEntryDB(entry);
1723
+ }), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(filteredElements);
1724
+ }
1725
+ length() {
1726
+ return this.#heap.length;
1727
+ }
1728
+ getEntries() {
1729
+ let entries = [
1730
+ ...this.#ctx.storage.sql.exec("SELECT * FROM priority_queue ORDER BY id")
1731
+ ], activeEntries = [];
1732
+ return entries.forEach((val) => {
1733
+ let entryType = toWakerPriorityType(val.entryType);
1734
+ if (val.action == 0) {
1735
+ let index = activeEntries.findIndex(
1736
+ (activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
1737
+ );
1738
+ index !== -1 && activeEntries.splice(index, 1);
1739
+ } else
1740
+ activeEntries.findIndex(
1741
+ (activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
1742
+ ) === -1 && activeEntries.push({
1743
+ hash: val.hash,
1744
+ targetTimestamp: val.target_timestamp,
1745
+ type: entryType
1746
+ });
1747
+ }), activeEntries;
1748
+ }
1749
+ removeEntryDB(entry) {
1750
+ this.#ctx.storage.sql.exec(
1751
+ `
1752
+ INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
1753
+ VALUES (?, ?, ? ,?)
1754
+ `,
1755
+ entry.targetTimestamp,
1756
+ 0 /* FALSE */,
1757
+ fromWakerPriorityType(entry.type),
1758
+ entry.hash
1759
+ );
1760
+ }
1761
+ addEntryDB(entry) {
1762
+ this.#ctx.storage.sql.exec(
1763
+ `
1764
+ INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
1765
+ VALUES (?, ?, ? ,?)
1766
+ `,
1767
+ entry.targetTimestamp,
1768
+ 1 /* TRUE */,
1769
+ fromWakerPriorityType(entry.type),
1770
+ entry.hash
1771
+ );
1772
+ }
1773
+ }, toWakerPriorityType = (entryType) => {
1774
+ switch (entryType) {
1775
+ case 0 /* RETRY */:
1776
+ return "retry";
1777
+ case 1 /* SLEEP */:
1778
+ return "sleep";
1779
+ case 2 /* TIMEOUT */:
1780
+ return "timeout";
1781
+ }
1782
+ }, fromWakerPriorityType = (entryType) => {
1783
+ switch (entryType) {
1784
+ case "retry":
1785
+ return 0 /* RETRY */;
1786
+ case "sleep":
1787
+ return 1 /* SLEEP */;
1788
+ case "timeout":
1789
+ return 2 /* TIMEOUT */;
1790
+ default:
1791
+ throw new Error(`WakerPriorityType "${entryType}" has not been handled`);
1792
+ }
1793
+ };
1794
+
1795
+ // ../workflows-shared/src/engine.ts
1796
+ var Engine = class extends DurableObject {
1797
+ logs = [];
1798
+ status = 0 /* Queued */;
1799
+ isRunning = !1;
1800
+ accountId;
1801
+ instanceId;
1802
+ workflowName;
1803
+ timeoutHandler;
1804
+ priorityQueue;
1805
+ constructor(state, env) {
1806
+ super(state, env), this.ctx.blockConcurrencyWhile(async () => {
1807
+ this.ctx.storage.transactionSync(() => {
1808
+ this.ctx.storage.sql.exec(`
1809
+ CREATE TABLE IF NOT EXISTS priority_queue (
1810
+ id INTEGER PRIMARY KEY NOT NULL,
1811
+ created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1812
+ target_timestamp INTEGER NOT NULL,
1813
+ action INTEGER NOT NULL, -- should only be 0 or 1 (1 for added, 0 for deleted),
1814
+ entryType INTEGER NOT NULL,
1815
+ hash TEXT NOT NULL,
1816
+ CHECK (action IN (0, 1)), -- guararentee that action can only be 0 or 1
1817
+ UNIQUE (action, entryType, hash)
1818
+ )
1819
+ `);
1820
+ });
1821
+ }), this.timeoutHandler = new GracePeriodSemaphore(
1822
+ startGracePeriod,
1823
+ ENGINE_TIMEOUT
1824
+ );
1825
+ }
1826
+ writeLog(event, group, target = null, metadata) {
1827
+ this.logs.push({
1828
+ event,
1829
+ group,
1830
+ target,
1831
+ metadata
1832
+ });
1833
+ }
1834
+ readLogsFromStep(_cacheKey) {
1835
+ return [];
1836
+ }
1837
+ readLogs() {
1838
+ return {
1839
+ // @ts-expect-error TODO: Fix this
1840
+ logs: this.logs
1841
+ };
1842
+ }
1843
+ async getStatus(_accountId, _instanceId) {
1844
+ return this.status;
1845
+ }
1846
+ async setStatus(accountId, instanceId, status) {
1847
+ this.status = status;
1848
+ }
1849
+ async abort(_reason) {
1850
+ }
1851
+ async userTriggeredTerminate() {
1852
+ }
1853
+ async init(accountId, workflow, version, instance, event) {
1854
+ if (this.priorityQueue === void 0 && (this.priorityQueue = new TimePriorityQueue(
1855
+ this.ctx,
1856
+ // this.env,
1857
+ {
1858
+ accountId,
1859
+ workflow,
1860
+ version,
1861
+ instance,
1862
+ event
1863
+ }
1864
+ )), this.priorityQueue.popPastEntries(), await this.priorityQueue.handleNextAlarm(), this.isRunning)
1865
+ return;
1866
+ this.accountId = accountId, this.instanceId = instance.id, this.workflowName = workflow.name;
1867
+ let status = await this.getStatus(accountId, instance.id);
1868
+ if ([
1869
+ 3 /* Errored */,
1870
+ // TODO (WOR-85): Remove this once upgrade story is done
1871
+ 4 /* Terminated */,
1872
+ 5 /* Complete */
1873
+ ].includes(status))
1874
+ return;
1875
+ if (await this.ctx.storage.get(INSTANCE_METADATA) == null) {
1876
+ let instanceMetadata = {
1877
+ accountId,
1878
+ workflow,
1879
+ version,
1880
+ instance,
1881
+ event
1882
+ };
1883
+ await this.ctx.storage.put(INSTANCE_METADATA, instanceMetadata), this.writeLog(0 /* WORKFLOW_QUEUED */, null, null, {
1884
+ params: event.payload,
1885
+ versionId: version.id,
1886
+ trigger: {
1887
+ source: 0 /* API */
1888
+ }
1889
+ }), this.writeLog(1 /* WORKFLOW_START */, null, null, {});
1890
+ }
1891
+ let stubStep = new Context(this, this.ctx), workflowRunningHandler = async () => {
1892
+ await this.ctx.storage.transaction(async () => {
1893
+ await this.setStatus(accountId, instance.id, 1 /* Running */);
1894
+ });
1895
+ };
1896
+ this.isRunning = !0, workflowRunningHandler();
1897
+ try {
1898
+ let result = await this.env.USER_WORKFLOW.run(event, stubStep);
1899
+ this.writeLog(2 /* WORKFLOW_SUCCESS */, null, null, {
1900
+ result
1901
+ }), await this.ctx.storage.transaction(async () => {
1902
+ await this.setStatus(accountId, instance.id, 5 /* Complete */);
1903
+ }), this.isRunning = !1;
1904
+ } catch (err) {
1905
+ let error;
1906
+ err instanceof Error ? error = {
1907
+ message: err.message,
1908
+ name: err.name
1909
+ } : error = {
1910
+ name: "Error",
1911
+ message: err
1912
+ }, this.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
1913
+ error
1914
+ }), await this.ctx.storage.transaction(async () => {
1915
+ await this.setStatus(accountId, instance.id, 3 /* Errored */);
1916
+ }), this.isRunning = !1;
1917
+ }
1918
+ return {
1919
+ id: instance.id
1920
+ };
1921
+ }
1922
+ };
1923
+ export {
1924
+ Engine,
1925
+ WorkflowBinding
1926
+ };
1927
+ //# sourceMappingURL=binding.worker.js.map