@dropgate/core 2.2.0-beta.1 → 2.2.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 CHANGED
@@ -60,6 +60,7 @@ const result = await client.uploadFile({
60
60
  secure: true,
61
61
  file: myFile, // File or Blob
62
62
  lifetimeMs: 3600000, // 1 hour
63
+ maxDownloads: 5, // Optional: Limit number of downloads
63
64
  encrypt: true,
64
65
  onProgress: ({ phase, text, percent }) => {
65
66
  console.log(`${phase}: ${text} (${percent ? percent : 0}%)`);
@@ -1,3 +1,3 @@
1
- "use strict";var DropgateCore=(()=>{var je=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var rt=(r,e)=>{for(var t in e)je(r,t,{get:e[t],enumerable:!0})},nt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of et(e))!tt.call(r,o)&&o!==t&&je(r,o,{get:()=>e[o],enumerable:!(n=Qe(e,o))||n.enumerable});return r};var ot=r=>nt(je({},"__esModule",{value:!0}),r);var ct={};rt(ct,{AES_GCM_IV_BYTES:()=>ue,AES_GCM_TAG_BYTES:()=>He,DEFAULT_CHUNK_SIZE:()=>Ce,DropgateAbortError:()=>J,DropgateClient:()=>Ie,DropgateError:()=>L,DropgateNetworkError:()=>M,DropgateProtocolError:()=>V,DropgateTimeoutError:()=>ae,DropgateValidationError:()=>f,ENCRYPTION_OVERHEAD_PER_CHUNK:()=>Ae,arrayBufferToBase64:()=>le,base64ToBytes:()=>Ye,buildBaseUrl:()=>xe,buildPeerOptions:()=>se,bytesToBase64:()=>_e,createPeerWithRetries:()=>ve,decryptChunk:()=>ne,decryptFilenameFromBase64:()=>ge,encryptFilenameToBase64:()=>Oe,encryptToBlob:()=>we,estimateTotalUploadSizeBytes:()=>Te,exportKeyBase64:()=>Fe,fetchJson:()=>te,generateAesGcmKey:()=>Re,generateP2PCode:()=>be,getDefaultBase64:()=>Q,getDefaultCrypto:()=>ce,getDefaultFetch:()=>me,getServerInfo:()=>$e,importKeyFromBase64:()=>ye,isLocalhostHostname:()=>Me,isP2PCodeLike:()=>Pe,isSecureContextForP2P:()=>ze,lifetimeToMs:()=>qe,makeAbortSignal:()=>re,parseSemverMajorMinor:()=>he,parseServerUrl:()=>Xe,resolvePeerConfig:()=>oe,sha256Hex:()=>ke,sleep:()=>pe,startP2PReceive:()=>Ge,startP2PSend:()=>Le,validatePlainFilename:()=>Ee});var Ce=5242880,ue=12,He=16,Ae=28;var L=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 L{constructor(e,t={}){super(e,{...t,code:t.code||"VALIDATION_ERROR"})}},M=class extends L{constructor(e,t={}){super(e,{...t,code:t.code||"NETWORK_ERROR"})}},V=class extends L{constructor(e,t={}){super(e,{...t,code:t.code||"PROTOCOL_ERROR"})}},J=class extends L{constructor(e="Operation aborted"){super(e,{code:"ABORT_ERROR"}),this.name="AbortError"}},ae=class extends L{constructor(e="Request timed out"){super(e,{code:"TIMEOUT_ERROR"}),this.name="TimeoutError"}};function Q(){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 ce(){return globalThis.crypto}function me(){return globalThis.fetch?.bind(globalThis)}var Ne=null;function We(r){return r||(Ne||(Ne=Q()),Ne)}function _e(r,e){return We(e).encode(r)}function le(r,e){return _e(new Uint8Array(r),e)}function Ye(r,e){return We(e).decode(r)}var st={minutes:6e4,hours:36e5,days:864e5};function qe(r,e){let t=String(e||"").toLowerCase(),n=Number(r);if(t==="unlimited"||!Number.isFinite(n)||n<=0)return 0;let o=st[t];return o?Math.round(n*o):0}function he(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 Ee(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 Xe(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 xe(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 pe(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 re(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 ae)},e)),{signal:t.signal,cleanup:()=>{n&&clearTimeout(n)}}}async function te(r,e,t={}){let{timeoutMs:n,signal:o,...s}=t,{signal:p,cleanup:d}=re(o,n);try{let i=await r(e,{...s,signal:p}),u=await i.text(),h=null;try{h=u?JSON.parse(u):null}catch{}return{res:i,json:h,text:u}}finally{d()}}async function ye(r,e,t){let o=(t||Q()).decode(e),s=new Uint8Array(o).buffer;return r.subtle.importKey("raw",s,{name:"AES-GCM"},!0,["decrypt"])}async function ne(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 ge(r,e,t,n){let s=(n||Q()).decode(e),p=await ne(r,s,t);return new TextDecoder().decode(p)}async function ke(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 Re(r){return r.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}async function Fe(r,e){let t=await r.subtle.exportKey("raw",e);return le(t)}async function we(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 Oe(r,e,t){let n=new TextEncoder().encode(String(e)),s=await(await we(r,n.buffer,t)).arrayBuffer();return le(s)}function Te(r,e,t){let n=Number(r)||0;return t?n+(Number(e)||0)*28:n}async function $e(r){let{host:e,port:t,secure:n,timeoutMs:o=5e3,signal:s,fetchFn:p}=r,d=p||me();if(!d)throw new f("No fetch() implementation found.");let i=xe({host:e,port:t,secure:n});try{let{res:u,json:h}=await te(d,`${i}/api/info`,{method:"GET",timeoutMs:o,signal:s,headers:{Accept:"application/json"}});if(u.ok&&h&&typeof h=="object"&&"version"in h)return{baseUrl:i,serverInfo:h};throw new V(`Server info request failed (status ${u.status}).`)}catch(u){throw u instanceof L?u:new M("Could not reach server /api/info.",{cause:u})}}var Ie=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||me();if(!t)throw new f("No fetch() implementation found.");this.fetchFn=t;let n=e.cryptoObj||ce();if(!n)throw new f("No crypto implementation found.");this.cryptoObj=n,this.base64=e.base64||Q(),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:p}=s,{res:d,json:i}=await te(this.fetchFn,`${p}/api/resolve`,{method:"POST",timeoutMs:n,signal:o,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({value:e})});if(!d.ok){let u=(i&&typeof i=="object"&&"error"in i?i.error:null)||`Share lookup failed (status ${d.status}).`;throw new V(u,{details:i})}return i||{valid:!1,reason:"Unknown response."}}async checkCompatibility(e){let t,n;try{let i=await $e({...e,fetchFn:this.fetchFn});t=i.baseUrl,n=i.serverInfo}catch(i){throw i instanceof L?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"),p=he(s),d=he(o);return p.major!==d.major?{compatible:!1,clientVersion:s,serverVersion:o,message:`Incompatible versions. Client v${s}, Server v${o}${n?.name?` (${n.name})`:""}.`,serverInfo:n,baseUrl:t}:p.minor>d.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,p=s?.capabilities?.upload;if(!p||!p.enabled)throw new f("Server does not support file uploads.");let d=Number(t?.size||0);if(!t||!Number.isFinite(d)||d<=0)throw new f("File is missing or invalid.");let i=Number(p.maxSizeMB);if(Number.isFinite(i)&&i>0){let S=i*1e3*1e3,k=Math.ceil(d/this.chunkSize);if(Te(d,k,!!o)>S){let G=o?`File too large once encryption overhead is included. Server limit: ${i} MB.`:`File too large. Server limit: ${i} MB.`;throw new f(G)}}let u=Number(p.maxLifetimeHours),h=Number(n);if(!Number.isFinite(h)||h<0||!Number.isInteger(h))throw new f("Invalid lifetime. Must be a non-negative integer (milliseconds).");if(Number.isFinite(u)&&u>0){let S=Math.round(u*60*60*1e3);if(h===0)throw new f(`Server does not allow unlimited file lifetime. Max: ${u} hours.`);if(h>S)throw new f(`File lifetime too long. Server limit: ${u} hours.`)}if(o&&!p.e2ee)throw new f("Server does not support end-to-end encryption.");return!0}async uploadFile(e){let{host:t,port:n,secure:o,file:s,lifetimeMs:p,encrypt:d,filenameOverride:i,onProgress:u,onCancel:h,signal:S,timeouts:k={},retry:O={}}=e,G=S?null:new AbortController,_=S||G?.signal,R="initializing",Y=null,B=null,F=(async()=>{try{let w=y=>{try{u&&u(y)}catch{}};if(!this.cryptoObj?.subtle)throw new f("Web Crypto API not available (crypto.subtle).");let T=s.size;w({phase:"server-info",text:"Checking server...",percent:0,processedBytes:0,totalBytes:T});let C=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:k.serverInfoMs??5e3,signal:_}),{baseUrl:A,serverInfo:m}=C;if(w({phase:"server-compat",text:C.message,percent:0,processedBytes:0,totalBytes:T}),!C.compatible)throw new f(C.message);let P=i??s.name??"file";d||Ee(P),this.validateUploadInputs({file:s,lifetimeMs:p,encrypt:d,serverInfo:m});let l=null,D=null,U=P;if(d){w({phase:"crypto",text:"Generating encryption key...",percent:0,processedBytes:0,totalBytes:T});try{l=await Re(this.cryptoObj),D=await Fe(this.cryptoObj,l),U=await Oe(this.cryptoObj,P,l)}catch(y){throw new L("Failed to prepare encryption.",{code:"CRYPTO_PREP_FAILED",cause:y})}}let g=Math.ceil(s.size/this.chunkSize),j=Te(s.size,g,d);w({phase:"init",text:"Reserving server storage...",percent:0,processedBytes:0,totalBytes:T});let W={filename:U,lifetime:p,isEncrypted:!!d,totalSize:j,totalChunks:g},c=await te(this.fetchFn,`${A}/upload/init`,{method:"POST",timeoutMs:k.initMs??15e3,signal:_,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(W)});if(!c.res.ok){let a=c.json?.error||`Server initialisation failed: ${c.res.status}`;throw new V(a,{details:c.json||c.text})}let E=c.json?.uploadId;if(!E||typeof E!="string")throw new V("Server did not return a valid uploadId.");Y=E,B=A,R="uploading";let K=Number.isFinite(O.retries)?O.retries:5,ee=Number.isFinite(O.backoffMs)?O.backoffMs:1e3,H=Number.isFinite(O.maxBackoffMs)?O.maxBackoffMs:3e4;for(let y=0;y<g;y++){if(_?.aborted)throw _.reason||new J;let a=y*this.chunkSize,z=Math.min(a+this.chunkSize,s.size),Z=s.slice(a,z),de=y/g*100,De=y*this.chunkSize;w({phase:"chunk",text:`Uploading chunk ${y+1} of ${g}...`,percent:de,processedBytes:De,totalBytes:T,chunkIndex:y,totalChunks:g});let I=await Z.arrayBuffer(),x;if(d&&l?x=await we(this.cryptoObj,I,l):x=new Blob([I]),x.size>5243904)throw new f("Chunk too large (client-side). Check chunk size settings.");let Ue=await x.arrayBuffer(),fe=await ke(this.cryptoObj,Ue),Se={"Content-Type":"application/octet-stream","X-Upload-ID":E,"X-Chunk-Index":String(y),"X-Chunk-Hash":fe},ie=`${A}/upload/chunk`;await this.attemptChunkUpload(ie,{method:"POST",headers:Se,body:x},{retries:K,backoffMs:ee,maxBackoffMs:H,timeoutMs:k.chunkMs??6e4,signal:_,progress:w,chunkIndex:y,totalChunks:g,chunkSize:this.chunkSize,fileSizeBytes:T})}w({phase:"complete",text:"Finalising upload...",percent:100,processedBytes:T,totalBytes:T}),R="completing";let q=await te(this.fetchFn,`${A}/upload/complete`,{method:"POST",timeoutMs:k.completeMs??3e4,signal:_,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:E})});if(!q.res.ok){let a=q.json?.error||"Finalisation failed.";throw new V(a,{details:q.json||q.text})}let b=q.json?.id;if(!b||typeof b!="string")throw new V("Server did not return a valid file id.");let N=`${A}/${b}`;return d&&D&&(N+=`#${D}`),w({phase:"done",text:"Upload successful!",percent:100,processedBytes:T,totalBytes:T}),R="completed",{downloadUrl:N,fileId:b,uploadId:E,baseUrl:A,...d&&D?{keyB64:D}:{}}}catch(w){throw w instanceof Error&&(w.name==="AbortError"||w.message?.includes("abort"))?(R="cancelled",h?.()):R="error",w}})(),$=async(w,T)=>{try{await te(this.fetchFn,`${T}/upload/cancel`,{method:"POST",timeoutMs:5e3,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:w})})}catch{}};return{result:F,cancel:w=>{R==="completed"||R==="cancelled"||(R="cancelled",Y&&B&&$(Y,B).catch(()=>{}),G?.abort(new J(w||"Upload cancelled by user.")))},getStatus:()=>R}}async downloadFile(e){let{host:t,port:n,secure:o,fileId:s,keyB64:p,onProgress:d,onData:i,signal:u,timeoutMs:h=6e4}=e,S=l=>{try{d&&d(l)}catch{}};if(!s||typeof s!="string")throw new f("File ID is required.");S({phase:"server-info",text:"Checking server...",processedBytes:0,totalBytes:0,percent:0});let k=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:h,signal:u}),{baseUrl:O}=k;if(S({phase:"server-compat",text:k.message,processedBytes:0,totalBytes:0,percent:0}),!k.compatible)throw new f(k.message);S({phase:"metadata",text:"Fetching file info...",processedBytes:0,totalBytes:0,percent:0});let{signal:G,cleanup:_}=re(u,h),R;try{let l=await this.fetchFn(`${O}/api/file/${s}/meta`,{method:"GET",headers:{Accept:"application/json"},signal:G});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}).`);R=await l.json()}catch(l){throw l instanceof L?l:l instanceof Error&&l.name==="AbortError"?new J("Download cancelled."):new M("Could not fetch file metadata.",{cause:l})}finally{_()}let Y=!!R.isEncrypted,B=R.sizeBytes||0;if(!i&&B>104857600){let l=Math.round(B/1048576),D=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 ${D}MB.`)}let F,$;if(Y){if(!p)throw new f("Decryption key is required for encrypted files.");if(!this.cryptoObj?.subtle)throw new f("Web Crypto API not available for decryption.");S({phase:"decrypting",text:"Preparing decryption...",processedBytes:0,totalBytes:0,percent:0});try{$=await ye(this.cryptoObj,p,this.base64),F=await ge(this.cryptoObj,R.encryptedFilename,$,this.base64)}catch(l){throw new L("Failed to decrypt filename. Invalid key or corrupted data.",{code:"DECRYPT_FILENAME_FAILED",cause:l})}}else F=R.filename||"file";S({phase:"downloading",text:"Starting download...",percent:0,processedBytes:0,totalBytes:B});let{signal:w,cleanup:T}=re(u,h),C=0,A=[],m=!i;try{let l=await this.fetchFn(`${O}/api/file/${s}`,{method:"GET",signal:w});if(!l.ok)throw new V(`Download failed (status ${l.status}).`);if(!l.body)throw new V("Streaming response not available.");let D=l.body.getReader();if(Y&&$){let U=this.chunkSize+28,g=[],j=0,W=()=>{if(g.length===0)return new Uint8Array(0);if(g.length===1){let E=g[0];return g.length=0,j=0,E}let c=new Uint8Array(j),v=0;for(let E of g)c.set(E,v),v+=E.length;return g.length=0,j=0,c};for(;;){if(u?.aborted)throw new J("Download cancelled.");let{done:c,value:v}=await D.read();if(c)break;for(g.push(v),j+=v.length;j>=U;){let K=W(),ee=K.subarray(0,U);if(K.length>U){let X=K.subarray(U);g.push(X),j=X.length}let H=await ne(this.cryptoObj,ee,$),q=new Uint8Array(H);m?A.push(q):await i(q)}C+=v.length;let E=B>0?Math.round(C/B*100):0;S({phase:"decrypting",text:`Downloading & decrypting... (${E}%)`,percent:E,processedBytes:C,totalBytes:B})}if(j>0){let c=W(),v=await ne(this.cryptoObj,c,$),E=new Uint8Array(v);m?A.push(E):await i(E)}}else for(;;){if(u?.aborted)throw new J("Download cancelled.");let{done:U,value:g}=await D.read();if(U)break;m?A.push(g):await i(g),C+=g.length;let j=B>0?Math.round(C/B*100):0;S({phase:"downloading",text:`Downloading... (${j}%)`,percent:j,processedBytes:C,totalBytes:B})}}catch(l){throw l instanceof L?l:l instanceof Error&&l.name==="AbortError"?new J("Download cancelled."):new M("Download failed.",{cause:l})}finally{T()}S({phase:"complete",text:"Download complete!",percent:100,processedBytes:C,totalBytes:B});let P;if(m&&A.length>0){let l=A.reduce((U,g)=>U+g.length,0);P=new Uint8Array(l);let D=0;for(let U of A)P.set(U,D),D+=U.length}return{filename:F,receivedBytes:C,wasEncrypted:Y,...P?{data:P}:{}}}async attemptChunkUpload(e,t,n){let{retries:o,backoffMs:s,maxBackoffMs:p,timeoutMs:d,signal:i,progress:u,chunkIndex:h,totalChunks:S,chunkSize:k,fileSizeBytes:O}=n,G=o,_=s,R=o;for(;;){if(i?.aborted)throw i.reason||new J;let{signal:Y,cleanup:B}=re(i,d);try{let F=await this.fetchFn(e,{...t,signal:Y});if(F.ok)return;let $=await F.text().catch(()=>"");throw new V(`Chunk ${h+1} failed (HTTP ${F.status}).`,{details:{status:F.status,bodySnippet:$.slice(0,120)}})}catch(F){if(B(),F instanceof Error&&(F.name==="AbortError"||F.code==="ABORT_ERR"))throw F;if(i?.aborted)throw i.reason||new J;if(G<=0)throw F instanceof L?F:new M("Chunk upload failed.",{cause:F});let $=R-G+1,w=h*k,T=h/S*100,C=_,A=100;for(;C>0;){let m=(C/1e3).toFixed(1);u({phase:"retry-wait",text:`Chunk upload failed. Retrying in ${m}s... (${$}/${R})`,percent:T,processedBytes:w,totalBytes:O,chunkIndex:h,totalChunks:S}),await pe(Math.min(A,C),i),C-=A}u({phase:"retry",text:`Chunk upload failed. Retrying now... (${$}/${R})`,percent:T,processedBytes:w,totalBytes:O,chunkIndex:h,totalChunks:S}),G-=1,_=Math.min(_*2,p);continue}finally{B()}}}};function Me(r){let e=String(r||"").toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function ze(r,e){return!!e||Me(r||"")}function be(r){let e=r||ce(),t="ABCDEFGHJKLMNPQRSTUVWXYZ";if(e){let s=new Uint8Array(8);e.getRandomValues(s);let p="";for(let i=0;i<4;i++)p+=t[s[i]%t.length];let d="";for(let i=4;i<8;i++)d+=(s[i]%10).toString();return`${p}-${d}`}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 Pe(r){return/^[A-Z]{4}-\d{4}$/.test(String(r||"").trim())}function oe(r,e){return{path:r.peerjsPath??e?.peerjsPath??"/peerjs",iceServers:r.iceServers??e?.iceServers??[]}}function se(r={}){let{host:e,port:t,peerjsPath:n="/peerjs",secure:o=!1,iceServers:s=[]}=r,p={host:e,path:n,secure:o,config:{iceServers:s},debug:0};return t&&(p.port=t),p}async function ve(r){let{code:e,codeGenerator:t,maxAttempts:n,buildPeer:o,onCode:s}=r,p=e||t(),d=null,i=null;for(let u=0;u<n;u++){s?.(p,u);try{return d=await new Promise((h,S)=>{let k=o(p);k.on("open",()=>h(k)),k.on("error",O=>{try{k.destroy()}catch{}S(O)})}),{peer:d,code:p}}catch(h){i=h,p=t()}}throw i||new M("Could not establish PeerJS connection.")}function at(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async function Le(r){let{file:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:p,secure:d=!1,iceServers:i,codeGenerator:u,cryptoObj:h,maxAttempts:S=4,chunkSize:k=256*1024,endAckTimeoutMs:O=15e3,bufferHighWaterMark:G=8*1024*1024,bufferLowWaterMark:_=2*1024*1024,heartbeatIntervalMs:R=5e3,onCode:Y,onStatus:B,onProgress:F,onComplete:$,onError:w,onDisconnect:T,onCancel:C}=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 A=n?.capabilities?.p2p;if(n&&!A?.enabled)throw new f("Direct transfer is disabled on this server.");let{path:m,iceServers:P}=oe({peerjsPath:p,iceServers:i},A),l=se({host:o,port:s,peerjsPath:m,secure:d,iceServers:P}),D=u||(()=>be(h)),U=a=>new t(a,l),{peer:g,code:j}=await ve({code:null,codeGenerator:D,maxAttempts:S,buildPeer:U,onCode:Y}),W=at(),c="listening",v=null,E=0,K=null,ee=a=>{let z=Number.isFinite(a.total)&&a.total>0?a.total:e.size,Z=Math.min(Number(a.received)||0,z||0),de=z?Z/z*100:0;F?.({processedBytes:Z,totalBytes:z,percent:de})},H=a=>{c==="closed"||c==="completed"||c==="cancelled"||(c="closed",w?.(a),X())},q=()=>{c==="finishing"&&(c="completed",$?.(),X())},X=()=>{K&&(clearInterval(K),K=null),typeof window<"u"&&window.removeEventListener("beforeunload",b);try{v?.close()}catch{}try{g.destroy()}catch{}},b=()=>{try{v?.send({t:"error",message:"Sender closed the connection."})}catch{}N()};typeof window<"u"&&window.addEventListener("beforeunload",b);let N=()=>{if(c==="closed"||c==="cancelled")return;let a=c==="transferring"||c==="finishing";c="cancelled";try{v&&v.open&&v.send({t:"cancelled",message:"Sender cancelled the transfer."})}catch{}a&&C&&C({cancelledBy:"sender"}),X()},y=()=>c==="closed"||c==="cancelled";return g.on("connection",a=>{if(c==="closed")return;if(v){let I=v.open!==!1;if(I&&c==="transferring"){try{a.send({t:"error",message:"Transfer already in progress."})}catch{}try{a.close()}catch{}return}else if(I){try{a.send({t:"error",message:"Another receiver is already connected."})}catch{}try{a.close()}catch{}return}else{try{v.close()}catch{}v=null,c="listening",E=0}}v=a,c="negotiating",B?.({phase:"waiting",message:"Connected. Waiting for receiver to accept..."});let z=null,Z=null,de=new Promise(I=>{z=I}),De=new Promise(I=>{Z=I});a.on("data",I=>{if(!I||typeof I!="object"||I instanceof ArrayBuffer||ArrayBuffer.isView(I))return;let x=I;if(x.t){if(x.t==="ready"){B?.({phase:"transferring",message:"Receiver accepted. Starting transfer..."}),z?.();return}if(x.t==="progress"){ee({received:x.received||0,total:x.total||0});return}if(x.t==="ack"&&x.phase==="end"){Z?.(x);return}if(x.t!=="pong"){if(x.t==="error"){H(new M(x.message||"Receiver reported an error."));return}if(x.t==="cancelled"){if(c==="cancelled"||c==="closed"||c==="completed")return;c="cancelled",C?.({cancelledBy:"receiver",message:x.message}),X()}}}}),a.on("open",async()=>{try{if(y())return;a.send({t:"meta",sessionId:W,name:e.name,size:e.size,mime:e.type||"application/octet-stream"});let I=e.size,x=a._dc;if(x&&Number.isFinite(_))try{x.bufferedAmountLowThreshold=_}catch{}if(await de,y())return;R>0&&(K=setInterval(()=>{if(c==="transferring"||c==="finishing")try{a.send({t:"ping"})}catch{}},R)),c="transferring";for(let Be=0;Be<I;Be+=k){if(y())return;let Ve=await e.slice(Be,Be+k).arrayBuffer();if(y())return;if(a.send(Ve),E+=Ve.byteLength,x)for(;x.bufferedAmount>G;)await new Promise(Je=>{let Ze=setTimeout(Je,60);try{x.addEventListener("bufferedamountlow",()=>{clearTimeout(Ze),Je()},{once:!0})}catch{}})}if(y())return;c="finishing",a.send({t:"end"});let Ue=Number.isFinite(O)?Math.max(O,Math.ceil(e.size/(1024*1024))*1e3):null,fe=await Promise.race([De,pe(Ue||15e3).catch(()=>null)]);if(y())return;if(!fe||typeof fe!="object")throw new M("Receiver did not confirm completion.");let Se=fe,ie=Number(Se.total)||e.size,Ke=Number(Se.received)||0;if(ie&&Ke<ie)throw new M("Receiver reported an incomplete transfer.");ee({received:Ke||ie,total:ie}),q()}catch(I){H(I)}}),a.on("error",I=>{H(I)}),a.on("close",()=>{if(c==="closed"||c==="completed"||c==="cancelled"){X();return}c==="transferring"||c==="finishing"?(c="cancelled",C?.({cancelledBy:"receiver"}),X()):(v=null,c="listening",E=0,T?.())})}),{peer:g,code:j,sessionId:W,stop:N,getStatus:()=>c,getBytesSent:()=>E,getConnectedPeerId:()=>v&&v.peer||null}}async function Ge(r){let{code:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:p,secure:d=!1,iceServers:i,autoReady:u=!0,watchdogTimeoutMs:h=15e3,onStatus:S,onMeta:k,onData:O,onProgress:G,onComplete:_,onError:R,onDisconnect:Y,onCancel:B}=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 F=n?.capabilities?.p2p;if(n&&!F?.enabled)throw new f("Direct transfer is disabled on this server.");let $=String(e).trim().replace(/\s+/g,"").toUpperCase();if(!Pe($))throw new f("Invalid direct transfer code.");let{path:w,iceServers:T}=oe({peerjsPath:p,iceServers:i},F),C=se({host:o,port:s,peerjsPath:w,secure:d,iceServers:T}),A=new t(void 0,C),m="initializing",P=0,l=0,D=null,U=0,g=120,j=Promise.resolve(),W=null,c=null,v=()=>{h<=0||(W&&clearTimeout(W),W=setTimeout(()=>{m==="transferring"&&K(new M("Connection timed out (no data received)."))},h))},E=()=>{W&&(clearTimeout(W),W=null)},K=b=>{m==="closed"||m==="completed"||m==="cancelled"||(m="closed",R?.(b),H())},ee=b=>{m==="transferring"&&(m="completed",_?.(b),H())},H=()=>{E(),typeof window<"u"&&window.removeEventListener("beforeunload",q);try{A.destroy()}catch{}},q=()=>{try{c?.send({t:"error",message:"Receiver closed the connection."})}catch{}X()};typeof window<"u"&&window.addEventListener("beforeunload",q);let X=()=>{if(m==="closed"||m==="cancelled")return;let b=m==="transferring";m="cancelled";try{c&&c.open&&c.send({t:"cancelled",message:"Receiver cancelled the transfer."})}catch{}b&&B&&B({cancelledBy:"receiver"}),H()};return A.on("error",b=>{K(b)}),A.on("open",()=>{m="connecting";let b=A.connect($,{reliable:!0});c=b,b.on("open",()=>{m="negotiating",S?.({phase:"connected",message:"Waiting for file details..."})}),b.on("data",async N=>{try{if(v(),N&&typeof N=="object"&&!(N instanceof ArrayBuffer)&&!ArrayBuffer.isView(N)){let a=N;if(a.t==="meta"){if(D&&a.sessionId&&a.sessionId!==D){try{b.send({t:"error",message:"Busy with another session."})}catch{}return}a.sessionId&&(D=a.sessionId);let z=String(a.name||"file");P=Number(a.size)||0,l=0,j=Promise.resolve();let Z=()=>{m="transferring",v();try{b.send({t:"ready"})}catch{}};u?(k?.({name:z,total:P}),G?.({processedBytes:l,totalBytes:P,percent:0}),Z()):(k?.({name:z,total:P,sendReady:Z}),G?.({processedBytes:l,totalBytes:P,percent:0}));return}if(a.t==="ping"){try{b.send({t:"pong"})}catch{}return}if(a.t==="end"){if(E(),await j,P&&l<P){let z=new M("Transfer ended before the full file was received.");try{b.send({t:"error",message:z.message})}catch{}throw z}try{b.send({t:"ack",phase:"end",received:l,total:P})}catch{}ee({received:l,total:P});return}if(a.t==="error")throw new M(a.message||"Sender reported an error.");if(a.t==="cancelled"){if(m==="cancelled"||m==="closed"||m==="completed")return;m="cancelled",B?.({cancelledBy:"sender",message:a.message}),H();return}return}let y;if(N instanceof ArrayBuffer)y=Promise.resolve(new Uint8Array(N));else if(ArrayBuffer.isView(N))y=Promise.resolve(new Uint8Array(N.buffer,N.byteOffset,N.byteLength));else if(typeof Blob<"u"&&N instanceof Blob)y=N.arrayBuffer().then(a=>new Uint8Array(a));else return;j=j.then(async()=>{let a=await y;O&&await O(a),l+=a.byteLength;let z=P?Math.min(100,l/P*100):0;G?.({processedBytes:l,totalBytes:P,percent:z});let Z=Date.now();if(l===P||Z-U>=g){U=Z;try{b.send({t:"progress",received:l,total:P})}catch{}}}).catch(a=>{try{b.send({t:"error",message:a?.message||"Receiver write failed."})}catch{}K(a)})}catch(y){K(y)}}),b.on("close",()=>{if(m==="closed"||m==="completed"||m==="cancelled"){H();return}m==="transferring"?(m="cancelled",B?.({cancelledBy:"sender"}),H()):m==="negotiating"?(m="closed",H(),Y?.()):K(new M("Sender disconnected before file details were received."))})}),{peer:A,stop:X,getStatus:()=>m,getBytesReceived:()=>l,getTotalBytes:()=>P,getSessionId:()=>D}}return ot(ct);})();
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);})();
2
2
  if(typeof window!=="undefined"){window.DropgateCore=DropgateCore;}
3
3
  //# sourceMappingURL=index.browser.js.map