UNPKG

filepond

Version:

FilePond, where files go to stretch their bits.

93 lines (92 loc) • 3.44 kB
/*! * FilePond v5.0.2 * Copyright (c) 2017-2026 Pqina B.V. * Released under the MIT License * https://filepond.com */ import O from "./functionToBlob.js"; import { arrayRemoveInPlace as k } from "./array.js"; import { requestIdleCallback as I } from "./poly.js"; import { createObjectURL as j } from "./objectURL.js"; import { isString as C } from "./test.js"; const U = (n) => `function () {self.onmessage = function (message) {(${n.toString()}).apply(null, message.data.concat([function (err, response, transferList = []) {const message = { content: response, error: err };return self.postMessage(message, transferList);},{onprogress: function({ lengthComputable, loaded, total }) {self.postMessage({ type: 'progress', content: { lengthComputable, loaded, total }, error: null })}}]))}}`, l = [], s = [], A = 5e3; function B(n, m) { return n ? `${n}/${m.fileName}Worker.js` : m; } function K(n, m, R = {}) { return new Promise((h, f) => { const S = navigator.hardwareConcurrency, b = ({ fn: a, args: v, options: y, abortQueuedTask: L, promise: i }) => { const { signal: o, transferList: M = [], onprogress: W } = y; if (o?.aborted) { i.reject(o.reason); return; } const E = !C(a), d = E ? a.toString() : a; let e = l.find((r) => r.fnStr === d && !r.busy); if (!e) { if (l.filter((t) => t.busy).length >= S) { let t; const c = () => { k( s, (g) => g === t ), i.reject(o?.reason); }; t = { fn: a, fnStr: d, args: v, options: y, abortQueuedTask: c, promise: { resolve: h, reject: f } }, s.push(t), o?.addEventListener("abort", c, { once: !0 }); return; } const r = E ? j(O(U(a))) : d, u = new window.Worker(r); u.addEventListener("error", f), e = { busy: !1, fnStr: d, url: r, worker: u, terminationTimeout: void 0, terminate: () => { clearTimeout(e.terminationTimeout), e.worker.terminate(), u.removeEventListener("error", f), r.startsWith("blob:") && URL.revokeObjectURL(r), k( l, (t) => t === e ), s.length && b(s.shift()); } }, l.find((t) => t.busy === !1)?.terminate(), l.push(e); } e.busy = !0, L && o?.removeEventListener("abort", L); const w = () => { e.terminate(), i.reject(o?.reason); }; clearTimeout(e.terminationTimeout), e.worker.onmessage = function(r) { const { type: u, content: p, error: t } = r.data; if (u === "progress") { W && W(p); return; } clearTimeout(e.terminationTimeout), e.terminationTimeout = setTimeout(() => { e.terminate(); }, A), t !== null ? i.reject(t) : i.resolve(p), o?.removeEventListener("abort", w); const c = s.filter( (T) => T.fnStr === e.fnStr ); if (!c.length) { e.busy = !1; return; } const g = c.shift(); k(s, (T) => T === g), I(() => { e.busy = !1, b(g); }); }, o?.addEventListener("abort", w, { once: !0 }), e.worker.postMessage(v, M); }; b({ fn: n, args: m, options: R, promise: { resolve: h, reject: f } }); }); } export { B as createThreadWorker, K as thread };