UNPKG

@masvio/uploader

Version:

A simple, lightweight library to easily share files using MASV

734 lines (733 loc) 35.7 kB
class A extends Error { constructor() { super("Terminated"), Object.setPrototypeOf(this, A.prototype); } } function f(s) { return s >= 400 && s < 500; } var n = /* @__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))(n || {}), h = /* @__PURE__ */ ((s) => (s.ApiError = "worker:api_error", 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))(h || {}); class c { 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 k = "Y2xhc3MgcCB7CiAgY29uc3RydWN0b3IoYSwgcywgdCkgewogICAgdGhpcy5uYW1lID0gIkFwaUVycm9yIiwgdGhpcy5zdGF0dXNDb2RlID0gYSwgdGhpcy5jb2RlID0gcywgdGhpcy5tZXNzYWdlID0gdDsKICB9Cn0Kc2VsZi5hcGlCYXNlVXJsID0gIiI7CnNlbGYucGFja2FnZVRva2VuID0gIiI7CnNlbGYucGFja2FnZUlEID0gIiI7CnNlbGYubWFzdlVzZXJBZ2VudCA9ICIiOwp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odCwgdCAtIG4gKyBzKSwgYyA9IGUuZmlsZS5zbGljZShpLCByKSwgbyA9IGUuYmx1ZXByaW50c1tsXTsKICAgIGEuY2h1bmtzLnB1c2goewogICAgICB1cmw6IG8udXJsLAogICAgICBtZXRob2Q6IG8ubWV0aG9kLAogICAgICBoZWFkZXJzOiBvLmhlYWRlcnMsCiAgICAgIGJvZHk6IGMKICAgIH0pLCBuIC09IHMsIGwrKzsKICB9CiAgcmV0dXJuIGE7Cn0K", y = (s) => Uint8Array.from(atob(s), (e) => e.charCodeAt(0)), p = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", y(k)], { type: "text/javascript;charset=utf-8" }); function W(s) { let e; try { if (e = p && (self.URL || self.webkitURL).createObjectURL(p), !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 } ); } } class F extends c { constructor(e, t, i, r, g) { super(), this.apiBaseUrl = e, this.chunkSize = t, this.packageID = i, this.packageToken = r, this.masvUserAgent = g, this.terminated = !1, this.onNativeWorkerMessage = (l) => { const { name: a, data: o } = l.data; this.emit(a, { data: o }); }, this.emit(h.Created), this.startWorker(); } startWorker() { this.nativeWorker = new W(), 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, t) { if (this.terminated) throw new Error("Can't use a terminated worker"); this.nativeWorker.postMessage({ name: "Chunk", input: e, spec: t }); } abort() { this.stopWorker(), this.startWorker(); } terminate() { this.terminated = !0, this.emit(h.Terminate), this.clearHandlers(), this.nativeWorker.terminate(); } } class X extends c { constructor(e, t, i, r, g = 6, l) { super(), this.workers = new Array(), this.counter = 0, this.terminated = !1; let a; for (let o = 0; o < g; o++) a = new F( e, t, i, r, l ), a.on("emit", this.bubbleEmit.bind(this)), this.workers.push(a); } createFile(e, t) { const i = this.workers[this.counter % this.workers.length]; if (this.terminated) throw new A(); this.counter++, i.createFile(e, t); } abort() { this.workers.forEach((e) => e.abort()); } terminate() { this.terminated = !0, this.workers.forEach((e) => e.terminate()), this.clearHandlers(); } } const S = "Y2xhc3MgYyB7CiAgY29uc3RydWN0b3IodCwgcywgcikgewogICAgdGhpcy5uYW1lID0gIkFwaUVycm9yIiwgdGhpcy5zdGF0dXNDb2RlID0gdCwgdGhpcy5jb2RlID0gcywgdGhpcy5tZXNzYWdlID0gcjsKICB9Cn0KZnVuY3Rpb24gbShlKSB7CiAgcmV0dXJuIGUgPj0gNDAwICYmIGUgPCA1MDA7Cn0KY29uc3QgUiA9IDEwLCBoID0gMWUzLCBnID0gKCkgPT4gKHsKICByZXRyaWVzOiBSLAogIGRlbGF5OiBoCn0pOwpzZWxmLmN1cnJlbnRSZXF1ZXN0ID0gbnVsbDsKc2VsZi5jdXJyZW50UmVxdWVzdHMgPSBbXTsKc2VsZi5yZXRyeTQwMCA9ICExOwpzZWxmLnJldHJ5VGltZW91dCA9IG51bGw7CmZ1bmN0aW9uIGEoKSB7CiAgbGV0IGU7CiAgaWYgKHNlbGYuY3VycmVudFJlcXVlc3RzLmxlbmd0aCA9PT0gMCB8fCBzZWxmLmN1cnJlbnRSZXF1ZXN0ICE9IG51bGwpCiAgICByZXR1cm47CiAgZSA9IHNlbGYuY3VycmVudFJlcXVlc3RzLnNoaWZ0KCksIGUuaW5wdXQucmV0cnlDb25maWcgPT0gbnVsbCAmJiAoZS5pbnB1dC5yZXRyeUNvbmZpZyA9IGcoKSk7CiAgY29uc3QgdCA9IG5ldyBYTUxIdHRwUmVxdWVzdCgpOwogIHNlbGYuY3VycmVudFJlcXVlc3QgPSB7CiAgICBpbnB1dDogZS5pbnB1dCwKICAgIHhocjogdA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AgICAgICAgIGVycm9yOiB1CiAgICAgICAgfQogICAgICB9KSA6IHNlbGYucG9zdE1lc3NhZ2UoewogICAgICAgIG5hbWU6ICJ3b3JrZXI6ZXJyb3IiLAogICAgICAgIHBheWxvYWQ6IHsKICAgICAgICAgIGlucHV0OiBlLmlucHV0LAogICAgICAgICAgZXJyb3I6IHUKICAgICAgICB9CiAgICAgIH0pOwogICAgfSBlbHNlCiAgICAgIHNlbGYucG9zdE1lc3NhZ2UoewogICAgICAgIG5hbWU6ICJ3b3JrZXI6ZmluaXNoIiwKICAgICAgICBwYXlsb2FkOiB7CiAgICAgICAgICByZXE6IGUuaW5wdXQsCiAgICAgICAgICBib2R5OiB0LnJlc3BvbnNlVGV4dCwKICAgICAgICAgIHN0YXR1c0NvZGU6IGwsCiAgICAgICAgICBoZWFkZXJzOiBwLAogICAgICAgICAgdHJhbnNmZXJyZWQ6IHMKICAgICAgICB9CiAgICAgIH0pLCBzZWxmLmN1cnJlbnRSZXF1ZXN0ID0gbnVsbCwgYSgpOwogIH0sIHQub25lcnJvciA9IGFzeW5jICgpID0+IHsKICAgIGlmIChlLmlucHV0Py5ib2R5ICE9IG51bGwgJiYgZS5pbnB1dC50eXBlID09PSAidXBsb2FkX2ZpbGUiKSB7CiAgICAgIGNvbnN0IG4gPSBlLmlucHV0LmJvZHkuc3RyZWFtKCkuZ2V0UmVhZGVyKCk7CiAgICAgIHRyeSB7CiAgICAgICAgYXdhaXQgbi5yZWFkKCksIGkoZSk7CiAgICAgIH0gY2F0Y2ggKGYpIHsKICAgICAgICBzZWxmLnBvc3RNZXNzYWdlKHsKICAgICAgICAgIG5hbWU6ICJ3b3JrZXI6ZXJyb3IiLAogICAgICAgICAgcGF5bG9hZDogewogICAgICAgICAgICBlcnJvcjogZiwKICAgICAgICAgICAgaW5wdXQ6IGUuaW5wdXQKICAgICAgICAgIH0KICAgICAgICB9KSwgc2VsZi5jdXJyZW50UmVxdWVzdCA9IG51bGwsIGEoKTsKICAgICAgfQogIC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ubWVzc2FnZV0odCk7Cn07Cg==", V = (s) => Uint8Array.from(atob(s), (e) => e.charCodeAt(0)), b = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", V(S)], { type: "text/javascript;charset=utf-8" }); function K(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," + S, { type: "module", name: s?.name } ); } } var I = /* @__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))(I || {}); class H extends c { 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(h.Created); } startWorker(e = !1) { this.nativeWorker = new K(), 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(h.Execute, { data: e }), this.nativeWorker.postMessage({ message: "request", ...e }); } abort() { this.nativeWorker.postMessage({ message: "abort" /* Abort */ }); } terminate() { this.terminated = !0, this.emit(h.Terminate), this.clearHandlers(), this.nativeWorker.terminate(); } } const Y = 1600 * 1e3; class z extends c { constructor(e, t, i, r, g, l = 6, a) { super(), this.apiBaseUrl = e, this.packageID = r, this.packageToken = g, this.poolSize = l, this.masvUserAgent = a, this.apiXhrExecutor = t, this.storageXhrExecutor = i, this.emit(n.Created), this.storageXhrExecutor.on(h.Progress, (o) => this.onStorageProgress(o)), this.storageXhrExecutor.on(h.Abort, (o) => this.onStorageAbort(o)), this.storageXhrExecutor.on(h.Retry, (o) => this.onStorageRetry(o)), this.storageXhrExecutor.on(h.Finish, (o) => this.onStorageFinish(o)), this.storageXhrExecutor.on(h.Error, (o) => this.onStorageError(o)); } upload(e) { const t = e.chunks.filter((i) => !i.isFinished).map((i) => ({ fileId: e.id, sequence: i.index, timeout: Y, ...i.chunk, type: I.UploadFile })); return this.emit(n.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 === I.UploadFile && this.bubbleEmit({ event: n.Progress, target: e.target, data: t }); } onStorageFinish(e) { const t = e.data; t.req.type === I.UploadFile && this.bubbleEmit({ event: n.Chunk, target: e.target, data: t }); } onStorageAbort(e) { const t = e.data; t.type === I.UploadFile && this.bubbleEmit({ event: n.Abort, target: e.target, data: t }); } onStorageRetry(e) { const t = e.data; t.input.type === I.UploadFile && this.bubbleEmit({ event: n.Retry, target: e.target, data: t }); } onStorageError(e) { const t = e.data; this.bubbleEmit({ event: n.Error, target: e.target, data: t }); } } class B extends c { 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 H(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 A(); for (let t of e) this.workers[this.counter++ % this.workers.length].execute(t); } terminate() { this.terminated = !0, this.clearHandlers(), this.stopWorkerPool(); } } let v = 0; const N = Date.now(); function U() { return "randomUUID" in crypto ? crypto.randomUUID() : `${N}_${v++}`; } class L { constructor() { this.queue = {}; } getFile(e) { return this.queue[e]; } addFile(e) { const t = new x(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 g = r.getChunk(t); if (g) return g.setProgress(i), g; } 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 x { constructor({ fileId: e, req: t, file: i, chunks: r, storageType: g, fileExtras: l }) { this.chunks = [], this.running = !1, this.finalized = !1, this.id = e, this.req = t, this.file = i, this.chunks = r.map((a, o) => new E(a, o)), this.chunkSize = t.chunkSize > i.file.size ? i.file.size : t.chunkSize, this.storageType = g, this.fileExtras = l; } setChunkExtras({ headers: e, req: t }) { const i = t.sequence || 0, r = this.chunks.find((l) => l.index === i); if (!r) return; const g = 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: g }); } 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 E { 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, g = i * r; this.ma = i * t + (1 - i) * this.ma, this.v = (1 - i) * (this.v + r * g), 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 u = /* @__PURE__ */ ((s) => (s.Start = "upload_start", s.Stop = "upload_stop", s.Pause = "upload_pause", s.Finish = "upload_finish", s.Continue = "upload_continue", s))(u || {}); const m = 500; class D { 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(m), 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 / (m / 1e3), this.lastSampleAmount = this.transferred, this.moving.push(t, this.instantSpeed), this.movingSpeed = this.moving.movingAverage(), setTimeout(() => { this.debounceAverage = !1; }, m); } 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 C = 6, J = "masv-web", T = "masv-web-uploader", P = "dev"; var G = /* @__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))(G || {}); const d = class d extends c { constructor(e, t, i = "https://api.massive.app", r = 100 << 20, g = `${J}/${P}`, l = 6e4) { super(), this.packageID = e, this.packageToken = t, this.apiBaseUrl = i, this.stallTimeout = l, this.stallTimer = -1, this.performanceStats = new D(), this.version = "2.2.7", this.uploadState = new L(), this.fileQueue = [], this.createQueue = /* @__PURE__ */ new Set(), this.unreadableFiles = /* @__PURE__ */ new Set(), this.status = "idle", this.spec = { max_chunk_count: 1e4, max_chunk_size: 5 * 2 ** 30, // 5 GiB min_chunk_size: 5 * 2 ** 20 // 5 MiB }, this.masvUserAgent = `${g}+${T}/${this.version}`, this.apiXhrExecutor = new B(C), this.storageXhrExecutor = new B(C, !0), this.fchunker = new X( i, r, e, t, C, this.masvUserAgent ), this.fuploader = new z( i, this.apiXhrExecutor, this.storageXhrExecutor, e, t, C, this.masvUserAgent ), this.fchunker.on(h.ApiError, (a) => this.onUploadApiError(a)), this.fchunker.on(h.Finish, (a) => this.onChunkFinish(a)), this.fuploader.on(n.Progress, (a) => { this.onUploadProgress(a); }), this.fuploader.on(n.Chunk, (a) => this.onChunkUploadFinish(a)), this.fuploader.on(n.Abort, (a) => this.onUploadAbort(a)), this.fuploader.on(n.Retry, (a) => this.onUploadRetry(a)), this.fuploader.on(n.Error, (a) => this.onUploadError(a)), this.fchunker.on("emit", this.bubbleEmit.bind(this)), this.fuploader.on("emit", this.bubbleEmit.bind(this)), this.apiXhrExecutor.on(h.ApiError, (a) => this.onUploadApiError(a)), this.apiXhrExecutor.on(h.Finish, (a) => this.onAPIFinish(a)); } resetStallTimer() { clearTimeout(this.stallTimer), this.stallTimer = setTimeout(() => { this.emit(n.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 >= C ? !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(n.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((g) => { this.setUnreadableFile(t, g.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); } onUploadApiError({ data: e }) { const t = e.error; let { code: i } = t; this.emit(n.Error, { data: { input: e.input, apiError: t } }), f(i) && (this.fuploader.abort(), this.fchunker.abort(), this.terminate()); } 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 g = r.getChunk(i); this.performanceStats.addReceived(g.totalBytes), r.setChunkExtras(e), r.isFinished && (this.emit(n.File, { data: r }), this.finalizeFile(r)); } this.uploadNext(); } onAPIFinish({ data: e }) { const t = [200, 201, 204]; if (e.req.type === I.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(n.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 === I.FinalizePackage && (t.includes(e.statusCode) ? (this.performanceStats.mark(u.Finish), this.emit(n.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 === I.CancelPackage && this.terminate(); } setUnreadableFile(e, t) { this.emit(n.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: I.Error }), this.emit(n.Stalled), clearTimeout(this.stallTimer); } async 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.spec = await this.getSpec(), 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(u.Continue) : this.performanceStats.mark(u.Start), this.uploadState.totalChunksInProgress > 0) { const t = Object.values(this.uploadState.queue); for (let i of t) this.fuploader.upload(i); } else this.uploadNext(); } async getSpec(e = 0) { let t; try { t = await fetch(`${this.apiBaseUrl}/v1/system/packages/spec`, { method: "GET", headers: { "Content-Type": "application/json", "Masv-User-Agent": this.masvUserAgent } }); } catch { } if (t) { const i = await t.json(); if (t.ok) return i; if (t.status >= 500 && e < 5) return this.getSpec(e++); } return { max_chunk_count: 1e4, max_chunk_size: 5 * 2 ** 30, // 5 GiB min_chunk_size: 5 * 2 ** 20 // 5 MiB }; } 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, this.spec)); } stop() { this.status = "idle", this.performanceStats.mark(u.Stop); } pause() { this.status !== "paused" && (clearTimeout(this.stallTimer), this.status = "paused", this.performanceStats.mark(u.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: I.CancelPackage }); } finalizeFile(e) { if (e.validateMissingEtags().length > 0) { this.fuploader.upload(e); return; } const { id: i, fileExtras: r, chunkSize: g, file: l, chunks: a } = e, o = a.map((w) => w.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: g, size: l.file.size, chunkExtras: o }), timeout: 6e4, fileId: i, type: I.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: I.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) }; } }; d.UploaderEvents = n, d.States = G; let Z = d; export { Z as Uploader };