@byterygon/workerr
Version:
Workerr is a lightweight library that simplifies working with Web Workers in JavaScript. It provides a more intuitive way to handle parallel tasks by using Promises, along with a built-in worker pool to efficiently manage worker instances. With strong Typ
935 lines (928 loc) • 31.8 kB
JavaScript
var Ce = Object.defineProperty;
var re = (r) => {
throw TypeError(r);
};
var Oe = (r, t, e) => t in r ? Ce(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
var _ = (r, t, e) => Oe(r, typeof t != "symbol" ? t + "" : t, e), G = (r, t, e) => t.has(r) || re("Cannot " + e);
var u = (r, t, e) => (G(r, t, "read from private field"), e ? e.call(r) : t.get(r)), L = (r, t, e) => t.has(r) ? re("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(r) : t.set(r, e), w = (r, t, e, n) => (G(r, t, "write to private field"), n ? n.call(r, e) : t.set(r, e), e), E = (r, t, e) => (G(r, t, "access private method"), e);
var W = (r, t, e, n) => ({
set _(s) {
w(r, t, s, e);
},
get _() {
return u(r, t, n);
}
});
class Ke {
constructor() {
}
buildInvokeHandlers(t) {
return t;
}
}
function ue(r) {
return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
}
var te = { exports: {} }, N = typeof Reflect == "object" ? Reflect : null, ne = N && typeof N.apply == "function" ? N.apply : function(t, e, n) {
return Function.prototype.apply.call(t, e, n);
}, K;
N && typeof N.ownKeys == "function" ? K = N.ownKeys : Object.getOwnPropertySymbols ? K = function(t) {
return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t));
} : K = function(t) {
return Object.getOwnPropertyNames(t);
};
function ke(r) {
console && console.warn && console.warn(r);
}
var ce = Number.isNaN || function(t) {
return t !== t;
};
function p() {
p.init.call(this);
}
te.exports = p;
te.exports.once = Se;
p.EventEmitter = p;
p.prototype._events = void 0;
p.prototype._eventsCount = 0;
p.prototype._maxListeners = void 0;
var se = 10;
function J(r) {
if (typeof r != "function")
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof r);
}
Object.defineProperty(p, "defaultMaxListeners", {
enumerable: !0,
get: function() {
return se;
},
set: function(r) {
if (typeof r != "number" || r < 0 || ce(r))
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + r + ".");
se = r;
}
});
p.init = function() {
(this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) && (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
};
p.prototype.setMaxListeners = function(t) {
if (typeof t != "number" || t < 0 || ce(t))
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + t + ".");
return this._maxListeners = t, this;
};
function le(r) {
return r._maxListeners === void 0 ? p.defaultMaxListeners : r._maxListeners;
}
p.prototype.getMaxListeners = function() {
return le(this);
};
p.prototype.emit = function(t) {
for (var e = [], n = 1; n < arguments.length; n++) e.push(arguments[n]);
var s = t === "error", o = this._events;
if (o !== void 0)
s = s && o.error === void 0;
else if (!s)
return !1;
if (s) {
var i;
if (e.length > 0 && (i = e[0]), i instanceof Error)
throw i;
var a = new Error("Unhandled error." + (i ? " (" + i.message + ")" : ""));
throw a.context = i, a;
}
var h = o[t];
if (h === void 0)
return !1;
if (typeof h == "function")
ne(h, this, e);
else
for (var c = h.length, l = ve(h, c), n = 0; n < c; ++n)
ne(l[n], this, e);
return !0;
};
function fe(r, t, e, n) {
var s, o, i;
if (J(e), o = r._events, o === void 0 ? (o = r._events = /* @__PURE__ */ Object.create(null), r._eventsCount = 0) : (o.newListener !== void 0 && (r.emit(
"newListener",
t,
e.listener ? e.listener : e
), o = r._events), i = o[t]), i === void 0)
i = o[t] = e, ++r._eventsCount;
else if (typeof i == "function" ? i = o[t] = n ? [e, i] : [i, e] : n ? i.unshift(e) : i.push(e), s = le(r), s > 0 && i.length > s && !i.warned) {
i.warned = !0;
var a = new Error("Possible EventEmitter memory leak detected. " + i.length + " " + String(t) + " listeners added. Use emitter.setMaxListeners() to increase limit");
a.name = "MaxListenersExceededWarning", a.emitter = r, a.type = t, a.count = i.length, ke(a);
}
return r;
}
p.prototype.addListener = function(t, e) {
return fe(this, t, e, !1);
};
p.prototype.on = p.prototype.addListener;
p.prototype.prependListener = function(t, e) {
return fe(this, t, e, !0);
};
function Ae() {
if (!this.fired)
return this.target.removeListener(this.type, this.wrapFn), this.fired = !0, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
}
function he(r, t, e) {
var n = { fired: !1, wrapFn: void 0, target: r, type: t, listener: e }, s = Ae.bind(n);
return s.listener = e, n.wrapFn = s, s;
}
p.prototype.once = function(t, e) {
return J(e), this.on(t, he(this, t, e)), this;
};
p.prototype.prependOnceListener = function(t, e) {
return J(e), this.prependListener(t, he(this, t, e)), this;
};
p.prototype.removeListener = function(t, e) {
var n, s, o, i, a;
if (J(e), s = this._events, s === void 0)
return this;
if (n = s[t], n === void 0)
return this;
if (n === e || n.listener === e)
--this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : (delete s[t], s.removeListener && this.emit("removeListener", t, n.listener || e));
else if (typeof n != "function") {
for (o = -1, i = n.length - 1; i >= 0; i--)
if (n[i] === e || n[i].listener === e) {
a = n[i].listener, o = i;
break;
}
if (o < 0)
return this;
o === 0 ? n.shift() : Me(n, o), n.length === 1 && (s[t] = n[0]), s.removeListener !== void 0 && this.emit("removeListener", t, a || e);
}
return this;
};
p.prototype.off = p.prototype.removeListener;
p.prototype.removeAllListeners = function(t) {
var e, n, s;
if (n = this._events, n === void 0)
return this;
if (n.removeListener === void 0)
return arguments.length === 0 ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : n[t] !== void 0 && (--this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : delete n[t]), this;
if (arguments.length === 0) {
var o = Object.keys(n), i;
for (s = 0; s < o.length; ++s)
i = o[s], i !== "removeListener" && this.removeAllListeners(i);
return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
}
if (e = n[t], typeof e == "function")
this.removeListener(t, e);
else if (e !== void 0)
for (s = e.length - 1; s >= 0; s--)
this.removeListener(t, e[s]);
return this;
};
function de(r, t, e) {
var n = r._events;
if (n === void 0)
return [];
var s = n[t];
return s === void 0 ? [] : typeof s == "function" ? e ? [s.listener || s] : [s] : e ? Ne(s) : ve(s, s.length);
}
p.prototype.listeners = function(t) {
return de(this, t, !0);
};
p.prototype.rawListeners = function(t) {
return de(this, t, !1);
};
p.listenerCount = function(r, t) {
return typeof r.listenerCount == "function" ? r.listenerCount(t) : me.call(r, t);
};
p.prototype.listenerCount = me;
function me(r) {
var t = this._events;
if (t !== void 0) {
var e = t[r];
if (typeof e == "function")
return 1;
if (e !== void 0)
return e.length;
}
return 0;
}
p.prototype.eventNames = function() {
return this._eventsCount > 0 ? K(this._events) : [];
};
function ve(r, t) {
for (var e = new Array(t), n = 0; n < t; ++n)
e[n] = r[n];
return e;
}
function Me(r, t) {
for (; t + 1 < r.length; t++)
r[t] = r[t + 1];
r.pop();
}
function Ne(r) {
for (var t = new Array(r.length), e = 0; e < t.length; ++e)
t[e] = r[e].listener || r[e];
return t;
}
function Se(r, t) {
return new Promise(function(e, n) {
function s(i) {
r.removeListener(t, o), n(i);
}
function o() {
typeof r.removeListener == "function" && r.removeListener("error", s), e([].slice.call(arguments));
}
pe(r, t, o, { once: !0 }), t !== "error" && ze(r, s, { once: !0 });
});
}
function ze(r, t, e) {
typeof r.on == "function" && pe(r, "error", t, e);
}
function pe(r, t, e, n) {
if (typeof r.on == "function")
n.once ? r.once(t, e) : r.on(t, e);
else if (typeof r.addEventListener == "function")
r.addEventListener(t, function s(o) {
n.once && r.removeEventListener(t, s), e(o);
});
else
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof r);
}
var Re = te.exports;
const ye = /* @__PURE__ */ ue(Re);
function X() {
const r = URL.createObjectURL(new Blob()), t = r.toString();
return URL.revokeObjectURL(r), t.substr(t.lastIndexOf("/") + 1);
}
function ie(r) {
if (r instanceof Error)
return r;
if (typeof r == "string")
return new Error(r);
if (typeof r == "object" && r !== null)
try {
const t = JSON.stringify(r, je());
return new Error(t);
} catch {
return new Error("An error occurred, but it could not be stringified.");
}
else
return new Error(String(r));
}
function je() {
const r = /* @__PURE__ */ new WeakSet();
return (t, e) => {
if (typeof e == "object" && e !== null) {
if (r.has(e))
return "[Circular]";
r.add(e);
}
return e;
};
}
class $ {
constructor({
invokeHandler: t
}) {
_(this, "context");
_(this, "invokeHandler");
_(this, "emitter", new ye());
this.invokeHandler = t, this.context = {};
const e = async (n) => {
var s;
switch (n.data.messageType) {
case "context:update":
this.context = n.data.messagePayload, $.postMessage({
messageType: "context:ack",
messagePayload: {
messageId: n.data.messageId
}
}), this.emitter.emit("context:update", this.context);
break;
case "excecute:start": {
const o = n.data;
try {
if (o.messagePayload.cmd in this.invokeHandler) {
let i;
if (o.messagePayload.abortSignalChannelPort) {
const c = new AbortController();
i = c.signal, o.messagePayload.abortSignalChannelPort.onmessage = (l) => {
var f;
c.abort(l.data), (f = o.messagePayload.abortSignalChannelPort) == null || f.close();
};
}
let a = [];
const h = await this.invokeHandler[o.messagePayload.cmd](o.messagePayload.params, {
context: this.context,
abortSignal: i,
transferObject(c) {
a.push(...c);
}
});
(s = o.messagePayload.abortSignalChannelPort) == null || s.close(), $.postMessage({ messageType: "excecute:response", messagePayload: { messageId: o.messageId, result: h } }, a);
} else
throw new Error("Command is not supported");
} catch (i) {
const a = ie(i);
$.postMessage({
messageType: "excecute:error",
messagePayload: {
messageId: n.data.messageId,
error: a
}
});
}
}
}
};
self.addEventListener("message", e);
}
static async create(t) {
this.postMessage({ messageType: "initialization:start", messagePayload: void 0 });
try {
const { invokeHandler: e } = await t();
return await new Promise((n, s) => {
const o = (a) => {
a.data.messageType === "initialization:ack" && (n(void 0), self.removeEventListener("messageerror", i), self.removeEventListener("message", o));
}, i = (a) => {
self.removeEventListener("messageerror", i), self.removeEventListener("message", o), console.error("Unable to deserialized message:", a.data), s(new Error("Unable to deserialized message"));
};
self.addEventListener("message", o), self.addEventListener("messageerror", i), this.postMessage({ messageType: "initialization:complete", messagePayload: void 0 });
}), new $({
invokeHandler: e
});
} catch (e) {
this.postMessage({ messageType: "initialization:error", messagePayload: ie(e) });
}
}
static postMessage(t, e) {
self.postMessage(
{
...t,
messageId: t.messageId ?? X(),
timestamp: t.timestamp ?? Date.now()
},
e
);
}
addListener(t, e) {
this.emitter.addListener(t, e);
}
removeListener(t, e) {
this.emitter.removeListener(t, e);
}
removeAllListeners(t) {
this.emitter.removeAllListeners(t);
}
}
var ge = { exports: {} };
(function(r) {
var t = Object.prototype.hasOwnProperty, e = "~";
function n() {
}
Object.create && (n.prototype = /* @__PURE__ */ Object.create(null), new n().__proto__ || (e = !1));
function s(h, c, l) {
this.fn = h, this.context = c, this.once = l || !1;
}
function o(h, c, l, f, y) {
if (typeof l != "function")
throw new TypeError("The listener must be a function");
var m = new s(l, f || h, y), g = e ? e + c : c;
return h._events[g] ? h._events[g].fn ? h._events[g] = [h._events[g], m] : h._events[g].push(m) : (h._events[g] = m, h._eventsCount++), h;
}
function i(h, c) {
--h._eventsCount === 0 ? h._events = new n() : delete h._events[c];
}
function a() {
this._events = new n(), this._eventsCount = 0;
}
a.prototype.eventNames = function() {
var c = [], l, f;
if (this._eventsCount === 0) return c;
for (f in l = this._events)
t.call(l, f) && c.push(e ? f.slice(1) : f);
return Object.getOwnPropertySymbols ? c.concat(Object.getOwnPropertySymbols(l)) : c;
}, a.prototype.listeners = function(c) {
var l = e ? e + c : c, f = this._events[l];
if (!f) return [];
if (f.fn) return [f.fn];
for (var y = 0, m = f.length, g = new Array(m); y < m; y++)
g[y] = f[y].fn;
return g;
}, a.prototype.listenerCount = function(c) {
var l = e ? e + c : c, f = this._events[l];
return f ? f.fn ? 1 : f.length : 0;
}, a.prototype.emit = function(c, l, f, y, m, g) {
var C = e ? e + c : c;
if (!this._events[C]) return !1;
var d = this._events[C], k = arguments.length, M, b;
if (d.fn) {
switch (d.once && this.removeListener(c, d.fn, void 0, !0), k) {
case 1:
return d.fn.call(d.context), !0;
case 2:
return d.fn.call(d.context, l), !0;
case 3:
return d.fn.call(d.context, l, f), !0;
case 4:
return d.fn.call(d.context, l, f, y), !0;
case 5:
return d.fn.call(d.context, l, f, y, m), !0;
case 6:
return d.fn.call(d.context, l, f, y, m, g), !0;
}
for (b = 1, M = new Array(k - 1); b < k; b++)
M[b - 1] = arguments[b];
d.fn.apply(d.context, M);
} else {
var Te = d.length, q;
for (b = 0; b < Te; b++)
switch (d[b].once && this.removeListener(c, d[b].fn, void 0, !0), k) {
case 1:
d[b].fn.call(d[b].context);
break;
case 2:
d[b].fn.call(d[b].context, l);
break;
case 3:
d[b].fn.call(d[b].context, l, f);
break;
case 4:
d[b].fn.call(d[b].context, l, f, y);
break;
default:
if (!M) for (q = 1, M = new Array(k - 1); q < k; q++)
M[q - 1] = arguments[q];
d[b].fn.apply(d[b].context, M);
}
}
return !0;
}, a.prototype.on = function(c, l, f) {
return o(this, c, l, f, !1);
}, a.prototype.once = function(c, l, f) {
return o(this, c, l, f, !0);
}, a.prototype.removeListener = function(c, l, f, y) {
var m = e ? e + c : c;
if (!this._events[m]) return this;
if (!l)
return i(this, m), this;
var g = this._events[m];
if (g.fn)
g.fn === l && (!y || g.once) && (!f || g.context === f) && i(this, m);
else {
for (var C = 0, d = [], k = g.length; C < k; C++)
(g[C].fn !== l || y && !g[C].once || f && g[C].context !== f) && d.push(g[C]);
d.length ? this._events[m] = d.length === 1 ? d[0] : d : i(this, m);
}
return this;
}, a.prototype.removeAllListeners = function(c) {
var l;
return c ? (l = e ? e + c : c, this._events[l] && i(this, l)) : (this._events = new n(), this._eventsCount = 0), this;
}, a.prototype.off = a.prototype.removeListener, a.prototype.addListener = a.prototype.on, a.prefixed = e, a.EventEmitter = a, r.exports = a;
})(ge);
var Fe = ge.exports;
const qe = /* @__PURE__ */ ue(Fe);
class we extends Error {
constructor(t) {
super(t), this.name = "TimeoutError";
}
}
class $e extends Error {
constructor(t) {
super(), this.name = "AbortError", this.message = t;
}
}
const oe = (r) => globalThis.DOMException === void 0 ? new $e(r) : new DOMException(r), ae = (r) => {
const t = r.reason === void 0 ? oe("This operation was aborted.") : r.reason;
return t instanceof Error ? t : oe(t);
};
function De(r, t) {
const {
milliseconds: e,
fallback: n,
message: s,
customTimers: o = { setTimeout, clearTimeout }
} = t;
let i, a;
const c = new Promise((l, f) => {
if (typeof e != "number" || Math.sign(e) !== 1)
throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);
if (t.signal) {
const { signal: m } = t;
m.aborted && f(ae(m)), a = () => {
f(ae(m));
}, m.addEventListener("abort", a, { once: !0 });
}
if (e === Number.POSITIVE_INFINITY) {
r.then(l, f);
return;
}
const y = new we();
i = o.setTimeout.call(void 0, () => {
if (n) {
try {
l(n());
} catch (m) {
f(m);
}
return;
}
typeof r.cancel == "function" && r.cancel(), s === !1 ? l() : s instanceof Error ? f(s) : (y.message = s ?? `Promise timed out after ${e} milliseconds`, f(y));
}, e), (async () => {
try {
l(await r);
} catch (m) {
f(m);
}
})();
}).finally(() => {
c.clear(), a && t.signal && t.signal.removeEventListener("abort", a);
});
return c.clear = () => {
o.clearTimeout.call(void 0, i), i = void 0;
}, c;
}
function He(r, t, e) {
let n = 0, s = r.length;
for (; s > 0; ) {
const o = Math.trunc(s / 2);
let i = n + o;
e(r[i], t) <= 0 ? (n = ++i, s -= o + 1) : s = o;
}
return n;
}
var T;
class Ue {
constructor() {
L(this, T, []);
}
enqueue(t, e) {
e = {
priority: 0,
...e
};
const n = {
priority: e.priority,
run: t
};
if (this.size && u(this, T)[this.size - 1].priority >= e.priority) {
u(this, T).push(n);
return;
}
const s = He(u(this, T), n, (o, i) => i.priority - o.priority);
u(this, T).splice(s, 0, n);
}
dequeue() {
const t = u(this, T).shift();
return t == null ? void 0 : t.run;
}
filter(t) {
return u(this, T).filter((e) => e.priority === t.priority).map((e) => e.run);
}
get size() {
return u(this, T).length;
}
}
T = new WeakMap();
var S, z, A, D, R, H, P, j, x, U, I, F, O, Q, v, be, Le, Ee, xe, _e, B, Z, ee, V, Pe, Y;
class Qe extends qe {
// TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`
constructor(e) {
var n, s;
super();
L(this, v);
L(this, S);
L(this, z);
L(this, A, 0);
L(this, D);
L(this, R);
L(this, H, 0);
L(this, P);
L(this, j);
L(this, x);
L(this, U);
L(this, I, 0);
// The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
L(this, F);
L(this, O);
L(this, Q);
/**
Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.
Applies to each future operation.
*/
_(this, "timeout");
if (e = {
carryoverConcurrencyCount: !1,
intervalCap: Number.POSITIVE_INFINITY,
interval: 0,
concurrency: Number.POSITIVE_INFINITY,
autoStart: !0,
queueClass: Ue,
...e
}, !(typeof e.intervalCap == "number" && e.intervalCap >= 1))
throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${((n = e.intervalCap) == null ? void 0 : n.toString()) ?? ""}\` (${typeof e.intervalCap})`);
if (e.interval === void 0 || !(Number.isFinite(e.interval) && e.interval >= 0))
throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${((s = e.interval) == null ? void 0 : s.toString()) ?? ""}\` (${typeof e.interval})`);
w(this, S, e.carryoverConcurrencyCount), w(this, z, e.intervalCap === Number.POSITIVE_INFINITY || e.interval === 0), w(this, D, e.intervalCap), w(this, R, e.interval), w(this, x, new e.queueClass()), w(this, U, e.queueClass), this.concurrency = e.concurrency, this.timeout = e.timeout, w(this, Q, e.throwOnTimeout === !0), w(this, O, e.autoStart === !1);
}
get concurrency() {
return u(this, F);
}
set concurrency(e) {
if (!(typeof e == "number" && e >= 1))
throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);
w(this, F, e), E(this, v, V).call(this);
}
async add(e, n = {}) {
return n = {
timeout: this.timeout,
throwOnTimeout: u(this, Q),
...n
}, new Promise((s, o) => {
u(this, x).enqueue(async () => {
var i;
W(this, I)._++, W(this, A)._++;
try {
(i = n.signal) == null || i.throwIfAborted();
let a = e({ signal: n.signal });
n.timeout && (a = De(Promise.resolve(a), { milliseconds: n.timeout })), n.signal && (a = Promise.race([a, E(this, v, Pe).call(this, n.signal)]));
const h = await a;
s(h), this.emit("completed", h);
} catch (a) {
if (a instanceof we && !n.throwOnTimeout) {
s();
return;
}
o(a), this.emit("error", a);
} finally {
E(this, v, Ee).call(this);
}
}, n), this.emit("add"), E(this, v, B).call(this);
});
}
async addAll(e, n) {
return Promise.all(e.map(async (s) => this.add(s, n)));
}
/**
Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
*/
start() {
return u(this, O) ? (w(this, O, !1), E(this, v, V).call(this), this) : this;
}
/**
Put queue execution on hold.
*/
pause() {
w(this, O, !0);
}
/**
Clear the queue.
*/
clear() {
w(this, x, new (u(this, U))());
}
/**
Can be called multiple times. Useful if you for example add additional items at a later time.
@returns A promise that settles when the queue becomes empty.
*/
async onEmpty() {
u(this, x).size !== 0 && await E(this, v, Y).call(this, "empty");
}
/**
@returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.
If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.
Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.
*/
async onSizeLessThan(e) {
u(this, x).size < e || await E(this, v, Y).call(this, "next", () => u(this, x).size < e);
}
/**
The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
@returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
*/
async onIdle() {
u(this, I) === 0 && u(this, x).size === 0 || await E(this, v, Y).call(this, "idle");
}
/**
Size of the queue, the number of queued items waiting to run.
*/
get size() {
return u(this, x).size;
}
/**
Size of the queue, filtered by the given options.
For example, this can be used to find the number of items remaining in the queue with a specific priority level.
*/
sizeBy(e) {
return u(this, x).filter(e).length;
}
/**
Number of running items (no longer in the queue).
*/
get pending() {
return u(this, I);
}
/**
Whether the queue is currently paused.
*/
get isPaused() {
return u(this, O);
}
}
S = new WeakMap(), z = new WeakMap(), A = new WeakMap(), D = new WeakMap(), R = new WeakMap(), H = new WeakMap(), P = new WeakMap(), j = new WeakMap(), x = new WeakMap(), U = new WeakMap(), I = new WeakMap(), F = new WeakMap(), O = new WeakMap(), Q = new WeakMap(), v = new WeakSet(), be = function() {
return u(this, z) || u(this, A) < u(this, D);
}, Le = function() {
return u(this, I) < u(this, F);
}, Ee = function() {
W(this, I)._--, E(this, v, B).call(this), this.emit("next");
}, xe = function() {
E(this, v, ee).call(this), E(this, v, Z).call(this), w(this, j, void 0);
}, _e = function() {
const e = Date.now();
if (u(this, P) === void 0) {
const n = u(this, H) - e;
if (n < 0)
w(this, A, u(this, S) ? u(this, I) : 0);
else
return u(this, j) === void 0 && w(this, j, setTimeout(() => {
E(this, v, xe).call(this);
}, n)), !0;
}
return !1;
}, B = function() {
if (u(this, x).size === 0)
return u(this, P) && clearInterval(u(this, P)), w(this, P, void 0), this.emit("empty"), u(this, I) === 0 && this.emit("idle"), !1;
if (!u(this, O)) {
const e = !u(this, v, _e);
if (u(this, v, be) && u(this, v, Le)) {
const n = u(this, x).dequeue();
return n ? (this.emit("active"), n(), e && E(this, v, Z).call(this), !0) : !1;
}
}
return !1;
}, Z = function() {
u(this, z) || u(this, P) !== void 0 || (w(this, P, setInterval(() => {
E(this, v, ee).call(this);
}, u(this, R))), w(this, H, Date.now() + u(this, R)));
}, ee = function() {
u(this, A) === 0 && u(this, I) === 0 && u(this, P) && (clearInterval(u(this, P)), w(this, P, void 0)), w(this, A, u(this, S) ? u(this, I) : 0), E(this, v, V).call(this);
}, /**
Executes all queued functions until it reaches the limit.
*/
V = function() {
for (; E(this, v, B).call(this); )
;
}, Pe = async function(e) {
return new Promise((n, s) => {
e.addEventListener("abort", () => {
s(e.reason);
}, { once: !0 });
});
}, Y = async function(e, n) {
return new Promise((s) => {
const o = () => {
n && !n() || (this.off(e, o), s());
};
this.on(e, o);
});
};
class Ie {
// hide constructor, makesure WorkerrController only init by createWorkerrController
constructor(t) {
_(this, "worker");
_(this, "taskQueue");
_(this, "concurrency");
_(this, "context");
_(this, "eventEmitter", new ye());
_(this, "readyPromise");
_(this, "ready", !1);
_(this, "terminated", !1);
try {
this.worker = t.worker(), this.context = t.context ?? {}, this.concurrency = t.concurrency || 1 / 0, Number.isFinite(this.concurrency) && this.concurrency >= 1 && (this.taskQueue = new Qe({ concurrency: this.concurrency })), this.readyPromise = new Promise((e, n) => {
const s = setTimeout(() => {
n(new Error("Cannot initialized worker"));
}, 5e3), o = (i) => {
switch (i.data.messageType) {
case "initialization:start":
clearTimeout(s);
break;
case "initialization:error":
this.eventEmitter.emit("error", i.data.messagePayload), n(i.data.messagePayload), this.worker.removeEventListener("message", o);
break;
case "initialization:complete":
this.ready = !0, this.postMessage({
messageType: "initialization:ack",
messagePayload: void 0
}), this.updateContext(() => this.context), this.worker.removeEventListener("message", o), this.eventEmitter.emit("ready"), e(!0);
break;
}
};
this.worker.addEventListener("message", o);
});
} catch (e) {
throw e;
}
}
static create(t) {
return new Ie(t);
}
postMessage(t, e) {
this.worker.postMessage({
...t,
messageId: t.messageId ?? X(),
timestamp: t.timestamp ?? Date.now()
}, e);
}
async awaitReady() {
await this.readyPromise;
}
async updateContext(t) {
if (this.terminated)
throw new Error("Workerr had been terminated");
this.context = t(this.context), this.postMessage({
messageType: "context:update",
messagePayload: this.context
});
}
_invoke(t, e, n) {
return new Promise(async (s, o) => {
var f;
await this.awaitReady;
const i = X();
let a, h;
if (n != null && n.abortSignal) {
const y = new MessageChannel();
a = y.port1, h = y.port2;
}
const c = (y) => {
const m = y.target;
a == null || a.postMessage(m.reason);
};
(f = n == null ? void 0 : n.abortSignal) == null || f.addEventListener("abort", c, { once: !0 });
const l = (y) => {
var g;
let m = y.data;
if ((m.messageType === "excecute:error" || m.messageType === "excecute:response") && m.messagePayload.messageId === i) {
switch (m.messageType) {
case "excecute:response":
this.worker.removeEventListener("message", l), s(m.messagePayload.result);
break;
case "excecute:error": {
this.worker.removeEventListener("message", l), o(m.messagePayload.error);
break;
}
}
(g = n == null ? void 0 : n.abortSignal) == null || g.removeEventListener("abort", c), a == null || a.close();
}
};
this.worker.addEventListener("message", l), this.postMessage({
messageType: "excecute:start",
messagePayload: {
cmd: t,
params: e,
abortSignalChannelPort: h
},
messageId: i
}, { transfer: [...(n == null ? void 0 : n.transfer) ?? [], ...h ? [h] : []] });
});
}
async invoke(t, e, n) {
if (this.terminated)
throw new Error("Workerr had been terminated");
return this.taskQueue ? this.taskQueue.add(({ signal: s }) => this._invoke(t, e, {
...n,
abortSignal: s
}), { signal: n == null ? void 0 : n.abortSignal }) : this._invoke(t, e, n);
}
// public send() {
// if (this.terminated) {
// throw new Error("Workerr had been terminated")
// }
// }
// public streamingRequest() {
// if (this.terminated) {
// throw new Error("Workerr had been terminated")
// }
// }
addListener(t, e) {
if (this.terminated)
throw new Error("Workerr had been terminated");
this.eventEmitter.addListener(t, e);
}
removeListener(t, e) {
if (this.terminated)
throw new Error("Workerr had been terminated");
this.eventEmitter.removeListener(t, e);
}
removeAllListeners(t) {
if (this.terminated)
throw new Error("Workerr had been terminated");
this.eventEmitter.removeAllListeners(t);
}
terminate() {
this.worker.terminate(), this.removeAllListeners();
}
}
export {
Ke as CommandBuilder,
$ as Workerr,
Ie as WorkerrController
};