@dropgate/core 2.1.0 → 2.2.0-beta.2
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 +4 -4
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +290 -199
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -7
- package/dist/index.d.ts +32 -7
- package/dist/index.js +290 -199
- package/dist/index.js.map +1 -1
- package/dist/p2p/index.cjs +54 -15
- package/dist/p2p/index.cjs.map +1 -1
- package/dist/p2p/index.d.cts +13 -2
- package/dist/p2p/index.d.ts +13 -2
- package/dist/p2p/index.js +54 -15
- package/dist/p2p/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
<div align="center">
|
|
10
10
|
|
|
11
11
|

|
|
12
|
-

|
|
13
13
|

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