Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@mux/upchunk

Package Overview
Dependencies
Maintainers
2
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mux/upchunk - npm Package Compare versions

Comparing version 2.4.0 to 2.5.0

6

dist/upchunk.cjs.js

@@ -1,4 +0,4 @@

var Se=Object.create;var S=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fe=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},x=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _e(e))!Be.call(t,s)&&s!==n&&S(t,s,{get:()=>e[s],enumerable:!(r=ke(e,s))||r.enumerable});return t};var Ie=(t,e,n)=>(n=t!=null?Se(Le(t)):{},x(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),Ne=t=>x(S({},"__esModule",{value:!0}),t);var ge=P((yt,de)=>{var A;typeof window!="undefined"?A=window:typeof global!="undefined"?A=global:typeof self!="undefined"?A=self:A={};de.exports=A});var be=P((wt,me)=>{me.exports=nt;var tt=Object.prototype.toString;function nt(t){if(!t)return!1;var e=tt.call(t);return e==="[object Function]"||typeof t=="function"&&e!=="[object RegExp]"||typeof window!="undefined"&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)}});var ve=P((Ct,Ee)=>{var H=function(t){return t.replace(/^\s+|\s+$/g,"")},rt=function(t){return Object.prototype.toString.call(t)==="[object Array]"};Ee.exports=function(t){if(!t)return{};for(var e={},n=H(t).split(`
`),r=0;r<n.length;r++){var s=n[r],a=s.indexOf(":"),o=H(s.slice(0,a)).toLowerCase(),i=H(s.slice(a+1));typeof e[o]=="undefined"?e[o]=i:rt(e[o])?e[o].push(i):e[o]=[e[o],i]}return e}});var we=P((Rt,ye)=>{ye.exports=it;var st=Object.prototype.hasOwnProperty;function it(){for(var t={},e=0;e<arguments.length;e++){var n=arguments[e];for(var r in n)st.call(n,r)&&(t[r]=n[r])}return t}});var Pe=P((Tt,U)=>{"use strict";var Ce=ge(),at=be(),ot=ve(),ut=we();U.exports=b;U.exports.default=b;b.XMLHttpRequest=Ce.XMLHttpRequest||pt;b.XDomainRequest="withCredentials"in new b.XMLHttpRequest?b.XMLHttpRequest:Ce.XDomainRequest;lt(["get","put","post","patch","head","delete"],function(t){b[t==="delete"?"del":t]=function(e,n,r){return n=Re(e,n,r),n.method=t.toUpperCase(),Te(n)}});function lt(t,e){for(var n=0;n<t.length;n++)e(t[n])}function ct(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function Re(t,e,n){var r=t;return at(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=ut(e,{uri:t}),r.callback=n,r}function b(t,e,n){return e=Re(t,e,n),Te(e)}function Te(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(y,O,Oe){e||(e=!0,t.callback(y,O,Oe))};function r(){i.readyState===4&&setTimeout(o,0)}function s(){var u=void 0;if(i.response?u=i.response:u=i.responseText||ft(i),X)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(B),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,z)}function o(){if(!f){var u;clearTimeout(B),t.useXDR&&i.status===void 0?u=200:u=i.status===1223?204:i.status;var y=z,O=null;return u!==0?(y={body:s(),statusCode:u,method:g,headers:{},url:E,rawRequest:i},i.getAllResponseHeaders&&(y.headers=ot(i.getAllResponseHeaders()))):O=new Error("Internal XMLHttpRequest Error"),n(O,y,y.body)}}var i=t.xhr||null;i||(t.cors||t.useXDR?i=new b.XDomainRequest:i=new b.XMLHttpRequest);var c,f,E=i.url=t.uri||t.url,g=i.method=t.method||"GET",C=t.body||t.data,m=i.headers=t.headers||{},L=!!t.sync,X=!1,B,z={body:void 0,headers:{},statusCode:0,method:g,url:E,rawRequest:i};if("json"in t&&t.json!==!1&&(X=!0,m.accept||m.Accept||(m.Accept="application/json"),g!=="GET"&&g!=="HEAD"&&(m["content-type"]||m["Content-Type"]||(m["Content-Type"]="application/json"),C=JSON.stringify(t.json===!0?C:t.json))),i.onreadystatechange=r,i.onload=o,i.onerror=a,i.onprogress=function(){},i.onabort=function(){f=!0},i.ontimeout=a,i.open(g,E,!L,t.username,t.password),L||(i.withCredentials=!!t.withCredentials),!L&&t.timeout>0&&(B=setTimeout(function(){if(!f){f=!0,i.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),i.setRequestHeader)for(c in m)m.hasOwnProperty(c)&&i.setRequestHeader(c,m[c]);else if(t.headers&&!ct(t.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in t&&(i.responseType=t.responseType),"beforeSend"in t&&typeof t.beforeSend=="function"&&t.beforeSend(i),i.send(C||null),i}function ft(t){try{if(t.responseType==="document")return t.responseXML;var e=t.responseXML&&t.responseXML.documentElement.nodeName==="parsererror";if(t.responseType===""&&!e)return t.responseXML}catch{}return null}function pt(){}});var mt={};Fe(mt,{UpChunk:()=>_,createUpload:()=>gt});module.exports=Ne(mt);function M(t,e,...n){if(!t)throw new TypeError(ee(e,n))}function ee(t,e){let n=0;return t.replace(/%[os]/gu,()=>te(e[n++]))}function te(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var W;function De(t){try{let e=t instanceof Error?t:new Error(te(t));if(W){W(e);return}if(typeof dispatchEvent=="function"&&typeof ErrorEvent=="function")dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}));else if(typeof process!="undefined"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)}catch{}}var p=typeof window!="undefined"?window:typeof self!="undefined"?self:typeof global!="undefined"?global:typeof globalThis!="undefined"?globalThis:void 0,V;var h=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if(V){V({...this,args:e});return}let r=((n=new Error().stack)!==null&&n!==void 0?n:"").replace(/^(?:.+?\n){2}/gu,`
`);console.warn(this.message,...e,r)}catch{}}},je=new h("W01","Unable to initialize event under dispatching."),Me=new h("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),He=new h("W03","Assigning any truthy value to 'returnValue' property has no effect."),Ue=new h("W04","Unable to preventDefault on non-cancelable events."),Xe=new h("W05","Unable to preventDefault inside passive event listener invocation."),ze=new h("W06","An event listener wasn't added because it has been added already: %o, %o"),F=new h("W07","The %o option value was abandoned because the event listener wasn't added as duplicated."),q=new h("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),Et=new h("W09","Event attribute handler must be a function: %o"),d=class{static get NONE(){return $}static get CAPTURING_PHASE(){return G}static get AT_TARGET(){return Y}static get BUBBLING_PHASE(){return J}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};j.set(this,{type:String(e),bubbles:Boolean(r.bubbles),cancelable:Boolean(r.cancelable),composed:Boolean(r.composed),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1,inPassiveListenerFlag:!1,dispatchFlag:!1,timeStamp:Date.now()})}get type(){return l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return $}get CAPTURING_PHASE(){return G}get AT_TARGET(){return Y}get BUBBLING_PHASE(){return J}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:Me.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?He.warn():K(l(this))}preventDefault(){K(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let s=l(this);if(s.dispatchFlag){je.warn();return}j.set(this,{...s,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},$=0,G=1,Y=2,J=3,j=new WeakMap;function l(t,e="this"){let n=j.get(t);return M(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function K(t){if(t.inPassiveListenerFlag){Xe.warn();return}if(!t.cancelable){Ue.warn();return}t.canceledFlag=!0}Object.defineProperty(d,"NONE",{enumerable:!0});Object.defineProperty(d,"CAPTURING_PHASE",{enumerable:!0});Object.defineProperty(d,"AT_TARGET",{enumerable:!0});Object.defineProperty(d,"BUBBLING_PHASE",{enumerable:!0});var I=Object.getOwnPropertyNames(d.prototype);for(let t=0;t<I.length;++t)I[t]!=="constructor"&&Object.defineProperty(d.prototype,I[t],{enumerable:!0});typeof p!="undefined"&&typeof p.Event!="undefined"&&Object.setPrototypeOf(d.prototype,p.Event.prototype);function xe(t){return p.DOMException?new p.DOMException(t,"InvalidStateError"):(R==null&&(R=class ne extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,ne)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(R.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),Z(R),Z(R.prototype)),new R(t))}var R,Q={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25};function Z(t){let e=Object.keys(Q);for(let n=0;n<e.length;++n){let r=e[n],s=Q[r];Object.defineProperty(t,r,{get(){return s},configurable:!0,enumerable:!0})}}var T=class extends d{static wrap(e){return new(se(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),re.set(this,{original:e});let n=Object.keys(e);for(let r=0;r<n.length;++r){let s=n[r];s in this||Object.defineProperty(this,s,ie(e,s))}}stopPropagation(){super.stopPropagation();let{original:e}=v(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=v(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=v(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=v(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=v(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=v(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},re=new WeakMap;function v(t){let e=re.get(t);return M(e!=null,"'this' is expected an Event object, but got",t),e}var k=new WeakMap;k.set(Object.prototype,T);typeof p!="undefined"&&typeof p.Event!="undefined"&&k.set(p.Event.prototype,T);function se(t){let e=Object.getPrototypeOf(t);if(e==null)return T;let n=k.get(e);return n==null&&(n=We(se(e),e),k.set(e,n)),n}function We(t,e){class n extends t{}let r=Object.keys(e);for(let s=0;s<r.length;++s)Object.defineProperty(n.prototype,r[s],ie(e,r[s]));return n}function ie(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=v(this).original,s=r[e];return typeof s=="function"?s.bind(r):s},set(r){let s=v(this).original;s[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function Ve(t,e,n,r,s,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:s,signalListener:a}}function qe(t){t.flags|=8}function ae(t){return(t.flags&1)===1}function oe(t){return(t.flags&2)===2}function ue(t){return(t.flags&4)===4}function $e(t){return(t.flags&8)===8}function Ge({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){De(r)}}function le({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&ae(t[r])===n)return r;return-1}function Ye(t,e,n,r,s,a){let o;a&&(o=ce.bind(null,t,e,n),a.addEventListener("abort",o));let i=Ve(e,n,r,s,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,i]):t.listeners.push(i),i}function ce(t,e,n){let r=le(t,e,n);return r!==-1?fe(t,r):!1}function fe(t,e,n=!1){let r=t.listeners[e];return qe(r),r.signal&&r.signal.removeEventListener("abort",r.signalListener),t.cow&&!n?(t.cow=!1,t.listeners=t.listeners.filter((s,a)=>a!==e),!1):(t.listeners.splice(e,1),!0)}function Je(){return Object.create(null)}function Ke(t,e){var n;return(n=t[e])!==null&&n!==void 0?n:t[e]={attrCallback:void 0,attrListener:void 0,cow:!1,listeners:[]}}var w=class{constructor(){pe.set(this,Je())}addEventListener(e,n,r){let s=N(this),{callback:a,capture:o,once:i,passive:c,signal:f,type:E}=Qe(e,n,r);if(a==null||(f==null?void 0:f.aborted))return;let g=Ke(s,E),C=le(g,a,o);if(C!==-1){et(g.listeners[C],c,i,f);return}Ye(g,a,o,c,i,f)}removeEventListener(e,n,r){let s=N(this),{callback:a,capture:o,type:i}=Ze(e,n,r),c=s[i];a!=null&&c&&ce(c,a,o)}dispatchEvent(e){let n=N(this)[String(e.type)];if(n==null)return!0;let r=e instanceof d?e:T.wrap(e),s=l(r,"event");if(s.dispatchFlag)throw xe("This event has been in dispatching.");if(s.dispatchFlag=!0,s.target=s.currentTarget=this,!s.stopPropagationFlag){let{cow:a,listeners:o}=n;n.cow=!0;for(let i=0;i<o.length;++i){let c=o[i];if(!$e(c)&&(ue(c)&&fe(n,i,!a)&&(i-=1),s.inPassiveListenerFlag=oe(c),Ge(c,this,r),s.inPassiveListenerFlag=!1,s.stopImmediatePropagationFlag))break}a||(n.cow=!1)}return s.target=null,s.currentTarget=null,s.stopImmediatePropagationFlag=!1,s.stopPropagationFlag=!1,s.dispatchFlag=!1,!s.canceledFlag}},pe=new WeakMap;function N(t,e="this"){let n=pe.get(t);return M(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function Qe(t,e,n){var r;return he(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture),passive:Boolean(n.passive),once:Boolean(n.once),signal:(r=n.signal)!==null&&r!==void 0?r:void 0}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n),passive:!1,once:!1,signal:void 0}}function Ze(t,e,n){return he(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture)}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n)}}function he(t){if(!(typeof t=="function"||typeof t=="object"&&t!==null&&typeof t.handleEvent=="function")){if(t==null||typeof t=="object"){q.warn(t);return}throw new TypeError(ee(q.message,[t]))}}function et(t,e,n,r){ze.warn(ae(t)?"capture":"bubble",t.callback),oe(t)!==e&&F.warn("passive"),ue(t)!==n&&F.warn("once"),t.signal!==r&&F.warn("signal")}var D=Object.getOwnPropertyNames(w.prototype);for(let t=0;t<D.length;++t)D[t]!=="constructor"&&Object.defineProperty(w.prototype,D[t],{enumerable:!0});typeof p!="undefined"&&typeof p.EventTarget!="undefined"&&Object.setPrototypeOf(w.prototype,p.EventTarget.prototype);var Ae=Ie(Pe()),ht=[200,201,202,204,308],dt=[408,502,503,504],_=class{constructor(e){this.endpoint=e.endpoint,this.file=e.file,this.headers=e.headers||{},this.method=e.method||"PUT",this.chunkSize=e.chunkSize||30720,this.attempts=e.attempts||5,this.delayBeforeAttempt=e.delayBeforeAttempt||1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.chunkByteSize=this.chunkSize*1024,this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.attemptCount=0,this.offline=!1,this.paused=!1,this.success=!1,this.reader=new FileReader,this.eventTarget=new w,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}on(e,n){this.eventTarget.addEventListener(e,n)}abort(){var e;this.pause(),(e=this.currentXhr)==null||e.abort()}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.sendChunks())}dispatch(e,n){let r=new CustomEvent(e,{detail:n});this.eventTarget.dispatchEvent(r)}validateOptions(){if(!this.endpoint||typeof this.endpoint!="function"&&typeof this.endpoint!="string")throw new TypeError("endpoint must be defined as a string or a function that returns a promise");if(!(this.file instanceof File))throw new TypeError("file must be a File object");if(this.headers&&typeof this.headers!="object")throw new TypeError("headers must be null or an object");if(this.chunkSize&&(typeof this.chunkSize!="number"||this.chunkSize<=0||this.chunkSize%256!==0))throw new TypeError("chunkSize must be a positive number in multiples of 256");if(this.maxFileBytes>0&&this.maxFileBytes<this.file.size)throw new Error(`file size exceeds maximum (${this.file.size} > ${this.maxFileBytes})`);if(this.attempts&&(typeof this.attempts!="number"||this.attempts<=0))throw new TypeError("retries must be a positive number");if(this.delayBeforeAttempt&&(typeof this.delayBeforeAttempt!="number"||this.delayBeforeAttempt<0))throw new TypeError("delayBeforeAttempt must be a positive number")}getEndpoint(){return typeof this.endpoint=="string"?(this.endpointValue=this.endpoint,Promise.resolve(this.endpoint)):this.endpoint(this.file).then(e=>(this.endpointValue=e,this.endpointValue))}getChunk(){return new Promise(e=>{let n=this.totalChunks===1?this.file.size:this.chunkByteSize,r=n*this.chunkCount;this.reader.onload=()=>{this.reader.result!==null&&(this.chunk=new Blob([this.reader.result],{type:"application/octet-stream"})),e()},this.reader.readAsArrayBuffer(this.file.slice(r,r+n))})}xhrPromise(e){let n=r=>{r.upload.onprogress=s=>{var E;let a=100/this.totalChunks,o=a*this.file.size,i=a*this.chunkCount,f=s.loaded/((E=s.total)!=null?E:o)*a;this.dispatch("progress",Math.min(i+f,100))}};return new Promise((r,s)=>{this.currentXhr=(0,Ae.default)({...e,beforeSend:n},(a,o)=>(this.currentXhr=void 0,a?s(a):r(o)))})}sendChunk(){let e=this.chunkCount*this.chunkByteSize,n=e+this.chunk.size-1,r={...this.headers,"Content-Type":this.file.type,"Content-Range":`bytes ${e}-${n}/${this.file.size}`};return this.dispatch("attempt",{chunkNumber:this.chunkCount,chunkSize:this.chunk.size}),this.xhrPromise({headers:r,url:this.endpointValue,method:this.method,body:this.chunk})}manageRetries(){if(this.attemptCount<this.attempts){setTimeout(()=>this.sendChunks(),this.delayBeforeAttempt*1e3),this.dispatch("attemptFailure",{message:`An error occured uploading chunk ${this.chunkCount}. ${this.attempts-this.attemptCount} retries left.`,chunkNumber:this.chunkCount,attemptsLeft:this.attempts-this.attemptCount});return}this.dispatch("error",{message:`An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`,chunk:this.chunkCount,attempts:this.attemptCount})}sendChunks(){this.paused||this.offline||this.success||this.getChunk().then(()=>(this.attemptCount=this.attemptCount+1,this.sendChunk())).then(e=>{if(ht.includes(e.statusCode)){this.dispatch("chunkSuccess",{chunk:this.chunkCount,attempts:this.attemptCount,response:e}),this.attemptCount=0,this.chunkCount=this.chunkCount+1,this.chunkCount<this.totalChunks?this.sendChunks():(this.success=!0,this.dispatch("success"));let r=this.chunkCount/this.totalChunks*this.file.size,s=100*r/this.file.size;this.dispatch("progress",s)}else if(dt.includes(e.statusCode)){if(this.paused||this.offline)return;this.manageRetries()}else{if(this.paused||this.offline)return;this.dispatch("error",{message:`Server responded with ${e.statusCode}. Stopping upload.`,chunkNumber:this.chunkCount,attempts:this.attemptCount})}}).catch(e=>{this.paused||this.offline||this.manageRetries()})}},gt=t=>new _(t);
var Ae=Object.create;var A=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Be=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},X=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ze(e))!Le.call(t,i)&&i!==n&&A(t,i,{get:()=>e[i],enumerable:!(r=Oe(e,i))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?Ae(_e(t)):{},X(e||!t||!t.__esModule?A(n,"default",{value:t,enumerable:!0}):n,t)),Ie=t=>X(A({},"__esModule",{value:!0}),t);var me=R((yt,de)=>{var T;typeof window!="undefined"?T=window:typeof global!="undefined"?T=global:typeof self!="undefined"?T=self:T={};de.exports=T});var be=R((Ct,ge)=>{ge.exports=nt;var tt=Object.prototype.toString;function nt(t){if(!t)return!1;var e=tt.call(t);return e==="[object Function]"||typeof t=="function"&&e!=="[object RegExp]"||typeof window!="undefined"&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)}});var ve=R((St,Ee)=>{var M=function(t){return t.replace(/^\s+|\s+$/g,"")},rt=function(t){return Object.prototype.toString.call(t)==="[object Array]"};Ee.exports=function(t){if(!t)return{};for(var e={},n=M(t).split(`
`),r=0;r<n.length;r++){var i=n[r],a=i.indexOf(":"),o=M(i.slice(0,a)).toLowerCase(),s=M(i.slice(a+1));typeof e[o]=="undefined"?e[o]=s:rt(e[o])?e[o].push(s):e[o]=[e[o],s]}return e}});var Ce=R((kt,ye)=>{ye.exports=st;var it=Object.prototype.hasOwnProperty;function st(){for(var t={},e=0;e<arguments.length;e++){var n=arguments[e];for(var r in n)it.call(n,r)&&(t[r]=n[r])}return t}});var Re=R((wt,j)=>{"use strict";var Se=me(),at=be(),ot=ve(),ut=Ce();j.exports=b;j.exports.default=b;b.XMLHttpRequest=Se.XMLHttpRequest||ft;b.XDomainRequest="withCredentials"in new b.XMLHttpRequest?b.XMLHttpRequest:Se.XDomainRequest;lt(["get","put","post","patch","head","delete"],function(t){b[t==="delete"?"del":t]=function(e,n,r){return n=ke(e,n,r),n.method=t.toUpperCase(),we(n)}});function lt(t,e){for(var n=0;n<t.length;n++)e(t[n])}function ct(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function ke(t,e,n){var r=t;return at(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=ut(e,{uri:t}),r.callback=n,r}function b(t,e,n){return e=ke(t,e,n),we(e)}function we(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(y,P,Pe){e||(e=!0,t.callback(y,P,Pe))};function r(){s.readyState===4&&setTimeout(o,0)}function i(){var u=void 0;if(s.response?u=s.response:u=s.responseText||ht(s),H)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(L),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,U)}function o(){if(!h){var u;clearTimeout(L),t.useXDR&&s.status===void 0?u=200:u=s.status===1223?204:s.status;var y=U,P=null;return u!==0?(y={body:i(),statusCode:u,method:m,headers:{},url:E,rawRequest:s},s.getAllResponseHeaders&&(y.headers=ot(s.getAllResponseHeaders()))):P=new Error("Internal XMLHttpRequest Error"),n(P,y,y.body)}}var s=t.xhr||null;s||(t.cors||t.useXDR?s=new b.XDomainRequest:s=new b.XMLHttpRequest);var c,h,E=s.url=t.uri||t.url,m=s.method=t.method||"GET",S=t.body||t.data,g=s.headers=t.headers||{},_=!!t.sync,H=!1,L,U={body:void 0,headers:{},statusCode:0,method:m,url:E,rawRequest:s};if("json"in t&&t.json!==!1&&(H=!0,g.accept||g.Accept||(g.Accept="application/json"),m!=="GET"&&m!=="HEAD"&&(g["content-type"]||g["Content-Type"]||(g["Content-Type"]="application/json"),S=JSON.stringify(t.json===!0?S:t.json))),s.onreadystatechange=r,s.onload=o,s.onerror=a,s.onprogress=function(){},s.onabort=function(){h=!0},s.ontimeout=a,s.open(m,E,!_,t.username,t.password),_||(s.withCredentials=!!t.withCredentials),!_&&t.timeout>0&&(L=setTimeout(function(){if(!h){h=!0,s.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),s.setRequestHeader)for(c in g)g.hasOwnProperty(c)&&s.setRequestHeader(c,g[c]);else if(t.headers&&!ct(t.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in t&&(s.responseType=t.responseType),"beforeSend"in t&&typeof t.beforeSend=="function"&&t.beforeSend(s),s.send(S||null),s}function ht(t){try{if(t.responseType==="document")return t.responseXML;var e=t.responseXML&&t.responseXML.documentElement.nodeName==="parsererror";if(t.responseType===""&&!e)return t.responseXML}catch{}return null}function ft(){}});var gt={};Be(gt,{UpChunk:()=>z,createUpload:()=>mt});module.exports=Ie(gt);function D(t,e,...n){if(!t)throw new TypeError(ee(e,n))}function ee(t,e){let n=0;return t.replace(/%[os]/gu,()=>te(e[n++]))}function te(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var W;function Fe(t){try{let e=t instanceof Error?t:new Error(te(t));if(W){W(e);return}if(typeof dispatchEvent=="function"&&typeof ErrorEvent=="function")dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}));else if(typeof process!="undefined"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)}catch{}}var f=typeof window!="undefined"?window:typeof self!="undefined"?self:typeof global!="undefined"?global:typeof globalThis!="undefined"?globalThis:void 0,$;var p=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if($){$({...this,args:e});return}let r=((n=new Error().stack)!==null&&n!==void 0?n:"").replace(/^(?:.+?\n){2}/gu,`
`);console.warn(this.message,...e,r)}catch{}}},Ne=new p("W01","Unable to initialize event under dispatching."),De=new p("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),Me=new p("W03","Assigning any truthy value to 'returnValue' property has no effect."),je=new p("W04","Unable to preventDefault on non-cancelable events."),He=new p("W05","Unable to preventDefault inside passive event listener invocation."),Ue=new p("W06","An event listener wasn't added because it has been added already: %o, %o"),B=new p("W07","The %o option value was abandoned because the event listener wasn't added as duplicated."),q=new p("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),Et=new p("W09","Event attribute handler must be a function: %o"),d=class{static get NONE(){return V}static get CAPTURING_PHASE(){return G}static get AT_TARGET(){return Y}static get BUBBLING_PHASE(){return J}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};N.set(this,{type:String(e),bubbles:Boolean(r.bubbles),cancelable:Boolean(r.cancelable),composed:Boolean(r.composed),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1,inPassiveListenerFlag:!1,dispatchFlag:!1,timeStamp:Date.now()})}get type(){return l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return V}get CAPTURING_PHASE(){return G}get AT_TARGET(){return Y}get BUBBLING_PHASE(){return J}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:De.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?Me.warn():K(l(this))}preventDefault(){K(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let i=l(this);if(i.dispatchFlag){Ne.warn();return}N.set(this,{...i,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},V=0,G=1,Y=2,J=3,N=new WeakMap;function l(t,e="this"){let n=N.get(t);return D(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function K(t){if(t.inPassiveListenerFlag){He.warn();return}if(!t.cancelable){je.warn();return}t.canceledFlag=!0}Object.defineProperty(d,"NONE",{enumerable:!0});Object.defineProperty(d,"CAPTURING_PHASE",{enumerable:!0});Object.defineProperty(d,"AT_TARGET",{enumerable:!0});Object.defineProperty(d,"BUBBLING_PHASE",{enumerable:!0});var x=Object.getOwnPropertyNames(d.prototype);for(let t=0;t<x.length;++t)x[t]!=="constructor"&&Object.defineProperty(d.prototype,x[t],{enumerable:!0});typeof f!="undefined"&&typeof f.Event!="undefined"&&Object.setPrototypeOf(d.prototype,f.Event.prototype);function Xe(t){return f.DOMException?new f.DOMException(t,"InvalidStateError"):(k==null&&(k=class ne extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,ne)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(k.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),Z(k),Z(k.prototype)),new k(t))}var k,Q={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25};function Z(t){let e=Object.keys(Q);for(let n=0;n<e.length;++n){let r=e[n],i=Q[r];Object.defineProperty(t,r,{get(){return i},configurable:!0,enumerable:!0})}}var w=class extends d{static wrap(e){return new(ie(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),re.set(this,{original:e});let n=Object.keys(e);for(let r=0;r<n.length;++r){let i=n[r];i in this||Object.defineProperty(this,i,se(e,i))}}stopPropagation(){super.stopPropagation();let{original:e}=v(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=v(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=v(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=v(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=v(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=v(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},re=new WeakMap;function v(t){let e=re.get(t);return D(e!=null,"'this' is expected an Event object, but got",t),e}var O=new WeakMap;O.set(Object.prototype,w);typeof f!="undefined"&&typeof f.Event!="undefined"&&O.set(f.Event.prototype,w);function ie(t){let e=Object.getPrototypeOf(t);if(e==null)return w;let n=O.get(e);return n==null&&(n=We(ie(e),e),O.set(e,n)),n}function We(t,e){class n extends t{}let r=Object.keys(e);for(let i=0;i<r.length;++i)Object.defineProperty(n.prototype,r[i],se(e,r[i]));return n}function se(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=v(this).original,i=r[e];return typeof i=="function"?i.bind(r):i},set(r){let i=v(this).original;i[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function $e(t,e,n,r,i,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:i,signalListener:a}}function qe(t){t.flags|=8}function ae(t){return(t.flags&1)===1}function oe(t){return(t.flags&2)===2}function ue(t){return(t.flags&4)===4}function Ve(t){return(t.flags&8)===8}function Ge({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){Fe(r)}}function le({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&ae(t[r])===n)return r;return-1}function Ye(t,e,n,r,i,a){let o;a&&(o=ce.bind(null,t,e,n),a.addEventListener("abort",o));let s=$e(e,n,r,i,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,s]):t.listeners.push(s),s}function ce(t,e,n){let r=le(t,e,n);return r!==-1?he(t,r):!1}function he(t,e,n=!1){let r=t.listeners[e];return qe(r),r.signal&&r.signal.removeEventListener("abort",r.signalListener),t.cow&&!n?(t.cow=!1,t.listeners=t.listeners.filter((i,a)=>a!==e),!1):(t.listeners.splice(e,1),!0)}function Je(){return Object.create(null)}function Ke(t,e){var n;return(n=t[e])!==null&&n!==void 0?n:t[e]={attrCallback:void 0,attrListener:void 0,cow:!1,listeners:[]}}var C=class{constructor(){fe.set(this,Je())}addEventListener(e,n,r){let i=I(this),{callback:a,capture:o,once:s,passive:c,signal:h,type:E}=Qe(e,n,r);if(a==null||(h==null?void 0:h.aborted))return;let m=Ke(i,E),S=le(m,a,o);if(S!==-1){et(m.listeners[S],c,s,h);return}Ye(m,a,o,c,s,h)}removeEventListener(e,n,r){let i=I(this),{callback:a,capture:o,type:s}=Ze(e,n,r),c=i[s];a!=null&&c&&ce(c,a,o)}dispatchEvent(e){let n=I(this)[String(e.type)];if(n==null)return!0;let r=e instanceof d?e:w.wrap(e),i=l(r,"event");if(i.dispatchFlag)throw Xe("This event has been in dispatching.");if(i.dispatchFlag=!0,i.target=i.currentTarget=this,!i.stopPropagationFlag){let{cow:a,listeners:o}=n;n.cow=!0;for(let s=0;s<o.length;++s){let c=o[s];if(!Ve(c)&&(ue(c)&&he(n,s,!a)&&(s-=1),i.inPassiveListenerFlag=oe(c),Ge(c,this,r),i.inPassiveListenerFlag=!1,i.stopImmediatePropagationFlag))break}a||(n.cow=!1)}return i.target=null,i.currentTarget=null,i.stopImmediatePropagationFlag=!1,i.stopPropagationFlag=!1,i.dispatchFlag=!1,!i.canceledFlag}},fe=new WeakMap;function I(t,e="this"){let n=fe.get(t);return D(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function Qe(t,e,n){var r;return pe(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture),passive:Boolean(n.passive),once:Boolean(n.once),signal:(r=n.signal)!==null&&r!==void 0?r:void 0}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n),passive:!1,once:!1,signal:void 0}}function Ze(t,e,n){return pe(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture)}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n)}}function pe(t){if(!(typeof t=="function"||typeof t=="object"&&t!==null&&typeof t.handleEvent=="function")){if(t==null||typeof t=="object"){q.warn(t);return}throw new TypeError(ee(q.message,[t]))}}function et(t,e,n,r){Ue.warn(ae(t)?"capture":"bubble",t.callback),oe(t)!==e&&B.warn("passive"),ue(t)!==n&&B.warn("once"),t.signal!==r&&B.warn("signal")}var F=Object.getOwnPropertyNames(C.prototype);for(let t=0;t<F.length;++t)F[t]!=="constructor"&&Object.defineProperty(C.prototype,F[t],{enumerable:!0});typeof f!="undefined"&&typeof f.EventTarget!="undefined"&&Object.setPrototypeOf(C.prototype,f.EventTarget.prototype);var Te=xe(Re()),pt=[200,201,202,204,308],dt=[408,502,503,504],z=class{constructor(e){this.endpoint=e.endpoint,this.file=e.file,this.headers=e.headers||{},this.method=e.method||"PUT",this.chunkSize=e.chunkSize||30720,this.attempts=e.attempts||5,this.delayBeforeAttempt=e.delayBeforeAttempt||1,this.dynamicChunkSize=e.dynamicChunkSize||!1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.chunkByteSize=this.chunkSize*1024,this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.attemptCount=0,this.offline=!1,this.paused=!1,this.success=!1,this.nextChunkRangeStart=0,this.maxChunkSize=e.maxChunkSize||512e3,this.minChunkSize=e.minChunkSize||256,this.reader=new FileReader,this.eventTarget=new C,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}on(e,n){this.eventTarget.addEventListener(e,n)}abort(){var e;this.pause(),(e=this.currentXhr)==null||e.abort()}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.sendChunks())}dispatch(e,n){let r=new CustomEvent(e,{detail:n});this.eventTarget.dispatchEvent(r)}validateOptions(){if(!this.endpoint||typeof this.endpoint!="function"&&typeof this.endpoint!="string")throw new TypeError("endpoint must be defined as a string or a function that returns a promise");if(!(this.file instanceof File))throw new TypeError("file must be a File object");if(this.headers&&typeof this.headers!="object")throw new TypeError("headers must be null or an object");if(this.chunkSize&&(typeof this.chunkSize!="number"||this.chunkSize<256||this.chunkSize%256!==0||this.chunkSize<this.minChunkSize||this.chunkSize>this.maxChunkSize))throw new TypeError(`chunkSize must be a positive number in multiples of 256, between ${this.minChunkSize} and ${this.maxChunkSize}`);if(this.maxChunkSize&&(typeof this.maxChunkSize!="number"||this.maxChunkSize<256||this.maxChunkSize%256!==0||this.maxChunkSize<this.chunkSize||this.maxChunkSize<this.minChunkSize))throw new TypeError(`maxChunkSize must be a positive number in multiples of 256, and larger than or equal to both ${this.minChunkSize} and ${this.chunkSize}`);if(this.minChunkSize&&(typeof this.minChunkSize!="number"||this.minChunkSize<256||this.minChunkSize%256!==0||this.minChunkSize>this.chunkSize||this.minChunkSize>this.maxChunkSize))throw new TypeError(`minChunkSize must be a positive number in multiples of 256, and smaller than ${this.chunkSize} and ${this.maxChunkSize}`);if(this.maxFileBytes>0&&this.maxFileBytes<this.file.size)throw new Error(`file size exceeds maximum (${this.file.size} > ${this.maxFileBytes})`);if(this.attempts&&(typeof this.attempts!="number"||this.attempts<=0))throw new TypeError("retries must be a positive number");if(this.delayBeforeAttempt&&(typeof this.delayBeforeAttempt!="number"||this.delayBeforeAttempt<0))throw new TypeError("delayBeforeAttempt must be a positive number")}getEndpoint(){return typeof this.endpoint=="string"?(this.endpointValue=this.endpoint,Promise.resolve(this.endpoint)):this.endpoint(this.file).then(e=>(this.endpointValue=e,this.endpointValue))}getChunk(){return new Promise(e=>{let n=this.totalChunks===1?this.file.size:this.chunkByteSize;this.reader.onload=()=>{this.reader.result!==null&&(this.chunk=new Blob([this.reader.result],{type:"application/octet-stream"})),e()},this.reader.readAsArrayBuffer(this.file.slice(this.nextChunkRangeStart,this.nextChunkRangeStart+n))})}xhrPromise(e){let n=r=>{r.upload.onprogress=i=>{var E;let a=this.totalChunks-this.chunkCount,o=(this.file.size-this.nextChunkRangeStart)/this.file.size/a,s=this.nextChunkRangeStart/this.file.size,h=i.loaded/((E=i.total)!=null?E:this.chunkByteSize)*o;this.dispatch("progress",Math.min((s+h)*100,100))}};return new Promise((r,i)=>{this.currentXhr=(0,Te.default)({...e,beforeSend:n},(a,o)=>(this.currentXhr=void 0,a?i(a):r(o)))})}async sendChunk(){let e=this.nextChunkRangeStart,n=e+this.chunk.size-1,r={...this.headers,"Content-Type":this.file.type,"Content-Range":`bytes ${e}-${n}/${this.file.size}`};return this.dispatch("attempt",{chunkNumber:this.chunkCount,totalChunks:this.totalChunks,chunkSize:this.chunkSize}),this.xhrPromise({headers:r,url:this.endpointValue,method:this.method,body:this.chunk})}manageRetries(){if(this.attemptCount<this.attempts){setTimeout(()=>this.sendChunks(),this.delayBeforeAttempt*1e3),this.dispatch("attemptFailure",{message:`An error occured uploading chunk ${this.chunkCount}. ${this.attempts-this.attemptCount} retries left.`,chunkNumber:this.chunkCount,attemptsLeft:this.attempts-this.attemptCount});return}this.dispatch("error",{message:`An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`,chunk:this.chunkCount,attempts:this.attemptCount})}sendChunks(){this.paused||this.offline||this.success||this.getChunk().then(()=>(this.attemptCount=this.attemptCount+1,this.lastChunkStart=new Date,this.sendChunk())).then(e=>{if(pt.includes(e.statusCode)){let r=(new Date().getTime()-this.lastChunkStart.getTime())/1e3;if(this.dispatch("chunkSuccess",{chunk:this.chunkCount,chunkSize:this.chunkSize,attempts:this.attemptCount,timeInterval:r,response:e}),this.attemptCount=0,this.chunkCount=this.chunkCount+1,this.nextChunkRangeStart=this.nextChunkRangeStart+this.chunkByteSize,this.chunkCount<this.totalChunks){if(this.dynamicChunkSize){r<10?this.chunkSize=Math.min(this.chunkSize*2,this.maxChunkSize):r>30&&(this.chunkSize=Math.max(this.chunkSize/2,this.minChunkSize)),this.chunkSize=Math.ceil(this.chunkSize/256)*256,this.chunkByteSize=this.chunkSize*1024;let i=(this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;this.totalChunks=Math.ceil(this.chunkCount+i)}this.sendChunks()}else this.success=!0,this.dispatch("success")}else if(dt.includes(e.statusCode)){if(this.paused||this.offline)return;this.manageRetries()}else{if(this.paused||this.offline)return;this.dispatch("error",{message:`Server responded with ${e.statusCode}. Stopping upload.`,chunkNumber:this.chunkCount,attempts:this.attemptCount})}}).catch(e=>{this.paused||this.offline||this.manageRetries()})}},mt=t=>new z(t);
//# sourceMappingURL=upchunk.cjs.js.map

@@ -1,2 +0,2 @@

import { XhrHeaders } from 'xhr';
import { XhrHeaders, XhrResponse } from 'xhr';
declare type EventName = 'attempt' | 'attemptFailure' | 'chunkSuccess' | 'error' | 'offline' | 'online' | 'progress' | 'success';

@@ -13,2 +13,5 @@ declare type AllowedMethods = 'PUT' | 'POST' | 'PATCH';

delayBeforeAttempt?: number;
dynamicChunkSize?: boolean;
maxChunkSize?: number;
minChunkSize?: number;
}

@@ -23,2 +26,3 @@ export declare class UpChunk {

delayBeforeAttempt: number;
dynamicChunkSize: boolean;
private chunk;

@@ -35,2 +39,6 @@ private chunkCount;

private currentXhr?;
private lastChunkStart;
private nextChunkRangeStart;
private maxChunkSize;
private minChunkSize;
private reader;

@@ -64,5 +72,5 @@ private eventTarget;

/**
* Send chunk of the file with appropriate headers and add post parameters if it's last chunk
* Send chunk of the file with appropriate headers
*/
private sendChunk;
protected sendChunk(): Promise<XhrResponse>;
/**

@@ -69,0 +77,0 @@ * Called on net failure. If retry counter !== 0, retry after delayBeforeAttempt

@@ -1,4 +0,4 @@

var UpChunk=(()=>{var Se=Object.create;var S=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fe=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},x=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _e(e))!Be.call(t,s)&&s!==n&&S(t,s,{get:()=>e[s],enumerable:!(r=ke(e,s))||r.enumerable});return t};var Ie=(t,e,n)=>(n=t!=null?Se(Le(t)):{},x(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),Ne=t=>x(S({},"__esModule",{value:!0}),t);var ge=P((yt,de)=>{var A;typeof window!="undefined"?A=window:typeof global!="undefined"?A=global:typeof self!="undefined"?A=self:A={};de.exports=A});var be=P((wt,me)=>{me.exports=nt;var tt=Object.prototype.toString;function nt(t){if(!t)return!1;var e=tt.call(t);return e==="[object Function]"||typeof t=="function"&&e!=="[object RegExp]"||typeof window!="undefined"&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)}});var ve=P((Ct,Ee)=>{var H=function(t){return t.replace(/^\s+|\s+$/g,"")},rt=function(t){return Object.prototype.toString.call(t)==="[object Array]"};Ee.exports=function(t){if(!t)return{};for(var e={},n=H(t).split(`
`),r=0;r<n.length;r++){var s=n[r],a=s.indexOf(":"),o=H(s.slice(0,a)).toLowerCase(),i=H(s.slice(a+1));typeof e[o]=="undefined"?e[o]=i:rt(e[o])?e[o].push(i):e[o]=[e[o],i]}return e}});var we=P((Rt,ye)=>{ye.exports=it;var st=Object.prototype.hasOwnProperty;function it(){for(var t={},e=0;e<arguments.length;e++){var n=arguments[e];for(var r in n)st.call(n,r)&&(t[r]=n[r])}return t}});var Pe=P((Tt,U)=>{"use strict";var Ce=ge(),at=be(),ot=ve(),ut=we();U.exports=b;U.exports.default=b;b.XMLHttpRequest=Ce.XMLHttpRequest||pt;b.XDomainRequest="withCredentials"in new b.XMLHttpRequest?b.XMLHttpRequest:Ce.XDomainRequest;lt(["get","put","post","patch","head","delete"],function(t){b[t==="delete"?"del":t]=function(e,n,r){return n=Re(e,n,r),n.method=t.toUpperCase(),Te(n)}});function lt(t,e){for(var n=0;n<t.length;n++)e(t[n])}function ct(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function Re(t,e,n){var r=t;return at(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=ut(e,{uri:t}),r.callback=n,r}function b(t,e,n){return e=Re(t,e,n),Te(e)}function Te(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(y,O,Oe){e||(e=!0,t.callback(y,O,Oe))};function r(){i.readyState===4&&setTimeout(o,0)}function s(){var u=void 0;if(i.response?u=i.response:u=i.responseText||ft(i),X)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(B),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,z)}function o(){if(!f){var u;clearTimeout(B),t.useXDR&&i.status===void 0?u=200:u=i.status===1223?204:i.status;var y=z,O=null;return u!==0?(y={body:s(),statusCode:u,method:g,headers:{},url:E,rawRequest:i},i.getAllResponseHeaders&&(y.headers=ot(i.getAllResponseHeaders()))):O=new Error("Internal XMLHttpRequest Error"),n(O,y,y.body)}}var i=t.xhr||null;i||(t.cors||t.useXDR?i=new b.XDomainRequest:i=new b.XMLHttpRequest);var c,f,E=i.url=t.uri||t.url,g=i.method=t.method||"GET",C=t.body||t.data,m=i.headers=t.headers||{},L=!!t.sync,X=!1,B,z={body:void 0,headers:{},statusCode:0,method:g,url:E,rawRequest:i};if("json"in t&&t.json!==!1&&(X=!0,m.accept||m.Accept||(m.Accept="application/json"),g!=="GET"&&g!=="HEAD"&&(m["content-type"]||m["Content-Type"]||(m["Content-Type"]="application/json"),C=JSON.stringify(t.json===!0?C:t.json))),i.onreadystatechange=r,i.onload=o,i.onerror=a,i.onprogress=function(){},i.onabort=function(){f=!0},i.ontimeout=a,i.open(g,E,!L,t.username,t.password),L||(i.withCredentials=!!t.withCredentials),!L&&t.timeout>0&&(B=setTimeout(function(){if(!f){f=!0,i.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),i.setRequestHeader)for(c in m)m.hasOwnProperty(c)&&i.setRequestHeader(c,m[c]);else if(t.headers&&!ct(t.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in t&&(i.responseType=t.responseType),"beforeSend"in t&&typeof t.beforeSend=="function"&&t.beforeSend(i),i.send(C||null),i}function ft(t){try{if(t.responseType==="document")return t.responseXML;var e=t.responseXML&&t.responseXML.documentElement.nodeName==="parsererror";if(t.responseType===""&&!e)return t.responseXML}catch{}return null}function pt(){}});var mt={};Fe(mt,{UpChunk:()=>_,createUpload:()=>gt});function M(t,e,...n){if(!t)throw new TypeError(ee(e,n))}function ee(t,e){let n=0;return t.replace(/%[os]/gu,()=>te(e[n++]))}function te(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var W;function De(t){try{let e=t instanceof Error?t:new Error(te(t));if(W){W(e);return}if(typeof dispatchEvent=="function"&&typeof ErrorEvent=="function")dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}));else if(typeof process!="undefined"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)}catch{}}var p=typeof window!="undefined"?window:typeof self!="undefined"?self:typeof global!="undefined"?global:typeof globalThis!="undefined"?globalThis:void 0,V;var h=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if(V){V({...this,args:e});return}let r=((n=new Error().stack)!==null&&n!==void 0?n:"").replace(/^(?:.+?\n){2}/gu,`
`);console.warn(this.message,...e,r)}catch{}}},je=new h("W01","Unable to initialize event under dispatching."),Me=new h("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),He=new h("W03","Assigning any truthy value to 'returnValue' property has no effect."),Ue=new h("W04","Unable to preventDefault on non-cancelable events."),Xe=new h("W05","Unable to preventDefault inside passive event listener invocation."),ze=new h("W06","An event listener wasn't added because it has been added already: %o, %o"),F=new h("W07","The %o option value was abandoned because the event listener wasn't added as duplicated."),q=new h("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),Et=new h("W09","Event attribute handler must be a function: %o"),d=class{static get NONE(){return $}static get CAPTURING_PHASE(){return G}static get AT_TARGET(){return Y}static get BUBBLING_PHASE(){return J}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};j.set(this,{type:String(e),bubbles:Boolean(r.bubbles),cancelable:Boolean(r.cancelable),composed:Boolean(r.composed),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1,inPassiveListenerFlag:!1,dispatchFlag:!1,timeStamp:Date.now()})}get type(){return l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return $}get CAPTURING_PHASE(){return G}get AT_TARGET(){return Y}get BUBBLING_PHASE(){return J}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:Me.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?He.warn():K(l(this))}preventDefault(){K(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let s=l(this);if(s.dispatchFlag){je.warn();return}j.set(this,{...s,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},$=0,G=1,Y=2,J=3,j=new WeakMap;function l(t,e="this"){let n=j.get(t);return M(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function K(t){if(t.inPassiveListenerFlag){Xe.warn();return}if(!t.cancelable){Ue.warn();return}t.canceledFlag=!0}Object.defineProperty(d,"NONE",{enumerable:!0});Object.defineProperty(d,"CAPTURING_PHASE",{enumerable:!0});Object.defineProperty(d,"AT_TARGET",{enumerable:!0});Object.defineProperty(d,"BUBBLING_PHASE",{enumerable:!0});var I=Object.getOwnPropertyNames(d.prototype);for(let t=0;t<I.length;++t)I[t]!=="constructor"&&Object.defineProperty(d.prototype,I[t],{enumerable:!0});typeof p!="undefined"&&typeof p.Event!="undefined"&&Object.setPrototypeOf(d.prototype,p.Event.prototype);function xe(t){return p.DOMException?new p.DOMException(t,"InvalidStateError"):(R==null&&(R=class ne extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,ne)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(R.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),Z(R),Z(R.prototype)),new R(t))}var R,Q={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25};function Z(t){let e=Object.keys(Q);for(let n=0;n<e.length;++n){let r=e[n],s=Q[r];Object.defineProperty(t,r,{get(){return s},configurable:!0,enumerable:!0})}}var T=class extends d{static wrap(e){return new(se(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),re.set(this,{original:e});let n=Object.keys(e);for(let r=0;r<n.length;++r){let s=n[r];s in this||Object.defineProperty(this,s,ie(e,s))}}stopPropagation(){super.stopPropagation();let{original:e}=v(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=v(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=v(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=v(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=v(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=v(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},re=new WeakMap;function v(t){let e=re.get(t);return M(e!=null,"'this' is expected an Event object, but got",t),e}var k=new WeakMap;k.set(Object.prototype,T);typeof p!="undefined"&&typeof p.Event!="undefined"&&k.set(p.Event.prototype,T);function se(t){let e=Object.getPrototypeOf(t);if(e==null)return T;let n=k.get(e);return n==null&&(n=We(se(e),e),k.set(e,n)),n}function We(t,e){class n extends t{}let r=Object.keys(e);for(let s=0;s<r.length;++s)Object.defineProperty(n.prototype,r[s],ie(e,r[s]));return n}function ie(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=v(this).original,s=r[e];return typeof s=="function"?s.bind(r):s},set(r){let s=v(this).original;s[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function Ve(t,e,n,r,s,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:s,signalListener:a}}function qe(t){t.flags|=8}function ae(t){return(t.flags&1)===1}function oe(t){return(t.flags&2)===2}function ue(t){return(t.flags&4)===4}function $e(t){return(t.flags&8)===8}function Ge({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){De(r)}}function le({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&ae(t[r])===n)return r;return-1}function Ye(t,e,n,r,s,a){let o;a&&(o=ce.bind(null,t,e,n),a.addEventListener("abort",o));let i=Ve(e,n,r,s,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,i]):t.listeners.push(i),i}function ce(t,e,n){let r=le(t,e,n);return r!==-1?fe(t,r):!1}function fe(t,e,n=!1){let r=t.listeners[e];return qe(r),r.signal&&r.signal.removeEventListener("abort",r.signalListener),t.cow&&!n?(t.cow=!1,t.listeners=t.listeners.filter((s,a)=>a!==e),!1):(t.listeners.splice(e,1),!0)}function Je(){return Object.create(null)}function Ke(t,e){var n;return(n=t[e])!==null&&n!==void 0?n:t[e]={attrCallback:void 0,attrListener:void 0,cow:!1,listeners:[]}}var w=class{constructor(){pe.set(this,Je())}addEventListener(e,n,r){let s=N(this),{callback:a,capture:o,once:i,passive:c,signal:f,type:E}=Qe(e,n,r);if(a==null||(f==null?void 0:f.aborted))return;let g=Ke(s,E),C=le(g,a,o);if(C!==-1){et(g.listeners[C],c,i,f);return}Ye(g,a,o,c,i,f)}removeEventListener(e,n,r){let s=N(this),{callback:a,capture:o,type:i}=Ze(e,n,r),c=s[i];a!=null&&c&&ce(c,a,o)}dispatchEvent(e){let n=N(this)[String(e.type)];if(n==null)return!0;let r=e instanceof d?e:T.wrap(e),s=l(r,"event");if(s.dispatchFlag)throw xe("This event has been in dispatching.");if(s.dispatchFlag=!0,s.target=s.currentTarget=this,!s.stopPropagationFlag){let{cow:a,listeners:o}=n;n.cow=!0;for(let i=0;i<o.length;++i){let c=o[i];if(!$e(c)&&(ue(c)&&fe(n,i,!a)&&(i-=1),s.inPassiveListenerFlag=oe(c),Ge(c,this,r),s.inPassiveListenerFlag=!1,s.stopImmediatePropagationFlag))break}a||(n.cow=!1)}return s.target=null,s.currentTarget=null,s.stopImmediatePropagationFlag=!1,s.stopPropagationFlag=!1,s.dispatchFlag=!1,!s.canceledFlag}},pe=new WeakMap;function N(t,e="this"){let n=pe.get(t);return M(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function Qe(t,e,n){var r;return he(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture),passive:Boolean(n.passive),once:Boolean(n.once),signal:(r=n.signal)!==null&&r!==void 0?r:void 0}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n),passive:!1,once:!1,signal:void 0}}function Ze(t,e,n){return he(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture)}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n)}}function he(t){if(!(typeof t=="function"||typeof t=="object"&&t!==null&&typeof t.handleEvent=="function")){if(t==null||typeof t=="object"){q.warn(t);return}throw new TypeError(ee(q.message,[t]))}}function et(t,e,n,r){ze.warn(ae(t)?"capture":"bubble",t.callback),oe(t)!==e&&F.warn("passive"),ue(t)!==n&&F.warn("once"),t.signal!==r&&F.warn("signal")}var D=Object.getOwnPropertyNames(w.prototype);for(let t=0;t<D.length;++t)D[t]!=="constructor"&&Object.defineProperty(w.prototype,D[t],{enumerable:!0});typeof p!="undefined"&&typeof p.EventTarget!="undefined"&&Object.setPrototypeOf(w.prototype,p.EventTarget.prototype);var Ae=Ie(Pe()),ht=[200,201,202,204,308],dt=[408,502,503,504],_=class{constructor(e){this.endpoint=e.endpoint,this.file=e.file,this.headers=e.headers||{},this.method=e.method||"PUT",this.chunkSize=e.chunkSize||30720,this.attempts=e.attempts||5,this.delayBeforeAttempt=e.delayBeforeAttempt||1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.chunkByteSize=this.chunkSize*1024,this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.attemptCount=0,this.offline=!1,this.paused=!1,this.success=!1,this.reader=new FileReader,this.eventTarget=new w,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}on(e,n){this.eventTarget.addEventListener(e,n)}abort(){var e;this.pause(),(e=this.currentXhr)==null||e.abort()}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.sendChunks())}dispatch(e,n){let r=new CustomEvent(e,{detail:n});this.eventTarget.dispatchEvent(r)}validateOptions(){if(!this.endpoint||typeof this.endpoint!="function"&&typeof this.endpoint!="string")throw new TypeError("endpoint must be defined as a string or a function that returns a promise");if(!(this.file instanceof File))throw new TypeError("file must be a File object");if(this.headers&&typeof this.headers!="object")throw new TypeError("headers must be null or an object");if(this.chunkSize&&(typeof this.chunkSize!="number"||this.chunkSize<=0||this.chunkSize%256!==0))throw new TypeError("chunkSize must be a positive number in multiples of 256");if(this.maxFileBytes>0&&this.maxFileBytes<this.file.size)throw new Error(`file size exceeds maximum (${this.file.size} > ${this.maxFileBytes})`);if(this.attempts&&(typeof this.attempts!="number"||this.attempts<=0))throw new TypeError("retries must be a positive number");if(this.delayBeforeAttempt&&(typeof this.delayBeforeAttempt!="number"||this.delayBeforeAttempt<0))throw new TypeError("delayBeforeAttempt must be a positive number")}getEndpoint(){return typeof this.endpoint=="string"?(this.endpointValue=this.endpoint,Promise.resolve(this.endpoint)):this.endpoint(this.file).then(e=>(this.endpointValue=e,this.endpointValue))}getChunk(){return new Promise(e=>{let n=this.totalChunks===1?this.file.size:this.chunkByteSize,r=n*this.chunkCount;this.reader.onload=()=>{this.reader.result!==null&&(this.chunk=new Blob([this.reader.result],{type:"application/octet-stream"})),e()},this.reader.readAsArrayBuffer(this.file.slice(r,r+n))})}xhrPromise(e){let n=r=>{r.upload.onprogress=s=>{var E;let a=100/this.totalChunks,o=a*this.file.size,i=a*this.chunkCount,f=s.loaded/((E=s.total)!=null?E:o)*a;this.dispatch("progress",Math.min(i+f,100))}};return new Promise((r,s)=>{this.currentXhr=(0,Ae.default)({...e,beforeSend:n},(a,o)=>(this.currentXhr=void 0,a?s(a):r(o)))})}sendChunk(){let e=this.chunkCount*this.chunkByteSize,n=e+this.chunk.size-1,r={...this.headers,"Content-Type":this.file.type,"Content-Range":`bytes ${e}-${n}/${this.file.size}`};return this.dispatch("attempt",{chunkNumber:this.chunkCount,chunkSize:this.chunk.size}),this.xhrPromise({headers:r,url:this.endpointValue,method:this.method,body:this.chunk})}manageRetries(){if(this.attemptCount<this.attempts){setTimeout(()=>this.sendChunks(),this.delayBeforeAttempt*1e3),this.dispatch("attemptFailure",{message:`An error occured uploading chunk ${this.chunkCount}. ${this.attempts-this.attemptCount} retries left.`,chunkNumber:this.chunkCount,attemptsLeft:this.attempts-this.attemptCount});return}this.dispatch("error",{message:`An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`,chunk:this.chunkCount,attempts:this.attemptCount})}sendChunks(){this.paused||this.offline||this.success||this.getChunk().then(()=>(this.attemptCount=this.attemptCount+1,this.sendChunk())).then(e=>{if(ht.includes(e.statusCode)){this.dispatch("chunkSuccess",{chunk:this.chunkCount,attempts:this.attemptCount,response:e}),this.attemptCount=0,this.chunkCount=this.chunkCount+1,this.chunkCount<this.totalChunks?this.sendChunks():(this.success=!0,this.dispatch("success"));let r=this.chunkCount/this.totalChunks*this.file.size,s=100*r/this.file.size;this.dispatch("progress",s)}else if(dt.includes(e.statusCode)){if(this.paused||this.offline)return;this.manageRetries()}else{if(this.paused||this.offline)return;this.dispatch("error",{message:`Server responded with ${e.statusCode}. Stopping upload.`,chunkNumber:this.chunkCount,attempts:this.attemptCount})}}).catch(e=>{this.paused||this.offline||this.manageRetries()})}},gt=t=>new _(t);return Ne(mt);})();
var UpChunk=(()=>{var Ae=Object.create;var A=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Be=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},X=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ze(e))!Le.call(t,i)&&i!==n&&A(t,i,{get:()=>e[i],enumerable:!(r=Oe(e,i))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?Ae(_e(t)):{},X(e||!t||!t.__esModule?A(n,"default",{value:t,enumerable:!0}):n,t)),Ie=t=>X(A({},"__esModule",{value:!0}),t);var me=R((yt,de)=>{var T;typeof window!="undefined"?T=window:typeof global!="undefined"?T=global:typeof self!="undefined"?T=self:T={};de.exports=T});var be=R((Ct,ge)=>{ge.exports=nt;var tt=Object.prototype.toString;function nt(t){if(!t)return!1;var e=tt.call(t);return e==="[object Function]"||typeof t=="function"&&e!=="[object RegExp]"||typeof window!="undefined"&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)}});var ve=R((St,Ee)=>{var M=function(t){return t.replace(/^\s+|\s+$/g,"")},rt=function(t){return Object.prototype.toString.call(t)==="[object Array]"};Ee.exports=function(t){if(!t)return{};for(var e={},n=M(t).split(`
`),r=0;r<n.length;r++){var i=n[r],a=i.indexOf(":"),o=M(i.slice(0,a)).toLowerCase(),s=M(i.slice(a+1));typeof e[o]=="undefined"?e[o]=s:rt(e[o])?e[o].push(s):e[o]=[e[o],s]}return e}});var Ce=R((kt,ye)=>{ye.exports=st;var it=Object.prototype.hasOwnProperty;function st(){for(var t={},e=0;e<arguments.length;e++){var n=arguments[e];for(var r in n)it.call(n,r)&&(t[r]=n[r])}return t}});var Re=R((wt,j)=>{"use strict";var Se=me(),at=be(),ot=ve(),ut=Ce();j.exports=b;j.exports.default=b;b.XMLHttpRequest=Se.XMLHttpRequest||ft;b.XDomainRequest="withCredentials"in new b.XMLHttpRequest?b.XMLHttpRequest:Se.XDomainRequest;lt(["get","put","post","patch","head","delete"],function(t){b[t==="delete"?"del":t]=function(e,n,r){return n=ke(e,n,r),n.method=t.toUpperCase(),we(n)}});function lt(t,e){for(var n=0;n<t.length;n++)e(t[n])}function ct(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function ke(t,e,n){var r=t;return at(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=ut(e,{uri:t}),r.callback=n,r}function b(t,e,n){return e=ke(t,e,n),we(e)}function we(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(y,P,Pe){e||(e=!0,t.callback(y,P,Pe))};function r(){s.readyState===4&&setTimeout(o,0)}function i(){var u=void 0;if(s.response?u=s.response:u=s.responseText||ht(s),H)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(L),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,U)}function o(){if(!h){var u;clearTimeout(L),t.useXDR&&s.status===void 0?u=200:u=s.status===1223?204:s.status;var y=U,P=null;return u!==0?(y={body:i(),statusCode:u,method:m,headers:{},url:E,rawRequest:s},s.getAllResponseHeaders&&(y.headers=ot(s.getAllResponseHeaders()))):P=new Error("Internal XMLHttpRequest Error"),n(P,y,y.body)}}var s=t.xhr||null;s||(t.cors||t.useXDR?s=new b.XDomainRequest:s=new b.XMLHttpRequest);var c,h,E=s.url=t.uri||t.url,m=s.method=t.method||"GET",S=t.body||t.data,g=s.headers=t.headers||{},_=!!t.sync,H=!1,L,U={body:void 0,headers:{},statusCode:0,method:m,url:E,rawRequest:s};if("json"in t&&t.json!==!1&&(H=!0,g.accept||g.Accept||(g.Accept="application/json"),m!=="GET"&&m!=="HEAD"&&(g["content-type"]||g["Content-Type"]||(g["Content-Type"]="application/json"),S=JSON.stringify(t.json===!0?S:t.json))),s.onreadystatechange=r,s.onload=o,s.onerror=a,s.onprogress=function(){},s.onabort=function(){h=!0},s.ontimeout=a,s.open(m,E,!_,t.username,t.password),_||(s.withCredentials=!!t.withCredentials),!_&&t.timeout>0&&(L=setTimeout(function(){if(!h){h=!0,s.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),s.setRequestHeader)for(c in g)g.hasOwnProperty(c)&&s.setRequestHeader(c,g[c]);else if(t.headers&&!ct(t.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in t&&(s.responseType=t.responseType),"beforeSend"in t&&typeof t.beforeSend=="function"&&t.beforeSend(s),s.send(S||null),s}function ht(t){try{if(t.responseType==="document")return t.responseXML;var e=t.responseXML&&t.responseXML.documentElement.nodeName==="parsererror";if(t.responseType===""&&!e)return t.responseXML}catch{}return null}function ft(){}});var gt={};Be(gt,{UpChunk:()=>z,createUpload:()=>mt});function D(t,e,...n){if(!t)throw new TypeError(ee(e,n))}function ee(t,e){let n=0;return t.replace(/%[os]/gu,()=>te(e[n++]))}function te(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var W;function Fe(t){try{let e=t instanceof Error?t:new Error(te(t));if(W){W(e);return}if(typeof dispatchEvent=="function"&&typeof ErrorEvent=="function")dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}));else if(typeof process!="undefined"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)}catch{}}var f=typeof window!="undefined"?window:typeof self!="undefined"?self:typeof global!="undefined"?global:typeof globalThis!="undefined"?globalThis:void 0,$;var p=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if($){$({...this,args:e});return}let r=((n=new Error().stack)!==null&&n!==void 0?n:"").replace(/^(?:.+?\n){2}/gu,`
`);console.warn(this.message,...e,r)}catch{}}},Ne=new p("W01","Unable to initialize event under dispatching."),De=new p("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),Me=new p("W03","Assigning any truthy value to 'returnValue' property has no effect."),je=new p("W04","Unable to preventDefault on non-cancelable events."),He=new p("W05","Unable to preventDefault inside passive event listener invocation."),Ue=new p("W06","An event listener wasn't added because it has been added already: %o, %o"),B=new p("W07","The %o option value was abandoned because the event listener wasn't added as duplicated."),q=new p("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),Et=new p("W09","Event attribute handler must be a function: %o"),d=class{static get NONE(){return V}static get CAPTURING_PHASE(){return G}static get AT_TARGET(){return Y}static get BUBBLING_PHASE(){return J}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};N.set(this,{type:String(e),bubbles:Boolean(r.bubbles),cancelable:Boolean(r.cancelable),composed:Boolean(r.composed),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1,inPassiveListenerFlag:!1,dispatchFlag:!1,timeStamp:Date.now()})}get type(){return l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return V}get CAPTURING_PHASE(){return G}get AT_TARGET(){return Y}get BUBBLING_PHASE(){return J}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:De.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?Me.warn():K(l(this))}preventDefault(){K(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let i=l(this);if(i.dispatchFlag){Ne.warn();return}N.set(this,{...i,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},V=0,G=1,Y=2,J=3,N=new WeakMap;function l(t,e="this"){let n=N.get(t);return D(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function K(t){if(t.inPassiveListenerFlag){He.warn();return}if(!t.cancelable){je.warn();return}t.canceledFlag=!0}Object.defineProperty(d,"NONE",{enumerable:!0});Object.defineProperty(d,"CAPTURING_PHASE",{enumerable:!0});Object.defineProperty(d,"AT_TARGET",{enumerable:!0});Object.defineProperty(d,"BUBBLING_PHASE",{enumerable:!0});var x=Object.getOwnPropertyNames(d.prototype);for(let t=0;t<x.length;++t)x[t]!=="constructor"&&Object.defineProperty(d.prototype,x[t],{enumerable:!0});typeof f!="undefined"&&typeof f.Event!="undefined"&&Object.setPrototypeOf(d.prototype,f.Event.prototype);function Xe(t){return f.DOMException?new f.DOMException(t,"InvalidStateError"):(k==null&&(k=class ne extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,ne)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(k.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),Z(k),Z(k.prototype)),new k(t))}var k,Q={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25};function Z(t){let e=Object.keys(Q);for(let n=0;n<e.length;++n){let r=e[n],i=Q[r];Object.defineProperty(t,r,{get(){return i},configurable:!0,enumerable:!0})}}var w=class extends d{static wrap(e){return new(ie(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),re.set(this,{original:e});let n=Object.keys(e);for(let r=0;r<n.length;++r){let i=n[r];i in this||Object.defineProperty(this,i,se(e,i))}}stopPropagation(){super.stopPropagation();let{original:e}=v(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=v(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=v(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=v(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=v(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=v(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},re=new WeakMap;function v(t){let e=re.get(t);return D(e!=null,"'this' is expected an Event object, but got",t),e}var O=new WeakMap;O.set(Object.prototype,w);typeof f!="undefined"&&typeof f.Event!="undefined"&&O.set(f.Event.prototype,w);function ie(t){let e=Object.getPrototypeOf(t);if(e==null)return w;let n=O.get(e);return n==null&&(n=We(ie(e),e),O.set(e,n)),n}function We(t,e){class n extends t{}let r=Object.keys(e);for(let i=0;i<r.length;++i)Object.defineProperty(n.prototype,r[i],se(e,r[i]));return n}function se(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=v(this).original,i=r[e];return typeof i=="function"?i.bind(r):i},set(r){let i=v(this).original;i[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function $e(t,e,n,r,i,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:i,signalListener:a}}function qe(t){t.flags|=8}function ae(t){return(t.flags&1)===1}function oe(t){return(t.flags&2)===2}function ue(t){return(t.flags&4)===4}function Ve(t){return(t.flags&8)===8}function Ge({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){Fe(r)}}function le({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&ae(t[r])===n)return r;return-1}function Ye(t,e,n,r,i,a){let o;a&&(o=ce.bind(null,t,e,n),a.addEventListener("abort",o));let s=$e(e,n,r,i,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,s]):t.listeners.push(s),s}function ce(t,e,n){let r=le(t,e,n);return r!==-1?he(t,r):!1}function he(t,e,n=!1){let r=t.listeners[e];return qe(r),r.signal&&r.signal.removeEventListener("abort",r.signalListener),t.cow&&!n?(t.cow=!1,t.listeners=t.listeners.filter((i,a)=>a!==e),!1):(t.listeners.splice(e,1),!0)}function Je(){return Object.create(null)}function Ke(t,e){var n;return(n=t[e])!==null&&n!==void 0?n:t[e]={attrCallback:void 0,attrListener:void 0,cow:!1,listeners:[]}}var C=class{constructor(){fe.set(this,Je())}addEventListener(e,n,r){let i=I(this),{callback:a,capture:o,once:s,passive:c,signal:h,type:E}=Qe(e,n,r);if(a==null||(h==null?void 0:h.aborted))return;let m=Ke(i,E),S=le(m,a,o);if(S!==-1){et(m.listeners[S],c,s,h);return}Ye(m,a,o,c,s,h)}removeEventListener(e,n,r){let i=I(this),{callback:a,capture:o,type:s}=Ze(e,n,r),c=i[s];a!=null&&c&&ce(c,a,o)}dispatchEvent(e){let n=I(this)[String(e.type)];if(n==null)return!0;let r=e instanceof d?e:w.wrap(e),i=l(r,"event");if(i.dispatchFlag)throw Xe("This event has been in dispatching.");if(i.dispatchFlag=!0,i.target=i.currentTarget=this,!i.stopPropagationFlag){let{cow:a,listeners:o}=n;n.cow=!0;for(let s=0;s<o.length;++s){let c=o[s];if(!Ve(c)&&(ue(c)&&he(n,s,!a)&&(s-=1),i.inPassiveListenerFlag=oe(c),Ge(c,this,r),i.inPassiveListenerFlag=!1,i.stopImmediatePropagationFlag))break}a||(n.cow=!1)}return i.target=null,i.currentTarget=null,i.stopImmediatePropagationFlag=!1,i.stopPropagationFlag=!1,i.dispatchFlag=!1,!i.canceledFlag}},fe=new WeakMap;function I(t,e="this"){let n=fe.get(t);return D(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function Qe(t,e,n){var r;return pe(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture),passive:Boolean(n.passive),once:Boolean(n.once),signal:(r=n.signal)!==null&&r!==void 0?r:void 0}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n),passive:!1,once:!1,signal:void 0}}function Ze(t,e,n){return pe(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture)}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n)}}function pe(t){if(!(typeof t=="function"||typeof t=="object"&&t!==null&&typeof t.handleEvent=="function")){if(t==null||typeof t=="object"){q.warn(t);return}throw new TypeError(ee(q.message,[t]))}}function et(t,e,n,r){Ue.warn(ae(t)?"capture":"bubble",t.callback),oe(t)!==e&&B.warn("passive"),ue(t)!==n&&B.warn("once"),t.signal!==r&&B.warn("signal")}var F=Object.getOwnPropertyNames(C.prototype);for(let t=0;t<F.length;++t)F[t]!=="constructor"&&Object.defineProperty(C.prototype,F[t],{enumerable:!0});typeof f!="undefined"&&typeof f.EventTarget!="undefined"&&Object.setPrototypeOf(C.prototype,f.EventTarget.prototype);var Te=xe(Re()),pt=[200,201,202,204,308],dt=[408,502,503,504],z=class{constructor(e){this.endpoint=e.endpoint,this.file=e.file,this.headers=e.headers||{},this.method=e.method||"PUT",this.chunkSize=e.chunkSize||30720,this.attempts=e.attempts||5,this.delayBeforeAttempt=e.delayBeforeAttempt||1,this.dynamicChunkSize=e.dynamicChunkSize||!1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.chunkByteSize=this.chunkSize*1024,this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.attemptCount=0,this.offline=!1,this.paused=!1,this.success=!1,this.nextChunkRangeStart=0,this.maxChunkSize=e.maxChunkSize||512e3,this.minChunkSize=e.minChunkSize||256,this.reader=new FileReader,this.eventTarget=new C,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}on(e,n){this.eventTarget.addEventListener(e,n)}abort(){var e;this.pause(),(e=this.currentXhr)==null||e.abort()}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.sendChunks())}dispatch(e,n){let r=new CustomEvent(e,{detail:n});this.eventTarget.dispatchEvent(r)}validateOptions(){if(!this.endpoint||typeof this.endpoint!="function"&&typeof this.endpoint!="string")throw new TypeError("endpoint must be defined as a string or a function that returns a promise");if(!(this.file instanceof File))throw new TypeError("file must be a File object");if(this.headers&&typeof this.headers!="object")throw new TypeError("headers must be null or an object");if(this.chunkSize&&(typeof this.chunkSize!="number"||this.chunkSize<256||this.chunkSize%256!==0||this.chunkSize<this.minChunkSize||this.chunkSize>this.maxChunkSize))throw new TypeError(`chunkSize must be a positive number in multiples of 256, between ${this.minChunkSize} and ${this.maxChunkSize}`);if(this.maxChunkSize&&(typeof this.maxChunkSize!="number"||this.maxChunkSize<256||this.maxChunkSize%256!==0||this.maxChunkSize<this.chunkSize||this.maxChunkSize<this.minChunkSize))throw new TypeError(`maxChunkSize must be a positive number in multiples of 256, and larger than or equal to both ${this.minChunkSize} and ${this.chunkSize}`);if(this.minChunkSize&&(typeof this.minChunkSize!="number"||this.minChunkSize<256||this.minChunkSize%256!==0||this.minChunkSize>this.chunkSize||this.minChunkSize>this.maxChunkSize))throw new TypeError(`minChunkSize must be a positive number in multiples of 256, and smaller than ${this.chunkSize} and ${this.maxChunkSize}`);if(this.maxFileBytes>0&&this.maxFileBytes<this.file.size)throw new Error(`file size exceeds maximum (${this.file.size} > ${this.maxFileBytes})`);if(this.attempts&&(typeof this.attempts!="number"||this.attempts<=0))throw new TypeError("retries must be a positive number");if(this.delayBeforeAttempt&&(typeof this.delayBeforeAttempt!="number"||this.delayBeforeAttempt<0))throw new TypeError("delayBeforeAttempt must be a positive number")}getEndpoint(){return typeof this.endpoint=="string"?(this.endpointValue=this.endpoint,Promise.resolve(this.endpoint)):this.endpoint(this.file).then(e=>(this.endpointValue=e,this.endpointValue))}getChunk(){return new Promise(e=>{let n=this.totalChunks===1?this.file.size:this.chunkByteSize;this.reader.onload=()=>{this.reader.result!==null&&(this.chunk=new Blob([this.reader.result],{type:"application/octet-stream"})),e()},this.reader.readAsArrayBuffer(this.file.slice(this.nextChunkRangeStart,this.nextChunkRangeStart+n))})}xhrPromise(e){let n=r=>{r.upload.onprogress=i=>{var E;let a=this.totalChunks-this.chunkCount,o=(this.file.size-this.nextChunkRangeStart)/this.file.size/a,s=this.nextChunkRangeStart/this.file.size,h=i.loaded/((E=i.total)!=null?E:this.chunkByteSize)*o;this.dispatch("progress",Math.min((s+h)*100,100))}};return new Promise((r,i)=>{this.currentXhr=(0,Te.default)({...e,beforeSend:n},(a,o)=>(this.currentXhr=void 0,a?i(a):r(o)))})}async sendChunk(){let e=this.nextChunkRangeStart,n=e+this.chunk.size-1,r={...this.headers,"Content-Type":this.file.type,"Content-Range":`bytes ${e}-${n}/${this.file.size}`};return this.dispatch("attempt",{chunkNumber:this.chunkCount,totalChunks:this.totalChunks,chunkSize:this.chunkSize}),this.xhrPromise({headers:r,url:this.endpointValue,method:this.method,body:this.chunk})}manageRetries(){if(this.attemptCount<this.attempts){setTimeout(()=>this.sendChunks(),this.delayBeforeAttempt*1e3),this.dispatch("attemptFailure",{message:`An error occured uploading chunk ${this.chunkCount}. ${this.attempts-this.attemptCount} retries left.`,chunkNumber:this.chunkCount,attemptsLeft:this.attempts-this.attemptCount});return}this.dispatch("error",{message:`An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`,chunk:this.chunkCount,attempts:this.attemptCount})}sendChunks(){this.paused||this.offline||this.success||this.getChunk().then(()=>(this.attemptCount=this.attemptCount+1,this.lastChunkStart=new Date,this.sendChunk())).then(e=>{if(pt.includes(e.statusCode)){let r=(new Date().getTime()-this.lastChunkStart.getTime())/1e3;if(this.dispatch("chunkSuccess",{chunk:this.chunkCount,chunkSize:this.chunkSize,attempts:this.attemptCount,timeInterval:r,response:e}),this.attemptCount=0,this.chunkCount=this.chunkCount+1,this.nextChunkRangeStart=this.nextChunkRangeStart+this.chunkByteSize,this.chunkCount<this.totalChunks){if(this.dynamicChunkSize){r<10?this.chunkSize=Math.min(this.chunkSize*2,this.maxChunkSize):r>30&&(this.chunkSize=Math.max(this.chunkSize/2,this.minChunkSize)),this.chunkSize=Math.ceil(this.chunkSize/256)*256,this.chunkByteSize=this.chunkSize*1024;let i=(this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;this.totalChunks=Math.ceil(this.chunkCount+i)}this.sendChunks()}else this.success=!0,this.dispatch("success")}else if(dt.includes(e.statusCode)){if(this.paused||this.offline)return;this.manageRetries()}else{if(this.paused||this.offline)return;this.dispatch("error",{message:`Server responded with ${e.statusCode}. Stopping upload.`,chunkNumber:this.chunkCount,attempts:this.attemptCount})}}).catch(e=>{this.paused||this.offline||this.manageRetries()})}},mt=t=>new z(t);return Ie(gt);})();
//# sourceMappingURL=upchunk.js.map
{
"name": "@mux/upchunk",
"version": "2.4.0",
"version": "2.5.0",
"description": "Dead simple chunked file uploads using Fetch",

@@ -5,0 +5,0 @@ "main": "dist/upchunk.js",

@@ -173,3 +173,3 @@ ![UpChunk](banner.png)

The size in kb of the chunks to split the file into, with the exception of the final chunk which may be smaller. This parameter should be in multiples of 256.
The size in kB of the chunks to split the file into, with the exception of the final chunk which may be smaller. This parameter must be in multiples of 256.

@@ -192,2 +192,14 @@ - `maxFileSize` <small>type: `integer`</small>

- `dynamicChunkSize` <small>type: `boolean`, default: `false`</small>
Whether or not the system should dynamically scale the `chunkSize` up and down to adjust to network conditions.
- `maxChunkSize` <small>type: `integer`, default: `512000`</small>
When `dynamicChunkSize` is `true`, the largest chunk size that will be used, in kB.
- `minChunkSize` <small>type: `integer`, default: `256`</small>
When `dynamicChunkSize` is `true`, the smallest chunk size that will be used, in kB.
### UpChunk Instance Methods

@@ -194,0 +206,0 @@

@@ -285,3 +285,3 @@ import * as nock from 'nock';

});
expect(progressCallback).toHaveBeenCalledTimes(7);
expect(progressCallback).toHaveBeenCalledTimes(4);
const progressPercentageArray = progressCallback.mock.calls.map(([percentage]) => percentage);

@@ -288,0 +288,0 @@ expect(isNumberArraySorted(progressPercentageArray)).toBeTruthy();

@@ -35,2 +35,5 @@ import { EventTarget, Event } from 'event-target-shim';

delayBeforeAttempt?: number;
dynamicChunkSize?: boolean;
maxChunkSize?: number;
minChunkSize?: number;
}

@@ -46,2 +49,3 @@

public delayBeforeAttempt: number;
public dynamicChunkSize: boolean;

@@ -59,2 +63,6 @@ private chunk: Blob;

private currentXhr?: XMLHttpRequest;
private lastChunkStart: Date;
private nextChunkRangeStart: number;
private maxChunkSize: number;
private minChunkSize: number;

@@ -64,2 +72,4 @@ private reader: FileReader;

constructor(options: UpChunkOptions) {

@@ -73,2 +83,3 @@ this.endpoint = options.endpoint;

this.delayBeforeAttempt = options.delayBeforeAttempt || 1;
this.dynamicChunkSize = options.dynamicChunkSize || false;

@@ -83,2 +94,5 @@ this.maxFileBytes = (options.maxFileSize || 0) * 1024;

this.success = false;
this.nextChunkRangeStart = 0;
this.maxChunkSize = options.maxChunkSize || 512000; // in kB
this.minChunkSize = options.minChunkSize || 256; // in kB

@@ -165,9 +179,35 @@ this.reader = new FileReader();

(typeof this.chunkSize !== 'number' ||
this.chunkSize <= 0 ||
this.chunkSize % 256 !== 0)
this.chunkSize < 256 ||
this.chunkSize % 256 !== 0 ||
this.chunkSize < this.minChunkSize ||
this.chunkSize > this.maxChunkSize)
) {
throw new TypeError(
'chunkSize must be a positive number in multiples of 256'
`chunkSize must be a positive number in multiples of 256, between ${this.minChunkSize} and ${this.maxChunkSize}`
);
}
if (
this.maxChunkSize &&
(typeof this.maxChunkSize !== 'number' ||
this.maxChunkSize < 256 ||
this.maxChunkSize % 256 !== 0 ||
this.maxChunkSize < this.chunkSize ||
this.maxChunkSize < this.minChunkSize)
) {
throw new TypeError(
`maxChunkSize must be a positive number in multiples of 256, and larger than or equal to both ${this.minChunkSize} and ${this.chunkSize}`
);
}
if (
this.minChunkSize &&
(typeof this.minChunkSize !== 'number' ||
this.minChunkSize < 256 ||
this.minChunkSize % 256 !== 0 ||
this.minChunkSize > this.chunkSize ||
this.minChunkSize > this.maxChunkSize)
) {
throw new TypeError(
`minChunkSize must be a positive number in multiples of 256, and smaller than ${this.chunkSize} and ${this.maxChunkSize}`
);
}
if (this.maxFileBytes > 0 && this.maxFileBytes < this.file.size) {

@@ -216,3 +256,2 @@ throw new Error(

this.totalChunks === 1 ? this.file.size : this.chunkByteSize;
const start = length * this.chunkCount;

@@ -228,3 +267,3 @@ this.reader.onload = () => {

this.reader.readAsArrayBuffer(this.file.slice(start, start + length));
this.reader.readAsArrayBuffer(this.file.slice(this.nextChunkRangeStart, this.nextChunkRangeStart + length));
});

@@ -236,8 +275,9 @@ }

xhrObject.upload.onprogress = (event: ProgressEvent) => {
const percentagePerChunk = 100 / this.totalChunks;
const sizePerChunk = percentagePerChunk * this.file.size;
const successfulPercentage = percentagePerChunk * this.chunkCount;
const currentChunkProgress = event.loaded / (event.total ?? sizePerChunk);
const remainingChunks = this.totalChunks - this.chunkCount;
// const remainingBytes = this.file.size-(this.nextChunkRangeStart+event.loaded);
const percentagePerChunk = (this.file.size-this.nextChunkRangeStart)/this.file.size/remainingChunks;
const successfulPercentage = this.nextChunkRangeStart/this.file.size;
const currentChunkProgress = event.loaded / (event.total ?? this.chunkByteSize);
const chunkPercentage = currentChunkProgress * percentagePerChunk;
this.dispatch('progress', Math.min(successfulPercentage + chunkPercentage, 100));
this.dispatch('progress', Math.min((successfulPercentage + chunkPercentage)*100, 100));
};

@@ -259,6 +299,6 @@ };

/**
* Send chunk of the file with appropriate headers and add post parameters if it's last chunk
* Send chunk of the file with appropriate headers
*/
private sendChunk() {
const rangeStart = this.chunkCount * this.chunkByteSize;
protected async sendChunk() {
const rangeStart = this.nextChunkRangeStart;
const rangeEnd = rangeStart + this.chunk.size - 1;

@@ -273,3 +313,4 @@ const headers = {

chunkNumber: this.chunkCount,
chunkSize: this.chunk.size,
totalChunks: this.totalChunks,
chunkSize: this.chunkSize,
});

@@ -320,3 +361,3 @@

this.attemptCount = this.attemptCount + 1;
this.lastChunkStart = new Date();
return this.sendChunk()

@@ -326,5 +367,10 @@ })

if (SUCCESSFUL_CHUNK_UPLOAD_CODES.includes(res.statusCode)) {
const lastChunkEnd = new Date();
const lastChunkInterval = (lastChunkEnd.getTime() - this.lastChunkStart.getTime()) / 1000;
this.dispatch('chunkSuccess', {
chunk: this.chunkCount,
chunkSize: this.chunkSize,
attempts: this.attemptCount,
timeInterval: lastChunkInterval,
response: res,

@@ -335,4 +381,24 @@ });

this.chunkCount = this.chunkCount + 1;
this.nextChunkRangeStart = this.nextChunkRangeStart + this.chunkByteSize;
if (this.chunkCount < this.totalChunks) {
// dynamic chunk sizing
if (this.dynamicChunkSize) {
if (lastChunkInterval < 10)
{
this.chunkSize = Math.min(this.chunkSize * 2,this.maxChunkSize);
} else if (lastChunkInterval > 30) {
this.chunkSize = Math.max(this.chunkSize / 2,this.minChunkSize);
}
// ensure it's a multiple of 256k
this.chunkSize = Math.ceil(this.chunkSize / 256) * 256;
// Now update the new chunkByteSize to the newly calculated chunk size
this.chunkByteSize = this.chunkSize * 1024;
// Re-estimate the total number of chunks, by adding the completed
// chunks to the remaining chunks
const remainingChunks = (this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;
this.totalChunks = Math.ceil(this.chunkCount + remainingChunks);
}
this.sendChunks();

@@ -344,8 +410,2 @@ } else {

const chunkFraction = this.chunkCount / this.totalChunks;
const uploadedBytes = chunkFraction * this.file.size;
const percentProgress = (100 * uploadedBytes) / this.file.size;
this.dispatch('progress', percentProgress);
} else if (TEMPORARY_ERROR_CODES.includes(res.statusCode)) {

@@ -355,2 +415,3 @@ if (this.paused || this.offline) {

}
// console.warn('DEBUG: Caught a temporary error: %j',res);
this.manageRetries();

@@ -374,2 +435,3 @@ } else {

// console.warn('DEBUG: Caught an error: %j',err);
// this type of error can happen after network disconnection on CORS setup

@@ -376,0 +438,0 @@ this.manageRetries();

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc