@dropgate/core 2.2.0 → 3.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/README.md +259 -128
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +2814 -1436
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +424 -283
- package/dist/index.d.ts +424 -283
- package/dist/index.js +2816 -1389
- package/dist/index.js.map +1 -1
- package/dist/p2p/index.cjs +495 -190
- package/dist/p2p/index.cjs.map +1 -1
- package/dist/p2p/index.d.cts +366 -5
- package/dist/p2p/index.d.ts +366 -5
- package/dist/p2p/index.js +497 -178
- package/dist/p2p/index.js.map +1 -1
- package/package.json +15 -12
package/dist/index.browser.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var DropgateCore=(()=>{var Ne=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var nt=(r,e)=>{for(var t in e)Ne(r,t,{get:e[t],enumerable:!0})},ot=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of tt(e))!rt.call(r,o)&&o!==t&&Ne(r,o,{get:()=>e[o],enumerable:!(n=et(e,o))||n.enumerable});return r};var st=r=>ot(Ne({},"__esModule",{value:!0}),r);var lt={};nt(lt,{AES_GCM_IV_BYTES:()=>he,AES_GCM_TAG_BYTES:()=>We,DEFAULT_CHUNK_SIZE:()=>Ee,DropgateAbortError:()=>J,DropgateClient:()=>Me,DropgateError:()=>G,DropgateNetworkError:()=>M,DropgateProtocolError:()=>V,DropgateTimeoutError:()=>de,DropgateValidationError:()=>f,ENCRYPTION_OVERHEAD_PER_CHUNK:()=>Ae,arrayBufferToBase64:()=>ue,base64ToBytes:()=>qe,buildBaseUrl:()=>ke,buildPeerOptions:()=>ae,bytesToBase64:()=>$e,createPeerWithRetries:()=>Be,decryptChunk:()=>se,decryptFilenameFromBase64:()=>be,encryptFilenameToBase64:()=>Te,encryptToBlob:()=>Pe,estimateTotalUploadSizeBytes:()=>Ie,exportKeyBase64:()=>Oe,fetchJson:()=>re,generateAesGcmKey:()=>Fe,generateP2PCode:()=>ve,getDefaultBase64:()=>ee,getDefaultCrypto:()=>fe,getDefaultFetch:()=>ye,getServerInfo:()=>ze,importKeyFromBase64:()=>we,isLocalhostHostname:()=>De,isP2PCodeLike:()=>Se,isSecureContextForP2P:()=>Le,lifetimeToMs:()=>Xe,makeAbortSignal:()=>oe,parseSemverMajorMinor:()=>ge,parseServerUrl:()=>Ze,resolvePeerConfig:()=>ie,sha256Hex:()=>Re,sleep:()=>me,startP2PReceive:()=>Ke,startP2PSend:()=>Ge,validatePlainFilename:()=>xe});var Ee=5242880,he=12,We=16,Ae=28;var G=class extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.code=t.code||"DROPGATE_ERROR",this.details=t.details,t.cause!==void 0&&Object.defineProperty(this,"cause",{value:t.cause,writable:!1,enumerable:!1,configurable:!0})}},f=class extends G{constructor(e,t={}){super(e,{...t,code:t.code||"VALIDATION_ERROR"})}},M=class extends G{constructor(e,t={}){super(e,{...t,code:t.code||"NETWORK_ERROR"})}},V=class extends G{constructor(e,t={}){super(e,{...t,code:t.code||"PROTOCOL_ERROR"})}},J=class extends G{constructor(e="Operation aborted"){super(e,{code:"ABORT_ERROR"}),this.name="AbortError"}},de=class extends G{constructor(e="Request timed out"){super(e,{code:"TIMEOUT_ERROR"}),this.name="TimeoutError"}};function ee(){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return{encode(r){return Buffer.from(r).toString("base64")},decode(r){return new Uint8Array(Buffer.from(r,"base64"))}};if(typeof btoa=="function"&&typeof atob=="function")return{encode(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)},decode(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}};throw new Error("No Base64 implementation available. Provide a Base64Adapter via options.")}function fe(){return globalThis.crypto}function ye(){return globalThis.fetch?.bind(globalThis)}var _e=null;function Ye(r){return r||(_e||(_e=ee()),_e)}function $e(r,e){return Ye(e).encode(r)}function ue(r,e){return $e(new Uint8Array(r),e)}function qe(r,e){return Ye(e).decode(r)}var it={minutes:6e4,hours:36e5,days:864e5};function Xe(r,e){let t=String(e||"").toLowerCase(),n=Number(r);if(t==="unlimited"||!Number.isFinite(n)||n<=0)return 0;let o=it[t];return o?Math.round(n*o):0}function ge(r){let e=String(r||"").split(".").map(o=>Number(o)),t=Number.isFinite(e[0])?e[0]:0,n=Number.isFinite(e[1])?e[1]:0;return{major:t,minor:n}}function xe(r){if(typeof r!="string"||r.trim().length===0)throw new f("Invalid filename. Must be a non-empty string.");if(r.length>255||/[\/\\]/.test(r))throw new f("Invalid filename. Contains illegal characters or is too long.")}function Ze(r){let e=r.trim();!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e);let t=new URL(e);return{host:t.hostname,port:t.port?Number(t.port):void 0,secure:t.protocol==="https:"}}function ke(r){let{host:e,port:t,secure:n}=r;if(!e||typeof e!="string")throw new f("Server host is required.");let o=n===!1?"http":"https",s=t?`:${t}`:"";return`${o}://${e}${s}`}function me(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(e.reason||new J);let o=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(o),n(e.reason||new J)},{once:!0})})}function oe(r,e){let t=new AbortController,n=null,o=s=>{t.signal.aborted||t.abort(s)};return r&&(r.aborted?o(r.reason):r.addEventListener("abort",()=>o(r.reason),{once:!0})),Number.isFinite(e)&&e>0&&(n=setTimeout(()=>{o(new de)},e)),{signal:t.signal,cleanup:()=>{n&&clearTimeout(n)}}}async function re(r,e,t={}){let{timeoutMs:n,signal:o,...s}=t,{signal:d,cleanup:y}=oe(o,n);try{let i=await r(e,{...s,signal:d}),u=await i.text(),m=null;try{m=u?JSON.parse(u):null}catch{}return{res:i,json:m,text:u}}finally{y()}}async function we(r,e,t){let o=(t||ee()).decode(e),s=new Uint8Array(o).buffer;return r.subtle.importKey("raw",s,{name:"AES-GCM"},!0,["decrypt"])}async function se(r,e,t){let n=e.slice(0,12),o=e.slice(12);return r.subtle.decrypt({name:"AES-GCM",iv:n},t,o)}async function be(r,e,t,n){let s=(n||ee()).decode(e),d=await se(r,s,t);return new TextDecoder().decode(d)}async function Re(r,e){let t=await r.subtle.digest("SHA-256",e),n=new Uint8Array(t),o="";for(let s=0;s<n.length;s++)o+=n[s].toString(16).padStart(2,"0");return o}async function Fe(r){return r.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}async function Oe(r,e){let t=await r.subtle.exportKey("raw",e);return ue(t)}async function Pe(r,e,t){let n=r.getRandomValues(new Uint8Array(12)),o=await r.subtle.encrypt({name:"AES-GCM",iv:n},t,e);return new Blob([n,new Uint8Array(o)])}async function Te(r,e,t){let n=new TextEncoder().encode(String(e)),s=await(await Pe(r,n.buffer,t)).arrayBuffer();return ue(s)}function Ie(r,e,t){let n=Number(r)||0;return t?n+(Number(e)||0)*28:n}async function ze(r){let{host:e,port:t,secure:n,timeoutMs:o=5e3,signal:s,fetchFn:d}=r,y=d||ye();if(!y)throw new f("No fetch() implementation found.");let i=ke({host:e,port:t,secure:n});try{let{res:u,json:m}=await re(y,`${i}/api/info`,{method:"GET",timeoutMs:o,signal:s,headers:{Accept:"application/json"}});if(u.ok&&m&&typeof m=="object"&&"version"in m)return{baseUrl:i,serverInfo:m};throw new V(`Server info request failed (status ${u.status}).`)}catch(u){throw u instanceof G?u:new M("Could not reach server /api/info.",{cause:u})}}var Me=class{constructor(e){if(!e||typeof e.clientVersion!="string")throw new f("DropgateClient requires clientVersion (string).");this.clientVersion=e.clientVersion,this.chunkSize=Number.isFinite(e.chunkSize)?e.chunkSize:5242880;let t=e.fetchFn||ye();if(!t)throw new f("No fetch() implementation found.");this.fetchFn=t;let n=e.cryptoObj||fe();if(!n)throw new f("No crypto implementation found.");this.cryptoObj=n,this.base64=e.base64||ee(),this.logger=e.logger||null}async resolveShareTarget(e,t){let{timeoutMs:n=5e3,signal:o}=t,s=await this.checkCompatibility(t);if(!s.compatible)throw new f(s.message);let{baseUrl:d}=s,{res:y,json:i}=await re(this.fetchFn,`${d}/api/resolve`,{method:"POST",timeoutMs:n,signal:o,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({value:e})});if(!y.ok){let u=(i&&typeof i=="object"&&"error"in i?i.error:null)||`Share lookup failed (status ${y.status}).`;throw new V(u,{details:i})}return i||{valid:!1,reason:"Unknown response."}}async checkCompatibility(e){let t,n;try{let i=await ze({...e,fetchFn:this.fetchFn});t=i.baseUrl,n=i.serverInfo}catch(i){throw i instanceof G?i:new M("Could not connect to the server.",{cause:i})}let o=String(n?.version||"0.0.0"),s=String(this.clientVersion||"0.0.0"),d=ge(s),y=ge(o);return d.major!==y.major?{compatible:!1,clientVersion:s,serverVersion:o,message:`Incompatible versions. Client v${s}, Server v${o}${n?.name?` (${n.name})`:""}.`,serverInfo:n,baseUrl:t}:d.minor>y.minor?{compatible:!0,clientVersion:s,serverVersion:o,message:`Client (v${s}) is newer than Server (v${o})${n?.name?` (${n.name})`:""}. Some features may not work.`,serverInfo:n,baseUrl:t}:{compatible:!0,clientVersion:s,serverVersion:o,message:`Server: v${o}, Client: v${s}${n?.name?` (${n.name})`:""}.`,serverInfo:n,baseUrl:t}}validateUploadInputs(e){let{file:t,lifetimeMs:n,encrypt:o,serverInfo:s}=e,d=s?.capabilities?.upload;if(!d||!d.enabled)throw new f("Server does not support file uploads.");let y=Number(t?.size||0);if(!t||!Number.isFinite(y)||y<=0)throw new f("File is missing or invalid.");let i=Number(d.maxSizeMB);if(Number.isFinite(i)&&i>0){let E=i*1e3*1e3,R=Math.ceil(y/this.chunkSize);if(Ie(y,R,!!o)>E){let D=o?`File too large once encryption overhead is included. Server limit: ${i} MB.`:`File too large. Server limit: ${i} MB.`;throw new f(D)}}let u=Number(d.maxLifetimeHours),m=Number(n);if(!Number.isFinite(m)||m<0||!Number.isInteger(m))throw new f("Invalid lifetime. Must be a non-negative integer (milliseconds).");if(Number.isFinite(u)&&u>0){let E=Math.round(u*60*60*1e3);if(m===0)throw new f(`Server does not allow unlimited file lifetime. Max: ${u} hours.`);if(m>E)throw new f(`File lifetime too long. Server limit: ${u} hours.`)}if(o&&!d.e2ee)throw new f("End-to-end encryption is not supported on this server.");return!0}async uploadFile(e){let{host:t,port:n,secure:o,file:s,lifetimeMs:d,encrypt:y,maxDownloads:i,filenameOverride:u,onProgress:m,onCancel:E,signal:R,timeouts:_={},retry:D={}}=e,q=R?null:new AbortController,O=R||q?.signal,$="initializing",v=null,S=null,L=(async()=>{try{let b=w=>{try{m&&m(w)}catch{}};if(!this.cryptoObj?.subtle)throw new f("Web Crypto API not available (crypto.subtle).");let h=s.size;b({phase:"server-info",text:"Checking server...",percent:0,processedBytes:0,totalBytes:h});let x=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:_.serverInfoMs??5e3,signal:O}),{baseUrl:p,serverInfo:B}=x;if(b({phase:"server-compat",text:x.message,percent:0,processedBytes:0,totalBytes:h}),!x.compatible)throw new f(x.message);let l=u??s.name??"file",K=!!B?.capabilities?.upload?.e2ee,C=y??K;C||xe(l),this.validateUploadInputs({file:s,lifetimeMs:d,encrypt:C,serverInfo:B});let P=null,k=null,H=l;if(C){b({phase:"crypto",text:"Generating encryption key...",percent:0,processedBytes:0,totalBytes:h});try{P=await Fe(this.cryptoObj),k=await Oe(this.cryptoObj,P),H=await Te(this.cryptoObj,l,P)}catch(w){throw new G("Failed to prepare encryption.",{code:"CRYPTO_PREP_FAILED",cause:w})}}let a=Math.ceil(s.size/this.chunkSize),g=Ie(s.size,a,C);b({phase:"init",text:"Reserving server storage...",percent:0,processedBytes:0,totalBytes:h});let U={filename:H,lifetime:d,isEncrypted:C,totalSize:g,totalChunks:a,...i!==void 0?{maxDownloads:i}:{}},T=await re(this.fetchFn,`${p}/upload/init`,{method:"POST",timeoutMs:_.initMs??15e3,signal:O,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(U)});if(!T.res.ok){let Z=T.json?.error||`Server initialisation failed: ${T.res.status}`;throw new V(Z,{details:T.json||T.text})}let j=T.json?.uploadId;if(!j||typeof j!="string")throw new V("Server did not return a valid uploadId.");v=j,S=p,$="uploading";let Q=Number.isFinite(D.retries)?D.retries:5,W=Number.isFinite(D.backoffMs)?D.backoffMs:1e3,A=Number.isFinite(D.maxBackoffMs)?D.maxBackoffMs:3e4;for(let w=0;w<a;w++){if(O?.aborted)throw O.reason||new J;let Z=w*this.chunkSize,Ue=Math.min(Z+this.chunkSize,s.size),N=s.slice(Z,Ue),I=w/a*100,je=w*this.chunkSize;b({phase:"chunk",text:`Uploading chunk ${w+1} of ${a}...`,percent:I,processedBytes:je,totalBytes:h,chunkIndex:w,totalChunks:a});let ce=await N.arrayBuffer(),te;if(C&&P?te=await Pe(this.cryptoObj,ce,P):te=new Blob([ce]),te.size>5243904)throw new f("Chunk too large (client-side). Check chunk size settings.");let le=await te.arrayBuffer(),Ce=await Re(this.cryptoObj,le),pe={"Content-Type":"application/octet-stream","X-Upload-ID":j,"X-Chunk-Index":String(w),"X-Chunk-Hash":Ce},Ve=`${p}/upload/chunk`;await this.attemptChunkUpload(Ve,{method:"POST",headers:pe,body:te},{retries:Q,backoffMs:W,maxBackoffMs:A,timeoutMs:_.chunkMs??6e4,signal:O,progress:b,chunkIndex:w,totalChunks:a,chunkSize:this.chunkSize,fileSizeBytes:h})}b({phase:"complete",text:"Finalising upload...",percent:100,processedBytes:h,totalBytes:h}),$="completing";let F=await re(this.fetchFn,`${p}/upload/complete`,{method:"POST",timeoutMs:_.completeMs??3e4,signal:O,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:j})});if(!F.res.ok){let Z=F.json?.error||"Finalisation failed.";throw new V(Z,{details:F.json||F.text})}let c=F.json?.id;if(!c||typeof c!="string")throw new V("Server did not return a valid file id.");let z=`${p}/${c}`;return C&&k&&(z+=`#${k}`),b({phase:"done",text:"Upload successful!",percent:100,processedBytes:h,totalBytes:h}),$="completed",{downloadUrl:z,fileId:c,uploadId:j,baseUrl:p,...C&&k?{keyB64:k}:{}}}catch(b){throw b instanceof Error&&(b.name==="AbortError"||b.message?.includes("abort"))?($="cancelled",E?.()):$="error",b}})(),X=async(b,h)=>{try{await re(this.fetchFn,`${h}/upload/cancel`,{method:"POST",timeoutMs:5e3,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:b})})}catch{}};return{result:L,cancel:b=>{$==="completed"||$==="cancelled"||($="cancelled",v&&S&&X(v,S).catch(()=>{}),q?.abort(new J(b||"Upload cancelled by user.")))},getStatus:()=>$}}async downloadFile(e){let{host:t,port:n,secure:o,fileId:s,keyB64:d,onProgress:y,onData:i,signal:u,timeoutMs:m=6e4}=e,E=l=>{try{y&&y(l)}catch{}};if(!s||typeof s!="string")throw new f("File ID is required.");E({phase:"server-info",text:"Checking server...",processedBytes:0,totalBytes:0,percent:0});let R=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:m,signal:u}),{baseUrl:_}=R;if(E({phase:"server-compat",text:R.message,processedBytes:0,totalBytes:0,percent:0}),!R.compatible)throw new f(R.message);E({phase:"metadata",text:"Fetching file info...",processedBytes:0,totalBytes:0,percent:0});let{signal:D,cleanup:q}=oe(u,m),O;try{let l=await this.fetchFn(`${_}/api/file/${s}/meta`,{method:"GET",headers:{Accept:"application/json"},signal:D});if(!l.ok)throw l.status===404?new V("File not found or has expired."):new V(`Failed to fetch file metadata (status ${l.status}).`);O=await l.json()}catch(l){throw l instanceof G?l:l instanceof Error&&l.name==="AbortError"?new J("Download cancelled."):new M("Could not fetch file metadata.",{cause:l})}finally{q()}let $=!!O.isEncrypted,v=O.sizeBytes||0;if(!i&&v>104857600){let l=Math.round(v/1048576),K=Math.round(104857600/(1024*1024));throw new f(`File is too large (${l}MB) to download without streaming. Provide an onData callback to stream files larger than ${K}MB.`)}let S,L;if($){if(!d)throw new f("Decryption key is required for encrypted files.");if(!this.cryptoObj?.subtle)throw new f("Web Crypto API not available for decryption.");E({phase:"decrypting",text:"Preparing decryption...",processedBytes:0,totalBytes:0,percent:0});try{L=await we(this.cryptoObj,d,this.base64),S=await be(this.cryptoObj,O.encryptedFilename,L,this.base64)}catch(l){throw new G("Failed to decrypt filename. Invalid key or corrupted data.",{code:"DECRYPT_FILENAME_FAILED",cause:l})}}else S=O.filename||"file";E({phase:"downloading",text:"Starting download...",percent:0,processedBytes:0,totalBytes:v});let{signal:X,cleanup:b}=oe(u,m),h=0,x=[],p=!i;try{let l=await this.fetchFn(`${_}/api/file/${s}`,{method:"GET",signal:X});if(!l.ok)throw new V(`Download failed (status ${l.status}).`);if(!l.body)throw new V("Streaming response not available.");let K=l.body.getReader();if($&&L){let C=this.chunkSize+28,P=[],k=0,H=()=>{if(P.length===0)return new Uint8Array(0);if(P.length===1){let U=P[0];return P.length=0,k=0,U}let a=new Uint8Array(k),g=0;for(let U of P)a.set(U,g),g+=U.length;return P.length=0,k=0,a};for(;;){if(u?.aborted)throw new J("Download cancelled.");let{done:a,value:g}=await K.read();if(a)break;for(P.push(g),k+=g.length;k>=C;){let T=H(),ne=T.subarray(0,C);if(T.length>C){let W=T.subarray(C);P.push(W),k=W.length}let j=await se(this.cryptoObj,ne,L),Q=new Uint8Array(j);p?x.push(Q):await i(Q)}h+=g.length;let U=v>0?Math.round(h/v*100):0;E({phase:"decrypting",text:`Downloading & decrypting... (${U}%)`,percent:U,processedBytes:h,totalBytes:v})}if(k>0){let a=H(),g=await se(this.cryptoObj,a,L),U=new Uint8Array(g);p?x.push(U):await i(U)}}else for(;;){if(u?.aborted)throw new J("Download cancelled.");let{done:C,value:P}=await K.read();if(C)break;p?x.push(P):await i(P),h+=P.length;let k=v>0?Math.round(h/v*100):0;E({phase:"downloading",text:`Downloading... (${k}%)`,percent:k,processedBytes:h,totalBytes:v})}}catch(l){throw l instanceof G?l:l instanceof Error&&l.name==="AbortError"?new J("Download cancelled."):new M("Download failed.",{cause:l})}finally{b()}E({phase:"complete",text:"Download complete!",percent:100,processedBytes:h,totalBytes:v});let B;if(p&&x.length>0){let l=x.reduce((C,P)=>C+P.length,0);B=new Uint8Array(l);let K=0;for(let C of x)B.set(C,K),K+=C.length}return{filename:S,receivedBytes:h,wasEncrypted:$,...B?{data:B}:{}}}async attemptChunkUpload(e,t,n){let{retries:o,backoffMs:s,maxBackoffMs:d,timeoutMs:y,signal:i,progress:u,chunkIndex:m,totalChunks:E,chunkSize:R,fileSizeBytes:_}=n,D=o,q=s,O=o;for(;;){if(i?.aborted)throw i.reason||new J;let{signal:$,cleanup:v}=oe(i,y);try{let S=await this.fetchFn(e,{...t,signal:$});if(S.ok)return;let L=await S.text().catch(()=>"");throw new V(`Chunk ${m+1} failed (HTTP ${S.status}).`,{details:{status:S.status,bodySnippet:L.slice(0,120)}})}catch(S){if(v(),S instanceof Error&&(S.name==="AbortError"||S.code==="ABORT_ERR"))throw S;if(i?.aborted)throw i.reason||new J;if(D<=0)throw S instanceof G?S:new M("Chunk upload failed.",{cause:S});let L=O-D+1,X=m*R,b=m/E*100,h=q,x=100;for(;h>0;){let p=(h/1e3).toFixed(1);u({phase:"retry-wait",text:`Chunk upload failed. Retrying in ${p}s... (${L}/${O})`,percent:b,processedBytes:X,totalBytes:_,chunkIndex:m,totalChunks:E}),await me(Math.min(x,h),i),h-=x}u({phase:"retry",text:`Chunk upload failed. Retrying now... (${L}/${O})`,percent:b,processedBytes:X,totalBytes:_,chunkIndex:m,totalChunks:E}),D-=1,q=Math.min(q*2,d);continue}finally{v()}}}};function De(r){let e=String(r||"").toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Le(r,e){return!!e||De(r||"")}function ve(r){let e=r||fe(),t="ABCDEFGHJKLMNPQRSTUVWXYZ";if(e){let s=new Uint8Array(8);e.getRandomValues(s);let d="";for(let i=0;i<4;i++)d+=t[s[i]%t.length];let y="";for(let i=4;i<8;i++)y+=(s[i]%10).toString();return`${d}-${y}`}let n="";for(let s=0;s<4;s++)n+=t[Math.floor(Math.random()*t.length)];let o="";for(let s=0;s<4;s++)o+=Math.floor(Math.random()*10);return`${n}-${o}`}function Se(r){return/^[A-Z]{4}-\d{4}$/.test(String(r||"").trim())}function ie(r,e){return{path:r.peerjsPath??e?.peerjsPath??"/peerjs",iceServers:r.iceServers??e?.iceServers??[]}}function ae(r={}){let{host:e,port:t,peerjsPath:n="/peerjs",secure:o=!1,iceServers:s=[]}=r,d={host:e,path:n,secure:o,config:{iceServers:s},debug:0};return t&&(d.port=t),d}async function Be(r){let{code:e,codeGenerator:t,maxAttempts:n,buildPeer:o,onCode:s}=r,d=e||t(),y=null,i=null;for(let u=0;u<n;u++){s?.(d,u);try{return y=await new Promise((m,E)=>{let R=o(d);R.on("open",()=>m(R)),R.on("error",_=>{try{R.destroy()}catch{}E(_)})}),{peer:y,code:d}}catch(m){i=m,d=t()}}throw i||new M("Could not establish PeerJS connection.")}function ct(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async function Ge(r){let{file:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:d,secure:y=!1,iceServers:i,codeGenerator:u,cryptoObj:m,maxAttempts:E=4,chunkSize:R=256*1024,endAckTimeoutMs:_=15e3,bufferHighWaterMark:D=8*1024*1024,bufferLowWaterMark:q=2*1024*1024,heartbeatIntervalMs:O=5e3,onCode:$,onStatus:v,onProgress:S,onComplete:L,onError:X,onDisconnect:b,onCancel:h}=r;if(!e)throw new f("File is missing.");if(!t)throw new f("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let x=n?.capabilities?.p2p;if(n&&!x?.enabled)throw new f("Direct transfer is disabled on this server.");let{path:p,iceServers:B}=ie({peerjsPath:d,iceServers:i},x),l=ae({host:o,port:s,peerjsPath:p,secure:y,iceServers:B}),K=u||(()=>ve(m)),C=c=>new t(c,l),{peer:P,code:k}=await Be({code:null,codeGenerator:K,maxAttempts:E,buildPeer:C,onCode:$}),H=ct(),a="listening",g=null,U=0,T=null,ne=c=>{let z=Number.isFinite(c.total)&&c.total>0?c.total:e.size,w=Math.min(Number(c.received)||0,z||0),Z=z?w/z*100:0;S?.({processedBytes:w,totalBytes:z,percent:Z})},j=c=>{a==="closed"||a==="completed"||a==="cancelled"||(a="closed",X?.(c),W())},Q=()=>{a==="finishing"&&(a="completed",L?.(),W())},W=()=>{T&&(clearInterval(T),T=null),typeof window<"u"&&window.removeEventListener("beforeunload",A);try{g?.close()}catch{}try{P.destroy()}catch{}},A=()=>{try{g?.send({t:"error",message:"Sender closed the connection."})}catch{}F()};typeof window<"u"&&window.addEventListener("beforeunload",A);let F=()=>{if(a==="closed"||a==="cancelled")return;let c=a==="transferring"||a==="finishing";a="cancelled";try{g&&g.open&&g.send({t:"cancelled",message:"Sender cancelled the transfer."})}catch{}c&&h&&h({cancelledBy:"sender"}),W()},Y=()=>a==="closed"||a==="cancelled";return P.on("connection",c=>{if(a==="closed")return;if(g){let N=g.open!==!1;if(N&&a==="transferring"){try{c.send({t:"error",message:"Transfer already in progress."})}catch{}try{c.close()}catch{}return}else if(N){try{c.send({t:"error",message:"Another receiver is already connected."})}catch{}try{c.close()}catch{}return}else{try{g.close()}catch{}g=null,a="listening",U=0}}g=c,a="negotiating",v?.({phase:"waiting",message:"Connected. Waiting for receiver to accept..."});let z=null,w=null,Z=new Promise(N=>{z=N}),Ue=new Promise(N=>{w=N});c.on("data",N=>{if(!N||typeof N!="object"||N instanceof ArrayBuffer||ArrayBuffer.isView(N))return;let I=N;if(I.t){if(I.t==="ready"){v?.({phase:"transferring",message:"Receiver accepted. Starting transfer..."}),z?.();return}if(I.t==="progress"){ne({received:I.received||0,total:I.total||0});return}if(I.t==="ack"&&I.phase==="end"){w?.(I);return}if(I.t!=="pong"){if(I.t==="error"){j(new M(I.message||"Receiver reported an error."));return}if(I.t==="cancelled"){if(a==="cancelled"||a==="closed"||a==="completed")return;a="cancelled",h?.({cancelledBy:"receiver",message:I.message}),W()}}}}),c.on("open",async()=>{try{if(Y())return;c.send({t:"meta",sessionId:H,name:e.name,size:e.size,mime:e.type||"application/octet-stream"});let N=e.size,I=c._dc;if(I&&Number.isFinite(q))try{I.bufferedAmountLowThreshold=q}catch{}if(await Z,Y())return;O>0&&(T=setInterval(()=>{if(a==="transferring"||a==="finishing")try{c.send({t:"ping"})}catch{}},O)),a="transferring";for(let pe=0;pe<N;pe+=R){if(Y())return;let Je=await e.slice(pe,pe+R).arrayBuffer();if(Y())return;if(c.send(Je),U+=Je.byteLength,I)for(;I.bufferedAmount>D;)await new Promise(He=>{let Qe=setTimeout(He,60);try{I.addEventListener("bufferedamountlow",()=>{clearTimeout(Qe),He()},{once:!0})}catch{}})}if(Y())return;a="finishing",c.send({t:"end"});let je=Number.isFinite(_)?Math.max(_,Math.ceil(e.size/(1024*1024))*1e3):null,ce=await Promise.race([Ue,me(je||15e3).catch(()=>null)]);if(Y())return;if(!ce||typeof ce!="object")throw new M("Receiver did not confirm completion.");let te=ce,le=Number(te.total)||e.size,Ce=Number(te.received)||0;if(le&&Ce<le)throw new M("Receiver reported an incomplete transfer.");ne({received:Ce||le,total:le}),Q()}catch(N){j(N)}}),c.on("error",N=>{j(N)}),c.on("close",()=>{if(a==="closed"||a==="completed"||a==="cancelled"){W();return}a==="transferring"||a==="finishing"?(a="cancelled",h?.({cancelledBy:"receiver"}),W()):(g=null,a="listening",U=0,b?.())})}),{peer:P,code:k,sessionId:H,stop:F,getStatus:()=>a,getBytesSent:()=>U,getConnectedPeerId:()=>g&&g.peer||null}}async function Ke(r){let{code:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:d,secure:y=!1,iceServers:i,autoReady:u=!0,watchdogTimeoutMs:m=15e3,onStatus:E,onMeta:R,onData:_,onProgress:D,onComplete:q,onError:O,onDisconnect:$,onCancel:v}=r;if(!e)throw new f("No sharing code was provided.");if(!t)throw new f("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let S=n?.capabilities?.p2p;if(n&&!S?.enabled)throw new f("Direct transfer is disabled on this server.");let L=String(e).trim().replace(/\s+/g,"").toUpperCase();if(!Se(L))throw new f("Invalid direct transfer code.");let{path:X,iceServers:b}=ie({peerjsPath:d,iceServers:i},S),h=ae({host:o,port:s,peerjsPath:X,secure:y,iceServers:b}),x=new t(void 0,h),p="initializing",B=0,l=0,K=null,C=0,P=120,k=Promise.resolve(),H=null,a=null,g=()=>{m<=0||(H&&clearTimeout(H),H=setTimeout(()=>{p==="transferring"&&T(new M("Connection timed out (no data received)."))},m))},U=()=>{H&&(clearTimeout(H),H=null)},T=A=>{p==="closed"||p==="completed"||p==="cancelled"||(p="closed",O?.(A),j())},ne=A=>{p==="transferring"&&(p="completed",q?.(A),j())},j=()=>{U(),typeof window<"u"&&window.removeEventListener("beforeunload",Q);try{x.destroy()}catch{}},Q=()=>{try{a?.send({t:"error",message:"Receiver closed the connection."})}catch{}W()};typeof window<"u"&&window.addEventListener("beforeunload",Q);let W=()=>{if(p==="closed"||p==="cancelled")return;let A=p==="transferring";p="cancelled";try{a&&a.open&&a.send({t:"cancelled",message:"Receiver cancelled the transfer."})}catch{}A&&v&&v({cancelledBy:"receiver"}),j()};return x.on("error",A=>{T(A)}),x.on("open",()=>{p="connecting";let A=x.connect(L,{reliable:!0});a=A,A.on("open",()=>{p="negotiating",E?.({phase:"connected",message:"Waiting for file details..."})}),A.on("data",async F=>{try{if(g(),F&&typeof F=="object"&&!(F instanceof ArrayBuffer)&&!ArrayBuffer.isView(F)){let c=F;if(c.t==="meta"){if(K&&c.sessionId&&c.sessionId!==K){try{A.send({t:"error",message:"Busy with another session."})}catch{}return}c.sessionId&&(K=c.sessionId);let z=String(c.name||"file");B=Number(c.size)||0,l=0,k=Promise.resolve();let w=()=>{p="transferring",g();try{A.send({t:"ready"})}catch{}};u?(R?.({name:z,total:B}),D?.({processedBytes:l,totalBytes:B,percent:0}),w()):(R?.({name:z,total:B,sendReady:w}),D?.({processedBytes:l,totalBytes:B,percent:0}));return}if(c.t==="ping"){try{A.send({t:"pong"})}catch{}return}if(c.t==="end"){if(U(),await k,B&&l<B){let z=new M("Transfer ended before the full file was received.");try{A.send({t:"error",message:z.message})}catch{}throw z}try{A.send({t:"ack",phase:"end",received:l,total:B})}catch{}ne({received:l,total:B});return}if(c.t==="error")throw new M(c.message||"Sender reported an error.");if(c.t==="cancelled"){if(p==="cancelled"||p==="closed"||p==="completed")return;p="cancelled",v?.({cancelledBy:"sender",message:c.message}),j();return}return}let Y;if(F instanceof ArrayBuffer)Y=Promise.resolve(new Uint8Array(F));else if(ArrayBuffer.isView(F))Y=Promise.resolve(new Uint8Array(F.buffer,F.byteOffset,F.byteLength));else if(typeof Blob<"u"&&F instanceof Blob)Y=F.arrayBuffer().then(c=>new Uint8Array(c));else return;k=k.then(async()=>{let c=await Y;_&&await _(c),l+=c.byteLength;let z=B?Math.min(100,l/B*100):0;D?.({processedBytes:l,totalBytes:B,percent:z});let w=Date.now();if(l===B||w-C>=P){C=w;try{A.send({t:"progress",received:l,total:B})}catch{}}}).catch(c=>{try{A.send({t:"error",message:c?.message||"Receiver write failed."})}catch{}T(c)})}catch(Y){T(Y)}}),A.on("close",()=>{if(p==="closed"||p==="completed"||p==="cancelled"){j();return}p==="transferring"?(p="cancelled",v?.({cancelledBy:"sender"}),j()):p==="negotiating"?(p="closed",j(),$?.()):T(new M("Sender disconnected before file details were received."))})}),{peer:x,stop:W,getStatus:()=>p,getBytesReceived:()=>l,getTotalBytes:()=>B,getSessionId:()=>K}}return st(lt);})();
|
|
1
|
+
"use strict";var DropgateCore=(()=>{var Xe=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Xt=Object.prototype.hasOwnProperty;var Qt=(r,e,t)=>e in r?Xe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var er=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var tr=(r,e)=>{for(var t in e)Xe(r,t,{get:e[t],enumerable:!0})},rr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yt(e))!Xt.call(r,i)&&i!==t&&Xe(r,i,{get:()=>e[i],enumerable:!(n=Zt(e,i))||n.enumerable});return r};var nr=r=>rr(Xe({},"__esModule",{value:!0}),r);var Q=(r,e,t)=>Qt(r,typeof e!="symbol"?e+"":e,t);var kr={};tr(kr,{AES_GCM_IV_BYTES:()=>je,AES_GCM_TAG_BYTES:()=>xt,DEFAULT_CHUNK_SIZE:()=>dt,DropgateAbortError:()=>te,DropgateClient:()=>pt,DropgateError:()=>X,DropgateNetworkError:()=>N,DropgateProtocolError:()=>H,DropgateTimeoutError:()=>Te,DropgateValidationError:()=>S,ENCRYPTION_OVERHEAD_PER_CHUNK:()=>Qe,StreamingZipWriter:()=>Ne,arrayBufferToBase64:()=>Ue,base64ToBytes:()=>Ct,buildBaseUrl:()=>Ke,bytesToBase64:()=>gt,decryptChunk:()=>xe,decryptFilenameFromBase64:()=>De,encryptFilenameToBase64:()=>st,encryptToBlob:()=>_e,estimateTotalUploadSizeBytes:()=>qe,exportKeyBase64:()=>it,fetchJson:()=>oe,generateAesGcmKey:()=>nt,generateP2PCode:()=>He,getDefaultBase64:()=>be,getDefaultCrypto:()=>Re,getDefaultFetch:()=>$e,getServerInfo:()=>ut,importKeyFromBase64:()=>Ee,isLocalhostHostname:()=>lt,isP2PCodeLike:()=>Ge,isSecureContextForP2P:()=>vt,lifetimeToMs:()=>At,makeAbortSignal:()=>Oe,parseSemverMajorMinor:()=>Le,parseServerUrl:()=>tt,sha256Hex:()=>rt,sleep:()=>me,validatePlainFilename:()=>et});var dt=5242880,je=12,xt=16,Qe=28;var X=class extends Error{constructor(t,n={}){super(t,n.cause!==void 0?{cause:n.cause}:void 0);Q(this,"code");Q(this,"details");this.name=this.constructor.name,this.code=n.code||"DROPGATE_ERROR",this.details=n.details}},S=class extends X{constructor(e,t={}){super(e,{...t,code:t.code||"VALIDATION_ERROR"})}},N=class extends X{constructor(e,t={}){super(e,{...t,code:t.code||"NETWORK_ERROR"})}},H=class extends X{constructor(e,t={}){super(e,{...t,code:t.code||"PROTOCOL_ERROR"})}},te=class extends X{constructor(e="Operation aborted"){super(e,{code:"ABORT_ERROR"}),this.name="AbortError"}},Te=class extends X{constructor(e="Request timed out"){super(e,{code:"TIMEOUT_ERROR"}),this.name="TimeoutError"}};function be(){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return{encode(r){return Buffer.from(r).toString("base64")},decode(r){return new Uint8Array(Buffer.from(r,"base64"))}};if(typeof btoa=="function"&&typeof atob=="function")return{encode(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)},decode(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}};throw new Error("No Base64 implementation available. Provide a Base64Adapter via options.")}function Re(){return globalThis.crypto}function $e(){return globalThis.fetch?.bind(globalThis)}var mt=null;function St(r){return r||(mt||(mt=be()),mt)}function gt(r,e){return St(e).encode(r)}function Ue(r,e){return gt(new Uint8Array(r),e)}function Ct(r,e){return St(e).decode(r)}var ir={minutes:6e4,hours:36e5,days:864e5};function At(r,e){let t=String(e||"").toLowerCase(),n=Number(r);if(t==="unlimited"||!Number.isFinite(n)||n<=0)return 0;let i=ir[t];return i?Math.round(n*i):0}function Le(r){let e=String(r||"").split(".").map(i=>Number(i)),t=Number.isFinite(e[0])?e[0]:0,n=Number.isFinite(e[1])?e[1]:0;return{major:t,minor:n}}function et(r){if(typeof r!="string"||r.trim().length===0)throw new S("Invalid filename. Must be a non-empty string.");if(r.length>255||/[\/\\]/.test(r))throw new S("Invalid filename. Contains illegal characters or is too long.")}function tt(r){let e=r.trim();!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e);let t=new URL(e);return{host:t.hostname,port:t.port?Number(t.port):void 0,secure:t.protocol==="https:"}}function Ke(r){let{host:e,port:t,secure:n}=r;if(!e||typeof e!="string")throw new S("Server host is required.");let i=n===!1?"http":"https",s=t?`:${t}`:"";return`${i}://${e}${s}`}function me(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(e.reason||new te);let i=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(i),n(e.reason||new te)},{once:!0})})}function Oe(r,e){let t=new AbortController,n=null,i=s=>{t.signal.aborted||t.abort(s)};return r&&(r.aborted?i(r.reason):r.addEventListener("abort",()=>i(r.reason),{once:!0})),Number.isFinite(e)&&e>0&&(n=setTimeout(()=>{i(new Te)},e)),{signal:t.signal,cleanup:()=>{n&&clearTimeout(n)}}}async function oe(r,e,t={}){let{timeoutMs:n,signal:i,...s}=t,{signal:a,cleanup:l}=Oe(i,n);try{let o=await r(e,{...s,signal:a}),c=await o.text(),h=null;try{h=c?JSON.parse(c):null}catch{}return{res:o,json:h,text:c}}finally{l()}}var sr=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ye(r,e){return r>>>e|r<<32-e}function Mt(r){let e=new Uint8Array(r),t=e.length*8,n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;let i=new DataView(n.buffer);i.setUint32(n.length-8,t/4294967296>>>0,!1),i.setUint32(n.length-4,t>>>0,!1);let s=1779033703,a=3144134277,l=1013904242,o=2773480762,c=1359893119,h=2600822924,k=528734635,p=1541459225,d=new Uint32Array(64);for(let P=0;P<n.length;P+=64){for(let F=0;F<16;F++)d[F]=i.getUint32(P+F*4,!1);for(let F=16;F<64;F++){let B=ye(d[F-15],7)^ye(d[F-15],18)^d[F-15]>>>3,g=ye(d[F-2],17)^ye(d[F-2],19)^d[F-2]>>>10;d[F]=d[F-16]+B+d[F-7]+g|0}let u=s,E=a,m=l,f=o,C=c,w=h,M=k,z=p;for(let F=0;F<64;F++){let B=ye(C,6)^ye(C,11)^ye(C,25),g=C&w^~C&M,R=z+B+g+sr[F]+d[F]|0,D=ye(u,2)^ye(u,13)^ye(u,22),Z=u&E^u&m^E&m,ie=D+Z|0;z=M,M=w,w=C,C=f+R|0,f=m,m=E,E=u,u=R+ie|0}s=s+u|0,a=a+E|0,l=l+m|0,o=o+f|0,c=c+C|0,h=h+w|0,k=k+M|0,p=p+z|0}let y=new ArrayBuffer(32),v=new DataView(y);return v.setUint32(0,s,!1),v.setUint32(4,a,!1),v.setUint32(8,l,!1),v.setUint32(12,o,!1),v.setUint32(16,c,!1),v.setUint32(20,h,!1),v.setUint32(24,k,!1),v.setUint32(28,p,!1),y}async function Ee(r,e,t){let i=(t||be()).decode(e),s=new Uint8Array(i).buffer;return r.subtle.importKey("raw",s,{name:"AES-GCM"},!0,["decrypt"])}async function xe(r,e,t){let n=e.slice(0,12),i=e.slice(12);return r.subtle.decrypt({name:"AES-GCM",iv:n},t,i)}async function De(r,e,t,n){let s=(n||be()).decode(e),a=await xe(r,s,t);return new TextDecoder().decode(a)}function Bt(r){let e=new Uint8Array(r),t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}async function rt(r,e){if(r?.subtle){let t=await r.subtle.digest("SHA-256",e);return Bt(t)}return Bt(Mt(e))}async function nt(r){return r.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}async function it(r,e){let t=await r.subtle.exportKey("raw",e);return Ue(t)}async function _e(r,e,t){let n=r.getRandomValues(new Uint8Array(12)),i=await r.subtle.encrypt({name:"AES-GCM",iv:n},t,e);return new Blob([n,new Uint8Array(i)])}async function st(r,e,t){let n=new TextEncoder().encode(String(e)),s=await(await _e(r,n.buffer,t)).arrayBuffer();return Ue(s)}var It=er("module"),or=(0,It.createRequire)("/"),ar;try{ar=or("worker_threads").Worker}catch{}var le=Uint8Array,zt=Uint16Array,lr=Int32Array,cr=new le([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fr=new le([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Yr=new le([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Tt=function(r,e){for(var t=new zt(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new lr(t[30]),n=1;n<30;++n)for(var s=t[n];s<t[n+1];++s)i[s]=s-t[n]<<5|n;return{b:t,r:i}},Rt=Tt(cr,2),ur=Rt.b,pr=Rt.r;ur[28]=258,pr[258]=28;var Ut=Tt(fr,0),Xr=Ut.b,Qr=Ut.r,hr=new zt(32768);for(O=0;O<32768;++O)Se=(O&43690)>>1|(O&21845)<<1,Se=(Se&52428)>>2|(Se&13107)<<2,Se=(Se&61680)>>4|(Se&3855)<<4,hr[O]=((Se&65280)>>8|(Se&255)<<8)>>1;var Se,O;var at=new le(288);for(O=0;O<144;++O)at[O]=8;var O;for(O=144;O<256;++O)at[O]=9;var O;for(O=256;O<280;++O)at[O]=7;var O;for(O=280;O<288;++O)at[O]=8;var O,dr=new le(32);for(O=0;O<32;++O)dr[O]=5;var O;var mr=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new le(r.subarray(e,t))};var gr=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Me=function(r,e,t){var n=new Error(e||gr[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,Me),!t)throw n;return n};var vr=new le(0);var yr=(function(){for(var r=new Int32Array(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(t&1&&-306674912)^t>>>1;r[e]=t}return r})(),Pr=function(){var r=-1;return{p:function(e){for(var t=r,n=0;n<e.length;++n)t=yr[t&255^e[n]]^t>>>8;r=t},d:function(){return~r}}};var wr=function(r,e){var t={};for(var n in r)t[n]=r[n];for(var n in e)t[n]=e[n];return t};var J=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8};var kt=typeof TextEncoder<"u"&&new TextEncoder,br=typeof TextDecoder<"u"&&new TextDecoder,xr=0;try{br.decode(vr,{stream:!0}),xr=1}catch{}function Et(r,e){if(e){for(var t=new le(r.length),n=0;n<r.length;++n)t[n]=r.charCodeAt(n);return t}if(kt)return kt.encode(r);for(var i=r.length,s=new le(r.length+(r.length>>1)),a=0,l=function(h){s[a++]=h},n=0;n<i;++n){if(a+5>s.length){var o=new le(a+8+(i-n<<1));o.set(s),s=o}var c=r.charCodeAt(n);c<128||e?l(c):c<2048?(l(192|c>>6),l(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|r.charCodeAt(++n)&1023,l(240|c>>18),l(128|c>>12&63),l(128|c>>6&63),l(128|c&63)):(l(224|c>>12),l(128|c>>6&63),l(128|c&63))}return mr(s,0,a)}var ot=function(r){var e=0;if(r)for(var t in r){var n=r[t].length;n>65535&&Me(9),e+=n+4}return e},Ft=function(r,e,t,n,i,s,a,l){var o=n.length,c=t.extra,h=l&&l.length,k=ot(c);J(r,e,a!=null?33639248:67324752),e+=4,a!=null&&(r[e++]=20,r[e++]=t.os),r[e]=20,e+=2,r[e++]=t.flag<<1|(s<0&&8),r[e++]=i&&8,r[e++]=t.compression&255,r[e++]=t.compression>>8;var p=new Date(t.mtime==null?Date.now():t.mtime),d=p.getFullYear()-1980;if((d<0||d>119)&&Me(10),J(r,e,d<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),e+=4,s!=-1&&(J(r,e,t.crc),J(r,e+4,s<0?-s-2:s),J(r,e+8,t.size)),J(r,e+12,o),J(r,e+14,k),e+=16,a!=null&&(J(r,e,h),J(r,e+6,t.attrs),J(r,e+10,a),e+=14),r.set(n,e),e+=o,k)for(var y in c){var v=c[y],P=v.length;J(r,e,+y),J(r,e+2,P),r.set(v,e+4),e+=4+P}return h&&(r.set(l,e),e+=h),e},Sr=function(r,e,t,n,i){J(r,e,101010256),J(r,e+8,t),J(r,e+10,t),J(r,e+12,n),J(r,e+16,i)},Ot=(function(){function r(e){this.filename=e,this.c=Pr(),this.size=0,this.compression=0}return r.prototype.process=function(e,t){this.ondata(null,e,t)},r.prototype.push=function(e,t){this.ondata||Me(5),this.c.p(e),this.size+=e.length,t&&(this.crc=this.c.d()),this.process(e,t||!1)},r})();var Dt=(function(){function r(e){this.ondata=e,this.u=[],this.d=1}return r.prototype.add=function(e){var t=this;if(this.ondata||Me(5),this.d&2)this.ondata(Me(4+(this.d&1)*8,0,1),null,!1);else{var n=Et(e.filename),i=n.length,s=e.comment,a=s&&Et(s),l=i!=e.filename.length||a&&s.length!=a.length,o=i+ot(e.extra)+30;i>65535&&this.ondata(Me(11,0,1),null,!1);var c=new le(o);Ft(c,0,e,n,l,-1);var h=[c],k=function(){for(var P=0,u=h;P<u.length;P++){var E=u[P];t.ondata(null,E,!1)}h=[]},p=this.d;this.d=0;var d=this.u.length,y=wr(e,{f:n,u:l,o:a,t:function(){e.terminate&&e.terminate()},r:function(){if(k(),p){var P=t.u[d+1];P?P.r():t.d=1}p=1}}),v=0;e.ondata=function(P,u,E){if(P)t.ondata(P,u,E),t.terminate();else if(v+=u.length,h.push(u),E){var m=new le(16);J(m,0,134695760),J(m,4,e.crc),J(m,8,v),J(m,12,e.size),h.push(m),y.c=v,y.b=o+v+16,y.crc=e.crc,y.size=e.size,p&&y.r(),p=1}else p&&k()},this.u.push(y)}},r.prototype.end=function(){var e=this;if(this.d&2){this.ondata(Me(4+(this.d&1)*8,0,1),null,!0);return}this.d?this.e():this.u.push({r:function(){e.d&1&&(e.u.splice(-1,1),e.e())},t:function(){}}),this.d=3},r.prototype.e=function(){for(var e=0,t=0,n=0,i=0,s=this.u;i<s.length;i++){var a=s[i];n+=46+a.f.length+ot(a.extra)+(a.o?a.o.length:0)}for(var l=new le(n+22),o=0,c=this.u;o<c.length;o++){var a=c[o];Ft(l,e,a,a.f,a.u,-a.c-2,t,a.o),e+=46+a.f.length+ot(a.extra)+(a.o?a.o.length:0),t+=a.b}Sr(l,e,this.u.length,n,t),this.ondata(null,l,!0),this.d=2},r.prototype.terminate=function(){for(var e=0,t=this.u;e<t.length;e++){var n=t[e];n.t()}this.d=2},r})();var Ne=class{constructor(e){Q(this,"zip");Q(this,"currentFile",null);Q(this,"onData");Q(this,"finalized",!1);Q(this,"pendingWrites",Promise.resolve());this.onData=e,this.zip=new Dt((t,n,i)=>{if(t)throw t;this.pendingWrites=this.pendingWrites.then(()=>this.onData(n))})}startFile(e){if(this.currentFile)throw new Error("Must call endFile() before starting a new file.");if(this.finalized)throw new Error("ZIP has already been finalized.");let t=new Ot(e);this.zip.add(t),this.currentFile=t}writeChunk(e){if(!this.currentFile)throw new Error("No file started. Call startFile() first.");this.currentFile.push(e,!1)}endFile(){if(!this.currentFile)throw new Error("No file to end.");this.currentFile.push(new Uint8Array(0),!0),this.currentFile=null}async finalize(){if(this.currentFile)throw new Error("Cannot finalize with an open file. Call endFile() first.");this.finalized||(this.finalized=!0,this.zip.end(),await this.pendingWrites)}};function lt(r){let e=String(r||"").toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function vt(r,e){return!!e||lt(r||"")}function He(r){let e=r||Re(),t="ABCDEFGHJKLMNPQRSTUVWXYZ";if(e){let s=new Uint8Array(8);e.getRandomValues(s);let a="";for(let o=0;o<4;o++)a+=t[s[o]%t.length];let l="";for(let o=4;o<8;o++)l+=(s[o]%10).toString();return`${a}-${l}`}let n="";for(let s=0;s<4;s++)n+=t[Math.floor(Math.random()*t.length)];let i="";for(let s=0;s<4;s++)i+=Math.floor(Math.random()*10);return`${n}-${i}`}function Ge(r){return/^[A-Z]{4}-\d{4}$/.test(String(r||"").trim())}function Fe(r,e){return{path:r.peerjsPath??e?.peerjsPath??"/peerjs",iceServers:r.iceServers??e?.iceServers??[]}}function ct(r={}){let{host:e,port:t,peerjsPath:n="/peerjs",secure:i=!1,iceServers:s=[]}=r,a={host:e,path:n,secure:i,config:{iceServers:s},debug:0};return t&&(a.port=t),a}async function _t(r){let{code:e,codeGenerator:t,maxAttempts:n,buildPeer:i,onCode:s}=r,a=e||t(),l=null,o=null;for(let c=0;c<n;c++){s?.(a,c);try{return l=await new Promise((h,k)=>{let p=i(a);p.on("open",()=>h(p)),p.on("error",d=>{try{p.destroy()}catch{}k(d)})}),{peer:l,code:a}}catch(h){o=h,a=t()}}throw o||new N("Could not establish PeerJS connection.")}function ft(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.t=="string"&&["hello","file_list","meta","ready","chunk","chunk_ack","file_end","file_end_ack","end","end_ack","ping","pong","error","cancelled","resume","resume_ack"].includes(e.t)}var Nt=64*1024,jt=32,$t=15e3,Lt=3,Kt=100,Ht=2e3;function Cr(){return crypto.randomUUID()}var Ar={initializing:["listening","closed"],listening:["handshaking","closed","cancelled"],handshaking:["negotiating","closed","cancelled"],negotiating:["transferring","closed","cancelled"],transferring:["finishing","closed","cancelled"],finishing:["awaiting_ack","closed","cancelled"],awaiting_ack:["completed","closed","cancelled"],completed:["closed"],cancelled:["closed"],closed:[]};async function Gt(r){let{file:e,Peer:t,serverInfo:n,host:i,port:s,peerjsPath:a,secure:l=!1,iceServers:o,codeGenerator:c,cryptoObj:h,maxAttempts:k=4,chunkSize:p=Nt,endAckTimeoutMs:d=$t,bufferHighWaterMark:y=8*1024*1024,bufferLowWaterMark:v=2*1024*1024,heartbeatIntervalMs:P=5e3,chunkAcknowledgments:u=!0,maxUnackedChunks:E=jt,onCode:m,onStatus:f,onProgress:C,onComplete:w,onError:M,onDisconnect:z,onCancel:F,onConnectionHealth:B}=r,g=Array.isArray(e)?e:[e],R=g.length>1,D=g.reduce((x,K)=>x+K.size,0);if(!g.length)throw new S("At least one file is required.");if(!t)throw new S("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let Z=n?.capabilities?.p2p;if(n&&!Z?.enabled)throw new S("Direct transfer is disabled on this server.");let{path:ie,iceServers:pe}=Fe({peerjsPath:a,iceServers:o},Z),ge=ct({host:i,port:s,peerjsPath:ie,secure:l,iceServers:pe}),Ce=c||(()=>He(h)),G=x=>new t(x,ge),{peer:V,code:Pe}=await _t({code:null,codeGenerator:Ce,maxAttempts:k,buildPeer:G,onCode:m}),ee=Cr(),I="listening",q=null,ne=0,se=null,ce=null,re=Date.now(),fe=new Map,b=0,Y=[],A=x=>Ar[I].includes(x)?(I=x,!0):(console.warn(`[P2P Send] Invalid state transition: ${I} -> ${x}`),!1),U=x=>{if(j())return;let K=Number.isFinite(x.total)&&x.total>0?x.total:D,ue=Math.min(Number(x.received)||0,K||0),he=K?ue/K*100:0;C?.({processedBytes:ue,totalBytes:K,percent:he})},T=x=>{I==="closed"||I==="completed"||I==="cancelled"||(A("closed"),M?.(x),L())},$=()=>{I!=="awaiting_ack"&&I!=="finishing"||(A("completed"),w?.(),L())},L=()=>{se&&(clearInterval(se),se=null),ce&&(clearInterval(ce),ce=null),Y.forEach(x=>x()),Y=[],fe.clear(),typeof window<"u"&&window.removeEventListener("beforeunload",_);try{q?.close()}catch{}try{V.destroy()}catch{}},_=()=>{try{q?.send({t:"error",message:"Sender closed the connection."})}catch{}ae()};typeof window<"u"&&window.addEventListener("beforeunload",_);let ae=()=>{if(I==="closed"||I==="cancelled")return;if(I==="completed"){L();return}let x=I==="transferring"||I==="finishing"||I==="awaiting_ack";A("cancelled");try{q&&q.open&&q.send({t:"cancelled",message:"Sender cancelled the transfer."})}catch{}x&&F&&F({cancelledBy:"sender"}),L()},j=()=>I==="closed"||I==="cancelled",Ie=x=>{B&&(ce=setInterval(()=>{if(j())return;let K=x._dc;if(!K)return;let ue={iceConnectionState:K.readyState==="open"?"connected":"disconnected",bufferedAmount:K.bufferedAmount,lastActivityMs:Date.now()-re};B(ue)},2e3))},Ae=x=>{re=Date.now(),fe.delete(x.seq),U({received:x.received,total:D});let K=Y.shift();K&&K()},We=()=>new Promise(x=>{Y.push(x)}),Wt=async(x,K,ue,he)=>{if(u){for(;fe.size>=E;)if(await Promise.race([We(),me(1e3)]),j())return}let Be=b++;u&&fe.set(Be,{offset:ue,size:K.byteLength,sentAt:Date.now()}),x.send({t:"chunk",seq:Be,offset:ue,size:K.byteLength,total:he??D}),x.send(K),ne+=K.byteLength;let we=x._dc;if(we&&y>0){for(;we.bufferedAmount>y;)if(await new Promise(Je=>{let ht=setTimeout(Je,60);try{we.addEventListener("bufferedamountlow",()=>{clearTimeout(ht),Je()},{once:!0})}catch{}}),j())return}},Jt=async(x,K)=>{let ue=d;for(let he=0;he<Lt;he++){x.send({t:"end",attempt:he});let Be=ue*Math.pow(1.5,he),we=await Promise.race([K,me(Be).then(()=>null)]);if(we&&we.t==="end_ack")return we;if(j())throw new N("Connection closed during completion.")}throw new N("Receiver did not confirm completion after retries.")};return V.on("connection",x=>{if(j())return;if(q){let W=q.open!==!1;if(W&&I==="transferring"){try{x.send({t:"error",message:"Transfer already in progress."})}catch{}try{x.close()}catch{}return}else if(W){try{x.send({t:"error",message:"Another receiver is already connected."})}catch{}try{x.close()}catch{}return}else{try{q.close()}catch{}q=null,I="listening",ne=0,b=0,fe.clear()}}q=x,A("handshaking"),j()||f?.({phase:"connected",message:"Receiver connected."}),re=Date.now();let K=null,ue=null,he=null,Be=null,we=new Promise(W=>{K=W}),Je=new Promise(W=>{ue=W}),ht=new Promise(W=>{he=W});x.on("data",W=>{if(re=Date.now(),W instanceof ArrayBuffer||ArrayBuffer.isView(W)||!ft(W))return;let ve=W;switch(ve.t){case"hello":K?.(ve.protocolVersion);break;case"ready":j()||f?.({phase:"transferring",message:"Receiver accepted. Starting transfer..."}),ue?.();break;case"chunk_ack":Ae(ve);break;case"file_end_ack":Be?.(ve);break;case"end_ack":he?.(ve);break;case"pong":break;case"error":T(new N(ve.message||"Receiver reported an error."));break;case"cancelled":if(I==="cancelled"||I==="closed"||I==="completed")return;A("cancelled"),F?.({cancelledBy:"receiver",message:ve.reason}),L();break}}),x.on("open",async()=>{try{if(j())return;Ie(x),x.send({t:"hello",protocolVersion:3,sessionId:ee});let W=await Promise.race([we,me(1e4).then(()=>null)]);if(j())return;if(W===null)throw new N("Receiver did not respond to handshake.");if(W!==3)throw new N(`Protocol version mismatch: sender v${3}, receiver v${W}`);A("negotiating"),j()||f?.({phase:"waiting",message:"Connected. Waiting for receiver to accept..."}),R&&x.send({t:"file_list",fileCount:g.length,files:g.map(de=>({name:de.name,size:de.size,mime:de.type||"application/octet-stream"})),totalSize:D}),x.send({t:"meta",sessionId:ee,name:g[0].name,size:g[0].size,mime:g[0].type||"application/octet-stream",...R?{fileIndex:0}:{}});let ve=x._dc;if(ve&&Number.isFinite(v))try{ve.bufferedAmountLowThreshold=v}catch{}if(await Je,j())return;P>0&&(se=setInterval(()=>{if(I==="transferring"||I==="finishing"||I==="awaiting_ack")try{x.send({t:"ping",timestamp:Date.now()})}catch{}},P)),A("transferring");let yt=0;for(let de=0;de<g.length;de++){let ze=g[de];R&&de>0&&x.send({t:"meta",sessionId:ee,name:ze.name,size:ze.size,mime:ze.type||"application/octet-stream",fileIndex:de});for(let ke=0;ke<ze.size;ke+=p){if(j())return;let Ye=await ze.slice(ke,ke+p).arrayBuffer();if(j())return;await Wt(x,Ye,ke,ze.size),yt+=Ye.byteLength,U({received:yt,total:D})}if(j())return;if(R){let ke=new Promise(Ye=>{Be=Ye});x.send({t:"file_end",fileIndex:de});let bt=await Promise.race([ke,me(d).then(()=>null)]);if(j())return;if(!bt)throw new N(`Receiver did not confirm receipt of file ${de+1}/${g.length}.`)}}if(j())return;A("finishing"),A("awaiting_ack");let Pt=await Jt(x,ht);if(j())return;let Ze=Number(Pt.total)||D,wt=Number(Pt.received)||0;if(Ze&&wt<Ze)throw new N("Receiver reported an incomplete transfer.");U({received:wt||Ze,total:Ze}),$()}catch(W){T(W)}}),x.on("error",W=>{T(W)}),x.on("close",()=>{if(I==="closed"||I==="completed"||I==="cancelled"){L();return}if(I==="awaiting_ack"){setTimeout(()=>{I==="awaiting_ack"&&T(new N("Connection closed while awaiting confirmation."))},Ht);return}I==="transferring"||I==="finishing"?(A("cancelled"),F?.({cancelledBy:"receiver"}),L()):(q=null,I="listening",ne=0,b=0,fe.clear(),z?.())})}),{peer:V,code:Pe,sessionId:ee,stop:ae,getStatus:()=>I,getBytesSent:()=>ne,getConnectedPeerId:()=>q&&q.peer||null}}var Mr={initializing:["connecting","closed"],connecting:["handshaking","closed","cancelled"],handshaking:["negotiating","closed","cancelled"],negotiating:["transferring","closed","cancelled"],transferring:["completed","closed","cancelled"],completed:["closed"],cancelled:["closed"],closed:[]};async function Vt(r){let{code:e,Peer:t,serverInfo:n,host:i,port:s,peerjsPath:a,secure:l=!1,iceServers:o,autoReady:c=!0,watchdogTimeoutMs:h=15e3,onStatus:k,onMeta:p,onData:d,onProgress:y,onFileStart:v,onFileEnd:P,onComplete:u,onError:E,onDisconnect:m,onCancel:f}=r;if(!e)throw new S("No sharing code was provided.");if(!t)throw new S("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let C=n?.capabilities?.p2p;if(n&&!C?.enabled)throw new S("Direct transfer is disabled on this server.");let w=String(e).trim().replace(/\s+/g,"").toUpperCase();if(!Ge(w))throw new S("Invalid direct transfer code.");let{path:M,iceServers:z}=Fe({peerjsPath:a,iceServers:o},C),F=ct({host:i,port:s,peerjsPath:M,secure:l,iceServers:z}),B=new t(void 0,F),g="initializing",R=0,D=0,Z=null,ie=Promise.resolve(),pe=null,ge=null,Ce=null,G=null,V=0,Pe=0,ee=A=>Mr[g].includes(A)?(g=A,!0):(console.warn(`[P2P Receive] Invalid state transition: ${g} -> ${A}`),!1),I=()=>g==="closed"||g==="cancelled",q=()=>{h<=0||(pe&&clearTimeout(pe),pe=setTimeout(()=>{g==="transferring"&&se(new N("Connection timed out (no data received)."))},h))},ne=()=>{pe&&(clearTimeout(pe),pe=null)},se=A=>{g==="closed"||g==="completed"||g==="cancelled"||(ee("closed"),E?.(A),re())},ce=A=>{g==="transferring"&&(ee("completed"),u?.(A))},re=()=>{ne(),typeof window<"u"&&window.removeEventListener("beforeunload",fe);try{B.destroy()}catch{}},fe=()=>{try{ge?.send({t:"error",message:"Receiver closed the connection."})}catch{}b()};typeof window<"u"&&window.addEventListener("beforeunload",fe);let b=()=>{if(g==="closed"||g==="cancelled")return;if(g==="completed"){re();return}let A=g==="transferring";ee("cancelled");try{ge&&ge.open&&ge.send({t:"cancelled",reason:"Receiver cancelled the transfer."})}catch{}A&&f&&f({cancelledBy:"receiver"}),re()},Y=(A,U)=>{try{A.send({t:"chunk_ack",seq:U,received:D})}catch{}};return B.on("error",A=>{se(A)}),B.on("open",()=>{ee("connecting");let A=B.connect(w,{reliable:!0});ge=A,A.on("open",()=>{ee("handshaking"),k?.({phase:"connected",message:"Connected."}),A.send({t:"hello",protocolVersion:3,sessionId:""})}),A.on("data",async U=>{try{if(q(),U instanceof ArrayBuffer||ArrayBuffer.isView(U)||typeof Blob<"u"&&U instanceof Blob){let $;if(U instanceof ArrayBuffer)$=Promise.resolve(new Uint8Array(U));else if(ArrayBuffer.isView(U))$=Promise.resolve(new Uint8Array(U.buffer,U.byteOffset,U.byteLength));else if(typeof Blob<"u"&&U instanceof Blob)$=U.arrayBuffer().then(_=>new Uint8Array(_));else return;let L=Ce?.seq??-1;Ce=null,ie=ie.then(async()=>{let _=await $;d&&await d(_),D+=_.byteLength,V+=_.byteLength;let ae=G?Pe+V:D,j=G?G.totalSize:R,Ie=j?Math.min(100,ae/j*100):0;I()||y?.({processedBytes:ae,totalBytes:j,percent:Ie}),L>=0&&Y(A,L)}).catch(_=>{try{A.send({t:"error",message:_?.message||"Receiver write failed."})}catch{}se(_)});return}if(!ft(U))return;let T=U;switch(T.t){case"hello":Z=T.sessionId||null,ee("negotiating"),k?.({phase:"waiting",message:"Waiting for file details..."});break;case"file_list":G=T,R=G.totalSize;break;case"meta":{if(g!=="negotiating"&&!(g==="transferring"&&G))return;if(Z&&T.sessionId&&T.sessionId!==Z){try{A.send({t:"error",message:"Busy with another session."})}catch{}return}T.sessionId&&(Z=T.sessionId);let _=String(T.name||"file"),ae=Number(T.size)||0,j=T.fileIndex;if(G&&typeof j=="number"&&j>0){V=0,v?.({fileIndex:j,name:_,size:ae});break}D=0,V=0,Pe=0,G||(R=ae),ie=Promise.resolve();let Ie=()=>{ee("transferring"),q(),G&&v?.({fileIndex:0,name:_,size:ae});try{A.send({t:"ready"})}catch{}},Ae={name:_,total:R};G&&(Ae.fileCount=G.fileCount,Ae.files=G.files.map(We=>({name:We.name,size:We.size})),Ae.totalSize=G.totalSize),c?(I()||(p?.(Ae),y?.({processedBytes:D,totalBytes:R,percent:0})),Ie()):(Ae.sendReady=Ie,I()||(p?.(Ae),y?.({processedBytes:D,totalBytes:R,percent:0})));break}case"chunk":Ce=T;break;case"ping":try{A.send({t:"pong",timestamp:Date.now()})}catch{}break;case"file_end":{ne(),await ie;let _=T.fileIndex;P?.({fileIndex:_,receivedBytes:V});try{A.send({t:"file_end_ack",fileIndex:_,received:V,size:V})}catch{}Pe+=V,V=0,q();break}case"end":ne(),await ie;let $=G?Pe+V:D,L=G?G.totalSize:R;if(L&&$<L){let _=new N("Transfer ended before all data was received.");try{A.send({t:"error",message:_.message})}catch{}throw _}try{A.send({t:"end_ack",received:$,total:L})}catch{}ce({received:$,total:L}),(async()=>{for(let _=0;_<2;_++){await me(Kt);try{A.send({t:"end_ack",received:$,total:L})}catch{break}}})().catch(()=>{});break;case"error":throw new N(T.message||"Sender reported an error.");case"cancelled":if(g==="cancelled"||g==="closed"||g==="completed")return;ee("cancelled"),f?.({cancelledBy:"sender",message:T.reason}),re();break}}catch(T){se(T)}}),A.on("close",()=>{if(g==="closed"||g==="completed"||g==="cancelled"){re();return}g==="transferring"?(ee("cancelled"),f?.({cancelledBy:"sender"}),re()):g==="negotiating"?(ee("closed"),re(),m?.()):se(new N("Sender disconnected before file details were received."))})}),{peer:B,stop:b,getStatus:()=>g,getBytesReceived:()=>D,getTotalBytes:()=>R,getSessionId:()=>Z}}function qt(r){return typeof r=="string"?Ke(tt(r)):Ke(r)}function qe(r,e,t){let n=Number(r)||0;return t?n+(Number(e)||0)*28:n}async function ut(r){let{server:e,timeoutMs:t=5e3,signal:n,fetchFn:i}=r,s=i||$e();if(!s)throw new S("No fetch() implementation found.");let a=qt(e);try{let{res:l,json:o}=await oe(s,`${a}/api/info`,{method:"GET",timeoutMs:t,signal:n,headers:{Accept:"application/json"}});if(l.ok&&o&&typeof o=="object"&&"version"in o)return{baseUrl:a,serverInfo:o};throw new H(`Server info request failed (status ${l.status}).`)}catch(l){throw l instanceof X?l:new N("Could not reach server /api/info.",{cause:l})}}var pt=class{constructor(e){Q(this,"clientVersion");Q(this,"chunkSize");Q(this,"fetchFn");Q(this,"cryptoObj");Q(this,"base64");Q(this,"baseUrl");Q(this,"_fallbackToHttp");Q(this,"_compat",null);Q(this,"_connectPromise",null);if(!e||typeof e.clientVersion!="string")throw new S("DropgateClient requires clientVersion (string).");if(!e.server)throw new S("DropgateClient requires server (URL string or ServerTarget object).");this.clientVersion=e.clientVersion,this.chunkSize=Number.isFinite(e.chunkSize)?e.chunkSize:5242880;let t=e.fetchFn||$e();if(!t)throw new S("No fetch() implementation found.");this.fetchFn=t;let n=e.cryptoObj||Re();if(!n)throw new S("No crypto implementation found.");this.cryptoObj=n,this.base64=e.base64||be(),this._fallbackToHttp=!!e.fallbackToHttp,this.baseUrl=qt(e.server)}get serverTarget(){let e=new URL(this.baseUrl);return{host:e.hostname,port:e.port?Number(e.port):void 0,secure:e.protocol==="https:"}}async connect(e){return this._compat?this._compat:(this._connectPromise||(this._connectPromise=this._fetchAndCheckCompat(e).finally(()=>{this._connectPromise=null})),this._connectPromise)}async _fetchAndCheckCompat(e){let{timeoutMs:t=5e3,signal:n}=e??{},i=this.baseUrl,s;try{let l=await ut({server:i,timeoutMs:t,signal:n,fetchFn:this.fetchFn});i=l.baseUrl,s=l.serverInfo}catch(l){if(this._fallbackToHttp&&this.baseUrl.startsWith("https://")){let o=this.baseUrl.replace("https://","http://");try{let c=await ut({server:o,timeoutMs:t,signal:n,fetchFn:this.fetchFn});this.baseUrl=o,i=c.baseUrl,s=c.serverInfo}catch{throw l instanceof X?l:new N("Could not connect to the server.",{cause:l})}}else throw l instanceof X?l:new N("Could not connect to the server.",{cause:l})}let a=this._checkVersionCompat(s);return this._compat={...a,serverInfo:s,baseUrl:i},this._compat}_checkVersionCompat(e){let t=String(e?.version||"0.0.0"),n=String(this.clientVersion||"0.0.0"),i=Le(n),s=Le(t);return i.major!==s.major?{compatible:!1,clientVersion:n,serverVersion:t,message:`Incompatible versions. Client v${n}, Server v${t}${e?.name?` (${e.name})`:""}.`}:i.minor>s.minor?{compatible:!0,clientVersion:n,serverVersion:t,message:`Client (v${n}) is newer than Server (v${t})${e?.name?` (${e.name})`:""}. Some features may not work.`}:{compatible:!0,clientVersion:n,serverVersion:t,message:`Server: v${t}, Client: v${n}${e?.name?` (${e.name})`:""}.`}}async resolveShareTarget(e,t){let{timeoutMs:n=5e3,signal:i}=t??{},s=await this.connect(t);if(!s.compatible)throw new S(s.message);let{baseUrl:a}=s,{res:l,json:o}=await oe(this.fetchFn,`${a}/api/resolve`,{method:"POST",timeoutMs:n,signal:i,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({value:e})});if(!l.ok){let c=(o&&typeof o=="object"&&"error"in o?o.error:null)||`Share lookup failed (status ${l.status}).`;throw new H(c,{details:o})}return o||{valid:!1,reason:"Unknown response."}}async getFileMetadata(e,t){if(!e||typeof e!="string")throw new S("File ID is required.");let{timeoutMs:n=5e3,signal:i}=t??{},s=`${this.baseUrl}/api/file/${encodeURIComponent(e)}/meta`,{res:a,json:l}=await oe(this.fetchFn,s,{method:"GET",timeoutMs:n,signal:i});if(!a.ok){let o=(l&&typeof l=="object"&&"error"in l?l.error:null)||`Failed to fetch file metadata (status ${a.status}).`;throw new H(o,{details:l})}return l}async getBundleMetadata(e,t,n){if(!e||typeof e!="string")throw new S("Bundle ID is required.");let{timeoutMs:i=5e3,signal:s}=n??{},a=`${this.baseUrl}/api/bundle/${encodeURIComponent(e)}/meta`,{res:l,json:o}=await oe(this.fetchFn,a,{method:"GET",timeoutMs:i,signal:s});if(!l.ok){let d=(o&&typeof o=="object"&&"error"in o?o.error:null)||`Failed to fetch bundle metadata (status ${l.status}).`;throw new H(d,{details:o})}let c=o,h=[];if(c.sealed&&c.encryptedManifest){if(!t)throw new S("Decryption key (keyB64) is required for encrypted sealed bundles.");let d=await Ee(this.cryptoObj,t),y=this.base64.decode(c.encryptedManifest),v=await xe(this.cryptoObj,y,d),P=new TextDecoder().decode(v);h=JSON.parse(P).files.map(E=>({fileId:E.fileId,sizeBytes:E.sizeBytes,filename:E.name}))}else if(c.files)h=c.files;else throw new H("Invalid bundle metadata: missing files or manifest.");let k=h.reduce((d,y)=>d+(y.sizeBytes||0),0),p=h.length;return{isEncrypted:c.isEncrypted,sealed:c.sealed,encryptedManifest:c.encryptedManifest,files:h,totalSizeBytes:k,fileCount:p}}validateUploadInputs(e){let{files:t,lifetimeMs:n,encrypt:i,serverInfo:s}=e,a=s?.capabilities?.upload;if(!a||!a.enabled)throw new S("Server does not support file uploads.");let l=Array.isArray(t)?t:[t];if(l.length===0)throw new S("At least one file is required.");for(let h=0;h<l.length;h++){let k=l[h],p=Number(k?.size||0);if(!k||!Number.isFinite(p)||p<=0)throw new S(`File at index ${h} is missing or invalid.`);let d=Number(a.maxSizeMB);if(Number.isFinite(d)&&d>0){let y=d*1e3*1e3,v=Number.isFinite(a.chunkSize)&&a.chunkSize>0?a.chunkSize:this.chunkSize,P=Math.ceil(p/v);if(qe(p,P,!!i)>y){let E=i?`File at index ${h} too large once encryption overhead is included. Server limit: ${d} MB.`:`File at index ${h} too large. Server limit: ${d} MB.`;throw new S(E)}}}let o=Number(a.maxLifetimeHours),c=Number(n);if(!Number.isFinite(c)||c<0||!Number.isInteger(c))throw new S("Invalid lifetime. Must be a non-negative integer (milliseconds).");if(Number.isFinite(o)&&o>0){let h=Math.round(o*60*60*1e3);if(c===0)throw new S(`Server does not allow unlimited file lifetime. Max: ${o} hours.`);if(c>h)throw new S(`File lifetime too long. Server limit: ${o} hours.`)}if(i&&!a.e2ee)throw new S("End-to-end encryption is not supported on this server.");return!0}async uploadFiles(e){let{files:t,lifetimeMs:n,encrypt:i,maxDownloads:s,filenameOverrides:a,onProgress:l,onCancel:o,signal:c,timeouts:h={},retry:k={}}=e,p=Array.isArray(t)?t:[t];if(p.length===0)throw new S("At least one file is required.");let d=c?null:new AbortController,y=c||d?.signal,v="initializing",P=[],u=p.reduce((f,C)=>f+C.size,0),E=(async()=>{try{let f=b=>{try{l&&l(b)}catch{}};f({phase:"server-info",text:"Checking server...",percent:0,processedBytes:0,totalBytes:u});let C=await this.connect({timeoutMs:h.serverInfoMs??5e3,signal:y}),{baseUrl:w,serverInfo:M}=C;if(f({phase:"server-compat",text:C.message,percent:0,processedBytes:0,totalBytes:u}),!C.compatible)throw new S(C.message);let z=p.map((b,Y)=>a?.[Y]??b.name??"file"),F=!!M?.capabilities?.upload?.e2ee,B=i??F;if(!B)for(let b of z)et(b);this.validateUploadInputs({files:p,lifetimeMs:n,encrypt:B,serverInfo:M});let g=null,R=null,D=[];if(B){if(!this.cryptoObj?.subtle)throw new S("Web Crypto API not available (crypto.subtle). Encryption requires a secure context (HTTPS or localhost).");f({phase:"crypto",text:"Generating encryption key...",percent:0,processedBytes:0,totalBytes:u});try{g=await nt(this.cryptoObj),R=await it(this.cryptoObj,g);for(let b of z)D.push(await st(this.cryptoObj,b,g))}catch(b){throw new X("Failed to prepare encryption.",{code:"CRYPTO_PREP_FAILED",cause:b})}}else D.push(...z);let Z=M?.capabilities?.upload?.chunkSize,ie=Number.isFinite(Z)&&Z>0?Z:this.chunkSize,pe=Number.isFinite(k.retries)?k.retries:5,ge=Number.isFinite(k.backoffMs)?k.backoffMs:1e3,Ce=Number.isFinite(k.maxBackoffMs)?k.maxBackoffMs:3e4;if(p.length===1){let b=p[0],Y=Math.ceil(b.size/ie),A=qe(b.size,Y,B);f({phase:"init",text:"Reserving server storage...",percent:0,processedBytes:0,totalBytes:b.size});let U=await oe(this.fetchFn,`${w}/upload/init`,{method:"POST",timeoutMs:h.initMs??15e3,signal:y,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({filename:D[0],lifetime:n,isEncrypted:B,totalSize:A,totalChunks:Y,...s!==void 0?{maxDownloads:s}:{}})});if(!U.res.ok){let ae=U.json;throw new H(ae?.error||`Server initialisation failed: ${U.res.status}`,{details:U.json||U.text})}let T=U.json?.uploadId;if(!T)throw new H("Server did not return a valid uploadId.");P.push(T),v="uploading",await this._uploadFileChunks({file:b,uploadId:T,cryptoKey:g,effectiveChunkSize:ie,totalChunks:Y,totalUploadSize:A,baseOffset:0,totalBytesAllFiles:b.size,progress:f,signal:y,baseUrl:w,retries:pe,backoffMs:ge,maxBackoffMs:Ce,chunkTimeoutMs:h.chunkMs??6e4}),f({phase:"complete",text:"Finalising upload...",percent:100,processedBytes:b.size,totalBytes:b.size}),v="completing";let $=await oe(this.fetchFn,`${w}/upload/complete`,{method:"POST",timeoutMs:h.completeMs??3e4,signal:y,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:T})});if(!$.res.ok){let ae=$.json;throw new H(ae?.error||"Finalisation failed.",{details:$.json||$.text})}let L=$.json?.id;if(!L)throw new H("Server did not return a valid file id.");let _=`${w}/${L}`;return B&&R&&(_+=`#${R}`),f({phase:"done",text:"Upload successful!",percent:100,processedBytes:b.size,totalBytes:b.size}),v="completed",{downloadUrl:_,fileId:L,uploadId:T,baseUrl:w,...B&&R?{keyB64:R}:{}}}let G=p.map((b,Y)=>{let A=Math.ceil(b.size/ie),U=qe(b.size,A,B);return{filename:D[Y],totalSize:U,totalChunks:A}});f({phase:"init",text:`Reserving server storage for ${p.length} files...`,percent:0,processedBytes:0,totalBytes:u,totalFiles:p.length});let V=await oe(this.fetchFn,`${w}/upload/init-bundle`,{method:"POST",timeoutMs:h.initMs??15e3,signal:y,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fileCount:p.length,files:G,lifetime:n,isEncrypted:B,...s!==void 0?{maxDownloads:s}:{}})});if(!V.res.ok){let b=V.json;throw new H(b?.error||`Bundle initialisation failed: ${V.res.status}`,{details:V.json||V.text})}let Pe=V.json,ee=Pe?.bundleUploadId,I=Pe?.fileUploadIds;if(!ee||!I||I.length!==p.length)throw new H("Server did not return valid bundle upload IDs.");P.push(...I),v="uploading";let q=[],ne=0;for(let b=0;b<p.length;b++){let Y=p[b],A=I[b],U=G[b].totalChunks,T=G[b].totalSize;f({phase:"file-start",text:`Uploading file ${b+1} of ${p.length}: ${z[b]}`,percent:u>0?ne/u*100:0,processedBytes:ne,totalBytes:u,fileIndex:b,totalFiles:p.length,currentFileName:z[b]}),await this._uploadFileChunks({file:Y,uploadId:A,cryptoKey:g,effectiveChunkSize:ie,totalChunks:U,totalUploadSize:T,baseOffset:ne,totalBytesAllFiles:u,progress:f,signal:y,baseUrl:w,retries:pe,backoffMs:ge,maxBackoffMs:Ce,chunkTimeoutMs:h.chunkMs??6e4,fileIndex:b,totalFiles:p.length,currentFileName:z[b]});let $=await oe(this.fetchFn,`${w}/upload/complete`,{method:"POST",timeoutMs:h.completeMs??3e4,signal:y,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:A})});if(!$.res.ok){let _=$.json;throw new H(_?.error||`File ${b+1} finalisation failed.`,{details:$.json||$.text})}let L=$.json?.id;if(!L)throw new H(`Server did not return a valid file id for file ${b+1}.`);q.push({fileId:L,name:z[b],size:Y.size}),ne+=Y.size,f({phase:"file-complete",text:`File ${b+1} of ${p.length} uploaded.`,percent:u>0?ne/u*100:0,processedBytes:ne,totalBytes:u,fileIndex:b,totalFiles:p.length,currentFileName:z[b]})}f({phase:"complete",text:"Finalising bundle...",percent:100,processedBytes:u,totalBytes:u}),v="completing";let se;if(B&&g){let b=JSON.stringify({files:q.map(T=>({fileId:T.fileId,name:T.name,sizeBytes:T.size}))}),Y=new TextEncoder().encode(b),A=await _e(this.cryptoObj,Y.buffer,g),U=new Uint8Array(await A.arrayBuffer());se=this.base64.encode(U)}let ce=await oe(this.fetchFn,`${w}/upload/complete-bundle`,{method:"POST",timeoutMs:h.completeMs??3e4,signal:y,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({bundleUploadId:ee,...se?{encryptedManifest:se}:{}})});if(!ce.res.ok){let b=ce.json;throw new H(b?.error||"Bundle finalisation failed.",{details:ce.json||ce.text})}let re=ce.json?.bundleId;if(!re)throw new H("Server did not return a valid bundle id.");let fe=`${w}/b/${re}`;return B&&R&&(fe+=`#${R}`),f({phase:"done",text:"Upload successful!",percent:100,processedBytes:u,totalBytes:u}),v="completed",{downloadUrl:fe,bundleId:re,baseUrl:w,files:q,...B&&R?{keyB64:R}:{}}}catch(f){throw f instanceof Error&&(f.name==="AbortError"||f.message?.includes("abort"))?(v="cancelled",o?.()):v="error",f}})(),m=async f=>{try{await oe(this.fetchFn,`${this.baseUrl}/upload/cancel`,{method:"POST",timeoutMs:5e3,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:f})})}catch{}};return{result:E,cancel:f=>{if(!(v==="completed"||v==="cancelled")){v="cancelled";for(let C of P)m(C).catch(()=>{});d?.abort(new te(f||"Upload cancelled by user."))}},getStatus:()=>v}}async _uploadFileChunks(e){let{file:t,uploadId:n,cryptoKey:i,effectiveChunkSize:s,totalChunks:a,baseOffset:l,totalBytesAllFiles:o,progress:c,signal:h,baseUrl:k,retries:p,backoffMs:d,maxBackoffMs:y,chunkTimeoutMs:v,fileIndex:P,totalFiles:u,currentFileName:E}=e;for(let m=0;m<a;m++){if(h?.aborted)throw h.reason||new te;let f=m*s,C=Math.min(f+s,t.size),w=t.slice(f,C),M=l+f,z=o>0?M/o*100:0;c({phase:"chunk",text:`Uploading chunk ${m+1} of ${a}...`,percent:z,processedBytes:M,totalBytes:o,chunkIndex:m,totalChunks:a,...P!==void 0?{fileIndex:P,totalFiles:u,currentFileName:E}:{}});let F=await w.arrayBuffer(),B;if(i?B=await _e(this.cryptoObj,F,i):B=new Blob([F]),B.size>s+1024)throw new S("Chunk too large (client-side). Check chunk size settings.");let g=await B.arrayBuffer(),R=await rt(this.cryptoObj,g);await this._attemptChunkUpload(`${k}/upload/chunk`,{method:"POST",headers:{"Content-Type":"application/octet-stream","X-Upload-ID":n,"X-Chunk-Index":String(m),"X-Chunk-Hash":R},body:B},{retries:p,backoffMs:d,maxBackoffMs:y,timeoutMs:v,signal:h,progress:c,chunkIndex:m,totalChunks:a,chunkSize:s,fileSizeBytes:o})}}async downloadFiles(e){let{fileId:t,bundleId:n,keyB64:i,asZip:s,zipFilename:a,onProgress:l,onData:o,onFileStart:c,onFileData:h,onFileEnd:k,signal:p,timeoutMs:d=6e4}=e,y=M=>{try{l&&l(M)}catch{}};if(!t&&!n)throw new S("Either fileId or bundleId is required.");y({phase:"server-info",text:"Checking server...",processedBytes:0,totalBytes:0,percent:0});let v=await this.connect({timeoutMs:d,signal:p}),{baseUrl:P}=v;if(y({phase:"server-compat",text:v.message,processedBytes:0,totalBytes:0,percent:0}),!v.compatible)throw new S(v.message);if(t)return this._downloadSingleFile({fileId:t,keyB64:i,onProgress:l,onData:o,signal:p,timeoutMs:d,baseUrl:P,compat:v});y({phase:"metadata",text:"Fetching bundle info...",processedBytes:0,totalBytes:0,percent:0});let u;try{u=await this.getBundleMetadata(n,i,{timeoutMs:d,signal:p})}catch(M){throw M instanceof X?M:M instanceof Error&&M.name==="AbortError"?new te("Download cancelled."):new N("Could not fetch bundle metadata.",{cause:M})}let E=!!u.isEncrypted,m=u.totalSizeBytes||0,f,C=[];if(E){if(!i)throw new S("Decryption key is required for encrypted bundles.");if(!this.cryptoObj?.subtle)throw new S("Web Crypto API not available for decryption.");try{if(f=await Ee(this.cryptoObj,i,this.base64),u.sealed&&u.encryptedManifest){let M=this.base64.decode(u.encryptedManifest),z=await xe(this.cryptoObj,M,f),F=new TextDecoder().decode(z),B=JSON.parse(F);u.files=B.files.map(g=>({fileId:g.fileId,sizeBytes:g.sizeBytes,filename:g.name})),u.fileCount=u.files.length;for(let g of u.files)C.push(g.filename||"file")}else for(let M of u.files)C.push(await De(this.cryptoObj,M.encryptedFilename,f,this.base64))}catch(M){throw new X("Failed to decrypt bundle manifest.",{code:"DECRYPT_MANIFEST_FAILED",cause:M})}}else for(let M of u.files)C.push(M.filename||"file");let w=0;if(s&&o){let M=new Ne(o);for(let z=0;z<u.files.length;z++){let F=u.files[z],B=C[z];y({phase:"zipping",text:`Downloading ${B}...`,percent:m>0?w/m*100:0,processedBytes:w,totalBytes:m,fileIndex:z,totalFiles:u.files.length,currentFileName:B}),M.startFile(B);let g=w,R=await this._streamFileIntoCallback(P,F.fileId,E,f,v,p,d,D=>{M.writeChunk(D)},D=>{let Z=g+D;y({phase:"zipping",text:`Downloading ${B}...`,percent:m>0?Z/m*100:0,processedBytes:Z,totalBytes:m,fileIndex:z,totalFiles:u.files.length,currentFileName:B})});M.endFile(),w+=R}await M.finalize();try{await oe(this.fetchFn,`${P}/api/bundle/${n}/downloaded`,{method:"POST",timeoutMs:5e3,headers:{"Content-Type":"application/json",Accept:"application/json"},body:"{}"})}catch{}return y({phase:"complete",text:"Download complete!",percent:100,processedBytes:w,totalBytes:m}),{filenames:C,receivedBytes:w,wasEncrypted:E}}else{let M=h||o;for(let z=0;z<u.files.length;z++){let F=u.files[z],B=C[z];y({phase:"downloading",text:`Downloading ${B}...`,percent:m>0?w/m*100:0,processedBytes:w,totalBytes:m,fileIndex:z,totalFiles:u.files.length,currentFileName:B}),c?.({name:B,size:F.sizeBytes,index:z});let g=w,R=await this._streamFileIntoCallback(P,F.fileId,E,f,v,p,d,M?D=>M(D):void 0,D=>{let Z=g+D;y({phase:"downloading",text:`Downloading ${B}...`,percent:m>0?Z/m*100:0,processedBytes:Z,totalBytes:m,fileIndex:z,totalFiles:u.files.length,currentFileName:B})});k?.({name:B,index:z}),w+=R}return y({phase:"complete",text:"Download complete!",percent:100,processedBytes:w,totalBytes:m}),{filenames:C,receivedBytes:w,wasEncrypted:E}}}async _downloadSingleFile(e){let{fileId:t,keyB64:n,onProgress:i,onData:s,signal:a,timeoutMs:l,baseUrl:o,compat:c}=e,h=f=>{try{i&&i(f)}catch{}};h({phase:"metadata",text:"Fetching file info...",processedBytes:0,totalBytes:0,percent:0});let k;try{k=await this.getFileMetadata(t,{timeoutMs:l,signal:a})}catch(f){throw f instanceof X?f:f instanceof Error&&f.name==="AbortError"?new te("Download cancelled."):new N("Could not fetch file metadata.",{cause:f})}let p=!!k.isEncrypted,d=k.sizeBytes||0;if(!s&&d>104857600){let f=Math.round(d/1048576),C=Math.round(104857600/(1024*1024));throw new S(`File is too large (${f}MB) to download without streaming. Provide an onData callback to stream files larger than ${C}MB.`)}let y,v;if(p){if(!n)throw new S("Decryption key is required for encrypted files.");if(!this.cryptoObj?.subtle)throw new S("Web Crypto API not available for decryption.");h({phase:"decrypting",text:"Preparing decryption...",processedBytes:0,totalBytes:0,percent:0});try{v=await Ee(this.cryptoObj,n,this.base64),y=await De(this.cryptoObj,k.encryptedFilename,v,this.base64)}catch(f){throw new X("Failed to decrypt filename.",{code:"DECRYPT_FILENAME_FAILED",cause:f})}}else y=k.filename||"file";h({phase:"downloading",text:"Starting download...",percent:0,processedBytes:0,totalBytes:d});let P=[],u=!s,E=await this._streamFileIntoCallback(o,t,p,v,c,a,l,async f=>{u?P.push(f):await s(f)},f=>{h({phase:"downloading",text:"Downloading...",percent:d>0?f/d*100:0,processedBytes:f,totalBytes:d})});h({phase:"complete",text:"Download complete!",percent:100,processedBytes:E,totalBytes:d});let m;if(u&&P.length>0){let f=P.reduce((w,M)=>w+M.length,0);m=new Uint8Array(f);let C=0;for(let w of P)m.set(w,C),C+=w.length}return{filename:y,receivedBytes:E,wasEncrypted:p,...m?{data:m}:{}}}async _streamFileIntoCallback(e,t,n,i,s,a,l,o,c){let{signal:h,cleanup:k}=Oe(a,l),p=0;try{let d=await this.fetchFn(`${e}/api/file/${t}`,{method:"GET",signal:h});if(!d.ok)throw new H(`Download failed (status ${d.status}).`);if(!d.body)throw new H("Streaming response not available.");let y=d.body.getReader();if(n&&i){let P=(Number.isFinite(s.serverInfo?.capabilities?.upload?.chunkSize)&&s.serverInfo.capabilities.upload.chunkSize>0?s.serverInfo.capabilities.upload.chunkSize:this.chunkSize)+28,u=[],E=0,m=()=>{if(u.length===0)return new Uint8Array(0);if(u.length===1){let w=u[0];return u.length=0,E=0,w}let f=new Uint8Array(E),C=0;for(let w of u)f.set(w,C),C+=w.length;return u.length=0,E=0,f};for(;;){if(a?.aborted)throw new te("Download cancelled.");let{done:f,value:C}=await y.read();if(f)break;for(u.push(C),E+=C.length,p+=C.length,c&&c(p);E>=P;){let w=m(),M=w.subarray(0,P);w.length>P&&(u.push(w.subarray(P)),E=w.length-P);let z=await xe(this.cryptoObj,M,i);o&&await o(new Uint8Array(z))}}if(E>0){let f=m(),C=await xe(this.cryptoObj,f,i);o&&await o(new Uint8Array(C))}}else for(;;){if(a?.aborted)throw new te("Download cancelled.");let{done:v,value:P}=await y.read();if(v)break;p+=P.length,c&&c(p),o&&await o(P)}}catch(d){throw d instanceof X?d:d instanceof Error&&d.name==="AbortError"?new te("Download cancelled."):new N("Download failed.",{cause:d})}finally{k()}return p}async p2pSend(e){let t=await this.connect();if(!t.compatible)throw new S(t.message);let{serverInfo:n}=t,i=n?.capabilities?.p2p;if(!i?.enabled)throw new S("Direct transfer is disabled on this server.");let{host:s,port:a,secure:l}=this.serverTarget,{path:o,iceServers:c}=Fe({},i);return Gt({...e,host:s,port:a,secure:l,peerjsPath:o,iceServers:c,serverInfo:n,cryptoObj:this.cryptoObj})}async p2pReceive(e){let t=await this.connect();if(!t.compatible)throw new S(t.message);let{serverInfo:n}=t,i=n?.capabilities?.p2p;if(!i?.enabled)throw new S("Direct transfer is disabled on this server.");let{host:s,port:a,secure:l}=this.serverTarget,{path:o,iceServers:c}=Fe({},i);return Vt({...e,host:s,port:a,secure:l,peerjsPath:o,iceServers:c,serverInfo:n})}async _attemptChunkUpload(e,t,n){let{retries:i,backoffMs:s,maxBackoffMs:a,timeoutMs:l,signal:o,progress:c,chunkIndex:h,totalChunks:k,chunkSize:p,fileSizeBytes:d}=n,y=i,v=s,P=i;for(;;){if(o?.aborted)throw o.reason||new te;let{signal:u,cleanup:E}=Oe(o,l);try{let m=await this.fetchFn(e,{...t,signal:u});if(m.ok)return;let f=await m.text().catch(()=>"");throw new H(`Chunk ${h+1} failed (HTTP ${m.status}).`,{details:{status:m.status,bodySnippet:f.slice(0,120)}})}catch(m){if(E(),m instanceof Error&&(m.name==="AbortError"||m.code==="ABORT_ERR"))throw m;if(o?.aborted)throw o.reason||new te;if(y<=0)throw m instanceof X?m:new N("Chunk upload failed.",{cause:m});let f=P-y+1,C=h*p,w=h/k*100,M=v,z=100;for(;M>0;){let F=(M/1e3).toFixed(1);c({phase:"retry-wait",text:`Chunk upload failed. Retrying in ${F}s... (${f}/${P})`,percent:w,processedBytes:C,totalBytes:d,chunkIndex:h,totalChunks:k}),await me(Math.min(z,M),o),M-=z}c({phase:"retry",text:`Chunk upload failed. Retrying now... (${f}/${P})`,percent:w,processedBytes:C,totalBytes:d,chunkIndex:h,totalChunks:k}),y-=1,v=Math.min(v*2,a);continue}finally{E()}}}};return nr(kr);})();
|
|
2
2
|
if(typeof window!=="undefined"){window.DropgateCore=DropgateCore;}
|
|
3
3
|
//# sourceMappingURL=index.browser.js.map
|