/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@filen/sdk@0.3.12/dist/browser/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
import API from"./api";import Crypto from"./crypto";import utils from"./utils";import{environment,ANONYMOUS_SDK_CONFIG,REGISTER_AUTH_VERSION}from"./constants";import os from"os";import FS from"./fs";import appendStream from"./streams/append";import{streamDecodeBase64,streamEncodeBase64}from"./streams/base64";import cryptoUtils from"./crypto/utils";import Cloud from"./cloud";import pathModule from"path";import Chats from"./chats";import Notes from"./notes";import Contacts from"./contacts";import User from"./user";import Socket from"./socket";import TypedEventEmitter from"./events";import axios from"axios";import Lock from"./lock";export class FilenSDK{config;_api;_crypto;_fs;_cloud;_notes;_chats;_contacts;_user;socket=new Socket;workers;currentWorkerWorkIndex=0;events;axiosInstance;hmacKey=null;_locks={driveWrite:new Lock({sdk:this,resource:"drive-write"}),notesWrite:new Lock({sdk:this,resource:"notes-write"}),chatsWrite:new Lock({sdk:this,resource:"chats-write"}),intensive:new Lock({sdk:this,resource:"intensive"}),auth:new Lock({sdk:this,resource:"auth"})};constructor(t,e,r){t=t?{...ANONYMOUS_SDK_CONFIG,...t}:ANONYMOUS_SDK_CONFIG,this.config=t,this.workers=e||null,this.events=new TypedEventEmitter,this.axiosInstance=r||axios.create(),this._crypto=new Crypto(this),this._api=new API(this),this._cloud=new Cloud(this),this._fs=new FS({sdk:this,connectToSocket:t.connectToSocket}),this._notes=new Notes(this),this._chats=new Chats(this),this._contacts=new Contacts(this),this._user=new User(this)}init(t){t=t?{...ANONYMOUS_SDK_CONFIG,...t}:ANONYMOUS_SDK_CONFIG,this.config=t,this._crypto=new Crypto(this),this._api=new API(this),this._cloud=new Cloud(this),this._fs=new FS({sdk:this,connectToSocket:t.connectToSocket}),this._notes=new Notes(this),this._chats=new Chats(this),this._contacts=new Contacts(this),this._user=new User(this)}setSDKWorkers(t){this.workers=t}getBaseWorker(){return{crypto:{encrypt:this.crypto().encrypt(),decrypt:this.crypto().decrypt(),utils:cryptoUtils},api:{v3:{file:{upload:{chunk:{buffer:{fetch:t=>this._api.v3().file().upload().chunk().buffer(t)}}},download:{chunk:{buffer:{fetch:t=>this._api.v3().file().download().chunk().buffer(t)}}}}}}}}getWorker(){const t={crypto:{encrypt:this.crypto().encrypt(),decrypt:this.crypto().decrypt(),utils:cryptoUtils},api:{v3:{file:{upload:{chunk:{buffer:{fetch:t=>this._api.v3().file().upload().chunk().buffer(t)}}},download:{chunk:{buffer:{fetch:t=>this._api.v3().file().download().chunk().buffer(t)}}}}}}};if(!this.workers||0===this.workers.length)return t;(void 0===this.currentWorkerWorkIndex||this.currentWorkerWorkIndex<0||this.currentWorkerWorkIndex>=this.workers.length)&&(this.currentWorkerWorkIndex=0);const e=this.workers[this.currentWorkerWorkIndex];return this.currentWorkerWorkIndex=(this.currentWorkerWorkIndex+1)%this.workers.length,e||t}isLoggedIn(){return void 0!==this.config.apiKey&&void 0!==this.config.masterKeys&&void 0!==this.config.publicKey&&void 0!==this.config.privateKey&&void 0!==this.config.baseFolderUUID&&void 0!==this.config.authVersion&&void 0!==this.config.userId&&this.config.apiKey.length>0&&this.config.masterKeys.length>0&&this.config.publicKey.length>0&&this.config.privateKey.length>0&&this.config.baseFolderUUID.length>0&&this.config.userId>0&&[1,2,3].includes(this.config.authVersion)}async generateHMACKey(){if(this.hmacKey)return this.hmacKey;if(!this.config.privateKey||"anonymous"===this.config.privateKey)throw new Error("No private key set for HMAC key generation.");return this.hmacKey=await this.getWorker().crypto.utils.generatePrivateKeyHMAC(this.config.privateKey),this.hmacKey}async _updateKeyPair({apiKey:t,publicKey:e,privateKey:r,masterKeys:i}){await this._locks.auth.acquire();try{const s=await this.getWorker().crypto.encrypt.metadata({metadata:r,key:i.at(-1)});await this._api.v3().user().keyPair().update({publicKey:e,encryptedPrivateKey:s,apiKey:t})}finally{await this._locks.auth.release().catch((()=>{}))}}async _setKeyPair({apiKey:t,publicKey:e,privateKey:r,masterKeys:i}){await this._locks.auth.acquire();try{const s=await this.getWorker().crypto.encrypt.metadata({metadata:r,key:i.at(-1)});await this._api.v3().user().keyPair().set({publicKey:e,encryptedPrivateKey:s,apiKey:t})}finally{await this._locks.auth.release().catch((()=>{}))}}async __updateKeyPair({apiKey:t,masterKeys:e}){await this._locks.auth.acquire();try{const r=await this._api.v3().user().keyPair().info({apiKey:t});if("string"==typeof r.publicKey&&"string"==typeof r.privateKey&&r.publicKey.length>16&&r.privateKey.length>16){let i=null;for(const t of e)try{const e=await this.getWorker().crypto.decrypt.metadata({metadata:r.privateKey,key:t});if("string"==typeof e&&e.length>16){i=e;break}}catch{continue}if(!i)throw new Error("Could not decrypt private key.");return await this._updateKeyPair({apiKey:t,publicKey:r.publicKey,privateKey:i,masterKeys:e}),{publicKey:r.publicKey,privateKey:i}}const i=await this.getWorker().crypto.utils.generateKeyPair();return await this._setKeyPair({apiKey:t,publicKey:i.publicKey,privateKey:i.privateKey,masterKeys:e}),{publicKey:i.publicKey,privateKey:i.privateKey}}finally{await this._locks.auth.release().catch((()=>{}))}}async _updateKeys({apiKey:t,masterKeys:e,authVersion:r}){await this._locks.auth.acquire();try{if(1===r||2===r){const r=e.at(-1);if(!r||r.length<16)throw new Error("Invalid current master key.");const i=await this.getWorker().crypto.encrypt.metadata({metadata:e.join("|"),key:r}),s=await this._api.v3().user().masterKeys({encryptedMasterKeys:i,apiKey:t}),a=[...e];for(const t of e)try{const e=await this.getWorker().crypto.decrypt.metadata({metadata:s.keys,key:t});if("string"==typeof e&&e.length>16&&e.includes("|")){for(const t of e.split("|"))t.length>0&&!a.includes(t)&&a.push(t);break}}catch{continue}if(0===a.length)throw new Error("Could not decrypt master keys.");const{publicKey:o,privateKey:n}=await this.__updateKeyPair({apiKey:t,masterKeys:a});return{masterKeys:a,publicKey:o,privateKey:n}}if(3===r){if(1!==e.length||!e[0])throw new Error("Invalid master keys array.");const r=e[0];if(!r||64!==r.length)throw new Error("Invalid DEK encryption key.");let i=(await this._api.v3().user().getDEK({apiKey:t})).dek;i?i=await this.getWorker().crypto.decrypt.metadata({metadata:i,key:r}):(i=(await this.getWorker().crypto.utils.generateRandomBytes(32)).toString("hex"),await this._api.v3().user().setDEK({apiKey:t,encryptedDEK:await this.getWorker().crypto.encrypt.metadata({metadata:i,key:r})}));const{publicKey:s,privateKey:a}=await this.__updateKeyPair({apiKey:t,masterKeys:[i]});return{masterKeys:[i],publicKey:s,privateKey:a}}throw new Error("Invalid authVersion.")}finally{await this._locks.auth.release().catch((()=>{}))}}async login({email:t,password:e,twoFactorCode:r}){const i=t||(this.config.email?this.config.email:""),s=e||(this.config.password?this.config.password:""),a=r||(this.config.twoFactorCode?this.config.twoFactorCode:"XXXXXX");if(0===i.length||0===s.length||0===a.length)throw new Error("Empty email, password or twoFactorCode");const o=await this._api.v3().auth().info({email:i}),n=o.authVersion,c=await this.getWorker().crypto.utils.generatePasswordAndMasterKeyBasedOnAuthVersion({rawPassword:s,authVersion:n,salt:o.salt}),h=await this._api.v3().login({email:i,password:c.derivedPassword,twoFactorCode:a,authVersion:n});this.init({...this.config,email:i,password:"redacted",twoFactorCode:"redacted",apiKey:h.apiKey,authVersion:n}),await this._locks.auth.acquire();try{const[t,e,r]=await Promise.all([this._api.v3().user().info({apiKey:h.apiKey}),this._api.v3().user().baseFolder({apiKey:h.apiKey}),this._updateKeys({apiKey:h.apiKey,masterKeys:[c.derivedMasterKeys],authVersion:n})]);this.init({...this.config,email:i,password:"redacted",twoFactorCode:"redacted",masterKeys:r.masterKeys,apiKey:h.apiKey,publicKey:r.publicKey,privateKey:r.privateKey,authVersion:n,baseFolderUUID:e.uuid,userId:t.id})}finally{await this._locks.auth.release().catch((()=>{}))}}async register({email:t,password:e,refId:r,affId:i}){let s="",a={derivedMasterKeys:"",derivedPassword:""};if(3===REGISTER_AUTH_VERSION?(s=await this.getWorker().crypto.utils.generateRandomHexString(256),a=await this.getWorker().crypto.utils.generatePasswordAndMasterKeyBasedOnAuthVersion({rawPassword:e,salt:s,authVersion:REGISTER_AUTH_VERSION})):(s=await this.getWorker().crypto.utils.generateRandomHexString(128),a=await this.getWorker().crypto.utils.generatePasswordAndMasterKeyBasedOnAuthVersion({rawPassword:e,salt:s,authVersion:REGISTER_AUTH_VERSION})),0===s.length||0===a.derivedMasterKeys.length||0===a.derivedPassword.length)throw new Error("Failed to generate salt or derived password");await this.api(3).register({email:t,password:a.derivedPassword,salt:s,authVersion:REGISTER_AUTH_VERSION,..."string"==typeof r&&r.length>0&&r.length<128?{refId:r}:{},..."string"==typeof i&&i.length>0&&i.length<128?{affId:i}:{}})}logout(){this.init(ANONYMOUS_SDK_CONFIG)}api(t){if(3===t)return this._api.v3();throw new Error(`API version ${t} does not exist`)}crypto(){return this._crypto}fs(){if(!this.isLoggedIn())throw new Error("Not authenticated, please call login() first");return this._fs}cloud(){if(!this.isLoggedIn())throw new Error("Not authenticated, please call login() first");return this._cloud}notes(){if(!this.isLoggedIn())throw new Error("Not authenticated, please call login() first");return this._notes}chats(){if(!this.isLoggedIn())throw new Error("Not authenticated, please call login() first");return this._chats}contacts(){if(!this.isLoggedIn())throw new Error("Not authenticated, please call login() first");return this._contacts}user(){if(!this.isLoggedIn())throw new Error("Not authenticated, please call login() first");return this._user}async clearTemporaryDirectory(){if("node"!==environment)return;const t=utils.normalizePath(pathModule.join(this.config.tmpPath?this.config.tmpPath:os.tmpdir(),"filen-sdk"));await utils.clearTempDirectory({tmpDir:t})}utils={...utils,crypto:cryptoUtils,streams:{append:appendStream,decodeBase64:streamDecodeBase64,encodeBase64:streamEncodeBase64}}}export default FilenSDK;export*from"./types";export*from"./constants";export*from"./api/errors";export*from"./cloud/signals";export{ChunkedUploadWriter}from"./cloud/streams";
//# sourceMappingURL=/sm/3ed40ffc46d3d56cc4062118dda3b575ecf96bf4a473f1629553767241ea314f.map