@vedratech/anydrop-core 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/LICENSE
CHANGED
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
package/dist/index.global.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var AnyDropCore=(function(exports){'use strict';var Z="
|
|
1
|
+
var AnyDropCore=(function(exports){'use strict';var Z="1.0.0";function he(o){let i,e=new Promise(t=>i=t);return {sessionId:o,files:[],folders:new Set,terminalIn:new Set,readErrors:[],walking:true,pending:0,closed:false,manifestState:"pending",processRequested:false,deferred:[],promise:e,resolve:i}}function fe(o,i,e,t){let s=Number(e.chunkSize),r=o.upload;return !t&&!r.chunksDone.size&&(r.chunkSize=s,r.total=i,r.chunked=!!e.chunking&&(e.forceChunking||i>s),r.totalChunkCount=r.chunked?Math.max(1,Math.ceil(i/s)):1),r.chunkSize}function U(o,i,e,t){let s=i*e;return {file:o,index:i,start:s,end:Math.min(s+e,o.upload.total),retries:t}}function N(o,i){let e=o.upload;for(let t=0;t<e.totalChunkCount;t++)if(!e.chunksDone.has(t)&&!i.has(t))return t;return -1}function j(o,i){let e=0,t=o.upload.total;return o.upload.chunksDone.forEach(s=>e+=Math.max(0,Math.min(i,t-s*i))),e}var S="added",g="queued",ee=g,v="uploading",te=v,D="paused",x="success",w="error",T="canceled";function se(o){return o===x||o===w||o===T}var L=class{constructor(i){this.onChange=i;this.entries=new Map;}set(i){let e=me(i.fileId,i.relativePath);this.entries.delete(e),this.entries.set(e,i),this.onChange();}remove(i,e=""){let t=this.entries.delete(me(i,e));return t&&this.onChange(),t}has(i){return this.entries.has(i)}clear(){this.entries.size&&(this.entries.clear(),this.onChange());}get size(){return this.entries.size}list(){let i=[];return this.entries.forEach(e=>i.push({...e})),i}};function me(o,i){return o===null?"\0folder:"+i:o}var ye=["fileId","relativePath","uploadId","code","message","httpStatus","stage","chunkIndex","attempt","retryable","at"];function ge(o,i){if(i==="json")return JSON.stringify(o,null,2);if(i!=="csv")throw new Error(`Unknown export format: ${String(i)}`);let e=[ye.join(",")];for(let t of o)e.push(ye.map(s=>Ye(t[s])).join(","));return e.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
3
|
`}function Ye(o){if(o==null)return "";let i=String(o);return typeof o=="string"&&/^[=+\-@\t\r]/.test(i)&&(i="'"+i),/[",\r\n]/.test(i)?'"'+i.replace(/"/g,'""')+'"':i}function E(o){let i=globalThis;typeof i.reportError=="function"?i.reportError(o):typeof console!="undefined"&&console.error(o);}function C(o,...i){typeof console!="undefined"&&console.warn("[anydrop] "+o,...i);}function ve(){return new Promise(o=>setTimeout(o,0))}var z=class{constructor(){this._callbacks={};}on(i,e){return (this._callbacks[i]||(this._callbacks[i]=[])).push(e),this.unsubscribe(i,e)}once(i,e){let t=()=>this.off(i,e),s=function(...r){t(),e.apply(this,r);};return s._fn=e,(this._callbacks[i]||(this._callbacks[i]=[])).push(s),this.unsubscribe(i,e)}off(i,e){if(i===void 0)this._callbacks={};else if(e===void 0)delete this._callbacks[i];else {let t=this._callbacks[i]||[];for(let s=0;s<t.length;s++){let r=t[s];if(r===e||r._fn===e){t.splice(s,1);break}}}return this}emit(i,...e){let t=this._callbacks[i];if(t&&t.length)for(let s of t.slice())try{s.apply(this,e);}catch(r){this.onListenerError(r);}return this}hasListeners(i){let e=this._callbacks[i];return !!e&&e.length>0}onListenerError(i){E(i);}unsubscribe(i,e){let t=(()=>{this.off(i,e);});return t.on=this.on.bind(this),t.once=this.once.bind(this),t}};var ie="drop dragstart dragend dragenter dragover dragleave paste emptyfolder addedfile addedfiles removedfile reset thumbnail error errormultiple maxfilesexceeded maxfilesreached processing processingmultiple uploadprogress totaluploadprogress sending sendingmultiple success successmultiple canceled canceledmultiple complete completemultiple queuecomplete addedfolder removedfolder folderprogress foldercomplete paused resumed offline online reconnecting errorlistchanged actionclicked".split(" ");function Fe(o){return ie.indexOf(o)>=0}var _=class{constructor(i,e){this.ms=i;this.fire=e;this.timers=new Map;}request(i,e=false){let t=this.timers.get(i);e?(t!==void 0&&(clearTimeout(t),this.timers.delete(i)),this.fire(i)):t===void 0&&this.timers.set(i,setTimeout(()=>{this.timers.delete(i),this.fire(i);},this.ms));}pending(i){return this.timers.has(i)}clear(){this.timers.forEach(i=>clearTimeout(i)),this.timers.clear();}};function ke(o){let i=false;return ()=>{i||(i=true,Promise.resolve().then(()=>{i=false,o();}));}}function q(o,i,e){Object.defineProperty(o,i,{value:e,enumerable:true,configurable:true,writable:false});}function be(o,i){let e=o;q(e,"id",i.id),q(e,"relativePath",i.relativePath),q(e,"fingerprint",`${i.relativePath}|${o.size}|${o.lastModified}`),q(e,"folder",i.folder),i.fromFolder&&Object.defineProperty(e,"fullPath",{get(){return this.relativePath},enumerable:true,configurable:true}),e.status="added",e.accepted=void 0;let t=i.chunking&&(i.forceChunking||o.size>i.chunkSize);return e.upload={uuid:i.uploadId,filename:o.name,progress:0,total:o.size,bytesSent:0,chunked:t,chunkSize:i.chunkSize,totalChunkCount:t?Math.max(1,Math.ceil(o.size/i.chunkSize)):1,chunksDone:new Set},e.upload.filename=i.rename(e),e}function De(o){let i=typeof window!="undefined"?window:null,e=typeof document!="undefined"?document:null,t=[[i,"online",o.online],[i,"offline",o.offline],[i,"pagehide",o.pagehide],[i,"pageshow",o.pageshow],[e,"visibilitychange",()=>o.visibility(!!e&&e.visibilityState==="hidden")]],s=r=>t.forEach(([n,a,l])=>{n&&n.addEventListener&&n.removeEventListener&&(r?n.addEventListener(a,l):n.removeEventListener(a,l));});return s(true),()=>s(false)}function B(){return typeof navigator!="undefined"&&navigator.onLine===false}function re(){return {url:null,method:"post",withCredentials:false,timeout:null,headers:null,defaultHeaders:true,params:null,paramName:"file",uploadMultiple:false,binaryBody:false,parallelUploads:2,maxChunksInFlight:null,chunking:false,forceChunking:false,chunkSize:2*1024*1024,parallelChunkUploads:false,retryChunks:true,retryChunksLimit:3,chunksUploaded:null,transformFile:null,transport:null,maxFilesize:256,filesizeBase:1e3,maxFiles:null,acceptedFiles:null,accept:(o,i)=>i(),ignoreHiddenFiles:true,renameFile:null,autoProcessQueue:true,autoQueue:true,folders:true,preserveEmptyFolders:true,sendManifest:false,manifestUrl:null,chunkStatusUrl:null,finalizeUrl:null,pauseMode:"abort",persistState:true,persistKey:null,autoPauseOnHidden:true,autoResumeOnReconnect:true,stallTimeout:3e4,connectivityProbeUrl:null,dictFileTooBig:"File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",dictInvalidFileType:"You can't upload files of this type.",dictResponseError:"Server responded with {{statusCode}} code.",dictUploadCanceled:"Upload canceled.",dictMaxFilesExceeded:"You cannot upload any more files.",dictFileUnreadable:"The file could not be read (not downloaded, moved or deleted).",dictInvalidPath:"Invalid file path.",dictFileSizeUnits:{tb:"TB",gb:"GB",mb:"MB",kb:"KB",b:"b"}}}function ne(o){if(o.uploadMultiple&&o.chunking)throw new Error("You cannot set both: uploadMultiple and chunking.");if(o.binaryBody&&o.uploadMultiple)throw new Error("You cannot set both: binaryBody and uploadMultiple.")}var H=class{constructor(){this.all=false;this.sys=new Set;this.files=new WeakSet;}any(){return this.all||this.sys.size>0}blocks(i){if(this.any()||this.files.has(i))return true;for(let e=i.folder;e;e=e.parent)if(e.userPaused)return true;return false}};var Ee=7*864e5,Ae=1500,oe="uploads",Se=o=>IDBKeyRange.bound(o,o+"\uFFFF"),Ze=(o,i)=>new Promise(e=>{let t=setTimeout(()=>e(i),Ae);o.then(s=>{clearTimeout(t),e(s);});}),we=o=>o&&o.updatedAt>Date.now()-Ee?o:void 0;function je(){let o=new Map;return {get:(i,e)=>Promise.resolve(e.map(t=>we(o.get(t)))),put:i=>{o.set(i.key,i);},del:i=>{o.delete(i);},flush(){},close(){},clear(i){return o.forEach((e,t)=>{t.indexOf(i)||o.delete(t);}),Promise.resolve()}}}function et(){let o=null,i=null,e=new Map,t,s=false,r=p=>(o||(o=je(),C("IndexedDB is not available; resume state is kept in memory only.",p)),null),n=(p,h,m)=>new Promise(f=>{try{let y=p.transaction(oe,h);y.oncomplete=()=>f(!0),y.onerror=y.onabort=()=>f(!!r(y.error)),m(y.objectStore(oe));}catch(y){f(!!r(y));}}),a=()=>i||(i=new Promise(p=>{let h=false,m=setTimeout(()=>f("open timed out"),Ae),f=y=>{h=true,clearTimeout(m),p(r(y));};try{let y=indexedDB.open("anydrop",1);y.onupgradeneeded=()=>y.result.createObjectStore(oe,{keyPath:"key"}).createIndex("t","updatedAt"),y.onblocked=()=>f("open blocked"),y.onerror=()=>f(y.error),y.onsuccess=()=>{let b=y.result;if(h)return b.close();clearTimeout(m),b.onversionchange=()=>{b.close(),i=null;},n(b,"readwrite",P=>{let O=P.index("t").openCursor(IDBKeyRange.upperBound(Date.now()-Ee));O.onsuccess=()=>{let Y=O.result;Y&&(Y.delete(),Y.continue());};}),p(b);};}catch(y){f(y);}})),l=async(p,h)=>{let m=o?null:await a();return !!m&&!o&&n(m,p,h)},c=()=>{if(clearTimeout(t),t=void 0,!e.size)return;let p=Array.from(e);e.clear(),l("readwrite",h=>p.forEach(([m,f])=>f?h.put(f):h.delete(m))).then(h=>{let m=o;!h&&m&&p.forEach(([f,y])=>y?m.put(y):m.del(f));});},d=()=>{i&&i.then(p=>p&&p.close()),i=null;},u=()=>{t||(t=setTimeout(c,250));};return {async get(p,h){let m=new Map,y=!await Ze(l("readonly",b=>{let P=b.getAll(Se(p));P.onsuccess=()=>P.result.forEach(O=>m.set(O.key,O));}),false)&&o?await o.get(p,h):null;return h.map((b,P)=>we(e.has(b)?e.get(b)||void 0:y?y[P]:m.get(b)))},put(p){e.set(p.key,p),u();},del(p){e.set(p,null),u();},flush:c,close(){c(),s=true,d();},async clear(p){e.forEach((m,f)=>{f.indexOf(p)||e.delete(f);}),!await l("readwrite",m=>m.delete(Se(p)))&&o&&await o.clear(p),s&&d();}}}function xe(){return et()}function Ce(o){let i=o.status;if(!o.error&&i>=200&&i<300)return null;let e=o.body,t=e&&typeof e=="object"&&typeof e.code=="string"?e.code:"",s=o.error?o.error!=="abort":!i||i===408||i===429||i>=500,r=o.error==="abort"?"ABORTED":o.error==="timeout"?"TIMEOUT":o.error==="stalled"?"STALLED":o.error||!i?"NETWORK":t||(s?"SERVER_ERROR":i===401||i===403?"AUTH":"HTTP_ERROR");return {code:r,retry:s,mismatch:i===409&&r==="CHUNK_MISMATCH",wait:s?tt(o.header("Retry-After")):void 0,httpStatus:i||void 0}}function tt(o){let i=o?Number(o)*1e3:NaN;return i>=0?Math.min(6e4,i):void 0}function ae(o,i){return (.5+i()*.5)*Math.min(3e4,1e3*2**(o-1))}function Re(o){return o.slice(0,1).arrayBuffer().then(()=>false,()=>true)}var K=class{constructor(i){this.seq=i;this.items=[];this.held=new Set;}add(i){if(this.held.has(i))return;this.held.add(i);let e=this.items,t=this.seq(i),s=e.length;for(;s>0&&this.seq(e[s-1])>t;)s--;e.splice(s,0,i);}remove(i){this.held.delete(this.items.splice(i,1)[0]);}clear(){this.items.length=0,this.held.clear();}};function Pe(o){let i=o.parallelChunkUploads;return Math.max(1,i===true?o.parallelUploads:Number(i)||1)}function Te(o){return o.maxChunksInFlight!=null?Math.max(1,o.maxChunksInFlight):1/0}function Ie(o,i,e,t){let s=o.length;for(let r=true;r&&s;){r=false;for(let n=0;n<s;n++,i++){if(!e())return i%s;t(o[i%s])&&(r=true);}}return s?i%s:0}function k(o){let i=[];for(let e of o.replace(/\\/g,"/").split("/"))e&&e!=="."&&i.push(e);return i.join("/")}function A(o){let i=o.lastIndexOf("/");return i<0?"":o.slice(0,i)}function Oe(o){return o.slice(o.lastIndexOf("/")+1)}function le(o,i){return o&&i?o+"/"+i:o||i}function I(o){return le(A(o.relativePath),o.upload.filename)}function Ne(o){let i=typeof o.length=="number"?o:o.files;return i?Array.prototype.slice.call(i):[]}function de(o){let i=typeof o.webkitRelativePath=="string"?k(o.webkitRelativePath):"";return i.indexOf("/")>0?{path:i,fromFolder:true}:{path:o.name,fromFolder:false}}function Be(o,i){let e=[],t;for(let s of o){let{path:r,fromFolder:n}=de(s);if(n&&i.ignoreHiddenFiles&&s.name.charAt(0)==="."){(t||(t=new Set)).add(A(r));continue}e.push({kind:"file",file:s,path:r,fromFolder:n});}if(t){let s=new Set;for(let n of e)for(let a=A(n.path);a&&!s.has(a);a=A(a))s.add(a);let r=Array.from(t).sort((n,a)=>a.length-n.length);for(let n of r)if(!s.has(n)){e.push({kind:"folder",path:n,raw:false});for(let a=n;a&&!s.has(a);a=A(a))s.add(a);}}return e}function J(o){let i=[],e=o.items;if(e&&e.length>0){for(let s=0;s<e.length;s++){let r=e[s];if(r.kind==="string")continue;let n=typeof r.webkitGetAsEntry=="function"?r.webkitGetAsEntry():null;if(n&&n.isDirectory){i.push({entry:n});continue}let a=typeof r.getAsFile=="function"?r.getAsFile():null;a?i.push({file:a}):n&&i.push({entry:n});}return i}let t=o.files;if(t)for(let s=0;s<t.length;s++)i.push({file:t[s]});return i}function Me(o,i){let e=typeof o.fullPath=="string"?k(o.fullPath):"";return e&&e.split("/").pop()===o.name?e:k(i?i+"/"+o.name:o.name)}var st=o=>o.startsWith(".");function Ue(o){return new Promise((i,e)=>{try{o.file(i,e);}catch(t){e(t);}})}function it(o){return new Promise((i,e)=>{try{o().readEntries(i,e);}catch(t){e(t);}})}async function*Le(o,i){let e=(l,c)=>{var d;return (d=i.onError)==null?void 0:d.call(i,l,c)},t,s=[],r=0,n=false,a=false;for(;;){let l;try{l=await it(()=>t!=null?t:t=o.entry.createReader());}catch(d){e(d,o.path),a=true;break}if(l.length===0)break;r+=l.length;let c=[];for(let d of l){let u=Me(d,o.path);if(d.isDirectory)s.push({entry:d,path:u});else if(d.isFile&&!(i.ignoreHiddenFiles&&st(d.name)))try{let p=await Ue(d);c.push({kind:"file",file:p,path:u,fromFolder:!0});}catch(p){e(p,u);}}c.length>0&&(n=true,yield c);}for(let l of s)(yield*Le(l,i))&&(n=true);return !n&&!a?(yield [{kind:"folder",path:o.path,raw:r===0}],true):n}async function*ze(o,i){var s;let e=[],t=[];for(let r of o){if("file"in r){e.push({kind:"file",file:r.file,path:r.file.name,fromFolder:false});continue}let n=r.entry;if(n.isFile){let a=k(n.name);try{let l=await Ue(n);e.push({kind:"file",file:l,path:a,fromFolder:!1});}catch(l){(s=i.onError)==null||s.call(i,l,a);}}else n.isDirectory&&i.folders&&t.push({entry:n,path:Me(n,"")});}e.length>0&&(yield e);for(let r of t)yield*Le(r,i);}var rt={Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"};function Q(o,i){return {...o.defaultHeaders?rt:null,...i,...o.headers}}function ue(o,i){let{paramName:e}=o;return typeof e=="function"?e(i):o.uploadMultiple?`${e}[${i}]`:e}function _e(o,i,e,t,s){let r={},n=o[0];return s&&(r.adUploadId=n.upload.uuid,r.adChunkIndex=s.index,r.adTotalSize=n.upload.total,r.adChunkSize=e,r.adChunkCount=n.upload.totalChunkCount,r.adChunkOffset=s.start),t?o.forEach((a,l)=>{r[`adRelativePath[${l}]`]=I(a),r[`adSessionId[${l}]`]=i(a);}):(r.adRelativePath=I(n),r.adSessionId=i(n)),r}function qe(o,i){for(let e in i){let t=i[e];if(t!=null)for(let s of Array.isArray(t)?t:[t])o.append(e,s);}}var nt="Invalid JSON response from server.";function ot(o,i){if(!i||!i.includes("application/json"))return o;try{return JSON.parse(o)}catch{return nt}}var pe={send(o){let i=new XMLHttpRequest,e,t={abort:()=>i.abort(),promise:new Promise(n=>e=n)},s=n=>{try{return i.getResponseHeader(n)}catch{return null}},r=n=>e({status:n?0:i.status,body:n?void 0:ot(i.responseText,s("content-type")),header:s,error:n,xhr:i});i.open(o.method,o.url,true),o.timeout&&(i.timeout=o.timeout),i.withCredentials=o.withCredentials,i.onload=()=>r(),i.onerror=()=>r("network"),i.ontimeout=()=>r("timeout"),i.onabort=()=>r("abort"),(i.upload||i).onprogress=n=>{t.onProgress&&t.onProgress(n.loaded,n.total);};for(let n in o.headers){let a=o.headers[n];a&&i.setRequestHeader(n,a);}return o.beforeSend&&o.beforeSend(i),i.send(o.body),t}};function He(){return {total:0,added:0,queued:0,uploading:0,paused:0,success:0,error:0,canceled:0}}var W=class{constructor(i,e,t,s){this.path=i;this.name=e;this.parent=t;this.depth=s;this.children=[];this.files=[];this.progress=0;this.bytesTotal=0;this.bytesSent=0;this.counts=He();this.userPaused=false;this._keep=false;this._fc=false;this._empty=this.status=t?"queued":"added";}},V=class{constructor(i=()=>false){this.isAllPaused=i;this.root=new W("","",null,0);this.folders=new Map([["",this.root]]);this.records=new Map;this.path=[];}get fileCount(){return this.records.size}get folderCount(){return this.folders.size-1}getFolder(i){return this.folders.get(k(i))}getFile(i){let e=this.records.get(i);return e&&e.file}has(i){let e=this.records.get(i.id);return !!e&&e.file===i}ensureFolder(i,e){let t=this.folders.get(i);if(t)return t;let s=this.ensureFolder(A(i),e),r=new W(i,Oe(i),s,s.depth+1);return s.children.push(r),this.folders.set(i,r),e&&e(r),r}addFile(i){let e=i.folder;e.files.push(i);let t={file:i,status:i.status,total:0,sent:0};this.records.set(i.id,t);for(let s=e;s;s=s.parent)s.counts.total++,s.counts[t.status]++;this.update(i,true);}update(i,e=false){let t=this.records.get(i.id);if(!t||t.file!==i)return;let s=i.status,r=i.accepted===true&&s!=="canceled",n=r?i.upload.total:0,a=r?Math.min(Math.max(i.upload.bytesSent,0),n):0,l=t.status,c=n-t.total,d=a-t.sent;if(!(l===s&&!c&&!d&&!e)){for(let u=i.folder;u;u=u.parent)l!==s&&(u.counts[l]--,u.counts[s]++),u.bytesTotal+=c,u.bytesSent+=d;t.status=s,t.total=n,t.sent=a,this.refreshPath(i.folder);}}removeFile(i){let e=this.records.get(i.id),t=[];if(!e||e.file!==i)return t;this.records.delete(i.id);let s=i.folder,r=s.files.lastIndexOf(i);r>=0&&s.files.splice(r,1);for(let a=s;a;a=a.parent)a.counts.total--,a.counts[e.status]--,a.bytesTotal-=e.total,a.bytesSent-=e.sent;let n=s;for(;n.parent&&n.counts.total===0&&n.children.length===0&&!n._keep;){let a=n.parent;a.children.splice(a.children.indexOf(n),1),this.folders.delete(n.path),t.push(n),n=a;}return this.refreshPath(n),t}pruneEmpty(){let i=[],e=t=>{for(let s of t.children.slice())e(s);t.parent&&!t.counts.total&&!t.children.length&&(t.parent.children.splice(t.parent.children.indexOf(t),1),this.folders.delete(t.path),i.push(t));};return e(this.root),i}setEmptyStatus(i,e){i._empty=e,this.refreshPath(i);}isComplete(i){let e=i.counts;return e.total>0&&e.success+e.error+e.canceled===e.total}refreshSubtree(i){this.refreshPath(i);let e=i.children.slice();for(let t=e.pop();t;t=e.pop()){this.refreshPath(t);for(let s of t.children)e.push(s);}}clear(){let i=this.root;i.children.length=0,i.files.length=0,i.counts=He(),i.bytesTotal=i.bytesSent=0,i.userPaused=false,this.folders=new Map([["",i]]),this.records=new Map,this.refreshPath(i);}refreshPath(i){let e=this.path;e.length=0;for(let s=i;s;s=s.parent)e.push(s);let t=this.isAllPaused();for(let s=e.length-1;s>=0;s--){let r=e[s];t=t||r.userPaused;let n=r.status=at(r,t);n!=="success"&&n!=="error"&&n!=="canceled"&&(r._fc=false),r.progress=r.bytesTotal>0?r.bytesSent/r.bytesTotal*100:r.status==="success"?100:0;}e.length=0;}};function at(o,i){let e=o.counts;if(e.total===0)return o._empty;let t=e.success+e.error+e.canceled;return t===e.total?e.error?"error":e.canceled===e.total?"canceled":"success":e.uploading?"uploading":i||e.paused===e.total-t?"paused":e.queued?"queued":"added"}function G(){var t,s,r;let o=new Uint8Array(16),i=typeof crypto!="undefined"?crypto:void 0;if(i&&typeof i.getRandomValues=="function")i.getRandomValues(o);else for(let n=0;n<16;n++)o[n]=Math.random()*256|0;o[6]=((t=o[6])!=null?t:0)&15|64,o[8]=((s=o[8])!=null?s:0)&63|128;let e="";for(let n=0;n<16;n++)e+=(((r=o[n])!=null?r:0)+256).toString(16).slice(1),(n===3||n===5||n===7||n===9)&&(e+="-");return e}var lt="heic:image/heic,heics:image/heic-sequence,heif:image/heif,heifs:image/heif-sequence,avif:image/avif,webp:image/webp,jpg:image/jpeg,jpeg:image/jpeg,png:image/png,gif:image/gif,bmp:image/bmp,tif:image/tiff,tiff:image/tiff,svg:image/svg+xml,dng:image/x-adobe-dng,mov:video/quicktime,mp4:video/mp4,m4v:video/x-m4v,3gp:video/3gpp,webm:video/webm,mp3:audio/mpeg,m4a:audio/mp4,aac:audio/aac,wav:audio/wav,pdf:application/pdf,txt:text/plain,csv:text/csv,json:application/json,zip:application/zip",$;function Ke(o){let i=o.lastIndexOf(".");if(i<0)return "";if(!$){$=new Map;for(let e of lt.split(",")){let t=e.indexOf(":");$.set(e.slice(0,t),e.slice(t+1));}}return $.get(o.slice(i+1).toLowerCase())||""}var Je=1024*1024;function dt(o){return (typeof o=="string"?o.split(","):Array.from(o)).map(e=>e.trim())}function Qe(o){let i=o.indexOf("/");return i<0?o:o.slice(0,i)}function ut(o,i,e){return o.startsWith(".")?i.toLowerCase().endsWith(o.toLowerCase()):o.endsWith("/*")?Qe(o)===Qe(e):o===e}function X(o,i){if(!i)return true;let e=o.type||Ke(o.name);return dt(i).some(t=>ut(t,o.name,e))}function We(o,i,e){let{maxFilesize:t,maxFiles:s}=i;if(t&&o.size>t*Je){let r=Math.round(o.size/Je*100)/100;return {code:"REJECTED_SIZE",message:i.dictFileTooBig.replace("{{filesize}}",String(r)).replace("{{maxFilesize}}",String(t))}}return X(o,i.acceptedFiles)?s!=null&&e>=s?{code:"MAX_FILES",message:i.dictMaxFilesExceeded.replace("{{maxFiles}}",String(s))}:null:{code:"REJECTED_TYPE",message:i.dictInvalidFileType}}var pt=[["tb",4],["gb",3],["mb",2],["kb",1],["b",0]];function Ve(o,i,e){let t=0,s=e.b;if(o>0){for(let[r,n]of pt){let a=i**n;if(o>=a/10){t=o/a,s=e[r];break}}t=Math.round(t*10)/10;}return `<strong>${t}</strong> ${s}`}var Ge=500,ct=1e3,ht=3,ft=5e3,mt=1e4,R=o=>o===g||o===v||o===D,ce=(o,i)=>!i||o===i||o.indexOf(i+"/")===0,F=class extends z{constructor(e={}){super();this.files=[];this.disabled=false;this.flags=new H;this.tree=new V(()=>this.flags.any());this.handlers=new Map;this.openBatches=new Set;this.batchOf=new WeakMap;this.seqOf=new WeakMap;this.timers=new Set;this.queue=new K(e=>this.seqOf.get(e)||0);this.jobs=[];this.handles=new Set;this.manifestBatches=new Set;this.folderThrottle=new _(100,e=>{this.tree.getFolder(e.path)===e&&this.emit("folderprogress",e,e.progress,e.bytesSent);});this.tickBatch=null;this.acceptedCount=0;this.seq=0;this.activeTotal=0;this.activeSent=0;this.manifestsInFlight=0;this.rr=0;this.forced=new Set;this.blobs=new WeakMap;this.queueCompleteDue=false;this.run=false;this.destroyed=false;this.own=new WeakSet;this.setupFailed=new WeakSet;this.warned=false;this.rs=null;this.claims=new Map;this.keys=new WeakMap;this.toSkip=new WeakSet;this.sent=new WeakSet;this.stale=new WeakSet;this.resends=new WeakMap;this.restored=new WeakSet;this.failedBatches=new Set;this.detach=null;this.hidden=false;this.waiters=[];this.streak=0;this.attempt=0;this.retryAt=null;this.probing=false;this.lifted=false;this.live=new Map;this.stalled=new WeakSet;this.attempts=new WeakMap;this.onFolderCreated=e=>{this.emit("addedfolder",e);};let{_uuid:t,_random:s,...r}=e;this.uuid=t||G,this.random=s||Math.random;let n=re(),a=n.dictFileSizeUnits;for(let l of Object.keys(r)){let c=r[l];c!==void 0&&(n[l]=c);}n.dictFileSizeUnits={...a,...n.dictFileSizeUnits},ne(n),typeof n.method=="string"&&(n.method=n.method.toUpperCase()),this.options=n,this.errors=new L(ke(()=>{this.destroyed||this.emit("errorlistchanged",this.errors.list());}));for(let l of ie)this.setHandler(l,n[l]);}setOption(e,t){if(this.destroyed||e==="_uuid"||e==="_random")return;let s=this.options;Fe(e)?this.setHandler(e,t):(ne({...this.options,[e]:t}),e==="dictFileSizeUnits"&&(t={...this.options.dictFileSizeUnits,...t})),s[e]=t,e==="method"&&typeof t=="string"&&(s.method=t.toUpperCase()),/^(url|parallelUploads|maxChunksInFlight|parallelChunkUploads)$/.test(e)&&this.later(()=>this.next());}on(e,t){return this.destroyed?this.unsubscribe(e,t):super.on(e,t)}once(e,t){return this.destroyed?this.unsubscribe(e,t):super.once(e,t)}resolveOption(e,...t){return typeof e=="function"?e.apply(this,t):e}_addFormElementData(e){}_completeExternal(e){this.emit("complete",e),this.run&&this.checkQueueComplete();}disable(){this.disabled=true;let e=this.files.filter(t=>t.status!==v);for(let t of e.concat(this.getUploadingFiles()))this.cancel(t);this.kick();}enable(){this.disabled=false;}getOption(e){return this.options[e]}setHandler(e,t){let s=this.handlers.get(e);if(s&&this.off(e,s),this.handlers.delete(e),typeof t=="function"){let r=t;this.handlers.set(e,r),this.on(e,r);}}drop(e){return this.destroyed||!e||!e.dataTransfer?Promise.resolve([]):(this.emit("drop",e),this.ingestRoots(J(e.dataTransfer)))}paste(e){let t=e&&e.clipboardData;if(this.destroyed||!t||t.items==null)return Promise.resolve([]);this.emit("paste",e);let s=J(t);return s.length?this.ingestRoots(s):Promise.resolve([])}addDataTransfer(e){return this.destroyed?Promise.resolve([]):this.ingestRoots(J(e))}addFromInput(e){if(this.destroyed)return Promise.resolve([]);let t=Be(Ne(e),this.options);return this.runBatch(()=>yt(t))}addFile(e,t){if(this.destroyed)throw new Error("This AnyDropCore instance was destroyed.");let s=this.tree.getFile(e.id||"");if(s===e)return s;let r,n;if(t!=null){let a=k(t);r=le(a,e.name),n=!!a;}else ({path:r,fromFolder:n}=de(e));return this.ingestFile(this.currentTickBatch(),e,r,n)}addFiles(e){return Array.from(e,t=>this.addFile(t))}getTree(){return this.tree.root}getFolder(e){return this.tree.getFolder(e)}getFile(e){return this.tree.getFile(e)}getAcceptedFiles(){return this.files.filter(e=>e.accepted)}getRejectedFiles(){return this.files.filter(e=>!e.accepted)}getFilesWithStatus(e){return this.files.filter(t=>t.status===e)}getAddedFiles(){return this.getFilesWithStatus(S)}getQueuedFiles(){return this.getFilesWithStatus(g)}getUploadingFiles(){return this.getFilesWithStatus(v)}getPausedFiles(){return this.getFilesWithStatus(D)}getActiveFiles(){return this.files.filter(e=>e.status===g||e.status===v||e.status===D)}filesize(e){return Ve(e,this.options.filesizeBase,this.options.dictFileSizeUnits)}getErrors(){return this.errors.list()}clearErrors(){this.errors.clear();}exportErrors(e="json"){return ge(this.errors.list(),e)}retryFailedOnly(e){if(this.destroyed)return 0;let t=k(e||""),s=0;for(let r of this.files)ce(r.relativePath,t)&&this.requeue(r)&&s++;return this.failedBatches.forEach(r=>{r.folders.forEach(n=>{n._empty===w&&ce(n.path,t)&&this.tree.getFolder(n.path)===n&&(this.errors.remove(null,n.path),this.tree.setEmptyStatus(n,g),r.manifestState="pending");}),r.manifestState==="pending"&&(this.failedBatches.delete(r),this.manifestBatches.add(r));}),this.options.autoProcessQueue&&this.processQueue(),s}retryFile(e){let t=this.fileOf(e),s=!!t&&!this.destroyed&&this.requeue(t);return s&&this.options.autoProcessQueue&&this.processQueue(),s}requeue(e){if(e.status!==w||e.accepted!==true)return false;let t=this.batchOf.get(e);return t&&t.manifestState==="failed"&&(t.manifestState="pending"),this.errors.remove(e.id),this.attempts.delete(e),this.setStatus(e,g),true}pause(){this.flags.all=true,this.changed("paused",{scope:"all",reason:"user"});}resume(){this.flags.all=false,this.flags.sys.clear(),this.stopProbing(),this.changed("resumed",{scope:"all",reason:"user"});}pauseFolder(e){let t=this.tree.getFolder(k(e));t&&(t.userPaused=true,this.changed("paused",{scope:"folder",folder:t,reason:"user"}));}resumeFolder(e){let t=this.tree.getFolder(k(e));t&&(t.userPaused=false,this.changed("resumed",{scope:"folder",folder:t,reason:"user"}));}pauseFile(e){let t=this.fileOf(e);t&&(this.flags.files.add(t),this.changed("paused",{scope:"file",file:t,reason:"user"}));}resumeFile(e){let t=this.fileOf(e);t&&(this.flags.files.delete(t),this.changed("resumed",{scope:"file",file:t,reason:"user"}));}cancelFolder(e){let t=k(e);for(let s of this.files.slice())(s.status===S||R(s.status))&&ce(s.relativePath,t)&&this.cancel(s);this.kick();}clearPersistedState(){if(!this.options.persistState)return Promise.resolve();let e=this.scope()+"::";return this.claims.forEach((t,s)=>{s.indexOf(e)||this.claims.delete(s);}),this.store().clear(e)}fileOf(e){let t=typeof e=="string"?this.tree.getFile(e):e;return t&&this.tree.has(t)?t:void 0}changed(e,t,s=this.options.pauseMode,r=false){this.destroyed||(t.scope!=="file"&&this.tree.refreshSubtree(t.scope==="folder"?t.folder:this.tree.root),this.apply(s),r||this.emit(e,t),this.flags.any()||this.waiters.splice(0).forEach(n=>n()),this.next());}apply(e){let t=new Set;for(let s of this.files){let r=s.status,n=R(r)?this.jobOf(s):void 0;this.flags.blocks(s)?(r===g||r===v)&&(n&&t.add(n),this.setStatus(s,D)):r===D&&this.setStatus(s,n?v:g);}e==="abort"&&t.forEach(s=>this.stopJob(s));}sysPause(e,t=this.options.pauseMode){let s=e==="unreachable",r=s&&this.lifted;s&&(this.lifted=false);let n=this.flags.sys.has(e);this.flags.sys.add(e),n?(this.apply(t),this.next()):this.changed("paused",{scope:"all",reason:e},t,r),s&&(this.flush(),!this.pt&&!this.probing&&this.reprobe());}sysResume(e){this.flags.sys.delete(e)&&this.changed("resumed",{scope:"all",reason:e});}netPause(e,t){return !e||!/^(NETWORK|TIMEOUT|STALLED)$/.test(e.code)?"":(this.victim=t,B()||this.flags.sys.has("offline")?"offline":++this.streak>=ht||this.flags.sys.has("unreachable")?"unreachable":this.hidden&&this.options.autoPauseOnHidden?"hidden":"")}getConnectionState(){let e=this.flags.sys.has("offline")?"offline":this.flags.sys.has("unreachable")||this.lifted?"unreachable":"online";return {state:e,attempt:this.attempt,retryAt:e==="unreachable"?this.retryAt:null}}reconnect(){B()||this.sysResume("offline"),this.probeNow();}reprobe(){if(!this.options.autoResumeOnReconnect||this.destroyed)return;let e=++this.attempt,t=(.5+this.random()*.5)*Math.min(6e4,2e3*2**(e-1));this.retryAt=Date.now()+t,this.emit("reconnecting",e,t),this.pt=this.later(()=>{this.probe();},t);}probeNow(){!this.flags.sys.has("unreachable")||this.probing||(this.unlater(this.pt),this.pt=void 0,this.probe());}async probe(){this.pt=void 0;let e=this.options,t=e.connectivityProbeUrl,s=this.victim&&this.victim.upload.uuid,r=t||s&&e.chunkStatusUrl&&$e(e.chunkStatusUrl,s);if(!this.flags.sys.has("unreachable")&&!this.lifted)return;if(!r)return this.lifted=true,this.flags.sys.delete("unreachable"),this.reprobe(),this.changed("resumed",{scope:"all",reason:"unreachable"},void 0,true);this.probing=true;let n=await this.send(()=>({method:t?"HEAD":"GET",url:r,headers:Q(e),body:null,timeout:mt,withCredentials:!!e.withCredentials})).promise;this.probing=false,!this.destroyed&&(n.error||!n.status)&&this.flags.sys.has("unreachable")&&this.reprobe();}reachable(){this.streak=0,!(!this.flags.sys.has("unreachable")&&!this.lifted)&&(this.flags.sys.delete("unreachable"),this.stopProbing(),this.changed("resumed",{scope:"all",reason:"unreachable"}));}stopProbing(){this.unlater(this.pt),this.pt=void 0,this.attempt=0,this.retryAt=null,this.lifted=false;}check(){let e=this.options.stallTimeout;if(!e)return;let t=Date.now();this.live.forEach((s,r)=>{t-s.at>(s.body?4:1)*e&&(this.stalled.add(r),this.abort(r));});}tick(){this.wd=this.later(()=>{this.wd=void 0,this.check(),this.live.size&&this.tick();},ft);}grace(e){return e&&e.code==="NETWORK"&&!B()&&!this.flags.sys.size?new Promise(t=>this.later(t,ct)):Promise.resolve()}watch(){this.detach||this.destroyed||(this.hidden=typeof document!="undefined"&&document.visibilityState==="hidden",this.detach=De({online:()=>{this.emit("online"),this.check(),this.options.autoResumeOnReconnect&&(this.sysResume("offline"),this.probeNow());},offline:()=>{this.emit("offline"),this.sysPause("offline");},visibility:e=>{this.flush(),this.hidden=e,e||(this.sysResume("hidden"),this.check(),this.options.autoResumeOnReconnect&&this.probeNow());},pagehide:()=>{this.flush(),this.options.autoPauseOnHidden&&this.sysPause("hidden","abort");},pageshow:()=>this.sysResume("hidden")}));}store(){return this.rs||(this.rs=xe())}flush(){this.rs&&this.rs.flush();}scope(){let e=this.options;return encodeURIComponent(e.persistKey!=null?e.persistKey:typeof e.url=="string"?e.url:"default")}keyOf(e){let t=this.keys.get(e);return this.options.persistState&&t&&this.claims.get(t)===e?t:void 0}persist(e,t){let s=this.keyOf(e);if(!s||!t&&(this.blobs.get(e)||e)!==e)return;let r=e.upload;this.store().put({key:s,uploadId:r.uuid,chunkSize:r.chunkSize,totalChunks:r.totalChunkCount,chunksDone:Array.from(r.chunksDone),completed:t,updatedAt:Date.now()});}unpersist(e){let t=this.keyOf(e);t&&this.store().del(t);}enqueueFile(e){let t=this.batchOf.get(e);if(t&&!t.closed&&this.tree.has(e))t.deferred.push({file:e,process:false});else if(e.status===S&&e.accepted===true)this.setStatus(e,g),this.options.autoProcessQueue&&this.later(()=>this.processQueue());else throw new Error("This file can't be queued because it has already been processed or was rejected.")}enqueueFiles(e){for(let t of e)this.enqueueFile(t);}processQueue(){this.destroyed||(this.watch(),this.offlineStart(),this.openBatches.forEach(e=>{e.closed||(e.processRequested=true);}),this.startFiles(),this.fill());}processFiles(e){if(!this.destroyed){this.watch();for(let t of e){let s=this.batchOf.get(t);s&&!s.closed?s.deferred.push({file:t,process:true}):t.status===g?this.forced.add(t):C("processFile: the file is not queued:",t.relativePath,t.status);}this.offlineStart(),this.startForced(),this.fill();}}offlineStart(){B()&&!this.flags.sys.has("offline")&&this.tree.root.counts.queued&&this.sysPause("offline");}processFile(e){this.processFiles([e]);}uploadFile(e){this.processFiles([e]);}uploadFiles(e){this.processFiles(e);}cancelUpload(e){this.tree.has(e)&&(this.cancel(e),this.kick());}cancel(e){if(!this.tree.has(e))return;let t=this.jobOf(e),s=t?t.files:[e];t&&this.endJob(t);let r=s.filter(n=>n.status===S||R(n.status));for(let n of r)this.unpersist(n),this.setStatus(n,T);for(let n of r)this.emit("canceled",n),this.completed(n);r.length&&this.options.uploadMultiple&&this.emit("canceledmultiple",r);}kick(){this.options.autoProcessQueue?this.processQueue():this.next();}jobOf(e){return this.jobs.find(t=>t.files.indexOf(e)>=0)}removeFile(e){if(!this.tree.has(e))return;(e.status===v||this.jobOf(e))&&this.cancelUpload(e);let t=this.files.lastIndexOf(e);t>=0&&this.files.splice(t,1),this.removed(e,e.status,this.forget(e)),this.files.length===0&&this.emit("reset");}removed(e,t,s){this.emit("removedfile",e);for(let r of s)this.emit("removedfolder",r);this.emitTotal(),this.checkMaxFilesReached(),this.run&&(t===S||t===g||t===D)&&(this.foldersCompletedBy(e),this.checkQueueComplete());}removeAllFiles(e=false){let t=this.files.filter(a=>a.status!==v||e);for(let a of t)(a.status===v||this.jobOf(a))&&this.cancelUpload(a);let s=t.map(a=>a.status),r=[];for(let a=t.length-1;a>=0;a--)r[a]=this.forget(t[a]);let n=this.files.filter(a=>this.tree.has(a));this.files.length=0,this.files.push(...n),t.forEach((a,l)=>this.removed(a,s[l],r[l]));for(let a of this.tree.pruneEmpty())this.errors.remove(null,a.path),this.emit("removedfolder",a);t.length&&this.files.length===0&&this.emit("reset");}destroy(){if(!this.destroyed){this.destroyed=true,this.rs&&this.rs.close(),this.detach&&this.detach(),this.detach=null,this.waiters.length=0;for(let e of this.jobs)e.dead=true;this.jobs.length=0,this.handles.forEach(e=>this.abort(e)),this.handles.clear(),this.folderThrottle.clear(),this.timers.forEach(e=>clearTimeout(e)),this.timers.clear(),this.live.clear(),this.queue.clear(),this.manifestBatches.clear(),this.claims.clear(),this.forced.clear(),this.openBatches.forEach(e=>this.finishBatch(e)),this.tickBatch=null,this.off(),this.handlers.clear(),this.errors.clear(),this.tree.clear(),this.files.length=0,this.acceptedCount=0;}}get isDestroyed(){return this.destroyed}ingestRoots(e){return this.runBatch(t=>ze(e,{ignoreHiddenFiles:this.options.ignoreHiddenFiles,folders:this.options.folders,onError:(s,r)=>t.readErrors.push(r)}))}runBatch(e){let t=this.newBatch();return (async()=>{try{for await(let s of e(t)){if(this.destroyed)break;for(let r of s)this.ingestItem(t,r);}}catch(s){E(s);}t.walking=false,this.maybeCloseBatch(t);})(),t.promise}newBatch(){let e=he(this.uuid());return this.openBatches.add(e),e}currentTickBatch(){let e=this.tickBatch;if(!e){let t=e=this.tickBatch=this.newBatch();Promise.resolve().then(()=>{this.tickBatch===t&&(this.tickBatch=null),t.walking=false,this.maybeCloseBatch(t);});}return e}ingestItem(e,t){if(t.kind==="file"){this.ingestFile(e,t.file,t.path,t.fromFolder);return}this.options.preserveEmptyFolders&&(this.folderFor(e,t.path)._keep=true),t.raw&&this.emit("emptyfolder",t.path);}folderFor(e,t){let s=t?this.tree.ensureFolder(t,this.onFolderCreated):this.tree.root;for(let r=s;r&&r.parent&&!e.folders.has(r);r=r.parent)e.folders.add(r);return s}ingestFile(e,t,s,r){let n=this.options,a=this.folderFor(e,A(s)),l=be(t,{id:this.uuid(),uploadId:this.uuid(),relativePath:s,fromFolder:r,folder:a,chunking:n.chunking,forceChunking:n.forceChunking,chunkSize:n.chunkSize,rename:c=>this.renameFile(c)});return this.files.push(l),this.tree.addFile(l),e.files.push(l),this.batchOf.set(l,e),this.seqOf.set(l,this.seq++),this.emit("addedfile",l),this.validate(e,l),l}renameFile(e){let t=this.options.renameFile;if(typeof t!="function")return e.name;try{return String(t.call(this,e))}catch(s){return E(s),e.name}}validate(e,t){e.pending++;let s=false,r=(d,u)=>{s||(s=true,e.pending--,this.onValidated(e,t,d,u),this.maybeCloseBatch(e));},n=this.options,a=t.upload.filename,l=t.relativePath.split("/").indexOf("..")>=0||/[\\/]|^\.\.?$/.test(a)?{message:n.dictInvalidPath,code:"INVALID_PATH"}:We(t,n,this.acceptedCount);if(l){r(l.message,l.code),l.code==="MAX_FILES"&&this.emit("maxfilesexceeded",t);return}let c=d=>r(d,"REJECTED");try{n.accept.call(this,t,c);}catch(d){E(d),r(d instanceof Error?d.message:String(d),"REJECTED");}}onValidated(e,t,s,r){this.destroyed||!this.tree.has(t)||(s?(t.accepted=false,this.setStatus(t,w),this.errors.set({fileId:t.id,relativePath:t.relativePath,uploadId:null,code:r,message:M(s),stage:"validate",attempt:0,retryable:false,at:Date.now()}),this.emit("error",t,s),this.emit("complete",t),this.options.uploadMultiple&&(this.emit("errormultiple",[t],s),this.emit("completemultiple",[t])),e.closed?this.foldersCompletedBy(t):e.terminalIn.add(t.folder),this.checkQueueComplete(),this.options.autoProcessQueue&&this.processQueue()):(t.accepted=true,this.acceptedCount++,this.tree.update(t)),this.checkMaxFilesReached());}checkMaxFilesReached(){let e=this.options.maxFiles;e!=null&&this.acceptedCount===e&&this.emit("maxfilesreached",this.files);}maybeCloseBatch(e){e.closed||e.walking||e.pending>0||(e.closed=true,this.closeBatch(e));}async closeBatch(e){e.readErrors.length&&C(`${e.readErrors.length} dropped item(s) could not be read:`,e.readErrors);try{await this.prepareBatch(e);}catch(n){E(n);}if(this.destroyed)return;let t=this.options,s=e.files.filter(n=>this.tree.has(n));this.emit("addedfiles",s);for(let n of s)this.toSkip.has(n)&&!t.chunkStatusUrl&&this.tree.has(n)&&this.skip(n);if(t.autoQueue)for(let n of s)n.status===S&&n.accepted===true&&this.setStatus(n,g);let r=new Set(this.manifestDue()?[]:this.settleEmpty(e,x));e.terminalIn.forEach(n=>{for(let a=n;a&&a.parent;a=a.parent)!a._fc&&this.tree.isComplete(a)&&this.tree.getFolder(a.path)===a&&r.add(a);}),this.foldersComplete(Array.from(r)),this.finishBatch(e),this.manifestDue()&&this.manifestBatches.add(e);for(let{file:n,process:a}of e.deferred)if(this.tree.has(n)){if(n.accepted!==true){C("rejected, not queued:",n.relativePath);continue}n.status===S&&this.setStatus(n,g),a&&this.forced.add(n);}(t.autoProcessQueue||e.processRequested)&&(e.processRequested=false,this.processQueue()),this.startForced(),this.fill(),s.length&&this.checkQueueComplete();}foldersComplete(e){e.sort((t,s)=>s.depth-t.depth);for(let t of e)t._fc=true,this.emit("foldercomplete",t);}settleEmpty(e,t,s){let r=[];return e.folders.forEach(n=>{n.counts.total===0&&n._empty===g&&this.tree.getFolder(n.path)===n&&(this.tree.setEmptyStatus(n,t),s&&this.errors.set({...s,fileId:null,uploadId:null,relativePath:n.path}),r.push(n));}),r}async prepareBatch(e){let t=this.options;if(!t.persistState)return;let s=[],r=this.scope()+"::";for(let l of e.files){if(l.accepted!==true||!this.tree.has(l))continue;let c=r+l.fingerprint,d=this.claims.get(c);d&&d!==l&&this.tree.has(d)&&!se(d.status)||(this.claims.set(c,l),this.keys.set(l,c),s.push(l));}if(!s.length)return;let n=this.store(),a=await n.get(r,s.map(l=>this.keys.get(l)));s.forEach((l,c)=>{let d=a[c],u=l.upload;!d||!this.tree.has(l)||(d.completed?(u.uuid=d.uploadId,u.resumed=true,this.toSkip.add(l)):t.chunking&&d.chunkSize===Number(t.chunkSize)&&d.totalChunks===Math.max(1,Math.ceil(l.size/d.chunkSize))?(u.uuid=d.uploadId,u.chunked=u.resumed=true,u.chunkSize=d.chunkSize,u.totalChunkCount=d.totalChunks,u.chunksDone=new Set(Xe(d.chunksDone,d.totalChunks)),this.restored.add(l)):n.del(d.key));});}skip(e){let t=e.upload;this.toSkip.delete(e),t.skipped=t.resumed=true,this.setSent(e,t.total,true),this.setStatus(e,x),this.persist(e,true),this.emit("success",e,{skipped:true,uploadId:t.uuid},null),this.completed(e);}finishBatch(e){e.closed=true,this.openBatches.delete(e),e.resolve(e.files.filter(t=>this.tree.has(t)));}setStatus(e,t){t===g&&this.flags.blocks(e)&&(t=D);let s=R(e.status);if(s!==R(t)){let r=s?-1:1;this.activeTotal+=r*e.upload.total,this.activeSent+=r*e.upload.bytesSent;}e.status=t,this.tree.update(e),t===g&&this.queue.add(e);}completed(e){this.emit("complete",e),this.foldersCompletedBy(e),this.checkQueueComplete();}checkQueueComplete(){this.queueCompleteDue||(this.queueCompleteDue=true,this.later(()=>{this.queueCompleteDue=false;let e=this.tree.root.counts;!e.added&&!e.queued&&!e.uploading&&!e.paused&&!this.jobs.length&&!this.openBatches.size&&!this.manifestsInFlight&&(this.run=false,this.emit("queuecomplete"));}));}foldersCompletedBy(e){let t=this.batchOf.get(e);if(t&&!t.closed){t.terminalIn.add(e.folder);return}let s=[];for(let r=e.folder;r.parent;r=r.parent)!r._fc&&this.tree.isComplete(r)&&this.tree.getFolder(r.path)===r&&s.push(r);this.foldersComplete(s);}forget(e){e.accepted===true&&this.acceptedCount--,R(e.status)&&(this.activeTotal-=e.upload.total,this.activeSent-=e.upload.bytesSent),this.forced.delete(e),this.flags.files.delete(e),this.unpersist(e);let t=this.keys.get(e);t&&this.claims.get(t)===e&&this.claims.delete(t);let s=this.tree.removeFile(e);this.errors.remove(e.id);let r=this.batchOf.get(e);if(r&&!r.closed){let n=r.files.lastIndexOf(e);n>=0&&r.files.splice(n,1);}return s}next(){if(!this.destroyed){for(let e of this.jobs.slice()){let t=0;e.busy.forEach(s=>t+=s.wait?0:1),!t&&!e.finishing&&e.files.every(s=>s.status===D)&&(this.endJob(e),this.progress(e));}this.options.autoProcessQueue&&this.startFiles(),this.fill();}}manifestDue(){let e=this.options;return e.sendManifest&&!e.manifestUrl&&!this.warned&&(this.warned=true,C("sendManifest is set but manifestUrl is not: no manifest is sent.")),!!e.sendManifest&&!!e.manifestUrl}manifestOk(e){return !this.manifestDue()||e.manifestState==="sent"?true:(e.manifestState==="pending"&&this.sendManifest(e),false)}startForced(){!this.options.url||this.destroyed||this.forced.forEach(e=>{if(e.status!==g||!this.tree.has(e))return void this.forced.delete(e);if(!this.manifestOk(this.batchOf.get(e)))return;let t=[];this.forced.forEach(s=>{(s===e||this.options.uploadMultiple)&&s.status===g&&this.manifestOk(this.batchOf.get(s))&&(t.push(s),this.forced.delete(s));}),this.startJob(t);});}startFiles(){let e=this.options;if(!e.url)return;this.manifestBatches.forEach(r=>{this.manifestBatches.delete(r),r.manifestState==="pending"&&(r.files.some(n=>this.tree.has(n)&&(n.status===g||n.status===S))||(this.settleEmpty(r,g).length?this.sendManifest(r):r.manifestState="sent"));});let t=e.parallelUploads-this.jobs.reduce((r,n)=>r+n.files.length,0),s=this.queue.items;for(let r=0;t>0&&r<s.length;){let n=s[r];if(n.status!==g||!this.tree.has(n)){this.queue.remove(r);continue}let a=this.batchOf.get(n);if(!this.manifestOk(a)){a.processRequested=true,r++;continue}this.queue.remove(r);let l=[n];for(let c=r;e.uploadMultiple&&l.length<t&&c<s.length;){let d=s[c];d.status===g&&this.tree.has(d)&&this.manifestOk(this.batchOf.get(d))?(l.push(d),this.queue.remove(c)):c++;}t-=l.length,this.startJob(l);}}startJob(e){let t=this.options,s=e[0],r=this.attempts.get(s);r||this.attempts.set(s,r=new Map);let n={files:e,size:0,busy:new Map,tries:r,doneBytes:0,mismatches:0,finishing:true};this.jobs.push(n),this.run=true;for(let u of e)this.setStatus(u,v),this.emit("processing",u);t.uploadMultiple&&this.emit("processingmultiple",e);let a=()=>{if(n.dead)return;for(let h of e){let m=this.blobs.get(h)||h,f=h.upload;m!==h&&this.restored.has(h)&&(this.renew(h),f.resumed=false),this.restored.delete(h);let y=f.total;n.size=fe(h,m.size,t,this.sent.has(h)||f.chunksDone.size>0),this.activeTotal+=f.total-y,this.tree.update(h);}n.doneBytes=j(s,n.size),this.progress(n);let u=!!t.chunkStatusUrl&&e.length<2&&(s.upload.resumed||this.sent.has(s)),p=()=>{n.finishing=false,u?this.refreshStatus(n):s.upload.chunked&&N(s,n.busy)<0?this.finishChunks(n):d||this.next();};!u&&e.some(h=>this.stale.has(h))?this.announce(n).then(h=>h&&p()):p();},l=t.transformFile,c=e.length,d=true;for(let u of e){if(!l||this.blobs.has(u)){--c||a();continue}let p=false;try{l.call(this,u,h=>{p||(p=!0,this.blobs.set(u,h||u),--c||a());});}catch(h){return E(h),this.failJob(n,{code:"TRANSFORM_FAILED",message:M(h),stage:"upload",attempt:1})}}d=false;}fill(){let e=this.options,t=Te(e),s=Pe(e),r=0;for(let n of this.jobs)n.busy.forEach(a=>r+=a.wait?0:1);this.rr=Ie(this.jobs,this.rr,()=>r<t,n=>{let a=n.files[0];if(n.finishing||n.busy.size>=s||a.status===D)return false;let l=a.upload.chunked?N(a,n.busy):n.busy.size?-1:0;return l<0?false:(r++,this.sendUpload(n,l),true)});}sendUpload(e,t){let s=this.options,r=e.files,n=r[0],a=n.upload.chunked?U(n,t,e.size,e.tries.get(t)||0):null;a&&this.sent.add(n);let l={loaded:0};e.busy.set(t,l);let c=this.send(()=>{let d=a?[{name:ue(s,0),data:(this.blobs.get(n)||n).slice(a.start,a.end),filename:n.upload.filename,chunkIndex:t}]:r.map((p,h)=>({name:ue(s,h),data:this.blobs.get(p)||p,filename:p.upload.filename})),u=s.binaryBody?null:new FormData;return {method:String(this.resolveOption(s.method,r,d)).toUpperCase(),url:String(this.resolveOption(s.url,r,d)),headers:Q(s,s.binaryBody?{"Content-Type":n.type}:void 0),body:u||d[0].data,timeout:this.resolveOption(s.timeout,r),withCredentials:!!s.withCredentials,beforeSend:p=>{let h=p;if(h)for(let f of r)f.xhr=h;let m=s.params;if(u){let y=_e(r,b=>this.batchOf.get(b).sessionId,e.size,s.uploadMultiple,a||void 0);qe(u,Object.assign(y,typeof m=="function"?m.call(this,r,h,a):m));}for(let f of r)this.emit("sending",f,h,u||void 0);if(s.uploadMultiple&&this.emit("sendingmultiple",r,h,u||void 0),u){this._addFormElementData(u);for(let f of d)u.append(f.name,f.data,f.filename);}}}});if(l.h=c,e.dead)return this.abort(c);c.onProgress=(d,u)=>{let p=this.live.get(c);p&&(p.at=Date.now(),u>0&&d>=u&&(p.body=true)),e.busy.get(t)===l&&(l.loaded=u>0?Math.min(1,d/u):0,this.progress(e));},c.promise.then(d=>this.uploaded(e,t,l,d));}uploaded(e,t,s,r){if(e.dead||e.busy.get(t)!==s)return;e.busy.delete(t);let n=this.classify(r);if(n)return void this.failed(e,t,n,r);e.response=r.body;let a=e.files[0];if(!a.upload.chunked)return this.succeed(e);a.upload.chunksDone.add(t),e.tries.delete(t),e.doneBytes+=U(a,t,e.size,0).end-t*e.size,this.progress(e),this.persist(a,false),N(a,e.busy)<0&&!e.busy.size?this.finishChunks(e):this.next();}classify(e){return this.setupFailed.has(e)?{code:"REQUEST_SETUP_FAILED",retry:false,mismatch:false}:Ce(e)}async failed(e,t,s,r){let n=this.options,a=e.files[0],l={loaded:0,wait:true};if(e.busy.set(t,l),await this.grace(s),e.dead||e.busy.get(t)!==l)return;let c=this.netPause(s,a);if(c)return e.busy.delete(t),this.sysPause(c,c==="unreachable"?void 0:"abort");let d=(e.tries.get(t)||0)+1;if(e.tries.set(t,d),this.progress(e),this.next(),e.dead)return;if(s.code==="NETWORK"){let p=await Promise.all(e.files.map(m=>Re(this.blobs.get(m)||m)));if(e.dead)return;let h=e.files.filter((m,f)=>p[f]);if(h.length){this.endJob(e);let m=e.files.filter(f=>h.indexOf(f)<0);this.failFiles(h,{code:"UNREADABLE",message:n.dictFileUnreadable,stage:"upload",attempt:d,chunkIndex:t}),m.length&&this.failFiles(m,this.failInfo(s,r,"upload",d));return}}let u=a.upload.chunked;if(u&&s.mismatch&&n.chunkStatusUrl&&e.mismatches++<3)return e.busy.delete(t),this.refreshStatus(e);if(u&&s.retry&&n.retryChunks&&d<=n.retryChunksLimit)return this.later(()=>{e.busy.get(t)===l&&(e.busy.delete(t),this.next());},s.wait!=null?s.wait:ae(d,this.random));this.failJob(e,this.failInfo(s,r,"upload",d,u?t:void 0));}async finishChunks(e){e.finishing=true;let t=this.options,s=e.files[0],r=t.chunksUploaded;if(typeof r=="function"){let d=false,u=p=>{if(!(d||e.dead)){if(d=true,!(p instanceof Error||typeof p=="string"&&p))return this.succeed(e);this.failJob(e,{code:"FINALIZE_FAILED",message:M(p),stage:"finalize",attempt:1});}};try{r.call(t,s,u,this);}catch(p){E(p),u(p instanceof Error?p:Error(String(p)));}return}if(!t.finalizeUrl)return this.succeed(e);let n={uploadId:s.upload.uuid,relativePath:I(s),totalSize:s.upload.total,totalChunks:s.upload.totalChunkCount},[a,l,c]=await this.call(e,"POST",t.finalizeUrl,JSON.stringify(n));if(!e.dead){if(!l)return e.response=a.body,this.succeed(e);if(l.mismatch&&t.chunkStatusUrl&&e.mismatches++<3)return this.refreshStatus(e);this.failJob(e,this.failInfo(l,a,"finalize",c));}}async refreshStatus(e){if(e.st)return;e.st=e.finishing=true,e.busy.forEach(u=>u.h&&this.abort(u.h)),e.busy.clear();let t=this.options.chunkStatusUrl,s=e.files[0],r=s.upload,[n,a,l]=await this.call(e,"GET",$e(t,r.uuid),null);if(e.st=false,e.dead)return;let c=n.body||{},d=this.toSkip.has(s);if(n.status===404||!a&&d&&c.complete!==true)this.renew(s);else {if(a)return this.failJob(e,this.failInfo(a,n,"status",l));if(c.complete===true&&d)return this.endJob(e),this.skip(s),this.next();r.chunked&&(r.chunksDone=new Set(Xe(c.received,r.totalChunkCount)),r.resumed=true);}this.toSkip.delete(s),e.doneBytes=j(s,e.size),this.progress(e),await this.announce(e)&&(e.finishing=false,r.chunked&&N(s,e.busy)<0?this.finishChunks(e):this.next());}postManifest(e){let t=e.files.filter(a=>a.accepted&&a.status!==T&&!a.upload.skipped&&this.tree.has(a)),s=[],r=[];e.folders.forEach(a=>{this.tree.getFolder(a.path)===a&&(s.push(a.path),a.depth===1&&r.push(a.name));});let n={sessionId:e.sessionId,roots:r,folders:s.sort(),files:t.map(a=>({uploadId:a.upload.uuid,relativePath:I(a),size:a.size,lastModified:a.lastModified,type:a.type}))};return this.call(null,"POST",this.options.manifestUrl,JSON.stringify(n))}async sendManifest(e){e.manifestState="sending",this.manifestsInFlight++;let[t,s,r]=await this.postManifest(e);if(this.manifestsInFlight--,!this.destroyed){if(e.manifestState=s?"failed":"sent",s||e.files.forEach(n=>this.stale.delete(n)),s){this.failedBatches.add(e);let n=this.failInfo(s,t,"manifest",r),a=e.files.filter(l=>l.accepted&&!se(l.status)&&this.tree.has(l)&&!this.jobOf(l));a.length&&this.failFiles(a,n),this.foldersComplete(this.settleEmpty(e,w,this.entry(null,n)));}else this.foldersComplete(this.settleEmpty(e,x));this.startForced(),(e.processRequested||this.options.autoProcessQueue)&&(e.processRequested=false,this.startFiles()),this.fill(),this.checkQueueComplete();}}renew(e){let t=e.upload;this.unpersist(e),t.uuid=this.uuid(),t.chunksDone=new Set,this.stale.add(e),this.persist(e,false);}async announce(e){let t=e.files.filter(n=>this.stale.has(n));if(!t.length)return true;let r=(await Promise.all(Array.from(new Set(t.map(n=>this.batchOf.get(n))),n=>this.resend(n)))).find(n=>n);return r||t.forEach(n=>this.stale.delete(n)),e.dead?false:(r&&this.failJob(e,r),!r)}resend(e){if(e.manifestState!=="sent"||!this.manifestDue())return Promise.resolve(null);let t=this.resends.get(e);t||this.resends.set(e,t={});let s=t;return s.next||(s.next=(async()=>{await s.cur,await new Promise(n=>this.later(n)),s.next=void 0;let r=this.postManifest(e).then(([n,a,l])=>a?this.failInfo(a,n,"manifest",l):null);return s.cur=r,r})())}async call(e,t,s,r){let n=this.options;for(let a=1;;a++){let l=this.send(()=>({method:t,url:s,body:r,headers:Q(n,r?{"Content-Type":"application/json"}:void 0),timeout:this.resolveOption(n.timeout,e?e.files:[]),withCredentials:!!n.withCredentials}));e&&(e.aux=l);let c=await l.promise,d=this.classify(c);await this.grace(d);let u=this.netPause(d,e?e.files[0]:void 0);if(u&&!(e&&e.dead)&&!this.destroyed){if(this.sysPause(u,u==="unreachable"?void 0:"abort"),e)return e.dead||this.stopJob(e),[c,d,a];await new Promise(h=>this.waiters.push(h)),a--;continue}if(!d||!d.retry||!n.retryChunks||a>n.retryChunksLimit||e&&e.dead)return [c,d,a];let p=d.wait!=null?d.wait:ae(a,this.random);if(await new Promise(h=>this.later(h,p)),e&&e.dead)return [c,d,a]}}send(e){let t,s=true;try{let n=e();s=!n.body||typeof n.body=="string",t=(this.options.transport||pe).send(n);}catch(n){E(n);let a={status:0,body:M(n),header:()=>null};this.setupFailed.add(a),t={abort(){},promise:Promise.resolve(a)};}let r=t;return this.handles.add(r),this.live.set(r,{at:Date.now(),body:s}),this.options.stallTimeout&&!this.wd&&this.tick(),r.promise.then(n=>{this.handles.delete(r),this.live.delete(r),this.live.size||(this.unlater(this.wd),this.wd=void 0),n.error==="abort"?this.stalled.has(r)?n.error="stalled":this.own.has(r)||(n.error="network"):!n.error&&n.status&&this.reachable();}),r}abort(e){this.own.add(e),e.abort();}progress(e){let t=e.files[0];if(t.upload.chunked){let s=e.doneBytes;e.busy.forEach((r,n)=>s+=r.loaded*(U(t,n,e.size,0).end-n*e.size)),this.setSent(t,s);}else {let s=e.busy.get(0);for(let r of e.files)this.setSent(r,(s?s.loaded:0)*r.upload.total);}}setSent(e,t,s=false){let r=e.upload,n=s?100:r.total?t/r.total*100:0;if(!(t===r.bytesSent&&n===r.progress)&&(R(e.status)&&(this.activeSent+=t-r.bytesSent),r.bytesSent=t,r.progress=n,this.tree.update(e),this.emit("uploadprogress",e,n,t),this.emitTotal(),this.hasListeners("folderprogress")))for(let a=e.folder;a.parent;a=a.parent)this.folderThrottle.request(a,a.progress>=100);}emitTotal(){let e=this.activeTotal;this.emit("totaluploadprogress",e?100*this.activeSent/e:100,e,this.activeSent);}endJob(e){e.dead=true;let t=this.jobs.indexOf(e);t>=0&&this.jobs.splice(t,1),e.busy.forEach(s=>s.h&&this.abort(s.h)),e.busy.clear(),e.aux&&this.abort(e.aux);}stopJob(e){this.endJob(e),this.progress(e);for(let t of e.files)t.status===v&&this.setStatus(t,g);}succeed(e){this.endJob(e);let t=e.files;for(let s of t)this.setSent(s,s.upload.total,true),this.setStatus(s,x),this.persist(s,true),this.emit("success",s,e.response,null),this.completed(s);this.options.uploadMultiple&&(this.emit("successmultiple",t,e.response,null),this.emit("completemultiple",t)),this.next();}failJob(e,t){this.endJob(e),this.failFiles(e.files,t);}failInfo(e,t,s,r,n){let a=this.options,l=t.body,c=l!=null&&l!==""?l:t.error==="timeout"?`Request timedout after ${(Number(this.resolveOption(a.timeout,[]))||0)/1e3} seconds`:a.dictResponseError.replace("{{statusCode}}",String(t.status));return {code:e.code,message:c,stage:s,attempt:r,res:t,chunkIndex:n}}entry(e,t){return {fileId:e&&e.id,relativePath:e?e.relativePath:"",uploadId:e&&e.upload.uuid,code:t.code,message:M(t.message),httpStatus:t.res&&t.res.status||void 0,stage:t.stage,chunkIndex:t.chunkIndex,attempt:t.attempt,retryable:true,at:Date.now()}}failFiles(e,t){let s=t.res&&t.res.xhr;for(let r of e)this.setStatus(r,w),this.errors.set(this.entry(r,t)),this.emit("error",r,t.message,s),this.completed(r);this.options.uploadMultiple&&(this.emit("errormultiple",e,t.message,s),this.emit("completemultiple",e)),this.next();}later(e,t=0){let s=setTimeout(()=>{this.timers.delete(s),this.destroyed||e();},t);return this.timers.add(s),s}unlater(e){clearTimeout(e),e&&this.timers.delete(e);}};F.version=Z,F.ADDED=S,F.QUEUED=g,F.ACCEPTED=ee,F.UPLOADING=v,F.PROCESSING=te,F.PAUSED=D,F.SUCCESS=x,F.ERROR=w,F.CANCELED=T,F.isValidFile=X,F.uuidv4=G;function $e(o,i){return o+(o.indexOf("?")<0?"?":"&")+"uploadId="+encodeURIComponent(i)}function Xe(o,i){return (Array.isArray(o)?o:[]).filter(e=>Number.isInteger(e)&&e>=0&&e<i)}function M(o){if(typeof o=="string")return o;if(o&&typeof o.message=="string")return o.message;try{return JSON.stringify(o)}catch{return String(o)}}async function*yt(o){for(let i=0;i<o.length;i+=Ge)i&&await ve(),yield o.slice(i,i+Ge);}exports.ACCEPTED=ee;exports.ADDED=S;exports.AnyDropCore=F;exports.CANCELED=T;exports.ERROR=w;exports.PAUSED=D;exports.PROCESSING=te;exports.QUEUED=g;exports.SUCCESS=x;exports.UPLOADING=v;exports.VERSION=Z;exports.defaultOptions=re;exports.isValidFile=X;exports.uuidv4=G;exports.xhrTransport=pe;return exports;})({});
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vedratech/anydrop-core",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Headless folder upload engine for the browser: chunked and resumable uploads, pause/resume, retry, offline handling. No dependencies, TypeScript.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"bugs": {
|
|
13
13
|
"url": "https://github.com/vedratech/anydrop/issues"
|
|
14
14
|
},
|
|
15
|
-
"author": "
|
|
15
|
+
"author": "Vedra Tech",
|
|
16
16
|
"keywords": [
|
|
17
17
|
"upload",
|
|
18
18
|
"file-upload",
|