/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/megajs@1.3.9/dist/main.node-cjs.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__copyProps=(t,e,r,i)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let s of __getOwnPropNames(e))__hasOwnProp.call(t,s)||s===r||__defProp(t,s,{get:()=>e[s],enumerable:!(i=__getOwnPropDesc(e,s))||i.enumerable});return t},__toESM=(t,e,r)=>(r=null!=t?__create(__getProtoOf(t)):{},__copyProps(!e&&t&&t.__esModule?r:__defProp(r,"default",{value:t,enumerable:!0}),t)),import_stream2=require("stream"),import_pumpify=__toESM(require("pumpify"),1),import_stream=require("stream");function streamToCb(t,e){const r=[];let i;t.on("data",(t=>r.push(t))),t.on("end",(()=>{i||(i=!0,e(null,Buffer.concat(r)))})),t.on("error",(t=>{i||(i=!0,e(t))}))}function chunkSizeSafe(t){let e;return new import_stream.Transform({transform(r,i,s){e&&(r=Buffer.concat([e,r]));const o=Math.floor(r.length/t)*t;o?r.length>o?(e=r.slice(o),this.push(r.slice(0,o))):(e=void 0,this.push(r)):e=e?Buffer.concat([e,r]):r,s()},flush(t){e&&this.push(e),t()}})}function detectSize(t,e){const r=[];let i=0;return new import_stream.Transform({transform(t,e,s){r.push(t),i+=t.length,s()},flush(s){e(i),function e(){for(;r.length;){if(!t.write(r.shift()))return t.once("drain",e)}t.end(),s()}()}})}function createPromise(t){let e;const r=new Promise(((t,r)=>{e=(e,i)=>{e?r(e):t(i)}}));return t&&r.then((e=>t(null,e)),t),[e,r]}var import_crypto=__toESM(require("crypto"),1);function prepareKey(t){let e,r,i,s=Buffer.from([147,196,103,227,125,176,199,164,209,190,63,129,1,82,203,86]);for(i=65536;i--;)for(r=0;r<t.length;r+=16){const i=Buffer.alloc(16);for(e=0;e<16;e+=4)e+r<t.length&&t.copy(i,e,e+r,e+r+4);s=import_crypto.default.createCipheriv("aes-128-ecb",i,Buffer.alloc(0)).setAutoPadding(!1).update(s)}return s}function prepareKeyV2(t,e,r){const i=Buffer.from(e.s,"base64");import_crypto.default.pbkdf2(t,i,1e5,32,"sha512",r)}var AES=class{constructor(t){if(16!==t.length)throw Error("Wrong key length. Key must be 128bit.");this.key=t}encryptCBC(t){const e=Buffer.alloc(16,0),r=import_crypto.default.createCipheriv("aes-128-cbc",this.key,e).setAutoPadding(!1),i=Buffer.concat([r.update(t),r.final()]);return i.copy(t),i}decryptCBC(t){const e=Buffer.alloc(16,0),r=import_crypto.default.createDecipheriv("aes-128-cbc",this.key,e).setAutoPadding(!1),i=Buffer.concat([r.update(t),r.final()]);return i.copy(t),i}stringhash(t){const e=[0,0,0,0];for(let r=0;r<t.length;r+=4)if(t.length-r<4){const i=t.length-r;e[r/4&3]^=t.readIntBE(r,i)<<8*(4-i)}else e[r/4&3]^=t.readInt32BE(r);let r=Buffer.allocUnsafe(16);for(let t=0;t<4;t++)r.writeInt32BE(e[t],4*t,!0);const i=import_crypto.default.createCipheriv("aes-128-ecb",this.key,Buffer.alloc(0));for(let t=16384;t--;)r=i.update(r);const s=Buffer.allocUnsafe(8);return r.copy(s,0,0,4),r.copy(s,4,8,12),s}encryptECB(t){const e=import_crypto.default.createCipheriv("aes-128-ecb",this.key,Buffer.alloc(0)).setAutoPadding(!1).update(t);return e.copy(t),e}decryptECB(t){const e=import_crypto.default.createDecipheriv("aes-128-ecb",this.key,Buffer.alloc(0)).setAutoPadding(!1).update(t);return e.copy(t),e}},CTR=class{constructor(t,e,r=0){this.key=t.key,this.nonce=e.slice(0,8);const i=Buffer.alloc(16);this.nonce.copy(i,0),0!==r&&this.incrementCTRBuffer(i,r/16),this.encrypt=t=>(this.encryptCipher=import_crypto.default.createCipheriv("aes-128-ctr",this.key,i),this.encrypt=this._encrypt,this.encrypt(t)),this.decrypt=t=>(this.decryptCipher=import_crypto.default.createDecipheriv("aes-128-ctr",this.key,i),this.decrypt=this._decrypt,this.decrypt(t))}_encrypt(t){return this.encryptCipher.update(t).copy(t),t}_decrypt(t){return this.decryptCipher.update(t).copy(t),t}incrementCTRBuffer(t,e){const r=t.length;let i,s=r-1;for(;0!==e;)i=(e+t[s])%256,e=Math.floor((e+t[s])/256),t[s]=i,s-=1,s<0&&(s=r-1)}},MAC=class{constructor(t,e){this.key=t.key,this.nonce=e.slice(0,8),this.macCipher=import_crypto.default.createCipheriv("aes-128-ecb",this.key,Buffer.alloc(0)),this.posNext=this.increment=131072,this.pos=0,this.macs=[],this.mac=Buffer.alloc(16),this.nonce.copy(this.mac,0),this.nonce.copy(this.mac,8)}condense(){this.mac&&(this.macs.push(this.mac),this.mac=void 0);let t=Buffer.alloc(16,0);for(const e of this.macs){for(let r=0;r<16;r++)t[r]^=e[r];t=this.macCipher.update(t)}const e=Buffer.allocUnsafe(8);return e.writeInt32BE(t.readInt32BE(0)^t.readInt32BE(4),0),e.writeInt32BE(t.readInt32BE(8)^t.readInt32BE(12),4),e}update(t){for(let e=0;e<t.length;e+=16){for(let r=0;r<16;r++)this.mac[r]^=t[e+r];this.mac=this.macCipher.update(this.mac),this.checkBounding()}}checkBounding(){this.pos+=16,this.pos>=this.posNext&&(this.macs.push(Buffer.from(this.mac)),this.nonce.copy(this.mac,0),this.nonce.copy(this.mac,8),this.increment<1048576&&(this.increment+=131072),this.posNext+=this.increment)}};function formatKey(t){return"string"==typeof t?d64(t):t}function e64(t){return t.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function d64(t){return Buffer.from(t,"base64")}function getCipher(t){return new AES(unmergeKeyMac(t).slice(0,16))}function megaEncrypt(t,e={}){const r=e.start||0;if(0!==r)throw Error("Encryption cannot start midstream otherwise MAC verification will fail.");(t=formatKey(t))||(t=globalThis.crypto.getRandomValues(new Uint8Array(24))),t instanceof Buffer||(t=Buffer.from(t));let i=new import_stream2.Transform({transform(t,e,r){n.update(t);const i=o.encrypt(t);r(null,Buffer.from(i))},flush(e){i.mac=n.condense(),i.key=mergeKeyMac(t,i.mac),e()}});if(24!==t.length)throw Error("Wrong key length. Key must be 192bit.");const s=new AES(t.slice(0,16)),o=new CTR(s,t.slice(16),r),n=new MAC(s,t.slice(16));return i=(0,import_pumpify.default)(chunkSizeSafe(16),i),i}function megaDecrypt(t,e={}){const r=e.start||0;if(0!==r&&(e.disableVerification=!0),r%16!=0)throw Error("start argument of megaDecrypt must be a multiple of 16");(t=formatKey(t))instanceof Buffer||(t=Buffer.from(t));const i=getCipher(t),s=new CTR(i,t.slice(16),r),o=!e.disableVerification&&new MAC(i,t.slice(16));let n=new import_stream2.Transform({transform(t,e,r){const i=s.decrypt(t);o&&o.update(i),r(null,Buffer.from(i))},flush(r){o&&(n.mac=o.condense()),e.disableVerification||n.mac.equals(t.slice(24))?r():r(Error("MAC verification failed"))}});return n=(0,import_pumpify.default)(chunkSizeSafe(16),n),n}function megaVerify(t){(t=formatKey(t))instanceof Buffer||(t=Buffer.from(t));let e=new import_stream2.Transform({transform(t,e,r){i.update(t),r(null)},flush(r){e.mac=i.condense(),e.mac.equals(t.slice(24))?r():r(Error("MAC verification failed"))}});if(32!==t.length)throw Error("Wrong key length. Key must be 256bit.");const r=getCipher(t),i=new MAC(r,t.slice(16));return e=(0,import_pumpify.default)(chunkSizeSafe(16),e),e}function unmergeKeyMac(t){const e=Buffer.alloc(32);t.copy(e);for(let t=0;t<16;t++)e.writeUInt8(e.readUInt8(t)^e.readUInt8(16+t,!0),t);return e}function mergeKeyMac(t,e){const r=Buffer.alloc(32);t.copy(r),e.copy(r,24);for(let t=0;t<16;t++)r.writeUInt8(r.readUInt8(t)^r.readUInt8(16+t),t);return r}function constantTimeCompare(t,e){if(t.length!==e.length)return!1;const r=t.length;let i=0;for(let s=0;s<r;s++)i|=t[s]^e[s];return 0===i}async function generateHashcashToken(t){const[e,r,,i]=t.split(":");if(1!==Number(e))throw Error("hashcash challenge is not version 1");const s=Number(r),o=1+((63&s)<<1)<<7*(s>>6)+3,n=d64(i),a=Buffer.alloc(12582916);for(let t=0;t<262144;t++)a.set(n,4+48*t);for(;;){if(new DataView(await globalThis.crypto.subtle.digest("SHA-256",a)).getUint32(0)<=o)return`1:${i}:${e64(a.slice(0,4))}`;let t=0;for(;a[t]++,!a[t++];);}}var globalState={},bs=28,bx2=1<<bs,bm=bx2-1,bd=bs>>1,bdm=(1<<bd)-1,log2=Math.log(2);function zeros(t){const e=[];for(;t-- >0;)e[t]=0;return e}function zclip(t){let e=t.length;if(t[e-1])return t;for(;e>1&&0===t[e-1];)e--;return t.slice(0,e)}function nbits(t){let e,r=1;return 0!=(e=t>>>16)&&(t=e,r+=16),0!=(e=t>>8)&&(t=e,r+=8),0!=(e=t>>4)&&(t=e,r+=4),0!=(e=t>>2)&&(t=e,r+=2),0!=(e=t>>1)&&(t=e,r+=1),r}function badd(t,e){const r=t.length,i=e.length;if(r<i)return badd(e,t);const s=[];let o=0,n=0;for(;n<i;n++)o+=t[n]+e[n],s[n]=o&bm,o>>>=bs;for(;n<r;n++)o+=t[n],s[n]=o&bm,o>>>=bs;return o&&(s[n]=o),s}function bsub(t,e){const r=t.length,i=e.length;if(i>r)return[];if(i===r){if(e[i-1]>t[i-1])return[];if(1===i)return[t[0]-e[0]]}const s=[];let o,n=0;for(o=0;o<i;o++)n+=t[o]-e[o],s[o]=n&bm,n>>=bs;for(;o<r;o++)n+=t[o],s[o]=n&bm,n>>=bs;return n?[]:zclip(s)}function ip(t,e,r,i,s){const o=r&bdm,n=r>>bd,a=i&bdm,l=i>>bd,h=n*a+l*o,c=o*a+((h&bdm)<<bd)+t[e]+s;return t[e]=c&bm,s=n*l+(h>>bd)+(c>>bs)}function bsqr(t){const e=t.length,r=zeros(2*e);let i,s,o=0;for(i=0;i<e;i++){for(o=ip(r,2*i,t[i],t[i],0),s=i+1;s<e;s++)o=ip(r,i+s,2*t[s],t[i],o);r[i+e]=o}return zclip(r)}function bmul(t,e){const r=t.length,i=e.length,s=zeros(r+i-1);let o,n,a;for(n=0;n<i;n++){for(o=0,a=0;a<r;a++)o=ip(s,n+a,t[a],e[n],o);s[n+r]=o}return zclip(s)}function toppart(t,e,r){let i=0;for(;e>=0&&r-- >0;)i=i*bx2+t[e--];return i}function bdiv(t,e){let r=t.length-1;const i=e.length-1;let s,o,n,a,l=r-i;if(r<i||r===i&&(t[r]<e[r]||r>0&&t[r]===e[r]&&t[r-1]<e[r-1]))return globalState.q=[0],globalState.mod=t,globalState;if(r===i&&toppart(t,i,2)/toppart(e,i,2)<4){for(s=t.concat(),o=0;n=bsub(s,e),0!==n.length;)s=n,o++;return globalState.q=[o],globalState.mod=s,globalState}const h=Math.floor(Math.log(e[i])/log2)+1,c=bs-h;s=t.concat();const u=e.concat();if(c){for(a=i;a>0;a--)u[a]=u[a]<<c&bm|u[a-1]>>h;for(u[0]=u[0]<<c&bm,s[r]&bm<<h&bm&&(s[++r]=0,l++),a=r;a>0;a--)s[a]=s[a]<<c&bm|s[a-1]>>h;s[0]=s[0]<<c&bm}let d;const f=zeros(l+1);let p=zeros(l).concat(u);for(;d=bsub(s,p),0!==d.length;)f[l]++,s=d;const m=u[i],y=toppart(u,i,2);let g;for(a=r;a>i;a--){g=a-i-1,a>=s.length?f[g]=1:s[a]===m?f[g]=bm:f[g]=Math.floor(toppart(s,a,2)/m);const t=toppart(s,a,3);for(;f[g]*y>t;)f[g]--;p=p.slice(1),d=bsub(s,bmul([f[g]],p)),0===d.length&&(f[g]--,d=bsub(s,bmul([f[g]],p))),s=d}if(c){for(a=0;a<s.length-1;a++)s[a]=s[a]>>c|s[a+1]<<h&bm;s[s.length-1]>>=c}return globalState.q=zclip(f),globalState.mod=zclip(s),globalState}function simplemod(t,e){let r,i=0;for(let s=t.length-1;s>=0;s--)r=t[s],i=((r>>bd)+(i<<bd))%e,i=((r&bdm)+(i<<bd))%e;return i}function bmod(t,e){if(1===e.length){if(1===t.length)return[t[0]%e[0]];if(e[0]<bdm)return[simplemod(t,e[0])]}return bdiv(t,e).mod}function bmod2(t,e,r){const i=t.length-(e.length<<1);if(i>0)return bmod2(t.slice(0,i).concat(bmod2(t.slice(i),e,r)),e,r);const s=e.length+1,o=e.length-1;let n;const a=bmul(t.slice(o),r).slice(s),l=t.slice(0,s),h=bmul(a,e).slice(0,s);let c=bsub(l,h);0===c.length&&(l[s]=1,c=bsub(l,h));for(let t=0;n=bsub(c,e),0!==n.length;t++)if(c=n,t>=3)return bmod2(c,e,r);return c}function bmodexp(t,e,r){let i=t.concat(),s=e.length-1,o=2*r.length,n=zeros(o+1);for(n[o]=1,n=bdiv(n,r).q,o=nbits(e[s])-2;s>=0;s--){for(;o>=0;o-=1)i=bmod2(bsqr(i),r,n),e[s]&1<<o&&(i=bmod2(bmul(i,t),r,n));o=bs-1}return i}function RSAdecrypt(t,e,r,i,s){const o=bmodexp(bmod(t,r),bmod(e,bsub(r,[1])),r),n=bmodexp(bmod(t,i),bmod(e,bsub(i,[1])),i);let a=bsub(n,o);return 0===a.length?(a=bsub(o,n),a=bmod(bmul(a,s),i),a=bsub(i,a)):a=bmod(bmul(a,s),i),badd(bmul(a,r),o)}function mpi2b(t){let e=1;const r=[0];let i,s=0,o=256,n=t.length;if(n<2)return 0;const a=8*(n-2),l=256*t.charCodeAt(0)+t.charCodeAt(1);if(l>a||l<a-8)return 0;for(let l=0;l<a;l++)(o<<=1)>255&&(o=1,i=t.charCodeAt(--n)),e>bm&&(e=1,r[++s]=0),i&o&&(r[s]|=e),e<<=1;return r}function b2s(t){let e=1,r=0;const i=[0];let s=1,o=0;const n=t.length*bs;let a,l="";for(a=0;a<n;a++)t[r]&e&&(i[o]|=s),(s<<=1)>255&&(s=1,i[++o]=0),(e<<=1)>bm&&(e=1,r++);for(;o>=0&&0===i[o];)o--;for(a=0;a<=o;a++)l=String.fromCharCode(i[a])+l;return l}function cryptoDecodePrivKey(t){const e=[];for(let r=0;r<4;r++){const i=2+(256*t[0]+t[1]+7>>3);if(e[r]=mpi2b(t.toString("binary").substr(0,i)),"number"==typeof e[r]){if(4!==r||t.length>=16)return!1;break}t=t.slice(i)}return e}function cryptoRsaDecrypt(t,e){const r=b2s(RSAdecrypt(mpi2b(t.toString("binary")),e[2],e[0],e[1],e[3]));return Buffer.from(r,"binary")}var import_events=require("events"),import_http=require("http"),import_https=require("https"),MAX_RETRIES=4,ERRORS={1:"EINTERNAL (-1): An internal error has occurred. Please submit a bug report, detailing the exact circumstances in which this error occurred.",2:"EARGS (-2): You have passed invalid arguments to this command.",3:"EAGAIN (-3): A temporary congestion or server malfunction prevented your request from being processed. No data was altered. Retried "+MAX_RETRIES+" times.",4:"ERATELIMIT (-4): You have exceeded your command weight per time quota. Please wait a few seconds, then try again (this should never happen in sane real-life applications).",5:"EFAILED (-5): The upload failed. Please restart it from scratch.",6:"ETOOMANY (-6): Too many concurrent IP addresses are accessing this upload target URL.",7:"ERANGE (-7): The upload file packet is out of range or not starting and ending on a chunk boundary.",8:"EEXPIRED (-8): The upload target URL you are trying to access has expired. Please request a fresh one.",9:"ENOENT (-9): Object (typically, node or user) not found. Wrong password?",10:"ECIRCULAR (-10): Circular linkage attempted",11:"EACCESS (-11): Access violation (e.g., trying to write to a read-only share)",12:"EEXIST (-12): Trying to create an object that already exists",13:"EINCOMPLETE (-13): Trying to access an incomplete resource",14:"EKEY (-14): A decryption operation failed (never returned by the API)",15:"ESID (-15): Invalid or expired user session, please relogin",16:"EBLOCKED (-16): User blocked",17:"EOVERQUOTA (-17): Request over quota",18:"ETEMPUNAVAIL (-18): Resource temporarily not available, please try again later",19:"ETOOMANYCONNECTIONS (-19)",24:"EGOINGOVERQUOTA (-24)",25:"EROLLEDBACK (-25)",26:"EMFAREQUIRED (-26): Multi-Factor Authentication Required",27:"EMASTERONLY (-27)",28:"EBUSINESSPASTDUE (-28)",29:"EPAYWALL (-29): ODQ paywall state",400:"ETOOERR (-400)",401:"ESHAREROVERQUOTA (-401)"},DEFAULT_GATEWAY="https://g.api.mega.co.nz/",DEFAULT_HTTP_AGENT=new import_http.Agent({keepAlive:!0}),DEFAULT_HTTPS_AGENT=new import_https.Agent({keepAlive:!0}),API=class t extends import_events.EventEmitter{constructor(e,r={}){super(),this.keepalive=e,this.counterId=Math.random().toString().substr(2,10),this.gateway=r.gateway||DEFAULT_GATEWAY;const i=t.getShouldAvoidUA();this.userAgent=null===r.userAgent||i?null:`${r.userAgent||""} megajs/1.3.8`.trim(),this.httpAgent=r.httpAgent||DEFAULT_HTTP_AGENT,this.httpsAgent=r.httpsAgent||DEFAULT_HTTPS_AGENT,this.fetch=r.fetch||this.defaultFetch.bind(this),this.closed=!1}async defaultFetch(e,r){if(r||(r={}),r.agent||(r.agent=t=>"http:"===t.protocol?this.httpAgent:this.httpsAgent),this.userAgent&&(r.headers||(r.headers={}),r.headers["user-agent"]||(r.headers["user-agent"]=this.userAgent)),!t.fetchModule){if("function"!=typeof globalThis.fetch)throw Error("globalThis.fetch not found!");t.fetchModule=globalThis.fetch.bind(globalThis)}return t.fetchModule(e,r)}request(t,e,r=0){const i="sml"===t.a;if(this.closed&&!i)throw Error("API is closed");const[s,o]=createPromise(e);"string"!=typeof t._hashcash&&this.counterId++;const n={id:this.counterId.toString()};this.sid&&(n.sid=this.sid),"object"==typeof t._querystring&&(Object.assign(n,t._querystring),delete t._querystring);const a={"Content-Type":"application/json"};return"string"==typeof t._hashcash&&(a["X-Hashcash"]=t._hashcash,delete t._hashcash),this.fetch(`${this.gateway}cs?${new URLSearchParams(n)}`,{method:"POST",headers:a,body:JSON.stringify([t])}).then((async e=>{const r=e.headers.get("X-Hashcash");return r?(t._hashcash=await generateHashcashToken(r),-3):handleApiResponse(e)})).then((e=>{if(this.closed&&!i)return;if(!e)return s(Error("Empty response"));let o;if(e.length&&(e=e[0]),"number"==typeof e&&e<0){if(-3===e&&r<MAX_RETRIES)return setTimeout((()=>{this.request(t,s,r+1)}),1e3*Math.pow(2,r+1));o=Error(ERRORS[-e])}else this.keepalive&&e&&e.sn&&this.pull(e.sn);s(o,e)})).catch((t=>{s(t)})),o}pull(e,r=0){const i=new AbortController,s=t.handleForceHttps()?1:0;this.sn=i,this.fetch(`${this.gateway}sc?${new URLSearchParams({sn:e,ssl:s,sid:this.sid})}`,{method:"POST",signal:i.signal}).then(handleApiResponse).then((t=>{if(this.sn=void 0,!this.closed){if("number"==typeof t&&t<0){if(-3===t&&r<MAX_RETRIES)return setTimeout((()=>{this.pull(e,r+1)}),1e3*Math.pow(2,r+1));this.emit("error",Error(ERRORS[-t]))}t.w?this.wait(t.w,e):t.sn&&(t.a&&this.emit("sc",t.a),this.pull(t.sn))}})).catch(ignoreAbortError).catch((t=>{this.emit("error",t)}))}wait(t,e){const r=new AbortController;this.sn=r,this.fetch(t,{method:"POST",signal:r.signal}).catch((()=>{})).then((()=>{this.sn=void 0,this.pull(e)}))}close(){this.sn&&this.sn.abort(),this.closed=!0}static getGlobalApi(){return t.globalApi||(t.globalApi=new t),t.globalApi}static handleForceHttps(t){return null!=t?t:!!globalThis.isSecureContext}static getShouldAvoidUA(){return!!globalThis.navigator}};function handleApiResponse(t){if("Server Too Busy"===t.statusText)return-3;if(!t.ok)throw Error(`Server returned error: ${t.statusText}`);return t.json()}function ignoreAbortError(t){if("AbortError"!==t.name)throw t}var api_default=API,import_events3=require("events"),import_events2=require("events"),import_stream3=require("stream"),import_stream_skip=__toESM(require("stream-skip"),1),File=class t extends import_events2.EventEmitter{constructor(t){if(super(),this.checkConstructorArgument(t.downloadId),this.checkConstructorArgument(t.key),this.checkConstructorArgument(t.loadedFile),this.downloadId=t.downloadId,this.key=t.key?formatKey(t.key):null,this.type=t.directory?1:0,this.directory=!!t.directory,this.directory&&!this.children&&(this.children=[]),this.api=t.api||api_default.getGlobalApi(),!(this.api instanceof api_default))throw Error("api must be a instance of API");this.loadedFile=t.loadedFile}get createdAt(){if(void 0!==this.timestamp)return 1e3*this.timestamp}checkConstructorArgument(t){if("string"==typeof t&&!/^[\w-]+$/.test(t))throw Error(`Invalid argument: "${t}"`)}loadMetadata(t,e){if(this.size=e.s||0,this.timestamp=e.ts||0,this.type=e.t,this.directory=!!e.t,this.owner=e.u,this.name=null,this.directory&&!this.children&&(this.children=[]),!t||!e.k)return;const r=e.k.split(":");this.key=formatKey(r[r.length-1]),this.key.length<=32?t.decryptECB(this.key):this.storage?this.key=this.storage.decryptRsaKey(this.key).slice(0,this.directory?16:32):this.key=null,e.a&&this.decryptAttributes(e.a)}decryptAttributes(e){if(!this.key)return this;e=d64(e),getCipher(this.key).decryptCBC(e);const r=t.unpackAttributes(e);r&&this.parseAttributes(r)}parseAttributes(t){this.attributes=t,this.name=t.n,this.label=LABEL_NAMES[t.lbl||0],this.favorited=!!t.fav}loadAttributes(e){const[r,i]=createPromise(e),s=this.directory?{a:"f",c:1,ca:1,r:1,_querystring:{n:this.downloadId}}:{a:"g",p:this.downloadId};return this.api.request(s,((e,i)=>{if(e)return r(e);if(this.directory){const e=Object.create(null),s=i.f,o=s.find((t=>t.k&&t.h===t.k.split(":")[0])),n=this.key?new AES(this.key):null;this.nodeId=o.h,this.timestamp=o.ts,e[o.h]=this;for(const r of s){if(r===o)continue;const i=new t(r,this.storage);i.loadMetadata(n,r),i.downloadId=[this.downloadId,r.h],e[r.h]=i}for(const t of s){const r=e[t.p];if(r){const i=e[t.h];r.children.push(i),i.parent=r}}if(this.loadMetadata(n,o),this.key&&!this.attributes)return r(Error("Attributes could not be decrypted with provided key."));if(this.loadedFile){const t=e[this.loadedFile];void 0===t?r(Error("Node (file or folder) not found in folder")):r(null,t)}else r(null,this)}else{if(this.size=i.s,this.decryptAttributes(i.at),this.key&&!this.attributes)return r(Error("Attributes could not be decrypted with provided key."));r(null,this)}})),i}download(e,r){"function"==typeof e&&(r=e,e={}),e||(e={});const i=e.start||0,s=e.returnCiphertext?i:i-i%16;let o=e.end||null;const n=e.maxConnections||4,a=e.initialChunkSize||131072,l=e.chunkSizeIncrement||131072,h=e.maxChunkSize||1048576,c={a:"g",g:1,ssl:api_default.handleForceHttps(e.forceHttps)?2:0};if(this.nodeId?c.n=this.nodeId:Array.isArray(this.downloadId)?(c._querystring={n:this.downloadId[0]},c.n=this.downloadId[1]):c.p=this.downloadId,this.directory)throw Error("Can't download: folder download isn't supported");if(!this.key&&!e.returnCiphertext)throw Error("Can't download: key isn't defined");const u=this.key&&!e.returnCiphertext?megaDecrypt(this.key,{start:s,disableVerification:0!==s||null!==o}):new import_stream3.PassThrough,d=s===i?u:u.pipe(new import_stream_skip.default({skip:i-s})),f=e.handleRetries||t.defaultHandleRetries;return this.api.request(c,((t,e)=>{if(t)return d.emit("error",t);if("string"!=typeof e.g||"http"!==e.g.substr(0,4))return d.emit("error",Error("MEGA servers returned an invalid response, maybe caused by rate limit"));if(0===e.s)return d.end();if(o||(o=e.s-1),i>o)return d.emit("error",Error("You can't download past the end of the file."));function r(t){if(200!==t.status){if(509===t.status){const e=t.headers.get("x-mega-time-left"),r=Error("Bandwidth limit reached: "+e+" seconds until it resets");return r.timeLimit=e,void d.emit("error",r)}d.emit("error",Error("MEGA returned a "+t.status+" status code"))}}function c(t){d.emit("error",t)}let p=0;if(d.on("data",(t=>{p+=t.length,d.emit("progress",{bytesLoaded:p,bytesTotal:e.s})})),1===n){const t=new AbortController;return d.on("close",(()=>{t.abort()})),void this.api.fetch(e.g+"/"+s+"-"+o,{signal:t.signal}).then((t=>{r(t);const e=t.body;if(!e)throw Error("Missing response body");if(e.pipe)t.body.pipe(u);else{if(!e.getReader)throw Error("Single connection streaming not supported by fetch");{const t=e.getReader(),r=({done:e,value:i})=>{if(!e)return u.write(i),t.read().then(r);u.end()};t.read().then(r)}}})).catch(c)}const m={};let y=0,g=0,b=!1,E=s,w=a;d.on("error",(()=>{b=!0})),d.on("close",(()=>{b=!0}));const A=()=>{if(E>o)return b=!0,void(y===g&&u.end());const t=E,i=Math.min(o,t+w-1),s=y++;let n=0;const a=()=>{n++,this.api.fetch(e.g+"/"+t+"-"+i).then((t=>(r(t),t.arrayBuffer()))).then((t=>{const e=Buffer.from(t);m[s]=e,g===s&&_()}),(t=>{f(n,t,(t=>{t?c(t):a()}))}))};a(),E=i+1,w<h&&(w+=l)},_=()=>{let t;for(;;){const e=m[g];if(!e)break;if(t=!u.write(e),delete m[g],g++,t)break}b&&y===g&&u.end(),t?u.once("drain",_):A()};for(let t=0;t<n;t++)A()})),r&&streamToCb(d,r),d}downloadBuffer(t,e){const[r,i]=createPromise(e);return this.download(t,r),i}link(t,e){1===arguments.length&&"function"==typeof t&&(e=t,t={noKey:!1});const[r,i]=createPromise(e);"boolean"==typeof t&&(t={noKey:t});let s=`https://mega.nz/${this.directory?"folder":"file"}/${this.downloadId}`;return!t.noKey&&this.key&&(s+=`#${e64(this.key)}`),!t.noKey&&this.loadedFile&&(s+=`/file/${this.loadedFile}`),r(null,s),i}find(t,e){if(!this.children)throw Error("You can only call .find on directories");if("string"==typeof t){const e=t;t=t=>t.name===e}else if(Array.isArray(t)){const e=t;t=t=>e.includes(t.name)}if("function"!=typeof t)throw Error("Query must be a file matching function, an array of valid file names or a string with a file name");return this.children.reduce(((r,i)=>r||(t(i)?i:i.children&&e?i.find(t,e):null)),null)}filter(t,e){if(!this.children)throw Error("You can only call .filter on directories");if("string"==typeof t){const e=t;t=t=>t.name===e}else if(Array.isArray(t)){const e=t;t=t=>e.includes(t.name)}if("function"!=typeof t)throw Error("Query must be a file matching function, an array of valid file names or a string with a file name");return this.children.reduce(((r,i)=>(t(i)&&r.push(i),i.children&&e?r.concat(i.filter(t,e)):r)),[])}navigate(t){if(!this.children)throw Error("You can only call .navigate on directories");if("string"==typeof t)t=t.split("/");else if(!Array.isArray(t))throw Error("Query must be an array or a string");return t.reduce(((t,e)=>t&&t.children&&t.children.find((t=>t.name===e))),this)}static fromURL(e,r={}){if("object"==typeof e)return new t(e);const i=new URL(e);if("mega.nz"!==i.hostname&&"mega.co.nz"!==i.hostname)throw Error("Invalid URL: wrong hostname");if(!i.hash)throw Error("Invalid URL: no hash");if(null!==i.pathname.match(/\/(file|folder)\//)){const e=i.hash.substr(1).split("/file/"),s=i.pathname.substring(i.pathname.lastIndexOf("/")+1,i.pathname.length+1),o=e[0];if(s&&!o||!s&&o)throw Error("Invalid URL: too few arguments");return new t({downloadId:s,key:o,directory:i.pathname.indexOf("/folder/")>=0,loadedFile:e[1],...r})}{const e=i.hash.split("!");if("#"!==e[0]&&"#F"!==e[0])throw Error("Invalid URL: format not recognized");if(e.length<=1)throw Error("Invalid URL: too few arguments");if(e.length>=("#"===e[0]?4:5))throw Error("Invalid URL: too many arguments");return new t({downloadId:e[1],key:e[2],directory:"#F"===e[0],loadedFile:e[3],...r})}}static unpackAttributes(t){let e=0;for(;e<t.length&&t.readUInt8(e);)e++;if('MEGA{"'===(t=t.slice(0,e).toString()).substr(0,6))try{return JSON.parse(t.substr(4))}catch(t){}}static defaultHandleRetries(t,e,r){t>8?r(e):setTimeout(r,1e3*Math.pow(2,t))}},LABEL_NAMES=["","red","orange","yellow","green","blue","purple","grey"],file_default=File,import_stream4=require("stream"),KEY_CACHE={},MutableFile=class t extends file_default{constructor(t,e){if(super(t),this.storage=e,this.api=e.api,this.nodeId=t.h,this.timestamp=t.ts,this.type=t.t,this.directory=!!this.type,this.directory&&!this.children&&(this.children=[]),t.k){const r=t.k.split("/");let i=e.aes;for(const s of r){const r=s.split(":")[0];if(r===e.user){t.k=s;break}const o=e.shareKeys[r];if(o){t.k=s,i=KEY_CACHE[r],i||(i=KEY_CACHE[r]=new AES(o));break}}this.loadMetadata(i,t)}}loadAttributes(){throw Error("This is not needed for files loaded from logged in sessions")}mkdir(e,r){if(!this.directory)throw Error("node isn't a directory");const[i,s]=createPromise(r);if("string"==typeof e&&(e={name:e}),e.attributes||(e.attributes={}),e.name&&(e.attributes.n=e.name),!e.attributes.n)throw Error("file name is required");if(e.target||(e.target=this),e.key||(e.key=Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(16)))),16!==e.key.length)throw Error("wrong key length, must be 128bit");const o=e.key,n=t.packAttributes(e.attributes);getCipher(o).encryptCBC(n);const a=Buffer.from(o);this.storage.aes.encryptECB(a);const l={a:"p",t:e.target.nodeId?e.target.nodeId:e.target,n:[{h:"xxxxxxxx",t:1,a:e64(n),k:e64(a)}]},h=getShares(this.storage.shareKeys,this);return h.length>0&&(l.cr=makeCryptoRequest(this.storage,[{nodeId:"xxxxxxxx",key:o}],h)),this.api.request(l,((t,e)=>{if(t)return i(t);const r=this.storage._importFile(e.f[0]);this.storage.emit("add",r),i(null,r)})),s}upload(e,r,i){if(!this.directory)throw Error("node is not a directory");2===arguments.length&&"function"==typeof r&&([i,r]=[r,null]);const[s,o]=createPromise(i);if("string"==typeof e&&(e={name:e}),e.attributes||(e.attributes={}),e.name&&(e.attributes.n=e.name),!e.attributes.n)throw Error("File name is required.");if(!("number"==typeof e.size&&e.size>=0||r&&"function"!=typeof r.pipe&&"number"==typeof r.length||e.allowUploadBuffering))throw Error("Specify a file size or set allowUploadBuffering to true");let n;e.target||(e.target=this);let a=formatKey(e.key);a||(a=globalThis.crypto.getRandomValues(new Uint8Array(24))),a instanceof Buffer||(a=Buffer.from(a));const l=e.uploadCiphertext?32:24;if(a.length!==l)throw Error("Wrong key length. Key must be 192bit");e.uploadCiphertext&&(n=a,a=unmergeKeyMac(a).slice(0,24)),e.key=a;const h=[],c=(r,i,o,a)=>{if(r)return d(r);if(!o||0===o.length)return void d(Error("Server returned a invalid response while uploading"));const l=Number(o.toString());if(l<0)return void d(Error("Server returned error "+l+" while uploading"));if(h[i]=o,0!==i||n||(n=a.key),e.thumbnailImage&&!h[1])return;if(e.previewImage&&!h[2])return;if(!h[0])return;const c=t.packAttributes(e.attributes);getCipher(n).encryptCBC(c);const f=Buffer.from(n);this.storage.aes.encryptECB(f);const p={h:e64(h[0]),t:0,a:e64(c),k:e64(f)};1!==h.length&&(p.fa=h.slice(1).map(((t,e)=>e+"*"+e64(t))).filter((t=>t)).join("/"));const m={a:"p",t:e.target.nodeId?e.target.nodeId:e.target,n:[p]},y=getShares(this.storage.shareKeys,this);y.length>0&&(m.cr=makeCryptoRequest(this.storage,[{nodeId:p.h,key:n}],y)),this.api.request(m,((t,e)=>{if(t)return d(t);const r=this.storage._importFile(e.f[0]);this.storage.emit("add",r),u.emit("complete",r),s&&s(null,r)}))};e.thumbnailImage&&this._uploadAttribute(e,e.thumbnailImage,1,c),e.previewImage&&this._uploadAttribute(e,e.previewImage,2,c);const u=this._upload(e,r,0,c);function d(t){u.listenerCount("error")?u.emit("error",t):s(t)}return u.complete=o,u}_upload(t,e,r,i){const s=t.uploadCiphertext?new import_stream4.PassThrough:megaEncrypt(t.key);let o=s,n=t.size;return e&&"function"!=typeof e.pipe&&(n=e.length,o.end(e)),null!=n?(0===n&&s.end(),this._uploadWithSize(o,n,s,r,t,i)):o=detectSize(o,(e=>{this._uploadWithSize(o,e,s,r,t,i)})),e&&"function"==typeof e.pipe&&e.pipe(o),o}_uploadAttribute(t,e,r,i){const s=(e,s)=>{if(e)return i(e);const o=s.length,n=16*Math.ceil(o/16)-o;0!==n&&(s=Buffer.concat([s,Buffer.alloc(n)]));(t.handle?getCipher(t.key):new AES(t.key.slice(0,16))).encryptCBC(s);const a=new import_stream4.PassThrough;a.end(s),this._uploadWithSize(a,s.length,a,r,t,i)};e instanceof Buffer?s(null,e):streamToCb(e,s)}_uploadWithSize(t,e,r,i,s,o){const n=api_default.handleForceHttps(s.forceHttps)?2:0,a=0===i?{a:"u",ssl:n,s:e,ms:0,r:0,e:0,v:2}:{a:"ufa",ssl:n,s:e};s.handle&&(a.h=s.handle);const l=0===i?s.initialChunkSize||131072:e,h=s.chunkSizeIncrement||131072,c=s.maxChunkSize||1048576,u=s.maxConnections||4,d=s.handleRetries||file_default.defaultHandleRetries;let f,p,m,y,g,b=l,E=0,w=!1,A=0,_=0;const k=()=>{y=Math.min(b,e-A),p=Buffer.alloc(y),E++,b<c&&(b+=h),g=0,f&&(f.copy(p),g=Math.min(f.length,y),f=f.length>y?f.slice(y):null),g===y?v():(w=!0,I())},v=()=>{const s=A,n=p;let a=0;const l=()=>{a++,this.api.fetch(m+"/"+(0===i?s:i-1),{method:"POST",body:n,headers:{"content-length":n.length}}).then((t=>{if(200!==t.status)throw Error("MEGA returned a "+t.status+" status code");return t.arrayBuffer()})).then((s=>{_+=n.length,t.emit("progress",{bytesLoaded:C,bytesUploaded:_,bytesTotal:e});const a=Buffer.from(s);a.length>0?(r.end(),process.nextTick((()=>{o(null,i,a,r)}))):A<e&&!w&&k()}),(e=>{d(a,e,(e=>{e?t.emit("error",e):l()}))}))};l(),p=null,A+=y,A<e&&!w&&E<u&&k()};let C=0;const I=()=>{for(;;){const t=r.read();if(null===t){r.once("readable",I);break}if(C+=t.length,t.copy(p,g),g+=t.length,g>=y){w=!1,f=t.slice(t.length-(g-y)),v();break}}};r.on("end",(()=>{e&&C!==e&&t.emit("error",Error("Specified data size does not match: "+e+" !== "+C))})),this.api.request(a,((t,e)=>{if(t)return o(t);m=e.p,k()}))}uploadAttribute(t,e,r){const[i,s]=createPromise(r);if("string"==typeof t&&(t=["thumbnail","preview"].indexOf(t)),0!==t&&1!==t)throw Error("Invalid attribute type");return this._uploadAttribute({key:this.key,handle:this.nodeId},e,t+1,((e,r,s,o)=>{if(e)return i(e);const n={a:"pfa",n:this.nodeId,fa:t+"*"+e64(s)};this.api.request(n,((t,e)=>{if(t)return i(t);i(null,this)}))})),s}delete(t,e){return"function"==typeof t&&(e=t,t=void 0),void 0===t&&(t=this.parent===this.storage.trash),t?this.api.request({a:"d",n:this.nodeId},e):this.moveTo(this.storage.trash,e)}moveTo(t,e){if("string"==typeof t&&(t=this.storage.files[t]),!(t instanceof file_default))throw Error("target must be a folder or a nodeId");const r={a:"m",n:this.nodeId,t:t.nodeId},i=getShares(this.storage.shareKeys,t);return i.length>0&&(r.cr=makeCryptoRequest(this.storage,[this],i)),this.api.request(r,e)}setAttributes(e,r){const[i,s]=createPromise(r);Object.assign(this.attributes,e);const o=t.packAttributes(this.attributes);return getCipher(this.key).encryptCBC(o),this.api.request({a:"a",n:this.nodeId,at:e64(o)},(t=>{this.parseAttributes(this.attributes),i(t)})),s}rename(t,e){return this.setAttributes({n:t},e)}setLabel(t,e){if("string"==typeof t&&(t=LABEL_NAMES.indexOf(t)),"number"!=typeof t||Math.floor(t)!==t||t<0||t>7)throw Error("label must be a integer between 0 and 7 or a valid label name");return this.setAttributes({lbl:t},e)}setFavorite(t,e){return this.setAttributes({fav:t?1:0},e)}link(t,e){1===arguments.length&&"function"==typeof t&&(e=t,t={noKey:!1}),"boolean"==typeof t&&(t={noKey:t}),t||(t={});const r=t.__folderKey;if(this.directory&&!r)return this.shareFolder(t,e);const[i,s]=createPromise(e);return this.api.request({a:"l",n:this.nodeId},((e,s)=>{if(e)return i(e);let o=`https://mega.nz/${r?"folder":"file"}/${s}`;!t.noKey&&this.key&&(o+=`#${e64(r||this.key)}`),i(null,o)})),s}shareFolder(t,e){if(!this.directory)throw Error("node isn't a folder");const r=this.nodeId,i=this.storage.shareKeys[r];if(i)return this.link(Object.assign({__folderKey:i},t),e);let s=formatKey(t.key);s||(s=globalThis.crypto.getRandomValues(new Uint8Array(16))),s instanceof Buffer||(s=Buffer.from(s));const[o,n]=createPromise(e);if(16!==s.length)return o(Error("share key must be 16 byte / 22 characters")),n;this.storage.shareKeys[r]=s;const a=Buffer.from(r+r);this.storage.aes.encryptECB(a);const l={a:"s2",n:r,s:[{u:"EXP",r:0}],ok:e64(this.storage.aes.encryptECB(Buffer.from(s))),ha:e64(a),cr:makeCryptoRequest(this.storage,this)};return this.api.request(l,(e=>{if(e)return o(e);this.link(Object.assign({__folderKey:s},t),o)})),n}unshare(t){return this.directory?this.unshareFolder(t):this.api.request({a:"l",n:this.nodeId,d:1},t)}unshareFolder(t){if(!this.directory)throw Error("node isn't a folder");return delete this.storage.shareKeys[this.nodeId],this.api.request({a:"s2",n:this.nodeId,s:[{u:"EXP",r:""}]},t)}importFile(e,r){const[i,s]=createPromise(r);if(!this.directory)throw Error("importFile can only be called on directories");if("string"==typeof e&&(e=file_default.fromURL(e)),!(e instanceof file_default))throw Error("First argument of importFile should be a File or a URL string");if(!e.key)return i(Error("Can't import files without encryption keys")),s;const o=(e,r)=>{if(e)return i(e);const s=t.packAttributes(r.attributes);getCipher(r.key).encryptCBC(s);const o=Array.isArray(r.downloadId)?r.downloadId[1]:r.downloadId,n={a:"p",t:this.nodeId,n:[{ph:o,t:0,a:e64(s),k:e64(this.storage.aes.encryptECB(r.key))}]};this.api.request(n,((t,e)=>{if(t)return i(t);const r=this.storage._importFile(e.f[0]);this.storage.emit("add",r),i(null,r)}))};return e.attributes?o(null,e):e.loadAttributes(o),s}static packAttributes(t){let e=JSON.stringify(t);e=Buffer.from(`MEGA${e}`);const r=Buffer.alloc(16*Math.ceil(e.length/16));return e.copy(r),r}};function makeCryptoRequest(t,e,r){const i=t.shareKeys;Array.isArray(e)||(e=selfAndChildren(e)),r||(r=e.map((t=>getShares(i,t))).reduce(((t,e)=>t.concat(e))).filter(((t,e,r)=>e===r.indexOf(t))));const s=[r,e.map((t=>t.nodeId)),[]];for(let t=r.length;t--;){const o=new AES(i[r[t]]);for(let r=e.length;r--;){const i=Buffer.from(e[r].key);!i||32!==i.length&&16!==i.length||s[2].push(t,r,e64(o.encryptECB(i)))}}return s}function selfAndChildren(t){return[t].concat((t.children||[]).map(selfAndChildren).reduce(((t,e)=>t.concat(e)),[]))}function getShares(t,e){const r=e.nodeId,i=e.parent,s=[];return t[r]&&s.push(r),i?s.concat(getShares(t,i)):s}var mutable_file_default=MutableFile,Storage=class t extends import_events3.EventEmitter{constructor(t,e){super(),1===arguments.length&&"function"==typeof t&&(e=t,t={});const[r,i]=createPromise(e);this.ready=i,t.keepalive=void 0===t.keepalive||!!t.keepalive,t.autoload=void 0===t.autoload||!!t.autoload,t.autologin=void 0===t.autologin||!!t.autologin,this.api=new api_default(t.keepalive,t),this.files={},this.options=t,this.status="closed",t.autologin?this.login(r):process.nextTick((()=>{r(null,this)}))}login(t){const[e,r]=createPromise(t);if("string"!=typeof this.options.email)return process.nextTick((()=>{e(Error("starting a session without credentials isn't supported"))})),r;const i=()=>{this.status="ready",e(null,this),this.emit("ready",this)},s=t=>{this.api.request({a:"ug"},((e,r)=>{if(e)return t(e);this.name=r.name,this.user=r.u,this.options.autoload?this.reload(!0,(e=>{if(e)return t(e);i()})):i()}))};this.email=this.options.email.toLowerCase();const o=()=>{const t=prepareKey(Buffer.from(this.options.password)),e=new AES(t),r=e64(e.stringhash(Buffer.from(this.email))),i={a:"us",user:this.email,uh:r};a(i,e)},n=t=>{prepareKeyV2(Buffer.from(this.options.password),t,((t,r)=>{if(t)return e(t);const i=new AES(r.slice(0,16)),s=e64(r.slice(16)),o={a:"us",user:this.email,uh:s};a(o,i)}))},a=(t,r)=>{delete this.options.password,this.options.secondFactorCode&&(t.mfa=this.options.secondFactorCode.toString()),this.api.request(t,((t,i)=>{if(t)return e(t);this.key=formatKey(i.k),r.decryptECB(this.key),this.aes=new AES(this.key);const o=formatKey(i.csid),n=cryptoDecodePrivKey(this.aes.decryptECB(formatKey(i.privk)));if(!n)throw Error("invalid credentials");const a=e64(cryptoRsaDecrypt(o,n).slice(0,43));this.api.sid=this.sid=a,this.RSAPrivateKey=n,s(e)}))};return this.api.request({a:"us0",user:this.email},((t,r)=>t?e(t):1===r.v?o():2===r.v?n(r):void e(Error("Account version not supported")))),this.status="connecting",r}reload(t,e){"function"==typeof t&&([t,e]=[e,t]);const[r,i]=createPromise(e);return"connecting"!==this.status||t?(this.mounts=[],this.api.request({a:"f",c:1},((t,e)=>{if(t)return r(t);this.shareKeys=e.ok.reduce(((t,e)=>{const r=e.h,i=this.aes.encryptECB(Buffer.from(r+r));return constantTimeCompare(formatKey(e.ha),i)&&(t[r]=this.aes.decryptECB(formatKey(e.k))),t}),{});for(let t of e.f)if(t=this._importFile(t),void 0!==e.ph&&(t.shareId=e.ph.find((e=>e.h===t.nodeId))?.ph,t.shared=!!t.shareId,t.shared)){t.shareURL=`https://mega.nz/${t.directory?"folder":"file"}/${t.shareId}`;const e=t.directory?this.shareKeys[t.nodeId]:t.key;e&&(t.shareURL+="#"+e64(e))}r(null,this.mounts)})),this.api.on("sc",(t=>{const e={};t.forEach((t=>{if("u"===t.a){const e=this.files[t.n];e&&(e.timestamp=t.ts,e.decryptAttributes(t.at),e.emit("update"),this.emit("update",e))}else"d"===t.a?e[t.n]=!0:"t"===t.a&&t.t.f.forEach((t=>{const r=this.files[t.h];if(r){delete e[t.h];const i=r.parent;if(i.nodeId===t.p)return;i.children.splice(i.children.indexOf(r),1),r.parent=this.files[t.p],r.parent.children.push(r),r.emit("move",i),this.emit("move",r,i)}else this.emit("add",this._importFile(t))}))})),Object.keys(e).forEach((t=>{const e=this.files[t],r=e.parent;r.children.splice(r.children.indexOf(e),1),this.emit("delete",e),e.emit("delete")}))})),i):(this.once("ready",(()=>{this.reload(t,r)})),i)}_importFile(t){if(!this.files[t.h]){const e=this.files[t.h]=new mutable_file_default(t,this);if(t.t===NODE_TYPE_DRIVE&&(this.root=e,e.name="Cloud Drive"),t.t===NODE_TYPE_RUBBISH_BIN&&(this.trash=e,e.name="Rubbish Bin"),t.t===NODE_TYPE_INBOX&&(this.inbox=e,e.name="Inbox"),t.t>1&&this.mounts.push(e),t.p){const r=this.files[t.p];r&&(r.children.push(e),e.parent=r)}}return this.files[t.h]}mkdir(t,e){if("ready"!==this.status)throw Error("storage is not ready");return this.root.mkdir(t,e)}upload(t,e,r){if("ready"!==this.status)throw Error("storage is not ready");return this.root.upload(t,e,r)}find(t,e){if("ready"!==this.status)throw Error("storage is not ready");return this.root.find(t,e)}filter(t,e){if("ready"!==this.status)throw Error("storage is not ready");return this.root.filter(t,e)}navigate(t,e){if("ready"!==this.status)throw Error("storage is not ready");return this.root.navigate(t,e)}close(t){return this.status="closed",this.api.close(),this.api.request({a:"sml"},t)}getAccountInfo(t){const[e,r]=createPromise(t);return this.api.request({a:"uq",strg:1,xfer:1,pro:1},((t,r)=>{t&&e(t);const i={};i.type=r.utype,i.spaceUsed=r.cstrg,i.spaceTotal=r.mstrg,i.downloadBandwidthTotal=r.mxfer||10*Math.pow(1024,5),i.downloadBandwidthUsed=r.caxfer||0,i.sharedBandwidthUsed=r.csxfer||0,i.sharedBandwidthLimit=r.srvratio,e(null,i)})),r}toJSON(){return{key:e64(this.key),sid:this.sid,name:this.name,user:this.user,options:this.options}}static fromJSON(e){const r=new t(Object.assign(e.options,{autoload:!1,autologin:!1}));return r.key=d64(e.key),r.aes=new AES(r.key),r.api.sid=r.sid=e.sid,r.name=e.name,r.user=e.user,r}decryptRsaKey(t){return cryptoRsaDecrypt(t,this.RSAPrivateKey)}},NODE_TYPE_DRIVE=2,NODE_TYPE_INBOX=3,NODE_TYPE_RUBBISH_BIN=4,storage_default=Storage;function mega(t,e){return new storage_default(t,e)}mega.Storage=storage_default,mega.File=file_default,mega.MutableFile=mutable_file_default,mega.API=api_default,mega.file=file_default.fromURL,mega.encrypt=megaEncrypt,mega.decrypt=megaDecrypt,mega.verify=megaVerify,module.exports=mega;
//# sourceMappingURL=/sm/4a9400efe3ebae457a2dc23449215b88338dbc81d4032416392765d2700b74db.map