@depup/miniflare 4.20260317.0-depup.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -0
- package/bootstrap.js +11 -0
- package/changes.json +10 -0
- package/dist/local-explorer-ui/assets/Breadcrumbs-7hjI0sYt.js +1 -0
- package/dist/local-explorer-ui/assets/TableSelect-_bi6l6Iv.js +25 -0
- package/dist/local-explorer-ui/assets/_className-gSkjniQn.js +1 -0
- package/dist/local-explorer-ui/assets/_databaseId-DWcfgBis.js +1 -0
- package/dist/local-explorer-ui/assets/_namespaceId-8ViM8VDL.js +1 -0
- package/dist/local-explorer-ui/assets/_objectId-X6x-JUph.js +1 -0
- package/dist/local-explorer-ui/assets/dropdown-DFeFcKfn-BCd_NRZS.js +1 -0
- package/dist/local-explorer-ui/assets/index-BFNDwiew.js +42 -0
- package/dist/local-explorer-ui/assets/index-CLSFsgi0.js +1 -0
- package/dist/local-explorer-ui/assets/index-KG4JeHCX.js +1 -0
- package/dist/local-explorer-ui/assets/index-mgoUmSld.css +1 -0
- package/dist/local-explorer-ui/assets/table-BUmvaBj8-v-EIZgOz.js +1 -0
- package/dist/local-explorer-ui/favicon.svg +3 -0
- package/dist/local-explorer-ui/index.html +14 -0
- package/dist/src/index.d.ts +8703 -0
- package/dist/src/index.js +83666 -0
- package/dist/src/index.js.map +6 -0
- package/dist/src/shared/dev-registry.worker.js +69801 -0
- package/dist/src/shared/dev-registry.worker.js.map +6 -0
- package/dist/src/workers/analytics-engine/analytics-engine.worker.js +15 -0
- package/dist/src/workers/analytics-engine/analytics-engine.worker.js.map +6 -0
- package/dist/src/workers/assets/assets-kv.worker.js +28 -0
- package/dist/src/workers/assets/assets-kv.worker.js.map +6 -0
- package/dist/src/workers/assets/assets.worker.js +9014 -0
- package/dist/src/workers/assets/assets.worker.js.map +6 -0
- package/dist/src/workers/assets/router.worker.js +9625 -0
- package/dist/src/workers/assets/router.worker.js.map +6 -0
- package/dist/src/workers/assets/rpc-proxy.worker.js +29 -0
- package/dist/src/workers/assets/rpc-proxy.worker.js.map +6 -0
- package/dist/src/workers/browser-rendering/binding.worker.js +129 -0
- package/dist/src/workers/browser-rendering/binding.worker.js.map +6 -0
- package/dist/src/workers/cache/cache-entry-noop.worker.js +19 -0
- package/dist/src/workers/cache/cache-entry-noop.worker.js.map +6 -0
- package/dist/src/workers/cache/cache-entry.worker.js +28 -0
- package/dist/src/workers/cache/cache-entry.worker.js.map +6 -0
- package/dist/src/workers/cache/cache.worker.js +653 -0
- package/dist/src/workers/cache/cache.worker.js.map +6 -0
- package/dist/src/workers/core/do-wrapper.worker.js +43 -0
- package/dist/src/workers/core/do-wrapper.worker.js.map +6 -0
- package/dist/src/workers/core/entry.worker.js +4633 -0
- package/dist/src/workers/core/entry.worker.js.map +6 -0
- package/dist/src/workers/core/strip-cf-connecting-ip.worker.js +11 -0
- package/dist/src/workers/core/strip-cf-connecting-ip.worker.js.map +6 -0
- package/dist/src/workers/d1/database.worker.js +219 -0
- package/dist/src/workers/d1/database.worker.js.map +6 -0
- package/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js +2271 -0
- package/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js.map +6 -0
- package/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js +12 -0
- package/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js.map +6 -0
- package/dist/src/workers/email/email.worker.js +23 -0
- package/dist/src/workers/email/email.worker.js.map +6 -0
- package/dist/src/workers/email/send_email.worker.js +3294 -0
- package/dist/src/workers/email/send_email.worker.js.map +6 -0
- package/dist/src/workers/hello-world/binding.worker.js +19 -0
- package/dist/src/workers/hello-world/binding.worker.js.map +6 -0
- package/dist/src/workers/hello-world/object.worker.js +14 -0
- package/dist/src/workers/hello-world/object.worker.js.map +6 -0
- package/dist/src/workers/images/images.worker.js +155 -0
- package/dist/src/workers/images/images.worker.js.map +6 -0
- package/dist/src/workers/kv/namespace.worker.js +322 -0
- package/dist/src/workers/kv/namespace.worker.js.map +6 -0
- package/dist/src/workers/kv/sites.worker.js +146 -0
- package/dist/src/workers/kv/sites.worker.js.map +6 -0
- package/dist/src/workers/local-explorer/explorer.worker.js +5245 -0
- package/dist/src/workers/local-explorer/explorer.worker.js.map +6 -0
- package/dist/src/workers/pipelines/pipeline.worker.js +10 -0
- package/dist/src/workers/pipelines/pipeline.worker.js.map +6 -0
- package/dist/src/workers/queues/broker.worker.js +289 -0
- package/dist/src/workers/queues/broker.worker.js.map +6 -0
- package/dist/src/workers/r2/bucket.worker.js +1134 -0
- package/dist/src/workers/r2/bucket.worker.js.map +6 -0
- package/dist/src/workers/ratelimit/ratelimit.worker.js +54 -0
- package/dist/src/workers/ratelimit/ratelimit.worker.js.map +6 -0
- package/dist/src/workers/secrets-store/secret.worker.js +65 -0
- package/dist/src/workers/secrets-store/secret.worker.js.map +6 -0
- package/dist/src/workers/shared/index.worker.js +693 -0
- package/dist/src/workers/shared/index.worker.js.map +6 -0
- package/dist/src/workers/shared/object-entry.worker.js +21 -0
- package/dist/src/workers/shared/object-entry.worker.js.map +6 -0
- package/dist/src/workers/shared/remote-proxy-client.worker.js +2271 -0
- package/dist/src/workers/shared/remote-proxy-client.worker.js.map +6 -0
- package/dist/src/workers/shared/zod.worker.js +2954 -0
- package/dist/src/workers/shared/zod.worker.js.map +6 -0
- package/dist/src/workers/workflows/binding.worker.js +2422 -0
- package/dist/src/workers/workflows/binding.worker.js.map +6 -0
- package/dist/src/workers/workflows/wrapped-binding.worker.js +71 -0
- package/dist/src/workers/workflows/wrapped-binding.worker.js.map +6 -0
- package/package.json +139 -0
|
@@ -0,0 +1,2422 @@
|
|
|
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) throw t[1];
|
|
60
|
+
return t[1];
|
|
61
|
+
}, trys: [], ops: [] }, f, y, t, g;
|
|
62
|
+
return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
|
|
63
|
+
return this;
|
|
64
|
+
}), g;
|
|
65
|
+
function verb(n2) {
|
|
66
|
+
return function(v) {
|
|
67
|
+
return step([n2, v]);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function step(op) {
|
|
71
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
72
|
+
for (; g && (g = 0, op[0] && (_ = 0)), _; ) try {
|
|
73
|
+
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) return t;
|
|
74
|
+
switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
|
|
75
|
+
case 0:
|
|
76
|
+
case 1:
|
|
77
|
+
t = op;
|
|
78
|
+
break;
|
|
79
|
+
case 4:
|
|
80
|
+
return _.label++, { value: op[1], done: !1 };
|
|
81
|
+
case 5:
|
|
82
|
+
_.label++, y = op[1], op = [0];
|
|
83
|
+
continue;
|
|
84
|
+
case 7:
|
|
85
|
+
op = _.ops.pop(), _.trys.pop();
|
|
86
|
+
continue;
|
|
87
|
+
default:
|
|
88
|
+
if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
89
|
+
_ = 0;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
93
|
+
_.label = op[1];
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
if (op[0] === 6 && _.label < t[1]) {
|
|
97
|
+
_.label = t[1], t = op;
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
if (t && _.label < t[2]) {
|
|
101
|
+
_.label = t[2], _.ops.push(op);
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
t[2] && _.ops.pop(), _.trys.pop();
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
op = body.call(thisArg, _);
|
|
108
|
+
} catch (e) {
|
|
109
|
+
op = [6, e], y = 0;
|
|
110
|
+
} finally {
|
|
111
|
+
f = t = 0;
|
|
112
|
+
}
|
|
113
|
+
if (op[0] & 5) throw op[1];
|
|
114
|
+
return { value: op[0] ? op[1] : void 0, done: !0 };
|
|
115
|
+
}
|
|
116
|
+
}, __read$1 = function(o, n2) {
|
|
117
|
+
var m = typeof Symbol == "function" && o[Symbol.iterator];
|
|
118
|
+
if (!m) return o;
|
|
119
|
+
var i = m.call(o), r2, ar = [], e;
|
|
120
|
+
try {
|
|
121
|
+
for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; ) ar.push(r2.value);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
e = { error };
|
|
124
|
+
} finally {
|
|
125
|
+
try {
|
|
126
|
+
r2 && !r2.done && (m = i.return) && m.call(i);
|
|
127
|
+
} finally {
|
|
128
|
+
if (e) throw e.error;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return ar;
|
|
132
|
+
}, __spreadArray$1 = function(to, from, pack) {
|
|
133
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++)
|
|
134
|
+
(ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
|
|
135
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
136
|
+
}, __values = function(o) {
|
|
137
|
+
var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
138
|
+
if (m) return m.call(o);
|
|
139
|
+
if (o && typeof o.length == "number") return {
|
|
140
|
+
next: function() {
|
|
141
|
+
return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
145
|
+
}, HeapAsync = (
|
|
146
|
+
/** @class */
|
|
147
|
+
(function() {
|
|
148
|
+
function HeapAsync2(compare) {
|
|
149
|
+
compare === void 0 && (compare = HeapAsync2.minComparator);
|
|
150
|
+
var _this = this;
|
|
151
|
+
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) {
|
|
152
|
+
return _this.compare(a, b).then(function(res) {
|
|
153
|
+
return -1 * res;
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return HeapAsync2.getChildrenIndexOf = function(idx) {
|
|
158
|
+
return [idx * 2 + 1, idx * 2 + 2];
|
|
159
|
+
}, HeapAsync2.getParentIndexOf = function(idx) {
|
|
160
|
+
if (idx <= 0)
|
|
161
|
+
return -1;
|
|
162
|
+
var whichChildren = idx % 2 ? 1 : 2;
|
|
163
|
+
return Math.floor((idx - whichChildren) / 2);
|
|
164
|
+
}, HeapAsync2.getSiblingIndexOf = function(idx) {
|
|
165
|
+
if (idx <= 0)
|
|
166
|
+
return -1;
|
|
167
|
+
var whichChildren = idx % 2 ? 1 : -1;
|
|
168
|
+
return idx + whichChildren;
|
|
169
|
+
}, HeapAsync2.minComparator = function(a, b) {
|
|
170
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
171
|
+
return __generator$1(this, function(_a) {
|
|
172
|
+
return a > b ? [2, 1] : a < b ? [2, -1] : [2, 0];
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
}, HeapAsync2.maxComparator = function(a, b) {
|
|
176
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
177
|
+
return __generator$1(this, function(_a) {
|
|
178
|
+
return b > a ? [2, 1] : b < a ? [2, -1] : [2, 0];
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
}, HeapAsync2.minComparatorNumber = function(a, b) {
|
|
182
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
183
|
+
return __generator$1(this, function(_a) {
|
|
184
|
+
return [2, a - b];
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
}, HeapAsync2.maxComparatorNumber = function(a, b) {
|
|
188
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
189
|
+
return __generator$1(this, function(_a) {
|
|
190
|
+
return [2, b - a];
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
}, HeapAsync2.defaultIsEqual = function(a, b) {
|
|
194
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
195
|
+
return __generator$1(this, function(_a) {
|
|
196
|
+
return [2, a === b];
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
}, HeapAsync2.print = function(heap) {
|
|
200
|
+
function deep(i2) {
|
|
201
|
+
var pi = HeapAsync2.getParentIndexOf(i2);
|
|
202
|
+
return Math.floor(Math.log2(pi + 1));
|
|
203
|
+
}
|
|
204
|
+
function repeat(str, times) {
|
|
205
|
+
for (var out = ""; times > 0; --times)
|
|
206
|
+
out += str;
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
|
|
210
|
+
var i = deep(node) + 1;
|
|
211
|
+
node === 0 && (i = 0);
|
|
212
|
+
var nodeText = String(heap.get(node));
|
|
213
|
+
nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
|
|
214
|
+
}
|
|
215
|
+
return lines.map(function(line, i2) {
|
|
216
|
+
var times = Math.pow(2, maxLines - i2) - 1;
|
|
217
|
+
return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
|
|
218
|
+
var half = (maxLength - el.length) / 2;
|
|
219
|
+
return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
|
|
220
|
+
}).join(repeat(" ", times * maxLength));
|
|
221
|
+
}).join(`
|
|
222
|
+
`);
|
|
223
|
+
}, HeapAsync2.heapify = function(arr, compare) {
|
|
224
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
225
|
+
var heap;
|
|
226
|
+
return __generator$1(this, function(_a) {
|
|
227
|
+
switch (_a.label) {
|
|
228
|
+
case 0:
|
|
229
|
+
return heap = new HeapAsync2(compare), heap.heapArray = arr, [4, heap.init()];
|
|
230
|
+
case 1:
|
|
231
|
+
return _a.sent(), [2, heap];
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
}, HeapAsync2.heappop = function(heapArr, compare) {
|
|
236
|
+
var heap = new HeapAsync2(compare);
|
|
237
|
+
return heap.heapArray = heapArr, heap.pop();
|
|
238
|
+
}, HeapAsync2.heappush = function(heapArr, item, compare) {
|
|
239
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
240
|
+
var heap;
|
|
241
|
+
return __generator$1(this, function(_a) {
|
|
242
|
+
switch (_a.label) {
|
|
243
|
+
case 0:
|
|
244
|
+
return heap = new HeapAsync2(compare), heap.heapArray = heapArr, [4, heap.push(item)];
|
|
245
|
+
case 1:
|
|
246
|
+
return _a.sent(), [
|
|
247
|
+
2
|
|
248
|
+
/*return*/
|
|
249
|
+
];
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
}, HeapAsync2.heappushpop = function(heapArr, item, compare) {
|
|
254
|
+
var heap = new HeapAsync2(compare);
|
|
255
|
+
return heap.heapArray = heapArr, heap.pushpop(item);
|
|
256
|
+
}, HeapAsync2.heapreplace = function(heapArr, item, compare) {
|
|
257
|
+
var heap = new HeapAsync2(compare);
|
|
258
|
+
return heap.heapArray = heapArr, heap.replace(item);
|
|
259
|
+
}, HeapAsync2.heaptop = function(heapArr, n2, compare) {
|
|
260
|
+
n2 === void 0 && (n2 = 1);
|
|
261
|
+
var heap = new HeapAsync2(compare);
|
|
262
|
+
return heap.heapArray = heapArr, heap.top(n2);
|
|
263
|
+
}, HeapAsync2.heapbottom = function(heapArr, n2, compare) {
|
|
264
|
+
n2 === void 0 && (n2 = 1);
|
|
265
|
+
var heap = new HeapAsync2(compare);
|
|
266
|
+
return heap.heapArray = heapArr, heap.bottom(n2);
|
|
267
|
+
}, HeapAsync2.nlargest = function(n2, iterable, compare) {
|
|
268
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
269
|
+
var heap;
|
|
270
|
+
return __generator$1(this, function(_a) {
|
|
271
|
+
switch (_a.label) {
|
|
272
|
+
case 0:
|
|
273
|
+
return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
|
|
274
|
+
case 1:
|
|
275
|
+
return _a.sent(), [2, heap.top(n2)];
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
}, HeapAsync2.nsmallest = function(n2, iterable, compare) {
|
|
280
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
281
|
+
var heap;
|
|
282
|
+
return __generator$1(this, function(_a) {
|
|
283
|
+
switch (_a.label) {
|
|
284
|
+
case 0:
|
|
285
|
+
return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
|
|
286
|
+
case 1:
|
|
287
|
+
return _a.sent(), [2, heap.bottom(n2)];
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
}, HeapAsync2.prototype.add = function(element) {
|
|
292
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
293
|
+
return __generator$1(this, function(_a) {
|
|
294
|
+
switch (_a.label) {
|
|
295
|
+
case 0:
|
|
296
|
+
return [4, this._sortNodeUp(this.heapArray.push(element) - 1)];
|
|
297
|
+
case 1:
|
|
298
|
+
return _a.sent(), this._applyLimit(), [2, !0];
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
});
|
|
302
|
+
}, HeapAsync2.prototype.addAll = function(elements) {
|
|
303
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
304
|
+
var i, l, _a;
|
|
305
|
+
return __generator$1(this, function(_b) {
|
|
306
|
+
switch (_b.label) {
|
|
307
|
+
case 0:
|
|
308
|
+
i = this.length, (_a = this.heapArray).push.apply(_a, __spreadArray$1([], __read$1(elements), !1)), l = this.length, _b.label = 1;
|
|
309
|
+
case 1:
|
|
310
|
+
return i < l ? [4, this._sortNodeUp(i)] : [3, 4];
|
|
311
|
+
case 2:
|
|
312
|
+
_b.sent(), _b.label = 3;
|
|
313
|
+
case 3:
|
|
314
|
+
return ++i, [3, 1];
|
|
315
|
+
case 4:
|
|
316
|
+
return this._applyLimit(), [2, !0];
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
});
|
|
320
|
+
}, HeapAsync2.prototype.bottom = function(n2) {
|
|
321
|
+
return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
|
|
322
|
+
return __generator$1(this, function(_a) {
|
|
323
|
+
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)];
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
}, HeapAsync2.prototype.check = function() {
|
|
327
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
328
|
+
var j, el, children, children_1, children_1_1, ch, e_1_1, e_1, _a;
|
|
329
|
+
return __generator$1(this, function(_b) {
|
|
330
|
+
switch (_b.label) {
|
|
331
|
+
case 0:
|
|
332
|
+
j = 0, _b.label = 1;
|
|
333
|
+
case 1:
|
|
334
|
+
if (!(j < this.heapArray.length)) return [3, 10];
|
|
335
|
+
el = this.heapArray[j], children = this.getChildrenOf(j), _b.label = 2;
|
|
336
|
+
case 2:
|
|
337
|
+
_b.trys.push([2, 7, 8, 9]), children_1 = (e_1 = void 0, __values(children)), children_1_1 = children_1.next(), _b.label = 3;
|
|
338
|
+
case 3:
|
|
339
|
+
return children_1_1.done ? [3, 6] : (ch = children_1_1.value, [4, this.compare(el, ch)]);
|
|
340
|
+
case 4:
|
|
341
|
+
if (_b.sent() > 0)
|
|
342
|
+
return [2, el];
|
|
343
|
+
_b.label = 5;
|
|
344
|
+
case 5:
|
|
345
|
+
return children_1_1 = children_1.next(), [3, 3];
|
|
346
|
+
case 6:
|
|
347
|
+
return [3, 9];
|
|
348
|
+
case 7:
|
|
349
|
+
return e_1_1 = _b.sent(), e_1 = { error: e_1_1 }, [3, 9];
|
|
350
|
+
case 8:
|
|
351
|
+
try {
|
|
352
|
+
children_1_1 && !children_1_1.done && (_a = children_1.return) && _a.call(children_1);
|
|
353
|
+
} finally {
|
|
354
|
+
if (e_1) throw e_1.error;
|
|
355
|
+
}
|
|
356
|
+
return [
|
|
357
|
+
7
|
|
358
|
+
/*endfinally*/
|
|
359
|
+
];
|
|
360
|
+
case 9:
|
|
361
|
+
return ++j, [3, 1];
|
|
362
|
+
case 10:
|
|
363
|
+
return [
|
|
364
|
+
2
|
|
365
|
+
/*return*/
|
|
366
|
+
];
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
}, HeapAsync2.prototype.clear = function() {
|
|
371
|
+
this.heapArray = [];
|
|
372
|
+
}, HeapAsync2.prototype.clone = function() {
|
|
373
|
+
var cloned = new HeapAsync2(this.comparator());
|
|
374
|
+
return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
|
|
375
|
+
}, HeapAsync2.prototype.comparator = function() {
|
|
376
|
+
return this.compare;
|
|
377
|
+
}, HeapAsync2.prototype.contains = function(o, fn) {
|
|
378
|
+
return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
|
|
379
|
+
var _a, _b, el, e_2_1, e_2, _c;
|
|
380
|
+
return __generator$1(this, function(_d) {
|
|
381
|
+
switch (_d.label) {
|
|
382
|
+
case 0:
|
|
383
|
+
_d.trys.push([0, 5, 6, 7]), _a = __values(this.heapArray), _b = _a.next(), _d.label = 1;
|
|
384
|
+
case 1:
|
|
385
|
+
return _b.done ? [3, 4] : (el = _b.value, [4, fn(el, o)]);
|
|
386
|
+
case 2:
|
|
387
|
+
if (_d.sent())
|
|
388
|
+
return [2, !0];
|
|
389
|
+
_d.label = 3;
|
|
390
|
+
case 3:
|
|
391
|
+
return _b = _a.next(), [3, 1];
|
|
392
|
+
case 4:
|
|
393
|
+
return [3, 7];
|
|
394
|
+
case 5:
|
|
395
|
+
return e_2_1 = _d.sent(), e_2 = { error: e_2_1 }, [3, 7];
|
|
396
|
+
case 6:
|
|
397
|
+
try {
|
|
398
|
+
_b && !_b.done && (_c = _a.return) && _c.call(_a);
|
|
399
|
+
} finally {
|
|
400
|
+
if (e_2) throw e_2.error;
|
|
401
|
+
}
|
|
402
|
+
return [
|
|
403
|
+
7
|
|
404
|
+
/*endfinally*/
|
|
405
|
+
];
|
|
406
|
+
case 7:
|
|
407
|
+
return [2, !1];
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
});
|
|
411
|
+
}, HeapAsync2.prototype.init = function(array) {
|
|
412
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
413
|
+
var i;
|
|
414
|
+
return __generator$1(this, function(_a) {
|
|
415
|
+
switch (_a.label) {
|
|
416
|
+
case 0:
|
|
417
|
+
array && (this.heapArray = __spreadArray$1([], __read$1(array), !1)), i = Math.floor(this.heapArray.length), _a.label = 1;
|
|
418
|
+
case 1:
|
|
419
|
+
return i >= 0 ? [4, this._sortNodeDown(i)] : [3, 4];
|
|
420
|
+
case 2:
|
|
421
|
+
_a.sent(), _a.label = 3;
|
|
422
|
+
case 3:
|
|
423
|
+
return --i, [3, 1];
|
|
424
|
+
case 4:
|
|
425
|
+
return this._applyLimit(), [
|
|
426
|
+
2
|
|
427
|
+
/*return*/
|
|
428
|
+
];
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
});
|
|
432
|
+
}, HeapAsync2.prototype.isEmpty = function() {
|
|
433
|
+
return this.length === 0;
|
|
434
|
+
}, HeapAsync2.prototype.leafs = function() {
|
|
435
|
+
if (this.heapArray.length === 0)
|
|
436
|
+
return [];
|
|
437
|
+
var pi = HeapAsync2.getParentIndexOf(this.heapArray.length - 1);
|
|
438
|
+
return this.heapArray.slice(pi + 1);
|
|
439
|
+
}, Object.defineProperty(HeapAsync2.prototype, "length", {
|
|
440
|
+
/**
|
|
441
|
+
* Length of the heap.
|
|
442
|
+
* @return {Number}
|
|
443
|
+
*/
|
|
444
|
+
get: function() {
|
|
445
|
+
return this.heapArray.length;
|
|
446
|
+
},
|
|
447
|
+
enumerable: !1,
|
|
448
|
+
configurable: !0
|
|
449
|
+
}), Object.defineProperty(HeapAsync2.prototype, "limit", {
|
|
450
|
+
/**
|
|
451
|
+
* Get length limit of the heap.
|
|
452
|
+
* @return {Number}
|
|
453
|
+
*/
|
|
454
|
+
get: function() {
|
|
455
|
+
return this._limit;
|
|
456
|
+
},
|
|
457
|
+
/**
|
|
458
|
+
* Set length limit of the heap.
|
|
459
|
+
* @return {Number}
|
|
460
|
+
*/
|
|
461
|
+
set: function(_l) {
|
|
462
|
+
this._limit = ~~_l, this._applyLimit();
|
|
463
|
+
},
|
|
464
|
+
enumerable: !1,
|
|
465
|
+
configurable: !0
|
|
466
|
+
}), HeapAsync2.prototype.peek = function() {
|
|
467
|
+
return this.heapArray[0];
|
|
468
|
+
}, HeapAsync2.prototype.pop = function() {
|
|
469
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
470
|
+
var last;
|
|
471
|
+
return __generator$1(this, function(_a) {
|
|
472
|
+
return last = this.heapArray.pop(), this.length > 0 && last !== void 0 ? [2, this.replace(last)] : [2, last];
|
|
473
|
+
});
|
|
474
|
+
});
|
|
475
|
+
}, HeapAsync2.prototype.push = function() {
|
|
476
|
+
for (var elements = [], _i = 0; _i < arguments.length; _i++)
|
|
477
|
+
elements[_i] = arguments[_i];
|
|
478
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
479
|
+
return __generator$1(this, function(_a) {
|
|
480
|
+
return elements.length < 1 ? [2, !1] : elements.length === 1 ? [2, this.add(elements[0])] : [2, this.addAll(elements)];
|
|
481
|
+
});
|
|
482
|
+
});
|
|
483
|
+
}, HeapAsync2.prototype.pushpop = function(element) {
|
|
484
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
485
|
+
var _a;
|
|
486
|
+
return __generator$1(this, function(_b) {
|
|
487
|
+
switch (_b.label) {
|
|
488
|
+
case 0:
|
|
489
|
+
return [4, this.compare(this.heapArray[0], element)];
|
|
490
|
+
case 1:
|
|
491
|
+
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];
|
|
492
|
+
case 2:
|
|
493
|
+
_b.sent(), _b.label = 3;
|
|
494
|
+
case 3:
|
|
495
|
+
return [2, element];
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
});
|
|
499
|
+
}, HeapAsync2.prototype.remove = function(o, fn) {
|
|
500
|
+
return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
|
|
501
|
+
var idx, i;
|
|
502
|
+
return __generator$1(this, function(_a) {
|
|
503
|
+
switch (_a.label) {
|
|
504
|
+
case 0:
|
|
505
|
+
return this.length > 0 ? o !== void 0 ? [3, 2] : [4, this.pop()] : [3, 13];
|
|
506
|
+
case 1:
|
|
507
|
+
return _a.sent(), [2, !0];
|
|
508
|
+
case 2:
|
|
509
|
+
idx = -1, i = 0, _a.label = 3;
|
|
510
|
+
case 3:
|
|
511
|
+
return i < this.heapArray.length ? [4, fn(this.heapArray[i], o)] : [3, 6];
|
|
512
|
+
case 4:
|
|
513
|
+
if (_a.sent())
|
|
514
|
+
return idx = i, [3, 6];
|
|
515
|
+
_a.label = 5;
|
|
516
|
+
case 5:
|
|
517
|
+
return ++i, [3, 3];
|
|
518
|
+
case 6:
|
|
519
|
+
return idx >= 0 ? idx !== 0 ? [3, 8] : [4, this.pop()] : [3, 13];
|
|
520
|
+
case 7:
|
|
521
|
+
return _a.sent(), [3, 12];
|
|
522
|
+
case 8:
|
|
523
|
+
return idx !== this.length - 1 ? [3, 9] : (this.heapArray.pop(), [3, 12]);
|
|
524
|
+
case 9:
|
|
525
|
+
return this.heapArray.splice(idx, 1, this.heapArray.pop()), [4, this._sortNodeUp(idx)];
|
|
526
|
+
case 10:
|
|
527
|
+
return _a.sent(), [4, this._sortNodeDown(idx)];
|
|
528
|
+
case 11:
|
|
529
|
+
_a.sent(), _a.label = 12;
|
|
530
|
+
case 12:
|
|
531
|
+
return [2, !0];
|
|
532
|
+
case 13:
|
|
533
|
+
return [2, !1];
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
});
|
|
537
|
+
}, HeapAsync2.prototype.replace = function(element) {
|
|
538
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
539
|
+
var peek;
|
|
540
|
+
return __generator$1(this, function(_a) {
|
|
541
|
+
switch (_a.label) {
|
|
542
|
+
case 0:
|
|
543
|
+
return peek = this.heapArray[0], this.heapArray[0] = element, [4, this._sortNodeDown(0)];
|
|
544
|
+
case 1:
|
|
545
|
+
return _a.sent(), [2, peek];
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
});
|
|
549
|
+
}, HeapAsync2.prototype.size = function() {
|
|
550
|
+
return this.length;
|
|
551
|
+
}, HeapAsync2.prototype.top = function(n2) {
|
|
552
|
+
return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
|
|
553
|
+
return __generator$1(this, function(_a) {
|
|
554
|
+
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)];
|
|
555
|
+
});
|
|
556
|
+
});
|
|
557
|
+
}, HeapAsync2.prototype.toArray = function() {
|
|
558
|
+
return __spreadArray$1([], __read$1(this.heapArray), !1);
|
|
559
|
+
}, HeapAsync2.prototype.toString = function() {
|
|
560
|
+
return this.heapArray.toString();
|
|
561
|
+
}, HeapAsync2.prototype.get = function(i) {
|
|
562
|
+
return this.heapArray[i];
|
|
563
|
+
}, HeapAsync2.prototype.getChildrenOf = function(idx) {
|
|
564
|
+
var _this = this;
|
|
565
|
+
return HeapAsync2.getChildrenIndexOf(idx).map(function(i) {
|
|
566
|
+
return _this.heapArray[i];
|
|
567
|
+
}).filter(function(e) {
|
|
568
|
+
return e !== void 0;
|
|
569
|
+
});
|
|
570
|
+
}, HeapAsync2.prototype.getParentOf = function(idx) {
|
|
571
|
+
var pi = HeapAsync2.getParentIndexOf(idx);
|
|
572
|
+
return this.heapArray[pi];
|
|
573
|
+
}, HeapAsync2.prototype[Symbol.iterator] = function() {
|
|
574
|
+
return __generator$1(this, function(_a) {
|
|
575
|
+
switch (_a.label) {
|
|
576
|
+
case 0:
|
|
577
|
+
return this.length ? [4, this.pop()] : [3, 2];
|
|
578
|
+
case 1:
|
|
579
|
+
return _a.sent(), [3, 0];
|
|
580
|
+
case 2:
|
|
581
|
+
return [
|
|
582
|
+
2
|
|
583
|
+
/*return*/
|
|
584
|
+
];
|
|
585
|
+
}
|
|
586
|
+
});
|
|
587
|
+
}, HeapAsync2.prototype.iterator = function() {
|
|
588
|
+
return this;
|
|
589
|
+
}, HeapAsync2.prototype._applyLimit = function() {
|
|
590
|
+
if (this._limit && this._limit < this.heapArray.length)
|
|
591
|
+
for (var rm = this.heapArray.length - this._limit; rm; )
|
|
592
|
+
this.heapArray.pop(), --rm;
|
|
593
|
+
}, HeapAsync2.prototype._bottomN_push = function(n2) {
|
|
594
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
595
|
+
var bottomHeap, startAt, parentStartAt, indices, i, arr, i;
|
|
596
|
+
return __generator$1(this, function(_a) {
|
|
597
|
+
switch (_a.label) {
|
|
598
|
+
case 0:
|
|
599
|
+
return bottomHeap = new HeapAsync2(this.compare), bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), [4, bottomHeap.init()];
|
|
600
|
+
case 1:
|
|
601
|
+
for (_a.sent(), startAt = this.heapArray.length - 1 - n2, parentStartAt = HeapAsync2.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
|
|
602
|
+
indices.push(i);
|
|
603
|
+
arr = this.heapArray, _a.label = 2;
|
|
604
|
+
case 2:
|
|
605
|
+
return indices.length ? (i = indices.shift(), [4, this.compare(arr[i], bottomHeap.peek())]) : [3, 6];
|
|
606
|
+
case 3:
|
|
607
|
+
return _a.sent() > 0 ? [4, bottomHeap.replace(arr[i])] : [3, 5];
|
|
608
|
+
case 4:
|
|
609
|
+
_a.sent(), i % 2 && indices.push(HeapAsync2.getParentIndexOf(i)), _a.label = 5;
|
|
610
|
+
case 5:
|
|
611
|
+
return [3, 2];
|
|
612
|
+
case 6:
|
|
613
|
+
return [2, bottomHeap.toArray()];
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
});
|
|
617
|
+
}, HeapAsync2.prototype._moveNode = function(j, k) {
|
|
618
|
+
var _a;
|
|
619
|
+
_a = __read$1([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
|
|
620
|
+
}, HeapAsync2.prototype._sortNodeDown = function(i) {
|
|
621
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
622
|
+
var moveIt, self2, getPotentialParent, childrenIdx, bestChildIndex, j, bestChild, _a, _this = this;
|
|
623
|
+
return __generator$1(this, function(_b) {
|
|
624
|
+
switch (_b.label) {
|
|
625
|
+
case 0:
|
|
626
|
+
moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j2) {
|
|
627
|
+
return __awaiter(_this, void 0, void 0, function() {
|
|
628
|
+
var _a2;
|
|
629
|
+
return __generator$1(this, function(_b2) {
|
|
630
|
+
switch (_b2.label) {
|
|
631
|
+
case 0:
|
|
632
|
+
return _a2 = this.heapArray.length > j2, _a2 ? [4, this.compare(this.heapArray[j2], this.heapArray[best])] : [3, 2];
|
|
633
|
+
case 1:
|
|
634
|
+
_a2 = _b2.sent() < 0, _b2.label = 2;
|
|
635
|
+
case 2:
|
|
636
|
+
return _a2 && (best = j2), [2, best];
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
});
|
|
640
|
+
}, _b.label = 1;
|
|
641
|
+
case 1:
|
|
642
|
+
if (!moveIt) return [3, 8];
|
|
643
|
+
childrenIdx = HeapAsync2.getChildrenIndexOf(i), bestChildIndex = childrenIdx[0], j = 1, _b.label = 2;
|
|
644
|
+
case 2:
|
|
645
|
+
return j < childrenIdx.length ? [4, getPotentialParent(bestChildIndex, childrenIdx[j])] : [3, 5];
|
|
646
|
+
case 3:
|
|
647
|
+
bestChildIndex = _b.sent(), _b.label = 4;
|
|
648
|
+
case 4:
|
|
649
|
+
return ++j, [3, 2];
|
|
650
|
+
case 5:
|
|
651
|
+
return bestChild = this.heapArray[bestChildIndex], _a = typeof bestChild < "u", _a ? [4, this.compare(self2, bestChild)] : [3, 7];
|
|
652
|
+
case 6:
|
|
653
|
+
_a = _b.sent() > 0, _b.label = 7;
|
|
654
|
+
case 7:
|
|
655
|
+
return _a ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1, [3, 1];
|
|
656
|
+
case 8:
|
|
657
|
+
return [
|
|
658
|
+
2
|
|
659
|
+
/*return*/
|
|
660
|
+
];
|
|
661
|
+
}
|
|
662
|
+
});
|
|
663
|
+
});
|
|
664
|
+
}, HeapAsync2.prototype._sortNodeUp = function(i) {
|
|
665
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
666
|
+
var moveIt, pi, _a;
|
|
667
|
+
return __generator$1(this, function(_b) {
|
|
668
|
+
switch (_b.label) {
|
|
669
|
+
case 0:
|
|
670
|
+
moveIt = i > 0, _b.label = 1;
|
|
671
|
+
case 1:
|
|
672
|
+
return moveIt ? (pi = HeapAsync2.getParentIndexOf(i), _a = pi >= 0, _a ? [4, this.compare(this.heapArray[pi], this.heapArray[i])] : [3, 3]) : [3, 4];
|
|
673
|
+
case 2:
|
|
674
|
+
_a = _b.sent() > 0, _b.label = 3;
|
|
675
|
+
case 3:
|
|
676
|
+
return _a ? (this._moveNode(i, pi), i = pi) : moveIt = !1, [3, 1];
|
|
677
|
+
case 4:
|
|
678
|
+
return [
|
|
679
|
+
2
|
|
680
|
+
/*return*/
|
|
681
|
+
];
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
});
|
|
685
|
+
}, HeapAsync2.prototype._topN_push = function(n2) {
|
|
686
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
687
|
+
var topHeap, indices, arr, i;
|
|
688
|
+
return __generator$1(this, function(_a) {
|
|
689
|
+
switch (_a.label) {
|
|
690
|
+
case 0:
|
|
691
|
+
topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, indices = [0], arr = this.heapArray, _a.label = 1;
|
|
692
|
+
case 1:
|
|
693
|
+
return indices.length ? (i = indices.shift(), i < arr.length ? topHeap.length < n2 ? [4, topHeap.push(arr[i])] : [3, 3] : [3, 6]) : [3, 7];
|
|
694
|
+
case 2:
|
|
695
|
+
return _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), [3, 6];
|
|
696
|
+
case 3:
|
|
697
|
+
return [4, this.compare(arr[i], topHeap.peek())];
|
|
698
|
+
case 4:
|
|
699
|
+
return _a.sent() < 0 ? [4, topHeap.replace(arr[i])] : [3, 6];
|
|
700
|
+
case 5:
|
|
701
|
+
_a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 6;
|
|
702
|
+
case 6:
|
|
703
|
+
return [3, 1];
|
|
704
|
+
case 7:
|
|
705
|
+
return [2, topHeap.toArray()];
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
}, HeapAsync2.prototype._topN_fill = function(n2) {
|
|
710
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
711
|
+
var heapArray, topHeap, branch, indices, i, i;
|
|
712
|
+
return __generator$1(this, function(_a) {
|
|
713
|
+
switch (_a.label) {
|
|
714
|
+
case 0:
|
|
715
|
+
return heapArray = this.heapArray, topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), [4, topHeap.init()];
|
|
716
|
+
case 1:
|
|
717
|
+
for (_a.sent(), branch = HeapAsync2.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
|
|
718
|
+
indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i).filter(function(l) {
|
|
719
|
+
return l < heapArray.length;
|
|
720
|
+
})), !1));
|
|
721
|
+
(n2 - 1) % 2 && indices.push(n2), _a.label = 2;
|
|
722
|
+
case 2:
|
|
723
|
+
return indices.length ? (i = indices.shift(), i < heapArray.length ? [4, this.compare(heapArray[i], topHeap.peek())] : [3, 5]) : [3, 6];
|
|
724
|
+
case 3:
|
|
725
|
+
return _a.sent() < 0 ? [4, topHeap.replace(heapArray[i])] : [3, 5];
|
|
726
|
+
case 4:
|
|
727
|
+
_a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 5;
|
|
728
|
+
case 5:
|
|
729
|
+
return [3, 2];
|
|
730
|
+
case 6:
|
|
731
|
+
return [2, topHeap.toArray()];
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
});
|
|
735
|
+
}, HeapAsync2.prototype._topN_heap = function(n2) {
|
|
736
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
737
|
+
var topHeap, result, i, _a, _b;
|
|
738
|
+
return __generator$1(this, function(_c) {
|
|
739
|
+
switch (_c.label) {
|
|
740
|
+
case 0:
|
|
741
|
+
topHeap = this.clone(), result = [], i = 0, _c.label = 1;
|
|
742
|
+
case 1:
|
|
743
|
+
return i < n2 ? (_b = (_a = result).push, [4, topHeap.pop()]) : [3, 4];
|
|
744
|
+
case 2:
|
|
745
|
+
_b.apply(_a, [_c.sent()]), _c.label = 3;
|
|
746
|
+
case 3:
|
|
747
|
+
return ++i, [3, 1];
|
|
748
|
+
case 4:
|
|
749
|
+
return [2, result];
|
|
750
|
+
}
|
|
751
|
+
});
|
|
752
|
+
});
|
|
753
|
+
}, HeapAsync2.prototype._topIdxOf = function(list) {
|
|
754
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
755
|
+
var idx, top, i, comp;
|
|
756
|
+
return __generator$1(this, function(_a) {
|
|
757
|
+
switch (_a.label) {
|
|
758
|
+
case 0:
|
|
759
|
+
if (!list.length)
|
|
760
|
+
return [2, -1];
|
|
761
|
+
idx = 0, top = list[idx], i = 1, _a.label = 1;
|
|
762
|
+
case 1:
|
|
763
|
+
return i < list.length ? [4, this.compare(list[i], top)] : [3, 4];
|
|
764
|
+
case 2:
|
|
765
|
+
comp = _a.sent(), comp < 0 && (idx = i, top = list[i]), _a.label = 3;
|
|
766
|
+
case 3:
|
|
767
|
+
return ++i, [3, 1];
|
|
768
|
+
case 4:
|
|
769
|
+
return [2, idx];
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
});
|
|
773
|
+
}, HeapAsync2.prototype._topOf = function() {
|
|
774
|
+
for (var list = [], _i = 0; _i < arguments.length; _i++)
|
|
775
|
+
list[_i] = arguments[_i];
|
|
776
|
+
return __awaiter(this, void 0, void 0, function() {
|
|
777
|
+
var heap;
|
|
778
|
+
return __generator$1(this, function(_a) {
|
|
779
|
+
switch (_a.label) {
|
|
780
|
+
case 0:
|
|
781
|
+
return heap = new HeapAsync2(this.compare), [4, heap.init(list)];
|
|
782
|
+
case 1:
|
|
783
|
+
return _a.sent(), [2, heap.peek()];
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
});
|
|
787
|
+
}, HeapAsync2;
|
|
788
|
+
})()
|
|
789
|
+
), __generator = function(thisArg, body) {
|
|
790
|
+
var _ = { label: 0, sent: function() {
|
|
791
|
+
if (t[0] & 1) throw t[1];
|
|
792
|
+
return t[1];
|
|
793
|
+
}, trys: [], ops: [] }, f, y, t, g;
|
|
794
|
+
return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
|
|
795
|
+
return this;
|
|
796
|
+
}), g;
|
|
797
|
+
function verb(n2) {
|
|
798
|
+
return function(v) {
|
|
799
|
+
return step([n2, v]);
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
function step(op) {
|
|
803
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
804
|
+
for (; g && (g = 0, op[0] && (_ = 0)), _; ) try {
|
|
805
|
+
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) return t;
|
|
806
|
+
switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
|
|
807
|
+
case 0:
|
|
808
|
+
case 1:
|
|
809
|
+
t = op;
|
|
810
|
+
break;
|
|
811
|
+
case 4:
|
|
812
|
+
return _.label++, { value: op[1], done: !1 };
|
|
813
|
+
case 5:
|
|
814
|
+
_.label++, y = op[1], op = [0];
|
|
815
|
+
continue;
|
|
816
|
+
case 7:
|
|
817
|
+
op = _.ops.pop(), _.trys.pop();
|
|
818
|
+
continue;
|
|
819
|
+
default:
|
|
820
|
+
if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
821
|
+
_ = 0;
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
825
|
+
_.label = op[1];
|
|
826
|
+
break;
|
|
827
|
+
}
|
|
828
|
+
if (op[0] === 6 && _.label < t[1]) {
|
|
829
|
+
_.label = t[1], t = op;
|
|
830
|
+
break;
|
|
831
|
+
}
|
|
832
|
+
if (t && _.label < t[2]) {
|
|
833
|
+
_.label = t[2], _.ops.push(op);
|
|
834
|
+
break;
|
|
835
|
+
}
|
|
836
|
+
t[2] && _.ops.pop(), _.trys.pop();
|
|
837
|
+
continue;
|
|
838
|
+
}
|
|
839
|
+
op = body.call(thisArg, _);
|
|
840
|
+
} catch (e) {
|
|
841
|
+
op = [6, e], y = 0;
|
|
842
|
+
} finally {
|
|
843
|
+
f = t = 0;
|
|
844
|
+
}
|
|
845
|
+
if (op[0] & 5) throw op[1];
|
|
846
|
+
return { value: op[0] ? op[1] : void 0, done: !0 };
|
|
847
|
+
}
|
|
848
|
+
}, __read = function(o, n2) {
|
|
849
|
+
var m = typeof Symbol == "function" && o[Symbol.iterator];
|
|
850
|
+
if (!m) return o;
|
|
851
|
+
var i = m.call(o), r2, ar = [], e;
|
|
852
|
+
try {
|
|
853
|
+
for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; ) ar.push(r2.value);
|
|
854
|
+
} catch (error) {
|
|
855
|
+
e = { error };
|
|
856
|
+
} finally {
|
|
857
|
+
try {
|
|
858
|
+
r2 && !r2.done && (m = i.return) && m.call(i);
|
|
859
|
+
} finally {
|
|
860
|
+
if (e) throw e.error;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
return ar;
|
|
864
|
+
}, __spreadArray = function(to, from, pack) {
|
|
865
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++)
|
|
866
|
+
(ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
|
|
867
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
868
|
+
}, toInt = function(n2) {
|
|
869
|
+
return ~~n2;
|
|
870
|
+
}, Heap2 = (
|
|
871
|
+
/** @class */
|
|
872
|
+
(function() {
|
|
873
|
+
function Heap3(compare) {
|
|
874
|
+
compare === void 0 && (compare = Heap3.minComparator);
|
|
875
|
+
var _this = this;
|
|
876
|
+
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) {
|
|
877
|
+
return -1 * _this.compare(a, b);
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
return Heap3.getChildrenIndexOf = function(idx) {
|
|
881
|
+
return [idx * 2 + 1, idx * 2 + 2];
|
|
882
|
+
}, Heap3.getParentIndexOf = function(idx) {
|
|
883
|
+
if (idx <= 0)
|
|
884
|
+
return -1;
|
|
885
|
+
var whichChildren = idx % 2 ? 1 : 2;
|
|
886
|
+
return Math.floor((idx - whichChildren) / 2);
|
|
887
|
+
}, Heap3.getSiblingIndexOf = function(idx) {
|
|
888
|
+
if (idx <= 0)
|
|
889
|
+
return -1;
|
|
890
|
+
var whichChildren = idx % 2 ? 1 : -1;
|
|
891
|
+
return idx + whichChildren;
|
|
892
|
+
}, Heap3.minComparator = function(a, b) {
|
|
893
|
+
return a > b ? 1 : a < b ? -1 : 0;
|
|
894
|
+
}, Heap3.maxComparator = function(a, b) {
|
|
895
|
+
return b > a ? 1 : b < a ? -1 : 0;
|
|
896
|
+
}, Heap3.minComparatorNumber = function(a, b) {
|
|
897
|
+
return a - b;
|
|
898
|
+
}, Heap3.maxComparatorNumber = function(a, b) {
|
|
899
|
+
return b - a;
|
|
900
|
+
}, Heap3.defaultIsEqual = function(a, b) {
|
|
901
|
+
return a === b;
|
|
902
|
+
}, Heap3.print = function(heap) {
|
|
903
|
+
function deep(i2) {
|
|
904
|
+
var pi = Heap3.getParentIndexOf(i2);
|
|
905
|
+
return Math.floor(Math.log2(pi + 1));
|
|
906
|
+
}
|
|
907
|
+
function repeat(str, times) {
|
|
908
|
+
for (var out = ""; times > 0; --times)
|
|
909
|
+
out += str;
|
|
910
|
+
return out;
|
|
911
|
+
}
|
|
912
|
+
for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
|
|
913
|
+
var i = deep(node) + 1;
|
|
914
|
+
node === 0 && (i = 0);
|
|
915
|
+
var nodeText = String(heap.get(node));
|
|
916
|
+
nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
|
|
917
|
+
}
|
|
918
|
+
return lines.map(function(line, i2) {
|
|
919
|
+
var times = Math.pow(2, maxLines - i2) - 1;
|
|
920
|
+
return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
|
|
921
|
+
var half = (maxLength - el.length) / 2;
|
|
922
|
+
return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
|
|
923
|
+
}).join(repeat(" ", times * maxLength));
|
|
924
|
+
}).join(`
|
|
925
|
+
`);
|
|
926
|
+
}, Heap3.heapify = function(arr, compare) {
|
|
927
|
+
var heap = new Heap3(compare);
|
|
928
|
+
return heap.heapArray = arr, heap.init(), heap;
|
|
929
|
+
}, Heap3.heappop = function(heapArr, compare) {
|
|
930
|
+
var heap = new Heap3(compare);
|
|
931
|
+
return heap.heapArray = heapArr, heap.pop();
|
|
932
|
+
}, Heap3.heappush = function(heapArr, item, compare) {
|
|
933
|
+
var heap = new Heap3(compare);
|
|
934
|
+
heap.heapArray = heapArr, heap.push(item);
|
|
935
|
+
}, Heap3.heappushpop = function(heapArr, item, compare) {
|
|
936
|
+
var heap = new Heap3(compare);
|
|
937
|
+
return heap.heapArray = heapArr, heap.pushpop(item);
|
|
938
|
+
}, Heap3.heapreplace = function(heapArr, item, compare) {
|
|
939
|
+
var heap = new Heap3(compare);
|
|
940
|
+
return heap.heapArray = heapArr, heap.replace(item);
|
|
941
|
+
}, Heap3.heaptop = function(heapArr, n2, compare) {
|
|
942
|
+
n2 === void 0 && (n2 = 1);
|
|
943
|
+
var heap = new Heap3(compare);
|
|
944
|
+
return heap.heapArray = heapArr, heap.top(n2);
|
|
945
|
+
}, Heap3.heapbottom = function(heapArr, n2, compare) {
|
|
946
|
+
n2 === void 0 && (n2 = 1);
|
|
947
|
+
var heap = new Heap3(compare);
|
|
948
|
+
return heap.heapArray = heapArr, heap.bottom(n2);
|
|
949
|
+
}, Heap3.nlargest = function(n2, iterable, compare) {
|
|
950
|
+
var heap = new Heap3(compare);
|
|
951
|
+
return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.top(n2);
|
|
952
|
+
}, Heap3.nsmallest = function(n2, iterable, compare) {
|
|
953
|
+
var heap = new Heap3(compare);
|
|
954
|
+
return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.bottom(n2);
|
|
955
|
+
}, Heap3.prototype.add = function(element) {
|
|
956
|
+
return this._sortNodeUp(this.heapArray.push(element) - 1), this._applyLimit(), !0;
|
|
957
|
+
}, Heap3.prototype.addAll = function(elements) {
|
|
958
|
+
var _a, i = this.length;
|
|
959
|
+
(_a = this.heapArray).push.apply(_a, __spreadArray([], __read(elements), !1));
|
|
960
|
+
for (var l = this.length; i < l; ++i)
|
|
961
|
+
this._sortNodeUp(i);
|
|
962
|
+
return this._applyLimit(), !0;
|
|
963
|
+
}, Heap3.prototype.bottom = function(n2) {
|
|
964
|
+
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);
|
|
965
|
+
}, Heap3.prototype.check = function() {
|
|
966
|
+
var _this = this;
|
|
967
|
+
return this.heapArray.find(function(el, j) {
|
|
968
|
+
return !!_this.getChildrenOf(j).find(function(ch) {
|
|
969
|
+
return _this.compare(el, ch) > 0;
|
|
970
|
+
});
|
|
971
|
+
});
|
|
972
|
+
}, Heap3.prototype.clear = function() {
|
|
973
|
+
this.heapArray = [];
|
|
974
|
+
}, Heap3.prototype.clone = function() {
|
|
975
|
+
var cloned = new Heap3(this.comparator());
|
|
976
|
+
return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
|
|
977
|
+
}, Heap3.prototype.comparator = function() {
|
|
978
|
+
return this.compare;
|
|
979
|
+
}, Heap3.prototype.contains = function(o, callbackFn) {
|
|
980
|
+
return callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.indexOf(o, callbackFn) !== -1;
|
|
981
|
+
}, Heap3.prototype.init = function(array) {
|
|
982
|
+
array && (this.heapArray = __spreadArray([], __read(array), !1));
|
|
983
|
+
for (var i = Math.floor(this.heapArray.length); i >= 0; --i)
|
|
984
|
+
this._sortNodeDown(i);
|
|
985
|
+
this._applyLimit();
|
|
986
|
+
}, Heap3.prototype.isEmpty = function() {
|
|
987
|
+
return this.length === 0;
|
|
988
|
+
}, Heap3.prototype.indexOf = function(element, callbackFn) {
|
|
989
|
+
if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
|
|
990
|
+
return -1;
|
|
991
|
+
for (var indexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
|
|
992
|
+
var currentElement = this.heapArray[currentIndex];
|
|
993
|
+
if (callbackFn(currentElement, element))
|
|
994
|
+
return currentIndex;
|
|
995
|
+
this.compare(currentElement, element) <= 0 && indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1)), currentIndex = indexes.shift() || this.heapArray.length;
|
|
996
|
+
}
|
|
997
|
+
return -1;
|
|
998
|
+
}, Heap3.prototype.indexOfEvery = function(element, callbackFn) {
|
|
999
|
+
if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
|
|
1000
|
+
return [];
|
|
1001
|
+
for (var indexes = [], foundIndexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
|
|
1002
|
+
var currentElement = this.heapArray[currentIndex];
|
|
1003
|
+
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;
|
|
1004
|
+
}
|
|
1005
|
+
return foundIndexes;
|
|
1006
|
+
}, Heap3.prototype.leafs = function() {
|
|
1007
|
+
if (this.heapArray.length === 0)
|
|
1008
|
+
return [];
|
|
1009
|
+
var pi = Heap3.getParentIndexOf(this.heapArray.length - 1);
|
|
1010
|
+
return this.heapArray.slice(pi + 1);
|
|
1011
|
+
}, Object.defineProperty(Heap3.prototype, "length", {
|
|
1012
|
+
/**
|
|
1013
|
+
* Length of the heap. Aliases: {@link size}.
|
|
1014
|
+
* @return {Number}
|
|
1015
|
+
* @see size
|
|
1016
|
+
*/
|
|
1017
|
+
get: function() {
|
|
1018
|
+
return this.heapArray.length;
|
|
1019
|
+
},
|
|
1020
|
+
enumerable: !1,
|
|
1021
|
+
configurable: !0
|
|
1022
|
+
}), Object.defineProperty(Heap3.prototype, "limit", {
|
|
1023
|
+
/**
|
|
1024
|
+
* Get length limit of the heap.
|
|
1025
|
+
* Use {@link setLimit} or {@link limit} to set the limit.
|
|
1026
|
+
* @return {Number}
|
|
1027
|
+
* @see setLimit
|
|
1028
|
+
*/
|
|
1029
|
+
get: function() {
|
|
1030
|
+
return this._limit;
|
|
1031
|
+
},
|
|
1032
|
+
/**
|
|
1033
|
+
* Set length limit of the heap. Same as using {@link setLimit}.
|
|
1034
|
+
* @description If the heap is longer than the limit, the needed amount of leafs are removed.
|
|
1035
|
+
* @param {Number} _l Limit, defaults to 0 (no limit). Negative, Infinity, or NaN values set the limit to 0.
|
|
1036
|
+
* @see setLimit
|
|
1037
|
+
*/
|
|
1038
|
+
set: function(_l) {
|
|
1039
|
+
_l < 0 || isNaN(_l) ? this._limit = 0 : this._limit = ~~_l, this._applyLimit();
|
|
1040
|
+
},
|
|
1041
|
+
enumerable: !1,
|
|
1042
|
+
configurable: !0
|
|
1043
|
+
}), Heap3.prototype.setLimit = function(_l) {
|
|
1044
|
+
return this.limit = _l, _l < 0 || isNaN(_l) ? NaN : this._limit;
|
|
1045
|
+
}, Heap3.prototype.peek = function() {
|
|
1046
|
+
return this.heapArray[0];
|
|
1047
|
+
}, Heap3.prototype.pop = function() {
|
|
1048
|
+
var last = this.heapArray.pop();
|
|
1049
|
+
return this.length > 0 && last !== void 0 ? this.replace(last) : last;
|
|
1050
|
+
}, Heap3.prototype.push = function() {
|
|
1051
|
+
for (var elements = [], _i = 0; _i < arguments.length; _i++)
|
|
1052
|
+
elements[_i] = arguments[_i];
|
|
1053
|
+
return elements.length < 1 ? !1 : elements.length === 1 ? this.add(elements[0]) : this.addAll(elements);
|
|
1054
|
+
}, Heap3.prototype.pushpop = function(element) {
|
|
1055
|
+
var _a;
|
|
1056
|
+
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;
|
|
1057
|
+
}, Heap3.prototype.remove = function(o, callbackFn) {
|
|
1058
|
+
if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.length > 0) {
|
|
1059
|
+
if (o === void 0)
|
|
1060
|
+
return this.pop(), !0;
|
|
1061
|
+
var idx = this.indexOf(o, callbackFn);
|
|
1062
|
+
if (idx >= 0)
|
|
1063
|
+
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;
|
|
1064
|
+
}
|
|
1065
|
+
return !1;
|
|
1066
|
+
}, Heap3.prototype.replace = function(element) {
|
|
1067
|
+
var peek = this.heapArray[0];
|
|
1068
|
+
return this.heapArray[0] = element, this._sortNodeDown(0), peek;
|
|
1069
|
+
}, Heap3.prototype.size = function() {
|
|
1070
|
+
return this.length;
|
|
1071
|
+
}, Heap3.prototype.top = function(n2) {
|
|
1072
|
+
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);
|
|
1073
|
+
}, Heap3.prototype.toArray = function() {
|
|
1074
|
+
return __spreadArray([], __read(this.heapArray), !1);
|
|
1075
|
+
}, Heap3.prototype.toString = function() {
|
|
1076
|
+
return this.heapArray.toString();
|
|
1077
|
+
}, Heap3.prototype.get = function(i) {
|
|
1078
|
+
return this.heapArray[i];
|
|
1079
|
+
}, Heap3.prototype.getChildrenOf = function(idx) {
|
|
1080
|
+
var _this = this;
|
|
1081
|
+
return Heap3.getChildrenIndexOf(idx).map(function(i) {
|
|
1082
|
+
return _this.heapArray[i];
|
|
1083
|
+
}).filter(function(e) {
|
|
1084
|
+
return e !== void 0;
|
|
1085
|
+
});
|
|
1086
|
+
}, Heap3.prototype.getParentOf = function(idx) {
|
|
1087
|
+
var pi = Heap3.getParentIndexOf(idx);
|
|
1088
|
+
return this.heapArray[pi];
|
|
1089
|
+
}, Heap3.prototype[Symbol.iterator] = function() {
|
|
1090
|
+
return __generator(this, function(_a) {
|
|
1091
|
+
switch (_a.label) {
|
|
1092
|
+
case 0:
|
|
1093
|
+
return this.length ? [4, this.pop()] : [3, 2];
|
|
1094
|
+
case 1:
|
|
1095
|
+
return _a.sent(), [3, 0];
|
|
1096
|
+
case 2:
|
|
1097
|
+
return [
|
|
1098
|
+
2
|
|
1099
|
+
/*return*/
|
|
1100
|
+
];
|
|
1101
|
+
}
|
|
1102
|
+
});
|
|
1103
|
+
}, Heap3.prototype.iterator = function() {
|
|
1104
|
+
return this.toArray();
|
|
1105
|
+
}, Heap3.prototype._applyLimit = function() {
|
|
1106
|
+
if (this._limit > 0 && this._limit < this.heapArray.length)
|
|
1107
|
+
for (var rm = this.heapArray.length - this._limit; rm; )
|
|
1108
|
+
this.heapArray.pop(), --rm;
|
|
1109
|
+
}, Heap3.prototype._bottomN_push = function(n2) {
|
|
1110
|
+
var bottomHeap = new Heap3(this.compare);
|
|
1111
|
+
bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), bottomHeap.init();
|
|
1112
|
+
for (var startAt = this.heapArray.length - 1 - n2, parentStartAt = Heap3.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
|
|
1113
|
+
indices.push(i);
|
|
1114
|
+
for (var arr = this.heapArray; indices.length; ) {
|
|
1115
|
+
var i = indices.shift();
|
|
1116
|
+
this.compare(arr[i], bottomHeap.peek()) > 0 && (bottomHeap.replace(arr[i]), i % 2 && indices.push(Heap3.getParentIndexOf(i)));
|
|
1117
|
+
}
|
|
1118
|
+
return bottomHeap.toArray();
|
|
1119
|
+
}, Heap3.prototype._moveNode = function(j, k) {
|
|
1120
|
+
var _a;
|
|
1121
|
+
_a = __read([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
|
|
1122
|
+
}, Heap3.prototype._sortNodeDown = function(i) {
|
|
1123
|
+
for (var _this = this, moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j) {
|
|
1124
|
+
return _this.heapArray.length > j && _this.compare(_this.heapArray[j], _this.heapArray[best]) < 0 && (best = j), best;
|
|
1125
|
+
}; moveIt; ) {
|
|
1126
|
+
var childrenIdx = Heap3.getChildrenIndexOf(i), bestChildIndex = childrenIdx.reduce(getPotentialParent, childrenIdx[0]), bestChild = this.heapArray[bestChildIndex];
|
|
1127
|
+
typeof bestChild < "u" && this.compare(self2, bestChild) > 0 ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1;
|
|
1128
|
+
}
|
|
1129
|
+
}, Heap3.prototype._sortNodeUp = function(i) {
|
|
1130
|
+
for (var moveIt = i > 0; moveIt; ) {
|
|
1131
|
+
var pi = Heap3.getParentIndexOf(i);
|
|
1132
|
+
pi >= 0 && this.compare(this.heapArray[pi], this.heapArray[i]) > 0 ? (this._moveNode(i, pi), i = pi) : moveIt = !1;
|
|
1133
|
+
}
|
|
1134
|
+
}, Heap3.prototype._topN_push = function(n2) {
|
|
1135
|
+
var topHeap = new Heap3(this._invertedCompare);
|
|
1136
|
+
topHeap.limit = n2;
|
|
1137
|
+
for (var indices = [0], arr = this.heapArray; indices.length; ) {
|
|
1138
|
+
var i = indices.shift();
|
|
1139
|
+
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))));
|
|
1140
|
+
}
|
|
1141
|
+
return topHeap.toArray();
|
|
1142
|
+
}, Heap3.prototype._topN_fill = function(n2) {
|
|
1143
|
+
var heapArray = this.heapArray, topHeap = new Heap3(this._invertedCompare);
|
|
1144
|
+
topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), topHeap.init();
|
|
1145
|
+
for (var branch = Heap3.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
|
|
1146
|
+
indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i).filter(function(l) {
|
|
1147
|
+
return l < heapArray.length;
|
|
1148
|
+
})), !1));
|
|
1149
|
+
for ((n2 - 1) % 2 && indices.push(n2); indices.length; ) {
|
|
1150
|
+
var i = indices.shift();
|
|
1151
|
+
i < heapArray.length && this.compare(heapArray[i], topHeap.peek()) < 0 && (topHeap.replace(heapArray[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1)));
|
|
1152
|
+
}
|
|
1153
|
+
return topHeap.toArray();
|
|
1154
|
+
}, Heap3.prototype._topN_heap = function(n2) {
|
|
1155
|
+
for (var topHeap = this.clone(), result = [], i = 0; i < n2; ++i)
|
|
1156
|
+
result.push(topHeap.pop());
|
|
1157
|
+
return result;
|
|
1158
|
+
}, Heap3.prototype._topIdxOf = function(list) {
|
|
1159
|
+
if (!list.length)
|
|
1160
|
+
return -1;
|
|
1161
|
+
for (var idx = 0, top = list[idx], i = 1; i < list.length; ++i) {
|
|
1162
|
+
var comp = this.compare(list[i], top);
|
|
1163
|
+
comp < 0 && (idx = i, top = list[i]);
|
|
1164
|
+
}
|
|
1165
|
+
return idx;
|
|
1166
|
+
}, Heap3.prototype._topOf = function() {
|
|
1167
|
+
for (var list = [], _i = 0; _i < arguments.length; _i++)
|
|
1168
|
+
list[_i] = arguments[_i];
|
|
1169
|
+
var heap = new Heap3(this.compare);
|
|
1170
|
+
return heap.init(list), heap.peek();
|
|
1171
|
+
}, Heap3;
|
|
1172
|
+
})()
|
|
1173
|
+
);
|
|
1174
|
+
exports2.Heap = Heap2, exports2.HeapAsync = HeapAsync, exports2.default = Heap2, exports2.toInt = toInt, Object.defineProperty(exports2, "__esModule", { value: !0 });
|
|
1175
|
+
}));
|
|
1176
|
+
}
|
|
1177
|
+
});
|
|
1178
|
+
|
|
1179
|
+
// ../workflows-shared/src/engine.ts
|
|
1180
|
+
import { DurableObject } from "cloudflare:workers";
|
|
1181
|
+
|
|
1182
|
+
// ../workflows-shared/src/context.ts
|
|
1183
|
+
import { RpcTarget } from "cloudflare:workers";
|
|
1184
|
+
|
|
1185
|
+
// ../../node_modules/.pnpm/itty-time@2.0.2/node_modules/itty-time/index.mjs
|
|
1186
|
+
var n = { year: 315576e5, month: 2592e6, week: 6048e5, day: 864e5, hour: 36e5, minute: 6e4, second: 1e3, m: 1 }, r = (e) => {
|
|
1187
|
+
if (!isNaN(+e)) return +e;
|
|
1188
|
+
let [, t, r2] = e.match(/^([^ ]+) +(\w\w*?)s?$/) || [, e];
|
|
1189
|
+
return +t * (n[r2] || 1);
|
|
1190
|
+
};
|
|
1191
|
+
|
|
1192
|
+
// ../workflows-shared/src/instance.ts
|
|
1193
|
+
var INSTANCE_METADATA = "INSTANCE_METADATA";
|
|
1194
|
+
function instanceStatusName(status) {
|
|
1195
|
+
switch (status) {
|
|
1196
|
+
case 0 /* Queued */:
|
|
1197
|
+
return "queued";
|
|
1198
|
+
case 1 /* Running */:
|
|
1199
|
+
return "running";
|
|
1200
|
+
case 2 /* Paused */:
|
|
1201
|
+
return "paused";
|
|
1202
|
+
case 3 /* Errored */:
|
|
1203
|
+
return "errored";
|
|
1204
|
+
case 4 /* Terminated */:
|
|
1205
|
+
return "terminated";
|
|
1206
|
+
case 5 /* Complete */:
|
|
1207
|
+
return "complete";
|
|
1208
|
+
default:
|
|
1209
|
+
return "unknown";
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
function toInstanceStatus(status) {
|
|
1213
|
+
switch (status) {
|
|
1214
|
+
case "queued":
|
|
1215
|
+
return 0 /* Queued */;
|
|
1216
|
+
case "running":
|
|
1217
|
+
return 1 /* Running */;
|
|
1218
|
+
case "paused":
|
|
1219
|
+
return 2 /* Paused */;
|
|
1220
|
+
case "errored":
|
|
1221
|
+
return 3 /* Errored */;
|
|
1222
|
+
case "terminated":
|
|
1223
|
+
return 4 /* Terminated */;
|
|
1224
|
+
case "complete":
|
|
1225
|
+
return 5 /* Complete */;
|
|
1226
|
+
case "unknown":
|
|
1227
|
+
throw new Error("unknown cannot be parsed into a InstanceStatus");
|
|
1228
|
+
default:
|
|
1229
|
+
throw new Error(
|
|
1230
|
+
`${status} was not handled because it's not a valid InstanceStatus`
|
|
1231
|
+
);
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
// ../workflows-shared/src/lib/cache.ts
|
|
1236
|
+
async function computeHash(value) {
|
|
1237
|
+
let msgUint8 = new TextEncoder().encode(value), hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8);
|
|
1238
|
+
return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// ../workflows-shared/src/lib/errors.ts
|
|
1242
|
+
var WorkflowTimeoutError = class extends Error {
|
|
1243
|
+
name = "WorkflowTimeoutError";
|
|
1244
|
+
}, WorkflowInternalError = class extends Error {
|
|
1245
|
+
name = "WorkflowInternalError";
|
|
1246
|
+
}, WorkflowFatalError = class extends Error {
|
|
1247
|
+
name = "WorkflowFatalError";
|
|
1248
|
+
toJSON() {
|
|
1249
|
+
return {
|
|
1250
|
+
name: this.name,
|
|
1251
|
+
message: this.message
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
}, WorkflowError = class extends Error {
|
|
1255
|
+
name = "WorkflowError";
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
// ../workflows-shared/src/lib/retries.ts
|
|
1259
|
+
function calcRetryDuration(config, stepState) {
|
|
1260
|
+
let { attemptedCount: attemptCount } = stepState, { retries } = config, delay = r(retries.delay);
|
|
1261
|
+
switch (retries.backoff) {
|
|
1262
|
+
case "exponential":
|
|
1263
|
+
return delay * Math.pow(2, attemptCount - 1);
|
|
1264
|
+
case "linear":
|
|
1265
|
+
return delay * attemptCount;
|
|
1266
|
+
default:
|
|
1267
|
+
return delay;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// ../workflows-shared/src/lib/validators.ts
|
|
1272
|
+
var ALLOWED_STRING_ID_PATTERN = "^[a-zA-Z0-9_][a-zA-Z0-9-_]*$", ALLOWED_WORKFLOW_INSTANCE_ID_REGEX = new RegExp(
|
|
1273
|
+
ALLOWED_STRING_ID_PATTERN
|
|
1274
|
+
);
|
|
1275
|
+
var CONTROL_CHAR_REGEX = new RegExp("[\0-]");
|
|
1276
|
+
function isValidWorkflowInstanceId(id) {
|
|
1277
|
+
return typeof id != "string" || id.length > 100 ? !1 : ALLOWED_WORKFLOW_INSTANCE_ID_REGEX.test(id);
|
|
1278
|
+
}
|
|
1279
|
+
function isValidStepName(name) {
|
|
1280
|
+
return name.length > 256 ? !1 : !CONTROL_CHAR_REGEX.test(name);
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
// ../workflows-shared/src/context.ts
|
|
1284
|
+
var defaultConfig = {
|
|
1285
|
+
retries: {
|
|
1286
|
+
limit: 5,
|
|
1287
|
+
delay: 1e3,
|
|
1288
|
+
backoff: "exponential"
|
|
1289
|
+
},
|
|
1290
|
+
timeout: "10 minutes"
|
|
1291
|
+
}, Context = class extends RpcTarget {
|
|
1292
|
+
#engine;
|
|
1293
|
+
#state;
|
|
1294
|
+
#counters = /* @__PURE__ */ new Map();
|
|
1295
|
+
#lifetimeStepCounter = 0;
|
|
1296
|
+
constructor(engine, state) {
|
|
1297
|
+
super(), this.#engine = engine, this.#state = state;
|
|
1298
|
+
}
|
|
1299
|
+
#getCount(name) {
|
|
1300
|
+
let val = this.#counters.get(name) ?? 0;
|
|
1301
|
+
return val++, this.#counters.set(name, val), val;
|
|
1302
|
+
}
|
|
1303
|
+
async do(name, configOrCallback, callback) {
|
|
1304
|
+
let closure, stepConfig;
|
|
1305
|
+
callback ? (closure = callback, stepConfig = configOrCallback) : (closure = configOrCallback, stepConfig = {}), this.#lifetimeStepCounter++;
|
|
1306
|
+
let stepLimit = this.#engine.stepLimit;
|
|
1307
|
+
if (this.#lifetimeStepCounter > stepLimit)
|
|
1308
|
+
throw new WorkflowFatalError(
|
|
1309
|
+
`The limit of ${stepLimit} steps has been reached. This limit can be changed in your worker configuration.`
|
|
1310
|
+
);
|
|
1311
|
+
if (!isValidStepName(name)) {
|
|
1312
|
+
let error = new WorkflowFatalError(
|
|
1313
|
+
`Step name "${name}" exceeds max length (${256} chars) or invalid characters found`
|
|
1314
|
+
);
|
|
1315
|
+
throw error.isUserError = !0, error;
|
|
1316
|
+
}
|
|
1317
|
+
let config = {
|
|
1318
|
+
...defaultConfig,
|
|
1319
|
+
...stepConfig,
|
|
1320
|
+
retries: {
|
|
1321
|
+
...defaultConfig.retries,
|
|
1322
|
+
...stepConfig.retries
|
|
1323
|
+
}
|
|
1324
|
+
}, hash = await computeHash(name), count = this.#getCount("run-" + name), cacheKey = `${hash}-${count}`, valueKey = `${cacheKey}-value`, configKey = `${cacheKey}-config`, errorKey = `${cacheKey}-error`, stepNameWithCounter = `${name}-${count}`, stepStateKey = `${cacheKey}-metadata`, maybeMap = await this.#state.storage.get([
|
|
1325
|
+
valueKey,
|
|
1326
|
+
configKey,
|
|
1327
|
+
errorKey
|
|
1328
|
+
]), maybeResult = maybeMap.get(valueKey);
|
|
1329
|
+
if (maybeResult)
|
|
1330
|
+
return maybeResult.value;
|
|
1331
|
+
let maybeError = maybeMap.get(
|
|
1332
|
+
errorKey
|
|
1333
|
+
);
|
|
1334
|
+
if (maybeError)
|
|
1335
|
+
throw maybeError.isUserError = !0, maybeError;
|
|
1336
|
+
maybeMap.has(configKey) ? config = maybeMap.get(configKey) : await this.#state.storage.put(configKey, config);
|
|
1337
|
+
let attemptLogs = this.#engine.readLogsFromStep(cacheKey).filter(
|
|
1338
|
+
(val) => [
|
|
1339
|
+
11 /* ATTEMPT_SUCCESS */,
|
|
1340
|
+
12 /* ATTEMPT_FAILURE */,
|
|
1341
|
+
10 /* ATTEMPT_START */
|
|
1342
|
+
].includes(val.event)
|
|
1343
|
+
);
|
|
1344
|
+
if (attemptLogs.length > 0 && attemptLogs.at(-1)?.event === 10 /* ATTEMPT_START */) {
|
|
1345
|
+
let stepState = await this.#state.storage.get(
|
|
1346
|
+
stepStateKey
|
|
1347
|
+
) ?? {
|
|
1348
|
+
attemptedCount: 1
|
|
1349
|
+
}, priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, timeoutEntryPQ = this.#engine.priorityQueue.getFirst(
|
|
1350
|
+
(a) => a.hash === priorityQueueHash && a.type === "timeout"
|
|
1351
|
+
);
|
|
1352
|
+
timeoutEntryPQ !== void 0 && this.#engine.priorityQueue.remove(timeoutEntryPQ), this.#engine.writeLog(
|
|
1353
|
+
12 /* ATTEMPT_FAILURE */,
|
|
1354
|
+
cacheKey,
|
|
1355
|
+
stepNameWithCounter,
|
|
1356
|
+
{
|
|
1357
|
+
attempt: stepState.attemptedCount,
|
|
1358
|
+
error: {
|
|
1359
|
+
name: "WorkflowInternalError",
|
|
1360
|
+
message: "Attempt failed due to internal workflows error"
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
), await this.#state.storage.put(stepStateKey, stepState);
|
|
1364
|
+
}
|
|
1365
|
+
let doWrapper = async (doWrapperClosure) => {
|
|
1366
|
+
let stepState = await this.#state.storage.get(
|
|
1367
|
+
stepStateKey
|
|
1368
|
+
) ?? {
|
|
1369
|
+
attemptedCount: 0
|
|
1370
|
+
};
|
|
1371
|
+
if (await this.#engine.timeoutHandler.acquire(this.#engine), stepState.attemptedCount == 0)
|
|
1372
|
+
this.#engine.writeLog(
|
|
1373
|
+
5 /* STEP_START */,
|
|
1374
|
+
cacheKey,
|
|
1375
|
+
stepNameWithCounter,
|
|
1376
|
+
{
|
|
1377
|
+
config
|
|
1378
|
+
}
|
|
1379
|
+
);
|
|
1380
|
+
else {
|
|
1381
|
+
let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, retryEntryPQ = this.#engine.priorityQueue.getFirst(
|
|
1382
|
+
(a) => a.hash === priorityQueueHash && a.type === "retry"
|
|
1383
|
+
);
|
|
1384
|
+
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({
|
|
1385
|
+
hash: priorityQueueHash,
|
|
1386
|
+
type: "retry"
|
|
1387
|
+
}));
|
|
1388
|
+
}
|
|
1389
|
+
let result, instanceMetadata = await this.#state.storage.get(INSTANCE_METADATA);
|
|
1390
|
+
if (!instanceMetadata)
|
|
1391
|
+
throw new Error("instanceMetadata is undefined");
|
|
1392
|
+
let { accountId, instance } = instanceMetadata;
|
|
1393
|
+
try {
|
|
1394
|
+
let timeoutPromise = async () => {
|
|
1395
|
+
let priorityQueueHash2 = `${cacheKey}-${stepState.attemptedCount}`, timeout = r(config.timeout);
|
|
1396
|
+
throw forceStepTimeout && (timeout = 0), await this.#engine.priorityQueue.add({
|
|
1397
|
+
hash: priorityQueueHash2,
|
|
1398
|
+
targetTimestamp: Date.now() + timeout,
|
|
1399
|
+
type: "timeout"
|
|
1400
|
+
}), await scheduler.wait(timeout), await this.#engine.priorityQueue.remove({
|
|
1401
|
+
hash: priorityQueueHash2,
|
|
1402
|
+
type: "timeout"
|
|
1403
|
+
}), new WorkflowTimeoutError(
|
|
1404
|
+
`Execution timed out after ${timeout}ms`
|
|
1405
|
+
);
|
|
1406
|
+
};
|
|
1407
|
+
this.#engine.writeLog(
|
|
1408
|
+
10 /* ATTEMPT_START */,
|
|
1409
|
+
cacheKey,
|
|
1410
|
+
stepNameWithCounter,
|
|
1411
|
+
{
|
|
1412
|
+
attempt: stepState.attemptedCount + 1
|
|
1413
|
+
}
|
|
1414
|
+
), stepState.attemptedCount++, await this.#state.storage.put(stepStateKey, stepState);
|
|
1415
|
+
let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, mockErrorKey = `mock-step-error-${valueKey}`, persistentMockError = await this.#state.storage.get(mockErrorKey), transientMockError = await this.#state.storage.get(`${mockErrorKey}-${stepState.attemptedCount}`), mockErrorPayload = persistentMockError || transientMockError;
|
|
1416
|
+
if (mockErrorPayload) {
|
|
1417
|
+
let errorToThrow = new Error(mockErrorPayload.message);
|
|
1418
|
+
throw errorToThrow.name = mockErrorPayload.name, errorToThrow;
|
|
1419
|
+
}
|
|
1420
|
+
let replaceResult = await this.#state.storage.get(
|
|
1421
|
+
`replace-result-${valueKey}`
|
|
1422
|
+
), forceStepTimeoutKey = `force-step-timeout-${valueKey}`, persistentStepTimeout = await this.#state.storage.get(forceStepTimeoutKey), transientStepTimeout = await this.#state.storage.get(
|
|
1423
|
+
`${forceStepTimeoutKey}-${stepState.attemptedCount}`
|
|
1424
|
+
), forceStepTimeout = persistentStepTimeout || transientStepTimeout;
|
|
1425
|
+
forceStepTimeout ? result = await timeoutPromise() : replaceResult ? (result = replaceResult, await this.#state.storage.delete(`replace-result-${valueKey}`)) : result = await Promise.race([
|
|
1426
|
+
doWrapperClosure({ attempt: stepState.attemptedCount }),
|
|
1427
|
+
timeoutPromise()
|
|
1428
|
+
]), await this.#engine.priorityQueue.remove({
|
|
1429
|
+
hash: priorityQueueHash,
|
|
1430
|
+
type: "timeout"
|
|
1431
|
+
});
|
|
1432
|
+
try {
|
|
1433
|
+
await this.#state.storage.put(valueKey, { value: result });
|
|
1434
|
+
} catch (e) {
|
|
1435
|
+
if (e instanceof Error && e.name === "DataCloneError")
|
|
1436
|
+
this.#engine.writeLog(
|
|
1437
|
+
12 /* ATTEMPT_FAILURE */,
|
|
1438
|
+
cacheKey,
|
|
1439
|
+
stepNameWithCounter,
|
|
1440
|
+
{
|
|
1441
|
+
attempt: stepState.attemptedCount,
|
|
1442
|
+
error: new WorkflowFatalError(
|
|
1443
|
+
`Value returned from step "${name}" is not serialisable`
|
|
1444
|
+
)
|
|
1445
|
+
}
|
|
1446
|
+
), this.#engine.writeLog(
|
|
1447
|
+
7 /* STEP_FAILURE */,
|
|
1448
|
+
cacheKey,
|
|
1449
|
+
stepNameWithCounter,
|
|
1450
|
+
{}
|
|
1451
|
+
), this.#engine.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
|
|
1452
|
+
error: new WorkflowFatalError(
|
|
1453
|
+
`The execution of the Workflow instance was terminated, as the step "${name}" returned a value which is not serialisable`
|
|
1454
|
+
)
|
|
1455
|
+
}), await this.#engine.setStatus(
|
|
1456
|
+
accountId,
|
|
1457
|
+
instance.id,
|
|
1458
|
+
3 /* Errored */
|
|
1459
|
+
), await this.#engine.timeoutHandler.release(this.#engine), await this.#engine.abort("Value is not serialisable");
|
|
1460
|
+
else
|
|
1461
|
+
throw new WorkflowInternalError(
|
|
1462
|
+
`Storage failure for ${valueKey}: ${e} `
|
|
1463
|
+
);
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
this.#engine.writeLog(
|
|
1467
|
+
11 /* ATTEMPT_SUCCESS */,
|
|
1468
|
+
cacheKey,
|
|
1469
|
+
stepNameWithCounter,
|
|
1470
|
+
{
|
|
1471
|
+
attempt: stepState.attemptedCount
|
|
1472
|
+
}
|
|
1473
|
+
);
|
|
1474
|
+
} catch (e) {
|
|
1475
|
+
let error = e;
|
|
1476
|
+
if (this.#engine.priorityQueue.remove({
|
|
1477
|
+
hash: `${cacheKey}-${stepState.attemptedCount}`,
|
|
1478
|
+
type: "timeout"
|
|
1479
|
+
}), e instanceof Error && (error.name === "NonRetryableError" || error.message.startsWith("NonRetryableError")))
|
|
1480
|
+
throw this.#engine.writeLog(
|
|
1481
|
+
12 /* ATTEMPT_FAILURE */,
|
|
1482
|
+
cacheKey,
|
|
1483
|
+
stepNameWithCounter,
|
|
1484
|
+
{
|
|
1485
|
+
attempt: stepState.attemptedCount,
|
|
1486
|
+
error: new WorkflowFatalError(
|
|
1487
|
+
`Step threw a NonRetryableError with message "${e.message}"`
|
|
1488
|
+
)
|
|
1489
|
+
}
|
|
1490
|
+
), this.#engine.writeLog(
|
|
1491
|
+
7 /* STEP_FAILURE */,
|
|
1492
|
+
cacheKey,
|
|
1493
|
+
stepNameWithCounter,
|
|
1494
|
+
{}
|
|
1495
|
+
), error;
|
|
1496
|
+
if (this.#engine.writeLog(
|
|
1497
|
+
12 /* ATTEMPT_FAILURE */,
|
|
1498
|
+
cacheKey,
|
|
1499
|
+
stepNameWithCounter,
|
|
1500
|
+
{
|
|
1501
|
+
attempt: stepState.attemptedCount,
|
|
1502
|
+
error: {
|
|
1503
|
+
name: error.name,
|
|
1504
|
+
message: error.message
|
|
1505
|
+
// TODO (WOR-79): Stacks are all incorrect over RPC and need work
|
|
1506
|
+
// stack: error.stack,
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
), await this.#state.storage.put(stepStateKey, stepState), stepState.attemptedCount <= config.retries.limit) {
|
|
1510
|
+
let durationMs = calcRetryDuration(config, stepState), priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`;
|
|
1511
|
+
return await this.#engine.priorityQueue.add({
|
|
1512
|
+
hash: priorityQueueHash,
|
|
1513
|
+
targetTimestamp: Date.now() + durationMs,
|
|
1514
|
+
type: "retry"
|
|
1515
|
+
}), await this.#engine.timeoutHandler.release(this.#engine), await scheduler.wait(durationMs), this.#engine.priorityQueue.remove({
|
|
1516
|
+
hash: priorityQueueHash,
|
|
1517
|
+
type: "retry"
|
|
1518
|
+
}), doWrapper(doWrapperClosure);
|
|
1519
|
+
} else
|
|
1520
|
+
throw await this.#engine.timeoutHandler.release(this.#engine), this.#engine.writeLog(
|
|
1521
|
+
7 /* STEP_FAILURE */,
|
|
1522
|
+
cacheKey,
|
|
1523
|
+
stepNameWithCounter,
|
|
1524
|
+
{}
|
|
1525
|
+
), await this.#state.storage.put(errorKey, error), error;
|
|
1526
|
+
}
|
|
1527
|
+
return this.#engine.writeLog(
|
|
1528
|
+
6 /* STEP_SUCCESS */,
|
|
1529
|
+
cacheKey,
|
|
1530
|
+
stepNameWithCounter,
|
|
1531
|
+
{
|
|
1532
|
+
// TODO (WOR-86): Add limits, figure out serialization
|
|
1533
|
+
result
|
|
1534
|
+
}
|
|
1535
|
+
), await this.#engine.timeoutHandler.release(this.#engine), result;
|
|
1536
|
+
};
|
|
1537
|
+
return doWrapper(closure);
|
|
1538
|
+
}
|
|
1539
|
+
async sleep(name, duration) {
|
|
1540
|
+
typeof duration == "string" && (duration = r(duration));
|
|
1541
|
+
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`, maybeResult = await this.#state.storage.get(sleepKey), sleepNameCountHash = await computeHash(
|
|
1542
|
+
name + this.#getCount("sleep-" + name)
|
|
1543
|
+
), disableThisSleep = await this.#state.storage.get(sleepNameCountHash), disableSleep = await this.#state.storage.get("disableAllSleeps") || disableThisSleep;
|
|
1544
|
+
if (maybeResult != null) {
|
|
1545
|
+
let entryPQ = this.#engine.priorityQueue.getFirst(
|
|
1546
|
+
(a) => a.hash === cacheKey && a.type === "sleep"
|
|
1547
|
+
);
|
|
1548
|
+
entryPQ !== void 0 && (await scheduler.wait(
|
|
1549
|
+
disableSleep ? 0 : entryPQ.targetTimestamp - Date.now()
|
|
1550
|
+
), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" })), await this.#state.storage.get(sleepLogWrittenKey) == null && (this.#engine.writeLog(
|
|
1551
|
+
9 /* SLEEP_COMPLETE */,
|
|
1552
|
+
cacheKey,
|
|
1553
|
+
sleepNameWithCounter,
|
|
1554
|
+
{}
|
|
1555
|
+
), await this.#state.storage.put(sleepLogWrittenKey, !0));
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
if (this.#engine.writeLog(
|
|
1559
|
+
8 /* SLEEP_START */,
|
|
1560
|
+
cacheKey,
|
|
1561
|
+
sleepNameWithCounter,
|
|
1562
|
+
{
|
|
1563
|
+
durationMs: duration
|
|
1564
|
+
}
|
|
1565
|
+
), !await this.#state.storage.get(INSTANCE_METADATA))
|
|
1566
|
+
throw new Error("instanceMetadata is undefined");
|
|
1567
|
+
await this.#state.storage.put(sleepKey, !0), await this.#engine.priorityQueue.add({
|
|
1568
|
+
hash: cacheKey,
|
|
1569
|
+
targetTimestamp: Date.now() + (disableSleep ? 0 : duration),
|
|
1570
|
+
type: "sleep"
|
|
1571
|
+
}), await scheduler.wait(disableSleep ? 0 : duration), this.#engine.writeLog(
|
|
1572
|
+
9 /* SLEEP_COMPLETE */,
|
|
1573
|
+
cacheKey,
|
|
1574
|
+
sleepNameWithCounter,
|
|
1575
|
+
{}
|
|
1576
|
+
), await this.#state.storage.put(sleepLogWrittenKey, !0), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" });
|
|
1577
|
+
}
|
|
1578
|
+
async sleepUntil(name, timestamp) {
|
|
1579
|
+
timestamp instanceof Date && (timestamp = timestamp.valueOf());
|
|
1580
|
+
let now = Date.now();
|
|
1581
|
+
if (timestamp < now)
|
|
1582
|
+
throw new Error(
|
|
1583
|
+
"You can't sleep until a time in the past, time-traveler"
|
|
1584
|
+
);
|
|
1585
|
+
return this.sleep(name, timestamp - now);
|
|
1586
|
+
}
|
|
1587
|
+
async waitForEvent(name, options) {
|
|
1588
|
+
options.timeout || (options.timeout = "24 hours");
|
|
1589
|
+
let count = this.#getCount("waitForEvent-" + name), waitForEventNameWithCounter = `${name}-${count}`, cacheKey = `${await computeHash(waitForEventNameWithCounter)}-${count}`, waitForEventKey = `${cacheKey}-value`, errorKey = `${cacheKey}-error`, pendingWaiterRegistered = `${cacheKey}-pending`, timeoutError = new WorkflowTimeoutError(
|
|
1590
|
+
`Execution timed out after ${r(options.timeout)}ms`
|
|
1591
|
+
), maybeResult = await this.#state.storage.get(waitForEventKey);
|
|
1592
|
+
if (maybeResult)
|
|
1593
|
+
return await this.#state.storage.get(waitForEventKey) == null && this.#engine.writeLog(
|
|
1594
|
+
15 /* WAIT_COMPLETE */,
|
|
1595
|
+
cacheKey,
|
|
1596
|
+
waitForEventNameWithCounter,
|
|
1597
|
+
maybeResult
|
|
1598
|
+
), maybeResult;
|
|
1599
|
+
let maybeError = await this.#state.storage.get(errorKey);
|
|
1600
|
+
if (maybeError)
|
|
1601
|
+
throw maybeError.isUserError = !0, maybeError;
|
|
1602
|
+
await this.#state.storage.get(
|
|
1603
|
+
pendingWaiterRegistered
|
|
1604
|
+
) || (this.#engine.writeLog(
|
|
1605
|
+
14 /* WAIT_START */,
|
|
1606
|
+
cacheKey,
|
|
1607
|
+
waitForEventNameWithCounter,
|
|
1608
|
+
{
|
|
1609
|
+
event: options.type
|
|
1610
|
+
}
|
|
1611
|
+
), await this.#state.storage.put(pendingWaiterRegistered, !0));
|
|
1612
|
+
let timeoutEntryPQ = this.#engine.priorityQueue.getFirst(
|
|
1613
|
+
(a) => a.hash === cacheKey && a.type === "timeout"
|
|
1614
|
+
), forceEventTimeout = await this.#state.storage.get(
|
|
1615
|
+
`force-event-timeout-${waitForEventKey}`
|
|
1616
|
+
);
|
|
1617
|
+
if (timeoutEntryPQ === void 0 && this.#engine.priorityQueue !== void 0 && this.#engine.priorityQueue.checkIfExistedInPast({
|
|
1618
|
+
hash: cacheKey,
|
|
1619
|
+
type: "timeout"
|
|
1620
|
+
}) || timeoutEntryPQ !== void 0 && timeoutEntryPQ.targetTimestamp < Date.now() || forceEventTimeout)
|
|
1621
|
+
throw this.#engine.writeLog(
|
|
1622
|
+
16 /* WAIT_TIMED_OUT */,
|
|
1623
|
+
cacheKey,
|
|
1624
|
+
waitForEventNameWithCounter,
|
|
1625
|
+
{
|
|
1626
|
+
name: timeoutError.name,
|
|
1627
|
+
message: timeoutError.message
|
|
1628
|
+
}
|
|
1629
|
+
), await this.#state.storage.put(errorKey, timeoutError), timeoutError;
|
|
1630
|
+
let timeoutPromise = async (timeoutToWait, addToPQ) => {
|
|
1631
|
+
let priorityQueueHash = cacheKey;
|
|
1632
|
+
addToPQ && await this.#engine.priorityQueue.add({
|
|
1633
|
+
hash: priorityQueueHash,
|
|
1634
|
+
targetTimestamp: Date.now() + timeoutToWait,
|
|
1635
|
+
type: "timeout"
|
|
1636
|
+
}), await scheduler.wait(timeoutToWait), this.#engine.priorityQueue.remove({
|
|
1637
|
+
hash: priorityQueueHash,
|
|
1638
|
+
type: "timeout"
|
|
1639
|
+
});
|
|
1640
|
+
let error = timeoutError;
|
|
1641
|
+
throw error.isUserError = !0, error;
|
|
1642
|
+
}, eventPromise = new Promise((resolve) => {
|
|
1643
|
+
let eventTypeQueue = this.#engine.eventMap.get(options.type);
|
|
1644
|
+
if (eventTypeQueue) {
|
|
1645
|
+
let event = eventTypeQueue.shift();
|
|
1646
|
+
if (event)
|
|
1647
|
+
return this.#engine.eventMap.set(options.type, eventTypeQueue), resolve(event);
|
|
1648
|
+
}
|
|
1649
|
+
let callbacks = this.#engine.waiters.get(options.type) ?? [];
|
|
1650
|
+
callbacks.push(resolve), this.#engine.waiters.set(options.type, callbacks);
|
|
1651
|
+
});
|
|
1652
|
+
return await Promise.race([
|
|
1653
|
+
eventPromise,
|
|
1654
|
+
timeoutEntryPQ !== void 0 ? timeoutPromise(timeoutEntryPQ.targetTimestamp - Date.now(), !1) : timeoutPromise(r(options.timeout), !0)
|
|
1655
|
+
]).then(async (event) => (this.#engine.writeLog(
|
|
1656
|
+
15 /* WAIT_COMPLETE */,
|
|
1657
|
+
cacheKey,
|
|
1658
|
+
waitForEventNameWithCounter,
|
|
1659
|
+
event
|
|
1660
|
+
), await this.#state.storage.put(waitForEventKey, event), event)).catch(async (error) => {
|
|
1661
|
+
throw this.#engine.writeLog(
|
|
1662
|
+
16 /* WAIT_TIMED_OUT */,
|
|
1663
|
+
cacheKey,
|
|
1664
|
+
waitForEventNameWithCounter,
|
|
1665
|
+
error
|
|
1666
|
+
), await this.#state.storage.put(errorKey, error), error;
|
|
1667
|
+
});
|
|
1668
|
+
}
|
|
1669
|
+
};
|
|
1670
|
+
|
|
1671
|
+
// ../workflows-shared/src/lib/gracePeriodSemaphore.ts
|
|
1672
|
+
var ENGINE_TIMEOUT = r("5 minutes"), latestGracePeriodTimestamp, GracePeriodSemaphore = class {
|
|
1673
|
+
#counter = 0;
|
|
1674
|
+
callback;
|
|
1675
|
+
timeoutMs;
|
|
1676
|
+
constructor(callback, timeoutMs) {
|
|
1677
|
+
this.callback = callback, this.timeoutMs = timeoutMs;
|
|
1678
|
+
}
|
|
1679
|
+
// acquire takes engine to be the same as release
|
|
1680
|
+
async acquire(_engine) {
|
|
1681
|
+
this.#counter == 0 && (latestGracePeriodTimestamp = void 0), this.#counter += 1;
|
|
1682
|
+
}
|
|
1683
|
+
async release(engine) {
|
|
1684
|
+
this.#counter = Math.max(this.#counter - 1, 0), this.#counter == 0 && this.callback(engine, this.timeoutMs);
|
|
1685
|
+
}
|
|
1686
|
+
isRunningStep() {
|
|
1687
|
+
return this.#counter > 0;
|
|
1688
|
+
}
|
|
1689
|
+
}, startGracePeriod = async (engine, timeoutMs) => {
|
|
1690
|
+
(async () => {
|
|
1691
|
+
let thisTimestamp = (/* @__PURE__ */ new Date()).valueOf();
|
|
1692
|
+
if (!(latestGracePeriodTimestamp === void 0 || latestGracePeriodTimestamp < thisTimestamp))
|
|
1693
|
+
throw new Error(
|
|
1694
|
+
"Can't start grace period since there is already an active one started on " + latestGracePeriodTimestamp
|
|
1695
|
+
);
|
|
1696
|
+
latestGracePeriodTimestamp = thisTimestamp, await scheduler.wait(timeoutMs), !(thisTimestamp !== latestGracePeriodTimestamp || engine.timeoutHandler.isRunningStep()) && (await engine.priorityQueue?.handleNextAlarm(), await engine.abort("Grace period complete"));
|
|
1697
|
+
})();
|
|
1698
|
+
};
|
|
1699
|
+
|
|
1700
|
+
// ../workflows-shared/src/lib/timePriorityQueue.ts
|
|
1701
|
+
var import_heap_js = __toESM(require_heap_js_umd()), wakerPriorityEntryComparator = (a, b) => a.targetTimestamp - b.targetTimestamp;
|
|
1702
|
+
var TimePriorityQueue = class {
|
|
1703
|
+
#heap = new import_heap_js.default(wakerPriorityEntryComparator);
|
|
1704
|
+
#ctx;
|
|
1705
|
+
constructor(ctx, _instanceMetadata) {
|
|
1706
|
+
this.#ctx = ctx, this.#heap.init(this.getEntries());
|
|
1707
|
+
}
|
|
1708
|
+
popPastEntries() {
|
|
1709
|
+
if (this.#heap.length === 0)
|
|
1710
|
+
return;
|
|
1711
|
+
let res = [], currentTimestamp = (/* @__PURE__ */ new Date()).valueOf();
|
|
1712
|
+
for (; ; ) {
|
|
1713
|
+
let element = this.#heap.peek();
|
|
1714
|
+
if (element === void 0 || element.targetTimestamp > currentTimestamp)
|
|
1715
|
+
break;
|
|
1716
|
+
res.push(element), this.#heap.pop();
|
|
1717
|
+
}
|
|
1718
|
+
return this.#ctx.storage.transactionSync(() => {
|
|
1719
|
+
for (let entry of res)
|
|
1720
|
+
this.removeEntryDB(entry);
|
|
1721
|
+
}), res;
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* `add` is ran using a transaction so it's race condition free, if it's ran atomically
|
|
1725
|
+
* @param entry
|
|
1726
|
+
*/
|
|
1727
|
+
async add(entry) {
|
|
1728
|
+
await this.#ctx.storage.transaction(async () => {
|
|
1729
|
+
this.#heap.add(entry), this.addEntryDB(entry);
|
|
1730
|
+
});
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* `remove` is ran using a transaction so it's race condition free, if it's ran atomically
|
|
1734
|
+
* @param entry
|
|
1735
|
+
*/
|
|
1736
|
+
remove(entry) {
|
|
1737
|
+
this.#ctx.storage.transactionSync(() => {
|
|
1738
|
+
this.removeFirst((e) => e.hash === entry.hash && e.type === entry.type);
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
popTypeAll(entryType) {
|
|
1742
|
+
this.#ctx.storage.transactionSync(() => {
|
|
1743
|
+
this.filter((e) => e.type !== entryType);
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
// Idempotent, perhaps name should suggest so
|
|
1747
|
+
async handleNextAlarm() {
|
|
1748
|
+
this.#heap.peek();
|
|
1749
|
+
}
|
|
1750
|
+
getFirst(callbackFn) {
|
|
1751
|
+
return structuredClone(this.#heap.toArray().find(callbackFn));
|
|
1752
|
+
}
|
|
1753
|
+
removeFirst(callbackFn) {
|
|
1754
|
+
let elements = this.#heap.toArray(), index = elements.findIndex(callbackFn);
|
|
1755
|
+
if (index === -1)
|
|
1756
|
+
return;
|
|
1757
|
+
let removedEntry = elements.splice(index, 1)[0];
|
|
1758
|
+
this.removeEntryDB(removedEntry), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(elements);
|
|
1759
|
+
}
|
|
1760
|
+
filter(callbackFn) {
|
|
1761
|
+
let filteredElements = this.#heap.toArray().filter(callbackFn), removedElements = this.#heap.toArray().filter((a) => !callbackFn(a));
|
|
1762
|
+
this.#ctx.storage.transactionSync(() => {
|
|
1763
|
+
for (let entry of removedElements)
|
|
1764
|
+
this.removeEntryDB(entry);
|
|
1765
|
+
}), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(filteredElements);
|
|
1766
|
+
}
|
|
1767
|
+
length() {
|
|
1768
|
+
return this.#heap.length;
|
|
1769
|
+
}
|
|
1770
|
+
getEntries() {
|
|
1771
|
+
let entries = [
|
|
1772
|
+
...this.#ctx.storage.sql.exec("SELECT * FROM priority_queue ORDER BY id")
|
|
1773
|
+
], activeEntries = [];
|
|
1774
|
+
return entries.forEach((val) => {
|
|
1775
|
+
let entryType = toWakerPriorityType(val.entryType);
|
|
1776
|
+
if (val.action == 0) {
|
|
1777
|
+
let index = activeEntries.findIndex(
|
|
1778
|
+
(activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
|
|
1779
|
+
);
|
|
1780
|
+
index !== -1 && activeEntries.splice(index, 1);
|
|
1781
|
+
} else
|
|
1782
|
+
activeEntries.findIndex(
|
|
1783
|
+
(activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
|
|
1784
|
+
) === -1 && activeEntries.push({
|
|
1785
|
+
hash: val.hash,
|
|
1786
|
+
targetTimestamp: val.target_timestamp,
|
|
1787
|
+
type: entryType
|
|
1788
|
+
});
|
|
1789
|
+
}), activeEntries;
|
|
1790
|
+
}
|
|
1791
|
+
removeEntryDB(entry) {
|
|
1792
|
+
this.#ctx.storage.sql.exec(
|
|
1793
|
+
`
|
|
1794
|
+
INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
|
|
1795
|
+
VALUES (?, ?, ? ,?)
|
|
1796
|
+
`,
|
|
1797
|
+
entry.targetTimestamp,
|
|
1798
|
+
0 /* FALSE */,
|
|
1799
|
+
fromWakerPriorityType(entry.type),
|
|
1800
|
+
entry.hash
|
|
1801
|
+
);
|
|
1802
|
+
}
|
|
1803
|
+
checkIfExistedInPast(entry) {
|
|
1804
|
+
return this.#ctx.storage.sql.exec(
|
|
1805
|
+
"SELECT * FROM priority_queue WHERE entryType = ? AND hash = ? AND action = ?",
|
|
1806
|
+
fromWakerPriorityType(entry.type),
|
|
1807
|
+
entry.hash,
|
|
1808
|
+
0
|
|
1809
|
+
).toArray().length >= 1;
|
|
1810
|
+
}
|
|
1811
|
+
addEntryDB(entry) {
|
|
1812
|
+
this.#ctx.storage.sql.exec(
|
|
1813
|
+
`
|
|
1814
|
+
INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
|
|
1815
|
+
VALUES (?, ?, ? ,?)
|
|
1816
|
+
`,
|
|
1817
|
+
entry.targetTimestamp,
|
|
1818
|
+
1 /* TRUE */,
|
|
1819
|
+
fromWakerPriorityType(entry.type),
|
|
1820
|
+
entry.hash
|
|
1821
|
+
);
|
|
1822
|
+
}
|
|
1823
|
+
}, toWakerPriorityType = (entryType) => {
|
|
1824
|
+
switch (entryType) {
|
|
1825
|
+
case 0 /* RETRY */:
|
|
1826
|
+
return "retry";
|
|
1827
|
+
case 1 /* SLEEP */:
|
|
1828
|
+
return "sleep";
|
|
1829
|
+
case 2 /* TIMEOUT */:
|
|
1830
|
+
return "timeout";
|
|
1831
|
+
}
|
|
1832
|
+
}, fromWakerPriorityType = (entryType) => {
|
|
1833
|
+
switch (entryType) {
|
|
1834
|
+
case "retry":
|
|
1835
|
+
return 0 /* RETRY */;
|
|
1836
|
+
case "sleep":
|
|
1837
|
+
return 1 /* SLEEP */;
|
|
1838
|
+
case "timeout":
|
|
1839
|
+
return 2 /* TIMEOUT */;
|
|
1840
|
+
default:
|
|
1841
|
+
throw new Error(`WakerPriorityType "${entryType}" has not been handled`);
|
|
1842
|
+
}
|
|
1843
|
+
};
|
|
1844
|
+
|
|
1845
|
+
// ../workflows-shared/src/modifier.ts
|
|
1846
|
+
import { RpcTarget as RpcTarget2 } from "cloudflare:workers";
|
|
1847
|
+
var WorkflowInstanceModifier = class extends RpcTarget2 {
|
|
1848
|
+
#engine;
|
|
1849
|
+
#state;
|
|
1850
|
+
constructor(engine, state) {
|
|
1851
|
+
super(), this.#engine = engine, this.#state = state;
|
|
1852
|
+
}
|
|
1853
|
+
async #getWaitForEventCacheKey(step) {
|
|
1854
|
+
let count = 1;
|
|
1855
|
+
step.index && (count = step.index);
|
|
1856
|
+
let name = `${step.name}-${count}`;
|
|
1857
|
+
return `${`${await computeHash(name)}-${count}`}-value`;
|
|
1858
|
+
}
|
|
1859
|
+
async #getStepCacheKey(step) {
|
|
1860
|
+
let hash = await computeHash(step.name), count = 1;
|
|
1861
|
+
return step.index && (count = step.index), `${`${hash}-${count}`}-value`;
|
|
1862
|
+
}
|
|
1863
|
+
#getAndIncrementCounter = async (valueKey, by) => {
|
|
1864
|
+
let counterKey = `failure-index-${valueKey}`, next = await this.#state.storage.get(counterKey) ?? 1;
|
|
1865
|
+
return await this.#state.storage.put(counterKey, next + by), next;
|
|
1866
|
+
};
|
|
1867
|
+
async #getSleepStepDisableKey(step) {
|
|
1868
|
+
let count = 1;
|
|
1869
|
+
return step.index && (count = step.index), await computeHash(step.name + count);
|
|
1870
|
+
}
|
|
1871
|
+
async disableSleeps(steps) {
|
|
1872
|
+
if (!steps)
|
|
1873
|
+
await this.#state.storage.put("disableAllSleeps", !0);
|
|
1874
|
+
else
|
|
1875
|
+
for (let step of steps) {
|
|
1876
|
+
let sleepDisableKey = await this.#getSleepStepDisableKey(step);
|
|
1877
|
+
await this.#state.storage.put(sleepDisableKey, !0);
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
// step.do() flow: It first checks if a result or error is already in the cache and, if so, returns it immediately.
|
|
1881
|
+
// If nothing is in the cache, it checks for remaining attempts and runs the user's code against the defined timeout.
|
|
1882
|
+
// Since `step.do()` performs this initial cache check, directly changing the `valueKey` would cause it to
|
|
1883
|
+
// assume the value was pre-cached, preventing it from writing any logs about the step's execution state.
|
|
1884
|
+
// Storing the value under a separate key is crucial because it ensures all execution logs for the step are
|
|
1885
|
+
// generated, rather than the step being skipped due to a premature cache hit.
|
|
1886
|
+
async mockStepResult(step, stepResult) {
|
|
1887
|
+
let valueKey = await this.#getStepCacheKey(step);
|
|
1888
|
+
if (await this.#state.storage.get(`replace-result-${valueKey}`))
|
|
1889
|
+
throw new Error(
|
|
1890
|
+
`[WorkflowIntrospector] Trying to mock step '${step.name}' multiple times!`
|
|
1891
|
+
);
|
|
1892
|
+
await this.#state.storage.put(`replace-result-${valueKey}`, stepResult);
|
|
1893
|
+
}
|
|
1894
|
+
// Same logic of `mockStepResult` but stores an error instead of a value.
|
|
1895
|
+
async mockStepError(step, error, times) {
|
|
1896
|
+
let valueKey = await this.#getStepCacheKey(step), serializableError = {
|
|
1897
|
+
name: error.name,
|
|
1898
|
+
message: error.message
|
|
1899
|
+
};
|
|
1900
|
+
if (await this.#state.storage.get(`replace-result-${valueKey}`))
|
|
1901
|
+
throw new Error(
|
|
1902
|
+
`[WorkflowIntrospector] Trying to mock error on step '${step.name}' after mocking its result!`
|
|
1903
|
+
);
|
|
1904
|
+
if (times) {
|
|
1905
|
+
let start = await this.#getAndIncrementCounter(valueKey, times), mockErrorsPuts = Array.from({ length: times }, (_, i) => {
|
|
1906
|
+
let attempt = start + i, mockErrorKey = `mock-step-error-${valueKey}-${attempt}`;
|
|
1907
|
+
return this.#state.storage.put(mockErrorKey, serializableError);
|
|
1908
|
+
});
|
|
1909
|
+
await Promise.all(mockErrorsPuts);
|
|
1910
|
+
} else {
|
|
1911
|
+
let mockErrorKey = `mock-step-error-${valueKey}`;
|
|
1912
|
+
await this.#state.storage.put(mockErrorKey, serializableError);
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
async forceStepTimeout(step, times) {
|
|
1916
|
+
let valueKey = await this.#getStepCacheKey(step);
|
|
1917
|
+
if (await this.#state.storage.get(`replace-result-${valueKey}`))
|
|
1918
|
+
throw new Error(
|
|
1919
|
+
`[WorkflowIntrospector] Trying to force timeout on step '${step.name}' after mocking its result!`
|
|
1920
|
+
);
|
|
1921
|
+
if (times) {
|
|
1922
|
+
let start = await this.#getAndIncrementCounter(valueKey, times), forceTimeouts = Array.from({ length: times }, (_, i) => {
|
|
1923
|
+
let attempt = start + i, forceStepTimeoutKey = `force-step-timeout-${valueKey}-${attempt}`;
|
|
1924
|
+
return this.#state.storage.put(forceStepTimeoutKey, !0);
|
|
1925
|
+
});
|
|
1926
|
+
await Promise.all(forceTimeouts);
|
|
1927
|
+
} else {
|
|
1928
|
+
let forceStepTimeoutKey = `force-step-timeout-${valueKey}`;
|
|
1929
|
+
await this.#state.storage.put(forceStepTimeoutKey, !0);
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
async mockEvent(event) {
|
|
1933
|
+
let myEvent = {
|
|
1934
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1935
|
+
payload: event.payload,
|
|
1936
|
+
type: event.type
|
|
1937
|
+
};
|
|
1938
|
+
await this.#state.storage.put(`mock-event-${event.type}`, !0), await this.#engine.receiveEvent(myEvent);
|
|
1939
|
+
}
|
|
1940
|
+
async forceEventTimeout(step) {
|
|
1941
|
+
let waitForEventKey = await this.#getWaitForEventCacheKey(step);
|
|
1942
|
+
await this.#state.storage.put(
|
|
1943
|
+
`force-event-timeout-${waitForEventKey}`,
|
|
1944
|
+
!0
|
|
1945
|
+
);
|
|
1946
|
+
}
|
|
1947
|
+
};
|
|
1948
|
+
|
|
1949
|
+
// ../workflows-shared/src/engine.ts
|
|
1950
|
+
var ENGINE_STATUS_KEY = "ENGINE_STATUS", EVENT_MAP_PREFIX = "EVENT_MAP", DEFAULT_STEP_LIMIT = 1e4, Engine = class extends DurableObject {
|
|
1951
|
+
logs = [];
|
|
1952
|
+
isRunning = !1;
|
|
1953
|
+
accountId;
|
|
1954
|
+
instanceId;
|
|
1955
|
+
workflowName;
|
|
1956
|
+
timeoutHandler;
|
|
1957
|
+
priorityQueue;
|
|
1958
|
+
stepLimit;
|
|
1959
|
+
waiters = /* @__PURE__ */ new Map();
|
|
1960
|
+
eventMap = /* @__PURE__ */ new Map();
|
|
1961
|
+
constructor(state, env) {
|
|
1962
|
+
super(state, env), this.stepLimit = env.STEP_LIMIT ? JSON.parse(env.STEP_LIMIT) : DEFAULT_STEP_LIMIT, this.ctx.blockConcurrencyWhile(async () => {
|
|
1963
|
+
this.ctx.storage.transactionSync(() => {
|
|
1964
|
+
try {
|
|
1965
|
+
this.ctx.storage.sql.exec(`
|
|
1966
|
+
CREATE TABLE IF NOT EXISTS priority_queue (
|
|
1967
|
+
id INTEGER PRIMARY KEY NOT NULL,
|
|
1968
|
+
created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1969
|
+
target_timestamp INTEGER NOT NULL,
|
|
1970
|
+
action INTEGER NOT NULL, -- should only be 0 or 1 (1 for added, 0 for deleted),
|
|
1971
|
+
entryType INTEGER NOT NULL,
|
|
1972
|
+
hash TEXT NOT NULL,
|
|
1973
|
+
CHECK (action IN (0, 1)), -- guararentee that action can only be 0 or 1
|
|
1974
|
+
UNIQUE (action, entryType, hash)
|
|
1975
|
+
);
|
|
1976
|
+
CREATE TABLE IF NOT EXISTS states (
|
|
1977
|
+
id INTEGER PRIMARY KEY NOT NULL,
|
|
1978
|
+
groupKey TEXT,
|
|
1979
|
+
target TEXT,
|
|
1980
|
+
metadata TEXT,
|
|
1981
|
+
event INTEGER NOT NULL
|
|
1982
|
+
)
|
|
1983
|
+
`);
|
|
1984
|
+
} catch (e) {
|
|
1985
|
+
throw console.error(e), e;
|
|
1986
|
+
}
|
|
1987
|
+
});
|
|
1988
|
+
}), this.timeoutHandler = new GracePeriodSemaphore(
|
|
1989
|
+
startGracePeriod,
|
|
1990
|
+
ENGINE_TIMEOUT
|
|
1991
|
+
);
|
|
1992
|
+
}
|
|
1993
|
+
writeLog(event, group, target = null, metadata) {
|
|
1994
|
+
this.ctx.storage.sql.exec(
|
|
1995
|
+
"INSERT INTO states (event, groupKey, target, metadata) VALUES (?, ?, ?, ?)",
|
|
1996
|
+
event,
|
|
1997
|
+
group,
|
|
1998
|
+
target,
|
|
1999
|
+
JSON.stringify(metadata)
|
|
2000
|
+
), group && this.handleStepResultWaiter(group, event, metadata);
|
|
2001
|
+
}
|
|
2002
|
+
readLogsFromStep(_cacheKey) {
|
|
2003
|
+
return [];
|
|
2004
|
+
}
|
|
2005
|
+
readLogs() {
|
|
2006
|
+
return {
|
|
2007
|
+
logs: [
|
|
2008
|
+
...this.ctx.storage.sql.exec("SELECT event, groupKey, target, metadata FROM states")
|
|
2009
|
+
].map((log) => ({
|
|
2010
|
+
...log,
|
|
2011
|
+
metadata: JSON.parse(log.metadata),
|
|
2012
|
+
group: log.groupKey
|
|
2013
|
+
}))
|
|
2014
|
+
};
|
|
2015
|
+
}
|
|
2016
|
+
readLogsFromEvent(eventType) {
|
|
2017
|
+
return {
|
|
2018
|
+
logs: [
|
|
2019
|
+
...this.ctx.storage.sql.exec(
|
|
2020
|
+
"SELECT event, groupKey, target, metadata FROM states WHERE event = ?",
|
|
2021
|
+
eventType
|
|
2022
|
+
)
|
|
2023
|
+
].map((log) => ({
|
|
2024
|
+
...log,
|
|
2025
|
+
metadata: JSON.parse(log.metadata),
|
|
2026
|
+
group: log.groupKey
|
|
2027
|
+
}))
|
|
2028
|
+
};
|
|
2029
|
+
}
|
|
2030
|
+
async getStatus() {
|
|
2031
|
+
if (this.accountId === void 0) {
|
|
2032
|
+
let metadata = await this.ctx.storage.get(INSTANCE_METADATA);
|
|
2033
|
+
if (metadata === void 0)
|
|
2034
|
+
throw new Error("Engine was never started");
|
|
2035
|
+
this.accountId = metadata.accountId, this.instanceId = metadata.instance.id, this.workflowName = metadata.workflow.name;
|
|
2036
|
+
}
|
|
2037
|
+
let res = await this.ctx.storage.get(ENGINE_STATUS_KEY);
|
|
2038
|
+
return res === void 0 ? 0 /* Queued */ : res;
|
|
2039
|
+
}
|
|
2040
|
+
async setStatus(accountId, instanceId, status) {
|
|
2041
|
+
await this.ctx.storage.put(ENGINE_STATUS_KEY, status), this.handleStatusWaiter(status);
|
|
2042
|
+
}
|
|
2043
|
+
statusWaiters = /* @__PURE__ */ new Map();
|
|
2044
|
+
async waitForStatus(status) {
|
|
2045
|
+
let targetStatus = toInstanceStatus(status), currentStatus = await this.ctx.storage.get(ENGINE_STATUS_KEY);
|
|
2046
|
+
if (currentStatus !== targetStatus)
|
|
2047
|
+
return new Promise((resolve, reject) => {
|
|
2048
|
+
this.statusWaiters.set(targetStatus, { resolve, reject }), this.handleStatusWaiter(currentStatus);
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
handleStatusWaiter(status) {
|
|
2052
|
+
let waiter = this.statusWaiters.get(status);
|
|
2053
|
+
if (waiter) {
|
|
2054
|
+
waiter.resolve(), this.statusWaiters.delete(status);
|
|
2055
|
+
return;
|
|
2056
|
+
}
|
|
2057
|
+
switch (status) {
|
|
2058
|
+
case 3 /* Errored */: {
|
|
2059
|
+
let unreachableStatuses = [
|
|
2060
|
+
5 /* Complete */,
|
|
2061
|
+
4 /* Terminated */
|
|
2062
|
+
];
|
|
2063
|
+
this.rejectUnreachableStatus(status, unreachableStatuses);
|
|
2064
|
+
break;
|
|
2065
|
+
}
|
|
2066
|
+
case 4 /* Terminated */: {
|
|
2067
|
+
let unreachableStatuses = [
|
|
2068
|
+
5 /* Complete */,
|
|
2069
|
+
3 /* Errored */
|
|
2070
|
+
];
|
|
2071
|
+
this.rejectUnreachableStatus(status, unreachableStatuses);
|
|
2072
|
+
break;
|
|
2073
|
+
}
|
|
2074
|
+
case 5 /* Complete */: {
|
|
2075
|
+
let unreachableStatuses = [
|
|
2076
|
+
4 /* Terminated */,
|
|
2077
|
+
3 /* Errored */
|
|
2078
|
+
];
|
|
2079
|
+
this.rejectUnreachableStatus(status, unreachableStatuses);
|
|
2080
|
+
break;
|
|
2081
|
+
}
|
|
2082
|
+
default:
|
|
2083
|
+
break;
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
rejectUnreachableStatus(reachedStatus, unreachableStatuses) {
|
|
2087
|
+
if (unreachableStatuses)
|
|
2088
|
+
for (let unreachableStatus of unreachableStatuses) {
|
|
2089
|
+
let waiter = this.statusWaiters.get(unreachableStatus);
|
|
2090
|
+
if (waiter) {
|
|
2091
|
+
waiter.reject(
|
|
2092
|
+
new Error(
|
|
2093
|
+
`[WorkflowIntrospector] The Workflow instance ${this.instanceId} has reached status '${instanceStatusName(reachedStatus)}'. This is a finite status that prevents it from ever reaching the expected status of '${instanceStatusName(unreachableStatus)}'.`
|
|
2094
|
+
)
|
|
2095
|
+
), this.statusWaiters.delete(unreachableStatus);
|
|
2096
|
+
return;
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
stepResultWaiters = /* @__PURE__ */ new Map();
|
|
2101
|
+
async waitForStepResult(stepName, stepCount) {
|
|
2102
|
+
let cacheKey = `${await computeHash(stepName)}-${stepCount ?? 1}`, rows = [
|
|
2103
|
+
...this.ctx.storage.sql.exec(
|
|
2104
|
+
"SELECT event, metadata FROM states WHERE groupKey = ? ORDER BY id DESC LIMIT 1",
|
|
2105
|
+
cacheKey
|
|
2106
|
+
)
|
|
2107
|
+
];
|
|
2108
|
+
if (rows.length > 0) {
|
|
2109
|
+
let { event, metadata } = rows[0], parsed = JSON.parse(metadata);
|
|
2110
|
+
if (event === 6 /* STEP_SUCCESS */)
|
|
2111
|
+
return parsed?.result;
|
|
2112
|
+
if (event === 7 /* STEP_FAILURE */)
|
|
2113
|
+
throw parsed?.error ?? parsed;
|
|
2114
|
+
}
|
|
2115
|
+
return new Promise((resolve, reject) => {
|
|
2116
|
+
this.stepResultWaiters.set(cacheKey, { resolve, reject });
|
|
2117
|
+
});
|
|
2118
|
+
}
|
|
2119
|
+
handleStepResultWaiter(group, event, metadata) {
|
|
2120
|
+
let waiter = this.stepResultWaiters.get(group);
|
|
2121
|
+
if (waiter) {
|
|
2122
|
+
if (event === 6 /* STEP_SUCCESS */) {
|
|
2123
|
+
let result = metadata?.result;
|
|
2124
|
+
waiter.resolve(result), this.stepResultWaiters.delete(group);
|
|
2125
|
+
} else if (event === 7 /* STEP_FAILURE */) {
|
|
2126
|
+
let error = metadata?.error ?? new Error("Step failed");
|
|
2127
|
+
waiter.reject(error), this.stepResultWaiters.delete(group);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
async getOutputOrError(isOutput) {
|
|
2132
|
+
let status = await this.getStatus();
|
|
2133
|
+
if (isOutput) {
|
|
2134
|
+
if (status !== 5 /* Complete */)
|
|
2135
|
+
throw new Error(
|
|
2136
|
+
`Cannot retrieve output: Workflow instance is in status "${instanceStatusName(status)}" but must be "complete" to have an output available`
|
|
2137
|
+
);
|
|
2138
|
+
return this.readLogsFromEvent(2 /* WORKFLOW_SUCCESS */).logs.at(0)?.metadata.result;
|
|
2139
|
+
} else {
|
|
2140
|
+
if (status !== 3 /* Errored */)
|
|
2141
|
+
throw new Error(
|
|
2142
|
+
`Cannot retrieve error: Workflow instance is in status "${instanceStatusName(status)}" but must be "errored" to have error information available`
|
|
2143
|
+
);
|
|
2144
|
+
let log = this.readLogsFromEvent(3 /* WORKFLOW_FAILURE */).logs.at(0);
|
|
2145
|
+
if (!log?.metadata.error)
|
|
2146
|
+
throw new Error(
|
|
2147
|
+
"Cannot retrieve error: No workflow instance failure log found"
|
|
2148
|
+
);
|
|
2149
|
+
return log.metadata.error;
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
async abort(_reason) {
|
|
2153
|
+
}
|
|
2154
|
+
// Called by the dispose function when introspecting the instance in tests
|
|
2155
|
+
// TODO: Ideally this abort should be done by `abortAllDurableObjects` from worked called by vitest-pool-workers
|
|
2156
|
+
async unsafeAbort(reason) {
|
|
2157
|
+
await this.ctx.storage.sync(), await this.ctx.storage.deleteAll(), this.ctx.abort(reason);
|
|
2158
|
+
}
|
|
2159
|
+
async storeEventMap() {
|
|
2160
|
+
await this.ctx.blockConcurrencyWhile(async () => {
|
|
2161
|
+
for (let [key, value] of this.eventMap.entries())
|
|
2162
|
+
for (let eventIdx in value)
|
|
2163
|
+
await this.ctx.storage.put(
|
|
2164
|
+
`${EVENT_MAP_PREFIX}
|
|
2165
|
+
${key}
|
|
2166
|
+
${eventIdx}`,
|
|
2167
|
+
value[eventIdx]
|
|
2168
|
+
);
|
|
2169
|
+
});
|
|
2170
|
+
}
|
|
2171
|
+
async restoreEventMap() {
|
|
2172
|
+
await this.ctx.blockConcurrencyWhile(async () => {
|
|
2173
|
+
let entries = await this.ctx.storage.list({
|
|
2174
|
+
prefix: EVENT_MAP_PREFIX
|
|
2175
|
+
});
|
|
2176
|
+
for (let [key, value] of entries) {
|
|
2177
|
+
let [_, eventType, _idx] = key.split(`
|
|
2178
|
+
`), eventList = this.eventMap.get(eventType) ?? [];
|
|
2179
|
+
eventList.push(value), this.eventMap.set(eventType, eventList);
|
|
2180
|
+
}
|
|
2181
|
+
});
|
|
2182
|
+
}
|
|
2183
|
+
async receiveEvent(event) {
|
|
2184
|
+
let eventTypeQueue = this.eventMap.get(event.type) ?? [];
|
|
2185
|
+
if (eventTypeQueue.push(event), await this.storeEventMap(), this.eventMap.set(event.type, eventTypeQueue), this.isRunning) {
|
|
2186
|
+
let callbacks = this.waiters.get(event.type);
|
|
2187
|
+
if (callbacks) {
|
|
2188
|
+
let callback = callbacks[0];
|
|
2189
|
+
if (callback) {
|
|
2190
|
+
callback(event), callbacks.shift(), this.waiters.set(event.type, callbacks), eventTypeQueue = this.eventMap.get(event.type) ?? [], eventTypeQueue.shift(), this.eventMap.set(event.type, eventTypeQueue);
|
|
2191
|
+
return;
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
} else {
|
|
2195
|
+
if (await this.ctx.storage.get(`mock-event-${event.type}`))
|
|
2196
|
+
return;
|
|
2197
|
+
let metadata = await this.ctx.storage.get(INSTANCE_METADATA);
|
|
2198
|
+
if (metadata === void 0)
|
|
2199
|
+
throw new Error("Engine was never started");
|
|
2200
|
+
this.init(
|
|
2201
|
+
metadata.accountId,
|
|
2202
|
+
metadata.workflow,
|
|
2203
|
+
metadata.version,
|
|
2204
|
+
metadata.instance,
|
|
2205
|
+
metadata.event
|
|
2206
|
+
);
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
getInstanceModifier() {
|
|
2210
|
+
return new WorkflowInstanceModifier(this, this.ctx);
|
|
2211
|
+
}
|
|
2212
|
+
async userTriggeredTerminate() {
|
|
2213
|
+
}
|
|
2214
|
+
async init(accountId, workflow, version, instance, event) {
|
|
2215
|
+
if (this.priorityQueue === void 0 && (this.priorityQueue = new TimePriorityQueue(
|
|
2216
|
+
this.ctx,
|
|
2217
|
+
// this.env,
|
|
2218
|
+
{
|
|
2219
|
+
accountId,
|
|
2220
|
+
workflow,
|
|
2221
|
+
version,
|
|
2222
|
+
instance,
|
|
2223
|
+
event
|
|
2224
|
+
}
|
|
2225
|
+
)), this.isRunning)
|
|
2226
|
+
return;
|
|
2227
|
+
this.priorityQueue.popPastEntries(), await this.priorityQueue.handleNextAlarm(), this.accountId = accountId, this.instanceId = instance.id, this.workflowName = workflow.name;
|
|
2228
|
+
let status = await this.getStatus();
|
|
2229
|
+
if ([
|
|
2230
|
+
3 /* Errored */,
|
|
2231
|
+
// TODO (WOR-85): Remove this once upgrade story is done
|
|
2232
|
+
4 /* Terminated */,
|
|
2233
|
+
5 /* Complete */
|
|
2234
|
+
].includes(status))
|
|
2235
|
+
return;
|
|
2236
|
+
if (await this.ctx.storage.get(INSTANCE_METADATA) == null) {
|
|
2237
|
+
let instanceMetadata = {
|
|
2238
|
+
accountId,
|
|
2239
|
+
workflow,
|
|
2240
|
+
version,
|
|
2241
|
+
instance,
|
|
2242
|
+
event
|
|
2243
|
+
};
|
|
2244
|
+
await this.ctx.storage.put(INSTANCE_METADATA, instanceMetadata), this.writeLog(0 /* WORKFLOW_QUEUED */, null, null, {
|
|
2245
|
+
params: event.payload,
|
|
2246
|
+
versionId: version.id,
|
|
2247
|
+
trigger: {
|
|
2248
|
+
source: 0 /* API */
|
|
2249
|
+
}
|
|
2250
|
+
}), this.writeLog(1 /* WORKFLOW_START */, null, null, {});
|
|
2251
|
+
}
|
|
2252
|
+
await this.restoreEventMap();
|
|
2253
|
+
let stubStep = new Context(this, this.ctx), workflowRunningHandler = async () => {
|
|
2254
|
+
await this.ctx.storage.transaction(async () => {
|
|
2255
|
+
await this.setStatus(accountId, instance.id, 1 /* Running */);
|
|
2256
|
+
});
|
|
2257
|
+
};
|
|
2258
|
+
this.isRunning = !0, workflowRunningHandler();
|
|
2259
|
+
try {
|
|
2260
|
+
let result = await this.env.USER_WORKFLOW.run(event, stubStep);
|
|
2261
|
+
this.writeLog(2 /* WORKFLOW_SUCCESS */, null, null, {
|
|
2262
|
+
result
|
|
2263
|
+
}), await this.ctx.storage.transaction(async () => {
|
|
2264
|
+
await this.setStatus(accountId, instance.id, 5 /* Complete */);
|
|
2265
|
+
}), this.isRunning = !1;
|
|
2266
|
+
} catch (err) {
|
|
2267
|
+
let error;
|
|
2268
|
+
if (err instanceof Error) {
|
|
2269
|
+
if (err.name === "NonRetryableError" || err.message.startsWith("NonRetryableError")) {
|
|
2270
|
+
this.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
|
|
2271
|
+
error: new WorkflowFatalError(
|
|
2272
|
+
"The execution of the Workflow instance was terminated, as a step threw an NonRetryableError and it was not handled"
|
|
2273
|
+
)
|
|
2274
|
+
}), await this.setStatus(accountId, instance.id, 3 /* Errored */), await this.abort("A step threw a NonRetryableError"), this.isRunning = !1;
|
|
2275
|
+
return;
|
|
2276
|
+
}
|
|
2277
|
+
error = {
|
|
2278
|
+
message: err.message,
|
|
2279
|
+
name: err.name
|
|
2280
|
+
};
|
|
2281
|
+
} else
|
|
2282
|
+
error = {
|
|
2283
|
+
name: "Error",
|
|
2284
|
+
message: err
|
|
2285
|
+
};
|
|
2286
|
+
this.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
|
|
2287
|
+
error
|
|
2288
|
+
}), await this.ctx.storage.transaction(async () => {
|
|
2289
|
+
await this.setStatus(accountId, instance.id, 3 /* Errored */);
|
|
2290
|
+
}), this.isRunning = !1;
|
|
2291
|
+
}
|
|
2292
|
+
return {
|
|
2293
|
+
id: instance.id
|
|
2294
|
+
};
|
|
2295
|
+
}
|
|
2296
|
+
};
|
|
2297
|
+
|
|
2298
|
+
// ../workflows-shared/src/binding.ts
|
|
2299
|
+
import { RpcTarget as RpcTarget3, WorkerEntrypoint } from "cloudflare:workers";
|
|
2300
|
+
var WorkflowBinding = class extends WorkerEntrypoint {
|
|
2301
|
+
constructor(ctx, env) {
|
|
2302
|
+
super(ctx, env);
|
|
2303
|
+
}
|
|
2304
|
+
async create({
|
|
2305
|
+
id = crypto.randomUUID(),
|
|
2306
|
+
params = {}
|
|
2307
|
+
} = {}) {
|
|
2308
|
+
if (!isValidWorkflowInstanceId(id))
|
|
2309
|
+
throw new WorkflowError("Workflow instance has invalid id");
|
|
2310
|
+
let stubId = this.env.ENGINE.idFromName(id), initPromise = this.env.ENGINE.get(stubId).init(
|
|
2311
|
+
0,
|
|
2312
|
+
// accountId: number,
|
|
2313
|
+
{},
|
|
2314
|
+
// workflow: DatabaseWorkflow,
|
|
2315
|
+
{},
|
|
2316
|
+
// version: DatabaseVersion,
|
|
2317
|
+
{ id },
|
|
2318
|
+
// instance: DatabaseInstance,
|
|
2319
|
+
{
|
|
2320
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
2321
|
+
payload: params,
|
|
2322
|
+
instanceId: id
|
|
2323
|
+
}
|
|
2324
|
+
).then((val) => {
|
|
2325
|
+
val !== void 0 && val[Symbol.dispose]();
|
|
2326
|
+
});
|
|
2327
|
+
return this.ctx.waitUntil(initPromise), {
|
|
2328
|
+
id
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
async get(id) {
|
|
2332
|
+
let stubId = this.env.ENGINE.idFromName(id), stub = this.env.ENGINE.get(stubId), handle = new WorkflowHandle(id, stub);
|
|
2333
|
+
try {
|
|
2334
|
+
await handle.status();
|
|
2335
|
+
} catch {
|
|
2336
|
+
throw new Error("instance.not_found");
|
|
2337
|
+
}
|
|
2338
|
+
return handle;
|
|
2339
|
+
}
|
|
2340
|
+
async createBatch(batch) {
|
|
2341
|
+
if (batch.length === 0)
|
|
2342
|
+
throw new Error(
|
|
2343
|
+
"WorkflowError: batchCreate should have at least 1 instance"
|
|
2344
|
+
);
|
|
2345
|
+
return await Promise.all(
|
|
2346
|
+
batch.map(async (val) => await this.create(val))
|
|
2347
|
+
);
|
|
2348
|
+
}
|
|
2349
|
+
async unsafeGetBindingName() {
|
|
2350
|
+
return this.env.BINDING_NAME;
|
|
2351
|
+
}
|
|
2352
|
+
async unsafeGetInstanceModifier(instanceId) {
|
|
2353
|
+
let stubId = this.env.ENGINE.idFromName(instanceId);
|
|
2354
|
+
return this.env.ENGINE.get(stubId).getInstanceModifier();
|
|
2355
|
+
}
|
|
2356
|
+
async unsafeWaitForStepResult(instanceId, name, index) {
|
|
2357
|
+
let stubId = this.env.ENGINE.idFromName(instanceId);
|
|
2358
|
+
return await this.env.ENGINE.get(stubId).waitForStepResult(name, index);
|
|
2359
|
+
}
|
|
2360
|
+
async unsafeAbort(instanceId, reason) {
|
|
2361
|
+
let stubId = this.env.ENGINE.idFromName(instanceId), stub = this.env.ENGINE.get(stubId);
|
|
2362
|
+
try {
|
|
2363
|
+
await stub.unsafeAbort(reason);
|
|
2364
|
+
} catch {
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
async unsafeWaitForStatus(instanceId, status) {
|
|
2368
|
+
let stubId = this.env.ENGINE.idFromName(instanceId);
|
|
2369
|
+
return await this.env.ENGINE.get(stubId).waitForStatus(status);
|
|
2370
|
+
}
|
|
2371
|
+
async unsafeGetOutputOrError(instanceId, isOutput) {
|
|
2372
|
+
let stubId = this.env.ENGINE.idFromName(instanceId);
|
|
2373
|
+
return await this.env.ENGINE.get(stubId).getOutputOrError(isOutput);
|
|
2374
|
+
}
|
|
2375
|
+
}, WorkflowHandle = class extends RpcTarget3 {
|
|
2376
|
+
constructor(id, stub) {
|
|
2377
|
+
super();
|
|
2378
|
+
this.id = id;
|
|
2379
|
+
this.stub = stub;
|
|
2380
|
+
}
|
|
2381
|
+
async pause() {
|
|
2382
|
+
throw new Error("Not implemented yet");
|
|
2383
|
+
}
|
|
2384
|
+
async resume() {
|
|
2385
|
+
throw new Error("Not implemented yet");
|
|
2386
|
+
}
|
|
2387
|
+
async terminate() {
|
|
2388
|
+
throw new Error("Not implemented yet");
|
|
2389
|
+
}
|
|
2390
|
+
async restart() {
|
|
2391
|
+
throw new Error("Not implemented yet");
|
|
2392
|
+
}
|
|
2393
|
+
async status() {
|
|
2394
|
+
let status = await this.stub.getStatus();
|
|
2395
|
+
using logs = await this.stub.readLogs();
|
|
2396
|
+
let stepOutputs = logs.logs.filter(
|
|
2397
|
+
(log) => log.event === 6 /* STEP_SUCCESS */ || log.event === 15 /* WAIT_COMPLETE */
|
|
2398
|
+
).map(
|
|
2399
|
+
(log) => log.event === 6 /* STEP_SUCCESS */ ? log.metadata.result : log.metadata.payload
|
|
2400
|
+
), workflowOutput = logs.logs.find((log) => log.event === 2 /* WORKFLOW_SUCCESS */)?.metadata.result ?? null, workflowError = logs.logs.find(
|
|
2401
|
+
(log) => log.event === 3 /* WORKFLOW_FAILURE */
|
|
2402
|
+
)?.metadata.error;
|
|
2403
|
+
return {
|
|
2404
|
+
status: instanceStatusName(status),
|
|
2405
|
+
__LOCAL_DEV_STEP_OUTPUTS: stepOutputs,
|
|
2406
|
+
output: workflowOutput,
|
|
2407
|
+
error: workflowError
|
|
2408
|
+
};
|
|
2409
|
+
}
|
|
2410
|
+
async sendEvent(args) {
|
|
2411
|
+
await this.stub.receiveEvent({
|
|
2412
|
+
payload: args.payload,
|
|
2413
|
+
type: args.type,
|
|
2414
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
2415
|
+
});
|
|
2416
|
+
}
|
|
2417
|
+
};
|
|
2418
|
+
export {
|
|
2419
|
+
Engine,
|
|
2420
|
+
WorkflowBinding
|
|
2421
|
+
};
|
|
2422
|
+
//# sourceMappingURL=binding.worker.js.map
|