UNPKG

@masvio/uploader

Version:

A simple, lightweight library to easily share files using MASV

702 lines (701 loc) 33 kB
var o = /* @__PURE__ */ ((s) => (s.Created = "uploader:create", s.Start = "upload:start", s.Progress = "upload:progress", s.Chunk = "upload:chunk", s.File = "upload:file", s.Error = "upload:error", s.Finished = "upload:finish", s.Finalize = "upload:finalize", s.FileQueued = "upload:file_queued", s.Abort = "upload:abort", s.Retry = "upload:retry", s.Stalled = "upload:stalled", s.FileUnreadable = "upload:file_unreadable", s))(o || {}), u = /* @__PURE__ */ ((s) => (s.Created = "worker:create", s.Execute = "worker:execute", s.Finish = "worker:finish", s.Error = "worker:error", s.Retry = "worker:retry", s.Progress = "worker:progress", s.Terminate = "worker:terminate", s.Abort = "worker:abort", s))(u || {}); class I { constructor() { this.handlers = {}; } on(e, t) { this.handlers[e] || (this.handlers[e] = []), this.handlers[e].push(t); } off(e, t) { if (t == null) { this.handlers[e] = []; return; } this.handlers[e] && (this.handlers[e] = this.handlers[e].filter((i) => i !== t)); } clearHandlers() { this.handlers = {}; } emit(e, t) { const i = { time: Date.now(), event: e, target: this, data: {}, ...t }; this.handlers[e] && this.handlers[e].forEach((r) => { r(i); }), this.handlers.emit != null && this.handlers.emit.forEach((r) => { r(i); }); } bubbleEmit(e) { "event" in e && this.emit(e.event, { ...e }); } } const S = "c2VsZi5hcGlCYXNlVXJsID0gIiI7CnNlbGYucGFja2FnZVRva2VuID0gIiI7CnNlbGYucGFja2FnZUlEID0gIiI7CnNlbGYubWFzdlVzZXJBZ2VudCA9ICIiOwpzZWxmLmNodW5rU2l6ZSA9IDEwMCA8PCAyMDsKc2VsZi5jdXJyZW50UHJvbWlzZSA9IG51bGw7CnNlbGYucHJvbWlzZVBvb2wgPSBbXTsKc2VsZi5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgY29uc3QgeyBuYW1lOiBzLCBpbnB1dDogYSB9ID0gZS5kYXRhOwogIHMgPT09ICJJbml0IiAmJiAoc2VsZi5wY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h1bmtTaXplOiBpLAogICAgICBibHVlcHJpbnRzOiBrCiAgICB9KSwgdSA9IHsKICAgICAgZmlsZTogZSwKICAgICAgZmlsZUlkOiBzLmlkLAogICAgICBzdG9yYWdlVHlwZTogYSwKICAgICAgZmlsZUV4dHJhczogbywKICAgICAgLi4ucCwKICAgICAgY2h1bmtTaXplOiBpCiAgICB9OwogICAgcmV0dXJuIHNlbGYucG9zdE1lc3NhZ2UoeyBuYW1lOiAid29ya2VyOmZpbmlzaCIsIGRhdGE6IHUgfSksIHU7CiAgfSBjYXRjaCAocykgewogICAgcmV0dXJuIHNlbGYucG9zdE1lc3NhZ2UoeyBuYW1lOiAid29ya2VyOmVycm9yIiwgZGF0YTogeyBpbnB1dDogZSwgZXJyb3I6IHMgfSB9KSwgczsKICB9Cn0KYXN5bmMgZnVuY3Rpb24gYyhlID0gIiIsIHMsIGEgPSB7fSwgbiA9ICJQT1NUIiwgbCA9ICExLCB0ID0gMCkgewogIGxldCBpOwogIHRyeSB7CiAgICBpID0gYXdhaXQgZmV0Y2goZSwgewogICAgICBtZXRob2Q6IG4sCiAgICAgIGhlYWRlcnM6IHsKICAgICAgICAiQ29udGVudC1UeXBlIjogImFwcGxpY2F0aW9uL2pzb24iLAogICAgICAgICJYLVBhY2thZ2UtVG9rZW4iOiBzZWxmLnBhY2thZ2VUb2tlbiwKICAgICAgICAiTWFzdi1Vc2VyLUFnZW50Ijogc2VsZi5tYXN2VXNlckFnZW50LAogICAgICAgIC4uLmEKICAgICAgfSwKICAgICAgYm9keTogcwogICAgfSk7CiAgfSBjYXRjaCB7CiAgICByZXR1cm4gaChlLCBzLCBhLCBuLCBsLCB0KTsKICB9CiAgY29uc3QgciA9IGwgPyBhd2FpdCBpLnRleHQoKSA6IGF3YWl0IGkuanNvbigpOwogIGlmIChpLm9rKQogICAgcmV0dXJuIHI7CiAgaWYgKGkuc3RhdHVzID49IDUwMCkKICAgIHJldHVybiBoKGUsIHMsIGEsIG4sIGwsIHQpOwogIHRoc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Zi5wYWNrYWdlSUR9L2ZpbGVzLyR7ZX0/c3RhcnQ9MCZjb3VudD0ke3N9YCwKICAgIEpTT04uc3RyaW5naWZ5KGEpCiAgKTsKfQphc3luYyBmdW5jdGlvbiBTKGUpIHsKICBjb25zdCBzID0geyByZXE6IGUsIGNodW5rczogW10gfSwgYSA9IGUuY2h1bmtTaXplLCBuID0gZS5maWxlLnNpemU7CiAgbGV0IGwgPSAwLCB0ID0gbjsKICBmb3IgKDsgdCA+IDA7ICkgewogICAgY29uc3QgaSA9IG4gLSB0LCByID0gTWF0aC5taW4obiwgbiAtIHQgKyBhKSwgZiA9IGUuZmlsZS5zbGljZShpLCByKSwgbyA9IGUuYmx1ZXByaW50c1tsXTsKICAgIHMuY2h1bmtzLnB1c2goewogICAgICB1cmw6IG8udXJsLAogICAgICBtZXRob2Q6IG8ubWV0aG9kLAogICAgICBoZWFkZXJzOiBvLmhlYWRlcnMsCiAgICAgIGJvZHk6IGYKICAgIH0pLCB0IC09IGEsIGwrKzsKICB9CiAgcmV0dXJuIHM7Cn0K", W = (s) => Uint8Array.from(atob(s), (e) => e.charCodeAt(0)), A = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", W(S)], { type: "text/javascript;charset=utf-8" }); function F(s) { let e; try { if (e = A && (self.URL || self.webkitURL).createObjectURL(A), !e) throw ""; const t = new Worker(e, { type: "module", name: s?.name }); return t.addEventListener("error", () => { (self.URL || self.webkitURL).revokeObjectURL(e); }), t; } catch { return new Worker( "data:text/javascript;base64," + S, { type: "module", name: s?.name } ); } } class y extends I { constructor(e, t, i, r, n) { super(), this.apiBaseUrl = e, this.chunkSize = t, this.packageID = i, this.packageToken = r, this.masvUserAgent = n, this.terminated = !1, this.onNativeWorkerMessage = (h) => { const { name: a, data: g } = h.data; this.emit(a, { data: g }); }, this.emit(u.Created), this.startWorker(); } startWorker() { this.nativeWorker = new F(), this.nativeWorker.onmessage = this.onNativeWorkerMessage, this.nativeWorker.postMessage({ name: "Init", input: { packageToken: this.packageToken, apiBaseUrl: this.apiBaseUrl, packageID: this.packageID, masvUserAgent: this.masvUserAgent, chunkSize: this.chunkSize } }); } stopWorker() { this.nativeWorker.onmessage = null, this.nativeWorker.terminate(); } createFile(e) { if (this.terminated) throw new Error("Can't use a terminated worker"); this.nativeWorker.postMessage({ name: "Chunk", input: e }); } abort() { this.stopWorker(), this.startWorker(); } terminate() { this.terminated = !0, this.emit(u.Terminate), this.clearHandlers(), this.nativeWorker.terminate(); } } class V extends I { constructor(e, t, i, r, n = 6, h) { super(), this.workers = new Array(), this.counter = 0, this.terminated = !1; let a; for (let g = 0; g < n; g++) a = new y( e, t, i, r, h ), a.on("emit", this.bubbleEmit.bind(this)), this.workers.push(a); } createFile(e) { const t = this.workers[this.counter % this.workers.length]; if (this.terminated) throw new m(); this.counter++, t.createFile(e); } abort() { this.workers.forEach((e) => e.abort()); } terminate() { this.terminated = !0, this.workers.forEach((e) => e.terminate()), this.clearHandlers(); } } const k = "Y29uc3QgZCA9ICgpID0+ICh7CiAgcmV0cmllczogMTAsCiAgZGVsYXk6IDFlMwp9KTsKc2VsZi5jdXJyZW50UmVxdWVzdCA9IG51bGw7CnNlbGYuY3VycmVudFJlcXVlc3RzID0gW107CnNlbGYucmV0cnk0MDAgPSAhMTsKc2VsZi5yZXRyeVRpbWVvdXQgPSBudWxsOwpmdW5jdGlvbiB1KCkgewogIGxldCBlOwogIGlmIChzZWxmLmN1cnJlbnRSZXF1ZXN0cy5sZW5ndGggPT09IDAgfHwgc2VsZi5jdXJyZW50UmVxdWVzdCAhPSBudWxsKQogICAgcmV0dXJuOwogIGUgPSBzZWxmLmN1cnJlbnRSZXF1ZXN0cy5zaGlmdCgpLCBlLmlucHV0LnJldHJ5Q29uZmlnID09IG51bGwgJiYgKGUuaW5wdXQucmV0cnlDb25maWcgPSBkKCkpOwogIGNvbnN0IHQgPSBuZXcgWE1MSHR0cFJlcXVlc3QoKTsKICBzZWxmLmN1cnJlbnRSZXF1ZX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nlUaW1lb3V0KSwgc2VsZi5jdXJyZW50UmVxdWVzdHMgPSBzZWxmLmN1cnJlbnRSZXF1ZXN0cy5maWx0ZXIoKHIpID0+IHIuaW5wdXQudHlwZSAhPT0gInVwbG9hZF9maWxlIiksIHUoKTsKICAgIH0sCiAgICBjb25maWc6IChyKSA9PiB7CiAgICAgIHNlbGYucmV0cnk0MDAgPSByLnJldHJ5NDAwIHx8ICExOwogICAgfQogIH07CiAgc1t0Lm1lc3NhZ2VdICE9IG51bGwgJiYgc1t0Lm1lc3NhZ2VdKHQpOwp9Owo=", X = (s) => Uint8Array.from(atob(s), (e) => e.charCodeAt(0)), b = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", X(k)], { type: "text/javascript;charset=utf-8" }); function H(s) { let e; try { if (e = b && (self.URL || self.webkitURL).createObjectURL(b), !e) throw ""; const t = new Worker(e, { type: "module", name: s?.name }); return t.addEventListener("error", () => { (self.URL || self.webkitURL).revokeObjectURL(e); }), t; } catch { return new Worker( "data:text/javascript;base64," + k, { type: "module", name: s?.name } ); } } var l = /* @__PURE__ */ ((s) => (s.AddChunk = "add_chunk", s.UploadFile = "upload_file", s.FinalizeFile = "finalize_file", s.FinalizePackage = "finalize_package", s.CancelPackage = "cancel_package", s.Error = "error", s))(l || {}); class Y extends I { constructor(e = !1) { super(), this.terminated = !1, this.onNativeWorkerMessage = (t) => { const { name: i, payload: r } = t.data; this.emit(i, { data: r }); }, this.startWorker(e), this.emit(u.Created); } startWorker(e = !1) { this.nativeWorker = new H(), this.nativeWorker.onmessage = this.onNativeWorkerMessage, this.nativeWorker.postMessage({ message: "config", retry400: e }); } execute(e) { if (this.terminated) throw new Error("Can't run a terminated worker"); this.emit(u.Execute, { data: e }), this.nativeWorker.postMessage({ message: "request", ...e }); } abort() { this.nativeWorker.postMessage({ message: "abort" /* Abort */ }); } terminate() { this.terminated = !0, this.emit(u.Terminate), this.clearHandlers(), this.nativeWorker.terminate(); } } const v = 1600 * 1e3; class z extends I { constructor(e, t, i, r, n, h = 6, a) { super(), this.apiBaseUrl = e, this.packageID = r, this.packageToken = n, this.poolSize = h, this.masvUserAgent = a, this.apiXhrExecutor = t, this.storageXhrExecutor = i, this.emit(o.Created), this.storageXhrExecutor.on(u.Progress, (g) => this.onStorageProgress(g)), this.storageXhrExecutor.on(u.Abort, (g) => this.onStorageAbort(g)), this.storageXhrExecutor.on(u.Retry, (g) => this.onStorageRetry(g)), this.storageXhrExecutor.on(u.Finish, (g) => this.onStorageFinish(g)), this.storageXhrExecutor.on(u.Error, (g) => this.onStorageError(g)); } upload(e) { const t = e.chunks.filter((i) => !i.isFinished).map((i) => ({ fileId: e.id, sequence: i.index, timeout: v, ...i.chunk, type: l.UploadFile })); return this.emit(o.Start, { data: e }), e.running = !0, this.storageXhrExecutor.execute(...t), e; } abort() { this.storageXhrExecutor.abort(), this.apiXhrExecutor.abort(); } onStorageProgress(e) { const t = e.data; e.data.input.type === l.UploadFile && this.bubbleEmit({ event: o.Progress, target: e.target, data: t }); } onStorageFinish(e) { const t = e.data; t.req.type === l.UploadFile && this.bubbleEmit({ event: o.Chunk, target: e.target, data: t }); } onStorageAbort(e) { const t = e.data; t.type === l.UploadFile && this.bubbleEmit({ event: o.Abort, target: e.target, data: t }); } onStorageRetry(e) { const t = e.data; t.input.type === l.UploadFile && this.bubbleEmit({ event: o.Retry, target: e.target, data: t }); } onStorageError(e) { const t = e.data; this.bubbleEmit({ event: o.Error, target: e.target, data: t }); } } class B extends I { constructor(e = 6, t = !1) { super(), this.workers = new Array(), this.counter = 0, this.retry400Errors = !1, this.terminated = !1, this.retry400Errors = t, this.initWorkerPool(e); } initWorkerPool(e = 6) { for (let t = 0; t < e; t++) { let i = new Y(this.retry400Errors); i.on("emit", this.bubbleEmit.bind(this)), this.workers.push(i); } } stopWorkerPool() { this.workers.forEach((e) => { e.terminate(); }); } abort() { this.workers.forEach((e) => e.abort()); } execute(...e) { if (this.terminated) throw new m(); for (let t of e) this.workers[this.counter++ % this.workers.length].execute(t); } terminate() { this.terminated = !0, this.clearHandlers(), this.stopWorkerPool(); } } let K = 0; const L = Date.now(); function U() { return "randomUUID" in crypto ? crypto.randomUUID() : `${L}_${K++}`; } class x { constructor() { this.queue = {}; } getFile(e) { return this.queue[e]; } addFile(e) { const t = new N(e); return this.queue[e.fileId] = t, t; } removeFile(e) { delete this.queue[e]; } setProgress(e, t, i) { const r = this.getFile(e); if (!r) return; const n = r.getChunk(t); if (n) return n.setProgress(i), n; } get length() { return Object.keys(this.queue).length; } get totalChunks() { return Object.values(this.queue).reduce((e, t) => e + t.chunks.length, 0); } get totalChunksInProgress() { return Object.values(this.queue).reduce((e, t) => e + t.chunksInProgress, 0); } } class N { constructor({ fileId: e, req: t, file: i, chunks: r, storageType: n, fileExtras: h }) { this.chunks = [], this.running = !1, this.finalized = !1, this.id = e, this.req = t, this.file = i, this.chunks = r.map((a, g) => new P(a, g)), this.chunkSize = t.chunkSize > i.file.size ? i.file.size : t.chunkSize, this.storageType = n, this.fileExtras = h; } setChunkExtras({ headers: e, req: t }) { const i = t.sequence || 0, r = this.chunks.find((h) => h.index === i); if (!r) return; const n = e.etag || e.ETag || e.Etag; r.setExtras({ // partNumber should be a number but it is converted to string here // https://masvio.atlassian.net/browse/MASV-11004 partNumber: String(i + 1), etag: n }); } getChunk(e) { return this.chunks[e]; } validateMissingEtags() { return this.chunks.filter((e) => e.extras == null || e.extras.etag == null); } get isFinished() { return this.chunks.every((e) => e.isFinished); } get inProgress() { return this.chunks.some((e) => e.currentBytes > 0) && !this.isFinished; } get currentBytes() { return this.chunks.reduce((e, t) => e + t.currentBytes, 0); } get totalBytes() { return this.chunks.reduce((e, t) => e + t.totalBytes, 0); } get chunksInProgress() { return this.chunks.filter((e) => !e.isFinished).length; } } class P { constructor(e, t) { this._currentBytes = 0, this.extras = null, this.index = t, this.chunk = e; } setProgress(e) { this._currentBytes = e; } setExtras(e) { this.extras = e; } get etag() { return this.extras?.etag; } get currentBytes() { return this._currentBytes; } get totalBytes() { return this.chunk.body.size; } get inProgress() { return this.currentBytes > 0 && !this.isFinished; } get isFinished() { return this.currentBytes >= this.totalBytes && this.extras != null; } } class R { constructor(e) { if (this.ma = 0, this.v = 0, this.d = 0, this.f = 0, this.previousTime = 0, e <= 0) throw new Error("must provide a timespan > 0 to the moving average constructor"); this.timespan = e; } alpha(e, t) { return 1 - Math.exp(-(e - t) / this.timespan); } push(e, t) { if (this.previousTime > 0) { const i = this.alpha(e, this.previousTime), r = t - this.ma, n = i * r; this.ma = i * t + (1 - i) * this.ma, this.v = (1 - i) * (this.v + r * n), this.d = Math.sqrt(this.v), this.f = this.ma + i * r; } else this.ma = t; this.previousTime = e; } // Exponential Moving Average movingAverage() { return this.ma; } // Variance variance() { return this.v; } deviation() { return this.d; } forecast() { return this.f; } } var c = /* @__PURE__ */ ((s) => (s.Start = "upload_start", s.Stop = "upload_stop", s.Pause = "upload_pause", s.Finish = "upload_finish", s.Continue = "upload_continue", s))(c || {}); const p = 500; class T { constructor() { this.transferred = 0, this.received = 0, this.finalized = 0, this.finalizedFiles = 0, this.total = 0, this.totalFiles = 0, this.marks = { upload_start: [], upload_pause: [], upload_continue: [], upload_finish: [], upload_stop: [] }, this.moving = new R(p), this.debounceAverage = !1, this.lastSampleAmount = 0, this.progress = 0, this.instantSpeed = 0, this.movingSpeed = 0, this.duration = 0, this.timer = -1; } mark(e) { this.marks[e] && (e === "upload_start" || e === "upload_continue" ? this.record(performance.now()) : this.stopTimer(), this.marks[e].push(Date.now())); } record(e) { this.timer = requestAnimationFrame((t) => { this.duration += t - e, this.record(t); }); } stopTimer() { cancelAnimationFrame(this.timer); } clear(e) { this.marks[e] = []; } setTotal(e) { this.total = e; } setTotalFiles(e) { this.totalFiles = e; } addData(e = 0) { const t = Date.now(); if (this.transferred += e, this.progress += e, this.debounceAverage) return; this.debounceAverage = !0; const i = this.transferred - this.lastSampleAmount; this.instantSpeed = i / (p / 1e3), this.lastSampleAmount = this.transferred, this.moving.push(t, this.instantSpeed), this.movingSpeed = this.moving.movingAverage(), setTimeout(() => { this.debounceAverage = !1; }, p); } addReceived(e = 0) { this.received += e; } addFinalizedFile(e = 0) { this.finalized += e, this.finalizedFiles++; } subtractProgress(e = 0) { this.progress -= e; } getStats() { return { duration: this.duration, speed: this.averageSpeed, instant: this.instantSpeed, moving: this.movingSpeed, transferred: this.transferred, total: this.total, totalFiles: this.totalFiles, progress: this.progress, received: this.received, finalized: this.finalized, finalizedFiles: this.finalizedFiles }; } get averageSpeed() { return this.transferred / (this.duration / 1e3); } } const d = 6, E = "masv-web", Q = "masv-web-uploader", D = "dev"; var w = /* @__PURE__ */ ((s) => (s.Idle = "idle", s.Uploading = "uploading", s.Processing = "processing", s.Ready = "ready", s.Paused = "paused", s.Finished = "finished", s.Terminated = "terminated", s.Cancelled = "cancelled", s))(w || {}); const C = class C extends I { constructor(e, t, i = "https://api.massive.app", r = 100 << 20, n = `${E}/${D}`, h = 6e4) { super(), this.packageID = e, this.packageToken = t, this.apiBaseUrl = i, this.stallTimeout = h, this.stallTimer = -1, this.performanceStats = new T(), this.version = "2.2.4", this.uploadState = new x(), this.fileQueue = [], this.createQueue = /* @__PURE__ */ new Set(), this.unreadableFiles = /* @__PURE__ */ new Set(), this.status = "idle", this.masvUserAgent = `${n}+${Q}/${this.version}`, this.apiXhrExecutor = new B(d), this.storageXhrExecutor = new B(d, !0), this.fchunker = new V( i, r, e, t, d, this.masvUserAgent ), this.fuploader = new z( i, this.apiXhrExecutor, this.storageXhrExecutor, e, t, d, this.masvUserAgent ), this.fchunker.on(u.Finish, (a) => this.onChunkFinish(a)), this.fuploader.on(o.Progress, (a) => { this.onUploadProgress(a); }), this.fuploader.on(o.Chunk, (a) => this.onChunkUploadFinish(a)), this.fuploader.on(o.Abort, (a) => this.onUploadAbort(a)), this.fuploader.on(o.Retry, (a) => this.onUploadRetry(a)), this.fuploader.on(o.Error, (a) => this.onUploadError(a)), this.fchunker.on("emit", this.bubbleEmit.bind(this)), this.fuploader.on("emit", this.bubbleEmit.bind(this)), this.apiXhrExecutor.on(u.Finish, (a) => this.onAPIFinish(a)); } resetStallTimer() { clearTimeout(this.stallTimer), this.stallTimer = setTimeout(() => { this.emit(o.Stalled); }, this.stallTimeout); } popNextFile() { return this.fileQueue.pop(); } get nextFile() { return this.fileQueue[this.fileQueue.length - 1]; } get canUploadFile() { return this.nextFile == null || this.uploadState.totalChunksInProgress + this.createQueue.size >= d ? !1 : this.status === "ready" || this.status === "uploading"; } get hasFinished() { return this.nextFile === void 0 && this.uploadState.length === 0 && this.fileQueue.length === 0 && this.createQueue.size === 0; } onUploadProgress({ data: e }) { this.resetStallTimer(), e.input.fileId && this.uploadState.setProgress(e.input.fileId, e.input.sequence || 0, e.loaded), this.performanceStats.addData(e.transferred); } onChunkFinish({ data: e }) { this.emit(o.FileQueued, { data: e }); const t = this.uploadState.addFile(e); this.resetStallTimer(), this.createQueue.delete(e.file.id), t.totalBytes === 0 ? t.file.file.stream().getReader().read().then(() => { t.running = !0, this.finalizeFile(t); }).catch((n) => { this.setUnreadableFile(t, n.message); }) : this.fuploader.upload(t), this.uploadNext(); } onUploadAbort({ data: e }) { const { fileId: t = "", sequence: i = 0 } = e, r = this.uploadState.getFile(t)?.getChunk(i).currentBytes ?? 0; this.performanceStats.subtractProgress(r), this.uploadState.setProgress(t, i, 0); } onUploadRetry({ data: e }) { const { fileId: t = "", sequence: i = 0 } = e.input, r = this.uploadState.getFile(t)?.getChunk(i).currentBytes ?? 0; this.performanceStats.subtractProgress(r), this.uploadState.setProgress(t, i, 0); } onUploadError({ data: e }) { const { fileId: t = "" } = e.input; let { message: i = "generic upload error" } = e.error; const r = this.uploadState.getFile(t); r != null && this.setUnreadableFile(r, i); } onChunkUploadFinish({ data: e }) { const { fileId: t = "", sequence: i = 0 } = e.req, r = this.uploadState.getFile(t); if (r) { const n = r.getChunk(i); this.performanceStats.addReceived(n.totalBytes), r.setChunkExtras(e), r.isFinished && (this.emit(o.File, { data: r }), this.finalizeFile(r)); } this.uploadNext(); } onAPIFinish({ data: e }) { const t = [200, 201, 204]; if (e.req.type === l.FinalizeFile) { const i = this.uploadState.getFile(e.req.fileId); if (i) if (t.includes(e.statusCode)) i.finalized = !0, i.running = !1, this.performanceStats.addFinalizedFile(i.file.file.size), this.uploadState.removeFile(i.id), this.emit(o.Finalize, { data: i }); else { this.setUnreadableFile(i, `unexpected status code for finalize file request: ${e.statusCode}`), this.hasFinished && this.stop(); return; } this.uploadNext(), this.hasFinished && (this.stop(), this.unreadableFiles.size > 0 ? this.markAsStalled() : this.finalize()); } e.req.type === l.FinalizePackage && (t.includes(e.statusCode) ? (this.performanceStats.mark(c.Finish), this.emit(o.Finished, { data: this.getPerformanceStats() }), this.status = "finished", this.terminate()) : (this.markAsStalled(`unexpected status code for finalize package request: ${e.statusCode}`), this.stop())), e.req.type === l.CancelPackage && this.terminate(); } setUnreadableFile(e, t) { this.emit(o.FileUnreadable, { data: e }), t === "network error" && (t = "file is unreadable (network error)"), this.unreadableFiles.add({ id: e.id, name: e.file?.file?.name, path: e.file?.path, size: e.file?.file?.size, errorMessage: t, errorTimestamp: (/* @__PURE__ */ new Date()).toISOString() }), this.uploadState.removeFile(e.id), this.hasFinished && this.markAsStalled(), this.uploadNext(); } markAsStalled(e = "Upload has become stalled due to unreadable files") { this.unreadableFiles.size > 0 && (e = [...this.unreadableFiles.values()][0].errorMessage); const t = { error_code: "upload_stalled", error_message: e, event_time: (/* @__PURE__ */ new Date()).toISOString(), extras: this.getProgressSummary() }; this.apiXhrExecutor.execute({ url: `${this.apiBaseUrl}/v1/packages/${this.packageID}/error`, method: "POST", headers: { "Content-Type": "application/json", "X-Package-Token": this.packageToken, "Masv-User-Agent": this.masvUserAgent }, body: JSON.stringify(t), timeout: 1e4, type: l.Error }), this.emit(o.Stalled), clearTimeout(this.stallTimer); } addFiles(...e) { this.status = "processing", this.performanceStats.setTotalFiles(e.length), this.performanceStats.setTotal(e.reduce((t, i) => t + i.file.size, 0)), this.status = "ready", this.fileQueue = e, this.start(); } start() { if (this.status === "uploading") return; this.resetStallTimer(), this.status = "uploading"; const { transferred: e } = this.performanceStats.getStats(); if (e > 0 ? this.performanceStats.mark(c.Continue) : this.performanceStats.mark(c.Start), this.uploadState.totalChunksInProgress > 0) { const t = Object.values(this.uploadState.queue); for (let i of t) this.fuploader.upload(i); } else this.uploadNext(); } uploadNext() { if (!this.canUploadFile) return; const e = this.popNextFile(); e && (e.id == null && (e.id = U()), this.createQueue.add(e.id), this.fchunker.createFile(e)); } stop() { this.status = "idle", this.performanceStats.mark(c.Stop); } pause() { this.status !== "paused" && (clearTimeout(this.stallTimer), this.status = "paused", this.performanceStats.mark(c.Pause), this.fuploader.abort()); } terminate() { this.status !== "terminated" && (this.status = "terminated", this.clearHandlers(), this.storageXhrExecutor.terminate(), this.apiXhrExecutor.terminate(), this.fchunker.terminate()); } cancel() { this.pause(), this.status = "cancelled", this.apiXhrExecutor.execute({ url: `${this.apiBaseUrl}/v1/packages/${this.packageID}`, method: "DELETE", headers: { "X-Package-Token": this.packageToken, "Masv-User-Agent": this.masvUserAgent }, timeout: 1e4, type: l.CancelPackage }); } finalizeFile(e) { if (e.validateMissingEtags().length > 0) { this.fuploader.upload(e); return; } const { id: i, fileExtras: r, chunkSize: n, file: h, chunks: a } = e, g = a.map((G) => G.extras); this.apiXhrExecutor.execute({ url: `${this.apiBaseUrl}/v1/packages/${this.packageID}/files/${i}/finalize`, method: "POST", headers: { "Content-Type": "application/json", "X-Package-Token": this.packageToken, "Masv-User-Agent": this.masvUserAgent }, body: JSON.stringify({ fileExtras: r, chunk_size: n, size: h.file.size, chunkExtras: g }), timeout: 6e4, fileId: i, type: l.FinalizeFile }); } getIncompleteFiles() { return { queued: this.fileQueue, creating: [...this.createQueue], uploading: Object.values(this.uploadState.queue), unreadable: [...this.unreadableFiles] }; } finalize() { clearTimeout(this.stallTimer), this.apiXhrExecutor.execute({ url: `${this.apiBaseUrl}/v1/packages/${this.packageID}/finalize`, method: "POST", headers: { "Content-Type": "application/json", "X-Package-Token": this.packageToken, "Masv-User-Agent": this.masvUserAgent }, timeout: 6e4, type: l.FinalizePackage }); } getPerformanceStats() { return this.performanceStats.getStats(); } getProgressSummary() { const e = this.performanceStats.getStats(); return { finalizedBytes: String(e.finalized), finalizedFiles: String(e.finalizedFiles), totalBytes: String(e.total), totalFiles: String(e.totalFiles), unreadableFiles: String(this.unreadableFiles.size) }; } }; C.UploaderEvents = o, C.States = w; let f = C; class Z extends Error { constructor(e, t) { super("HTTP error " + e), this.statusCode = e, this.bytesTransferred = t, Object.setPrototypeOf(this, Z.prototype); } getStatusCode() { return this.statusCode; } getBytesTransferred() { return this.bytesTransferred; } } class m extends Error { constructor() { super("Terminated"), Object.setPrototypeOf(this, m.prototype); } } export { Z as HttpError, m as TerminatedError, f as Uploader };