Next.js website for Rocky Mountain Vending company featuring: - Product catalog with Stripe integration - Service areas and parts pages - Admin dashboard with Clerk authentication - SEO optimized pages with JSON-LD structured data Co-authored-by: Cursor <cursoragent@cursor.com>
1974 lines
83 KiB
Text
1974 lines
83 KiB
Text
var __create = Object.create;
|
||
var __defProp = Object.defineProperty;
|
||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||
var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
|
||
var __commonJS = (cb, mod) => function() {
|
||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
||
};
|
||
var __copyProps = (to, from, except, desc) => {
|
||
if (from && typeof from == "object" || typeof from == "function")
|
||
for (let key of __getOwnPropNames(from))
|
||
!__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||
return to;
|
||
};
|
||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||
// If the importer is in node compatibility mode or this is not an ESM
|
||
// file that has been converted to a CommonJS file using a Babel-
|
||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
|
||
mod
|
||
));
|
||
|
||
// ../../node_modules/.pnpm/heap-js@2.5.0/node_modules/heap-js/dist/heap-js.umd.js
|
||
var require_heap_js_umd = __commonJS({
|
||
"../../node_modules/.pnpm/heap-js@2.5.0/node_modules/heap-js/dist/heap-js.umd.js"(exports, module) {
|
||
(function(global, factory) {
|
||
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 = {}));
|
||
})(exports, function(exports2) {
|
||
"use strict";
|
||
var __awaiter = function(thisArg, _arguments, P, generator) {
|
||
function adopt(value) {
|
||
return value instanceof P ? value : new P(function(resolve) {
|
||
resolve(value);
|
||
});
|
||
}
|
||
return new (P || (P = Promise))(function(resolve, reject) {
|
||
function fulfilled(value) {
|
||
try {
|
||
step(generator.next(value));
|
||
} catch (e) {
|
||
reject(e);
|
||
}
|
||
}
|
||
function rejected(value) {
|
||
try {
|
||
step(generator.throw(value));
|
||
} catch (e) {
|
||
reject(e);
|
||
}
|
||
}
|
||
function step(result) {
|
||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
|
||
}
|
||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||
});
|
||
}, __generator$1 = function(thisArg, body) {
|
||
var _ = { label: 0, sent: function() {
|
||
if (t[0] & 1)
|
||
throw t[1];
|
||
return t[1];
|
||
}, trys: [], ops: [] }, f, y, t, g;
|
||
return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
|
||
return this;
|
||
}), g;
|
||
function verb(n2) {
|
||
return function(v) {
|
||
return step([n2, v]);
|
||
};
|
||
}
|
||
function step(op) {
|
||
if (f)
|
||
throw new TypeError("Generator is already executing.");
|
||
for (; g && (g = 0, op[0] && (_ = 0)), _; )
|
||
try {
|
||
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;
|
||
switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
|
||
case 0:
|
||
case 1:
|
||
t = op;
|
||
break;
|
||
case 4:
|
||
return _.label++, { value: op[1], done: !1 };
|
||
case 5:
|
||
_.label++, y = op[1], op = [0];
|
||
continue;
|
||
case 7:
|
||
op = _.ops.pop(), _.trys.pop();
|
||
continue;
|
||
default:
|
||
if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
||
_ = 0;
|
||
continue;
|
||
}
|
||
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
||
_.label = op[1];
|
||
break;
|
||
}
|
||
if (op[0] === 6 && _.label < t[1]) {
|
||
_.label = t[1], t = op;
|
||
break;
|
||
}
|
||
if (t && _.label < t[2]) {
|
||
_.label = t[2], _.ops.push(op);
|
||
break;
|
||
}
|
||
t[2] && _.ops.pop(), _.trys.pop();
|
||
continue;
|
||
}
|
||
op = body.call(thisArg, _);
|
||
} catch (e) {
|
||
op = [6, e], y = 0;
|
||
} finally {
|
||
f = t = 0;
|
||
}
|
||
if (op[0] & 5)
|
||
throw op[1];
|
||
return { value: op[0] ? op[1] : void 0, done: !0 };
|
||
}
|
||
}, __read$1 = function(o, n2) {
|
||
var m = typeof Symbol == "function" && o[Symbol.iterator];
|
||
if (!m)
|
||
return o;
|
||
var i = m.call(o), r2, ar = [], e;
|
||
try {
|
||
for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; )
|
||
ar.push(r2.value);
|
||
} catch (error) {
|
||
e = { error };
|
||
} finally {
|
||
try {
|
||
r2 && !r2.done && (m = i.return) && m.call(i);
|
||
} finally {
|
||
if (e)
|
||
throw e.error;
|
||
}
|
||
}
|
||
return ar;
|
||
}, __spreadArray$1 = function(to, from, pack) {
|
||
if (pack || arguments.length === 2)
|
||
for (var i = 0, l = from.length, ar; i < l; i++)
|
||
(ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
|
||
return to.concat(ar || Array.prototype.slice.call(from));
|
||
}, __values = function(o) {
|
||
var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
|
||
if (m)
|
||
return m.call(o);
|
||
if (o && typeof o.length == "number")
|
||
return {
|
||
next: function() {
|
||
return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
|
||
}
|
||
};
|
||
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
||
}, HeapAsync = (
|
||
/** @class */
|
||
function() {
|
||
function HeapAsync2(compare) {
|
||
compare === void 0 && (compare = HeapAsync2.minComparator);
|
||
var _this = this;
|
||
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) {
|
||
return _this.compare(a, b).then(function(res) {
|
||
return -1 * res;
|
||
});
|
||
};
|
||
}
|
||
return HeapAsync2.getChildrenIndexOf = function(idx) {
|
||
return [idx * 2 + 1, idx * 2 + 2];
|
||
}, HeapAsync2.getParentIndexOf = function(idx) {
|
||
if (idx <= 0)
|
||
return -1;
|
||
var whichChildren = idx % 2 ? 1 : 2;
|
||
return Math.floor((idx - whichChildren) / 2);
|
||
}, HeapAsync2.getSiblingIndexOf = function(idx) {
|
||
if (idx <= 0)
|
||
return -1;
|
||
var whichChildren = idx % 2 ? 1 : -1;
|
||
return idx + whichChildren;
|
||
}, HeapAsync2.minComparator = function(a, b) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
return a > b ? [2, 1] : a < b ? [2, -1] : [2, 0];
|
||
});
|
||
});
|
||
}, HeapAsync2.maxComparator = function(a, b) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
return b > a ? [2, 1] : b < a ? [2, -1] : [2, 0];
|
||
});
|
||
});
|
||
}, HeapAsync2.minComparatorNumber = function(a, b) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
return [2, a - b];
|
||
});
|
||
});
|
||
}, HeapAsync2.maxComparatorNumber = function(a, b) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
return [2, b - a];
|
||
});
|
||
});
|
||
}, HeapAsync2.defaultIsEqual = function(a, b) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
return [2, a === b];
|
||
});
|
||
});
|
||
}, HeapAsync2.print = function(heap) {
|
||
function deep(i2) {
|
||
var pi = HeapAsync2.getParentIndexOf(i2);
|
||
return Math.floor(Math.log2(pi + 1));
|
||
}
|
||
function repeat(str, times) {
|
||
for (var out = ""; times > 0; --times)
|
||
out += str;
|
||
return out;
|
||
}
|
||
for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
|
||
var i = deep(node) + 1;
|
||
node === 0 && (i = 0);
|
||
var nodeText = String(heap.get(node));
|
||
nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
|
||
}
|
||
return lines.map(function(line, i2) {
|
||
var times = Math.pow(2, maxLines - i2) - 1;
|
||
return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
|
||
var half = (maxLength - el.length) / 2;
|
||
return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
|
||
}).join(repeat(" ", times * maxLength));
|
||
}).join(`
|
||
`);
|
||
}, HeapAsync2.heapify = function(arr, compare) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var heap;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return heap = new HeapAsync2(compare), heap.heapArray = arr, [4, heap.init()];
|
||
case 1:
|
||
return _a.sent(), [2, heap];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.heappop = function(heapArr, compare) {
|
||
var heap = new HeapAsync2(compare);
|
||
return heap.heapArray = heapArr, heap.pop();
|
||
}, HeapAsync2.heappush = function(heapArr, item, compare) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var heap;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return heap = new HeapAsync2(compare), heap.heapArray = heapArr, [4, heap.push(item)];
|
||
case 1:
|
||
return _a.sent(), [
|
||
2
|
||
/*return*/
|
||
];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.heappushpop = function(heapArr, item, compare) {
|
||
var heap = new HeapAsync2(compare);
|
||
return heap.heapArray = heapArr, heap.pushpop(item);
|
||
}, HeapAsync2.heapreplace = function(heapArr, item, compare) {
|
||
var heap = new HeapAsync2(compare);
|
||
return heap.heapArray = heapArr, heap.replace(item);
|
||
}, HeapAsync2.heaptop = function(heapArr, n2, compare) {
|
||
n2 === void 0 && (n2 = 1);
|
||
var heap = new HeapAsync2(compare);
|
||
return heap.heapArray = heapArr, heap.top(n2);
|
||
}, HeapAsync2.heapbottom = function(heapArr, n2, compare) {
|
||
n2 === void 0 && (n2 = 1);
|
||
var heap = new HeapAsync2(compare);
|
||
return heap.heapArray = heapArr, heap.bottom(n2);
|
||
}, HeapAsync2.nlargest = function(n2, iterable, compare) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var heap;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
|
||
case 1:
|
||
return _a.sent(), [2, heap.top(n2)];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.nsmallest = function(n2, iterable, compare) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var heap;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
|
||
case 1:
|
||
return _a.sent(), [2, heap.bottom(n2)];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.add = function(element) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return [4, this._sortNodeUp(this.heapArray.push(element) - 1)];
|
||
case 1:
|
||
return _a.sent(), this._applyLimit(), [2, !0];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.addAll = function(elements) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var i, l, _a;
|
||
return __generator$1(this, function(_b) {
|
||
switch (_b.label) {
|
||
case 0:
|
||
i = this.length, (_a = this.heapArray).push.apply(_a, __spreadArray$1([], __read$1(elements), !1)), l = this.length, _b.label = 1;
|
||
case 1:
|
||
return i < l ? [4, this._sortNodeUp(i)] : [3, 4];
|
||
case 2:
|
||
_b.sent(), _b.label = 3;
|
||
case 3:
|
||
return ++i, [3, 1];
|
||
case 4:
|
||
return this._applyLimit(), [2, !0];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.bottom = function(n2) {
|
||
return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
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)];
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.check = function() {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var j, el, children, children_1, children_1_1, ch, e_1_1, e_1, _a;
|
||
return __generator$1(this, function(_b) {
|
||
switch (_b.label) {
|
||
case 0:
|
||
j = 0, _b.label = 1;
|
||
case 1:
|
||
if (!(j < this.heapArray.length))
|
||
return [3, 10];
|
||
el = this.heapArray[j], children = this.getChildrenOf(j), _b.label = 2;
|
||
case 2:
|
||
_b.trys.push([2, 7, 8, 9]), children_1 = (e_1 = void 0, __values(children)), children_1_1 = children_1.next(), _b.label = 3;
|
||
case 3:
|
||
return children_1_1.done ? [3, 6] : (ch = children_1_1.value, [4, this.compare(el, ch)]);
|
||
case 4:
|
||
if (_b.sent() > 0)
|
||
return [2, el];
|
||
_b.label = 5;
|
||
case 5:
|
||
return children_1_1 = children_1.next(), [3, 3];
|
||
case 6:
|
||
return [3, 9];
|
||
case 7:
|
||
return e_1_1 = _b.sent(), e_1 = { error: e_1_1 }, [3, 9];
|
||
case 8:
|
||
try {
|
||
children_1_1 && !children_1_1.done && (_a = children_1.return) && _a.call(children_1);
|
||
} finally {
|
||
if (e_1)
|
||
throw e_1.error;
|
||
}
|
||
return [
|
||
7
|
||
/*endfinally*/
|
||
];
|
||
case 9:
|
||
return ++j, [3, 1];
|
||
case 10:
|
||
return [
|
||
2
|
||
/*return*/
|
||
];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.clear = function() {
|
||
this.heapArray = [];
|
||
}, HeapAsync2.prototype.clone = function() {
|
||
var cloned = new HeapAsync2(this.comparator());
|
||
return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
|
||
}, HeapAsync2.prototype.comparator = function() {
|
||
return this.compare;
|
||
}, HeapAsync2.prototype.contains = function(o, fn) {
|
||
return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
|
||
var _a, _b, el, e_2_1, e_2, _c;
|
||
return __generator$1(this, function(_d) {
|
||
switch (_d.label) {
|
||
case 0:
|
||
_d.trys.push([0, 5, 6, 7]), _a = __values(this.heapArray), _b = _a.next(), _d.label = 1;
|
||
case 1:
|
||
return _b.done ? [3, 4] : (el = _b.value, [4, fn(el, o)]);
|
||
case 2:
|
||
if (_d.sent())
|
||
return [2, !0];
|
||
_d.label = 3;
|
||
case 3:
|
||
return _b = _a.next(), [3, 1];
|
||
case 4:
|
||
return [3, 7];
|
||
case 5:
|
||
return e_2_1 = _d.sent(), e_2 = { error: e_2_1 }, [3, 7];
|
||
case 6:
|
||
try {
|
||
_b && !_b.done && (_c = _a.return) && _c.call(_a);
|
||
} finally {
|
||
if (e_2)
|
||
throw e_2.error;
|
||
}
|
||
return [
|
||
7
|
||
/*endfinally*/
|
||
];
|
||
case 7:
|
||
return [2, !1];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.init = function(array) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var i;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
array && (this.heapArray = __spreadArray$1([], __read$1(array), !1)), i = Math.floor(this.heapArray.length), _a.label = 1;
|
||
case 1:
|
||
return i >= 0 ? [4, this._sortNodeDown(i)] : [3, 4];
|
||
case 2:
|
||
_a.sent(), _a.label = 3;
|
||
case 3:
|
||
return --i, [3, 1];
|
||
case 4:
|
||
return this._applyLimit(), [
|
||
2
|
||
/*return*/
|
||
];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.isEmpty = function() {
|
||
return this.length === 0;
|
||
}, HeapAsync2.prototype.leafs = function() {
|
||
if (this.heapArray.length === 0)
|
||
return [];
|
||
var pi = HeapAsync2.getParentIndexOf(this.heapArray.length - 1);
|
||
return this.heapArray.slice(pi + 1);
|
||
}, Object.defineProperty(HeapAsync2.prototype, "length", {
|
||
/**
|
||
* Length of the heap.
|
||
* @return {Number}
|
||
*/
|
||
get: function() {
|
||
return this.heapArray.length;
|
||
},
|
||
enumerable: !1,
|
||
configurable: !0
|
||
}), Object.defineProperty(HeapAsync2.prototype, "limit", {
|
||
/**
|
||
* Get length limit of the heap.
|
||
* @return {Number}
|
||
*/
|
||
get: function() {
|
||
return this._limit;
|
||
},
|
||
/**
|
||
* Set length limit of the heap.
|
||
* @return {Number}
|
||
*/
|
||
set: function(_l) {
|
||
this._limit = ~~_l, this._applyLimit();
|
||
},
|
||
enumerable: !1,
|
||
configurable: !0
|
||
}), HeapAsync2.prototype.peek = function() {
|
||
return this.heapArray[0];
|
||
}, HeapAsync2.prototype.pop = function() {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var last;
|
||
return __generator$1(this, function(_a) {
|
||
return last = this.heapArray.pop(), this.length > 0 && last !== void 0 ? [2, this.replace(last)] : [2, last];
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.push = function() {
|
||
for (var elements = [], _i = 0; _i < arguments.length; _i++)
|
||
elements[_i] = arguments[_i];
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
return elements.length < 1 ? [2, !1] : elements.length === 1 ? [2, this.add(elements[0])] : [2, this.addAll(elements)];
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.pushpop = function(element) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var _a;
|
||
return __generator$1(this, function(_b) {
|
||
switch (_b.label) {
|
||
case 0:
|
||
return [4, this.compare(this.heapArray[0], element)];
|
||
case 1:
|
||
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];
|
||
case 2:
|
||
_b.sent(), _b.label = 3;
|
||
case 3:
|
||
return [2, element];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.remove = function(o, fn) {
|
||
return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
|
||
var idx, i;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return this.length > 0 ? o !== void 0 ? [3, 2] : [4, this.pop()] : [3, 13];
|
||
case 1:
|
||
return _a.sent(), [2, !0];
|
||
case 2:
|
||
idx = -1, i = 0, _a.label = 3;
|
||
case 3:
|
||
return i < this.heapArray.length ? [4, fn(this.heapArray[i], o)] : [3, 6];
|
||
case 4:
|
||
if (_a.sent())
|
||
return idx = i, [3, 6];
|
||
_a.label = 5;
|
||
case 5:
|
||
return ++i, [3, 3];
|
||
case 6:
|
||
return idx >= 0 ? idx !== 0 ? [3, 8] : [4, this.pop()] : [3, 13];
|
||
case 7:
|
||
return _a.sent(), [3, 12];
|
||
case 8:
|
||
return idx !== this.length - 1 ? [3, 9] : (this.heapArray.pop(), [3, 12]);
|
||
case 9:
|
||
return this.heapArray.splice(idx, 1, this.heapArray.pop()), [4, this._sortNodeUp(idx)];
|
||
case 10:
|
||
return _a.sent(), [4, this._sortNodeDown(idx)];
|
||
case 11:
|
||
_a.sent(), _a.label = 12;
|
||
case 12:
|
||
return [2, !0];
|
||
case 13:
|
||
return [2, !1];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.replace = function(element) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var peek;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return peek = this.heapArray[0], this.heapArray[0] = element, [4, this._sortNodeDown(0)];
|
||
case 1:
|
||
return _a.sent(), [2, peek];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.size = function() {
|
||
return this.length;
|
||
}, HeapAsync2.prototype.top = function(n2) {
|
||
return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
|
||
return __generator$1(this, function(_a) {
|
||
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)];
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype.toArray = function() {
|
||
return __spreadArray$1([], __read$1(this.heapArray), !1);
|
||
}, HeapAsync2.prototype.toString = function() {
|
||
return this.heapArray.toString();
|
||
}, HeapAsync2.prototype.get = function(i) {
|
||
return this.heapArray[i];
|
||
}, HeapAsync2.prototype.getChildrenOf = function(idx) {
|
||
var _this = this;
|
||
return HeapAsync2.getChildrenIndexOf(idx).map(function(i) {
|
||
return _this.heapArray[i];
|
||
}).filter(function(e) {
|
||
return e !== void 0;
|
||
});
|
||
}, HeapAsync2.prototype.getParentOf = function(idx) {
|
||
var pi = HeapAsync2.getParentIndexOf(idx);
|
||
return this.heapArray[pi];
|
||
}, HeapAsync2.prototype[Symbol.iterator] = function() {
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return this.length ? [4, this.pop()] : [3, 2];
|
||
case 1:
|
||
return _a.sent(), [3, 0];
|
||
case 2:
|
||
return [
|
||
2
|
||
/*return*/
|
||
];
|
||
}
|
||
});
|
||
}, HeapAsync2.prototype.iterator = function() {
|
||
return this;
|
||
}, HeapAsync2.prototype._applyLimit = function() {
|
||
if (this._limit && this._limit < this.heapArray.length)
|
||
for (var rm = this.heapArray.length - this._limit; rm; )
|
||
this.heapArray.pop(), --rm;
|
||
}, HeapAsync2.prototype._bottomN_push = function(n2) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var bottomHeap, startAt, parentStartAt, indices, i, arr, i;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return bottomHeap = new HeapAsync2(this.compare), bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), [4, bottomHeap.init()];
|
||
case 1:
|
||
for (_a.sent(), startAt = this.heapArray.length - 1 - n2, parentStartAt = HeapAsync2.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
|
||
indices.push(i);
|
||
arr = this.heapArray, _a.label = 2;
|
||
case 2:
|
||
return indices.length ? (i = indices.shift(), [4, this.compare(arr[i], bottomHeap.peek())]) : [3, 6];
|
||
case 3:
|
||
return _a.sent() > 0 ? [4, bottomHeap.replace(arr[i])] : [3, 5];
|
||
case 4:
|
||
_a.sent(), i % 2 && indices.push(HeapAsync2.getParentIndexOf(i)), _a.label = 5;
|
||
case 5:
|
||
return [3, 2];
|
||
case 6:
|
||
return [2, bottomHeap.toArray()];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype._moveNode = function(j, k) {
|
||
var _a;
|
||
_a = __read$1([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
|
||
}, HeapAsync2.prototype._sortNodeDown = function(i) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var moveIt, self2, getPotentialParent, childrenIdx, bestChildIndex, j, bestChild, _a, _this = this;
|
||
return __generator$1(this, function(_b) {
|
||
switch (_b.label) {
|
||
case 0:
|
||
moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j2) {
|
||
return __awaiter(_this, void 0, void 0, function() {
|
||
var _a2;
|
||
return __generator$1(this, function(_b2) {
|
||
switch (_b2.label) {
|
||
case 0:
|
||
return _a2 = this.heapArray.length > j2, _a2 ? [4, this.compare(this.heapArray[j2], this.heapArray[best])] : [3, 2];
|
||
case 1:
|
||
_a2 = _b2.sent() < 0, _b2.label = 2;
|
||
case 2:
|
||
return _a2 && (best = j2), [2, best];
|
||
}
|
||
});
|
||
});
|
||
}, _b.label = 1;
|
||
case 1:
|
||
if (!moveIt)
|
||
return [3, 8];
|
||
childrenIdx = HeapAsync2.getChildrenIndexOf(i), bestChildIndex = childrenIdx[0], j = 1, _b.label = 2;
|
||
case 2:
|
||
return j < childrenIdx.length ? [4, getPotentialParent(bestChildIndex, childrenIdx[j])] : [3, 5];
|
||
case 3:
|
||
bestChildIndex = _b.sent(), _b.label = 4;
|
||
case 4:
|
||
return ++j, [3, 2];
|
||
case 5:
|
||
return bestChild = this.heapArray[bestChildIndex], _a = typeof bestChild < "u", _a ? [4, this.compare(self2, bestChild)] : [3, 7];
|
||
case 6:
|
||
_a = _b.sent() > 0, _b.label = 7;
|
||
case 7:
|
||
return _a ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1, [3, 1];
|
||
case 8:
|
||
return [
|
||
2
|
||
/*return*/
|
||
];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype._sortNodeUp = function(i) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var moveIt, pi, _a;
|
||
return __generator$1(this, function(_b) {
|
||
switch (_b.label) {
|
||
case 0:
|
||
moveIt = i > 0, _b.label = 1;
|
||
case 1:
|
||
return moveIt ? (pi = HeapAsync2.getParentIndexOf(i), _a = pi >= 0, _a ? [4, this.compare(this.heapArray[pi], this.heapArray[i])] : [3, 3]) : [3, 4];
|
||
case 2:
|
||
_a = _b.sent() > 0, _b.label = 3;
|
||
case 3:
|
||
return _a ? (this._moveNode(i, pi), i = pi) : moveIt = !1, [3, 1];
|
||
case 4:
|
||
return [
|
||
2
|
||
/*return*/
|
||
];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype._topN_push = function(n2) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var topHeap, indices, arr, i;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, indices = [0], arr = this.heapArray, _a.label = 1;
|
||
case 1:
|
||
return indices.length ? (i = indices.shift(), i < arr.length ? topHeap.length < n2 ? [4, topHeap.push(arr[i])] : [3, 3] : [3, 6]) : [3, 7];
|
||
case 2:
|
||
return _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), [3, 6];
|
||
case 3:
|
||
return [4, this.compare(arr[i], topHeap.peek())];
|
||
case 4:
|
||
return _a.sent() < 0 ? [4, topHeap.replace(arr[i])] : [3, 6];
|
||
case 5:
|
||
_a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 6;
|
||
case 6:
|
||
return [3, 1];
|
||
case 7:
|
||
return [2, topHeap.toArray()];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype._topN_fill = function(n2) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var heapArray, topHeap, branch, indices, i, i;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return heapArray = this.heapArray, topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), [4, topHeap.init()];
|
||
case 1:
|
||
for (_a.sent(), branch = HeapAsync2.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
|
||
indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i).filter(function(l) {
|
||
return l < heapArray.length;
|
||
})), !1));
|
||
(n2 - 1) % 2 && indices.push(n2), _a.label = 2;
|
||
case 2:
|
||
return indices.length ? (i = indices.shift(), i < heapArray.length ? [4, this.compare(heapArray[i], topHeap.peek())] : [3, 5]) : [3, 6];
|
||
case 3:
|
||
return _a.sent() < 0 ? [4, topHeap.replace(heapArray[i])] : [3, 5];
|
||
case 4:
|
||
_a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 5;
|
||
case 5:
|
||
return [3, 2];
|
||
case 6:
|
||
return [2, topHeap.toArray()];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype._topN_heap = function(n2) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var topHeap, result, i, _a, _b;
|
||
return __generator$1(this, function(_c) {
|
||
switch (_c.label) {
|
||
case 0:
|
||
topHeap = this.clone(), result = [], i = 0, _c.label = 1;
|
||
case 1:
|
||
return i < n2 ? (_b = (_a = result).push, [4, topHeap.pop()]) : [3, 4];
|
||
case 2:
|
||
_b.apply(_a, [_c.sent()]), _c.label = 3;
|
||
case 3:
|
||
return ++i, [3, 1];
|
||
case 4:
|
||
return [2, result];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype._topIdxOf = function(list) {
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var idx, top, i, comp;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
if (!list.length)
|
||
return [2, -1];
|
||
idx = 0, top = list[idx], i = 1, _a.label = 1;
|
||
case 1:
|
||
return i < list.length ? [4, this.compare(list[i], top)] : [3, 4];
|
||
case 2:
|
||
comp = _a.sent(), comp < 0 && (idx = i, top = list[i]), _a.label = 3;
|
||
case 3:
|
||
return ++i, [3, 1];
|
||
case 4:
|
||
return [2, idx];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2.prototype._topOf = function() {
|
||
for (var list = [], _i = 0; _i < arguments.length; _i++)
|
||
list[_i] = arguments[_i];
|
||
return __awaiter(this, void 0, void 0, function() {
|
||
var heap;
|
||
return __generator$1(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return heap = new HeapAsync2(this.compare), [4, heap.init(list)];
|
||
case 1:
|
||
return _a.sent(), [2, heap.peek()];
|
||
}
|
||
});
|
||
});
|
||
}, HeapAsync2;
|
||
}()
|
||
), __generator = function(thisArg, body) {
|
||
var _ = { label: 0, sent: function() {
|
||
if (t[0] & 1)
|
||
throw t[1];
|
||
return t[1];
|
||
}, trys: [], ops: [] }, f, y, t, g;
|
||
return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
|
||
return this;
|
||
}), g;
|
||
function verb(n2) {
|
||
return function(v) {
|
||
return step([n2, v]);
|
||
};
|
||
}
|
||
function step(op) {
|
||
if (f)
|
||
throw new TypeError("Generator is already executing.");
|
||
for (; g && (g = 0, op[0] && (_ = 0)), _; )
|
||
try {
|
||
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;
|
||
switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
|
||
case 0:
|
||
case 1:
|
||
t = op;
|
||
break;
|
||
case 4:
|
||
return _.label++, { value: op[1], done: !1 };
|
||
case 5:
|
||
_.label++, y = op[1], op = [0];
|
||
continue;
|
||
case 7:
|
||
op = _.ops.pop(), _.trys.pop();
|
||
continue;
|
||
default:
|
||
if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
||
_ = 0;
|
||
continue;
|
||
}
|
||
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
||
_.label = op[1];
|
||
break;
|
||
}
|
||
if (op[0] === 6 && _.label < t[1]) {
|
||
_.label = t[1], t = op;
|
||
break;
|
||
}
|
||
if (t && _.label < t[2]) {
|
||
_.label = t[2], _.ops.push(op);
|
||
break;
|
||
}
|
||
t[2] && _.ops.pop(), _.trys.pop();
|
||
continue;
|
||
}
|
||
op = body.call(thisArg, _);
|
||
} catch (e) {
|
||
op = [6, e], y = 0;
|
||
} finally {
|
||
f = t = 0;
|
||
}
|
||
if (op[0] & 5)
|
||
throw op[1];
|
||
return { value: op[0] ? op[1] : void 0, done: !0 };
|
||
}
|
||
}, __read = function(o, n2) {
|
||
var m = typeof Symbol == "function" && o[Symbol.iterator];
|
||
if (!m)
|
||
return o;
|
||
var i = m.call(o), r2, ar = [], e;
|
||
try {
|
||
for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; )
|
||
ar.push(r2.value);
|
||
} catch (error) {
|
||
e = { error };
|
||
} finally {
|
||
try {
|
||
r2 && !r2.done && (m = i.return) && m.call(i);
|
||
} finally {
|
||
if (e)
|
||
throw e.error;
|
||
}
|
||
}
|
||
return ar;
|
||
}, __spreadArray = function(to, from, pack) {
|
||
if (pack || arguments.length === 2)
|
||
for (var i = 0, l = from.length, ar; i < l; i++)
|
||
(ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
|
||
return to.concat(ar || Array.prototype.slice.call(from));
|
||
}, toInt = function(n2) {
|
||
return ~~n2;
|
||
}, Heap2 = (
|
||
/** @class */
|
||
function() {
|
||
function Heap3(compare) {
|
||
compare === void 0 && (compare = Heap3.minComparator);
|
||
var _this = this;
|
||
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) {
|
||
return -1 * _this.compare(a, b);
|
||
};
|
||
}
|
||
return Heap3.getChildrenIndexOf = function(idx) {
|
||
return [idx * 2 + 1, idx * 2 + 2];
|
||
}, Heap3.getParentIndexOf = function(idx) {
|
||
if (idx <= 0)
|
||
return -1;
|
||
var whichChildren = idx % 2 ? 1 : 2;
|
||
return Math.floor((idx - whichChildren) / 2);
|
||
}, Heap3.getSiblingIndexOf = function(idx) {
|
||
if (idx <= 0)
|
||
return -1;
|
||
var whichChildren = idx % 2 ? 1 : -1;
|
||
return idx + whichChildren;
|
||
}, Heap3.minComparator = function(a, b) {
|
||
return a > b ? 1 : a < b ? -1 : 0;
|
||
}, Heap3.maxComparator = function(a, b) {
|
||
return b > a ? 1 : b < a ? -1 : 0;
|
||
}, Heap3.minComparatorNumber = function(a, b) {
|
||
return a - b;
|
||
}, Heap3.maxComparatorNumber = function(a, b) {
|
||
return b - a;
|
||
}, Heap3.defaultIsEqual = function(a, b) {
|
||
return a === b;
|
||
}, Heap3.print = function(heap) {
|
||
function deep(i2) {
|
||
var pi = Heap3.getParentIndexOf(i2);
|
||
return Math.floor(Math.log2(pi + 1));
|
||
}
|
||
function repeat(str, times) {
|
||
for (var out = ""; times > 0; --times)
|
||
out += str;
|
||
return out;
|
||
}
|
||
for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
|
||
var i = deep(node) + 1;
|
||
node === 0 && (i = 0);
|
||
var nodeText = String(heap.get(node));
|
||
nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
|
||
}
|
||
return lines.map(function(line, i2) {
|
||
var times = Math.pow(2, maxLines - i2) - 1;
|
||
return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
|
||
var half = (maxLength - el.length) / 2;
|
||
return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
|
||
}).join(repeat(" ", times * maxLength));
|
||
}).join(`
|
||
`);
|
||
}, Heap3.heapify = function(arr, compare) {
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = arr, heap.init(), heap;
|
||
}, Heap3.heappop = function(heapArr, compare) {
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = heapArr, heap.pop();
|
||
}, Heap3.heappush = function(heapArr, item, compare) {
|
||
var heap = new Heap3(compare);
|
||
heap.heapArray = heapArr, heap.push(item);
|
||
}, Heap3.heappushpop = function(heapArr, item, compare) {
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = heapArr, heap.pushpop(item);
|
||
}, Heap3.heapreplace = function(heapArr, item, compare) {
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = heapArr, heap.replace(item);
|
||
}, Heap3.heaptop = function(heapArr, n2, compare) {
|
||
n2 === void 0 && (n2 = 1);
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = heapArr, heap.top(n2);
|
||
}, Heap3.heapbottom = function(heapArr, n2, compare) {
|
||
n2 === void 0 && (n2 = 1);
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = heapArr, heap.bottom(n2);
|
||
}, Heap3.nlargest = function(n2, iterable, compare) {
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.top(n2);
|
||
}, Heap3.nsmallest = function(n2, iterable, compare) {
|
||
var heap = new Heap3(compare);
|
||
return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.bottom(n2);
|
||
}, Heap3.prototype.add = function(element) {
|
||
return this._sortNodeUp(this.heapArray.push(element) - 1), this._applyLimit(), !0;
|
||
}, Heap3.prototype.addAll = function(elements) {
|
||
var _a, i = this.length;
|
||
(_a = this.heapArray).push.apply(_a, __spreadArray([], __read(elements), !1));
|
||
for (var l = this.length; i < l; ++i)
|
||
this._sortNodeUp(i);
|
||
return this._applyLimit(), !0;
|
||
}, Heap3.prototype.bottom = function(n2) {
|
||
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);
|
||
}, Heap3.prototype.check = function() {
|
||
var _this = this;
|
||
return this.heapArray.find(function(el, j) {
|
||
return !!_this.getChildrenOf(j).find(function(ch) {
|
||
return _this.compare(el, ch) > 0;
|
||
});
|
||
});
|
||
}, Heap3.prototype.clear = function() {
|
||
this.heapArray = [];
|
||
}, Heap3.prototype.clone = function() {
|
||
var cloned = new Heap3(this.comparator());
|
||
return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
|
||
}, Heap3.prototype.comparator = function() {
|
||
return this.compare;
|
||
}, Heap3.prototype.contains = function(o, callbackFn) {
|
||
return callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.indexOf(o, callbackFn) !== -1;
|
||
}, Heap3.prototype.init = function(array) {
|
||
array && (this.heapArray = __spreadArray([], __read(array), !1));
|
||
for (var i = Math.floor(this.heapArray.length); i >= 0; --i)
|
||
this._sortNodeDown(i);
|
||
this._applyLimit();
|
||
}, Heap3.prototype.isEmpty = function() {
|
||
return this.length === 0;
|
||
}, Heap3.prototype.indexOf = function(element, callbackFn) {
|
||
if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
|
||
return -1;
|
||
for (var indexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
|
||
var currentElement = this.heapArray[currentIndex];
|
||
if (callbackFn(currentElement, element))
|
||
return currentIndex;
|
||
this.compare(currentElement, element) <= 0 && indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1)), currentIndex = indexes.shift() || this.heapArray.length;
|
||
}
|
||
return -1;
|
||
}, Heap3.prototype.indexOfEvery = function(element, callbackFn) {
|
||
if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
|
||
return [];
|
||
for (var indexes = [], foundIndexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
|
||
var currentElement = this.heapArray[currentIndex];
|
||
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;
|
||
}
|
||
return foundIndexes;
|
||
}, Heap3.prototype.leafs = function() {
|
||
if (this.heapArray.length === 0)
|
||
return [];
|
||
var pi = Heap3.getParentIndexOf(this.heapArray.length - 1);
|
||
return this.heapArray.slice(pi + 1);
|
||
}, Object.defineProperty(Heap3.prototype, "length", {
|
||
/**
|
||
* Length of the heap. Aliases: {@link size}.
|
||
* @return {Number}
|
||
* @see size
|
||
*/
|
||
get: function() {
|
||
return this.heapArray.length;
|
||
},
|
||
enumerable: !1,
|
||
configurable: !0
|
||
}), Object.defineProperty(Heap3.prototype, "limit", {
|
||
/**
|
||
* Get length limit of the heap.
|
||
* Use {@link setLimit} or {@link limit} to set the limit.
|
||
* @return {Number}
|
||
* @see setLimit
|
||
*/
|
||
get: function() {
|
||
return this._limit;
|
||
},
|
||
/**
|
||
* Set length limit of the heap. Same as using {@link setLimit}.
|
||
* @description If the heap is longer than the limit, the needed amount of leafs are removed.
|
||
* @param {Number} _l Limit, defaults to 0 (no limit). Negative, Infinity, or NaN values set the limit to 0.
|
||
* @see setLimit
|
||
*/
|
||
set: function(_l) {
|
||
_l < 0 || isNaN(_l) ? this._limit = 0 : this._limit = ~~_l, this._applyLimit();
|
||
},
|
||
enumerable: !1,
|
||
configurable: !0
|
||
}), Heap3.prototype.setLimit = function(_l) {
|
||
return this.limit = _l, _l < 0 || isNaN(_l) ? NaN : this._limit;
|
||
}, Heap3.prototype.peek = function() {
|
||
return this.heapArray[0];
|
||
}, Heap3.prototype.pop = function() {
|
||
var last = this.heapArray.pop();
|
||
return this.length > 0 && last !== void 0 ? this.replace(last) : last;
|
||
}, Heap3.prototype.push = function() {
|
||
for (var elements = [], _i = 0; _i < arguments.length; _i++)
|
||
elements[_i] = arguments[_i];
|
||
return elements.length < 1 ? !1 : elements.length === 1 ? this.add(elements[0]) : this.addAll(elements);
|
||
}, Heap3.prototype.pushpop = function(element) {
|
||
var _a;
|
||
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;
|
||
}, Heap3.prototype.remove = function(o, callbackFn) {
|
||
if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.length > 0) {
|
||
if (o === void 0)
|
||
return this.pop(), !0;
|
||
var idx = this.indexOf(o, callbackFn);
|
||
if (idx >= 0)
|
||
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;
|
||
}
|
||
return !1;
|
||
}, Heap3.prototype.replace = function(element) {
|
||
var peek = this.heapArray[0];
|
||
return this.heapArray[0] = element, this._sortNodeDown(0), peek;
|
||
}, Heap3.prototype.size = function() {
|
||
return this.length;
|
||
}, Heap3.prototype.top = function(n2) {
|
||
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);
|
||
}, Heap3.prototype.toArray = function() {
|
||
return __spreadArray([], __read(this.heapArray), !1);
|
||
}, Heap3.prototype.toString = function() {
|
||
return this.heapArray.toString();
|
||
}, Heap3.prototype.get = function(i) {
|
||
return this.heapArray[i];
|
||
}, Heap3.prototype.getChildrenOf = function(idx) {
|
||
var _this = this;
|
||
return Heap3.getChildrenIndexOf(idx).map(function(i) {
|
||
return _this.heapArray[i];
|
||
}).filter(function(e) {
|
||
return e !== void 0;
|
||
});
|
||
}, Heap3.prototype.getParentOf = function(idx) {
|
||
var pi = Heap3.getParentIndexOf(idx);
|
||
return this.heapArray[pi];
|
||
}, Heap3.prototype[Symbol.iterator] = function() {
|
||
return __generator(this, function(_a) {
|
||
switch (_a.label) {
|
||
case 0:
|
||
return this.length ? [4, this.pop()] : [3, 2];
|
||
case 1:
|
||
return _a.sent(), [3, 0];
|
||
case 2:
|
||
return [
|
||
2
|
||
/*return*/
|
||
];
|
||
}
|
||
});
|
||
}, Heap3.prototype.iterator = function() {
|
||
return this.toArray();
|
||
}, Heap3.prototype._applyLimit = function() {
|
||
if (this._limit > 0 && this._limit < this.heapArray.length)
|
||
for (var rm = this.heapArray.length - this._limit; rm; )
|
||
this.heapArray.pop(), --rm;
|
||
}, Heap3.prototype._bottomN_push = function(n2) {
|
||
var bottomHeap = new Heap3(this.compare);
|
||
bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), bottomHeap.init();
|
||
for (var startAt = this.heapArray.length - 1 - n2, parentStartAt = Heap3.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
|
||
indices.push(i);
|
||
for (var arr = this.heapArray; indices.length; ) {
|
||
var i = indices.shift();
|
||
this.compare(arr[i], bottomHeap.peek()) > 0 && (bottomHeap.replace(arr[i]), i % 2 && indices.push(Heap3.getParentIndexOf(i)));
|
||
}
|
||
return bottomHeap.toArray();
|
||
}, Heap3.prototype._moveNode = function(j, k) {
|
||
var _a;
|
||
_a = __read([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
|
||
}, Heap3.prototype._sortNodeDown = function(i) {
|
||
for (var _this = this, moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j) {
|
||
return _this.heapArray.length > j && _this.compare(_this.heapArray[j], _this.heapArray[best]) < 0 && (best = j), best;
|
||
}; moveIt; ) {
|
||
var childrenIdx = Heap3.getChildrenIndexOf(i), bestChildIndex = childrenIdx.reduce(getPotentialParent, childrenIdx[0]), bestChild = this.heapArray[bestChildIndex];
|
||
typeof bestChild < "u" && this.compare(self2, bestChild) > 0 ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1;
|
||
}
|
||
}, Heap3.prototype._sortNodeUp = function(i) {
|
||
for (var moveIt = i > 0; moveIt; ) {
|
||
var pi = Heap3.getParentIndexOf(i);
|
||
pi >= 0 && this.compare(this.heapArray[pi], this.heapArray[i]) > 0 ? (this._moveNode(i, pi), i = pi) : moveIt = !1;
|
||
}
|
||
}, Heap3.prototype._topN_push = function(n2) {
|
||
var topHeap = new Heap3(this._invertedCompare);
|
||
topHeap.limit = n2;
|
||
for (var indices = [0], arr = this.heapArray; indices.length; ) {
|
||
var i = indices.shift();
|
||
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))));
|
||
}
|
||
return topHeap.toArray();
|
||
}, Heap3.prototype._topN_fill = function(n2) {
|
||
var heapArray = this.heapArray, topHeap = new Heap3(this._invertedCompare);
|
||
topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), topHeap.init();
|
||
for (var branch = Heap3.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
|
||
indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i).filter(function(l) {
|
||
return l < heapArray.length;
|
||
})), !1));
|
||
for ((n2 - 1) % 2 && indices.push(n2); indices.length; ) {
|
||
var i = indices.shift();
|
||
i < heapArray.length && this.compare(heapArray[i], topHeap.peek()) < 0 && (topHeap.replace(heapArray[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1)));
|
||
}
|
||
return topHeap.toArray();
|
||
}, Heap3.prototype._topN_heap = function(n2) {
|
||
for (var topHeap = this.clone(), result = [], i = 0; i < n2; ++i)
|
||
result.push(topHeap.pop());
|
||
return result;
|
||
}, Heap3.prototype._topIdxOf = function(list) {
|
||
if (!list.length)
|
||
return -1;
|
||
for (var idx = 0, top = list[idx], i = 1; i < list.length; ++i) {
|
||
var comp = this.compare(list[i], top);
|
||
comp < 0 && (idx = i, top = list[i]);
|
||
}
|
||
return idx;
|
||
}, Heap3.prototype._topOf = function() {
|
||
for (var list = [], _i = 0; _i < arguments.length; _i++)
|
||
list[_i] = arguments[_i];
|
||
var heap = new Heap3(this.compare);
|
||
return heap.init(list), heap.peek();
|
||
}, Heap3;
|
||
}()
|
||
);
|
||
exports2.Heap = Heap2, exports2.HeapAsync = HeapAsync, exports2.default = Heap2, exports2.toInt = toInt, Object.defineProperty(exports2, "__esModule", { value: !0 });
|
||
});
|
||
}
|
||
});
|
||
|
||
// ../workflows-shared/src/binding.ts
|
||
import { RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
|
||
|
||
// ../workflows-shared/src/instance.ts
|
||
var INSTANCE_METADATA = "INSTANCE_METADATA";
|
||
function instanceStatusName(status) {
|
||
switch (status) {
|
||
case 0 /* Queued */:
|
||
return "queued";
|
||
case 1 /* Running */:
|
||
return "running";
|
||
case 2 /* Paused */:
|
||
return "paused";
|
||
case 3 /* Errored */:
|
||
return "errored";
|
||
case 4 /* Terminated */:
|
||
return "terminated";
|
||
case 5 /* Complete */:
|
||
return "complete";
|
||
default:
|
||
return "unknown";
|
||
}
|
||
}
|
||
|
||
// ../workflows-shared/src/binding.ts
|
||
var WorkflowBinding = class extends WorkerEntrypoint {
|
||
async create({
|
||
id = crypto.randomUUID(),
|
||
params = {}
|
||
} = {}) {
|
||
let stubId = this.env.ENGINE.idFromName(id), stub = this.env.ENGINE.get(stubId);
|
||
stub.init(
|
||
0,
|
||
// accountId: number,
|
||
{},
|
||
// workflow: DatabaseWorkflow,
|
||
{},
|
||
// version: DatabaseVersion,
|
||
{ id },
|
||
// instance: DatabaseInstance,
|
||
{
|
||
timestamp: /* @__PURE__ */ new Date(),
|
||
payload: params,
|
||
instanceId: id
|
||
}
|
||
);
|
||
let handle = new WorkflowHandle(id, stub);
|
||
return {
|
||
id,
|
||
pause: handle.pause.bind(handle),
|
||
resume: handle.resume.bind(handle),
|
||
terminate: handle.terminate.bind(handle),
|
||
restart: handle.restart.bind(handle),
|
||
status: handle.status.bind(handle)
|
||
};
|
||
}
|
||
async get(id) {
|
||
let engineStubId = this.env.ENGINE.idFromName(id), engineStub = this.env.ENGINE.get(engineStubId), handle = new WorkflowHandle(id, engineStub);
|
||
try {
|
||
await handle.status();
|
||
} catch {
|
||
throw new Error("instance.not_found");
|
||
}
|
||
return {
|
||
id,
|
||
pause: handle.pause.bind(handle),
|
||
resume: handle.resume.bind(handle),
|
||
terminate: handle.terminate.bind(handle),
|
||
restart: handle.restart.bind(handle),
|
||
status: handle.status.bind(handle)
|
||
};
|
||
}
|
||
async createBatch(_batch) {
|
||
throw new Error("createBatch is not yet implemented in local development.");
|
||
}
|
||
}, WorkflowHandle = class extends RpcTarget {
|
||
constructor(id, stub) {
|
||
super();
|
||
this.id = id;
|
||
this.stub = stub;
|
||
}
|
||
async pause() {
|
||
throw new Error("Not implemented yet");
|
||
}
|
||
async resume() {
|
||
throw new Error("Not implemented yet");
|
||
}
|
||
async terminate() {
|
||
throw new Error("Not implemented yet");
|
||
}
|
||
async restart() {
|
||
throw new Error("Not implemented yet");
|
||
}
|
||
async status() {
|
||
let status = await this.stub.getStatus(0, this.id), { logs } = await this.stub.readLogs(), workflowSuccessEvent = logs.filter((log) => log.event === 2 /* WORKFLOW_SUCCESS */).at(0), stepOutputs = logs.filter(
|
||
(log) => log.event === 6 /* STEP_SUCCESS */
|
||
).map((log) => log.metadata.result), workflowOutput = workflowSuccessEvent !== void 0 ? workflowSuccessEvent.metadata.result : null;
|
||
return {
|
||
status: instanceStatusName(status),
|
||
__LOCAL_DEV_STEP_OUTPUTS: stepOutputs,
|
||
// @ts-expect-error types are wrong, will remove this expect-error once I fix them
|
||
output: workflowOutput
|
||
};
|
||
}
|
||
};
|
||
|
||
// ../workflows-shared/src/engine.ts
|
||
import { DurableObject } from "cloudflare:workers";
|
||
|
||
// ../workflows-shared/src/context.ts
|
||
import { RpcTarget as RpcTarget2 } from "cloudflare:workers";
|
||
|
||
// ../../node_modules/.pnpm/itty-time@1.0.6/node_modules/itty-time/index.mjs
|
||
var n = { year: 315576e5, month: 2592e6, week: 6048e5, day: 864e5, hour: 36e5, minute: 6e4, second: 1e3, m: 1 }, r = (e) => {
|
||
if (+e)
|
||
return +e;
|
||
let [, t, r2] = e.match(/^([^ ]+) +(\w\w*?)s?$/) || [];
|
||
return +t * (n[r2] || 1);
|
||
};
|
||
|
||
// ../workflows-shared/src/lib/cache.ts
|
||
async function computeHash(value) {
|
||
let msgUint8 = new TextEncoder().encode(value), hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8);
|
||
return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
||
}
|
||
|
||
// ../workflows-shared/src/lib/errors.ts
|
||
var WorkflowTimeoutError = class extends Error {
|
||
name = "WorkflowTimeoutError";
|
||
}, WorkflowInternalError = class extends Error {
|
||
name = "WorkflowInternalError";
|
||
}, WorkflowFatalError = class extends Error {
|
||
name = "WorkflowFatalError";
|
||
toJSON() {
|
||
return {
|
||
name: this.name,
|
||
message: this.message
|
||
};
|
||
}
|
||
};
|
||
|
||
// ../workflows-shared/src/lib/retries.ts
|
||
function calcRetryDuration(config, stepState) {
|
||
let { attemptedCount: attemptCount } = stepState, { retries } = config, delay = r(retries.delay);
|
||
switch (retries.backoff) {
|
||
case "exponential":
|
||
return delay * Math.pow(2, attemptCount - 1);
|
||
case "linear":
|
||
return delay * attemptCount;
|
||
case "constant":
|
||
default:
|
||
return delay;
|
||
}
|
||
}
|
||
|
||
// ../workflows-shared/src/lib/validators.ts
|
||
var CONTROL_CHAR_REGEX = new RegExp("[\0-]");
|
||
function validateStepName(string) {
|
||
return string.length > 256 ? !1 : !CONTROL_CHAR_REGEX.test(string);
|
||
}
|
||
|
||
// ../workflows-shared/src/context.ts
|
||
var defaultConfig = {
|
||
retries: {
|
||
limit: 5,
|
||
delay: 1e3,
|
||
backoff: "constant"
|
||
},
|
||
timeout: "15 minutes"
|
||
}, Context = class extends RpcTarget2 {
|
||
#engine;
|
||
#state;
|
||
#counters = /* @__PURE__ */ new Map();
|
||
constructor(engine, state) {
|
||
super(), this.#engine = engine, this.#state = state;
|
||
}
|
||
#getCount(name) {
|
||
let val = this.#counters.get(name) ?? 0;
|
||
return val++, this.#counters.set(name, val), val;
|
||
}
|
||
async do(name, configOrCallback, callback) {
|
||
let closure, stepConfig;
|
||
if (callback ? (closure = callback, stepConfig = configOrCallback) : (closure = configOrCallback, stepConfig = {}), !validateStepName(name)) {
|
||
let error = new WorkflowFatalError(
|
||
`Step name "${name}" exceeds max length (${256} chars) or invalid characters found`
|
||
);
|
||
throw error.isUserError = !0, error;
|
||
}
|
||
let config = {
|
||
...defaultConfig,
|
||
...stepConfig,
|
||
retries: {
|
||
...defaultConfig.retries,
|
||
...stepConfig.retries
|
||
}
|
||
}, 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([valueKey, configKey]), maybeResult = maybeMap.get(valueKey);
|
||
if (maybeResult)
|
||
return maybeResult.value;
|
||
let maybeError = maybeMap.get(
|
||
errorKey
|
||
);
|
||
if (maybeError)
|
||
throw maybeError.isUserError = !0, maybeError;
|
||
maybeMap.has(configKey) ? config = maybeMap.get(configKey) : await this.#state.storage.put(configKey, config);
|
||
let attemptLogs = this.#engine.readLogsFromStep(cacheKey).filter(
|
||
(val) => [
|
||
11 /* ATTEMPT_SUCCESS */,
|
||
12 /* ATTEMPT_FAILURE */,
|
||
10 /* ATTEMPT_START */
|
||
].includes(val.event)
|
||
);
|
||
if (attemptLogs.length > 0 && attemptLogs.at(-1)?.event === 10 /* ATTEMPT_START */) {
|
||
let stepState = await this.#state.storage.get(
|
||
stepStateKey
|
||
) ?? {
|
||
attemptedCount: 1
|
||
}, priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, timeoutEntryPQ = this.#engine.priorityQueue.getFirst(
|
||
(a) => a.hash === priorityQueueHash && a.type === "timeout"
|
||
);
|
||
timeoutEntryPQ !== void 0 && this.#engine.priorityQueue.remove(timeoutEntryPQ), this.#engine.writeLog(
|
||
12 /* ATTEMPT_FAILURE */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
attempt: stepState.attemptedCount,
|
||
error: {
|
||
name: "WorkflowInternalError",
|
||
message: "Attempt failed due to internal workflows error"
|
||
}
|
||
}
|
||
), await this.#state.storage.put(stepStateKey, stepState);
|
||
}
|
||
let doWrapper = async (doWrapperClosure) => {
|
||
let stepState = await this.#state.storage.get(
|
||
stepStateKey
|
||
) ?? {
|
||
attemptedCount: 0
|
||
};
|
||
if (await this.#engine.timeoutHandler.acquire(this.#engine), stepState.attemptedCount == 0)
|
||
this.#engine.writeLog(
|
||
5 /* STEP_START */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
config
|
||
}
|
||
);
|
||
else {
|
||
let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, retryEntryPQ = this.#engine.priorityQueue.getFirst(
|
||
(a) => a.hash === priorityQueueHash && a.type === "retry"
|
||
);
|
||
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({
|
||
hash: priorityQueueHash,
|
||
type: "retry"
|
||
}));
|
||
}
|
||
let result, instanceMetadata = await this.#state.storage.get(INSTANCE_METADATA);
|
||
if (!instanceMetadata)
|
||
throw new Error("instanceMetadata is undefined");
|
||
let { accountId, instance } = instanceMetadata;
|
||
try {
|
||
let timeoutPromise = async () => {
|
||
let priorityQueueHash2 = `${cacheKey}-${stepState.attemptedCount}`, timeout = r(config.timeout);
|
||
throw await this.#engine.priorityQueue.add({
|
||
hash: priorityQueueHash2,
|
||
targetTimestamp: Date.now() + timeout,
|
||
type: "timeout"
|
||
}), await scheduler.wait(timeout), await this.#engine.priorityQueue.remove({
|
||
hash: priorityQueueHash2,
|
||
type: "timeout"
|
||
}), new WorkflowTimeoutError(
|
||
`Execution timed out after ${timeout}ms`
|
||
);
|
||
};
|
||
this.#engine.writeLog(
|
||
10 /* ATTEMPT_START */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
attempt: stepState.attemptedCount + 1
|
||
}
|
||
), stepState.attemptedCount++, await this.#state.storage.put(stepStateKey, stepState);
|
||
let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`;
|
||
result = await Promise.race([doWrapperClosure(), timeoutPromise()]), await this.#engine.priorityQueue.remove({
|
||
hash: priorityQueueHash,
|
||
type: "timeout"
|
||
});
|
||
try {
|
||
await this.#state.storage.put(valueKey, { value: result });
|
||
} catch (e) {
|
||
if (e instanceof Error && e.name === "DataCloneError")
|
||
this.#engine.writeLog(
|
||
12 /* ATTEMPT_FAILURE */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
attempt: stepState.attemptedCount,
|
||
error: new WorkflowFatalError(
|
||
`Value returned from step "${name}" is not serialisable`
|
||
)
|
||
}
|
||
), this.#engine.writeLog(
|
||
7 /* STEP_FAILURE */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{}
|
||
), this.#engine.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
|
||
error: new WorkflowFatalError(
|
||
`The execution of the Workflow instance was terminated, as the step "${name}" returned a value which is not serialisable`
|
||
)
|
||
}), await this.#engine.setStatus(
|
||
accountId,
|
||
instance.id,
|
||
3 /* Errored */
|
||
), await this.#engine.timeoutHandler.release(this.#engine), await this.#engine.abort("Value is not serialisable");
|
||
else
|
||
throw new WorkflowInternalError(
|
||
`Storage failure for ${valueKey}: ${e} `
|
||
);
|
||
return;
|
||
}
|
||
this.#engine.writeLog(
|
||
11 /* ATTEMPT_SUCCESS */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
attempt: stepState.attemptedCount
|
||
}
|
||
);
|
||
} catch (e) {
|
||
let error = e;
|
||
if (this.#engine.priorityQueue.remove({
|
||
hash: `${cacheKey}-${stepState.attemptedCount}`,
|
||
type: "timeout"
|
||
}), e instanceof Error && (error.name === "NonRetryableError" || error.message.startsWith("NonRetryableError")))
|
||
throw this.#engine.writeLog(
|
||
12 /* ATTEMPT_FAILURE */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
attempt: stepState.attemptedCount,
|
||
error: new WorkflowFatalError(
|
||
`Step threw a NonRetryableError with message "${e.message}"`
|
||
)
|
||
}
|
||
), this.#engine.writeLog(
|
||
7 /* STEP_FAILURE */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{}
|
||
), error;
|
||
if (this.#engine.writeLog(
|
||
12 /* ATTEMPT_FAILURE */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
attempt: stepState.attemptedCount,
|
||
error: {
|
||
name: error.name,
|
||
message: error.message
|
||
// TODO (WOR-79): Stacks are all incorrect over RPC and need work
|
||
// stack: error.stack,
|
||
}
|
||
}
|
||
), await this.#state.storage.put(stepStateKey, stepState), stepState.attemptedCount <= config.retries.limit) {
|
||
let durationMs = calcRetryDuration(config, stepState), priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`;
|
||
return await this.#engine.priorityQueue.add({
|
||
hash: priorityQueueHash,
|
||
targetTimestamp: Date.now() + durationMs,
|
||
type: "retry"
|
||
}), await this.#engine.timeoutHandler.release(this.#engine), await scheduler.wait(durationMs), this.#engine.priorityQueue.remove({
|
||
hash: priorityQueueHash,
|
||
type: "retry"
|
||
}), doWrapper(doWrapperClosure);
|
||
} else
|
||
throw await this.#engine.timeoutHandler.release(this.#engine), this.#engine.writeLog(
|
||
7 /* STEP_FAILURE */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{}
|
||
), await this.#state.storage.put(errorKey, error), error;
|
||
}
|
||
return this.#engine.writeLog(
|
||
6 /* STEP_SUCCESS */,
|
||
cacheKey,
|
||
stepNameWithCounter,
|
||
{
|
||
// TODO (WOR-86): Add limits, figure out serialization
|
||
result
|
||
}
|
||
), await this.#engine.timeoutHandler.release(this.#engine), result;
|
||
};
|
||
return doWrapper(closure);
|
||
}
|
||
async sleep(name, duration) {
|
||
typeof duration == "string" && (duration = r(duration));
|
||
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`;
|
||
if (await this.#state.storage.get(sleepKey) != null) {
|
||
let entryPQ = this.#engine.priorityQueue.getFirst(
|
||
(a) => a.hash === cacheKey && a.type === "sleep"
|
||
);
|
||
entryPQ !== void 0 && (await scheduler.wait(entryPQ.targetTimestamp - Date.now()), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" })), await this.#state.storage.get(sleepLogWrittenKey) == null && (this.#engine.writeLog(
|
||
9 /* SLEEP_COMPLETE */,
|
||
cacheKey,
|
||
sleepNameWithCounter,
|
||
{}
|
||
), await this.#state.storage.put(sleepLogWrittenKey, !0));
|
||
return;
|
||
}
|
||
if (this.#engine.writeLog(
|
||
8 /* SLEEP_START */,
|
||
cacheKey,
|
||
sleepNameWithCounter,
|
||
{
|
||
durationMs: duration
|
||
}
|
||
), !await this.#state.storage.get(INSTANCE_METADATA))
|
||
throw new Error("instanceMetadata is undefined");
|
||
await this.#state.storage.put(sleepKey, !0), await this.#engine.priorityQueue.add({
|
||
hash: cacheKey,
|
||
targetTimestamp: Date.now() + duration,
|
||
type: "sleep"
|
||
}), await scheduler.wait(duration), this.#engine.writeLog(
|
||
9 /* SLEEP_COMPLETE */,
|
||
cacheKey,
|
||
sleepNameWithCounter,
|
||
{}
|
||
), await this.#state.storage.put(sleepLogWrittenKey, !0), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" });
|
||
}
|
||
async sleepUntil(name, timestamp) {
|
||
timestamp instanceof Date && (timestamp = timestamp.valueOf());
|
||
let now = Date.now();
|
||
if (timestamp < now)
|
||
throw new Error(
|
||
"You can't sleep until a time in the past, time-traveler"
|
||
);
|
||
return this.sleep(name, timestamp - now);
|
||
}
|
||
};
|
||
|
||
// ../workflows-shared/src/lib/gracePeriodSemaphore.ts
|
||
var ENGINE_TIMEOUT = r("5 minutes"), latestGracePeriodTimestamp, GracePeriodSemaphore = class {
|
||
#counter = 0;
|
||
callback;
|
||
timeoutMs;
|
||
constructor(callback, timeoutMs) {
|
||
this.callback = callback, this.timeoutMs = timeoutMs;
|
||
}
|
||
// acquire takes engine to be the same as release
|
||
async acquire(_engine) {
|
||
this.#counter == 0 && (latestGracePeriodTimestamp = void 0), this.#counter += 1;
|
||
}
|
||
async release(engine) {
|
||
this.#counter = Math.max(this.#counter - 1, 0), this.#counter == 0 && this.callback(engine, this.timeoutMs);
|
||
}
|
||
isRunningStep() {
|
||
return this.#counter > 0;
|
||
}
|
||
}, startGracePeriod = async (engine, timeoutMs) => {
|
||
(async () => {
|
||
let thisTimestamp = (/* @__PURE__ */ new Date()).valueOf();
|
||
if (!(latestGracePeriodTimestamp === void 0 || latestGracePeriodTimestamp < thisTimestamp))
|
||
throw new Error(
|
||
"Can't start grace period since there is already an active one started on " + latestGracePeriodTimestamp
|
||
);
|
||
latestGracePeriodTimestamp = thisTimestamp, await scheduler.wait(timeoutMs), !(thisTimestamp !== latestGracePeriodTimestamp || engine.timeoutHandler.isRunningStep()) && (await engine.priorityQueue?.handleNextAlarm(), await engine.abort("Grace period complete"));
|
||
})();
|
||
};
|
||
|
||
// ../workflows-shared/src/lib/timePriorityQueue.ts
|
||
var import_heap_js = __toESM(require_heap_js_umd()), wakerPriorityEntryComparator = (a, b) => a.targetTimestamp - b.targetTimestamp;
|
||
var TimePriorityQueue = class {
|
||
#heap = new import_heap_js.default(wakerPriorityEntryComparator);
|
||
// #env: Env;
|
||
#ctx;
|
||
#instanceMetadata;
|
||
constructor(ctx, instanceMetadata) {
|
||
this.#ctx = ctx, this.#instanceMetadata = instanceMetadata, this.#heap.init(this.getEntries());
|
||
}
|
||
popPastEntries() {
|
||
if (this.#heap.length === 0)
|
||
return;
|
||
let res = [], currentTimestamp = (/* @__PURE__ */ new Date()).valueOf();
|
||
for (; ; ) {
|
||
let element = this.#heap.peek();
|
||
if (element === void 0 || element.targetTimestamp > currentTimestamp)
|
||
break;
|
||
res.push(element), this.#heap.pop();
|
||
}
|
||
return this.#ctx.storage.transactionSync(() => {
|
||
for (let entry of res)
|
||
this.removeEntryDB(entry);
|
||
}), res;
|
||
}
|
||
/**
|
||
* `add` is ran using a transaction so it's race condition free, if it's ran atomically
|
||
* @param entry
|
||
*/
|
||
async add(entry) {
|
||
await this.#ctx.storage.transaction(async () => {
|
||
this.#heap.add(entry), this.addEntryDB(entry);
|
||
});
|
||
}
|
||
/**
|
||
* `remove` is ran using a transaction so it's race condition free, if it's ran atomically
|
||
* @param entry
|
||
*/
|
||
remove(entry) {
|
||
this.#ctx.storage.transactionSync(() => {
|
||
this.removeFirst((e) => e.hash === entry.hash && e.type === entry.type);
|
||
});
|
||
}
|
||
popTypeAll(entryType) {
|
||
this.#ctx.storage.transactionSync(() => {
|
||
this.filter((e) => e.type !== entryType);
|
||
});
|
||
}
|
||
// Idempotent, perhaps name should suggest so
|
||
async handleNextAlarm() {
|
||
this.#heap.peek();
|
||
}
|
||
getFirst(callbackFn) {
|
||
return structuredClone(this.#heap.toArray().find(callbackFn));
|
||
}
|
||
removeFirst(callbackFn) {
|
||
let elements = this.#heap.toArray(), index = elements.findIndex(callbackFn);
|
||
if (index === -1)
|
||
return;
|
||
let removedEntry = elements.splice(index, 1)[0];
|
||
this.removeEntryDB(removedEntry), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(elements);
|
||
}
|
||
filter(callbackFn) {
|
||
let filteredElements = this.#heap.toArray().filter(callbackFn), removedElements = this.#heap.toArray().filter((a) => !callbackFn(a));
|
||
this.#ctx.storage.transactionSync(() => {
|
||
for (let entry of removedElements)
|
||
this.removeEntryDB(entry);
|
||
}), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(filteredElements);
|
||
}
|
||
length() {
|
||
return this.#heap.length;
|
||
}
|
||
getEntries() {
|
||
let entries = [
|
||
...this.#ctx.storage.sql.exec("SELECT * FROM priority_queue ORDER BY id")
|
||
], activeEntries = [];
|
||
return entries.forEach((val) => {
|
||
let entryType = toWakerPriorityType(val.entryType);
|
||
if (val.action == 0) {
|
||
let index = activeEntries.findIndex(
|
||
(activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
|
||
);
|
||
index !== -1 && activeEntries.splice(index, 1);
|
||
} else
|
||
activeEntries.findIndex(
|
||
(activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
|
||
) === -1 && activeEntries.push({
|
||
hash: val.hash,
|
||
targetTimestamp: val.target_timestamp,
|
||
type: entryType
|
||
});
|
||
}), activeEntries;
|
||
}
|
||
removeEntryDB(entry) {
|
||
this.#ctx.storage.sql.exec(
|
||
`
|
||
INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
|
||
VALUES (?, ?, ? ,?)
|
||
`,
|
||
entry.targetTimestamp,
|
||
0 /* FALSE */,
|
||
fromWakerPriorityType(entry.type),
|
||
entry.hash
|
||
);
|
||
}
|
||
addEntryDB(entry) {
|
||
this.#ctx.storage.sql.exec(
|
||
`
|
||
INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
|
||
VALUES (?, ?, ? ,?)
|
||
`,
|
||
entry.targetTimestamp,
|
||
1 /* TRUE */,
|
||
fromWakerPriorityType(entry.type),
|
||
entry.hash
|
||
);
|
||
}
|
||
}, toWakerPriorityType = (entryType) => {
|
||
switch (entryType) {
|
||
case 0 /* RETRY */:
|
||
return "retry";
|
||
case 1 /* SLEEP */:
|
||
return "sleep";
|
||
case 2 /* TIMEOUT */:
|
||
return "timeout";
|
||
}
|
||
}, fromWakerPriorityType = (entryType) => {
|
||
switch (entryType) {
|
||
case "retry":
|
||
return 0 /* RETRY */;
|
||
case "sleep":
|
||
return 1 /* SLEEP */;
|
||
case "timeout":
|
||
return 2 /* TIMEOUT */;
|
||
default:
|
||
throw new Error(`WakerPriorityType "${entryType}" has not been handled`);
|
||
}
|
||
};
|
||
|
||
// ../workflows-shared/src/engine.ts
|
||
var ENGINE_STATUS_KEY = "ENGINE_STATUS", Engine = class extends DurableObject {
|
||
logs = [];
|
||
isRunning = !1;
|
||
accountId;
|
||
instanceId;
|
||
workflowName;
|
||
timeoutHandler;
|
||
priorityQueue;
|
||
constructor(state, env) {
|
||
super(state, env), this.ctx.blockConcurrencyWhile(async () => {
|
||
this.ctx.storage.transactionSync(() => {
|
||
try {
|
||
this.ctx.storage.sql.exec(`
|
||
CREATE TABLE IF NOT EXISTS priority_queue (
|
||
id INTEGER PRIMARY KEY NOT NULL,
|
||
created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
target_timestamp INTEGER NOT NULL,
|
||
action INTEGER NOT NULL, -- should only be 0 or 1 (1 for added, 0 for deleted),
|
||
entryType INTEGER NOT NULL,
|
||
hash TEXT NOT NULL,
|
||
CHECK (action IN (0, 1)), -- guararentee that action can only be 0 or 1
|
||
UNIQUE (action, entryType, hash)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS states (
|
||
id INTEGER PRIMARY KEY NOT NULL,
|
||
groupKey TEXT,
|
||
target TEXT,
|
||
metadata TEXT,
|
||
event INTEGER NOT NULL
|
||
)
|
||
`);
|
||
} catch (e) {
|
||
throw console.error(e), e;
|
||
}
|
||
});
|
||
}), this.timeoutHandler = new GracePeriodSemaphore(
|
||
startGracePeriod,
|
||
ENGINE_TIMEOUT
|
||
);
|
||
}
|
||
writeLog(event, group, target = null, metadata) {
|
||
this.ctx.storage.sql.exec(
|
||
"INSERT INTO states (event, groupKey, target, metadata) VALUES (?, ?, ?, ?)",
|
||
event,
|
||
group,
|
||
target,
|
||
JSON.stringify(metadata)
|
||
);
|
||
}
|
||
readLogsFromStep(_cacheKey) {
|
||
return [];
|
||
}
|
||
readLogs() {
|
||
return {
|
||
logs: [
|
||
...this.ctx.storage.sql.exec("SELECT event, groupKey, target, metadata FROM states")
|
||
].map((log) => ({
|
||
...log,
|
||
metadata: JSON.parse(log.metadata),
|
||
group: log.groupKey
|
||
}))
|
||
};
|
||
}
|
||
async getStatus(_accountId, _instanceId) {
|
||
if (this.accountId === void 0)
|
||
throw new Error("stub not initialized");
|
||
let res = await this.ctx.storage.get(ENGINE_STATUS_KEY);
|
||
return res === void 0 ? 0 /* Queued */ : res;
|
||
}
|
||
async setStatus(accountId, instanceId, status) {
|
||
await this.ctx.storage.put(ENGINE_STATUS_KEY, status);
|
||
}
|
||
async abort(_reason) {
|
||
}
|
||
async userTriggeredTerminate() {
|
||
}
|
||
async init(accountId, workflow, version, instance, event) {
|
||
if (this.priorityQueue === void 0 && (this.priorityQueue = new TimePriorityQueue(
|
||
this.ctx,
|
||
// this.env,
|
||
{
|
||
accountId,
|
||
workflow,
|
||
version,
|
||
instance,
|
||
event
|
||
}
|
||
)), this.priorityQueue.popPastEntries(), await this.priorityQueue.handleNextAlarm(), this.isRunning)
|
||
return;
|
||
this.accountId = accountId, this.instanceId = instance.id, this.workflowName = workflow.name;
|
||
let status = await this.getStatus(accountId, instance.id);
|
||
if ([
|
||
3 /* Errored */,
|
||
// TODO (WOR-85): Remove this once upgrade story is done
|
||
4 /* Terminated */,
|
||
5 /* Complete */
|
||
].includes(status))
|
||
return;
|
||
if (await this.ctx.storage.get(INSTANCE_METADATA) == null) {
|
||
let instanceMetadata = {
|
||
accountId,
|
||
workflow,
|
||
version,
|
||
instance,
|
||
event
|
||
};
|
||
await this.ctx.storage.put(INSTANCE_METADATA, instanceMetadata), this.writeLog(0 /* WORKFLOW_QUEUED */, null, null, {
|
||
params: event.payload,
|
||
versionId: version.id,
|
||
trigger: {
|
||
source: 0 /* API */
|
||
}
|
||
}), this.writeLog(1 /* WORKFLOW_START */, null, null, {});
|
||
}
|
||
let stubStep = new Context(this, this.ctx), workflowRunningHandler = async () => {
|
||
await this.ctx.storage.transaction(async () => {
|
||
await this.setStatus(accountId, instance.id, 1 /* Running */);
|
||
});
|
||
};
|
||
this.isRunning = !0, workflowRunningHandler();
|
||
try {
|
||
let result = await this.env.USER_WORKFLOW.run(event, stubStep);
|
||
this.writeLog(2 /* WORKFLOW_SUCCESS */, null, null, {
|
||
result
|
||
}), await this.ctx.storage.transaction(async () => {
|
||
await this.setStatus(accountId, instance.id, 5 /* Complete */);
|
||
}), this.isRunning = !1;
|
||
} catch (err) {
|
||
let error;
|
||
if (err instanceof Error) {
|
||
if (err.name === "NonRetryableError" || err.message.startsWith("NonRetryableError")) {
|
||
this.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
|
||
error: new WorkflowFatalError(
|
||
"The execution of the Workflow instance was terminated, as a step threw an NonRetryableError and it was not handled"
|
||
)
|
||
}), await this.setStatus(accountId, instance.id, 3 /* Errored */), await this.abort("A step threw a NonRetryableError"), this.isRunning = !1;
|
||
return;
|
||
}
|
||
error = {
|
||
message: err.message,
|
||
name: err.name
|
||
};
|
||
} else
|
||
error = {
|
||
name: "Error",
|
||
message: err
|
||
};
|
||
this.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
|
||
error
|
||
}), await this.ctx.storage.transaction(async () => {
|
||
await this.setStatus(accountId, instance.id, 3 /* Errored */);
|
||
}), this.isRunning = !1;
|
||
}
|
||
return {
|
||
id: instance.id
|
||
};
|
||
}
|
||
};
|
||
export {
|
||
Engine,
|
||
WorkflowBinding
|
||
};
|
||
//# sourceMappingURL=binding.worker.js.map
|