diff --git a/package.json b/package.json index 1a0c7fbd..772d1ac7 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "koodo-reader", "main": "main.js", - "version": "2.4.5", + "version": "2.4.6", "description": "Koodo Reader is a cross-platform ebook reader", "author": { "name": "App by Troye", diff --git a/src/assets/lib/kookit-extra-browser.min.js b/src/assets/lib/kookit-extra-browser.min.js index ede57818..5f4524f7 100644 --- a/src/assets/lib/kookit-extra-browser.min.js +++ b/src/assets/lib/kookit-extra-browser.min.js @@ -1 +1 @@ -import e from"axios";import{Storage as a}from"megajs";import{Buffer as t}from"buffer";import{S3Client as o,ListObjectsV2Command as i,DeleteObjectCommand as n,PutObjectCommand as r,GetObjectCommand as l}from"@aws-sdk/client-s3";import s from"crypto-js";import{AuthType as d,createClient as c}from"webdav/dist/web/index.js";import{SSE as u}from"sse.js";function m(e,a,t,o){return new(t||(t=Promise))((function(i,n){function r(e){try{s(o.next(e))}catch(e){n(e)}}function l(e){try{s(o.throw(e))}catch(e){n(e)}}function s(e){var a;e.done?i(e.value):(a=e.value,a instanceof t?a:new t((function(e){e(a)}))).then(r,l)}s((o=o.apply(e,a||[])).next())}))}const p=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,h=["books","notes","bookmarks","plugins","words"],g=e=>{const a=atob(e),t=a.length,o=new Uint8Array(t);for(let e=0;e{let a="";const t=new Uint8Array(e),o=t.byteLength;for(let e=0;ee.toString(16).padStart(2,"0"))).join("")}))}function N(e){const a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],t=(e,a)=>e>>>a|e<<32-a,o=(e,a,t)=>e&a^~e&t,i=(e,a,t)=>e&a^e&t^a&t,n=e=>t(e,2)^t(e,13)^t(e,22),r=e=>t(e,6)^t(e,11)^t(e,25),l=e=>t(e,7)^t(e,18)^e>>>3,s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],d=8*e.length,c=(960-(8*e.length+1)%512)%512,u=e.length+Math.ceil((c+1)/8)+8,m=new Uint8Array(u);m.set(e),m[e.length]=128;new DataView(m.buffer,m.byteLength-8).setBigUint64(0,BigInt(d),!1);for(let e=0;e>>10)+c[e-7]+l(c[e-15])+c[e-16]>>>0);let[u,h,g,f,y,N,v,b]=s;for(let e=0;e<64;e++){const t=b+r(y)+o(y,N,v)+a[e]+c[e]>>>0,l=n(u)+i(u,h,g)>>>0;b=v,v=N,N=y,y=f+t>>>0,f=g,g=h,h=u,u=t+l>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+f>>>0,s[4]=s[4]+y>>>0,s[5]=s[5]+N>>>0,s[6]=s[6]+v>>>0,s[7]=s[7]+b>>>0}var p;const h=new ArrayBuffer(32),g=new DataView(h);return s.forEach(((e,a)=>{g.setUint32(4*a,e,!1)})),h}const v={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let a="",t=0;const o=this._stringToUtf8Bytes(e),i=o.length;for(;t>2,s=(3&e)<<4|n>>4,d=(15&n)<<2|r>>6,c=63&r;a+=this._chars.charAt(l),a+=this._chars.charAt(s),a+=t-2>=i?"=":this._chars.charAt(d),a+=t-1>=i?"=":this._chars.charAt(c)}return a},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const a=[];let t=0;const o=e.length;for(;t>4,s=(15&i)<<4|n>>2,d=(3&n)<<6|r;a.push(l),-1!==n&&a.push(s),-1!==r&&a.push(d)}return this._utf8BytesToString(a)},_stringToUtf8Bytes(e){const a=[];for(let t=0;t>6),a.push(128|63&o);else if(55296==(64512&o)&&t+1>18),a.push(128|e>>12&63),a.push(128|e>>6&63),a.push(128|63&e)}else a.push(239,191,189),t--}else a.push(224|o>>12),a.push(128|o>>6&63),a.push(128|63&o)}return a},_utf8BytesToString(e){let a="",t=0;for(;t65535){const t=e-65536;a+=String.fromCharCode(55296|t>>10),a+=String.fromCharCode(56320|1023&t)}else a+=String.fromCharCode(e)}else a+="�"}else a+="�"}return a},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}},b=e=>{const a=(e,a)=>{const t=(65535&e)+(65535&a);return(e>>16)+(a>>16)+(t>>16)<<16|65535&t},t=(e,t,o,i,n,r)=>{return a((l=a(a(t,e),a(i,r)))<<(s=n)|l>>>32-s,o);var l,s},o=(e,a,o,i,n,r,l)=>t(a&o|~a&i,e,a,n,r,l),i=(e,a,o,i,n,r,l)=>t(a&i|o&~i,e,a,n,r,l),n=(e,a,o,i,n,r,l)=>t(a^o^i,e,a,n,r,l),r=(e,a,o,i,n,r,l)=>t(o^(a|~i),e,a,n,r,l),l=e.length,s=1+(l+8>>6),d=new Array(16*s).fill(0);for(let a=0;a>2]|=e[a]<>2]|=128<{let a="";for(let t=0;t<4;t++)a+=("0"+(e>>8*t&255).toString(16)).slice(-2);return a})).join("")};class k{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return m(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((a,t)=>{if(this.hasFailedTasks)return void a(void 0);const o=()=>m(this,void 0,void 0,(function*(){if(this.hasFailedTasks)return this.completedTasks++,void a(void 0);try{this.runningTasks++;const t=yield e();return this.completedTasks++,a(t),t}catch(e){throw this.completedTasks++,t(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0;){const e=this.queue.shift();e&&e()}else if(this.queue.length>0&&this.runningTasks"application/json"===e?"json":e.startsWith("image/")?e.split("/")[1]:"application/zip"===e?"zip":"application/epub+zip"===e?"epub":"text/plain"===e?"txt":"application/pdf"===e?"pdf":"application/x-mobipocket-ebook"===e?"mobi":"application/vnd.amazon.ebook"===e?"azw3":"application/x-cbz"===e?"cbz":"application/x-cbr"===e?"cbr":"application/x-cbt"===e?"cbt":"application/x-cb7"===e?"cb7":"application/x-fictionbook+xml"===e?"fb2":"text/html"===e?"html":"text/css"===e?"css":"application/javascript"===e?"js":"application/xml"===e?"xml":"application/xhtml+xml"===e?"xhtml":"application/oebps-package+xml"===e?"opf":"application/x-dtbncx+xml"===e?"ncx":"audio/mpeg"===e?"mp3":"audio/wav"===e?"wav":"audio/ogg"===e?"ogg":"video/mp4"===e?"mp4":"video/webm"===e?"webm":"video/x-msvideo"===e?"avi":"video/x-ms-wmv"===e?"wmv":"video/x-flv"===e?"flv":"application/x-mpegURL"===e?"m3u8":"video/MP2T"===e?"ts":"video/3gpp"===e?"3gp":"video/3gpp2"===e?"3g2":"application/x-sqlite3"===e?"db":"",databaseList:h,configList:["themeColors","readingTime","appVersion","cloudSyncTime","lastSyncTime","recentBooks","koreaderBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","aiModelConfig","readingStats","noteTags","recordLocation","thirdpartyToken","sortedShelfList","kindleDeviceList","thirdpartyToken","opdsCatalogs","opdsCatalogList"],copyArrayBuffer:e=>{var a=new ArrayBuffer(e.byteLength);return new Uint8Array(a).set(new Uint8Array(e)),a},base64ToArrayBuffer:g,arrayBufferToBase64:f,generateSHA256Hash:y,simpleEncrypt:function(e,a){if(!e||!a)return"";const t=N((new TextEncoder).encode(a)),o=Array.from(new Uint8Array(t)),i=(new TextEncoder).encode(e),n=new Uint8Array(i.length);for(let e=0;e{const a=new Set(["anthropic","zhipu","doubao","moonshot","deepseek","minimax","minimaxi"]),t=new Set(["qwen","hunyuan","siliconflow","siliconflowglobal","infini"]),o=new Set(["sensenova","openai"]),i=new Set(["ollama"]);return e&&"custom"!==e?a.has(e)?{thinking:{type:"disabled"}}:t.has(e)?{enable_thinking:!1}:o.has(e)?{reasoning_effort:"none"}:i.has(e)?{think:!1}:{}:{}},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","sina.cn","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","live.cn","msn.cn","msn.com","aliyun.com","sohu.com","yandex.com","naver.com","mail.ru","yahoo.co.jp","139.com","189.com","yandex.ru","189.cn"],Base64:v};const E={cloudUrl:"https://cloud.koodoreader.com",cloudCNUrl:"https://cloud.koodoreader.cn",testUrl:"https://cloudtestv2.960960.xyz",devUrl:"http://192.168.28.159:8000"},C={callbackUrl:"https://web.koodoreader.com/",cnCallbackUrl:"https://web.koodoreader.cn/",dropboxClientId:"vnc67byrssocvy1",yandexClientId:"e5305b62f53844b1994f77a840fd0a37",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",duboxClientId:"kc0Ls6xLZugGgLLVhZ8yhUU1cRkRoKNU",yiyiwuClientId:"100197197",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",appleClientId:"com.koodoreader.auth",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"},T={google:{clientId:C.googleClientId,scopes:["openid email profile"],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{prompt:"consent",scope:"openid email profile"}},microsoft:{clientId:C.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:C.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:""}},github:{clientId:C.githubClientId,scopes:["user:email"],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"user:email"}},apple:{clientId:C.appleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:""}}},w=["backgroundColor","textColor","fontSize","margin","letterSpacing","paraSpacing","scale","brightness","fontFamily","subFontFamily","lineHeight","textAlign","textOrientation","convertChinese","selectAction","fullTranslationMode","readerMode","pdfReaderMode","isBold","isIndent","isSliding","isUnderline","isShadow","isItalic","isInvert","isBionic","isHyphenation","isOrphanWidow","isKeepPDFBackground","isAllowScript","isStartFromEven"];var A={CloudMode:"production",CloudConfig:E,ConvertLangMap:{en:"English",zhCN:"Chinese",zhTW:"Chinese",zhMO:"Chinese",tr:"Turkish",ar:"Arabic",ro:"Romanian",pl:"Polish",cs:"Czech",ja:"Japanese",ta:"Tamil",uk:"Ukrainian",sl:"Slovenian",bo:"Tibetan",id:"Indonesian",hy:"Armenian",el:"Greek",hu:"Hungarian",hi:"Hindi",bg:"Bulgarian",nl:"Dutch",it:"Italian",bn:"Bengali",tl:"Tagalog",sv:"Swedish",ga:"Irish",ko:"Korean",de:"German",ru:"Russian",es:"Spanish",fr:"French",fa:"Persian",ptBR:"Portuguese",th:"Thai",sr:"Serbian",am:"Amharic",da:"Danish",fi:"Finnish",ie:"Interlingue",pt:"Portuguese",vi:"Vietnamese"},ContentRegxConfig:[{label:"Default parser",value:"Default parser",subtitle:"Suitable for most txt files",regex:""},{label:"Chinese novel parser",value:"Chinese novel parser",subtitle:"Suitable for most Chinese novels, eg. 第一章,第2回",regex:"^\\s*(第[0-9一二三四五六七八九十百千万零壹贰叁肆伍陆柒捌玖拾佰仟]+[章回])\\s*"},{label:"English novel parser",value:"English novel parser",subtitle:"Suitable for most English novels, eg. Chapter 1, Part II",regex:"^\\s*(Chapter|Part|Book|CHAPTER|PART|BOOK)\\s*"},{label:"Number parser",value:"Number parser",subtitle:"Suitable for novels with number chapter titles, eg. 1, 2, 3",regex:"^\\s*([0-9]+[\\s.、::·\\-—]+|[一二三四五六七八九十百千万零]+[\\s.、::·\\-—]+).+"}],StyleKeys:w,ThirdpartyConfig:C,LoginAuthRequest:T,LoginDiscovery:{microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},facebook:{authorizationEndpoint:"https://www.facebook.com/v12.0/dialog/oauth",tokenEndpoint:"https://graph.facebook.com/v12.0/oauth/access_token"},github:{authorizationEndpoint:"https://github.com/login/oauth/authorize",tokenEndpoint:"https://github.com/login/oauth/access_token"},apple:{authorizationEndpoint:"https://appleid.apple.com/auth/authorize",tokenEndpoint:"https://appleid.apple.com/auth/token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:{dropbox:{clientId:C.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{token_access_type:"offline"}},yandex:{clientId:C.yandexClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{response_type:"code",force_confirm:"true"}},boxnet:{clientId:C.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:C.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{grant_type:"authorization_code"}},dubox:{clientId:C.duboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{response_type:"code",scope:"basic,netdisk",device_id:"119827642",qrcode:"1"}},yiyiwu:{clientId:C.yiyiwuClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{response_type:"code"}},adrive:{clientId:C.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:C.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:C.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.file",access_type:"offline"}},microsoft_exp:{clientId:C.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"files.readwrite.all offline_access"}},google_exp:{clientId:C.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive",access_type:"offline"}}},DriveDiscovery:{dropbox:{authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",tokenEndpoint:"https://www.dropbox.com/oauth2/token"},yandex:{authorizationEndpoint:"https://oauth.yandex.com/authorize",tokenEndpoint:"https://oauth.yandex.com/token"},boxnet:{authorizationEndpoint:"https://account.box.com/api/oauth2/authorize",tokenEndpoint:"https://api.box.com/oauth2/token"},pcloud:{authorizationEndpoint:"https://my.pcloud.com/oauth2/authorize",tokenEndpoint:"https://api.pcloud.com/oauth2_token"},dubox:{authorizationEndpoint:"https://openapi.baidu.com/oauth/2.0/authorize",tokenEndpoint:"https://openapi.baidu.com/oauth/2.0/token"},yiyiwu:{authorizationEndpoint:"https://passportapi.115.com/open/authorize",tokenEndpoint:"https://passportapi.115.com/open/authorize"},adrive:{authorizationEndpoint:"https://openapi.alipan.com/oauth/authorize",tokenEndpoint:"https://openapi.alipan.com/oauth/token"},microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},microsoft_exp:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google_exp:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}},AiProviderList:[{id:"custom",name:"Custom model",defaultEndpoint:"",modelsEndpoint:"",isCNAvailable:!0},{id:"openai",name:"OpenAI",defaultEndpoint:"https://api.openai.com/v1",modelsEndpoint:"https://api.openai.com/v1/models"},{id:"anthropic",name:"Anthropic",defaultEndpoint:"https://api.anthropic.com/v1",modelsEndpoint:"https://api.anthropic.com/v1/models"},{id:"google",name:"Google Gemini",defaultEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai",modelsEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai/models"},{id:"deepseek",name:"DeepSeek",defaultEndpoint:"https://api.deepseek.com/v1",modelsEndpoint:"https://api.deepseek.com/v1/models",isCNAvailable:!0},{id:"mistral",name:"Mistral AI",defaultEndpoint:"https://api.mistral.ai/v1",modelsEndpoint:"https://api.mistral.ai/v1/models"},{id:"cohere",name:"Cohere",defaultEndpoint:"https://api.cohere.ai/compatibility/v1",modelsEndpoint:"https://api.cohere.ai/compatibility/v1/models"},{id:"groq",name:"Groq",defaultEndpoint:"https://api.groq.com/openai/v1",modelsEndpoint:"https://api.groq.com/openai/v1/models"},{id:"together",name:"Together AI",defaultEndpoint:"https://api.together.xyz/v1",modelsEndpoint:"https://api.together.xyz/v1/models"},{id:"fireworks",name:"Fireworks AI",defaultEndpoint:"https://api.fireworks.ai/inference/v1",modelsEndpoint:"https://api.fireworks.ai/inference/v1/models"},{id:"perplexity",name:"Perplexity",defaultEndpoint:"https://api.perplexity.ai",modelsEndpoint:"https://api.perplexity.ai/v1/models"},{id:"openrouter",name:"OpenRouter",defaultEndpoint:"https://openrouter.ai/api/v1",modelsEndpoint:"https://openrouter.ai/api/v1/models"},{id:"ai21",name:"AI21 Labs",defaultEndpoint:"https://api.ai21.com/studio/v1",modelsEndpoint:"https://api.ai21.com/studio/v1/models"},{id:"xai",name:"xAI (Grok)",defaultEndpoint:"https://api.x.ai/v1",modelsEndpoint:"https://api.x.ai/v1/models"},{id:"sambanova",name:"SambaNova",defaultEndpoint:"https://api.sambanova.ai/v1",modelsEndpoint:"https://api.sambanova.ai/v1/models"},{id:"cerebras",name:"Cerebras",defaultEndpoint:"https://api.cerebras.ai/v1",modelsEndpoint:"https://api.cerebras.ai/v1/models"},{id:"hyperbolic",name:"Hyperbolic",defaultEndpoint:"https://api.hyperbolic.xyz/v1",modelsEndpoint:"https://api.hyperbolic.xyz/v1/models"},{id:"novita",name:"Novita AI",defaultEndpoint:"https://api.novita.ai/openai",modelsEndpoint:"https://api.novita.ai/openai/models"},{id:"lepton",name:"Lepton AI",defaultEndpoint:"https://llm.lepton.run/api/v1",modelsEndpoint:"https://llm.lepton.run/api/v1/models"},{id:"deepinfra",name:"DeepInfra",defaultEndpoint:"https://api.deepinfra.com/v1/openai",modelsEndpoint:"https://api.deepinfra.com/v1/openai/models"},{id:"replicate",name:"Replicate",defaultEndpoint:"https://api.replicate.com/v1",modelsEndpoint:"https://api.replicate.com/v1/models"},{id:"zhipu",name:"Zhipu AI (智谱)",defaultEndpoint:"https://open.bigmodel.cn/api/paas/v4",modelsEndpoint:"https://open.bigmodel.cn/api/paas/v4/models",isCNAvailable:!0},{id:"qwen",name:"Alibaba Qwen (通义千问)",defaultEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1",modelsEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/models",isCNAvailable:!0},{id:"moonshot",name:"Moonshot (月之暗面)",defaultEndpoint:"https://api.moonshot.cn/v1",modelsEndpoint:"https://api.moonshot.cn/v1/models",isCNAvailable:!0},{id:"baidu",name:"Baidu ERNIE (文心一言)",defaultEndpoint:"https://qianfan.baidubce.com/v2",modelsEndpoint:"https://qianfan.baidubce.com/v2/models",isCNAvailable:!0},{id:"doubao",name:"Volcengine Doubao (豆包)",defaultEndpoint:"https://ark.cn-beijing.volces.com/api/v3",modelsEndpoint:"https://ark.cn-beijing.volces.com/api/v3/models",isCNAvailable:!0},{id:"spark",name:"iFlytek Spark (讯飞星火)",defaultEndpoint:"https://spark-api-open.xf-yun.com/v1",modelsEndpoint:"https://spark-api-open.xf-yun.com/v1/models",isCNAvailable:!0},{id:"hunyuan",name:"Tencent Hunyuan (腾讯混元)",defaultEndpoint:"https://api.hunyuan.cloud.tencent.com/v1",modelsEndpoint:"https://api.hunyuan.cloud.tencent.com/v1/models",isCNAvailable:!0},{id:"minimaxi",name:"MiniMax (国内版)",defaultEndpoint:"https://api.minimaxi.com/v1",modelsEndpoint:"https://api.minimaxi.com/v1/models",isCNAvailable:!0},{id:"minimax",name:"MiniMax (国际版)",defaultEndpoint:"https://api.minimax.io/v1",modelsEndpoint:"https://api.minimax.io/v1/models"},{id:"baichuan",name:"Baichuan (百川)",defaultEndpoint:"https://api.baichuan-ai.com/v1",modelsEndpoint:"https://api.baichuan-ai.com/v1/models",isCNAvailable:!0},{id:"stepfun",name:"StepFun (阶跃星辰)",defaultEndpoint:"https://api.stepfun.com/v1",modelsEndpoint:"https://api.stepfun.com/v1/models",isCNAvailable:!0},{id:"lingyi",name:"Lingyiwanwu (零一万物)",defaultEndpoint:"https://api.lingyiwanwu.com/v1",modelsEndpoint:"https://api.lingyiwanwu.com/v1/models",isCNAvailable:!0},{id:"siliconflow",name:"SiliconFlow (硅基流动)",defaultEndpoint:"https://api.siliconflow.cn/v1",modelsEndpoint:"https://api.siliconflow.cn/v1/models",isCNAvailable:!0},{id:"siliconflowglobal",name:"SiliconFlow (国际版)",defaultEndpoint:"https://api.siliconflow.com/v1",modelsEndpoint:"https://api.siliconflow.com/v1/models"},{id:"sensenova",name:"SenseNova (日日新)",defaultEndpoint:"https://token.sensenova.cn/v1",modelsEndpoint:"https://token.sensenova.cn/v1/models",isCNAvailable:!0},{id:"infini",name:"Infini AI (无问芯穹)",defaultEndpoint:"https://cloud.infini-ai.com/maas/v1",modelsEndpoint:"https://cloud.infini-ai.com/maas/v1/models",isCNAvailable:!0},{id:"ollama",name:"Ollama (Local)",defaultEndpoint:"http://localhost:11434/v1",modelsEndpoint:"http://localhost:11434/v1/models",isCNAvailable:!0},{id:"lmstudio",name:"LM Studio (Local)",defaultEndpoint:"http://localhost:1234/v1",modelsEndpoint:"http://localhost:1234/v1/models",isCNAvailable:!0},{id:"vllm",name:"vLLM (Local)",defaultEndpoint:"http://localhost:8000/v1",modelsEndpoint:"http://localhost:8000/v1/models",isCNAvailable:!0},{id:"azure",name:"Azure OpenAI",defaultEndpoint:"",modelsEndpoint:""},{id:"aws_bedrock",name:"AWS Bedrock",defaultEndpoint:"",modelsEndpoint:""}],DefaultPrompts:{aiTranslate:"You are a professional translator. Translate the following text from {from} to {to}. Only return the translated text, no explanations.\n\nText: {text}",aiDict:"You are a professional dictionary assistant. Analyze the word or phrase: {word}\nProvide a comprehensive explanation including pronunciation, definitions, example sentences, and usage notes using {to} as the target language. ",aiAssistance:"You are a helpful reading assistant. The user is reading a book. Here is the context:\n{text}\n\nAnswer the user's question concisely and helpfully, and reply with the same language."},SpeechList:[{label:"English",code:"en",example:"To be, or not to be, that is the question."},{label:"Simplified Chinese",code:"zh",example:"千里之行,始于足下。"},{label:"Japanese",code:"ja",example:"猿も木から落ちる。"},{label:"Korean",code:"ko",example:"가는 날이 장날이다."},{label:"French",code:"fr",example:"Liberté, égalité, fraternité."},{label:"German",code:"de",example:"Der Weg ist das Ziel."},{label:"Spanish",code:"es",example:"La vida es un sueño."},{label:"Italian",code:"it",example:"Dolce far niente."},{label:"Russian",code:"ru",example:"Век живи, век учись."},{label:"Portuguese",code:"pt",example:"Saudade é um sentimento profundo."},{label:"Hindi",code:"hi",example:"सपने वो नहीं जो हम सोते वक्त देखते हैं।"},{label:"Afrikaans",code:"af",example:"Die lewe is 'n geskenk."},{label:"Amharic",code:"am",example:"ዕውቀት ብርሃን ነው።"},{label:"Arabic",code:"ar",example:"العلم نور والجهل ظلام."},{label:"Azerbaijani",code:"az",example:"Elm işıqdır, cəhalət zülmət."},{label:"Bulgarian",code:"bg",example:"Знанието е сила."},{label:"Bengali",code:"bn",example:"জ্ঞানই শক্তি।"},{label:"Bosnian",code:"bs",example:"Znanje je moć."},{label:"Catalan",code:"ca",example:"El saber no ocupa lloc."},{label:"Czech",code:"cs",example:"Bez práce nejsou koláče."},{label:"Welsh",code:"cy",example:"Nid aur popeth melyn."},{label:"Danish",code:"da",example:"Lykken er ikke et sted, men en retning."},{label:"Greek",code:"el",example:"Η γνώση είναι δύναμη."},{label:"Estonian",code:"et",example:"Teadmine on jõud."},{label:"Basque",code:"eu",example:"Jakitea boterea da."},{label:"Persian",code:"fa",example:"دانش قدرت است."},{label:"Finnish",code:"fi",example:"Tieto on valtaa."},{label:"Filipino",code:"fil",example:"Ang kaalaman ay kapangyarihan."},{label:"Irish",code:"ga",example:"Is fearr Gaeilge briste ná Béarla cliste."},{label:"Galician",code:"gl",example:"O saber non ocupa lugar."},{label:"Gujarati",code:"gu",example:"જ્ઞાન શક્તિ છે."},{label:"Hebrew",code:"he",example:"ידע הוא כוח."},{label:"Croatian",code:"hr",example:"Znanje je moć."},{label:"Hungarian",code:"hu",example:"A tudás hatalom."},{label:"Armenian",code:"hy",example:"Գիտելիքը ուժ է."},{label:"Indonesian",code:"id",example:"Pengetahuan adalah kekuatan."},{label:"Icelandic",code:"is",example:"Þekking er máttur."},{label:"Inuktitut",code:"iu",example:"ᐃᓕᓐᓂᐊᕐᓂᖅ ᐱᒻᒪᕆᐅᕗᖅ."},{label:"Javanese",code:"jv",example:"Ilmu iku kelakone kanthi laku."},{label:"Georgian",code:"ka",example:"ცოდნა ძალაა."},{label:"Kazakh",code:"kk",example:"Білім — күш."},{label:"Khmer",code:"km",example:"ចំណេះដឹងគឺជាអំណាច។"},{label:"Kannada",code:"kn",example:"ಜ್ಞಾನವೇ ಶಕ್ತಿ."},{label:"Lao",code:"lo",example:"ຄວາມຮູ້ຄືພະລັງ."},{label:"Lithuanian",code:"lt",example:"Žinios yra jėga."},{label:"Latvian",code:"lv",example:"Zināšanas ir spēks."},{label:"Macedonian",code:"mk",example:"Знаењето е моќ."},{label:"Malayalam",code:"ml",example:"അറിവ് ശക്തിയാണ്."},{label:"Mongolian",code:"mn",example:"Мэдлэг бол хүч."},{label:"Marathi",code:"mr",example:"ज्ञान हीच शक्ती आहे."},{label:"Malay",code:"ms",example:"Ilmu itu cahaya."},{label:"Maltese",code:"mt",example:"L-għarfien huwa l-poter."},{label:"Burmese",code:"my",example:"ဗဟုသုတသည် အားဖြစ်သည်။"},{label:"Norwegian",code:"nb",example:"Kunnskap er makt."},{label:"Nepali",code:"ne",example:"ज्ञान नै शक्ति हो।"},{label:"Dutch",code:"nl",example:"Kennis is macht."},{label:"Odia",code:"or",example:"ଜ୍ଞାନ ହିଁ ଶକ୍ତି।"},{label:"Punjabi",code:"pa",example:"ਗਿਆਨ ਹੀ ਸ਼ਕਤੀ ਹੈ।"},{label:"Polish",code:"pl",example:"Wiedza to potęga."},{label:"Pashto",code:"ps",example:"د پوهې ډیوه روښانه ده."},{label:"Romanian",code:"ro",example:"Cartea este o comoară."},{label:"Sinhala",code:"si",example:"දැනුම බලයකි."},{label:"Slovak",code:"sk",example:"Vedomosti sú sila."},{label:"Slovenian",code:"sl",example:"Znanje je moč."},{label:"Somali",code:"so",example:"Aqoontu waa iftiin."},{label:"Albanian",code:"sq",example:"Dija është fuqi."},{label:"Serbian",code:"sr",example:"Знање је моћ."},{label:"Sundanese",code:"su",example:"Élmu éta cahaya."},{label:"Swedish",code:"sv",example:"Kunskap är makt."},{label:"Swahili",code:"sw",example:"Maarifa ni nguvu."},{label:"Tamil",code:"ta",example:"அறிவே ஆற்றல்."},{label:"Telugu",code:"te",example:"జ్ఞానమే శక్తి."},{label:"Thai",code:"th",example:"ความรู้คือพลัง."},{label:"Turkish",code:"tr",example:"Bilgi güçtür."},{label:"Ukrainian",code:"uk",example:"Знання — сила."},{label:"Urdu",code:"ur",example:"علم ہی طاقت ہے۔"},{label:"Uzbek",code:"uz",example:"Bilim – kuch."},{label:"Vietnamese",code:"vi",example:"Học vấn là sức mạnh."},{label:"Wu Chinese",code:"wuu",example:"学问是力量。"},{label:"Cantonese",code:"yue",example:"知識就係力量。"},{label:"Zulu",code:"zu",example:"Ulwazi lungamandla."}],HighlightStyleTypes:[{value:"background",label:"Highlight background"},{value:"underline",label:"Underline"},{value:"strikethrough",label:"Strikethrough"},{value:"wavy",label:"Wavy underline"}],HighlightPresetColors:{background:["#F3C9C9","#FEF3CD","#CEFACD","#CDE9FA"],underline:["#FF0000","#60A5FA","#FF9900","#2EFF2E"],strikethrough:["#FF0000","#60A5FA","#FF9900","#2EFF2E"],wavy:["#FF0000","#60A5FA","#FF9900","#2EFF2E"]},PresetThemeList:[{key:"yellow",textColor:"rgba(89, 68, 41,1)",backgroundColor:"rgba(233, 216, 188,1)",title:"羊皮"},{key:"green",textColor:"rgba(54, 80, 62,1)",backgroundColor:"rgba(197, 231, 207,1)",title:"护眼"},{key:"light",textColor:"rgba(0,0,0,1)",backgroundColor:"rgba(255,255,255,1)",title:"白天"},{key:"night",textColor:"rgba(255,255,255,1)",backgroundColor:"rgba(44,47,49,1)",title:"黑夜"},{key:"sepia",textColor:"rgba(93, 64, 55,1)",backgroundColor:"rgba(245, 235, 220,1)",title:"古卷"},{key:"blue",textColor:"rgba(28, 52, 84,1)",backgroundColor:"rgba(230, 240, 250,1)",title:"晨雾"},{key:"purple",textColor:"rgba(68, 42, 84,1)",backgroundColor:"rgba(240, 230, 250,1)",title:"紫萝"},{key:"pink",textColor:"rgba(84, 42, 68,1)",backgroundColor:"rgba(250, 235, 245,1)",title:"樱花"},{key:"brown",textColor:"rgba(74, 54, 42,1)",backgroundColor:"rgba(240, 230, 215,1)",title:"木纹"},{key:"gray",textColor:"rgba(64, 64, 64,1)",backgroundColor:"rgba(240, 240, 240,1)",title:"素雅"},{key:"darkgreen",textColor:"rgba(200, 220, 200,1)",backgroundColor:"rgba(25, 35, 30,1)",title:"深林"},{key:"darkblue",textColor:"rgba(200, 210, 230,1)",backgroundColor:"rgba(20, 30, 45,1)",title:"深海"},{key:"coral",textColor:"rgba(84, 50, 42,1)",backgroundColor:"rgba(255, 235, 230,1)",title:"珊瑚"},{key:"mint",textColor:"rgba(42, 74, 64,1)",backgroundColor:"rgba(230, 250, 245,1)",title:"薄荷"},{key:"lavender",textColor:"rgba(54, 42, 74,1)",backgroundColor:"rgba(245, 240, 255,1)",title:"薰衣"},{key:"cream",textColor:"rgba(74, 64, 42,1)",backgroundColor:"rgba(255, 250, 240,1)",title:"奶油"},{key:"darkbrown",textColor:"rgba(230, 215, 200,1)",backgroundColor:"rgba(35, 25, 20,1)",title:"深棕"},{key:"olive",textColor:"rgba(64, 74, 42,1)",backgroundColor:"rgba(240, 245, 230,1)",title:"橄榄"},{key:"rose",textColor:"rgba(84, 42, 54,1)",backgroundColor:"rgba(255, 240, 245,1)",title:"玫瑰"},{key:"slate",textColor:"rgba(54, 64, 74,1)",backgroundColor:"rgba(235, 240, 245,1)",title:"石板"}],OfficialVoiceList:[{name:"af_alloy",gender:"female",displayName:"Alloy",locale:"en-US",language:"English (US)"},{name:"af_aoede",gender:"female",displayName:"Aoede",locale:"en-US",language:"English (US)"},{name:"af_bella",gender:"female",displayName:"Bella",locale:"en-US",language:"English (US)"},{name:"af_heart",gender:"female",displayName:"Heart",locale:"en-US",language:"English (US)"},{name:"af_jessica",gender:"female",displayName:"Jessica",locale:"en-US",language:"English (US)"},{name:"af_kore",gender:"female",displayName:"Kore",locale:"en-US",language:"English (US)"},{name:"af_nicole",gender:"female",displayName:"Nicole",locale:"en-US",language:"English (US)"},{name:"af_nova",gender:"female",displayName:"Nova",locale:"en-US",language:"English (US)"},{name:"af_river",gender:"female",displayName:"River",locale:"en-US",language:"English (US)"},{name:"af_sarah",gender:"female",displayName:"Sarah",locale:"en-US",language:"English (US)"},{name:"af_sky",gender:"female",displayName:"Sky",locale:"en-US",language:"English (US)"},{name:"am_adam",gender:"male",displayName:"Adam",locale:"en-US",language:"English (US)"},{name:"am_echo",gender:"male",displayName:"Echo",locale:"en-US",language:"English (US)"},{name:"am_eric",gender:"male",displayName:"Eric",locale:"en-US",language:"English (US)"},{name:"am_fenrir",gender:"male",displayName:"Fenrir",locale:"en-US",language:"English (US)"},{name:"am_liam",gender:"male",displayName:"Liam",locale:"en-US",language:"English (US)"},{name:"am_michael",gender:"male",displayName:"Michael",locale:"en-US",language:"English (US)"},{name:"am_onyx",gender:"male",displayName:"Onyx",locale:"en-US",language:"English (US)"},{name:"am_puck",gender:"male",displayName:"Puck",locale:"en-US",language:"English (US)"},{name:"am_santa",gender:"male",displayName:"Santa",locale:"en-US",language:"English (US)"},{name:"bf_alice",gender:"female",displayName:"Alice",locale:"en-GB",language:"English (UK)"},{name:"bf_emma",gender:"female",displayName:"Emma",locale:"en-GB",language:"English (UK)"},{name:"bf_isabella",gender:"female",displayName:"Isabella",locale:"en-GB",language:"English (UK)"},{name:"bf_lily",gender:"female",displayName:"Lily",locale:"en-GB",language:"English (UK)"},{name:"bm_daniel",gender:"male",displayName:"Daniel",locale:"en-GB",language:"English (UK)"},{name:"bm_fable",gender:"male",displayName:"Fable",locale:"en-GB",language:"English (UK)"},{name:"bm_george",gender:"male",displayName:"George",locale:"en-GB",language:"English (UK)"},{name:"bm_lewis",gender:"male",displayName:"Lewis",locale:"en-GB",language:"English (UK)"},{name:"ef_dora",gender:"female",displayName:"Dora",locale:"es-ES",language:"Español"},{name:"em_alex",gender:"male",displayName:"Alex",locale:"es-ES",language:"Español"},{name:"em_santa",gender:"male",displayName:"Santa",locale:"es-ES",language:"Español"},{name:"ff_siwis",gender:"female",displayName:"Siwis",locale:"fr-FR",language:"Français"},{name:"hf_alpha",gender:"female",displayName:"Alpha",locale:"hi-IN",language:"हिन्दी"},{name:"hf_beta",gender:"female",displayName:"Beta",locale:"hi-IN",language:"हिन्दी"},{name:"hm_omega",gender:"male",displayName:"Omega",locale:"hi-IN",language:"हिन्दी"},{name:"hm_psi",gender:"male",displayName:"Psi",locale:"hi-IN",language:"हिन्दी"},{name:"if_sara",gender:"female",displayName:"Sara",locale:"it-IT",language:"Italiano"},{name:"im_nicola",gender:"male",displayName:"Nicola",locale:"it-IT",language:"Italiano"},{name:"jf_alpha",gender:"female",displayName:"Alpha",locale:"ja-JP",language:"日本語"},{name:"jf_gongitsune",gender:"female",displayName:"Gongitsune",locale:"ja-JP",language:"日本語"},{name:"jf_nezumi",gender:"female",displayName:"Nezumi",locale:"ja-JP",language:"日本語"},{name:"jf_tebukuro",gender:"female",displayName:"Tebukuro",locale:"ja-JP",language:"日本語"},{name:"jm_kumo",gender:"male",displayName:"Kumo",locale:"ja-JP",language:"日本語"},{name:"pf_dora",gender:"female",displayName:"Dora",locale:"pt-BR",language:"Português (Brasil)"},{name:"pm_alex",gender:"male",displayName:"Alex",locale:"pt-BR",language:"Português (Brasil)"},{name:"pm_santa",gender:"male",displayName:"Santa",locale:"pt-BR",language:"Português (Brasil)"},{name:"zf_xiaoxiao",gender:"female",displayName:"Xiaoxiao",locale:"zh-CN",language:"中文"},{name:"zm_yunxi",gender:"male",displayName:"Yunxi",locale:"zh-CN",language:"中文"},{name:"zf_xiaoyi",gender:"female",displayName:"Xiaoyi",locale:"zh-CN",language:"中文"},{name:"zm_yunyang",gender:"male",displayName:"Yunyang",locale:"zh-CN",language:"中文"},{name:"zm_yunxia",gender:"male",displayName:"Yunxia",locale:"zh-CN",language:"中文"},{name:"zm_yunjian",gender:"male",displayName:"Yunjian",locale:"zh-CN",language:"中文"},{name:"zf_xiaoni",gender:"female",displayName:"Xiaoni 陕西",locale:"zh-CN",language:"中文"},{name:"zf_xiaobei",gender:"female",displayName:"Xiaobei 辽宁",locale:"zh-CN",language:"中文"}],AzureTTSVoiceList:[{name:"de-DE-AmalaNeural",gender:"female",displayName:"Amala",locale:"de-DE"},{name:"de-DE-BerndNeural",gender:"male",displayName:"Bernd",locale:"de-DE"},{name:"de-DE-ConradNeural",gender:"male",displayName:"Conrad",locale:"de-DE"},{name:"de-DE-KatjaNeural",gender:"female",displayName:"Katja",locale:"de-DE"},{name:"en-GB-LibbyNeural",gender:"female",displayName:"Libby",locale:"en-GB"},{name:"en-GB-RyanNeural",gender:"male",displayName:"Ryan",locale:"en-GB"},{name:"en-GB-SoniaNeural",gender:"female",displayName:"Sonia",locale:"en-GB"},{name:"en-US-AmberNeural",gender:"female",displayName:"Amber",locale:"en-US"},{name:"en-US-AriaNeural",gender:"female",displayName:"Aria",locale:"en-US"},{name:"en-US-ChristopherNeural",gender:"male",displayName:"Christopher",locale:"en-US"},{name:"en-US-DavisNeural",gender:"male",displayName:"Davis",locale:"en-US"},{name:"en-US-EricNeural",gender:"male",displayName:"Eric",locale:"en-US"},{name:"en-US-GuyNeural",gender:"male",displayName:"Guy",locale:"en-US"},{name:"en-US-JaneNeural",gender:"female",displayName:"Jane",locale:"en-US"},{name:"en-US-JennyNeural",gender:"female",displayName:"Jenny",locale:"en-US"},{name:"en-US-MichelleNeural",gender:"female",displayName:"Michelle",locale:"en-US"},{name:"en-US-SaraNeural",gender:"female",displayName:"Sara",locale:"en-US"},{name:"es-ES-AbrilNeural",gender:"female",displayName:"Abril",locale:"es-ES"},{name:"es-ES-AlvaroNeural",gender:"male",displayName:"Álvaro",locale:"es-ES"},{name:"es-ES-ArnauNeural",gender:"male",displayName:"Arnau",locale:"es-ES"},{name:"es-ES-ElviraNeural",gender:"female",displayName:"Elvira",locale:"es-ES"},{name:"fr-FR-DeniseNeural",gender:"female",displayName:"Denise",locale:"fr-FR"},{name:"fr-FR-HenriNeural",gender:"male",displayName:"Henri",locale:"fr-FR"},{name:"it-IT-BenignoNeural",gender:"male",displayName:"Benigno",locale:"it-IT"},{name:"it-IT-DiegoNeural",gender:"male",displayName:"Diego",locale:"it-IT"},{name:"it-IT-ElsaNeural",gender:"female",displayName:"Elsa",locale:"it-IT"},{name:"it-IT-IsabellaNeural",gender:"female",displayName:"Isabella",locale:"it-IT"},{name:"ja-JP-KeitaNeural",gender:"male",displayName:"圭太",locale:"ja-JP"},{name:"ja-JP-NanamiNeural",gender:"female",displayName:"七海",locale:"ja-JP"},{name:"ko-KR-InJoonNeural",gender:"male",displayName:"인준",locale:"ko-KR"},{name:"ko-KR-SoonBokNeural",gender:"female",displayName:"순복",locale:"ko-KR"},{name:"ko-KR-SunHiNeural",gender:"female",displayName:"선히",locale:"ko-KR"},{name:"pt-BR-AntonioNeural",gender:"male",displayName:"Antônio",locale:"pt-BR"},{name:"pt-BR-FranciscaNeural",gender:"female",displayName:"Francisca",locale:"pt-BR"},{name:"pt-PT-DuarteNeural",gender:"male",displayName:"Duarte",locale:"pt-PT"},{name:"pt-PT-RaquelNeural",gender:"female",displayName:"Raquel",locale:"pt-PT"},{name:"ru-RU-DariyaNeural",gender:"female",displayName:"Дария",locale:"ru-RU"},{name:"ru-RU-DmitryNeural",gender:"male",displayName:"Дмитрий",locale:"ru-RU"},{name:"ru-RU-SvetlanaNeural",gender:"female",displayName:"Светлана",locale:"ru-RU"},{name:"yue-CN-XiaoMinNeural",gender:"female",displayName:"晓敏",locale:"yue-CN"},{name:"yue-CN-YunSongNeural",gender:"male",displayName:"云松",locale:"yue-CN"},{name:"zh-CN-XiaoxiaoNeural",gender:"female",displayName:"晓晓",locale:"zh-CN"},{name:"zh-CN-YunxiNeural",gender:"male",displayName:"云希",locale:"zh-CN"},{name:"zh-HK-HiuMaanNeural",gender:"female",displayName:"曉曼",locale:"zh-HK"},{name:"zh-HK-WanLungNeural",gender:"male",displayName:"雲龍",locale:"zh-HK"},{name:"zh-TW-HsiaoChenNeural",gender:"female",displayName:"曉臻",locale:"zh-TW"},{name:"zh-TW-YunJheNeural",gender:"male",displayName:"雲哲",locale:"zh-TW"},{name:"af-ZA-AdriNeural",gender:"female",displayName:"Adri",locale:"af-ZA"},{name:"af-ZA-WillemNeural",gender:"male",displayName:"Willem",locale:"af-ZA"},{name:"sq-AL-AnilaNeural",gender:"female",displayName:"Anila",locale:"sq-AL"},{name:"sq-AL-IlirNeural",gender:"male",displayName:"Ilir",locale:"sq-AL"},{name:"am-ET-AmehaNeural",gender:"male",displayName:"አምሀ",locale:"am-ET"},{name:"am-ET-MekdesNeural",gender:"female",displayName:"መቅደስ",locale:"am-ET"},{name:"ar-DZ-AminaNeural",gender:"female",displayName:"أمينة",locale:"ar-DZ"},{name:"ar-DZ-IsmaelNeural",gender:"male",displayName:"إسماعيل",locale:"ar-DZ"},{name:"ar-BH-AliNeural",gender:"male",displayName:"علي",locale:"ar-BH"},{name:"ar-BH-LailaNeural",gender:"female",displayName:"ليلى",locale:"ar-BH"},{name:"ar-EG-SalmaNeural",gender:"female",displayName:"سلمى",locale:"ar-EG"},{name:"ar-EG-ShakirNeural",gender:"male",displayName:"شاكر",locale:"ar-EG"},{name:"ar-IQ-BasselNeural",gender:"male",displayName:"باسل",locale:"ar-IQ"},{name:"ar-IQ-RanaNeural",gender:"female",displayName:"رنا",locale:"ar-IQ"},{name:"ar-JO-SanaNeural",gender:"female",displayName:"سناء",locale:"ar-JO"},{name:"ar-JO-TaimNeural",gender:"male",displayName:"تيم",locale:"ar-JO"},{name:"ar-KW-FahedNeural",gender:"male",displayName:"فهد",locale:"ar-KW"},{name:"ar-KW-NouraNeural",gender:"female",displayName:"نورا",locale:"ar-KW"},{name:"ar-LB-LaylaNeural",gender:"female",displayName:"ليلى",locale:"ar-LB"},{name:"ar-LB-RamiNeural",gender:"male",displayName:"رامي",locale:"ar-LB"},{name:"ar-LY-ImanNeural",gender:"female",displayName:"إيمان",locale:"ar-LY"},{name:"ar-LY-OmarNeural",gender:"male",displayName:"أحمد",locale:"ar-LY"},{name:"ar-MA-JamalNeural",gender:"male",displayName:"جمال",locale:"ar-MA"},{name:"ar-MA-MounaNeural",gender:"female",displayName:"منى",locale:"ar-MA"},{name:"ar-OM-AbdullahNeural",gender:"male",displayName:"عبدالله",locale:"ar-OM"},{name:"ar-OM-AyshaNeural",gender:"female",displayName:"عائشة",locale:"ar-OM"},{name:"ar-QA-AmalNeural",gender:"female",displayName:"أمل",locale:"ar-QA"},{name:"ar-QA-MoazNeural",gender:"male",displayName:"معاذ",locale:"ar-QA"},{name:"ar-SA-HamedNeural",gender:"male",displayName:"حامد",locale:"ar-SA"},{name:"ar-SA-ZariyahNeural",gender:"female",displayName:"زارية",locale:"ar-SA"},{name:"ar-SY-AmanyNeural",gender:"female",displayName:"أماني",locale:"ar-SY"},{name:"ar-SY-LaithNeural",gender:"male",displayName:"ليث",locale:"ar-SY"},{name:"ar-TN-HediNeural",gender:"male",displayName:"هادي",locale:"ar-TN"},{name:"ar-TN-ReemNeural",gender:"female",displayName:"ريم",locale:"ar-TN"},{name:"ar-AE-FatimaNeural",gender:"female",displayName:"فاطمة",locale:"ar-AE"},{name:"ar-AE-HamdanNeural",gender:"male",displayName:"حمدان",locale:"ar-AE"},{name:"ar-YE-MaryamNeural",gender:"female",displayName:"مريم",locale:"ar-YE"},{name:"ar-YE-SalehNeural",gender:"male",displayName:"صالح",locale:"ar-YE"},{name:"az-AZ-BabekNeural",gender:"male",displayName:"Babək",locale:"az-AZ"},{name:"az-AZ-BanuNeural",gender:"female",displayName:"Banu",locale:"az-AZ"},{name:"bn-BD-NabanitaNeural",gender:"female",displayName:"নবনীতা",locale:"bn-BD"},{name:"bn-BD-PradeepNeural",gender:"male",displayName:"প্রদ্বীপ",locale:"bn-BD"},{name:"bn-IN-BashkarNeural",gender:"male",displayName:"ভাস্কর",locale:"bn-IN"},{name:"bn-IN-TanishaaNeural",gender:"female",displayName:"তানিশা",locale:"bn-IN"},{name:"bs-BA-VesnaNeural",gender:"female",displayName:"Vesna",locale:"bs-BA"},{name:"bs-BA-GoranNeural",gender:"male",displayName:"Goran",locale:"bs-BA"},{name:"bg-BG-BorislavNeural",gender:"male",displayName:"Борислав",locale:"bg-BG"},{name:"bg-BG-KalinaNeural",gender:"female",displayName:"Калина",locale:"bg-BG"},{name:"my-MM-NilarNeural",gender:"female",displayName:"နီလာ",locale:"my-MM"},{name:"my-MM-ThihaNeural",gender:"male",displayName:"သီဟ",locale:"my-MM"},{name:"ca-ES-EnricNeural",gender:"male",displayName:"Enric",locale:"ca-ES"},{name:"ca-ES-JoanaNeural",gender:"female",displayName:"Joana",locale:"ca-ES"},{name:"zh-HK-HiuGaaiNeural",gender:"female",displayName:"曉佳",locale:"zh-HK"},{name:"zh-CN-XiaoyiNeural",gender:"female",displayName:"晓伊",locale:"zh-CN"},{name:"zh-CN-YunjianNeural",gender:"male",displayName:"云健",locale:"zh-CN"},{name:"zh-CN-YunxiaNeural",gender:"male",displayName:"云夏",locale:"zh-CN"},{name:"zh-CN-YunyangNeural",gender:"male",displayName:"云扬",locale:"zh-CN"},{name:"zh-CN-liaoning-XiaobeiNeural",gender:"female",displayName:"晓北 辽宁",locale:"zh-CN"},{name:"zh-CN-shaanxi-XiaoniNeural",gender:"female",displayName:"晓妮 陕西",locale:"zh-CN"},{name:"zh-TW-HsiaoYuNeural",gender:"female",displayName:"曉雨",locale:"zh-TW"},{name:"hr-HR-GabrijelaNeural",gender:"female",displayName:"Gabrijela",locale:"hr-HR"},{name:"hr-HR-SreckoNeural",gender:"male",displayName:"Srećko",locale:"hr-HR"},{name:"cs-CZ-AntoninNeural",gender:"male",displayName:"Antonín",locale:"cs-CZ"},{name:"cs-CZ-VlastaNeural",gender:"female",displayName:"Vlasta",locale:"cs-CZ"},{name:"da-DK-ChristelNeural",gender:"female",displayName:"Christel",locale:"da-DK"},{name:"da-DK-JeppeNeural",gender:"male",displayName:"Jeppe",locale:"da-DK"},{name:"nl-BE-ArnaudNeural",gender:"male",displayName:"Arnaud",locale:"nl-BE"},{name:"nl-BE-DenaNeural",gender:"female",displayName:"Dena",locale:"nl-BE"},{name:"nl-NL-ColetteNeural",gender:"female",displayName:"Colette",locale:"nl-NL"},{name:"nl-NL-FennaNeural",gender:"female",displayName:"Fenna",locale:"nl-NL"},{name:"nl-NL-MaartenNeural",gender:"male",displayName:"Maarten",locale:"nl-NL"},{name:"en-AU-WilliamMultilingualNeural",gender:"male",displayName:"William Multilingual",locale:"en-AU"},{name:"en-AU-NatashaNeural",gender:"female",displayName:"Natasha",locale:"en-AU"},{name:"en-CA-ClaraNeural",gender:"female",displayName:"Clara",locale:"en-CA"},{name:"en-CA-LiamNeural",gender:"male",displayName:"Liam",locale:"en-CA"},{name:"en-HK-YanNeural",gender:"female",displayName:"Yan",locale:"en-HK"},{name:"en-HK-SamNeural",gender:"male",displayName:"Sam",locale:"en-HK"},{name:"en-IN-NeerjaNeural",gender:"female",displayName:"Neerja",locale:"en-IN"},{name:"en-IN-PrabhatNeural",gender:"male",displayName:"Prabhat",locale:"en-IN"},{name:"en-IE-ConnorNeural",gender:"male",displayName:"Connor",locale:"en-IE"},{name:"en-IE-EmilyNeural",gender:"female",displayName:"Emily",locale:"en-IE"},{name:"en-KE-AsiliaNeural",gender:"female",displayName:"Asilia",locale:"en-KE"},{name:"en-KE-ChilembaNeural",gender:"male",displayName:"Chilemba",locale:"en-KE"},{name:"en-NZ-MitchellNeural",gender:"male",displayName:"Mitchell",locale:"en-NZ"},{name:"en-NZ-MollyNeural",gender:"female",displayName:"Molly",locale:"en-NZ"},{name:"en-NG-AbeoNeural",gender:"male",displayName:"Abeo",locale:"en-NG"},{name:"en-NG-EzinneNeural",gender:"female",displayName:"Ezinne",locale:"en-NG"},{name:"en-PH-JamesNeural",gender:"male",displayName:"James",locale:"en-PH"},{name:"en-PH-RosaNeural",gender:"female",displayName:"Rosa",locale:"en-PH"},{name:"en-US-AvaNeural",gender:"female",displayName:"Ava",locale:"en-US"},{name:"en-US-AndrewNeural",gender:"male",displayName:"Andrew",locale:"en-US"},{name:"en-US-EmmaNeural",gender:"female",displayName:"Emma",locale:"en-US"},{name:"en-US-BrianNeural",gender:"male",displayName:"Brian",locale:"en-US"},{name:"en-SG-LunaNeural",gender:"female",displayName:"Luna",locale:"en-SG"},{name:"en-SG-WayneNeural",gender:"male",displayName:"Wayne",locale:"en-SG"},{name:"en-ZA-LeahNeural",gender:"female",displayName:"Leah",locale:"en-ZA"},{name:"en-ZA-LukeNeural",gender:"male",displayName:"Luke",locale:"en-ZA"},{name:"en-TZ-ElimuNeural",gender:"male",displayName:"Elimu",locale:"en-TZ"},{name:"en-TZ-ImaniNeural",gender:"female",displayName:"Imani",locale:"en-TZ"},{name:"en-GB-MaisieNeural",gender:"female",displayName:"Maisie",locale:"en-GB"},{name:"en-GB-ThomasNeural",gender:"male",displayName:"Thomas",locale:"en-GB"},{name:"en-US-AnaNeural",gender:"female",displayName:"Ana",locale:"en-US"},{name:"en-US-AndrewMultilingualNeural",gender:"male",displayName:"Andrew Multilingual",locale:"en-US"},{name:"en-US-AvaMultilingualNeural",gender:"female",displayName:"Ava Multilingual",locale:"en-US"},{name:"en-US-BrianMultilingualNeural",gender:"male",displayName:"Brian Multilingual",locale:"en-US"},{name:"en-US-EmmaMultilingualNeural",gender:"female",displayName:"Emma Multilingual",locale:"en-US"},{name:"en-US-RogerNeural",gender:"male",displayName:"Roger",locale:"en-US"},{name:"en-US-SteffanNeural",gender:"male",displayName:"Steffan",locale:"en-US"},{name:"et-EE-AnuNeural",gender:"female",displayName:"Anu",locale:"et-EE"},{name:"et-EE-KertNeural",gender:"male",displayName:"Kert",locale:"et-EE"},{name:"fil-PH-AngeloNeural",gender:"male",displayName:"Angelo",locale:"fil-PH"},{name:"fil-PH-BlessicaNeural",gender:"female",displayName:"Blessica",locale:"fil-PH"},{name:"fi-FI-HarriNeural",gender:"male",displayName:"Harri",locale:"fi-FI"},{name:"fi-FI-NooraNeural",gender:"female",displayName:"Noora",locale:"fi-FI"},{name:"fr-BE-CharlineNeural",gender:"female",displayName:"Charline",locale:"fr-BE"},{name:"fr-BE-GerardNeural",gender:"male",displayName:"Gerard",locale:"fr-BE"},{name:"fr-CA-ThierryNeural",gender:"male",displayName:"Thierry",locale:"fr-CA"},{name:"fr-CA-AntoineNeural",gender:"male",displayName:"Antoine",locale:"fr-CA"},{name:"fr-CA-JeanNeural",gender:"male",displayName:"Jean",locale:"fr-CA"},{name:"fr-CA-SylvieNeural",gender:"female",displayName:"Sylvie",locale:"fr-CA"},{name:"fr-FR-VivienneMultilingualNeural",gender:"female",displayName:"Vivienne Multilingue",locale:"fr-FR"},{name:"fr-FR-RemyMultilingualNeural",gender:"male",displayName:"Rémy Multilingue",locale:"fr-FR"},{name:"fr-FR-EloiseNeural",gender:"female",displayName:"Eloise",locale:"fr-FR"},{name:"fr-CH-ArianeNeural",gender:"female",displayName:"Ariane",locale:"fr-CH"},{name:"fr-CH-FabriceNeural",gender:"male",displayName:"Fabrice",locale:"fr-CH"},{name:"gl-ES-RoiNeural",gender:"male",displayName:"Roi",locale:"gl-ES"},{name:"gl-ES-SabelaNeural",gender:"female",displayName:"Sabela",locale:"gl-ES"},{name:"ka-GE-EkaNeural",gender:"female",displayName:"ეკა",locale:"ka-GE"},{name:"ka-GE-GiorgiNeural",gender:"male",displayName:"გიორგი",locale:"ka-GE"},{name:"de-AT-IngridNeural",gender:"female",displayName:"Ingrid",locale:"de-AT"},{name:"de-AT-JonasNeural",gender:"male",displayName:"Jonas",locale:"de-AT"},{name:"de-DE-SeraphinaMultilingualNeural",gender:"female",displayName:"Seraphine Mehrsprachig",locale:"de-DE"},{name:"de-DE-FlorianMultilingualNeural",gender:"male",displayName:"Florian Mehrsprachig",locale:"de-DE"},{name:"de-DE-KillianNeural",gender:"male",displayName:"Killian",locale:"de-DE"},{name:"de-CH-JanNeural",gender:"male",displayName:"Jan",locale:"de-CH"},{name:"de-CH-LeniNeural",gender:"female",displayName:"Leni",locale:"de-CH"},{name:"el-GR-AthinaNeural",gender:"female",displayName:"Αθηνά",locale:"el-GR"},{name:"el-GR-NestorasNeural",gender:"male",displayName:"Νέστορας",locale:"el-GR"},{name:"gu-IN-DhwaniNeural",gender:"female",displayName:"ધ્વની",locale:"gu-IN"},{name:"gu-IN-NiranjanNeural",gender:"male",displayName:"નિરંજન",locale:"gu-IN"},{name:"he-IL-AvriNeural",gender:"male",displayName:"אברי",locale:"he-IL"},{name:"he-IL-HilaNeural",gender:"female",displayName:"הילה",locale:"he-IL"},{name:"hi-IN-MadhurNeural",gender:"male",displayName:"मधुर",locale:"hi-IN"},{name:"hi-IN-SwaraNeural",gender:"female",displayName:"स्वरा",locale:"hi-IN"},{name:"hu-HU-NoemiNeural",gender:"female",displayName:"Noémi",locale:"hu-HU"},{name:"hu-HU-TamasNeural",gender:"male",displayName:"Tamás",locale:"hu-HU"},{name:"is-IS-GudrunNeural",gender:"female",displayName:"Guðrún",locale:"is-IS"},{name:"is-IS-GunnarNeural",gender:"male",displayName:"Gunnar",locale:"is-IS"},{name:"id-ID-ArdiNeural",gender:"male",displayName:"Ardi",locale:"id-ID"},{name:"id-ID-GadisNeural",gender:"female",displayName:"Gadis",locale:"id-ID"},{name:"iu-Latn-CA-SiqiniqNeural",gender:"female",displayName:"ᓯᕿᓂᖅ",locale:"iu-Latn-CA"},{name:"iu-Latn-CA-TaqqiqNeural",gender:"male",displayName:"ᑕᖅᑭᖅ",locale:"iu-Latn-CA"},{name:"iu-Cans-CA-SiqiniqNeural",gender:"female",displayName:"ᓯᕿᓂᖅ",locale:"iu-Cans-CA"},{name:"iu-Cans-CA-TaqqiqNeural",gender:"male",displayName:"ᑕᖅᑭᖅ",locale:"iu-Cans-CA"},{name:"ga-IE-ColmNeural",gender:"male",displayName:"Colm",locale:"ga-IE"},{name:"ga-IE-OrlaNeural",gender:"female",displayName:"Orla",locale:"ga-IE"},{name:"it-IT-GiuseppeMultilingualNeural",gender:"male",displayName:"Giuseppe Multilingual",locale:"it-IT"},{name:"jv-ID-DimasNeural",gender:"male",displayName:"Dimas",locale:"jv-ID"},{name:"jv-ID-SitiNeural",gender:"female",displayName:"Siti",locale:"jv-ID"},{name:"kn-IN-GaganNeural",gender:"male",displayName:"ಗಗನ್",locale:"kn-IN"},{name:"kn-IN-SapnaNeural",gender:"female",displayName:"ಸಪ್ನಾ",locale:"kn-IN"},{name:"kk-KZ-AigulNeural",gender:"female",displayName:"Айгүл",locale:"kk-KZ"},{name:"kk-KZ-DauletNeural",gender:"male",displayName:"Дәулет",locale:"kk-KZ"},{name:"km-KH-PisethNeural",gender:"male",displayName:"ពិសិដ្ឋ",locale:"km-KH"},{name:"km-KH-SreymomNeural",gender:"female",displayName:"ស្រីមុំ",locale:"km-KH"},{name:"ko-KR-HyunsuMultilingualNeural",gender:"male",displayName:"Hyunsu Multilingual",locale:"ko-KR"},{name:"lo-LA-ChanthavongNeural",gender:"male",displayName:"ຈັນທະວົງ",locale:"lo-LA"},{name:"lo-LA-KeomanyNeural",gender:"female",displayName:"ແກ້ວມະນີ",locale:"lo-LA"},{name:"lv-LV-EveritaNeural",gender:"female",displayName:"Everita",locale:"lv-LV"},{name:"lv-LV-NilsNeural",gender:"male",displayName:"Nils",locale:"lv-LV"},{name:"lt-LT-LeonasNeural",gender:"male",displayName:"Leonas",locale:"lt-LT"},{name:"lt-LT-OnaNeural",gender:"female",displayName:"Ona",locale:"lt-LT"},{name:"mk-MK-AleksandarNeural",gender:"male",displayName:"Александар",locale:"mk-MK"},{name:"mk-MK-MarijaNeural",gender:"female",displayName:"Марија",locale:"mk-MK"},{name:"ms-MY-OsmanNeural",gender:"male",displayName:"Osman",locale:"ms-MY"},{name:"ms-MY-YasminNeural",gender:"female",displayName:"Yasmin",locale:"ms-MY"},{name:"ml-IN-MidhunNeural",gender:"male",displayName:"മിഥുൻ",locale:"ml-IN"},{name:"ml-IN-SobhanaNeural",gender:"female",displayName:"ശോഭന",locale:"ml-IN"},{name:"mt-MT-GraceNeural",gender:"female",displayName:"Grace",locale:"mt-MT"},{name:"mt-MT-JosephNeural",gender:"male",displayName:"Joseph",locale:"mt-MT"},{name:"mr-IN-AarohiNeural",gender:"female",displayName:"आरोही",locale:"mr-IN"},{name:"mr-IN-ManoharNeural",gender:"male",displayName:"मनोहर",locale:"mr-IN"},{name:"mn-MN-BataaNeural",gender:"male",displayName:"Батаа",locale:"mn-MN"},{name:"mn-MN-YesuiNeural",gender:"female",displayName:"Есүй",locale:"mn-MN"},{name:"ne-NP-HemkalaNeural",gender:"female",displayName:"हेमकला",locale:"ne-NP"},{name:"ne-NP-SagarNeural",gender:"male",displayName:"सागर",locale:"ne-NP"},{name:"nb-NO-FinnNeural",gender:"male",displayName:"Finn",locale:"nb-NO"},{name:"nb-NO-PernilleNeural",gender:"female",displayName:"Pernille",locale:"nb-NO"},{name:"ps-AF-GulNawazNeural",gender:"male",displayName:" ګل نواز",locale:"ps-AF"},{name:"ps-AF-LatifaNeural",gender:"female",displayName:"لطيفه",locale:"ps-AF"},{name:"fa-IR-DilaraNeural",gender:"female",displayName:"دلارا",locale:"fa-IR"},{name:"fa-IR-FaridNeural",gender:"male",displayName:"فرید",locale:"fa-IR"},{name:"pl-PL-MarekNeural",gender:"male",displayName:"Marek",locale:"pl-PL"},{name:"pl-PL-ZofiaNeural",gender:"female",displayName:"Zofia",locale:"pl-PL"},{name:"pt-BR-ThalitaMultilingualNeural",gender:"female",displayName:"Thalita multilíngue",locale:"pt-BR"},{name:"ro-RO-AlinaNeural",gender:"female",displayName:"Alina",locale:"ro-RO"},{name:"ro-RO-EmilNeural",gender:"male",displayName:"Emil",locale:"ro-RO"},{name:"sr-RS-NicholasNeural",gender:"male",displayName:"Никола",locale:"sr-RS"},{name:"sr-RS-SophieNeural",gender:"female",displayName:"Софија",locale:"sr-RS"},{name:"si-LK-SameeraNeural",gender:"male",displayName:"සමීර",locale:"si-LK"},{name:"si-LK-ThiliniNeural",gender:"female",displayName:"තිළිණි",locale:"si-LK"},{name:"sk-SK-LukasNeural",gender:"male",displayName:"Lukáš",locale:"sk-SK"},{name:"sk-SK-ViktoriaNeural",gender:"female",displayName:"Viktória",locale:"sk-SK"},{name:"sl-SI-PetraNeural",gender:"female",displayName:"Petra",locale:"sl-SI"},{name:"sl-SI-RokNeural",gender:"male",displayName:"Rok",locale:"sl-SI"},{name:"so-SO-MuuseNeural",gender:"male",displayName:"Muuse",locale:"so-SO"},{name:"so-SO-UbaxNeural",gender:"female",displayName:"Ubax",locale:"so-SO"},{name:"es-AR-ElenaNeural",gender:"female",displayName:"Elena",locale:"es-AR"},{name:"es-AR-TomasNeural",gender:"male",displayName:"Tomas",locale:"es-AR"},{name:"es-BO-MarceloNeural",gender:"male",displayName:"Marcelo",locale:"es-BO"},{name:"es-BO-SofiaNeural",gender:"female",displayName:"Sofia",locale:"es-BO"},{name:"es-CL-CatalinaNeural",gender:"female",displayName:"Catalina",locale:"es-CL"},{name:"es-CL-LorenzoNeural",gender:"male",displayName:"Lorenzo",locale:"es-CL"},{name:"es-CO-GonzaloNeural",gender:"male",displayName:"Gonzalo",locale:"es-CO"},{name:"es-CO-SalomeNeural",gender:"female",displayName:"Salome",locale:"es-CO"},{name:"es-ES-XimenaNeural",gender:"female",displayName:"Ximena",locale:"es-ES"},{name:"es-CR-JuanNeural",gender:"male",displayName:"Juan",locale:"es-CR"},{name:"es-CR-MariaNeural",gender:"female",displayName:"María",locale:"es-CR"},{name:"es-CU-BelkysNeural",gender:"female",displayName:"Belkys",locale:"es-CU"},{name:"es-CU-ManuelNeural",gender:"male",displayName:"Manuel",locale:"es-CU"},{name:"es-DO-EmilioNeural",gender:"male",displayName:"Emilio",locale:"es-DO"},{name:"es-DO-RamonaNeural",gender:"female",displayName:"Ramona",locale:"es-DO"},{name:"es-EC-AndreaNeural",gender:"female",displayName:"Andrea",locale:"es-EC"},{name:"es-EC-LuisNeural",gender:"male",displayName:"Luis",locale:"es-EC"},{name:"es-SV-LorenaNeural",gender:"female",displayName:"Lorena",locale:"es-SV"},{name:"es-SV-RodrigoNeural",gender:"male",displayName:"Rodrigo",locale:"es-SV"},{name:"es-GQ-JavierNeural",gender:"male",displayName:"Javier",locale:"es-GQ"},{name:"es-GQ-TeresaNeural",gender:"female",displayName:"Teresa",locale:"es-GQ"},{name:"es-GT-AndresNeural",gender:"male",displayName:"Andrés",locale:"es-GT"},{name:"es-GT-MartaNeural",gender:"female",displayName:"Marta",locale:"es-GT"},{name:"es-HN-CarlosNeural",gender:"male",displayName:"Carlos",locale:"es-HN"},{name:"es-HN-KarlaNeural",gender:"female",displayName:"Karla",locale:"es-HN"},{name:"es-MX-DaliaNeural",gender:"female",displayName:"Dalia",locale:"es-MX"},{name:"es-MX-JorgeNeural",gender:"male",displayName:"Jorge",locale:"es-MX"},{name:"es-NI-FedericoNeural",gender:"male",displayName:"Federico",locale:"es-NI"},{name:"es-NI-YolandaNeural",gender:"female",displayName:"Yolanda",locale:"es-NI"},{name:"es-PA-MargaritaNeural",gender:"female",displayName:"Margarita",locale:"es-PA"},{name:"es-PA-RobertoNeural",gender:"male",displayName:"Roberto",locale:"es-PA"},{name:"es-PY-MarioNeural",gender:"male",displayName:"Mario",locale:"es-PY"},{name:"es-PY-TaniaNeural",gender:"female",displayName:"Tania",locale:"es-PY"},{name:"es-PE-AlexNeural",gender:"male",displayName:"Alex",locale:"es-PE"},{name:"es-PE-CamilaNeural",gender:"female",displayName:"Camila",locale:"es-PE"},{name:"es-PR-KarinaNeural",gender:"female",displayName:"Karina",locale:"es-PR"},{name:"es-PR-VictorNeural",gender:"male",displayName:"Víctor",locale:"es-PR"},{name:"es-US-AlonsoNeural",gender:"male",displayName:"Alonso",locale:"es-US"},{name:"es-US-PalomaNeural",gender:"female",displayName:"Paloma",locale:"es-US"},{name:"es-UY-MateoNeural",gender:"male",displayName:"Mateo",locale:"es-UY"},{name:"es-UY-ValentinaNeural",gender:"female",displayName:"Valentina",locale:"es-UY"},{name:"es-VE-PaolaNeural",gender:"female",displayName:"Paola",locale:"es-VE"},{name:"es-VE-SebastianNeural",gender:"male",displayName:"Sebastián",locale:"es-VE"},{name:"su-ID-JajangNeural",gender:"male",displayName:"Jajang",locale:"su-ID"},{name:"su-ID-TutiNeural",gender:"female",displayName:"Tuti",locale:"su-ID"},{name:"sw-KE-RafikiNeural",gender:"male",displayName:"Rafiki",locale:"sw-KE"},{name:"sw-KE-ZuriNeural",gender:"female",displayName:"Zuri",locale:"sw-KE"},{name:"sw-TZ-DaudiNeural",gender:"male",displayName:"Daudi",locale:"sw-TZ"},{name:"sw-TZ-RehemaNeural",gender:"female",displayName:"Rehema",locale:"sw-TZ"},{name:"sv-SE-MattiasNeural",gender:"male",displayName:"Mattias",locale:"sv-SE"},{name:"sv-SE-SofieNeural",gender:"female",displayName:"Sofie",locale:"sv-SE"},{name:"ta-IN-PallaviNeural",gender:"female",displayName:"பல்லவி",locale:"ta-IN"},{name:"ta-IN-ValluvarNeural",gender:"male",displayName:"வள்ளுவர்",locale:"ta-IN"},{name:"ta-MY-KaniNeural",gender:"female",displayName:"கனி",locale:"ta-MY"},{name:"ta-MY-SuryaNeural",gender:"male",displayName:"சூர்யா",locale:"ta-MY"},{name:"ta-SG-AnbuNeural",gender:"male",displayName:"அன்பு",locale:"ta-SG"},{name:"ta-SG-VenbaNeural",gender:"female",displayName:"வெண்பா",locale:"ta-SG"},{name:"ta-LK-KumarNeural",gender:"male",displayName:"குமார்",locale:"ta-LK"},{name:"ta-LK-SaranyaNeural",gender:"female",displayName:"சரண்யா",locale:"ta-LK"},{name:"te-IN-MohanNeural",gender:"male",displayName:"మోహన్",locale:"te-IN"},{name:"te-IN-ShrutiNeural",gender:"female",displayName:"శ్రుతి",locale:"te-IN"},{name:"th-TH-NiwatNeural",gender:"male",displayName:"นิวัฒน์",locale:"th-TH"},{name:"th-TH-PremwadeeNeural",gender:"female",displayName:"เปรมวดี",locale:"th-TH"},{name:"tr-TR-EmelNeural",gender:"female",displayName:"Emel",locale:"tr-TR"},{name:"tr-TR-AhmetNeural",gender:"male",displayName:"Ahmet",locale:"tr-TR"},{name:"uk-UA-OstapNeural",gender:"male",displayName:"Остап",locale:"uk-UA"},{name:"uk-UA-PolinaNeural",gender:"female",displayName:"Поліна",locale:"uk-UA"},{name:"ur-IN-GulNeural",gender:"female",displayName:"گل",locale:"ur-IN"},{name:"ur-IN-SalmanNeural",gender:"male",displayName:"سلمان",locale:"ur-IN"},{name:"ur-PK-AsadNeural",gender:"male",displayName:"اسد",locale:"ur-PK"},{name:"ur-PK-UzmaNeural",gender:"female",displayName:"عظمیٰ",locale:"ur-PK"},{name:"uz-UZ-MadinaNeural",gender:"female",displayName:"Madina",locale:"uz-UZ"},{name:"uz-UZ-SardorNeural",gender:"male",displayName:"Sardor",locale:"uz-UZ"},{name:"vi-VN-HoaiMyNeural",gender:"female",displayName:"Hoài My",locale:"vi-VN"},{name:"vi-VN-NamMinhNeural",gender:"male",displayName:"Nam Minh",locale:"vi-VN"},{name:"cy-GB-AledNeural",gender:"male",displayName:"Aled",locale:"cy-GB"},{name:"cy-GB-NiaNeural",gender:"female",displayName:"Nia",locale:"cy-GB"},{name:"zu-ZA-ThandoNeural",gender:"female",displayName:"Thando",locale:"zu-ZA"},{name:"zu-ZA-ThembaNeural",gender:"male",displayName:"Themba",locale:"zu-ZA"},{name:"as-IN-YashicaNeural",gender:"female",displayName:"যাশিকা",locale:"as-IN"},{name:"as-IN-PriyomNeural",gender:"male",displayName:"প্ৰিয়ম",locale:"as-IN"},{name:"ca-ES-AlbaNeural",gender:"female",displayName:"Alba",locale:"ca-ES"},{name:"de-DE-ChristophNeural",gender:"male",displayName:"Christoph",locale:"de-DE"},{name:"de-DE-ElkeNeural",gender:"female",displayName:"Elke",locale:"de-DE"},{name:"de-DE-GiselaNeural",gender:"female",displayName:"Gisela",locale:"de-DE"},{name:"de-DE-KasperNeural",gender:"male",displayName:"Kasper",locale:"de-DE"},{name:"de-DE-KlarissaNeural",gender:"female",displayName:"Klarissa",locale:"de-DE"},{name:"de-DE-KlausNeural",gender:"male",displayName:"Klaus",locale:"de-DE"},{name:"de-DE-LouisaNeural",gender:"female",displayName:"Louisa",locale:"de-DE"},{name:"de-DE-MajaNeural",gender:"female",displayName:"Maja",locale:"de-DE"},{name:"de-DE-RalfNeural",gender:"male",displayName:"Ralf",locale:"de-DE"},{name:"de-DE-TanjaNeural",gender:"female",displayName:"Tanja",locale:"de-DE"},{name:"en-AU-WilliamNeural",gender:"male",displayName:"William",locale:"en-AU"},{name:"en-AU-AnnetteNeural",gender:"female",displayName:"Annette",locale:"en-AU"},{name:"en-AU-CarlyNeural",gender:"female",displayName:"Carly",locale:"en-AU"},{name:"en-AU-DarrenNeural",gender:"male",displayName:"Darren",locale:"en-AU"},{name:"en-AU-DuncanNeural",gender:"male",displayName:"Duncan",locale:"en-AU"},{name:"en-AU-ElsieNeural",gender:"female",displayName:"Elsie",locale:"en-AU"},{name:"en-AU-FreyaNeural",gender:"female",displayName:"Freya",locale:"en-AU"},{name:"en-AU-JoanneNeural",gender:"female",displayName:"Joanne",locale:"en-AU"},{name:"en-AU-KenNeural",gender:"male",displayName:"Ken",locale:"en-AU"},{name:"en-AU-KimNeural",gender:"female",displayName:"Kim",locale:"en-AU"},{name:"en-AU-NeilNeural",gender:"male",displayName:"Neil",locale:"en-AU"},{name:"en-AU-TimNeural",gender:"male",displayName:"Tim",locale:"en-AU"},{name:"en-AU-TinaNeural",gender:"female",displayName:"Tina",locale:"en-AU"},{name:"en-GB-AdaMultilingualNeural",gender:"female",displayName:"Ada Multilingual",locale:"en-GB"},{name:"en-GB-OllieMultilingualNeural",gender:"male",displayName:"Ollie Multilingual",locale:"en-GB"},{name:"en-GB-AbbiNeural",gender:"female",displayName:"Abbi",locale:"en-GB"},{name:"en-GB-AlfieNeural",gender:"male",displayName:"Alfie",locale:"en-GB"},{name:"en-GB-BellaNeural",gender:"female",displayName:"Bella",locale:"en-GB"},{name:"en-GB-ElliotNeural",gender:"male",displayName:"Elliot",locale:"en-GB"},{name:"en-GB-EthanNeural",gender:"male",displayName:"Ethan",locale:"en-GB"},{name:"en-GB-HollieNeural",gender:"female",displayName:"Hollie",locale:"en-GB"},{name:"en-GB-NoahNeural",gender:"male",displayName:"Noah",locale:"en-GB"},{name:"en-GB-OliverNeural",gender:"male",displayName:"Oliver",locale:"en-GB"},{name:"en-GB-OliviaNeural",gender:"female",displayName:"Olivia",locale:"en-GB"},{name:"en-GB-MiaNeural",gender:"female",displayName:"Mia",locale:"en-GB"},{name:"en-IN-AartiIndicNeural",gender:"female",displayName:"Aarti Indic",locale:"en-IN"},{name:"en-IN-ArjunIndicNeural",gender:"male",displayName:"Arjun Indic",locale:"en-IN"},{name:"en-IN-NeerjaIndicNeural",gender:"female",displayName:"Neerja Indic",locale:"en-IN"},{name:"en-IN-PrabhatIndicNeural",gender:"male",displayName:"Prabhat Indic",locale:"en-IN"},{name:"en-IN-AaravNeural",gender:"male",displayName:"Aarav",locale:"en-IN"},{name:"en-IN-AashiNeural",gender:"female",displayName:"Aashi",locale:"en-IN"},{name:"en-IN-AartiNeural",gender:"female",displayName:"Aarti",locale:"en-IN"},{name:"en-IN-ArjunNeural",gender:"male",displayName:"Arjun",locale:"en-IN"},{name:"en-IN-AnanyaNeural",gender:"female",displayName:"Ananya",locale:"en-IN"},{name:"en-IN-KavyaNeural",gender:"female",displayName:"Kavya",locale:"en-IN"},{name:"en-IN-KunalNeural",gender:"male",displayName:"Kunal",locale:"en-IN"},{name:"en-IN-RehaanNeural",gender:"male",displayName:"Rehaan",locale:"en-IN"},{name:"en-US-AmandaMultilingualNeural",gender:"female",displayName:"Amanda Multilingual",locale:"en-US"},{name:"en-US-AdamMultilingualNeural",gender:"male",displayName:"Adam Multilingual",locale:"en-US"},{name:"en-US-PhoebeMultilingualNeural",gender:"female",displayName:"Phoebe Multilingual",locale:"en-US"},{name:"en-US-AlloyTurboMultilingualNeural",gender:"male",displayName:"Alloy Turbo Multilingual",locale:"en-US"},{name:"en-US-EchoTurboMultilingualNeural",gender:"male",displayName:"Echo Turbo Multilingual",locale:"en-US"},{name:"en-US-FableTurboMultilingualNeural",gender:"female",displayName:"Fable Turbo Multilingual",locale:"en-US"},{name:"en-US-OnyxTurboMultilingualNeural",gender:"male",displayName:"Onyx Turbo Multilingual",locale:"en-US"},{name:"en-US-NovaTurboMultilingualNeural",gender:"female",displayName:"Nova Turbo Multilingual",locale:"en-US"},{name:"en-US-ShimmerTurboMultilingualNeural",gender:"female",displayName:"Shimmer Turbo Multilingual",locale:"en-US"},{name:"en-US-JasonNeural",gender:"male",displayName:"Jason",locale:"en-US"},{name:"en-US-KaiNeural",gender:"male",displayName:"Kai",locale:"en-US"},{name:"en-US-LunaNeural",gender:"female",displayName:"Luna",locale:"en-US"},{name:"en-US-TonyNeural",gender:"male",displayName:"Tony",locale:"en-US"},{name:"en-US-NancyNeural",gender:"female",displayName:"Nancy",locale:"en-US"},{name:"en-US-CoraMultilingualNeural",gender:"female",displayName:"Cora Multilingual",locale:"en-US"},{name:"en-US-ChristopherMultilingualNeural",gender:"male",displayName:"Christopher Multilingual",locale:"en-US"},{name:"en-US-BrandonMultilingualNeural",gender:"male",displayName:"Brandon Multilingual",locale:"en-US"},{name:"en-US-AshleyNeural",gender:"female",displayName:"Ashley",locale:"en-US"},{name:"en-US-BrandonNeural",gender:"male",displayName:"Brandon",locale:"en-US"},{name:"en-US-CoraNeural",gender:"female",displayName:"Cora",locale:"en-US"},{name:"en-US-DavisMultilingualNeural",gender:"male",displayName:"Davis Multilingual",locale:"en-US"},{name:"en-US-DerekMultilingualNeural",gender:"male",displayName:"Derek Multilingual",locale:"en-US"},{name:"en-US-DustinMultilingualNeural",gender:"male",displayName:"Dustin Multilingual",locale:"en-US"},{name:"en-US-ElizabethNeural",gender:"female",displayName:"Elizabeth",locale:"en-US"},{name:"en-US-JacobNeural",gender:"male",displayName:"Jacob",locale:"en-US"},{name:"en-US-JennyMultilingualNeural",gender:"female",displayName:"Jenny Multilingual",locale:"en-US"},{name:"en-US-LewisMultilingualNeural",gender:"male",displayName:"Lewis Multilingual",locale:"en-US"},{name:"en-US-LolaMultilingualNeural",gender:"female",displayName:"Lola Multilingual",locale:"en-US"},{name:"en-US-MonicaNeural",gender:"female",displayName:"Monica",locale:"en-US"},{name:"en-US-NancyMultilingualNeural",gender:"female",displayName:"Nancy Multilingual",locale:"en-US"},{name:"en-US-RyanMultilingualNeural",gender:"male",displayName:"Ryan Multilingual",locale:"en-US"},{name:"en-US-SamuelMultilingualNeural",gender:"male",displayName:"Samuel Multilingual",locale:"en-US"},{name:"en-US-SerenaMultilingualNeural",gender:"female",displayName:"Serena Multilingual",locale:"en-US"},{name:"en-US-SteffanMultilingualNeural",gender:"male",displayName:"Steffan Multilingual",locale:"en-US"},{name:"en-US-AIGenerate1Neural",gender:"male",displayName:"AIGenerate1",locale:"en-US"},{name:"en-US-AIGenerate2Neural",gender:"female",displayName:"AIGenerate2",locale:"en-US"},{name:"en-US-AshTurboMultilingualNeural",gender:"male",displayName:"Ash Turbo Multilingual",locale:"en-US"},{name:"en-US-BlueNeural",gender:"female",displayName:"Blue",locale:"en-US"},{name:"en-US-EvelynMultilingualNeural",gender:"female",displayName:"Evelyn Multilingual",locale:"en-US"},{name:"es-ES-ArabellaMultilingualNeural",gender:"female",displayName:"Arabella Multilingual",locale:"es-ES"},{name:"es-ES-IsidoraMultilingualNeural",gender:"female",displayName:"Isidora Multilingual",locale:"es-ES"},{name:"es-ES-TristanMultilingualNeural",gender:"male",displayName:"Tristan Multilingual",locale:"es-ES"},{name:"es-ES-XimenaMultilingualNeural",gender:"female",displayName:"Ximena Multilingual",locale:"es-ES"},{name:"es-ES-DarioNeural",gender:"male",displayName:"Dario",locale:"es-ES"},{name:"es-ES-EliasNeural",gender:"male",displayName:"Elias",locale:"es-ES"},{name:"es-ES-EstrellaNeural",gender:"female",displayName:"Estrella",locale:"es-ES"},{name:"es-ES-IreneNeural",gender:"female",displayName:"Irene",locale:"es-ES"},{name:"es-ES-LaiaNeural",gender:"female",displayName:"Laia",locale:"es-ES"},{name:"es-ES-LiaNeural",gender:"female",displayName:"Lia",locale:"es-ES"},{name:"es-ES-NilNeural",gender:"male",displayName:"Nil",locale:"es-ES"},{name:"es-ES-SaulNeural",gender:"male",displayName:"Saul",locale:"es-ES"},{name:"es-ES-TeoNeural",gender:"male",displayName:"Teo",locale:"es-ES"},{name:"es-ES-TrianaNeural",gender:"female",displayName:"Triana",locale:"es-ES"},{name:"es-ES-VeraNeural",gender:"female",displayName:"Vera",locale:"es-ES"},{name:"es-MX-DaliaMultilingualNeural",gender:"female",displayName:"Dalia Multilingual",locale:"es-MX"},{name:"es-MX-JorgeMultilingualNeural",gender:"male",displayName:"Jorge Multilingual",locale:"es-MX"},{name:"es-MX-BeatrizNeural",gender:"female",displayName:"Beatriz",locale:"es-MX"},{name:"es-MX-CandelaNeural",gender:"female",displayName:"Candela",locale:"es-MX"},{name:"es-MX-CarlotaNeural",gender:"female",displayName:"Carlota",locale:"es-MX"},{name:"es-MX-CecilioNeural",gender:"male",displayName:"Cecilio",locale:"es-MX"},{name:"es-MX-GerardoNeural",gender:"male",displayName:"Gerardo",locale:"es-MX"},{name:"es-MX-LarissaNeural",gender:"female",displayName:"Larissa",locale:"es-MX"},{name:"es-MX-LibertoNeural",gender:"male",displayName:"Liberto",locale:"es-MX"},{name:"es-MX-LucianoNeural",gender:"male",displayName:"Luciano",locale:"es-MX"},{name:"es-MX-MarinaNeural",gender:"female",displayName:"Marina",locale:"es-MX"},{name:"es-MX-NuriaNeural",gender:"female",displayName:"Nuria",locale:"es-MX"},{name:"es-MX-PelayoNeural",gender:"male",displayName:"Pelayo",locale:"es-MX"},{name:"es-MX-RenataNeural",gender:"female",displayName:"Renata",locale:"es-MX"},{name:"es-MX-YagoNeural",gender:"male",displayName:"Yago",locale:"es-MX"},{name:"eu-ES-AinhoaNeural",gender:"female",displayName:"Ainhoa",locale:"eu-ES"},{name:"eu-ES-AnderNeural",gender:"male",displayName:"Ander",locale:"eu-ES"},{name:"fi-FI-SelmaNeural",gender:"female",displayName:"Selma",locale:"fi-FI"},{name:"fr-FR-LucienMultilingualNeural",gender:"male",displayName:"Lucien Multilingual",locale:"fr-FR"},{name:"fr-FR-AlainNeural",gender:"male",displayName:"Alain",locale:"fr-FR"},{name:"fr-FR-BrigitteNeural",gender:"female",displayName:"Brigitte",locale:"fr-FR"},{name:"fr-FR-CelesteNeural",gender:"female",displayName:"Celeste",locale:"fr-FR"},{name:"fr-FR-ClaudeNeural",gender:"male",displayName:"Claude",locale:"fr-FR"},{name:"fr-FR-CoralieNeural",gender:"female",displayName:"Coralie",locale:"fr-FR"},{name:"fr-FR-JacquelineNeural",gender:"female",displayName:"Jacqueline",locale:"fr-FR"},{name:"fr-FR-JeromeNeural",gender:"male",displayName:"Jerome",locale:"fr-FR"},{name:"fr-FR-JosephineNeural",gender:"female",displayName:"Josephine",locale:"fr-FR"},{name:"fr-FR-MauriceNeural",gender:"male",displayName:"Maurice",locale:"fr-FR"},{name:"fr-FR-YvesNeural",gender:"male",displayName:"Yves",locale:"fr-FR"},{name:"fr-FR-YvetteNeural",gender:"female",displayName:"Yvette",locale:"fr-FR"},{name:"hi-IN-AaravNeural",gender:"male",displayName:"आरव ",locale:"hi-IN"},{name:"hi-IN-AnanyaNeural",gender:"female",displayName:"अनन्या",locale:"hi-IN"},{name:"hi-IN-AartiNeural",gender:"female",displayName:"आरती",locale:"hi-IN"},{name:"hi-IN-ArjunNeural",gender:"male",displayName:"अर्जुन",locale:"hi-IN"},{name:"hi-IN-KavyaNeural",gender:"female",displayName:"काव्या",locale:"hi-IN"},{name:"hi-IN-KunalNeural",gender:"male",displayName:"कुनाल ",locale:"hi-IN"},{name:"hi-IN-RehaanNeural",gender:"male",displayName:"रेहान",locale:"hi-IN"},{name:"hy-AM-AnahitNeural",gender:"female",displayName:"Անահիտ",locale:"hy-AM"},{name:"hy-AM-HaykNeural",gender:"male",displayName:"Հայկ",locale:"hy-AM"},{name:"it-IT-AlessioMultilingualNeural",gender:"male",displayName:"Alessio Multilingual",locale:"it-IT"},{name:"it-IT-IsabellaMultilingualNeural",gender:"female",displayName:"Isabella Multilingual",locale:"it-IT"},{name:"it-IT-MarcelloMultilingualNeural",gender:"male",displayName:"Marcello Multilingual",locale:"it-IT"},{name:"it-IT-CalimeroNeural",gender:"male",displayName:"Calimero",locale:"it-IT"},{name:"it-IT-CataldoNeural",gender:"male",displayName:"Cataldo",locale:"it-IT"},{name:"it-IT-FabiolaNeural",gender:"female",displayName:"Fabiola",locale:"it-IT"},{name:"it-IT-FiammaNeural",gender:"female",displayName:"Fiamma",locale:"it-IT"},{name:"it-IT-GianniNeural",gender:"male",displayName:"Gianni",locale:"it-IT"},{name:"it-IT-GiuseppeNeural",gender:"male",displayName:"Giuseppe",locale:"it-IT"},{name:"it-IT-ImeldaNeural",gender:"female",displayName:"Imelda",locale:"it-IT"},{name:"it-IT-IrmaNeural",gender:"female",displayName:"Irma",locale:"it-IT"},{name:"it-IT-LisandroNeural",gender:"male",displayName:"Lisandro",locale:"it-IT"},{name:"it-IT-PalmiraNeural",gender:"female",displayName:"Palmira",locale:"it-IT"},{name:"it-IT-PierinaNeural",gender:"female",displayName:"Pierina",locale:"it-IT"},{name:"it-IT-RinaldoNeural",gender:"male",displayName:"Rinaldo",locale:"it-IT"},{name:"ja-JP-AoiNeural",gender:"female",displayName:"碧衣",locale:"ja-JP"},{name:"ja-JP-DaichiNeural",gender:"male",displayName:"大智",locale:"ja-JP"},{name:"ja-JP-MayuNeural",gender:"female",displayName:"真夕",locale:"ja-JP"},{name:"ja-JP-NaokiNeural",gender:"male",displayName:"直紀",locale:"ja-JP"},{name:"ja-JP-ShioriNeural",gender:"female",displayName:"志織",locale:"ja-JP"},{name:"ja-JP-MasaruMultilingualNeural",gender:"male",displayName:"勝 多言語",locale:"ja-JP"},{name:"ko-KR-BongJinNeural",gender:"male",displayName:"봉진",locale:"ko-KR"},{name:"ko-KR-GookMinNeural",gender:"male",displayName:"국민",locale:"ko-KR"},{name:"ko-KR-HyunsuNeural",gender:"male",displayName:"현수",locale:"ko-KR"},{name:"ko-KR-JiMinNeural",gender:"female",displayName:"지민",locale:"ko-KR"},{name:"ko-KR-SeoHyeonNeural",gender:"female",displayName:"서현",locale:"ko-KR"},{name:"ko-KR-YuJinNeural",gender:"female",displayName:"유진",locale:"ko-KR"},{name:"nb-NO-IselinNeural",gender:"female",displayName:"Iselin",locale:"nb-NO"},{name:"or-IN-SubhasiniNeural",gender:"female",displayName:"ସୁଭାସିନୀ",locale:"or-IN"},{name:"or-IN-SukantNeural",gender:"male",displayName:"ସୁକାନ୍ତ",locale:"or-IN"},{name:"pa-IN-OjasNeural",gender:"male",displayName:"ਓਜਸ",locale:"pa-IN"},{name:"pa-IN-VaaniNeural",gender:"female",displayName:"ਵਾਨੀ",locale:"pa-IN"},{name:"pl-PL-AgnieszkaNeural",gender:"female",displayName:"Agnieszka",locale:"pl-PL"},{name:"pt-BR-MacerioMultilingualNeural",gender:"male",displayName:"Macerio Multilingual",locale:"pt-BR"},{name:"pt-BR-BrendaNeural",gender:"female",displayName:"Brenda",locale:"pt-BR"},{name:"pt-BR-DonatoNeural",gender:"male",displayName:"Donato",locale:"pt-BR"},{name:"pt-BR-ElzaNeural",gender:"female",displayName:"Elza",locale:"pt-BR"},{name:"pt-BR-FabioNeural",gender:"male",displayName:"Fabio",locale:"pt-BR"},{name:"pt-BR-GiovannaNeural",gender:"female",displayName:"Giovanna",locale:"pt-BR"},{name:"pt-BR-HumbertoNeural",gender:"male",displayName:"Humberto",locale:"pt-BR"},{name:"pt-BR-JulioNeural",gender:"male",displayName:"Julio",locale:"pt-BR"},{name:"pt-BR-LeilaNeural",gender:"female",displayName:"Leila",locale:"pt-BR"},{name:"pt-BR-LeticiaNeural",gender:"female",displayName:"Leticia",locale:"pt-BR"},{name:"pt-BR-ManuelaNeural",gender:"female",displayName:"Manuela",locale:"pt-BR"},{name:"pt-BR-NicolauNeural",gender:"male",displayName:"Nicolau",locale:"pt-BR"},{name:"pt-BR-ThalitaNeural",gender:"female",displayName:"Thalita",locale:"pt-BR"},{name:"pt-BR-ValerioNeural",gender:"male",displayName:"Valerio",locale:"pt-BR"},{name:"pt-BR-YaraNeural",gender:"female",displayName:"Yara",locale:"pt-BR"},{name:"pt-PT-FernandaNeural",gender:"female",displayName:"Fernanda",locale:"pt-PT"},{name:"sr-Latn-RS-NicholasNeural",gender:"male",displayName:"Nicholas",locale:"sr-Latn-RS"},{name:"sr-Latn-RS-SophieNeural",gender:"female",displayName:"Sophie",locale:"sr-Latn-RS"},{name:"sv-SE-HilleviNeural",gender:"female",displayName:"Hillevi",locale:"sv-SE"},{name:"th-TH-AcharaNeural",gender:"female",displayName:"อัจฉรา",locale:"th-TH"},{name:"wuu-CN-XiaotongNeural",gender:"female",displayName:"晓彤",locale:"wuu-CN"},{name:"wuu-CN-YunzheNeural",gender:"male",displayName:"云哲",locale:"wuu-CN"},{name:"zh-CN-XiaochenNeural",gender:"female",displayName:"晓辰",locale:"zh-CN"},{name:"zh-CN-XiaochenMultilingualNeural",gender:"female",displayName:"晓辰 多语言",locale:"zh-CN"},{name:"zh-CN-XiaohanNeural",gender:"female",displayName:"晓涵",locale:"zh-CN"},{name:"zh-CN-XiaomengNeural",gender:"female",displayName:"晓梦",locale:"zh-CN"},{name:"zh-CN-XiaomoNeural",gender:"female",displayName:"晓墨",locale:"zh-CN"},{name:"zh-CN-XiaoqiuNeural",gender:"female",displayName:"晓秋",locale:"zh-CN"},{name:"zh-CN-XiaorouNeural",gender:"female",displayName:"晓柔",locale:"zh-CN"},{name:"zh-CN-XiaoruiNeural",gender:"female",displayName:"晓睿",locale:"zh-CN"},{name:"zh-CN-XiaoshuangNeural",gender:"female",displayName:"晓双",locale:"zh-CN"},{name:"zh-CN-XiaoxiaoDialectsNeural",gender:"female",displayName:"晓晓 ",locale:"zh-CN"},{name:"zh-CN-XiaoxiaoMultilingualNeural",gender:"female",displayName:"晓晓 多语言",locale:"zh-CN"},{name:"zh-CN-XiaoyanNeural",gender:"female",displayName:"晓颜",locale:"zh-CN"},{name:"zh-CN-XiaoyouNeural",gender:"female",displayName:"晓悠",locale:"zh-CN"},{name:"zh-CN-XiaoyuMultilingualNeural",gender:"female",displayName:"晓宇 多语言",locale:"zh-CN"},{name:"zh-CN-XiaozhenNeural",gender:"female",displayName:"晓甄",locale:"zh-CN"},{name:"zh-CN-YunfengNeural",gender:"male",displayName:"云枫",locale:"zh-CN"},{name:"zh-CN-YunhaoNeural",gender:"male",displayName:"云皓",locale:"zh-CN"},{name:"zh-CN-YunjieNeural",gender:"male",displayName:"云杰",locale:"zh-CN"},{name:"zh-CN-YunxiaoMultilingualNeural",gender:"male",displayName:"云霄 多语言",locale:"zh-CN"},{name:"zh-CN-YunyeNeural",gender:"male",displayName:"云野",locale:"zh-CN"},{name:"zh-CN-YunyiMultilingualNeural",gender:"male",displayName:"云逸 多语言",locale:"zh-CN"},{name:"zh-CN-YunzeNeural",gender:"male",displayName:"云泽",locale:"zh-CN"},{name:"zh-CN-YunfanMultilingualNeural",gender:"male",displayName:"云帆 多语言",locale:"zh-CN"},{name:"zh-CN-guangxi-YunqiNeural",gender:"male",displayName:"云奇 广西",locale:"zh-CN"},{name:"zh-CN-henan-YundengNeural",gender:"male",displayName:"云登 河南",locale:"zh-CN"},{name:"zh-CN-liaoning-YunbiaoNeural",gender:"male",displayName:"云彪 辽宁",locale:"zh-CN"},{name:"zh-CN-shandong-YunxiangNeural",gender:"male",displayName:"云翔 山东",locale:"zh-CN"},{name:"zh-CN-sichuan-YunxiNeural",gender:"male",displayName:"云希 四川",locale:"zh-CN"}],SelfHostedVoiceList:["de-DE-AmalaNeural","de-DE-BerndNeural","de-DE-ConradNeural","de-DE-KatjaNeural","en-GB-LibbyNeural","en-GB-RyanNeural","en-GB-SoniaNeural","en-US-AmberNeural","en-US-AriaNeural","en-US-ChristopherNeural","en-US-DavisNeural","en-US-EricNeural","en-US-GuyNeural","en-US-JaneNeural","en-US-JennyNeural","en-US-MichelleNeural","en-US-SaraNeural","es-ES-AbrilNeural","es-ES-AlvaroNeural","es-ES-ArnauNeural","es-ES-ElviraNeural","fr-FR-DeniseNeural","fr-FR-HenriNeural","it-IT-BenignoNeural","it-IT-DiegoNeural","it-IT-ElsaNeural","it-IT-IsabellaNeural","ja-JP-KeitaNeural","ja-JP-NanamiNeural","ko-KR-InJoonNeural","ko-KR-SoonBokNeural","ko-KR-SunHiNeural","pt-BR-AntonioNeural","pt-BR-FranciscaNeural","pt-PT-DuarteNeural","pt-PT-RaquelNeural","ru-RU-DariyaNeural","ru-RU-DmitryNeural","ru-RU-SvetlanaNeural","yue-CN-XiaoMinNeural","yue-CN-YunSongNeural","zh-CN-henan-YundengNeural","zh-CN-liaoning-XiaobeiNeural","zh-CN-shaanxi-XiaoniNeural","zh-CN-shandong-YunxiangNeural","zh-CN-sichuan-YunxiNeural","zh-CN-XiaoxiaoNeural","zh-CN-YunxiNeural","zh-HK-HiuMaanNeural","zh-HK-WanLungNeural","zh-TW-HsiaoChenNeural","zh-TW-YunJheNeural","zf_xiaoxiao","zm_yunxi","zf_xiaoni","zf_xiaobei"],CloudDictList:[{id:"basic-english-irish",name:"Basic English-Irish Dictionary",translation:"简明英爱词典",source:"Pat Griffin"},{id:"english-italian",name:"English-Italian Dictionary",translation:"简明英意词典",source:"Pat Griffin"},{id:"cc-cedict",name:"CC-CEDICT",translation:"简明中英词典",source:"www.mdbg.net"},{id:"et-tedict",name:"ET-TEDICT",translation:"简明中英英中词典",source:"cdict-1.0-1.i386.rpm"},{id:"jmdict",name:"Japanese English Dictionary",translation:"简明日英词典",source:"JMDict"},{id:"moby",name:"Moby Thesaurus",translation:"Moby Thesaurus",source:"Chua Welic"},{id:"wordnet",name:"Wordnet",translation:"Wordnet",source:"Chua Welic"},{id:"opted",name:"Online Plain Text English Dictionary",translation:"简明英英词典",source:"Chua Welic"},{id:"english-arabic",name:"English-Arabic Dictionary",translation:"简明英阿词典",source:"Khaldoun Mahmoud"},{id:"tcm_textbook",name:"中医教材仓库",translation:"中医教材仓库",source:"Fredrik Jornebo"},{id:"ecdict",name:"ECDICT",translation:"简明英汉字典增强版",source:"GitHub-skywind3000"}]};class x{constructor(e){this.config=e,this.driveId="",this.taskQueue=new k(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getDriveId(){return m(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const a=this.config.access_token,t=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${a}`}});return this.driveId=t.data.default_drive_id,this.driveId}))}getFolderIdByPath(a){return m(this,void 0,void 0,(function*(){const t=this.config.access_token,o=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:a},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const n=a.split("/").filter((e=>e));let r="",l="root";for(const a of n){r+="/"+a;try{l=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:r},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.file_id}catch(i){l=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,parent_file_id:l,name:a,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.file_id}}return l}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+a);let n=[],r="",l=!0;for(;l;){const a=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:i,marker:r||void 0},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}),s=a.data.items.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];n=n.concat(s),r=a.data.next_marker,l=!!r}return[...new Set(n.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+a);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(a){var t;return m(this,void 0,void 0,(function*(){try{const o=this.config.access_token,i=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:a},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(t=n.data)||void 0===t?void 0:t.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:i,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:C.adriveClientId,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class I extends x{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token,i=yield this.getDriveId(),n=t.substring(0,t.lastIndexOf("/")),r=t.substring(t.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(t);const l=yield this.getFolderIdByPath(this.baseFolder+"/"+n),s=yield a.arrayBuffer(),d=s.byteLength,c=yield crypto.subtle.digest("SHA-1",s),u=Array.from(new Uint8Array(c)).map((e=>e.toString(16).padStart(2,"0"))).join(""),m=(e=>{function a(e,a){const t=(65535&e)+(65535&a);return(e>>16)+(a>>16)+(t>>16)<<16|65535&t}function t(e,t,o,i,n,r){return a((l=a(a(t,e),a(i,r)))<<(s=n)|l>>>32-s,o);var l,s}function o(e,a,o,i,n,r,l){return t(a&o|~a&i,e,a,n,r,l)}function i(e,a,o,i,n,r,l){return t(a&i|o&~i,e,a,n,r,l)}function n(e,a,o,i,n,r,l){return t(a^o^i,e,a,n,r,l)}function r(e,a,o,i,n,r,l){return t(o^(a|~i),e,a,n,r,l)}const l=function(e){const a=e.length,t=1+(a+8>>6),o=new Array(16*t).fill(0);for(let t=0;t>2]|=e.charCodeAt(t)<>2]|=128<{let a="";for(let t=0;t<4;t++)a+=("0"+(e>>8*t&255).toString(16)).slice(-2);return a})).join("")})(o),p=Number(BigInt("0x"+m.slice(0,16))%BigInt(d||1)),h=new Uint8Array(s.slice(p,Math.min(p+8,d))),g=btoa(String.fromCharCode(...h)),f=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:i,parent_file_id:l,name:r,type:"file",check_name_mode:"ignore",size:d,content_hash:u,content_hash_name:"sha1",proof_code:g,proof_version:"v1",part_info_list:[{part_number:1}]},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),{file_id:y,upload_id:N,rapid_upload:v,part_info_list:b}=f.data;return v?(console.info("阿里云盘秒传成功"),!0):(yield fetch(b[0].upload_url,{method:"PUT",body:s,headers:{"Content-Length":d.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:i,file_id:y,upload_id:N},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token,o=yield this.getDriveId(),i=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:this.baseFolder+"/"+a},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.file_id,n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});return(yield e.get(n.data.url,{responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}})).data}catch(e){return console.error("Error downloading file:",e),!1}}))))))}}class F{constructor(e){this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFolderIdByPath(a){return m(this,void 0,void 0,(function*(){if(""==a)return"0";const t=this.config.access_token,o=a.split("/");let i="0";for(const a of o){const o=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(o,{headers:{Authorization:`Bearer ${t}`}})).data.entries.find((e=>e.name===a&&"folder"===e.type));if(n)i=n.id;else{const o={name:a,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return i}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;for(;o.startsWith("/");)o=o.substring(1);let i=yield this.getFolderIdByPath(o),n=[],r=0,l=!0;const s=1e3;for(;l;){const a=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:s,offset:r},headers:{Authorization:`Bearer ${t}`}}),o=a.data.entries||[];n=n.concat(o),r+=o.length,l=o.length===s&&a.data.total_count>r}return[...new Set(n.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=a.substring(0,a.lastIndexOf("/")),i=a.substring(a.lastIndexOf("/")+1);let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const r=yield this.getFolderIdByPath(n);if(!r)return!0;const l=`https://api.box.com/2.0/folders/${r}/items?fields=id,name&type=file&limit=1000`,s=(yield e.get(l,{headers:{Authorization:`Bearer ${t}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!s||(yield e.delete(`https://api.box.com/2.0/files/${s.id}`,{headers:{Authorization:`Bearer ${t}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:C.boxClientId,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class R extends F{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token,i=t.substring(0,t.lastIndexOf("/")),n=t.substring(t.lastIndexOf("/")+1);let r=this.baseFolder+"/"+i;for(;r.startsWith("/");)r=r.substring(1);const l=yield this.getFolderIdByPath(r);if(!l)throw new Error("Folder not found");const s=(yield this.listFiles(i)).find((e=>e===n));s&&(yield this.deleteFileWithoutQueue(i+"/"+n));let d=new File([a],n,{lastModified:(new Date).getTime(),type:a.type});const c=new FormData;c.append("file",d),c.append("parent_id",l);const u=yield e.post("https://upload.box.com/api/2.0/files/content",c,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token,o=a.substring(0,a.lastIndexOf("/")),i=a.substring(a.lastIndexOf("/")+1);let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const r=yield this.getFolderIdByPath(n);if(!r)return console.error("Folder not found"),!0;const l=`https://api.box.com/2.0/folders/${r}/items?fields=id,name&type=file&limit=1000`,s=(yield e.get(l,{headers:{Authorization:`Bearer ${t}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!s)return console.error("File not found:",i),!0;const d=yield e({url:`https://api.box.com/2.0/files/${s.id}/content`,method:"get",headers:{Authorization:`Bearer ${t}`},responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return d.status>=300?(console.error("Error occurred during file download:",d),!1):d.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class O{constructor(e){this.config=e,this.taskQueue=new k(3)}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=[],i=!0,n=null;for(;i;){let r;r=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+a,limit:2e3},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});const l=r.data.entries||[];o=o.concat(l),i=r.data.has_more,n=r.data.cursor}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+a},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${C.dropboxClientId}&redirect_uri=${e}`}}class _ extends O{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=t.split("/").pop()||"",n=new File([a],i,{lastModified:(new Date).getTime(),type:a.type});const r=yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+t,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0});return!(r.status>=300)||(console.error("Error occurred during file upload:",r),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token,o=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"post",headers:{Authorization:`Bearer ${t}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+a})},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ${constructor(e){this.folderExistsCache=new Set,this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){var t,o;return m(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);let n=[],r=0;const l=1e3;let s=!0;for(;s;){const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:a?`/${a}`:"/",limit:l,offset:r,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),c=(null===(t=d.data._embedded)||void 0===t?void 0:t.items)||[];n=n.concat(c);const u=(null===(o=d.data._embedded)||void 0===o?void 0:o.total)||0;r+=c.length,s=r({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);const o=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${t}`,"Content-Type":"application/json"},params:{path:a?`/${a}`:"/",permanently:!1}});return 202===o.status||204===o.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(a){var t,o;return m(this,void 0,void 0,(function*(){try{const i=this.config.access_token,n=a.split("/").filter((e=>e.length>0));let r="";for(const a of n)if(r+="/"+a,!this.folderExistsCache.has(r))try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:r}}),this.folderExistsCache.add(r)}catch(a){if(404!==(null===(t=a.response)||void 0===t?void 0:t.status))return console.error("Error checking directory:",a),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(r)}`,null,{headers:{Authorization:`OAuth ${i}`}}),this.folderExistsCache.add(r)}catch(e){if(409!==(null===(o=e.response)||void 0===o?void 0:o.status))return console.error("Error creating directory:",e),!1;this.folderExistsCache.add(r)}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${C.yandexClientId}&redirect_uri=${e}&force_confirm=true`}}class M extends ${constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=this.baseFolder+"/"+t;for(;i.startsWith("/");)i=i.substring(1);const n=i.substring(0,i.lastIndexOf("/"));if(n){if(!(yield this.ensureDirectoryExists(n)))return console.error("Failed to create directory:",n),!1}const r=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:`/${i}`,overwrite:!0}});if(200!==r.status)return console.error("Error getting upload URL:",r),!1;const l=r.data.href;let s=t.split("/").pop()||"",d=new File([a],s,{lastModified:(new Date).getTime(),type:a.type});const c=yield e.put(l,d,{headers:{"Content-Type":a.type||"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;for(;o.startsWith("/");)o=o.substring(1);const i=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${t}`,"Content-Type":"application/json"},params:{path:`/${o}`}});if(200!==i.status)return console.error("Error getting download URL:",i),!1;const n=i.data.href,r=yield e({url:n,method:"get",maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return r.status>=300?(console.error("Error occurred during file download:",r),!1):r.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class U{constructor(e){this.isExp=!1,this.folderIdCache=new Map,this.config=e,this.taskQueue=new k(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFileId(a,t){return m(this,void 0,void 0,(function*(){const o=this.config.access_token,i=`https://www.googleapis.com/drive/v3/files?q=name='${a}'+and+'${t}'+in+parents&fields=files(id,name)`;try{const a=yield e.get(i,{headers:{Authorization:"Bearer "+o}});if(0===a.data.files.length)return"";const t=a.data.files;return t.length>0?t[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(a){return m(this,void 0,void 0,(function*(){a=this.baseFolder+"/"+a;const t=this.config.access_token;if(""===a)return"root";if(this.folderIdCache.has(a))return this.folderIdCache.get(a);const o=a.split("/").filter((e=>""!==e.trim()));let i="root",n="";for(const a of o){if(n=n?n+"/"+a:a,this.folderIdCache.has(n)){i=this.folderIdCache.get(n);continue}let o=yield this.getFolderId(a,i);if(!o){const n={name:a,mimeType:"application/vnd.google-apps.folder",parents:[i]};try{o=(yield e.post("https://www.googleapis.com/drive/v3/files",n,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${a}:`,e),e}}this.folderIdCache.set(n,o),i=o}return i}))}getFolderId(a,t){return m(this,void 0,void 0,(function*(){const o=this.config.access_token,i=`https://www.googleapis.com/drive/v3/files?q=name='${a=encodeURIComponent(a)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${t}'+in+parents&fields=files(id,name)`;try{const a=(yield e.get(i,{headers:{Authorization:`Bearer ${o}`}})).data.files;return a.length>0?a[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=yield this.checkFolder(a),i=[],n="",r=!0;for(;r;){let a=`https://www.googleapis.com/drive/v3/files?q='${o}'+in+parents&fields=nextPageToken,files(id,name,size,mimeType)&pageSize=1000`;n&&(a+=`&pageToken=${n}`);const l=yield e.get(a,{headers:{Authorization:`Bearer ${t}`}}),s=l.data.files||[];i=i.concat(s),n=l.data.nextPageToken,r=!!n}return[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(a){return m(this,void 0,void 0,(function*(){const t=a.split("/").pop()||"",o=a.split("/").slice(0,-1).join("/"),i=yield this.checkFolder(o),n=this.config.access_token,r=yield this.getFileId(t,i);if(""===r)return console.error("File not found:",t),!0;try{const a=yield e.delete(`https://www.googleapis.com/drive/v3/files/${r}`,{headers:{Authorization:`Bearer ${n}`}});return console.error("File deleted:",a),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${C.googleClientId}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class B extends U{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=t.split("/").pop()||"",n=new File([a],i,{lastModified:(new Date).getTime(),type:a.type}),r=t.split(".").pop(),l=p(r||""),s=t.split("/")[0],d=yield this.checkFolder(s),c=yield this.getFileId(i||"",d);const u={mimeType:l,name:i,parents:[d]},m=c?`https://www.googleapis.com/upload/drive/v3/files/${c}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",h=(yield e({method:c?"PATCH":"POST",url:m,data:c?null:JSON.stringify(u),headers:{Authorization:"Bearer "+o,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,g=yield this.getData(n);if(0===Object.keys(g).length)return!1;const f=yield e.put(h,g.data,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/zip","Content-Range":`bytes 0-${g.fileSize-1}/${g.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(f.status>=300)||(console.error("Error occurred during file download:",f),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token;let o=a.split("/").pop(),i=a.split("/")[0],n=yield this.checkFolder(i),r=yield this.getFileId(o||"",n);if(!r)return console.error("File not found:",o),!0;const l=`https://www.googleapis.com/drive/v3/files/${r}?alt=media`,s=yield e.get(l,{headers:{Authorization:"Bearer "+t},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return s.status>=300?(console.error("Error occurred during file download:",s),!1):s.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getData(e){return m(this,void 0,void 0,(function*(){return e?new Promise(((a,t)=>{const o=new FileReader;o.onload=t=>a({fileName:e.name,mimeType:e.type,fileSize:e.size,data:t.target.result}),o.onerror=e=>t(e),o.readAsArrayBuffer(e)})):{}}))}}class z{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=2){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getStorage(){return m(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new a({email:e,password:t,userAgent:"KoodoReader/1.0"}).ready,this.storage}))}getRoot(){return m(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;if(""===this.baseFolder)return this.root=e,this.root;let a=e.children.find((e=>e.name===this.baseFolder&&e.directory));return a||(a=yield e.mkdir(this.baseFolder)),this.root=a,this.root}))}createFolder(e,a){return m(this,void 0,void 0,(function*(){const t=`${e.nodeId}_${a}`;if(this.folderCreationLocks.has(t))return yield this.folderCreationLocks.get(t);const o=(()=>m(this,void 0,void 0,(function*(){try{let t=e.children.find((e=>e.name===a&&e.directory));return t||(t=yield e.mkdir(a),t)}finally{this.folderCreationLocks.delete(t)}})))();return this.folderCreationLocks.set(t,o),yield o}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){try{let a=yield this.getRoot();if(e){const t=e.split("/").filter((e=>e));for(const e of t){const t=a.children.find((a=>a.name===e&&a.directory));if(!t)return[];a=t}}return a.children.map((e=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return m(this,void 0,void 0,(function*(){try{let a=yield this.getRoot();const t=e.split("/"),o=t.pop();for(const e of t){if(!e)continue;const t=a.children.find((a=>a.name===e&&a.directory));if(!t)return!0;a=t}const i=a.children.find((e=>e.name===o&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class D extends z{constructor(e){super(e)}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const i=a.split("/"),n=i.pop()||"";for(const e of i){if(!e)continue;let a=o.children.find((a=>a.name===e&&a.directory));a||(a=yield this.createFolder(o,e)),o=a}const r=new File([e],n,{lastModified:(new Date).getTime(),type:e.type}),l=yield e.arrayBuffer(),s=new Uint8Array(l),d=t.from(s),c=o.children.find((e=>e.name===n&&!e.directory));return c&&(yield c.delete()),yield o.upload({name:n,size:r.size},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let a=yield this.getRoot();const t=e.split("/"),o=t.pop()||"";for(const e of t){if(!e)continue;const t=a.children.find((a=>a.name===e&&a.directory));if(!t)return!0;a=t}const i=a.children.find((e=>e.name===o&&!e.directory));if(!i)return!0;const n=yield i.downloadBuffer();return this.taskQueue.setDownloadedSize(n.size),n.buffer}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class L{constructor(e){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.taskQueue=new k(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);let o,i=[];if(""===a)o=`${this.baseUrl}/children`;else{const e=encodeURIComponent(a);o=`${this.baseUrl}:/${e}:/children`}for(;o;){const a=yield e.get(o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(a.status>=300)break;const n=a.data.value||[];i=i.concat(n),o=a.data["@odata.nextLink"]||""}return[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);const o=yield e.delete(`${this.baseUrl}:/${a}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${C.microsoftClientId}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${e}`}}class P extends L{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=t.split("/").pop()||"",n=new File([a],i,{lastModified:(new Date).getTime(),type:a.type}),r=this.baseFolder+"/"+t;for(;r.startsWith("/");)r=r.substring(1);const l=this.baseUrl+":/"+r+":/createUploadSession",s=yield e.post(l,null,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let d=n.size;const c=n.type,u=s.data.uploadUrl,m=yield e.put(u,n,{headers:{"Content-Type":c,"Content-Range":`bytes 0-${d-1}/${d}`},maxContentLength:1/0,maxBodyLength:1/0});return!(m.status>=300)||(console.error("Error occurred during file download:",m),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;for(;o.startsWith("/");)o=o.substring(1);const i=`${this.baseUrl}:/${o}:/content`,n=yield e.get(i,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+t},maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error occurred during file download:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class j{downloadFile(e,a){return m(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return m(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}getAuthUrl(){return""}}class K{constructor(e){this.baseUrl="https://api.pcloud.com",this.config=e,this.taskQueue=new k(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}checkFolderExists(a,t){return m(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:t,path:`/${a}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(a,t){return m(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/createfolderifnotexists`,{params:{access_token:t,path:`/${a}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:t,path:"/"+a,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/deletefile`,{params:{access_token:t,path:"/"+a}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${C.pcloudClientId}&response_type=code&redirect_uri=${e}`}}class H extends K{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.refresh_token,i=t.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,o))){if(!(yield this.createFolder(i,o)))return!1}let n=t.split("/").pop()||"",r=new File([a],n,{lastModified:(new Date).getTime(),type:a.type});const l=new FormData;l.append("file",r);const s=yield e.post(`${this.baseUrl}/uploadfile`,l,{params:{access_token:o,path:`/${i}`,renew:1},maxContentLength:1/0,maxBodyLength:1/0});return 0===s.data.result||(console.error("Error uploading file:",s.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/getfilelink`,{params:{access_token:t,path:`/${a}`}});if(0!==o.data.result)return console.error("Error getting file link:",o.data),!0;const i=`https://${o.data.hosts[0]}${o.data.path}`,n=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class J{constructor(e){this.config=e,this.taskQueue=new k(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=0){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}shouldUsePathStyle(){try{if(this.config.forcePathStyle&&"no"!==this.config.forcePathStyle)return!0;let e=this.config.endpoint;const a=new URL(e),t=a.hostname,o=/^(\d{1,3}\.){3}\d{1,3}$/.test(t),i=""!==a.port;return!o&&i}catch(e){return!0}}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){let{endpoint:a,region:t,bucketName:n,accessKeyId:r,secretAccessKey:l,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;let d=s+"/"+e;for(;d.startsWith("/");)d=d.substring(1);""===d||d.endsWith("/")||(d+="/");const c=new o({endpoint:a,region:t,credentials:{accessKeyId:r,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle()});try{let e,a=[],t=[],o=!0;for(;o;){const r=yield c.send(new i({Bucket:n,Prefix:d,Delimiter:"/",ContinuationToken:e}));r.Contents&&(a=a.concat(r.Contents)),r.CommonPrefixes&&(t=t.concat(r.CommonPrefixes)),e=r.NextContinuationToken,o=!!e}let r=[];return a.forEach((e=>{if(!e.Key.endsWith("/")){const a=e.Key.substring(d.length);a.includes("/")||r.push({name:a,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),t.forEach((e=>{const a=e.Prefix.substring(d.length).replace(/\/$/,"");a&&r.push({name:a,size:0,type:"folder",modified:""})})),r}catch(e){return console.error(e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){let{endpoint:a,region:t,bucketName:i,accessKeyId:r,secretAccessKey:l,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const d=new o({endpoint:a,region:t,credentials:{accessKeyId:r,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield d.send(new n({Bucket:i,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class W extends J{constructor(e){super(e)}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:n,accessKeyId:l,secretAccessKey:s,dir:d}=this.config;const c=new o({endpoint:t,region:i,credentials:{accessKeyId:l,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let u=d+"/"+a;for(;u.startsWith("/");)u=u.substring(1);try{let a=yield c.send(new r({Bucket:n,Key:u,Body:e}));return 200===a.$metadata.httpStatusCode||(console.error("Error uploading file:",a),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:a,region:t,bucketName:i,accessKeyId:n,secretAccessKey:r,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const d=new o({endpoint:a,region:t,credentials:{accessKeyId:n,secretAccessKey:r},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{const e=yield d.send(new l({Bucket:i,Key:c}));if(!e.Body)return console.error("No response body"),!1;const a=yield e.Body.transformToByteArray();return this.taskQueue.setDownloadedSize(a.length),a.buffer}catch(a){return console.error("Error downloading file:",a,e),!1}}))))))}))}}class q{constructor(e){this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=this.baseFolder;a&&""!==a.trim()&&(o=o+"/"+a),o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));let i=[],n=0;const r=1e3;for(;;){const a=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:t,dir:"/"+o,start:n,limit:r,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(a.status>=300||0!==a.data.errno){console.error("百度网盘API错误:",a.data);break}const l=a.data.list||[];if(0===l.length)break;if(i=i.concat(l),l.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path,fs_id:e.fs_id})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));const i=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+o])}),n=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${t}&opera=delete`,i.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==n.data.errno)return console.error("百度网盘删除文件API错误:",n.data),-9===n.data.errno?console.error("文件不存在"):111===n.data.errno?console.error("有其他异步任务正在执行"):-7===n.data.errno&&console.error("文件名非法"),!1;const r=n.data.info||[];for(const e of r)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${C.duboxClientId}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}const G=4194304;class Q extends q{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){var o;try{const o=this.config.access_token;let i=this.baseFolder+"/"+t;i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));const n=yield a.arrayBuffer(),r=n.byteLength,l=new Uint8Array(n),{contentMd5:s,sliceMd5:d,blockList:c}=this.calculateFileMd5(l,r),u=new URLSearchParams({path:"/"+i,size:r.toString(),isdir:"0",autoinit:"1",rtype:"3",block_list:JSON.stringify(c),"content-md5":s,"slice-md5":d,local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),m=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=${o}`,u.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==m.data.errno)return console.error("预上传失败:",m.data),!1;const p=m.data.uploadid,h=m.data.block_list||[];if(0===h.length)return!0;const g=yield this.getUploadDomain(o,"/"+i,p);if(!g)return console.error("获取上传域名失败"),!1;for(const a of h){const t=a*G,n=Math.min(G,r-t),s=l.slice(t,t+n),d=new FormData;d.append("file",new Blob([s],{type:"application/octet-stream"}),`chunk_${a}`);const u=`${g}/rest/2.0/pcs/superfile2?method=upload&access_token=${o}&type=tmpfile&path=${encodeURIComponent("/"+i)}&uploadid=${p}&partseq=${a}`,m=yield e.post(u,d,{headers:{"User-Agent":"pan.baidu.com"},maxContentLength:1/0,maxBodyLength:1/0,timeout:0});if(m.status>=300)throw new Error(`分片上传失败: ${JSON.stringify(m.data)}`);const h=m.data.md5,f=c[a];h&&h!==f&&console.warn(`分片 ${a} MD5不匹配: 期望 ${f}, 实际 ${h}`)}const f=new URLSearchParams({path:"/"+i,size:r.toString(),isdir:"0",block_list:JSON.stringify(c),uploadid:p,rtype:"3",local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),y=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=${o}`,f.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});return 0===y.data.errno||(console.error("创建文件失败:",y.data),!1)}catch(e){return console.error("文件上传过程中发生错误:",(null===(o=e.response)||void 0===o?void 0:o.data)||e.message||e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){var t;this.taskQueue.setDownloadedSize(0);try{const o=this.config.access_token;let i=this.baseFolder+"/"+a;i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));const n=yield this.listFileInfos(a.substring(0,a.lastIndexOf("/"))),r=i.split("/").pop(),l=n.find((e=>e.name===r));if(!l)return console.error("文件不存在:",a),!1;const s=yield e.get("https://pan.baidu.com/rest/2.0/xpan/multimedia",{params:{method:"filemetas",access_token:o,fsids:JSON.stringify([l.fs_id]),dlink:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==s.data.errno||!(null===(t=s.data.list)||void 0===t?void 0:t[0]))return console.error("获取下载链接失败:",s.data),!1;const d=s.data.list[0].dlink;return(yield e.get(d,{responseType:"arraybuffer",params:{access_token:o},headers:{"User-Agent":"pan.baidu.com"},onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}})).data}catch(e){return console.error("下载文件时发生错误:",e),!1}}))))))}))}getUploadDomain(a,t,o){return m(this,void 0,void 0,(function*(){try{const i=yield e.get("https://d.pcs.baidu.com/rest/2.0/pcs/file",{params:{method:"locateupload",appid:"250528",access_token:a,path:t,uploadid:o,upload_version:"2.0"},headers:{"User-Agent":"pan.baidu.com"}});if(0!==i.data.error_code)return console.error("获取上传域名失败:",i.data),null;const n=i.data.servers||[],r=n.find((e=>e.server.startsWith("https://")));return r?r.server:n.length>0?n[0].server:(console.error("没有可用的上传服务器"),null)}catch(e){return console.error("获取上传域名时出错:",e),null}}))}calculateFileMd5(e,a){const t=[];let o="",i=0;for(;i=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getUploadCredentials(a){return m(this,void 0,void 0,(function*(){try{const t=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${a}`}});return t.status>=300||!t.data.state?(console.error("Error getting upload credentials:",t.data),null):t.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,a,t=new Date(Date.now()+36e5)){const o={expiration:t.toISOString(),conditions:[{bucket:e},{key:a},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(o)}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${C.yiyiwuClientId}&response_type=code&redirect_uri=${e}`}}class X extends Y{constructor(e){super(e)}sha1Hex(e){return m(this,void 0,void 0,(function*(){const a=yield crypto.subtle.digest("SHA-1",e);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}calculateFileSha1(e){return m(this,void 0,void 0,(function*(){try{const a=yield e.arrayBuffer();return this.sha1Hex(a)}catch(e){return console.error("Error calculating file SHA1:",e),""}}))}calculatePreSha1(e){return m(this,void 0,void 0,(function*(){try{const a=e.slice(0,131072),t=yield a.arrayBuffer();return this.sha1Hex(t)}catch(e){return console.error("Error calculating pre SHA1:",e),""}}))}calculateOSSSignature(e,a){const t=s.enc.Base64.stringify(s.enc.Utf8.parse(a));return s.HmacSHA1(t,e).toString(s.enc.Base64)}handleSecondAuth(e,a,t,o,i,n,r,l){return m(this,void 0,void 0,(function*(){try{if(!a.sign_check)return console.error("No sign_check provided for second authentication"),null;const[s,d]=a.sign_check.split("-"),c=parseInt(s),u=parseInt(d),m=t.slice(c,u+1),p=yield m.arrayBuffer(),h=(yield this.sha1Hex(p)).toUpperCase();return yield this.initializeUpload(e,o,i,n,r,l,a.sign_key,h,a.pick_code)}catch(e){return console.error("Error during second authentication:",e),null}}))}uploadToObjectStorage(a,t,o,i){var n;return m(this,void 0,void 0,(function*(){try{const n=i.endpoint,r=o.bucket,l=o.object;let s;if(n.includes(r))s=n;else{s=`https://${r}.${n.replace(/^https?:\/\//,"")}`}const d=this.generateOSSPolicy(r,l),c=this.calculateOSSSignature(i.AccessKeySecret,d),u=btoa(d),m=new FormData;if(m.append("key",l),m.append("policy",u),m.append("OSSAccessKeyId",i.AccessKeyId),m.append("signature",c),m.append("x-oss-security-token",i.SecurityToken),m.append("success_action_status","200"),o.callback&&o.callback.callback){const e=btoa(o.callback.callback);if(m.append("callback",e),o.callback.callback_var){const e=JSON.parse(o.callback.callback_var);for(const[a,t]of Object.entries(e))m.append(a,String(t))}}const p=new File([a],t,{type:a.type});m.append("file",p);const h=yield e.post(s,m,{maxContentLength:1/0,maxBodyLength:1/0});return 200===h.status||204===h.status||(console.error("Upload failed with status:",h.status),!1)}catch(e){return console.error("Error uploading file via REST API:",(null===(n=e.response)||void 0===n?void 0:n.data)||e.message||e),!1}}))}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){var t;try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;o.startsWith("/")||(o="/"+o);const i=e.size,n=yield this.calculateFileSha1(e),r=yield this.calculatePreSha1(e),l=a.split("/").pop()||a,s=o.substring(0,o.lastIndexOf("/"))||"/";let d=yield this.getFolderInfo(s,!0),c="0";if(d)c=d.file_id;else{let e=yield this.createFolder(s);if(!e)return console.error("Failed to create folder:",s),!1;c=e}yield this.deleteFileWithoutQueue(a);let u=yield this.initializeUpload(c,l,i,n,r,t);if(!u)return console.error("Failed to initialize upload"),!1;if((6===u.status||7===u.status||8===u.status)&&(u=yield this.handleSecondAuth(c,u,e,l,i,n,r,t),!u))return console.error("Second authentication failed"),!1;if(2===u.status)return console.info(`File ${a} uploaded successfully via instant upload.`),!0;const m=yield this.getUploadCredentials(t);if(!m)return console.error("Failed to get upload credentials"),!1;return(yield this.uploadToObjectStorage(e,l,u,m))?(console.info(`File ${a} uploaded successfully.`),!0):(console.error("Failed to upload to object storage"),!1)}catch(e){return console.error("Error occurred during file upload:",(null===(t=e.response)||void 0===t?void 0:t.data)||e.message||e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let t=this.baseFolder+"/"+a;t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t);const o=yield this.getFolderInfo(t,!1);if(!o||!o.pick_code)return console.error("Failed to get file info or pick_code for:",a),!1;const i=yield this.getFileDownloadUrl(o.pick_code);if(!i)return console.error("Failed to get download URL for:",a),!1;const n=yield e.get(i.url,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}initializeUpload(a,t,o,i,n,r,l,s,d){return m(this,void 0,void 0,(function*(){try{const c=new FormData;c.append("file_name",t),c.append("file_size",o.toString()),a?c.append("target","U_1_"+a):c.append("target","U_1_0"),c.append("fileid",i),c.append("preid",n),c.append("topupload","0"),d&&c.append("pick_code",d),l&&c.append("sign_key",l),s&&c.append("sign_val",s);const u=yield e.post(`${this.baseUrl}/open/upload/init`,c,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"multipart/form-data"}});return u.status>=300||!u.data.state?(console.error("Error initializing upload:",u.data),null):u.data.data}catch(e){return console.error("Error occurred during upload initialization:",e),null}}))}createFolder(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=a.replace(/^\/+|\/+$/g,"");if(!o)return"";const i=o.split("/");let n="",r="0";for(const a of i){n=n?`${n}/${a}`:a;const o=yield this.getFolderInfo(n,!0);if(o&&o.file_id)r=o.file_id;else{const o=new FormData;o.append("pid",r),o.append("file_name",a);const i=yield e.post(`${this.baseUrl}/open/folder/add`,o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});if(i.status>=300||!i.data.state)return console.error("Error creating folder:",i.data),"";r=i.data.data.file_id}}return r}catch(e){return console.error("Error occurred during folder creation:",e),""}}))}getFolderInfo(a,t){return m(this,void 0,void 0,(function*(){if(""===a||"/"===a)return{file_id:"0"};a.startsWith("/")||(a="/"+a);try{const t=this.config.access_token,o=new FormData;o.append("path",a);const i=yield e.post(`${this.baseUrl}/open/folder/get_info`,o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});return i.status>=300||!i.data.state||0===i.data.data.length?(console.error("Error getting file info:",i.data),null):i.data.data}catch(e){return console.error("Error occurred during get file info:",e),null}}))}getFileDownloadUrl(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=new FormData;o.append("pick_code",a);const i=yield e.post(`${this.baseUrl}/open/ufile/downurl`,o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});if(i.status>=300)return console.error("Error getting download URL:",i.data),null;const n=i.data.data,r=Object.keys(n)[0];return r&&n[r]?n[r].url:(console.error("No file data found in download URL response"),null)}catch(e){return console.error("Error occurred during get download URL:",e.message||e),null}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;(a=this.baseFolder+"/"+a).startsWith("/")||(a="/"+a);let o=[],i=0;const n=1150;let r=!0,l=yield this.getFolderInfo(a,!0),s="";if(l)s=l.file_id;else{let e=yield this.createFolder(a);if(!e)return console.error("Failed to create folder:",a),[];s=e}if(!s)return console.error("Failed to get or create folder ID:",a),[];let d=s;for(;r;){const a={offset:i,limit:n,cur:1,show_dir:1};d&&(a.cid=d);const l=yield e.get(`${this.baseUrl}/open/ufile/files`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},params:a});if(l.status>=300)break;const s=l.data.data||[];o=o.concat(s),s.length({name:e.fn,size:e.fs||0,type:"0"===e.fc?"folder":"file",modified:new Date(1e3*e.upt).toISOString()})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;a=this.baseFolder+"/"+a;const o=yield this.getFolderInfo(a,!1);if(!o)return!0;const i=new FormData;i.append("file_ids",o.file_id);const n=yield e.post(`${this.baseUrl}/open/ufile/delete`,i,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});return!(n.status>=300||!n.data.state)||(console.error("Error deleting file:",n),!1)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}}class V{constructor(e){let{username:a,password:t,url:o,dir:i,AuthType:n,createClient:r}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,i=i&&"KoodoReader"===this.baseFolder?i:this.baseFolder,this.username=a,this.password=t,this.url=o,this.dir=i,this.taskQueue=new k(5),this.AuthType=n,this.createClient=r}getClient(){return m(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(a){return m(this,void 0,void 0,(function*(){try{const t=yield e.head(a,{maxRedirects:0,validateStatus:()=>!0,timeout:5e3});return t.request&&t.request.responseURL&&t.request.responseURL!==a?t.request.responseURL:t.status>=300&&t.status<400&&t.headers.location?t.headers.location:a}catch(e){return console.info("Error handling URL redirection:",e),a}}))}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){const a=yield this.getClient();try{const t=a.getDirectoryContents(this.dir+"/"+e),o=new Promise(((e,a)=>{setTimeout((()=>a(new Error("WebDAV list directory timeout"))),5e3)}));return(yield Promise.race([t,o])).filter((a=>"."!==a.filename&&".."!==a.filename&&a.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}catch(t){return t.response&&404===t.response.status&&(yield a.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",t),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){const a=yield this.getClient();try{return yield a.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return m(this,void 0,void 0,(function*(){let a=yield this.getClient();try{const t=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let o="";for(const e of t)o=o?`${o}/${e}`:e,(yield a.exists(`/${o}`))||(yield a.createDirectory(`/${o}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class Z extends V{constructor(e){super(Object.assign(Object.assign({},e),{AuthType:d,createClient:c}))}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{let o=this.dir+"/"+t,i=yield this.getClient();const n=i.exists(o.substring(0,o.lastIndexOf("/"))),r=new Promise(((e,a)=>{setTimeout((()=>a(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([n,r]))&&(yield this.ensureDirectoryExists(o.substring(0,o.lastIndexOf("/"))));let l=t.split("/").pop()||"",s=new File([a],l,{lastModified:(new Date).getTime(),type:a.type}),d=i.getFileUploadLink(this.dir+"/"+t);const c=new URL(d);c.search="",d=c.toString();const u=btoa(this.username+":"+this.password),m=yield e.put(d,s,{headers:{Authorization:"Basic "+u},maxContentLength:1/0,maxBodyLength:1/0});return!(m.status>=300)||(console.error("Error occurred during file upload:",m),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===a.indexOf("."))return new ArrayBuffer(0);try{const t=btoa(this.username+":"+this.password);let o=this.url.endsWith("/")?this.url:this.url+"/",i=this.dir.startsWith("/")?this.dir.substring(1):this.dir;const n=yield e({url:o+i+"/"+a,method:"get",headers:{Authorization:"Basic "+t},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error occurred during file download:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ee{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.taskQueue=new k(3)}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:a},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:a.split("/").slice(0,-1).join("/")||"",filename:a.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}class ae extends ee{constructor(e){super(e)}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=t.split("/").pop()||"",i=t.substring(0,t.lastIndexOf("/"))||"";let n=this.listFiles("");const r=new Promise(((e,a)=>{setTimeout((()=>a(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([n,r]);let l=new File([a],o,{lastModified:(new Date).getTime(),type:a.type});const s=new FormData;s.append("file",l);const d=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(i)}`,s,{headers:{Authorization:this.getAuthHeader(),"Content-Type":"multipart/form-data"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=a.split("/").pop()||"",o=a.substring(0,a.lastIndexOf("/"))||"",i=yield e({url:`${this.url}/download`,method:"GET",params:{dir:o,filename:t},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const te=["book","config","cover","font"];class oe{constructor(e,a){this.type=e,this.remote="dropbox"===e?new _(a):"microsoft"===e?new P(a):"google"===e?new B(a):"microsoft_exp"===e?new P(Object.assign(Object.assign({},a),{isExp:!0})):"google_exp"===e?new B(Object.assign(Object.assign({},a),{isExp:!0})):"s3compatible"===e?new W(a):"webdav"===e?new Z(a):"docker"===e?new ae(a):"boxnet"===e?new R(a):"mega"===e?new D(a):"adrive"===e?new I(a):"pcloud"===e?new H(a):"dubox"===e?new Q(a):"yandex"===e?new M(a):"yiyiwu"===e?new X(a):new j}downloadFile(e,a){return m(this,void 0,void 0,(function*(){if("cover"!==a){if(!(yield this.listFiles(a)).find((a=>e.indexOf(a)>-1)))return!1}return yield this.remote.downloadFile(a+"/"+e)}))}uploadFile(e,a,t){return m(this,void 0,void 0,(function*(){return 0===t.size||(yield this.remote.uploadFile(t,a+"/"+e))}))}deleteFile(e,a){return m(this,void 0,void 0,(function*(){return!(yield this.listFiles(a)).find((a=>e.indexOf(a)>-1))||(yield this.remote.deleteFile(a+"/"+e))}))}listFiles(e){return m(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}isExist(e,a){return m(this,void 0,void 0,(function*(){return(yield this.listFiles(a)).find((a=>-1!==a.indexOf(e)))}))}downloadAllFiles(){return m(this,void 0,void 0,(function*(){for(let e of te){let a=yield this.listFiles(e);for(let t of a)yield this.downloadFile(t,e)}}))}getAuthUrl(e){return this.remote.getAuthUrl?this.remote.getAuthUrl(e):""}getStats(){return this.remote.taskQueue.getStats()}clearQueue(){return this.remote.taskQueue.clearQueue()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const ie={words:['ALTER TABLE words ADD COLUMN "sentence" text']},ne={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},re={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},le={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function se(e){for(const a in e)e.hasOwnProperty(a)&&(e[`temp-${a}`]=e[a]);return e}const de={notes:e=>{let a=Object.assign({},e);return a.date=JSON.parse(e.date),a.tag=JSON.parse(e.tag),a},bookmarks:e=>e,books:e=>e,plugins:e=>{let a=Object.assign({},e);return e.autoValue||delete a.autoValue,e.langList?a.langList=JSON.parse(e.langList):delete a.langList,e.voiceList?a.voiceList=JSON.parse(e.voiceList):delete a.voiceList,a.config=JSON.parse(e.config),a},words:e=>{let a=Object.assign({},e);return a.date=JSON.parse(e.date),void 0===a.sentence&&(a.sentence=""),a}};var ce={sqlStatement:{createTableStatement:se({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "sentence" text,\n "chapter" text\n );\n '}),migrateStatement:se(ie),getAllStatement:se({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:se({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:se({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:se({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, sentence, chapter) VALUES (@key, @bookKey, @date, @word, @sentence, @chapter)"}),deleteAllStatement:se({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:se({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, sentence = @sentence, chapter = @chapter WHERE key = @key"}),deleteStatement:se({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:se({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:se(ne),getByBookKeyStatement:se(re),getByBookKeysStatement:se({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),getKeysStatement:se({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:se({notes:(e,a,t,o)=>`SELECT * FROM notes ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,bookmarks:(e,a,t,o)=>`SELECT * FROM bookmarks ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,books:(e,a,t,o)=>`SELECT * FROM books ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,plugins:(e,a,t,o)=>`SELECT * FROM plugins ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,words:(e,a,t,o)=>`SELECT * FROM words ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`}),getByKeysStatement:se({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`}),deleteByBookKeyStatement:se(le)},jsonToSqlite:se({notes:e=>{let a=Object.assign({},e);return a.date=JSON.stringify(e.date),a.tag=JSON.stringify(e.tag),a},bookmarks:e=>e,books:e=>{let a=Object.assign({},e);return a.page=e.page||0,a},plugins:e=>{let a=Object.assign({},e);return e.autoValue||(a.autoValue=null),e.langList?a.langList=JSON.stringify(e.langList):a.langList=null,e.voiceList?a.voiceList=JSON.stringify(e.voiceList):a.voiceList=null,a.config=JSON.stringify(e.config),a},words:e=>{let a=Object.assign({},e);return a.date=JSON.stringify(e.date),void 0===a.sentence&&(a.sentence=""),a}}),sqliteToJson:se(de)};const ue=E.cloudUrl,me=E.cloudCNUrl;class pe{constructor(e,a,t){this.TokenService=e,this.ConfigService=a,this.baseUrl="china"===t?me:ue,this.serverRegion=t,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}refreshUserToken(){return m(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let a=(yield e.post(this.baseUrl+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===a.code&&(yield this.TokenService.setToken("access_token",a.data.access_token),yield this.TokenService.setToken("refresh_token",a.data.refresh_token),yield this.TokenService.setToken("expires_at",(1e3*a.data.expires_at).toString()),this.accessToken=a.data.access_token,this.refreshToken=a.data.refresh_token,this.expiresAt=1e3*a.data.expires_at),a}))}requestWithRetry(e){return m(this,void 0,void 0,(function*(){return pe.requestQueue||(pe.requestQueue=[]),new Promise(((a,t)=>{pe.requestQueue.push({config:e,resolve:a,reject:t}),pe.processingQueue||this.processQueue()}))}))}isTokenValid(){return m(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return m(this,void 0,void 0,(function*(){if(!pe.processingQueue){pe.processingQueue=!0;try{for(;pe.requestQueue.length>0;){const e=pe.requestQueue.shift();try{let a=yield this.executeRequest(e.config);e.resolve(a)}catch(a){e.reject(a)}}}finally{pe.processingQueue=!1}}}))}executeRequest(a){return m(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let t="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);if(a.baseURL=this.baseUrl,a.headers)a.headers.Authorization="Bearer "+this.accessToken,a.headers["X-Request-ID"]=t;else{let e=this.ConfigService.getItem("appVersion"),o=this.ConfigService.getItem("appPlatform");a.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":t,"X-App-Version":e||"1.0.0","X-App-Platform":o||"web"}}let o=(yield e(a)).data;if(402===o.code){let t=yield this.refreshUserToken();if(200===t.code){return a.headers=a.headers||{},a.headers.Authorization="Bearer "+this.accessToken,(yield e(a)).data}return t}return 200!==o.code&&console.error("Request error:",o),o}catch(e){return console.error("Request execution error:",e),"Network Error"===e.message?{code:503,message:"network error",data:null,msg:"Network error, please try again later. 网络错误,请稍后再试。"}:{code:500,message:e.message||"Unknown error",msg:e.message||"Unknown error",data:null}}}))}requestWithStream(e,a,t){return m(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>m(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let o=this.accessToken||"",i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,r)=>{let l=this.ConfigService.getItem("appVersion"),s=this.ConfigService.getItem("appPlatform");const d=new t(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":i,"X-App-Version":l||"1.0.0","X-App-Platform":s||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});d.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),d.addEventListener("message",(e=>m(this,void 0,void 0,(function*(){if(!e.data)return;const t=JSON.parse(e.data);t.done?(d.close(),n(t)):a(t.data)})))),d.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);a(t.data),n(t),d.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,a){return m(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>m(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let t=this.accessToken||"",o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,n)=>m(this,void 0,void 0,(function*(){let n=this.ConfigService.getItem("appVersion"),r=this.ConfigService.getItem("appPlatform");var l=new u(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+t,"X-Request-ID":o,"X-App-Version":n||"1.0.0","X-App-Platform":r||"web"},payload:JSON.stringify(e.data),method:"POST"});l.addEventListener("message",(e=>m(this,void 0,void 0,(function*(){if(!e.data)return;const t=JSON.parse(e.data);t.done?(l.close(),i(t)):a(t.data)})))),l.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),l.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);a(t.data),i(t),l.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}pe.processingQueue=!1,pe.requestQueue=[];class he extends pe{constructor(e,a,t){super(e,a,t)}getTransStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getTransFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithFetch(t,a)}))}getDictionary(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_llm_dict",data:e};return yield this.requestWithRetry(a)}))}getBatchTrans(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_llm_batch_trans",data:e};return yield this.requestWithRetry(a)}))}getSplitSentence(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_llm_split_sentence",data:e};return yield this.requestWithRetry(a)}))}getAnswerStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getAnswerFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithFetch(t,a)}))}getSummaryStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getSummaryFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithFetch(t,a)}))}getDictionaryStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_dict_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getDictionaryFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_dict_stream",data:e};return yield this.requestWithFetch(t,a)}))}getGoogleFont(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_google_font",data:e};return yield this.requestWithRetry(a)}))}sendToKindle(e,a){return m(this,void 0,void 0,(function*(){let t=new FormData;t.append("file",e.file),t.append("email",e.email),t.append("file_name",e.fileName);const o={method:"post",url:"/api/v1/pro/reader/send_to_kindle",headers:{"Content-Type":"multipart/form-data"},data:t,onUploadProgress:a?t=>{var o;const i=t.total||(null===(o=e.file)||void 0===o?void 0:o.size)||0;i>0&&a(Math.min(t.loaded/i,1))}:void 0};return yield this.requestWithRetry(o)}))}detectLanguage(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/detect_language",data:e};return yield this.requestWithRetry(a)}))}getTTSAudio(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_tts_audio",data:e};return yield this.executeRequest(a)}))}getOcrResult(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_ocr_result",data:e};return yield this.executeRequest(a)}))}getOcrResultV2(e){return m(this,void 0,void 0,(function*(){let a=new FormData;a.append("file",e.file);const t={method:"post",url:"/api/v1/pro/reader/get_ocr_result_v2",headers:{"Content-Type":"multipart/form-data"},data:a};return yield this.executeRequest(t)}))}analyzeText(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/analyze_text",data:e};return yield this.requestWithRetry(a)}))}getBookMetadata(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_book_metadata",data:e};return yield this.requestWithRetry(a)}))}analyzeBookTitle(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/analyze_book_title",data:e};return yield this.requestWithRetry(a)}))}}class ge extends pe{constructor(e,a,t){super(e,a,t),this.serverRegion=t}encryptToken(e){return m(this,void 0,void 0,(function*(){let a=e.token,t=v.encode(a),{extracted:o,remaining:i}=function(e){let a="",t="",o=[],i=1;for(;i<=e.length;)o.push(i-1),i*=2;for(let i=0;i-1){let t=a.split("#");e.encrypted_token=t[1]}const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let o=yield this.requestWithRetry(t);if(a.indexOf("#")>-1&&o.data&&o.data.token){let e=a.split("#"),t=function(e,a){let t="",o=[],i=1,n=e.length+a.length;for(;i<=n;)o.push(i-1),i*=2;let r=0,l=0;for(let i=0;i{let o="";if("github"===e?o=`https://github.com/login/oauth/authorize?client_id=${C.githubClientId}&redirect_uri=${t}&scope=${T.github.scopes.join(" ")}&response_type=code`:"google"===e?o=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${t}&prompt=consent&response_type=code&client_id=${C.googleClientId}&scope=${T.google.scopes.join(" ")}&access_type=offline`:"facebook"===e?o=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${C.facebookClientId}&redirect_uri=${t}&scope=&response_type=code`:"microsoft"===e&&(o=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${C.microsoftClientId}&scope=${T.microsoft.scopes.join(" ")}&response_type=code&redirect_uri=${t}`),"manual"===a)return o;let i=JSON.stringify({deeplink:"desktop"===a?"koodo-reader://callback":"browser"===a?`${C.callbackUrl}#/login`:"",service:e});return`${o}&state=${"state|"+encodeURIComponent(i)}`}};class Ne{static CompareDatabase(e,a,t){return m(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.bookmarks"))),r=Object.keys(e).filter((e=>e.startsWith("database.sqlite.plugins"))),l=Object.keys(e).filter((e=>e.startsWith("database.sqlite.words"))),s=Object.keys(a).filter((e=>e.startsWith("database.sqlite.books"))),d=Object.keys(a).filter((e=>e.startsWith("database.sqlite.notes"))),c=Object.keys(a).filter((e=>e.startsWith("database.sqlite.bookmarks"))),u=Object.keys(a).filter((e=>e.startsWith("database.sqlite.plugins"))),m=Object.keys(a).filter((e=>e.startsWith("database.sqlite.words"))),p={books:Array.from(new Set(o.concat(s))),notes:Array.from(new Set(i.concat(d))),bookmarks:Array.from(new Set(n.concat(c))),plugins:Array.from(new Set(r.concat(u))),words:Array.from(new Set(l.concat(m)))},h={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},g=["books","notes","bookmarks","plugins","words"];for(let o of g)for(let i of p[o]){let n=i.split(".")[3],r=e[i],l=a[i];r?l?("save"===l.operation&&("update"!==r.operation&&"delete"!==r.operation||h[o].upload.push(n)),"delete"===l.operation&&("save"===r.operation&&(h[o].delete.push(n),e[i]=l),"update"===r.operation&&(r.timel.time&&(h[o].conflict.push(n),"cloud"===t?(h[o].delete.push(n),e[i]=l):h[o].upload.push(n))),r.operation),"update"===l.operation&&("save"===r.operation&&(h[o].update.push(n),e[i]=l),"update"===r.operation&&(r.timel.time&&h[o].upload.push(n)),"delete"===r.operation&&(r.timel.time&&h[o].upload.push(n)))):h[o].upload.push(n):(h[o].save.push(n),e[i]=l)}return{compareResult:h,syncRecords:e}}))}static CompareConfig(e,a,t){return m(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),n=Object.keys(e).filter((e=>e.startsWith("config.objectConfig"))),r=Object.keys(e).filter((e=>e.startsWith("config.mapConfig"))),l=Object.keys(a).filter((e=>e.startsWith("config.readerConfig"))),s=Object.keys(a).filter((e=>e.startsWith("config.listConfig"))),d=Object.keys(a).filter((e=>e.startsWith("config.objectConfig"))),c=Object.keys(a).filter((e=>e.startsWith("config.mapConfig"))),u={readerConfig:Array.from(new Set(o.concat(l))),listConfig:Array.from(new Set(i.concat(s))),objectConfig:Array.from(new Set(n.concat(d))),mapConfig:Array.from(new Set(r.concat(c)))},m={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],save:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],save:[],upload:[]}},p=["readerConfig","listConfig"];for(let t of p)for(let o of u[t]){let i=o,n=e[o],r=a[o];n?r?n.timer.time&&m[t].upload.push(i):m[t].upload.push(i):(m[t].update.push(i),e[o]=r)}let h=["objectConfig","mapConfig"];for(let o of h)for(let i of u[o]){let n=i,r=e[i],l=a[i];r?l?("delete"===l.operation&&("update"===r.operation&&(r.timel.time&&(m[o].conflict.push(n),"cloud"===t?(m[o].delete.push(n),e[i]=l):m[o].upload.push(n))),r.operation),"update"===l.operation&&("update"===r.operation&&(r.timel.time&&m[o].upload.push(n)),"delete"===r.operation&&(r.timel.time&&m[o].upload.push(n)))):m[o].upload.push(n):(m[o].update.push(n),e[i]=l)}return{compareResult:m,syncRecords:e}}))}static compareAll(e,a,t,o,i){return m(this,void 0,void 0,(function*(){let n="cloud";if("yes"===t.getReaderConfig("isKeepLocal")){n="local";let e=t.getObjectConfig(yield o.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),a=yield i.getCloudConfig("config"),r=JSON.parse(a.cloudSyncTime||"{}");delete r[yield o.getFingerprint()],Object.values(r).filter((a=>"local"===a.conflictMode&&a.time>e.time)).length>0&&(n="cloud")}let{compareResult:r,syncRecords:l}=yield this.CompareDatabase(e,a,n),{compareResult:s,syncRecords:d}=yield this.CompareConfig(l,a,n),c=Object.assign(Object.assign({},r),s);return t.setAllSyncRecord(d),"local"===n&&(c.books.conflict.length>0||c.notes.conflict.length>0||c.bookmarks.conflict.length>0||c.plugins.conflict.length>0||c.words.conflict.length>0||c.objectConfig.conflict.length>0||c.mapConfig.conflict.length>0)?t.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):t.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),c}))}static startSync(e,a,t,o,i,n){return m(this,void 0,void 0,(function*(){let r=yield this.syncConfig(e,a,t,i,n,o);if(e.books.save.length>0||e.books.upload.length>0){let e=yield this.syncCover(a,n,i),t=yield this.syncBook(a,i);return[...r,...e,...t]}return r}))}static syncConfig(e,a,t,o,i,n){return m(this,void 0,void 0,(function*(){let r=[];for(let a of h){if(e[a].save.length+e[a].update.length>0){let o=yield n.getCloudDatabase(a);for(let i of e[a].save){let e=o.find((e=>e.key===i));e&&(yield t.saveRecord(e,a))}for(let i of e[a].update){let e=o.find((e=>e.key===i));e&&(yield t.updateRecord(e,a,!1))}}if(e[a].delete.length>0)for(let n of e[a].delete)"books"===a&&(yield o.deleteOfflineBook(n),yield i.deleteOfflineCover(n)),yield t.deleteRecord(n,a);yield t.dumpDatabase(a,!0)}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let t=yield n.getCloudConfig("config");for(let o of e.readerConfig.update){let e=o.split(".")[3];t.readerConfig&&a.setReaderConfig(e,JSON.parse(t.readerConfig)[e],!1)}for(let o of e.listConfig.update){let e=o.split(".")[3];t[e]&&a.setAllListConfig(JSON.parse(t[e]),e,!1)}for(let o of e.objectConfig.update){let e=o.split(".")[3],i=o.split(".")[2];t[i]&&JSON.parse(t[i])&&JSON.parse(t[i])[e]&&a.setObjectConfig(e,JSON.parse(t[i])[e],i,!1)}for(let o of e.mapConfig.update){let e=o.split(".")[3],i=o.split(".")[2];if(t[i]&&JSON.parse(t[i])&&JSON.parse(t[i])[e]){let o=JSON.parse(t[i])[e];a.setOneMapConfig(e,o,i,!1)}}}if(e.objectConfig.delete.length>0||e.mapConfig.delete.length>0){for(let t of e.objectConfig.delete){let e=t.split(".")[3],o=t.split(".")[2];a.deleteObjectConfig(e,o)}for(let t of e.mapConfig.delete){let e=t.split(".")[3],o=t.split(".")[2];a.deleteMapConfig(e,o)}}for(let a of h)e[a].upload.length>0&&r.push((()=>n.uploadDatabase(a)));return r.push((()=>n.uploadConfig("config"))),r.push((()=>n.uploadConfig("sync"))),r}))}static syncCover(e,a,t){return m(this,void 0,void 0,(function*(){let t=yield a.getLocalCoverList(),o=yield a.getCloudCoverList(),i=Array.from(new Set([...t,...o])),n=[];for(let r of i)t.includes(r)&&!o.includes(r)&&n.push((()=>a.uploadCover(r))),!t.includes(r)&&o.includes(r)&&"adrive"!==e.getItem("defaultSyncOption")&&n.push((()=>a.downloadCover(r)));return n}))}static syncBook(e,a){return m(this,void 0,void 0,(function*(){let t=yield a.getLocalBookList(),o=yield a.getCloudBookList(),i=[],n=Array.from(new Set([...t,...o]));for(let r of n){if(t.includes(r)&&!o.includes(r)){let e=r.split(".")[0],t=r.split(".")[1];i.push((()=>a.uploadBook(e,t)))}let n="yes"===e.getReaderConfig("autoOffline");if(!t.includes(r)&&o.includes(r)&&n&&"adrive"!==e.getItem("defaultSyncOption")){let e=r.split(".")[0],t=r.split(".")[1]||"epub";i.push((()=>a.offlineBook(e,t.toUpperCase())))}}return i}))}static runTasksWithLimit(e,a,t){return m(this,void 0,void 0,(function*(){if("ftp"!==t&&"adrive"!==t){const t=[],o=[];for(const i of e){const e=i().then((a=>(o.splice(o.indexOf(e),1),a)));t.push(e),o.push(e),o.length>=a&&(yield Promise.race(o))}return Promise.all(t)}for(let a of e)yield a()}))}}class ve{constructor(e,a){this.bookKey="",this.sessionStart=0,this.unregisterUnload=null,this.configService=e,this.platform=a}getDailySeconds(e,a){const t=((this.configService.getAllMapConfig("readingStats")||{})[a]||[]).find((a=>a.startsWith(e+"-")));if(!t)return 0;const o=t.split("-");return parseInt(o[o.length-1],10)||0}setDailySeconds(e,a,t){const o=(this.configService.getAllMapConfig("readingStats")||{})[a]||[],i=`${e}-${t}`,n=o.filter((a=>!a.startsWith(e+"-")));this.configService.setOneMapConfig(a,[...n,i],"readingStats")}start(e){this.bookKey=e,this.sessionStart=Date.now(),this.unregisterUnload=this.platform.registerUnloadHandler((()=>{var e,a;this.commit(),null===(a=(e=this.platform).onBeforeClose)||void 0===a||a.call(e)}))}stop(){var e;this.commit(),null===(e=this.unregisterUnload)||void 0===e||e.call(this),this.unregisterUnload=null,this.bookKey="",this.sessionStart=0}commit(){if(!this.bookKey||!this.sessionStart)return;const e=Date.now()-this.sessionStart;if(e<1e3)return void(this.sessionStart=0);const a=Math.round(e/1e3);this.sessionStart=0;const t=this.configService.getObjectConfig(this.bookKey,"readingTime",0);this.configService.setObjectConfig(this.bookKey,t+a,"readingTime");const o=function(){const e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}(),i=this.getDailySeconds(this.bookKey,o);this.setDailySeconds(this.bookKey,o,i+a)}getTotalSeconds(e){return this.configService.getObjectConfig(e,"readingTime",0)}getDailySecondsForBook(e,a){return this.getDailySeconds(e,a)}getDayStats(e){return((this.configService.getAllMapConfig("readingStats")||{})[e]||[]).map((e=>{const a=e.lastIndexOf("-");return{bookKey:e.substring(0,a),seconds:parseInt(e.substring(a+1),10)||0}}))}getAllDates(){const e=this.configService.getAllMapConfig("readingStats");return Object.keys(e||{})}}const be="Koodo Reader",ke="application/vnd.koreader.v1+json";class Se extends Error{constructor(e,a,t,o){super(e),this.name="KOReaderRequestError",this.status=a,this.code=t,this.body=o}}const Ee=e=>{const a=(e||"").trim();if(!a)return"";return(/^https?:\/\//i.test(a)?a:`https://${a}`).replace(/\/+$/,"")},Ce=e=>{const a="number"==typeof e?e:parseFloat((e||"0")+"");return!isFinite(a)||isNaN(a)?0:a>1&&a<=100?Math.min(Math.max(a/100,0),1):Math.min(Math.max(a,0),1)},Te=(e,a={})=>m(void 0,void 0,void 0,(function*(){const t=yield fetch(e,a);return t.ok||(yield(e=>m(void 0,void 0,void 0,(function*(){let a=null;try{a=yield e.json()}catch(t){try{a=yield e.text()}catch(e){a=null}}const t=(null==a?void 0:a.message)||(null==a?void 0:a.error)||(null==a?void 0:a.msg)||("string"==typeof a?a:"")||e.statusText||"Request failed";throw console.error(`[KOReader] HTTP ${e.status} error: ${t}`,null!=a?a:"(no body)"),new Se(t,e.status,null==a?void 0:a.code,a)})))(t)),204===t.status?{}:yield t.json()})),we=e=>({Accept:ke,"Content-Type":"application/json","x-auth-user":e.username,"x-auth-key":e.passwordHash});class Ae{constructor(e,a,t){this.getKOReaderSyncConfig=()=>{let e;try{e=this.ConfigService.getObjectConfig("koReaderSyncConfig","thirdpartyToken",{})}catch(e){return console.error("[KOReader] Failed to read koReaderSyncConfig:",e),null}if(!e||"object"!=typeof e)return console.error("[KOReader] koReaderSyncConfig is missing or invalid"),null;const a=Ee(e.serverUrl||""),t=(e.username||"").trim(),o=(e.passwordHash||"").trim();return a&&t&&o?{serverUrl:a,username:t,passwordHash:o}:(console.error("[KOReader] Incomplete config — missing fields"),null)},this.getLocalRecordLocation=e=>this.ConfigService.getObjectConfig(e,"recordLocation",{})||{},this.persistKOReaderMetadata=(e,a,t)=>{const o=Object.assign(Object.assign({},a),{percentage:t.percentage.toString(),xpath:t.progress,timestamp:t.timestamp||parseInt(Date.now()/1e3+"")});this.ConfigService.setObjectConfig(e,o,"recordLocation")},this.authUser=e=>m(this,void 0,void 0,(function*(){return yield Te(`${e.serverUrl}/users/auth`,{method:"GET",headers:we(e)})})),this.createUser=e=>m(this,void 0,void 0,(function*(){return yield Te(`${e.serverUrl}/users/create`,{method:"POST",headers:{Accept:ke,"Content-Type":"application/json"},body:JSON.stringify({username:e.username,password:e.passwordHash})})})),this.getBookProgress=(e,a)=>m(this,void 0,void 0,(function*(){const t=yield Te(`${e.serverUrl}/syncs/progress/${encodeURIComponent(a)}`,{method:"GET",headers:we(e)});return t&&0!==Object.keys(t).length?{document:a,percentage:Ce(t.percentage),progress:t.progress||"",device:t.device||"",device_id:t.device_id||"",timestamp:t.timestamp||0}:null})),this.updateBookProgress=(e,a)=>m(this,void 0,void 0,(function*(){yield Te(`${e.serverUrl}/syncs/progress`,{method:"PUT",headers:we(e),body:JSON.stringify({document:a.document,percentage:a.percentage,progress:a.progress,device:a.device||be,device_id:a.device_id||"",timestamp:a.timestamp||parseInt(Date.now()/1e3+"")})})})),this.buildLocalUploadPayload=(e,a,t,o)=>m(this,void 0,void 0,(function*(){const i=Ce(a.percentage),n=a.xpath||"",r=this.ConfigService.getObjectConfig(e.key,"koreaderBooks",{});if(!r.document){let a=yield o(e);if(!a)return console.error(`[KOReader] Cannot build upload payload for "${e.name}": failed to compute partial MD5`),null;r.document=a,this.ConfigService.setObjectConfig(e.key,r,"koreaderBooks")}return n?{document:r.document,percentage:i,progress:n,device:be,device_id:t,timestamp:a.timestamp||parseInt(Date.now()/1e3+"")}:(console.error(`[KOReader] Cannot build upload payload for "${e.name}": no xpath/progress recorded (localRecord.xpath is empty)`),null)})),this.resolveDeviceId=()=>m(this,void 0,void 0,(function*(){try{return(yield this.TokenService.getFingerprint())||"koodo-reader"}catch(e){return console.error("[KOReader] Failed to get device fingerprint, using fallback ID:",e),"koodo-reader"}})),this.verifyAndBuildKOReaderSyncConfig=e=>m(this,void 0,void 0,(function*(){const a={serverUrl:Ee(e.serverUrl),username:(e.username||"").trim(),passwordHash:(e.password||"").trim()?s.MD5((e.password||"").trim()).toString():(e.passwordHash||"").trim()};if(!a.serverUrl||!a.username||!a.passwordHash)throw new Error("Please fill in all fields");try{return yield this.authUser(a),a}catch(e){console.error(`[KOReader] Auth failed for user "${a.username}" at ${a.serverUrl}, attempting to create user:`,e);try{return yield this.createUser(a),yield this.authUser(a),a}catch(o){if((t=o)instanceof Se&&(2002===t.code||(t.message||"").toLowerCase().includes("already exists")))throw console.error(`[KOReader] User "${a.username}" already exists but auth failed. Original auth error:`,e),e;throw console.error(`[KOReader] Failed to create user "${a.username}":`,o),o}}var t})),this.syncKOReaderProgress=e=>m(this,void 0,void 0,(function*(){const a=this.getKOReaderSyncConfig();if(!a)throw new Error("Please configure the KOReader sync server first");yield this.authUser(a);const t=yield this.resolveDeviceId(),o=(yield this.DatabaseService.getAllRecords("books"))||[],i={checkedBooks:0,matchedBooks:0,pulledBooks:0,pushedBooks:0,skippedBooks:0};for(const n of o)try{i.checkedBooks++;const o=this.getLocalRecordLocation(n.key);if(!o||!o.xpath){console.error(`[KOReader] Skipping "${n.name}": no local reading progress (xpath) found`),i.skippedBooks++;continue}const r=this.ConfigService.getObjectConfig(n.key,"koreaderBooks",{});if(!r.document){let a=yield e(n);if(!a){console.error(`[KOReader] Skipping "${n.name}": failed to compute partial MD5 for document ID`),i.skippedBooks++;continue}r.document=a,this.ConfigService.setObjectConfig(n.key,r,"koreaderBooks")}let l=r.document;const s=yield this.getBookProgress(a,l),d=(null==s?void 0:s.timestamp)||0,c=o.timestamp||0;if(s){if(i.matchedBooks++,d>c)this.persistKOReaderMetadata(n.key,o,s),i.pulledBooks++;else{if(!(d{if("number"!=typeof e){const[a,t]=e.split("-");return{styleType:a,color:t}}if(e>=0&&e-1,t=parseInt(xe[e].split("-")[1]);return{styleType:a?"background":"underline",color:a?Ie[t]:Fe[t]}}return{styleType:"background",color:"#FEF3CD"}},this.formatHighlightValue=e=>`${e.styleType}-${e.color}`,this.getNoteHighlightString=()=>this.ConfigService.getReaderConfig(Me)||"background-#FEF3CD",this.getNoteHighlightValue=()=>{const e=this.getNoteHighlightString();if(!e)return Ue;const[a,t]=e.split("-");return{styleType:a,color:t}},this.saveNoteHighlightValue=e=>{this.ConfigService.setReaderConfig(Me,`${e.styleType}-${e.color}`)},this.getTtsHighlightString=()=>this.ConfigService.getReaderConfig(_e)||Re,this.getTtsHighlightValue=()=>{const e=this.getTtsHighlightString();if(!e)return Oe;const[a,t]=e.split("-");return{styleType:a,color:t}},this.saveTtsHighlightValue=e=>{this.ConfigService.setReaderConfig(_e,`${e.styleType}-${e.color}`)},this.getSearchHighlightString=()=>this.ConfigService.getReaderConfig($e)||Re,this.getSearchHighlightValue=()=>{const e=this.ConfigService.getReaderConfig($e);if(!e)return Oe;const[a,t]=e.split("-");return{styleType:a,color:t}},this.saveSearchHighlightValue=e=>{this.ConfigService.setReaderConfig($e,`${e.styleType}-${e.color}`)},this.buildHighlightStyleForType=(e,a,t)=>{let o="background",i="#FEF3CD";if("number"==typeof e){if(e>=0&&e-1,t=parseInt(xe[e].split("-")[1]);o=a?"background":"underline",i=a?Ie[t]:Fe[t]}}else o=e.split("-")[0],i=e.split("-")[1];const n="background"===o?((e,a)=>{const t=e.replace("#",""),o=3===t.length?t.split("").map((e=>e+e)).join(""):t;return 6!==o.length?e:`rgba(${parseInt(o.slice(0,2),16)}, ${parseInt(o.slice(2,4),16)}, ${parseInt(o.slice(4,6),16)}, ${a})`})(i,.8):i;switch(o){case"background":return a?`background: ${n}; mix-blend-mode: multiply;`:`background: ${n};`;case"underline":return a?t?`border-right: 2px solid ${n};`:`border-bottom: 2px solid ${n};`:`text-decoration: underline; text-decoration-color: ${n}; text-decoration-thickness: 2px; text-decoration-skip-ink: none;`;case"strikethrough":return a?`background: linear-gradient(transparent calc(50% - 1px), ${n} calc(50% - 1px), ${n} calc(50% + 1px), transparent calc(50% + 1px));`:t?`background: linear-gradient(to right, transparent calc(50% - 1px), ${n} calc(50% - 1px), ${n} calc(50% + 1px), transparent calc(50% + 1px));`:`text-decoration: line-through; text-decoration-color: ${n}; text-decoration-thickness: 2px; text-decoration-skip-ink: none;`;case"wavy":const e=i.replace("#","%23");if(a){return`background-image: ${`url("data:image/svg+xml,%3Csvg xmlns='http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width='6' height='3'%3E%3Cpath d='M0 2 Q1.5 0 3 2 Q4.5 4 6 2' fill='none' stroke='${e}' stroke-width='1.5'%2F%3E%3C%2Fsvg%3E")`}; background-repeat: repeat-x; background-position: bottom; background-size: 6px 3px;`}if(t){return`background-image: ${`url("data:image/svg+xml,%3Csvg xmlns='http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width='3' height='6'%3E%3Cpath d='M2 0 Q0 1.5 2 3 Q4 4.5 2 6' fill='none' stroke='${e}' stroke-width='1.5'%2F%3E%3C%2Fsvg%3E")`}; background-repeat: repeat-y; background-position: right; background-size: 3px 6px;`}return`text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: ${n}; text-decoration-thickness: 2px; text-decoration-skip-ink: none;`;default:return`background: ${n};`}},this.buildHighlightPreviewStyle=(e,a)=>{switch(e){case"background":default:return{background:a};case"underline":return{textDecoration:"underline",textDecorationColor:a,textDecorationThickness:"2px",textDecorationSkipInk:"none"};case"strikethrough":return{textDecoration:"line-through",textDecorationColor:a,textDecorationThickness:"2px",textDecorationSkipInk:"none"};case"wavy":return{textDecorationLine:"underline",textDecorationStyle:"wavy",textDecorationColor:a,textDecorationThickness:"2px",textDecorationSkipInk:"none"}}},this.convertNumberToHighlightValue=e=>this.getHighlightValue(e),this.buildTtsHighlightStyle=(e,a)=>this.buildHighlightStyleForType(this.getTtsHighlightString(),e,a),this.buildTtsHighlightPreviewStyle=(e,a)=>this.buildHighlightPreviewStyle(e,a),this.buildSearchHighlightStyle=(e,a)=>this.buildHighlightStyleForType(this.getSearchHighlightString(),e,a),this.buildSearchHighlightPreviewStyle=(e,a)=>this.buildHighlightPreviewStyle(e,a),this.ConfigService=e}}const ze=(De=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,a){localStorage.setItem(e,a)}static removeItem(e){localStorage.removeItem(e)}},Le="browser",class extends De{static getReaderConfig(e){return w.includes(e)&&"undefined"!=typeof window&&window.currentBookKey&&this.getAllListConfig("seperateStyleBooks").includes(window.currentBookKey)?this.getObjectConfig(window.currentBookKey,"seperateStyleConfig",{})[e]:JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,a,t=!0){if(w.includes(e)&&"undefined"!=typeof window&&window.currentBookKey&&this.getAllListConfig("seperateStyleBooks").includes(window.currentBookKey)){let o=this.getObjectConfig(window.currentBookKey,"seperateStyleConfig",{});return o[e]=a,void this.setObjectConfig(window.currentBookKey,o,"seperateStyleConfig",t)}let o=JSON.parse(this.getItem("readerConfig")||"{}");o[e]=a,this.setItem("readerConfig",JSON.stringify(o)),t&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:Le,key:e},{operation:"update",time:Date.now()})}static getAllListConfig(e){return("{}"!==this.getItem(e)&&this.getItem(e)?JSON.parse(this.getItem(e)||""):[])||[]}static deleteListConfig(e,a){let t=this.getAllListConfig(a);const o=t.indexOf(e);o>-1&&t.splice(o,1),this.setAllListConfig(t,a)}static setListConfig(e,a){let t=this.getAllListConfig(a);const o=t.indexOf(e);o>-1?(t.splice(o,1),t.unshift(e)):t.unshift(e),this.setAllListConfig(t,a)}static setAllListConfig(e,a,t=!0){this.setItem(a,JSON.stringify(e)),t&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:a},{operation:"update",time:Date.now()})}static setObjectConfig(e,a,t,o=!0){let i=this.getAllObjectConfig(t);i[e]=a,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(i,t)}static getObjectConfig(e,a,t){return this.getAllObjectConfig(a)[e]||t}static getAllObjectConfig(e){let a=this.getItem(e);return JSON.parse(a)||{}}static setAllObjectConfig(e,a){this.setItem(a,JSON.stringify(e))}static deleteObjectConfig(e,a){let t=this.getAllObjectConfig(a);delete t[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:a,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(t,a)}static getAllMapConfig(e){let a=this.getItem(e);return JSON.parse(a)||{}}static getMapConfig(e,a){return this.getAllMapConfig(a)[e]||[]}static setAllMapConfig(e,a){this.setItem(a,JSON.stringify(e))}static setMapConfig(e,a,t){let o=this.getAllMapConfig(t);void 0===o[e]&&(o[e]=[]),a&&-1===o[e].indexOf(a)&&o[e].unshift(a),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,t)}static setOneMapConfig(e,a,t,o=!0){let i=this.getAllMapConfig(t);i[e]=a,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,t)}static deleteFromMapConfig(e,a,t){let o=this.getAllMapConfig(t),i=o[e].indexOf(a);o[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,t)}static deleteFromAllMapConfig(e,a){let t=this.getAllMapConfig(a);Object.keys(t).forEach((o=>{let i=t[o].indexOf(e);i>-1&&(t[o].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:a,key:o},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(t,a)}static deleteMapConfig(e,a){let t=this.getAllMapConfig(a);delete t[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:a,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(t,a)}static getFromAllMapConfig(e,a){let t=this.getAllMapConfig(a),o=[];for(let a in t)t[a]&&t[a].indexOf(e)>-1&&o.push(a);return o}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,a){const t=e.type+"."+e.catergory+"."+e.name+"."+e.key;let o=JSON.parse(this.getItem("syncRecord")||"{}");o[t]=a,this.setItem("syncRecord",JSON.stringify(o))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var De,Le;class Pe{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("notionSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Notion] notionSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Notion] Failed to read notionSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableNotionSync")}resolveDatabaseId(e,a){return m(this,void 0,void 0,(function*(){const t=yield fetch(`https://api.notion.com/v1/blocks/${a}/children`,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Notion-Version":"2022-06-28"}});if(!t.ok){const e=yield t.json().catch((()=>null));throw console.error(`[Notion] resolveDatabaseId failed for page ${a}: HTTP ${t.status} ${t.statusText}`,JSON.stringify(e)),new Error(`Notion resolve database error: ${t.status} ${t.statusText}`)}const o=yield t.json(),i=(o.results||[]).find((e=>"child_database"===e.type));if(!i)throw console.error(`[Notion] No child_database block found under page ${a}. Available block types:`,JSON.stringify((o.results||[]).map((e=>e.type)))),new Error(`No child database found in page ${a}. Please provide a Database ID directly.`);return i.id}))}findOrCreatePage(e,a,t){return m(this,void 0,void 0,(function*(){const o=`${t}`,i=yield fetch(`https://api.notion.com/v1/databases/${a}/query`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({filter:{property:"title",title:{equals:o}}})});if(!i.ok){const o=yield i.json().catch((()=>({})));if(400===i.status&&"validation_error"===(null==o?void 0:o.code)&&"string"==typeof(null==o?void 0:o.message)&&o.message.includes("is a page, not a database")){console.error(`[Notion] Provided databaseId "${a}" is a page, not a database. Resolving child database...`);const o=yield this.resolveDatabaseId(e,a);return this.findOrCreatePage(e,o,t)}throw console.error(`[Notion] Database query failed for databaseId "${a}" (book: "${t}"): HTTP ${i.status} ${i.statusText}`,JSON.stringify(o)),new Error(`Notion API error: ${i.status} ${i.statusText}`)}const n=yield i.json();if(n.results&&n.results.length>0)return n.results[0].id;const r=yield fetch("https://api.notion.com/v1/pages",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({parent:{database_id:a},properties:{title:{title:[{text:{content:o}}]}}})});if(!r.ok){const e=yield r.json().catch((()=>null));throw console.error(`[Notion] Failed to create page for book "${t}" in database "${a}": HTTP ${r.status} ${r.statusText}`,JSON.stringify(e)),new Error(`Notion create page error: ${r.status} ${r.statusText}`)}return(yield r.json()).id}))}appendBlocks(e,a,t,o){return m(this,void 0,void 0,(function*(){const i=!t.notes||0===t.notes.length,n=[];n.push({object:"block",type:"divider",divider:{}}),o&&n.push({object:"block",type:"heading_3",heading_3:{rich_text:[{type:"text",text:{content:o}}]}}),n.push({object:"block",type:"quote",quote:{rich_text:[{type:"text",text:{content:t.text||""}}]}}),!i&&t.notes&&n.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`📝 ${t.notes}`}}]}});const r=`${t.date.year}-${String(t.date.month).padStart(2,"0")}-${String(t.date.day).padStart(2,"0")}`;n.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`Added on ${r}`},annotations:{italic:!0,color:"gray"}}]}});const l=yield fetch(`https://api.notion.com/v1/blocks/${a}/children`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({children:n})});if(!l.ok){const e=yield l.json().catch((()=>null));throw console.error(`[Notion] Failed to append blocks to page ${a}: HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),new Error(`Notion append blocks error: ${l.status} ${l.statusText}`)}}))}syncNote(e,a){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const t=this.getConfig();if(!t)return!1;try{const o=yield this.findOrCreatePage(t.token,t.databaseId,a);return yield this.appendBlocks(t.token,o,e,e.chapter||""),!0}catch(e){return console.error(`[Notion] Sync failed for book "${a}":`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}class je{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("yuqueSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Yuque] yuqueSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Yuque] Failed to read yuqueSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableYuqueSync")}generateDocSlug(e){return m(this,void 0,void 0,(function*(){const a=(e||"").trim()||"untitled",t=a.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").replace(/[-_.]{2,}/g,"-").replace(/^[-_.]+|[-_.]+$/g,"")||"book",o=(yield y(a)).slice(0,16),i=t,n=190-o.length-1;return`${i.substring(0,n).replace(/^[-_.]+|[-_.]+$/g,"")||"book"}-${o}`}))}findOrCreateDoc(e,a,t){return m(this,void 0,void 0,(function*(){const o=`${t}`,i=yield this.generateDocSlug(t);try{const t=yield fetch(`${je.API_BASE}/repos/${a}/docs/${i}`,{method:"GET",headers:{"X-Auth-Token":e,"Content-Type":"application/json"}});if(t.ok){const e=yield t.json();return{id:e.data.id,slug:e.data.slug,body:e.data.body||""}}if(404!==t.status){const e=yield t.json().catch((()=>null));console.error(`[Yuque] Unexpected error fetching doc "${i}" in repo "${a}": HTTP ${t.status} ${t.statusText}`,JSON.stringify(e))}}catch(e){console.error(`[Yuque] Network error fetching doc "${i}" in repo "${a}":`,JSON.stringify(e))}const n=yield fetch(`${je.API_BASE}/repos/${a}/docs`,{method:"POST",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({title:o,slug:i,body:`# ${o}\n\n`,format:"markdown"})});if(!n.ok){const e=yield n.json().catch((()=>null));throw console.error(`[Yuque] Failed to create doc "${o}" in repo "${a}": HTTP ${n.status} ${n.statusText}`,JSON.stringify(e)),new Error(`Yuque create doc error: ${n.status} ${n.statusText}`)}const r=yield n.json();return{id:r.data.id,slug:r.data.slug,body:r.data.body||""}}))}formatNoteMarkdown(e){const a=!e.notes||0===e.notes.length,t=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let o="\n---\n\n";return e.chapter&&(o+=`### ${e.chapter}\n\n`),o+=`> ${e.text||""}\n\n`,!a&&e.notes&&(o+=`📝 ${e.notes}\n\n`),o+=`*Added on ${t}*\n\n`,o}updateDoc(e,a,t,o){return m(this,void 0,void 0,(function*(){const i=yield fetch(`${je.API_BASE}/repos/${a}/docs/${t}`,{method:"PUT",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({body:o,format:"markdown"})});if(!i.ok){const e=yield i.json().catch((()=>null));throw console.error(`[Yuque] Failed to update doc ${t} in repo "${a}": HTTP ${i.status} ${i.statusText}`,JSON.stringify(e)),new Error(`Yuque update doc error: ${i.status} ${i.statusText}`)}}))}syncNote(e,a){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const t=this.getConfig();if(!t)return!1;try{const o=yield this.findOrCreateDoc(t.token,t.namespace,a),i=this.formatNoteMarkdown(e),n=o.body+i;return yield this.updateDoc(t.token,t.namespace,o.id,n),!0}catch(e){return console.error(`[Yuque] Sync failed for book "${a}":`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}je.API_BASE="https://www.yuque.com/api/v2";class Ke{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("readwiseSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Readwise] readwiseSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Readwise] Failed to read readwiseSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableReadwiseSync")}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const i=`${a}`,n=!e.notes||0===e.notes.length,r={text:e.text||"",title:i,author:t||"Unknown",source_type:"koodo-reader",category:"books",highlighted_at:`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`};if(!n&&e.notes&&(r.note=e.notes),e.chapter){const a=parseInt(e.chapter,10);isNaN(a)||(r.location_type="order",r.location=a)}try{const e=yield fetch(`${Ke.API_BASE}/highlights/`,{method:"POST",headers:{Authorization:`Token ${o.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({highlights:[r]})});if(!e.ok){const a=yield e.json().catch((()=>null));throw console.error(`[Readwise] Failed to sync highlight for book "${i}": HTTP ${e.status} ${e.statusText}`,JSON.stringify(a)),new Error(`Readwise API error: ${e.status} ${e.statusText}`)}return!0}catch(a){return console.error(`[Readwise] Sync failed for book "${i}" (text: "${(e.text||"").substring(0,50)}..."):`,JSON.stringify(a instanceof Error?a.message:a)),!1}}))}}Ke.API_BASE="https://readwise.io/api/v2";class He{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("imaSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[IMA] imaSyncConfig is empty or not set"),null):e}catch(e){return console.error("[IMA] Failed to read imaSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableImaSync")}getHeaders(e){return{"Content-Type":"application/json","ima-openapi-clientid":e.clientId,"ima-openapi-apikey":e.apiKey}}formatNoteMarkdown(e,a,t){const o=!e.notes||0===e.notes.length,i=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let n="\n---\n\n";return e.chapter&&(n+=`### ${e.chapter}\n\n`),n+=`> ${e.text||""}\n\n`,!o&&e.notes&&(n+=`**Note:** ${e.notes}\n\n`),n+=`*${i}*\n`,n}findNoteByTitle(e,a){var t,o,i,n;return m(this,void 0,void 0,(function*(){try{const r=JSON.stringify({search_type:0,query_info:{title:a},start:0,end:20}),l=yield fetch(`${He.API_BASE}/search_note`,{method:"POST",headers:this.getHeaders(e),body:r});if(!l.ok){const e=yield l.json().catch((()=>null));return console.error(`[IMA] search_note failed for title "${a}": HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),null}const s=yield l.json();if(0!==s.code)return console.error(`[IMA] search_note returned error code ${s.code} for title "${a}":`,JSON.stringify(null!==(t=s.msg)&&void 0!==t?t:s)),null;const d=((null===(o=s.data)||void 0===o?void 0:o.search_note_infos)||[]).find((e=>{var t;return a.includes(null===(t=e.note_book_info)||void 0===t?void 0:t.title.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,""))}));return null!==(n=null===(i=null==d?void 0:d.note_book_info)||void 0===i?void 0:i.note_id)&&void 0!==n?n:null}catch(e){return console.error(`[IMA] Network error in search_note for title "${a}":`,JSON.stringify(e)),null}}))}createNote(e,a,t){var o,i,n;return m(this,void 0,void 0,(function*(){try{const r={content_format:1,content:`# ${a}\n\n${t}`};e.folderId&&(r.folder_id=e.folderId);const l=yield fetch(`${He.API_BASE}/import_doc`,{method:"POST",headers:this.getHeaders(e),body:JSON.stringify(r)});if(!l.ok){const e=yield l.json().catch((()=>null));return console.error(`[IMA] import_doc failed for note "${a}": HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),null}const s=yield l.json();return 0!==s.code?(console.error(`[IMA] import_doc returned error code ${s.code} for note "${a}":`,JSON.stringify(null!==(o=s.msg)&&void 0!==o?o:s)),null):null!==(n=null===(i=s.data)||void 0===i?void 0:i.note_id)&&void 0!==n?n:null}catch(e){return console.error(`[IMA] Network error in import_doc for note "${a}":`,JSON.stringify(e)),null}}))}appendNote(e,a,t){var o;return m(this,void 0,void 0,(function*(){try{const i=yield fetch(`${He.API_BASE}/append_doc`,{method:"POST",headers:this.getHeaders(e),body:JSON.stringify({note_id:a,content_format:1,content:t})});if(!i.ok){const e=yield i.json().catch((()=>null));return console.error(`[IMA] append_doc failed for noteId "${a}": HTTP ${i.status} ${i.statusText}`,JSON.stringify(e)),!1}const n=yield i.json();return 0===n.code||(console.error(`[IMA] append_doc returned error code ${n.code} for noteId "${a}":`,JSON.stringify(null!==(o=n.msg)&&void 0!==o?o:n)),!1)}catch(e){return console.error(`[IMA] Network error in append_doc for noteId "${a}":`,JSON.stringify(e)),!1}}))}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const i=this.formatNoteMarkdown(e,a,t);let n=yield this.findNoteByTitle(o,a);if(n){const e=yield this.appendNote(o,n,i);return e||console.error(`[IMA] Failed to append to existing note "${a}" (noteId: ${n})`),e}return n=yield this.createNote(o,a,i),n||console.error(`[IMA] Failed to create note for book "${a}"`),null!==n}))}}He.API_BASE="https://ima.qq.com/openapi/note/v1";class Je{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("siyuanSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[SiYuan] siyuanSyncConfig is empty or not set"),null):e}catch(e){return console.error("[SiYuan] Failed to read siyuanSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableSiYuanSync")}getHeaders(e){return{"Content-Type":"application/json",Authorization:`Token ${e}`}}findOrCreateNotebook(e,a){var t,o;return m(this,void 0,void 0,(function*(){const i=yield fetch(`${e}/api/notebook/lsNotebooks`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({})});if(!i.ok){const a=yield i.json().catch((()=>null));throw console.error(`[SiYuan] lsNotebooks failed at ${e}: HTTP ${i.status} ${i.statusText}`,JSON.stringify(a)),new Error(`SiYuan list notebooks failed: ${i.status} ${i.statusText}`)}const n=yield i.json();if(0!==n.code)throw console.error(`[SiYuan] lsNotebooks returned error code ${n.code}:`,JSON.stringify(n.msg)),new Error(`SiYuan list notebooks error: ${n.msg}`);const r=(null!==(o=null===(t=n.data)||void 0===t?void 0:t.notebooks)&&void 0!==o?o:[]).find((e=>"Koodo Reader"===e.name));if(r)return r.id;const l=yield fetch(`${e}/api/notebook/createNotebook`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({name:"Koodo Reader"})});if(!l.ok){const a=yield l.json().catch((()=>null));throw console.error(`[SiYuan] createNotebook failed at ${e}: HTTP ${l.status} ${l.statusText}`,JSON.stringify(a)),new Error(`SiYuan create notebook failed: ${l.status} ${l.statusText}`)}const s=yield l.json();if(0!==s.code)throw console.error(`[SiYuan] createNotebook returned error code ${s.code}:`,JSON.stringify(s.msg)),new Error(`SiYuan create notebook error: ${s.msg}`);return s.data.notebook.id}))}findOrCreateDoc(e,a,t,o,i,n){return m(this,void 0,void 0,(function*(){const i=yield fetch(`${e}/api/query/sql`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({stmt:`SELECT id FROM blocks WHERE type='d' AND hpath='${o.replace(/'/g,"''")}' LIMIT 1`})});if(i.ok){const e=yield i.json();if(0!==e.code)console.error(`[SiYuan] SQL query for doc "${o}" returned error code ${e.code}:`,JSON.stringify(e.msg));else if(e.data&&e.data.length>0)return e.data[0].id}else{const e=yield i.json().catch((()=>null));console.error(`[SiYuan] SQL query for doc "${o}" failed: HTTP ${i.status} ${i.statusText}`,JSON.stringify(e))}const r=n?`**Author:** ${n}\n`:"",l=yield fetch(`${e}/api/filetree/createDocWithMd`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({notebook:t,path:o,markdown:r})});if(!l.ok){const e=yield l.json().catch((()=>null));throw console.error(`[SiYuan] createDocWithMd failed for "${o}" in notebook "${t}": HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),new Error(`SiYuan create doc failed: ${l.status} ${l.statusText}`)}const s=yield l.json();if(0!==s.code)throw console.error(`[SiYuan] createDocWithMd returned error code ${s.code} for "${o}":`,JSON.stringify(s.msg)),new Error(`SiYuan create doc error: ${s.msg}`);return s.data}))}appendMarkdownToDoc(e,a,t,o){return m(this,void 0,void 0,(function*(){const i=yield fetch(`${e}/api/block/appendBlock`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({data:o,dataType:"markdown",parentID:t})});if(!i.ok){const e=yield i.json().catch((()=>null));throw console.error(`[SiYuan] appendBlock failed for docId "${t}": HTTP ${i.status} ${i.statusText}`,JSON.stringify(e)),new Error(`SiYuan append block failed: ${i.status} ${i.statusText}`)}const n=yield i.json();if(0!==n.code)throw console.error(`[SiYuan] appendBlock returned error code ${n.code} for docId "${t}":`,JSON.stringify(n.msg)),new Error(`SiYuan append block error: ${n.msg}`)}))}formatNoteMarkdown(e){const a=!e.notes||0===e.notes.length,t=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let o="---\n\n";return e.chapter&&(o+=`### ${e.chapter}\n\n`),o+=`> ${e.text||""}\n\n`,!a&&e.notes&&(o+=`📝 ${e.notes}\n\n`),o+=`*Added on ${t}*\n\n`,o}sanitizePathComponent(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const{serverUrl:i,token:n}=o;if(!i||!n)return console.error("[SiYuan] Sync skipped: config is missing serverUrl or token",JSON.stringify({hasServerUrl:!!i,hasToken:!!n})),!1;try{const o=yield this.findOrCreateNotebook(i,n),r=`/${this.sanitizePathComponent(a)}`,l=yield this.findOrCreateDoc(i,n,o,r,a,t),s=this.formatNoteMarkdown(e);return yield this.appendMarkdownToDoc(i,n,l,s),!0}catch(e){return console.error(`[SiYuan] Sync failed for book "${a}" at ${o.serverUrl}:`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}class We{constructor(e,a){this.databaseService=e,this.notionSync=new Pe(a),this.yuqueSync=new je(a),this.readwiseSync=new Ke(a),this.imaSync=new He(a),this.siyuanSync=new Je(a)}getExtraServices(){return[]}getEnabledServices(){const e=[];return this.notionSync.isEnabled()&&e.push({name:"Notion",sync:this.notionSync.syncNote.bind(this.notionSync)}),this.yuqueSync.isEnabled()&&e.push({name:"Yuque",sync:this.yuqueSync.syncNote.bind(this.yuqueSync)}),this.readwiseSync.isEnabled()&&e.push({name:"Readwise",sync:this.readwiseSync.syncNote.bind(this.readwiseSync)}),this.imaSync.isEnabled()&&e.push({name:"IMA",sync:this.imaSync.syncNote.bind(this.imaSync)}),this.siyuanSync.isEnabled()&&e.push({name:"SiYuan",sync:this.siyuanSync.syncNote.bind(this.siyuanSync)}),[...e,...this.getExtraServices()]}syncNote(e,a){return m(this,void 0,void 0,(function*(){const t=this.getEnabledServices();if(0===t.length)return;let o="Unknown Book",i="";if(a||e.bookKey)try{const t=yield this.databaseService.getRecord(a||e.bookKey,"books");t&&t.name&&(o=t.name),t&&t.author&&(i=t.author)}catch(t){console.error(`[NoteSync] Failed to resolve book info for key: ${a||e.bookKey}`,JSON.stringify(t))}const n=(yield Promise.allSettled(t.map((a=>m(this,void 0,void 0,(function*(){var t,n,r,l;try{const r=yield a.sync(e,o,i);return r||console.error(`[NoteSync] ${a.name} sync returned false for book "${o}" (noteId: ${null!==(n=null!==(t=e.noteKey)&&void 0!==t?t:e.key)&&void 0!==n?n:"unknown"})`),{name:a.name,success:r}}catch(t){return console.error(`[NoteSync] ${a.name} sync threw an error for book "${o}" (noteId: ${null!==(l=null!==(r=e.noteKey)&&void 0!==r?r:e.key)&&void 0!==l?l:"unknown"}):`,JSON.stringify(t)),{name:a.name,success:!1}}})))))).filter((e=>"rejected"===e.status||"fulfilled"===e.status&&!e.value.success)).map((e=>"fulfilled"===e.status?e.value.name:"Unknown"));n.length>0&&console.error(`[NoteSync] Sync failed for services: ${n.join(", ")} | book: "${o}"`)}))}}class qe{constructor(e,a,t){this.configService=e,this.fs=a,this.path=t}getConfig(){try{const e=this.configService.getObjectConfig("markdownSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Markdown] markdownSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Markdown] Failed to read markdownSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableMarkdownSync")}formatNoteMarkdown(e){const a=!e.notes||0===e.notes.length,t=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let o="\n---\n\n";return e.chapter&&(o+=`### ${e.chapter}\n\n`),o+=`> ${e.text||""}\n\n`,!a&&e.notes&&(o+=`📝 ${e.notes}\n\n`),o+=`*Added on ${t}*\n\n`,o}sanitizeFileName(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const i=o.folder;if(!i)return console.error("[Markdown] Sync skipped: markdownSyncConfig.folder is not set"),!1;const n=this.fs,r=this.path;try{const o=this.sanitizeFileName(a),l=r.join(i,`${o}.md`);if(!n.existsSync(l)){const e=`# ${a}\n`,o=t?`**Author:** ${t}\n\n`:"\n";try{n.writeFileSync(l,e+o,"utf-8")}catch(e){return console.error(`[Markdown] Failed to create file "${l}" for book "${a}":`,JSON.stringify(e)),!1}}const s=this.formatNoteMarkdown(e);try{n.appendFileSync(l,s,"utf-8")}catch(e){return console.error(`[Markdown] Failed to append to file "${l}" for book "${a}":`,JSON.stringify(e)),!1}return!0}catch(e){return console.error(`[Markdown] Sync failed for book "${a}" in folder "${i}":`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}class Ge extends We{constructor(e,a,t,o){super(e,a),this.markdownSync=new qe(a,t,o)}getExtraServices(){return this.markdownSync.isEnabled()?[{name:"Markdown",sync:this.markdownSync.syncNote.bind(this.markdownSync)}]:[]}}class Qe{constructor(a){this.syncWordToEudic=(a,t)=>m(this,void 0,void 0,(function*(){var o,i,n,r,l,s,d,c,u,m;if("yes"===this.configService.getReaderConfig("isEnableEudicSync"))try{let c;try{c=this.configService.getObjectConfig("eudicSyncConfig","thirdpartyToken",{})}catch(e){return void console.error("[Eudic] Failed to read eudicSyncConfig:",JSON.stringify(e))}if(!c||!c.accessToken)return void console.error("[Eudic] Sync skipped: config is missing or accessToken is not set",JSON.stringify({hasConfig:!!c}));const u=c.language||"en",m={Authorization:`NIS ${c.accessToken}`,"Content-Type":"application/json","User-Agent":"Mozilla/5.0"};let p="0";const h=(c.categoryName||"").trim();if(h)if(void 0!==c.categoryId)p=c.categoryId;else try{const a=(null===(o=(yield e.get(`https://api.frdic.com/api/open/v1/studylist/category?language=${u}`,{headers:m})).data)||void 0===o?void 0:o.data)||[],t=a.find((e=>e.name===h));t?p=t.id:console.error(`[Eudic] Category "${h}" not found among available categories:`,JSON.stringify(a.map((e=>e.name))));const i=Object.assign(Object.assign({},c),{categoryId:p});this.configService.setObjectConfig("eudicSyncConfig",i,"thirdpartyToken")}catch(e){console.error("[Eudic] Failed to fetch category list:",null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.status,JSON.stringify(null!==(r=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.data)&&void 0!==r?r:e))}try{yield e.post("https://api.frdic.com/api/open/v1/studylist/word",{language:u,word:a,context_line:t||"",category_ids:[p]},{headers:m})}catch(e){throw console.error(`[Eudic] Failed to add word "${a}" to study list (category: ${p}):`,null===(l=null==e?void 0:e.response)||void 0===l?void 0:l.status,JSON.stringify(null!==(d=null===(s=null==e?void 0:e.response)||void 0===s?void 0:s.data)&&void 0!==d?d:e)),e}}catch(e){console.error("[Eudic] Sync error for word:",a,null===(c=null==e?void 0:e.response)||void 0===c?void 0:c.status,JSON.stringify(null!==(m=null===(u=null==e?void 0:e.response)||void 0===u?void 0:u.data)&&void 0!==m?m:e))}})),this.syncWordToAnki=(a,t,o,i,n="")=>m(this,void 0,void 0,(function*(){var r,l,s,d,c,u,m,p,h,g;if("yes"===this.configService.getReaderConfig("isEnableAnkiSync"))try{let h;try{h=this.configService.getObjectConfig("ankiSyncConfig","thirdpartyToken",{})}catch(e){return void console.error("[Anki] Failed to read ankiSyncConfig:",JSON.stringify(e))}if(!h||!h.deckName)return void console.error("[Anki] Sync skipped: config is missing or deckName is not set",JSON.stringify({hasConfig:!!h}));const g=h.host||"127.0.0.1",f=`http://${g}:${h.port||"8765"}`,y=h.deckName,N="Koodo Reader Word",v=(a,t={})=>{const o={action:a,version:6,params:t};return h.apiKey&&(o.key=h.apiKey),e.post(f,o)};if(!h.modelName)try{const e=yield v("modelNames");if(!((null===(r=e.data)||void 0===r?void 0:r.result)||[]).includes(N))try{yield v("createModel",{modelName:N,inOrderFields:["Word","Sentence","Book","Chapter","Definition"],cardTemplates:[{Name:"Card 1",Front:"{{Word}}

{{Sentence}}

{{Book}}
{{Chapter}}",Back:"{{Definition}}"}]})}catch(e){throw console.error(`[Anki] Failed to create model "${N}":`,JSON.stringify(null!==(s=null===(l=null==e?void 0:e.response)||void 0===l?void 0:l.data)&&void 0!==s?s:e)),e}this.configService.setObjectConfig("ankiSyncConfig",Object.assign(Object.assign({},h),{modelName:N}),"thirdpartyToken")}catch(e){throw console.error(`[Anki] Failed to fetch model names from ${f}:`,JSON.stringify(null!==(c=null===(d=null==e?void 0:e.response)||void 0===d?void 0:d.data)&&void 0!==c?c:e)),e}try{const e=yield v("addNote",{note:{deckName:y,modelName:N,fields:{Word:a,Sentence:t||"",Book:o||"",Chapter:i||"",Definition:n||""},options:{allowDuplicate:!1},tags:[]}});(null===(u=e.data)||void 0===u?void 0:u.error)&&console.error(`[Anki] addNote returned an error for word "${a}" in deck "${y}":`,JSON.stringify(e.data.error))}catch(e){throw console.error(`[Anki] Failed to add note for word "${a}" to deck "${y}" at ${f}:`,JSON.stringify(null!==(p=null===(m=null==e?void 0:e.response)||void 0===m?void 0:m.data)&&void 0!==p?p:e)),e}}catch(e){console.error("[Anki] Sync error for word:",a,JSON.stringify(null!==(g=null===(h=null==e?void 0:e.response)||void 0===h?void 0:h.data)&&void 0!==g?g:e))}})),this.syncWordToMaiMemo=a=>m(this,void 0,void 0,(function*(){var t,o,i,n,r,l,s,d,c,u,m,p,h,g,f,y,N,v,b,k;if("yes"===this.configService.getReaderConfig("isEnableMaiMemoSync"))try{let v;try{v=this.configService.getObjectConfig("maimemoSyncConfig","thirdpartyToken",{})}catch(e){return void console.error("[MaiMemo] Failed to read maimemoSyncConfig:",JSON.stringify(e))}if(!v||!v.accessToken||!v.notepadName)return void console.error("[MaiMemo] Sync skipped: config is missing accessToken or notepadName",JSON.stringify({hasConfig:!!v}));const b=v.accessToken,k=v.notepadName.trim(),S={Authorization:`Bearer ${b}`,"Content-Type":"application/json",Accept:"application/json"};let E=v.notepadId||"";if(!E)try{const l=yield e.get("https://open.maimemo.com/open/api/v1/memo/notepads",{headers:S}),s=((null===(o=null===(t=l.data)||void 0===t?void 0:t.data)||void 0===o?void 0:o.notepads)||[]).find((e=>"PUBLISHED"===e.status&&e.title===k));if(s)E=s.id;else{if(E=null===(r=null===(n=null===(i=(yield e.post("https://open.maimemo.com/open/api/v1/memo/notepads",{notepad:{status:"PUBLISHED",content:a,title:k,brief:k,tags:[]}},{headers:S})).data)||void 0===i?void 0:i.data)||void 0===n?void 0:n.notepad)||void 0===r?void 0:r.id,!E)return void console.error("[MaiMemo] Created notepad but no id returned")}this.configService.setObjectConfig("maimemoSyncConfig",Object.assign(Object.assign({},v),{notepadId:E}),"thirdpartyToken")}catch(e){return void console.error("[MaiMemo] Failed to resolve notepadId:",null===(l=null==e?void 0:e.response)||void 0===l?void 0:l.status,JSON.stringify(null!==(d=null===(s=null==e?void 0:e.response)||void 0===s?void 0:s.data)&&void 0!==d?d:e))}try{let t="";try{t=(null===(m=null===(u=null===(c=(yield e.get(`https://open.maimemo.com/open/api/v1/memo/notepads/${E}`,{headers:S})).data)||void 0===c?void 0:c.data)||void 0===u?void 0:u.notepad)||void 0===m?void 0:m.content)||""}catch(e){return void console.error("[MaiMemo] Failed to fetch notepad content:",null===(p=null==e?void 0:e.response)||void 0===p?void 0:p.status,JSON.stringify(null!==(g=null===(h=null==e?void 0:e.response)||void 0===h?void 0:h.data)&&void 0!==g?g:e))}const o=t.split("\n").map((e=>e.trim())).filter((e=>e.length>0));if(o.includes(a))return;o.push(a),yield e.post(`https://open.maimemo.com/open/api/v1/memo/notepads/${E}`,{id:E,notepad:{status:"PUBLISHED",content:o.join("\n"),title:k,brief:k,tags:[]}},{headers:S})}catch(e){throw console.error(`[MaiMemo] Failed to add word "${a}" to notepad "${k}" (${E}):`,null===(f=null==e?void 0:e.response)||void 0===f?void 0:f.status,JSON.stringify(null!==(N=null===(y=null==e?void 0:e.response)||void 0===y?void 0:y.data)&&void 0!==N?N:e)),e}}catch(e){console.error("[MaiMemo] Sync error for word:",a,null===(v=null==e?void 0:e.response)||void 0===v?void 0:v.status,JSON.stringify(null!==(k=null===(b=null==e?void 0:e.response)||void 0===b?void 0:b.data)&&void 0!==k?k:e))}})),this.configService=a}}class Ye extends Qe{}export{S as CommonTool,ze as ConfigService,Be as HighlightUtil,Ae as KOReaderUtil,A as KookitConfig,ye as LoginHelper,Ge as NoteSyncManager,he as ReaderRequest,ve as ReadingTimeUtil,ce as SqlStatement,Ne as SyncHelper,oe as SyncUtil,ge as ThirdpartyRequest,fe as UserRequest,Ye as WordSyncManager}; +import e from"axios";import{Storage as a}from"megajs";import{Buffer as t}from"buffer";import{S3Client as o,ListObjectsV2Command as i,DeleteObjectCommand as n,PutObjectCommand as r,GetObjectCommand as l}from"@aws-sdk/client-s3";import s from"crypto-js";import{AuthType as d,createClient as c}from"webdav/dist/web/index.js";import{SSE as u}from"sse.js";function m(e,a,t,o){return new(t||(t=Promise))((function(i,n){function r(e){try{s(o.next(e))}catch(e){n(e)}}function l(e){try{s(o.throw(e))}catch(e){n(e)}}function s(e){var a;e.done?i(e.value):(a=e.value,a instanceof t?a:new t((function(e){e(a)}))).then(r,l)}s((o=o.apply(e,a||[])).next())}))}const p=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,h=["books","notes","bookmarks","plugins","words"],g=e=>{const a=atob(e),t=a.length,o=new Uint8Array(t);for(let e=0;e{let a="";const t=new Uint8Array(e),o=t.byteLength;for(let e=0;ee.toString(16).padStart(2,"0"))).join("")}))}function N(e){const a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],t=(e,a)=>e>>>a|e<<32-a,o=(e,a,t)=>e&a^~e&t,i=(e,a,t)=>e&a^e&t^a&t,n=e=>t(e,2)^t(e,13)^t(e,22),r=e=>t(e,6)^t(e,11)^t(e,25),l=e=>t(e,7)^t(e,18)^e>>>3,s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],d=8*e.length,c=(960-(8*e.length+1)%512)%512,u=e.length+Math.ceil((c+1)/8)+8,m=new Uint8Array(u);m.set(e),m[e.length]=128;new DataView(m.buffer,m.byteLength-8).setBigUint64(0,BigInt(d),!1);for(let e=0;e>>10)+c[e-7]+l(c[e-15])+c[e-16]>>>0);let[u,h,g,f,y,N,v,b]=s;for(let e=0;e<64;e++){const t=b+r(y)+o(y,N,v)+a[e]+c[e]>>>0,l=n(u)+i(u,h,g)>>>0;b=v,v=N,N=y,y=f+t>>>0,f=g,g=h,h=u,u=t+l>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+f>>>0,s[4]=s[4]+y>>>0,s[5]=s[5]+N>>>0,s[6]=s[6]+v>>>0,s[7]=s[7]+b>>>0}var p;const h=new ArrayBuffer(32),g=new DataView(h);return s.forEach(((e,a)=>{g.setUint32(4*a,e,!1)})),h}const v={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let a="",t=0;const o=this._stringToUtf8Bytes(e),i=o.length;for(;t>2,s=(3&e)<<4|n>>4,d=(15&n)<<2|r>>6,c=63&r;a+=this._chars.charAt(l),a+=this._chars.charAt(s),a+=t-2>=i?"=":this._chars.charAt(d),a+=t-1>=i?"=":this._chars.charAt(c)}return a},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const a=[];let t=0;const o=e.length;for(;t>4,s=(15&i)<<4|n>>2,d=(3&n)<<6|r;a.push(l),-1!==n&&a.push(s),-1!==r&&a.push(d)}return this._utf8BytesToString(a)},_stringToUtf8Bytes(e){const a=[];for(let t=0;t>6),a.push(128|63&o);else if(55296==(64512&o)&&t+1>18),a.push(128|e>>12&63),a.push(128|e>>6&63),a.push(128|63&e)}else a.push(239,191,189),t--}else a.push(224|o>>12),a.push(128|o>>6&63),a.push(128|63&o)}return a},_utf8BytesToString(e){let a="",t=0;for(;t65535){const t=e-65536;a+=String.fromCharCode(55296|t>>10),a+=String.fromCharCode(56320|1023&t)}else a+=String.fromCharCode(e)}else a+="�"}else a+="�"}return a},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}},b=e=>{const a=(e,a)=>{const t=(65535&e)+(65535&a);return(e>>16)+(a>>16)+(t>>16)<<16|65535&t},t=(e,t,o,i,n,r)=>{return a((l=a(a(t,e),a(i,r)))<<(s=n)|l>>>32-s,o);var l,s},o=(e,a,o,i,n,r,l)=>t(a&o|~a&i,e,a,n,r,l),i=(e,a,o,i,n,r,l)=>t(a&i|o&~i,e,a,n,r,l),n=(e,a,o,i,n,r,l)=>t(a^o^i,e,a,n,r,l),r=(e,a,o,i,n,r,l)=>t(o^(a|~i),e,a,n,r,l),l=e.length,s=1+(l+8>>6),d=new Array(16*s).fill(0);for(let a=0;a>2]|=e[a]<>2]|=128<{let a="";for(let t=0;t<4;t++)a+=("0"+(e>>8*t&255).toString(16)).slice(-2);return a})).join("")};class k{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return m(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((a,t)=>{if(this.hasFailedTasks)return void a(void 0);const o=()=>m(this,void 0,void 0,(function*(){if(this.hasFailedTasks)return this.completedTasks++,void a(void 0);try{this.runningTasks++;const t=yield e();return this.completedTasks++,a(t),t}catch(e){throw this.completedTasks++,t(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0;){const e=this.queue.shift();e&&e()}else if(this.queue.length>0&&this.runningTasks"application/json"===e?"json":e.startsWith("image/")?e.split("/")[1]:"application/zip"===e?"zip":"application/epub+zip"===e?"epub":"text/plain"===e?"txt":"application/pdf"===e?"pdf":"application/x-mobipocket-ebook"===e?"mobi":"application/vnd.amazon.ebook"===e?"azw3":"application/x-cbz"===e?"cbz":"application/x-cbr"===e?"cbr":"application/x-cbt"===e?"cbt":"application/x-cb7"===e?"cb7":"application/x-fictionbook+xml"===e?"fb2":"text/html"===e?"html":"text/css"===e?"css":"application/javascript"===e?"js":"application/xml"===e?"xml":"application/xhtml+xml"===e?"xhtml":"application/oebps-package+xml"===e?"opf":"application/x-dtbncx+xml"===e?"ncx":"audio/mpeg"===e?"mp3":"audio/wav"===e?"wav":"audio/ogg"===e?"ogg":"video/mp4"===e?"mp4":"video/webm"===e?"webm":"video/x-msvideo"===e?"avi":"video/x-ms-wmv"===e?"wmv":"video/x-flv"===e?"flv":"application/x-mpegURL"===e?"m3u8":"video/MP2T"===e?"ts":"video/3gpp"===e?"3gp":"video/3gpp2"===e?"3g2":"application/x-sqlite3"===e?"db":"",databaseList:h,configList:["themeColors","readingTime","appVersion","cloudSyncTime","lastSyncTime","recentBooks","koreaderBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","aiModelConfig","readingStats","noteTags","recordLocation","thirdpartyToken","sortedShelfList","kindleDeviceList","thirdpartyToken","opdsCatalogs","opdsCatalogList"],copyArrayBuffer:e=>{var a=new ArrayBuffer(e.byteLength);return new Uint8Array(a).set(new Uint8Array(e)),a},base64ToArrayBuffer:g,arrayBufferToBase64:f,generateSHA256Hash:y,simpleEncrypt:function(e,a){if(!e||!a)return"";const t=N((new TextEncoder).encode(a)),o=Array.from(new Uint8Array(t)),i=(new TextEncoder).encode(e),n=new Uint8Array(i.length);for(let e=0;e{const a=new Set(["anthropic","zhipu","doubao","moonshot","deepseek","minimax","minimaxi"]),t=new Set(["qwen","hunyuan","siliconflow","siliconflowglobal","infini"]),o=new Set(["sensenova","openai"]),i=new Set(["ollama"]);return e&&"custom"!==e?a.has(e)?{thinking:{type:"disabled"}}:t.has(e)?{enable_thinking:!1}:o.has(e)?{reasoning_effort:"none"}:i.has(e)?{think:!1}:{}:{}},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","sina.cn","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","live.cn","msn.cn","msn.com","aliyun.com","sohu.com","yandex.com","naver.com","mail.ru","yahoo.co.jp","139.com","189.com","yandex.ru","189.cn"],Base64:v};const E={cloudUrl:"https://cloud.koodoreader.com",cloudCNUrl:"https://cloud.koodoreader.cn",testUrl:"https://cloudtestv2.960960.xyz",devUrl:"http://192.168.28.159:8000"},C={callbackUrl:"https://web.koodoreader.com/",cnCallbackUrl:"https://web.koodoreader.cn/",dropboxClientId:"vnc67byrssocvy1",yandexClientId:"e5305b62f53844b1994f77a840fd0a37",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",duboxClientId:"kc0Ls6xLZugGgLLVhZ8yhUU1cRkRoKNU",yiyiwuClientId:"100197197",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",appleClientId:"com.koodoreader.auth",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"},T={google:{clientId:C.googleClientId,scopes:["openid email profile"],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{prompt:"consent",scope:"openid email profile"}},microsoft:{clientId:C.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:C.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:""}},github:{clientId:C.githubClientId,scopes:["user:email"],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"user:email"}},apple:{clientId:C.appleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:""}}},w=["backgroundColor","textColor","fontSize","margin","letterSpacing","paraSpacing","scale","brightness","fontFamily","subFontFamily","lineHeight","textAlign","textOrientation","convertChinese","selectAction","fullTranslationMode","readerMode","pdfReaderMode","isBold","isIndent","isSliding","isUnderline","isShadow","isItalic","isInvert","isBionic","isHyphenation","isOrphanWidow","isKeepPDFBackground","isAllowScript","isStartFromEven"];var A={CloudMode:"test",CloudConfig:E,ConvertLangMap:{en:"English",zhCN:"Chinese",zhTW:"Chinese",zhMO:"Chinese",tr:"Turkish",ar:"Arabic",ro:"Romanian",pl:"Polish",cs:"Czech",ja:"Japanese",ta:"Tamil",uk:"Ukrainian",sl:"Slovenian",bo:"Tibetan",id:"Indonesian",hy:"Armenian",el:"Greek",hu:"Hungarian",hi:"Hindi",bg:"Bulgarian",nl:"Dutch",it:"Italian",bn:"Bengali",tl:"Tagalog",sv:"Swedish",ga:"Irish",ko:"Korean",de:"German",ru:"Russian",es:"Spanish",fr:"French",fa:"Persian",ptBR:"Portuguese",th:"Thai",sr:"Serbian",am:"Amharic",da:"Danish",fi:"Finnish",ie:"Interlingue",pt:"Portuguese",vi:"Vietnamese"},ContentRegxConfig:[{label:"Default parser",value:"Default parser",subtitle:"Suitable for most txt files",regex:""},{label:"Chinese novel parser",value:"Chinese novel parser",subtitle:"Suitable for most Chinese novels, eg. 第一章,第2回",regex:"^\\s*(第[0-9一二三四五六七八九十百千万零壹贰叁肆伍陆柒捌玖拾佰仟]+[章回])\\s*"},{label:"English novel parser",value:"English novel parser",subtitle:"Suitable for most English novels, eg. Chapter 1, Part II",regex:"^\\s*(Chapter|Part|Book|CHAPTER|PART|BOOK)\\s*"},{label:"Number parser",value:"Number parser",subtitle:"Suitable for novels with number chapter titles, eg. 1, 2, 3",regex:"^\\s*([0-9]+[\\s.、::·\\-—]+|[一二三四五六七八九十百千万零]+[\\s.、::·\\-—]+).+"}],StyleKeys:w,ThirdpartyConfig:C,LoginAuthRequest:T,LoginDiscovery:{microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},facebook:{authorizationEndpoint:"https://www.facebook.com/v12.0/dialog/oauth",tokenEndpoint:"https://graph.facebook.com/v12.0/oauth/access_token"},github:{authorizationEndpoint:"https://github.com/login/oauth/authorize",tokenEndpoint:"https://github.com/login/oauth/access_token"},apple:{authorizationEndpoint:"https://appleid.apple.com/auth/authorize",tokenEndpoint:"https://appleid.apple.com/auth/token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:{dropbox:{clientId:C.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{token_access_type:"offline"}},yandex:{clientId:C.yandexClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{response_type:"code",force_confirm:"true"}},boxnet:{clientId:C.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:C.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{grant_type:"authorization_code"}},dubox:{clientId:C.duboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{response_type:"code",scope:"basic,netdisk",device_id:"119827642",qrcode:"1"}},yiyiwu:{clientId:C.yiyiwuClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{response_type:"code"}},adrive:{clientId:C.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:C.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:C.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.file",access_type:"offline"}},microsoft_exp:{clientId:C.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{scope:"files.readwrite.all offline_access"}},google_exp:{clientId:C.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:C.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive",access_type:"offline"}}},DriveDiscovery:{dropbox:{authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",tokenEndpoint:"https://www.dropbox.com/oauth2/token"},yandex:{authorizationEndpoint:"https://oauth.yandex.com/authorize",tokenEndpoint:"https://oauth.yandex.com/token"},boxnet:{authorizationEndpoint:"https://account.box.com/api/oauth2/authorize",tokenEndpoint:"https://api.box.com/oauth2/token"},pcloud:{authorizationEndpoint:"https://my.pcloud.com/oauth2/authorize",tokenEndpoint:"https://api.pcloud.com/oauth2_token"},dubox:{authorizationEndpoint:"https://openapi.baidu.com/oauth/2.0/authorize",tokenEndpoint:"https://openapi.baidu.com/oauth/2.0/token"},yiyiwu:{authorizationEndpoint:"https://passportapi.115.com/open/authorize",tokenEndpoint:"https://passportapi.115.com/open/authorize"},adrive:{authorizationEndpoint:"https://openapi.alipan.com/oauth/authorize",tokenEndpoint:"https://openapi.alipan.com/oauth/token"},microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},microsoft_exp:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google_exp:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}},AiProviderList:[{id:"custom",name:"Custom model",defaultEndpoint:"",modelsEndpoint:"",isCNAvailable:!0},{id:"openai",name:"OpenAI",defaultEndpoint:"https://api.openai.com/v1",modelsEndpoint:"https://api.openai.com/v1/models"},{id:"anthropic",name:"Anthropic",defaultEndpoint:"https://api.anthropic.com/v1",modelsEndpoint:"https://api.anthropic.com/v1/models"},{id:"google",name:"Google Gemini",defaultEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai",modelsEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai/models"},{id:"deepseek",name:"DeepSeek",defaultEndpoint:"https://api.deepseek.com/v1",modelsEndpoint:"https://api.deepseek.com/v1/models",isCNAvailable:!0},{id:"mistral",name:"Mistral AI",defaultEndpoint:"https://api.mistral.ai/v1",modelsEndpoint:"https://api.mistral.ai/v1/models"},{id:"cohere",name:"Cohere",defaultEndpoint:"https://api.cohere.ai/compatibility/v1",modelsEndpoint:"https://api.cohere.ai/compatibility/v1/models"},{id:"groq",name:"Groq",defaultEndpoint:"https://api.groq.com/openai/v1",modelsEndpoint:"https://api.groq.com/openai/v1/models"},{id:"together",name:"Together AI",defaultEndpoint:"https://api.together.xyz/v1",modelsEndpoint:"https://api.together.xyz/v1/models"},{id:"fireworks",name:"Fireworks AI",defaultEndpoint:"https://api.fireworks.ai/inference/v1",modelsEndpoint:"https://api.fireworks.ai/inference/v1/models"},{id:"perplexity",name:"Perplexity",defaultEndpoint:"https://api.perplexity.ai",modelsEndpoint:"https://api.perplexity.ai/v1/models"},{id:"openrouter",name:"OpenRouter",defaultEndpoint:"https://openrouter.ai/api/v1",modelsEndpoint:"https://openrouter.ai/api/v1/models"},{id:"ai21",name:"AI21 Labs",defaultEndpoint:"https://api.ai21.com/studio/v1",modelsEndpoint:"https://api.ai21.com/studio/v1/models"},{id:"xai",name:"xAI (Grok)",defaultEndpoint:"https://api.x.ai/v1",modelsEndpoint:"https://api.x.ai/v1/models"},{id:"sambanova",name:"SambaNova",defaultEndpoint:"https://api.sambanova.ai/v1",modelsEndpoint:"https://api.sambanova.ai/v1/models"},{id:"cerebras",name:"Cerebras",defaultEndpoint:"https://api.cerebras.ai/v1",modelsEndpoint:"https://api.cerebras.ai/v1/models"},{id:"hyperbolic",name:"Hyperbolic",defaultEndpoint:"https://api.hyperbolic.xyz/v1",modelsEndpoint:"https://api.hyperbolic.xyz/v1/models"},{id:"novita",name:"Novita AI",defaultEndpoint:"https://api.novita.ai/openai",modelsEndpoint:"https://api.novita.ai/openai/models"},{id:"lepton",name:"Lepton AI",defaultEndpoint:"https://llm.lepton.run/api/v1",modelsEndpoint:"https://llm.lepton.run/api/v1/models"},{id:"deepinfra",name:"DeepInfra",defaultEndpoint:"https://api.deepinfra.com/v1/openai",modelsEndpoint:"https://api.deepinfra.com/v1/openai/models"},{id:"replicate",name:"Replicate",defaultEndpoint:"https://api.replicate.com/v1",modelsEndpoint:"https://api.replicate.com/v1/models"},{id:"zhipu",name:"Zhipu AI (智谱)",defaultEndpoint:"https://open.bigmodel.cn/api/paas/v4",modelsEndpoint:"https://open.bigmodel.cn/api/paas/v4/models",isCNAvailable:!0},{id:"qwen",name:"Alibaba Qwen (通义千问)",defaultEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1",modelsEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/models",isCNAvailable:!0},{id:"moonshot",name:"Moonshot (月之暗面)",defaultEndpoint:"https://api.moonshot.cn/v1",modelsEndpoint:"https://api.moonshot.cn/v1/models",isCNAvailable:!0},{id:"baidu",name:"Baidu ERNIE (文心一言)",defaultEndpoint:"https://qianfan.baidubce.com/v2",modelsEndpoint:"https://qianfan.baidubce.com/v2/models",isCNAvailable:!0},{id:"doubao",name:"Volcengine Doubao (豆包)",defaultEndpoint:"https://ark.cn-beijing.volces.com/api/v3",modelsEndpoint:"https://ark.cn-beijing.volces.com/api/v3/models",isCNAvailable:!0},{id:"spark",name:"iFlytek Spark (讯飞星火)",defaultEndpoint:"https://spark-api-open.xf-yun.com/v1",modelsEndpoint:"https://spark-api-open.xf-yun.com/v1/models",isCNAvailable:!0},{id:"hunyuan",name:"Tencent Hunyuan (腾讯混元)",defaultEndpoint:"https://api.hunyuan.cloud.tencent.com/v1",modelsEndpoint:"https://api.hunyuan.cloud.tencent.com/v1/models",isCNAvailable:!0},{id:"minimaxi",name:"MiniMax (国内版)",defaultEndpoint:"https://api.minimaxi.com/v1",modelsEndpoint:"https://api.minimaxi.com/v1/models",isCNAvailable:!0},{id:"minimax",name:"MiniMax (国际版)",defaultEndpoint:"https://api.minimax.io/v1",modelsEndpoint:"https://api.minimax.io/v1/models"},{id:"baichuan",name:"Baichuan (百川)",defaultEndpoint:"https://api.baichuan-ai.com/v1",modelsEndpoint:"https://api.baichuan-ai.com/v1/models",isCNAvailable:!0},{id:"stepfun",name:"StepFun (阶跃星辰)",defaultEndpoint:"https://api.stepfun.com/v1",modelsEndpoint:"https://api.stepfun.com/v1/models",isCNAvailable:!0},{id:"lingyi",name:"Lingyiwanwu (零一万物)",defaultEndpoint:"https://api.lingyiwanwu.com/v1",modelsEndpoint:"https://api.lingyiwanwu.com/v1/models",isCNAvailable:!0},{id:"siliconflow",name:"SiliconFlow (硅基流动)",defaultEndpoint:"https://api.siliconflow.cn/v1",modelsEndpoint:"https://api.siliconflow.cn/v1/models",isCNAvailable:!0},{id:"siliconflowglobal",name:"SiliconFlow (国际版)",defaultEndpoint:"https://api.siliconflow.com/v1",modelsEndpoint:"https://api.siliconflow.com/v1/models"},{id:"sensenova",name:"SenseNova (日日新)",defaultEndpoint:"https://token.sensenova.cn/v1",modelsEndpoint:"https://token.sensenova.cn/v1/models",isCNAvailable:!0},{id:"infini",name:"Infini AI (无问芯穹)",defaultEndpoint:"https://cloud.infini-ai.com/maas/v1",modelsEndpoint:"https://cloud.infini-ai.com/maas/v1/models",isCNAvailable:!0},{id:"ollama",name:"Ollama (Local)",defaultEndpoint:"http://localhost:11434/v1",modelsEndpoint:"http://localhost:11434/v1/models",isCNAvailable:!0},{id:"lmstudio",name:"LM Studio (Local)",defaultEndpoint:"http://localhost:1234/v1",modelsEndpoint:"http://localhost:1234/v1/models",isCNAvailable:!0},{id:"vllm",name:"vLLM (Local)",defaultEndpoint:"http://localhost:8000/v1",modelsEndpoint:"http://localhost:8000/v1/models",isCNAvailable:!0},{id:"azure",name:"Azure OpenAI",defaultEndpoint:"",modelsEndpoint:""},{id:"aws_bedrock",name:"AWS Bedrock",defaultEndpoint:"",modelsEndpoint:""}],DefaultPrompts:{aiTranslate:"You are a professional translator. Translate the following text from {from} to {to}. Only return the translated text, no explanations.\n\nText: {text}",aiDict:"You are a professional dictionary assistant. Analyze the word or phrase: {word}\nProvide a comprehensive explanation including pronunciation, definitions, example sentences, and usage notes using {to} as the target language. ",aiAssistance:"You are a helpful reading assistant. The user is reading a book. Here is the context:\n{text}\n\nAnswer the user's question concisely and helpfully, and reply with the same language."},SpeechList:[{label:"English",code:"en",example:"To be, or not to be, that is the question."},{label:"Simplified Chinese",code:"zh",example:"千里之行,始于足下。"},{label:"Japanese",code:"ja",example:"猿も木から落ちる。"},{label:"Korean",code:"ko",example:"가는 날이 장날이다."},{label:"French",code:"fr",example:"Liberté, égalité, fraternité."},{label:"German",code:"de",example:"Der Weg ist das Ziel."},{label:"Spanish",code:"es",example:"La vida es un sueño."},{label:"Italian",code:"it",example:"Dolce far niente."},{label:"Russian",code:"ru",example:"Век живи, век учись."},{label:"Portuguese",code:"pt",example:"Saudade é um sentimento profundo."},{label:"Hindi",code:"hi",example:"सपने वो नहीं जो हम सोते वक्त देखते हैं।"},{label:"Afrikaans",code:"af",example:"Die lewe is 'n geskenk."},{label:"Amharic",code:"am",example:"ዕውቀት ብርሃን ነው።"},{label:"Arabic",code:"ar",example:"العلم نور والجهل ظلام."},{label:"Azerbaijani",code:"az",example:"Elm işıqdır, cəhalət zülmət."},{label:"Bulgarian",code:"bg",example:"Знанието е сила."},{label:"Bengali",code:"bn",example:"জ্ঞানই শক্তি।"},{label:"Bosnian",code:"bs",example:"Znanje je moć."},{label:"Catalan",code:"ca",example:"El saber no ocupa lloc."},{label:"Czech",code:"cs",example:"Bez práce nejsou koláče."},{label:"Welsh",code:"cy",example:"Nid aur popeth melyn."},{label:"Danish",code:"da",example:"Lykken er ikke et sted, men en retning."},{label:"Greek",code:"el",example:"Η γνώση είναι δύναμη."},{label:"Estonian",code:"et",example:"Teadmine on jõud."},{label:"Basque",code:"eu",example:"Jakitea boterea da."},{label:"Persian",code:"fa",example:"دانش قدرت است."},{label:"Finnish",code:"fi",example:"Tieto on valtaa."},{label:"Filipino",code:"fil",example:"Ang kaalaman ay kapangyarihan."},{label:"Irish",code:"ga",example:"Is fearr Gaeilge briste ná Béarla cliste."},{label:"Galician",code:"gl",example:"O saber non ocupa lugar."},{label:"Gujarati",code:"gu",example:"જ્ઞાન શક્તિ છે."},{label:"Hebrew",code:"he",example:"ידע הוא כוח."},{label:"Croatian",code:"hr",example:"Znanje je moć."},{label:"Hungarian",code:"hu",example:"A tudás hatalom."},{label:"Armenian",code:"hy",example:"Գիտելիքը ուժ է."},{label:"Indonesian",code:"id",example:"Pengetahuan adalah kekuatan."},{label:"Icelandic",code:"is",example:"Þekking er máttur."},{label:"Inuktitut",code:"iu",example:"ᐃᓕᓐᓂᐊᕐᓂᖅ ᐱᒻᒪᕆᐅᕗᖅ."},{label:"Javanese",code:"jv",example:"Ilmu iku kelakone kanthi laku."},{label:"Georgian",code:"ka",example:"ცოდნა ძალაა."},{label:"Kazakh",code:"kk",example:"Білім — күш."},{label:"Khmer",code:"km",example:"ចំណេះដឹងគឺជាអំណាច។"},{label:"Kannada",code:"kn",example:"ಜ್ಞಾನವೇ ಶಕ್ತಿ."},{label:"Lao",code:"lo",example:"ຄວາມຮູ້ຄືພະລັງ."},{label:"Lithuanian",code:"lt",example:"Žinios yra jėga."},{label:"Latvian",code:"lv",example:"Zināšanas ir spēks."},{label:"Macedonian",code:"mk",example:"Знаењето е моќ."},{label:"Malayalam",code:"ml",example:"അറിവ് ശക്തിയാണ്."},{label:"Mongolian",code:"mn",example:"Мэдлэг бол хүч."},{label:"Marathi",code:"mr",example:"ज्ञान हीच शक्ती आहे."},{label:"Malay",code:"ms",example:"Ilmu itu cahaya."},{label:"Maltese",code:"mt",example:"L-għarfien huwa l-poter."},{label:"Burmese",code:"my",example:"ဗဟုသုတသည် အားဖြစ်သည်။"},{label:"Norwegian",code:"nb",example:"Kunnskap er makt."},{label:"Nepali",code:"ne",example:"ज्ञान नै शक्ति हो।"},{label:"Dutch",code:"nl",example:"Kennis is macht."},{label:"Odia",code:"or",example:"ଜ୍ଞାନ ହିଁ ଶକ୍ତି।"},{label:"Punjabi",code:"pa",example:"ਗਿਆਨ ਹੀ ਸ਼ਕਤੀ ਹੈ।"},{label:"Polish",code:"pl",example:"Wiedza to potęga."},{label:"Pashto",code:"ps",example:"د پوهې ډیوه روښانه ده."},{label:"Romanian",code:"ro",example:"Cartea este o comoară."},{label:"Sinhala",code:"si",example:"දැනුම බලයකි."},{label:"Slovak",code:"sk",example:"Vedomosti sú sila."},{label:"Slovenian",code:"sl",example:"Znanje je moč."},{label:"Somali",code:"so",example:"Aqoontu waa iftiin."},{label:"Albanian",code:"sq",example:"Dija është fuqi."},{label:"Serbian",code:"sr",example:"Знање је моћ."},{label:"Sundanese",code:"su",example:"Élmu éta cahaya."},{label:"Swedish",code:"sv",example:"Kunskap är makt."},{label:"Swahili",code:"sw",example:"Maarifa ni nguvu."},{label:"Tamil",code:"ta",example:"அறிவே ஆற்றல்."},{label:"Telugu",code:"te",example:"జ్ఞానమే శక్తి."},{label:"Thai",code:"th",example:"ความรู้คือพลัง."},{label:"Turkish",code:"tr",example:"Bilgi güçtür."},{label:"Ukrainian",code:"uk",example:"Знання — сила."},{label:"Urdu",code:"ur",example:"علم ہی طاقت ہے۔"},{label:"Uzbek",code:"uz",example:"Bilim – kuch."},{label:"Vietnamese",code:"vi",example:"Học vấn là sức mạnh."},{label:"Wu Chinese",code:"wuu",example:"学问是力量。"},{label:"Cantonese",code:"yue",example:"知識就係力量。"},{label:"Zulu",code:"zu",example:"Ulwazi lungamandla."}],HighlightStyleTypes:[{value:"background",label:"Highlight background"},{value:"underline",label:"Underline"},{value:"strikethrough",label:"Strikethrough"},{value:"wavy",label:"Wavy underline"}],HighlightPresetColors:{background:["#F3C9C9","#FEF3CD","#CEFACD","#CDE9FA"],underline:["#FF0000","#60A5FA","#FF9900","#2EFF2E"],strikethrough:["#FF0000","#60A5FA","#FF9900","#2EFF2E"],wavy:["#FF0000","#60A5FA","#FF9900","#2EFF2E"]},PresetThemeList:[{key:"yellow",textColor:"rgba(89, 68, 41,1)",backgroundColor:"rgba(233, 216, 188,1)",title:"羊皮"},{key:"green",textColor:"rgba(54, 80, 62,1)",backgroundColor:"rgba(197, 231, 207,1)",title:"护眼"},{key:"light",textColor:"rgba(0,0,0,1)",backgroundColor:"rgba(255,255,255,1)",title:"白天"},{key:"night",textColor:"rgba(255,255,255,1)",backgroundColor:"rgba(44,47,49,1)",title:"黑夜"},{key:"sepia",textColor:"rgba(93, 64, 55,1)",backgroundColor:"rgba(245, 235, 220,1)",title:"古卷"},{key:"blue",textColor:"rgba(28, 52, 84,1)",backgroundColor:"rgba(230, 240, 250,1)",title:"晨雾"},{key:"purple",textColor:"rgba(68, 42, 84,1)",backgroundColor:"rgba(240, 230, 250,1)",title:"紫萝"},{key:"pink",textColor:"rgba(84, 42, 68,1)",backgroundColor:"rgba(250, 235, 245,1)",title:"樱花"},{key:"brown",textColor:"rgba(74, 54, 42,1)",backgroundColor:"rgba(240, 230, 215,1)",title:"木纹"},{key:"gray",textColor:"rgba(64, 64, 64,1)",backgroundColor:"rgba(240, 240, 240,1)",title:"素雅"},{key:"darkgreen",textColor:"rgba(200, 220, 200,1)",backgroundColor:"rgba(25, 35, 30,1)",title:"深林"},{key:"darkblue",textColor:"rgba(200, 210, 230,1)",backgroundColor:"rgba(20, 30, 45,1)",title:"深海"},{key:"coral",textColor:"rgba(84, 50, 42,1)",backgroundColor:"rgba(255, 235, 230,1)",title:"珊瑚"},{key:"mint",textColor:"rgba(42, 74, 64,1)",backgroundColor:"rgba(230, 250, 245,1)",title:"薄荷"},{key:"lavender",textColor:"rgba(54, 42, 74,1)",backgroundColor:"rgba(245, 240, 255,1)",title:"薰衣"},{key:"cream",textColor:"rgba(74, 64, 42,1)",backgroundColor:"rgba(255, 250, 240,1)",title:"奶油"},{key:"darkbrown",textColor:"rgba(230, 215, 200,1)",backgroundColor:"rgba(35, 25, 20,1)",title:"深棕"},{key:"olive",textColor:"rgba(64, 74, 42,1)",backgroundColor:"rgba(240, 245, 230,1)",title:"橄榄"},{key:"rose",textColor:"rgba(84, 42, 54,1)",backgroundColor:"rgba(255, 240, 245,1)",title:"玫瑰"},{key:"slate",textColor:"rgba(54, 64, 74,1)",backgroundColor:"rgba(235, 240, 245,1)",title:"石板"}],OfficialVoiceList:[{name:"af_alloy",gender:"female",displayName:"Alloy",locale:"en-US",language:"English (US)"},{name:"af_aoede",gender:"female",displayName:"Aoede",locale:"en-US",language:"English (US)"},{name:"af_bella",gender:"female",displayName:"Bella",locale:"en-US",language:"English (US)"},{name:"af_heart",gender:"female",displayName:"Heart",locale:"en-US",language:"English (US)"},{name:"af_jessica",gender:"female",displayName:"Jessica",locale:"en-US",language:"English (US)"},{name:"af_kore",gender:"female",displayName:"Kore",locale:"en-US",language:"English (US)"},{name:"af_nicole",gender:"female",displayName:"Nicole",locale:"en-US",language:"English (US)"},{name:"af_nova",gender:"female",displayName:"Nova",locale:"en-US",language:"English (US)"},{name:"af_river",gender:"female",displayName:"River",locale:"en-US",language:"English (US)"},{name:"af_sarah",gender:"female",displayName:"Sarah",locale:"en-US",language:"English (US)"},{name:"af_sky",gender:"female",displayName:"Sky",locale:"en-US",language:"English (US)"},{name:"am_adam",gender:"male",displayName:"Adam",locale:"en-US",language:"English (US)"},{name:"am_echo",gender:"male",displayName:"Echo",locale:"en-US",language:"English (US)"},{name:"am_eric",gender:"male",displayName:"Eric",locale:"en-US",language:"English (US)"},{name:"am_fenrir",gender:"male",displayName:"Fenrir",locale:"en-US",language:"English (US)"},{name:"am_liam",gender:"male",displayName:"Liam",locale:"en-US",language:"English (US)"},{name:"am_michael",gender:"male",displayName:"Michael",locale:"en-US",language:"English (US)"},{name:"am_onyx",gender:"male",displayName:"Onyx",locale:"en-US",language:"English (US)"},{name:"am_puck",gender:"male",displayName:"Puck",locale:"en-US",language:"English (US)"},{name:"am_santa",gender:"male",displayName:"Santa",locale:"en-US",language:"English (US)"},{name:"bf_alice",gender:"female",displayName:"Alice",locale:"en-GB",language:"English (UK)"},{name:"bf_emma",gender:"female",displayName:"Emma",locale:"en-GB",language:"English (UK)"},{name:"bf_isabella",gender:"female",displayName:"Isabella",locale:"en-GB",language:"English (UK)"},{name:"bf_lily",gender:"female",displayName:"Lily",locale:"en-GB",language:"English (UK)"},{name:"bm_daniel",gender:"male",displayName:"Daniel",locale:"en-GB",language:"English (UK)"},{name:"bm_fable",gender:"male",displayName:"Fable",locale:"en-GB",language:"English (UK)"},{name:"bm_george",gender:"male",displayName:"George",locale:"en-GB",language:"English (UK)"},{name:"bm_lewis",gender:"male",displayName:"Lewis",locale:"en-GB",language:"English (UK)"},{name:"ef_dora",gender:"female",displayName:"Dora",locale:"es-ES",language:"Español"},{name:"em_alex",gender:"male",displayName:"Alex",locale:"es-ES",language:"Español"},{name:"em_santa",gender:"male",displayName:"Santa",locale:"es-ES",language:"Español"},{name:"ff_siwis",gender:"female",displayName:"Siwis",locale:"fr-FR",language:"Français"},{name:"hf_alpha",gender:"female",displayName:"Alpha",locale:"hi-IN",language:"हिन्दी"},{name:"hf_beta",gender:"female",displayName:"Beta",locale:"hi-IN",language:"हिन्दी"},{name:"hm_omega",gender:"male",displayName:"Omega",locale:"hi-IN",language:"हिन्दी"},{name:"hm_psi",gender:"male",displayName:"Psi",locale:"hi-IN",language:"हिन्दी"},{name:"if_sara",gender:"female",displayName:"Sara",locale:"it-IT",language:"Italiano"},{name:"im_nicola",gender:"male",displayName:"Nicola",locale:"it-IT",language:"Italiano"},{name:"jf_alpha",gender:"female",displayName:"Alpha",locale:"ja-JP",language:"日本語"},{name:"jf_gongitsune",gender:"female",displayName:"Gongitsune",locale:"ja-JP",language:"日本語"},{name:"jf_nezumi",gender:"female",displayName:"Nezumi",locale:"ja-JP",language:"日本語"},{name:"jf_tebukuro",gender:"female",displayName:"Tebukuro",locale:"ja-JP",language:"日本語"},{name:"jm_kumo",gender:"male",displayName:"Kumo",locale:"ja-JP",language:"日本語"},{name:"pf_dora",gender:"female",displayName:"Dora",locale:"pt-BR",language:"Português (Brasil)"},{name:"pm_alex",gender:"male",displayName:"Alex",locale:"pt-BR",language:"Português (Brasil)"},{name:"pm_santa",gender:"male",displayName:"Santa",locale:"pt-BR",language:"Português (Brasil)"},{name:"zf_xiaoxiao",gender:"female",displayName:"Xiaoxiao",locale:"zh-CN",language:"中文"},{name:"zm_yunxi",gender:"male",displayName:"Yunxi",locale:"zh-CN",language:"中文"},{name:"zf_xiaoyi",gender:"female",displayName:"Xiaoyi",locale:"zh-CN",language:"中文"},{name:"zm_yunyang",gender:"male",displayName:"Yunyang",locale:"zh-CN",language:"中文"},{name:"zm_yunxia",gender:"male",displayName:"Yunxia",locale:"zh-CN",language:"中文"},{name:"zm_yunjian",gender:"male",displayName:"Yunjian",locale:"zh-CN",language:"中文"},{name:"zf_xiaoni",gender:"female",displayName:"Xiaoni 陕西",locale:"zh-CN",language:"中文"},{name:"zf_xiaobei",gender:"female",displayName:"Xiaobei 辽宁",locale:"zh-CN",language:"中文"}],AzureTTSVoiceList:[{name:"de-DE-AmalaNeural",gender:"female",displayName:"Amala",locale:"de-DE"},{name:"de-DE-BerndNeural",gender:"male",displayName:"Bernd",locale:"de-DE"},{name:"de-DE-ConradNeural",gender:"male",displayName:"Conrad",locale:"de-DE"},{name:"de-DE-KatjaNeural",gender:"female",displayName:"Katja",locale:"de-DE"},{name:"en-GB-LibbyNeural",gender:"female",displayName:"Libby",locale:"en-GB"},{name:"en-GB-RyanNeural",gender:"male",displayName:"Ryan",locale:"en-GB"},{name:"en-GB-SoniaNeural",gender:"female",displayName:"Sonia",locale:"en-GB"},{name:"en-US-AmberNeural",gender:"female",displayName:"Amber",locale:"en-US"},{name:"en-US-AriaNeural",gender:"female",displayName:"Aria",locale:"en-US"},{name:"en-US-ChristopherNeural",gender:"male",displayName:"Christopher",locale:"en-US"},{name:"en-US-DavisNeural",gender:"male",displayName:"Davis",locale:"en-US"},{name:"en-US-EricNeural",gender:"male",displayName:"Eric",locale:"en-US"},{name:"en-US-GuyNeural",gender:"male",displayName:"Guy",locale:"en-US"},{name:"en-US-JaneNeural",gender:"female",displayName:"Jane",locale:"en-US"},{name:"en-US-JennyNeural",gender:"female",displayName:"Jenny",locale:"en-US"},{name:"en-US-MichelleNeural",gender:"female",displayName:"Michelle",locale:"en-US"},{name:"en-US-SaraNeural",gender:"female",displayName:"Sara",locale:"en-US"},{name:"es-ES-AbrilNeural",gender:"female",displayName:"Abril",locale:"es-ES"},{name:"es-ES-AlvaroNeural",gender:"male",displayName:"Álvaro",locale:"es-ES"},{name:"es-ES-ArnauNeural",gender:"male",displayName:"Arnau",locale:"es-ES"},{name:"es-ES-ElviraNeural",gender:"female",displayName:"Elvira",locale:"es-ES"},{name:"fr-FR-DeniseNeural",gender:"female",displayName:"Denise",locale:"fr-FR"},{name:"fr-FR-HenriNeural",gender:"male",displayName:"Henri",locale:"fr-FR"},{name:"it-IT-BenignoNeural",gender:"male",displayName:"Benigno",locale:"it-IT"},{name:"it-IT-DiegoNeural",gender:"male",displayName:"Diego",locale:"it-IT"},{name:"it-IT-ElsaNeural",gender:"female",displayName:"Elsa",locale:"it-IT"},{name:"it-IT-IsabellaNeural",gender:"female",displayName:"Isabella",locale:"it-IT"},{name:"ja-JP-KeitaNeural",gender:"male",displayName:"圭太",locale:"ja-JP"},{name:"ja-JP-NanamiNeural",gender:"female",displayName:"七海",locale:"ja-JP"},{name:"ko-KR-InJoonNeural",gender:"male",displayName:"인준",locale:"ko-KR"},{name:"ko-KR-SoonBokNeural",gender:"female",displayName:"순복",locale:"ko-KR"},{name:"ko-KR-SunHiNeural",gender:"female",displayName:"선히",locale:"ko-KR"},{name:"pt-BR-AntonioNeural",gender:"male",displayName:"Antônio",locale:"pt-BR"},{name:"pt-BR-FranciscaNeural",gender:"female",displayName:"Francisca",locale:"pt-BR"},{name:"pt-PT-DuarteNeural",gender:"male",displayName:"Duarte",locale:"pt-PT"},{name:"pt-PT-RaquelNeural",gender:"female",displayName:"Raquel",locale:"pt-PT"},{name:"ru-RU-DariyaNeural",gender:"female",displayName:"Дария",locale:"ru-RU"},{name:"ru-RU-DmitryNeural",gender:"male",displayName:"Дмитрий",locale:"ru-RU"},{name:"ru-RU-SvetlanaNeural",gender:"female",displayName:"Светлана",locale:"ru-RU"},{name:"yue-CN-XiaoMinNeural",gender:"female",displayName:"晓敏",locale:"yue-CN"},{name:"yue-CN-YunSongNeural",gender:"male",displayName:"云松",locale:"yue-CN"},{name:"zh-CN-XiaoxiaoNeural",gender:"female",displayName:"晓晓",locale:"zh-CN"},{name:"zh-CN-YunxiNeural",gender:"male",displayName:"云希",locale:"zh-CN"},{name:"zh-HK-HiuMaanNeural",gender:"female",displayName:"曉曼",locale:"zh-HK"},{name:"zh-HK-WanLungNeural",gender:"male",displayName:"雲龍",locale:"zh-HK"},{name:"zh-TW-HsiaoChenNeural",gender:"female",displayName:"曉臻",locale:"zh-TW"},{name:"zh-TW-YunJheNeural",gender:"male",displayName:"雲哲",locale:"zh-TW"},{name:"af-ZA-AdriNeural",gender:"female",displayName:"Adri",locale:"af-ZA"},{name:"af-ZA-WillemNeural",gender:"male",displayName:"Willem",locale:"af-ZA"},{name:"sq-AL-AnilaNeural",gender:"female",displayName:"Anila",locale:"sq-AL"},{name:"sq-AL-IlirNeural",gender:"male",displayName:"Ilir",locale:"sq-AL"},{name:"am-ET-AmehaNeural",gender:"male",displayName:"አምሀ",locale:"am-ET"},{name:"am-ET-MekdesNeural",gender:"female",displayName:"መቅደስ",locale:"am-ET"},{name:"ar-DZ-AminaNeural",gender:"female",displayName:"أمينة",locale:"ar-DZ"},{name:"ar-DZ-IsmaelNeural",gender:"male",displayName:"إسماعيل",locale:"ar-DZ"},{name:"ar-BH-AliNeural",gender:"male",displayName:"علي",locale:"ar-BH"},{name:"ar-BH-LailaNeural",gender:"female",displayName:"ليلى",locale:"ar-BH"},{name:"ar-EG-SalmaNeural",gender:"female",displayName:"سلمى",locale:"ar-EG"},{name:"ar-EG-ShakirNeural",gender:"male",displayName:"شاكر",locale:"ar-EG"},{name:"ar-IQ-BasselNeural",gender:"male",displayName:"باسل",locale:"ar-IQ"},{name:"ar-IQ-RanaNeural",gender:"female",displayName:"رنا",locale:"ar-IQ"},{name:"ar-JO-SanaNeural",gender:"female",displayName:"سناء",locale:"ar-JO"},{name:"ar-JO-TaimNeural",gender:"male",displayName:"تيم",locale:"ar-JO"},{name:"ar-KW-FahedNeural",gender:"male",displayName:"فهد",locale:"ar-KW"},{name:"ar-KW-NouraNeural",gender:"female",displayName:"نورا",locale:"ar-KW"},{name:"ar-LB-LaylaNeural",gender:"female",displayName:"ليلى",locale:"ar-LB"},{name:"ar-LB-RamiNeural",gender:"male",displayName:"رامي",locale:"ar-LB"},{name:"ar-LY-ImanNeural",gender:"female",displayName:"إيمان",locale:"ar-LY"},{name:"ar-LY-OmarNeural",gender:"male",displayName:"أحمد",locale:"ar-LY"},{name:"ar-MA-JamalNeural",gender:"male",displayName:"جمال",locale:"ar-MA"},{name:"ar-MA-MounaNeural",gender:"female",displayName:"منى",locale:"ar-MA"},{name:"ar-OM-AbdullahNeural",gender:"male",displayName:"عبدالله",locale:"ar-OM"},{name:"ar-OM-AyshaNeural",gender:"female",displayName:"عائشة",locale:"ar-OM"},{name:"ar-QA-AmalNeural",gender:"female",displayName:"أمل",locale:"ar-QA"},{name:"ar-QA-MoazNeural",gender:"male",displayName:"معاذ",locale:"ar-QA"},{name:"ar-SA-HamedNeural",gender:"male",displayName:"حامد",locale:"ar-SA"},{name:"ar-SA-ZariyahNeural",gender:"female",displayName:"زارية",locale:"ar-SA"},{name:"ar-SY-AmanyNeural",gender:"female",displayName:"أماني",locale:"ar-SY"},{name:"ar-SY-LaithNeural",gender:"male",displayName:"ليث",locale:"ar-SY"},{name:"ar-TN-HediNeural",gender:"male",displayName:"هادي",locale:"ar-TN"},{name:"ar-TN-ReemNeural",gender:"female",displayName:"ريم",locale:"ar-TN"},{name:"ar-AE-FatimaNeural",gender:"female",displayName:"فاطمة",locale:"ar-AE"},{name:"ar-AE-HamdanNeural",gender:"male",displayName:"حمدان",locale:"ar-AE"},{name:"ar-YE-MaryamNeural",gender:"female",displayName:"مريم",locale:"ar-YE"},{name:"ar-YE-SalehNeural",gender:"male",displayName:"صالح",locale:"ar-YE"},{name:"az-AZ-BabekNeural",gender:"male",displayName:"Babək",locale:"az-AZ"},{name:"az-AZ-BanuNeural",gender:"female",displayName:"Banu",locale:"az-AZ"},{name:"bn-BD-NabanitaNeural",gender:"female",displayName:"নবনীতা",locale:"bn-BD"},{name:"bn-BD-PradeepNeural",gender:"male",displayName:"প্রদ্বীপ",locale:"bn-BD"},{name:"bn-IN-BashkarNeural",gender:"male",displayName:"ভাস্কর",locale:"bn-IN"},{name:"bn-IN-TanishaaNeural",gender:"female",displayName:"তানিশা",locale:"bn-IN"},{name:"bs-BA-VesnaNeural",gender:"female",displayName:"Vesna",locale:"bs-BA"},{name:"bs-BA-GoranNeural",gender:"male",displayName:"Goran",locale:"bs-BA"},{name:"bg-BG-BorislavNeural",gender:"male",displayName:"Борислав",locale:"bg-BG"},{name:"bg-BG-KalinaNeural",gender:"female",displayName:"Калина",locale:"bg-BG"},{name:"my-MM-NilarNeural",gender:"female",displayName:"နီလာ",locale:"my-MM"},{name:"my-MM-ThihaNeural",gender:"male",displayName:"သီဟ",locale:"my-MM"},{name:"ca-ES-EnricNeural",gender:"male",displayName:"Enric",locale:"ca-ES"},{name:"ca-ES-JoanaNeural",gender:"female",displayName:"Joana",locale:"ca-ES"},{name:"zh-HK-HiuGaaiNeural",gender:"female",displayName:"曉佳",locale:"zh-HK"},{name:"zh-CN-XiaoyiNeural",gender:"female",displayName:"晓伊",locale:"zh-CN"},{name:"zh-CN-YunjianNeural",gender:"male",displayName:"云健",locale:"zh-CN"},{name:"zh-CN-YunxiaNeural",gender:"male",displayName:"云夏",locale:"zh-CN"},{name:"zh-CN-YunyangNeural",gender:"male",displayName:"云扬",locale:"zh-CN"},{name:"zh-CN-liaoning-XiaobeiNeural",gender:"female",displayName:"晓北 辽宁",locale:"zh-CN"},{name:"zh-CN-shaanxi-XiaoniNeural",gender:"female",displayName:"晓妮 陕西",locale:"zh-CN"},{name:"zh-TW-HsiaoYuNeural",gender:"female",displayName:"曉雨",locale:"zh-TW"},{name:"hr-HR-GabrijelaNeural",gender:"female",displayName:"Gabrijela",locale:"hr-HR"},{name:"hr-HR-SreckoNeural",gender:"male",displayName:"Srećko",locale:"hr-HR"},{name:"cs-CZ-AntoninNeural",gender:"male",displayName:"Antonín",locale:"cs-CZ"},{name:"cs-CZ-VlastaNeural",gender:"female",displayName:"Vlasta",locale:"cs-CZ"},{name:"da-DK-ChristelNeural",gender:"female",displayName:"Christel",locale:"da-DK"},{name:"da-DK-JeppeNeural",gender:"male",displayName:"Jeppe",locale:"da-DK"},{name:"nl-BE-ArnaudNeural",gender:"male",displayName:"Arnaud",locale:"nl-BE"},{name:"nl-BE-DenaNeural",gender:"female",displayName:"Dena",locale:"nl-BE"},{name:"nl-NL-ColetteNeural",gender:"female",displayName:"Colette",locale:"nl-NL"},{name:"nl-NL-FennaNeural",gender:"female",displayName:"Fenna",locale:"nl-NL"},{name:"nl-NL-MaartenNeural",gender:"male",displayName:"Maarten",locale:"nl-NL"},{name:"en-AU-WilliamMultilingualNeural",gender:"male",displayName:"William Multilingual",locale:"en-AU"},{name:"en-AU-NatashaNeural",gender:"female",displayName:"Natasha",locale:"en-AU"},{name:"en-CA-ClaraNeural",gender:"female",displayName:"Clara",locale:"en-CA"},{name:"en-CA-LiamNeural",gender:"male",displayName:"Liam",locale:"en-CA"},{name:"en-HK-YanNeural",gender:"female",displayName:"Yan",locale:"en-HK"},{name:"en-HK-SamNeural",gender:"male",displayName:"Sam",locale:"en-HK"},{name:"en-IN-NeerjaNeural",gender:"female",displayName:"Neerja",locale:"en-IN"},{name:"en-IN-PrabhatNeural",gender:"male",displayName:"Prabhat",locale:"en-IN"},{name:"en-IE-ConnorNeural",gender:"male",displayName:"Connor",locale:"en-IE"},{name:"en-IE-EmilyNeural",gender:"female",displayName:"Emily",locale:"en-IE"},{name:"en-KE-AsiliaNeural",gender:"female",displayName:"Asilia",locale:"en-KE"},{name:"en-KE-ChilembaNeural",gender:"male",displayName:"Chilemba",locale:"en-KE"},{name:"en-NZ-MitchellNeural",gender:"male",displayName:"Mitchell",locale:"en-NZ"},{name:"en-NZ-MollyNeural",gender:"female",displayName:"Molly",locale:"en-NZ"},{name:"en-NG-AbeoNeural",gender:"male",displayName:"Abeo",locale:"en-NG"},{name:"en-NG-EzinneNeural",gender:"female",displayName:"Ezinne",locale:"en-NG"},{name:"en-PH-JamesNeural",gender:"male",displayName:"James",locale:"en-PH"},{name:"en-PH-RosaNeural",gender:"female",displayName:"Rosa",locale:"en-PH"},{name:"en-US-AvaNeural",gender:"female",displayName:"Ava",locale:"en-US"},{name:"en-US-AndrewNeural",gender:"male",displayName:"Andrew",locale:"en-US"},{name:"en-US-EmmaNeural",gender:"female",displayName:"Emma",locale:"en-US"},{name:"en-US-BrianNeural",gender:"male",displayName:"Brian",locale:"en-US"},{name:"en-SG-LunaNeural",gender:"female",displayName:"Luna",locale:"en-SG"},{name:"en-SG-WayneNeural",gender:"male",displayName:"Wayne",locale:"en-SG"},{name:"en-ZA-LeahNeural",gender:"female",displayName:"Leah",locale:"en-ZA"},{name:"en-ZA-LukeNeural",gender:"male",displayName:"Luke",locale:"en-ZA"},{name:"en-TZ-ElimuNeural",gender:"male",displayName:"Elimu",locale:"en-TZ"},{name:"en-TZ-ImaniNeural",gender:"female",displayName:"Imani",locale:"en-TZ"},{name:"en-GB-MaisieNeural",gender:"female",displayName:"Maisie",locale:"en-GB"},{name:"en-GB-ThomasNeural",gender:"male",displayName:"Thomas",locale:"en-GB"},{name:"en-US-AnaNeural",gender:"female",displayName:"Ana",locale:"en-US"},{name:"en-US-AndrewMultilingualNeural",gender:"male",displayName:"Andrew Multilingual",locale:"en-US"},{name:"en-US-AvaMultilingualNeural",gender:"female",displayName:"Ava Multilingual",locale:"en-US"},{name:"en-US-BrianMultilingualNeural",gender:"male",displayName:"Brian Multilingual",locale:"en-US"},{name:"en-US-EmmaMultilingualNeural",gender:"female",displayName:"Emma Multilingual",locale:"en-US"},{name:"en-US-RogerNeural",gender:"male",displayName:"Roger",locale:"en-US"},{name:"en-US-SteffanNeural",gender:"male",displayName:"Steffan",locale:"en-US"},{name:"et-EE-AnuNeural",gender:"female",displayName:"Anu",locale:"et-EE"},{name:"et-EE-KertNeural",gender:"male",displayName:"Kert",locale:"et-EE"},{name:"fil-PH-AngeloNeural",gender:"male",displayName:"Angelo",locale:"fil-PH"},{name:"fil-PH-BlessicaNeural",gender:"female",displayName:"Blessica",locale:"fil-PH"},{name:"fi-FI-HarriNeural",gender:"male",displayName:"Harri",locale:"fi-FI"},{name:"fi-FI-NooraNeural",gender:"female",displayName:"Noora",locale:"fi-FI"},{name:"fr-BE-CharlineNeural",gender:"female",displayName:"Charline",locale:"fr-BE"},{name:"fr-BE-GerardNeural",gender:"male",displayName:"Gerard",locale:"fr-BE"},{name:"fr-CA-ThierryNeural",gender:"male",displayName:"Thierry",locale:"fr-CA"},{name:"fr-CA-AntoineNeural",gender:"male",displayName:"Antoine",locale:"fr-CA"},{name:"fr-CA-JeanNeural",gender:"male",displayName:"Jean",locale:"fr-CA"},{name:"fr-CA-SylvieNeural",gender:"female",displayName:"Sylvie",locale:"fr-CA"},{name:"fr-FR-VivienneMultilingualNeural",gender:"female",displayName:"Vivienne Multilingue",locale:"fr-FR"},{name:"fr-FR-RemyMultilingualNeural",gender:"male",displayName:"Rémy Multilingue",locale:"fr-FR"},{name:"fr-FR-EloiseNeural",gender:"female",displayName:"Eloise",locale:"fr-FR"},{name:"fr-CH-ArianeNeural",gender:"female",displayName:"Ariane",locale:"fr-CH"},{name:"fr-CH-FabriceNeural",gender:"male",displayName:"Fabrice",locale:"fr-CH"},{name:"gl-ES-RoiNeural",gender:"male",displayName:"Roi",locale:"gl-ES"},{name:"gl-ES-SabelaNeural",gender:"female",displayName:"Sabela",locale:"gl-ES"},{name:"ka-GE-EkaNeural",gender:"female",displayName:"ეკა",locale:"ka-GE"},{name:"ka-GE-GiorgiNeural",gender:"male",displayName:"გიორგი",locale:"ka-GE"},{name:"de-AT-IngridNeural",gender:"female",displayName:"Ingrid",locale:"de-AT"},{name:"de-AT-JonasNeural",gender:"male",displayName:"Jonas",locale:"de-AT"},{name:"de-DE-SeraphinaMultilingualNeural",gender:"female",displayName:"Seraphine Mehrsprachig",locale:"de-DE"},{name:"de-DE-FlorianMultilingualNeural",gender:"male",displayName:"Florian Mehrsprachig",locale:"de-DE"},{name:"de-DE-KillianNeural",gender:"male",displayName:"Killian",locale:"de-DE"},{name:"de-CH-JanNeural",gender:"male",displayName:"Jan",locale:"de-CH"},{name:"de-CH-LeniNeural",gender:"female",displayName:"Leni",locale:"de-CH"},{name:"el-GR-AthinaNeural",gender:"female",displayName:"Αθηνά",locale:"el-GR"},{name:"el-GR-NestorasNeural",gender:"male",displayName:"Νέστορας",locale:"el-GR"},{name:"gu-IN-DhwaniNeural",gender:"female",displayName:"ધ્વની",locale:"gu-IN"},{name:"gu-IN-NiranjanNeural",gender:"male",displayName:"નિરંજન",locale:"gu-IN"},{name:"he-IL-AvriNeural",gender:"male",displayName:"אברי",locale:"he-IL"},{name:"he-IL-HilaNeural",gender:"female",displayName:"הילה",locale:"he-IL"},{name:"hi-IN-MadhurNeural",gender:"male",displayName:"मधुर",locale:"hi-IN"},{name:"hi-IN-SwaraNeural",gender:"female",displayName:"स्वरा",locale:"hi-IN"},{name:"hu-HU-NoemiNeural",gender:"female",displayName:"Noémi",locale:"hu-HU"},{name:"hu-HU-TamasNeural",gender:"male",displayName:"Tamás",locale:"hu-HU"},{name:"is-IS-GudrunNeural",gender:"female",displayName:"Guðrún",locale:"is-IS"},{name:"is-IS-GunnarNeural",gender:"male",displayName:"Gunnar",locale:"is-IS"},{name:"id-ID-ArdiNeural",gender:"male",displayName:"Ardi",locale:"id-ID"},{name:"id-ID-GadisNeural",gender:"female",displayName:"Gadis",locale:"id-ID"},{name:"iu-Latn-CA-SiqiniqNeural",gender:"female",displayName:"ᓯᕿᓂᖅ",locale:"iu-Latn-CA"},{name:"iu-Latn-CA-TaqqiqNeural",gender:"male",displayName:"ᑕᖅᑭᖅ",locale:"iu-Latn-CA"},{name:"iu-Cans-CA-SiqiniqNeural",gender:"female",displayName:"ᓯᕿᓂᖅ",locale:"iu-Cans-CA"},{name:"iu-Cans-CA-TaqqiqNeural",gender:"male",displayName:"ᑕᖅᑭᖅ",locale:"iu-Cans-CA"},{name:"ga-IE-ColmNeural",gender:"male",displayName:"Colm",locale:"ga-IE"},{name:"ga-IE-OrlaNeural",gender:"female",displayName:"Orla",locale:"ga-IE"},{name:"it-IT-GiuseppeMultilingualNeural",gender:"male",displayName:"Giuseppe Multilingual",locale:"it-IT"},{name:"jv-ID-DimasNeural",gender:"male",displayName:"Dimas",locale:"jv-ID"},{name:"jv-ID-SitiNeural",gender:"female",displayName:"Siti",locale:"jv-ID"},{name:"kn-IN-GaganNeural",gender:"male",displayName:"ಗಗನ್",locale:"kn-IN"},{name:"kn-IN-SapnaNeural",gender:"female",displayName:"ಸಪ್ನಾ",locale:"kn-IN"},{name:"kk-KZ-AigulNeural",gender:"female",displayName:"Айгүл",locale:"kk-KZ"},{name:"kk-KZ-DauletNeural",gender:"male",displayName:"Дәулет",locale:"kk-KZ"},{name:"km-KH-PisethNeural",gender:"male",displayName:"ពិសិដ្ឋ",locale:"km-KH"},{name:"km-KH-SreymomNeural",gender:"female",displayName:"ស្រីមុំ",locale:"km-KH"},{name:"ko-KR-HyunsuMultilingualNeural",gender:"male",displayName:"Hyunsu Multilingual",locale:"ko-KR"},{name:"lo-LA-ChanthavongNeural",gender:"male",displayName:"ຈັນທະວົງ",locale:"lo-LA"},{name:"lo-LA-KeomanyNeural",gender:"female",displayName:"ແກ້ວມະນີ",locale:"lo-LA"},{name:"lv-LV-EveritaNeural",gender:"female",displayName:"Everita",locale:"lv-LV"},{name:"lv-LV-NilsNeural",gender:"male",displayName:"Nils",locale:"lv-LV"},{name:"lt-LT-LeonasNeural",gender:"male",displayName:"Leonas",locale:"lt-LT"},{name:"lt-LT-OnaNeural",gender:"female",displayName:"Ona",locale:"lt-LT"},{name:"mk-MK-AleksandarNeural",gender:"male",displayName:"Александар",locale:"mk-MK"},{name:"mk-MK-MarijaNeural",gender:"female",displayName:"Марија",locale:"mk-MK"},{name:"ms-MY-OsmanNeural",gender:"male",displayName:"Osman",locale:"ms-MY"},{name:"ms-MY-YasminNeural",gender:"female",displayName:"Yasmin",locale:"ms-MY"},{name:"ml-IN-MidhunNeural",gender:"male",displayName:"മിഥുൻ",locale:"ml-IN"},{name:"ml-IN-SobhanaNeural",gender:"female",displayName:"ശോഭന",locale:"ml-IN"},{name:"mt-MT-GraceNeural",gender:"female",displayName:"Grace",locale:"mt-MT"},{name:"mt-MT-JosephNeural",gender:"male",displayName:"Joseph",locale:"mt-MT"},{name:"mr-IN-AarohiNeural",gender:"female",displayName:"आरोही",locale:"mr-IN"},{name:"mr-IN-ManoharNeural",gender:"male",displayName:"मनोहर",locale:"mr-IN"},{name:"mn-MN-BataaNeural",gender:"male",displayName:"Батаа",locale:"mn-MN"},{name:"mn-MN-YesuiNeural",gender:"female",displayName:"Есүй",locale:"mn-MN"},{name:"ne-NP-HemkalaNeural",gender:"female",displayName:"हेमकला",locale:"ne-NP"},{name:"ne-NP-SagarNeural",gender:"male",displayName:"सागर",locale:"ne-NP"},{name:"nb-NO-FinnNeural",gender:"male",displayName:"Finn",locale:"nb-NO"},{name:"nb-NO-PernilleNeural",gender:"female",displayName:"Pernille",locale:"nb-NO"},{name:"ps-AF-GulNawazNeural",gender:"male",displayName:" ګل نواز",locale:"ps-AF"},{name:"ps-AF-LatifaNeural",gender:"female",displayName:"لطيفه",locale:"ps-AF"},{name:"fa-IR-DilaraNeural",gender:"female",displayName:"دلارا",locale:"fa-IR"},{name:"fa-IR-FaridNeural",gender:"male",displayName:"فرید",locale:"fa-IR"},{name:"pl-PL-MarekNeural",gender:"male",displayName:"Marek",locale:"pl-PL"},{name:"pl-PL-ZofiaNeural",gender:"female",displayName:"Zofia",locale:"pl-PL"},{name:"pt-BR-ThalitaMultilingualNeural",gender:"female",displayName:"Thalita multilíngue",locale:"pt-BR"},{name:"ro-RO-AlinaNeural",gender:"female",displayName:"Alina",locale:"ro-RO"},{name:"ro-RO-EmilNeural",gender:"male",displayName:"Emil",locale:"ro-RO"},{name:"sr-RS-NicholasNeural",gender:"male",displayName:"Никола",locale:"sr-RS"},{name:"sr-RS-SophieNeural",gender:"female",displayName:"Софија",locale:"sr-RS"},{name:"si-LK-SameeraNeural",gender:"male",displayName:"සමීර",locale:"si-LK"},{name:"si-LK-ThiliniNeural",gender:"female",displayName:"තිළිණි",locale:"si-LK"},{name:"sk-SK-LukasNeural",gender:"male",displayName:"Lukáš",locale:"sk-SK"},{name:"sk-SK-ViktoriaNeural",gender:"female",displayName:"Viktória",locale:"sk-SK"},{name:"sl-SI-PetraNeural",gender:"female",displayName:"Petra",locale:"sl-SI"},{name:"sl-SI-RokNeural",gender:"male",displayName:"Rok",locale:"sl-SI"},{name:"so-SO-MuuseNeural",gender:"male",displayName:"Muuse",locale:"so-SO"},{name:"so-SO-UbaxNeural",gender:"female",displayName:"Ubax",locale:"so-SO"},{name:"es-AR-ElenaNeural",gender:"female",displayName:"Elena",locale:"es-AR"},{name:"es-AR-TomasNeural",gender:"male",displayName:"Tomas",locale:"es-AR"},{name:"es-BO-MarceloNeural",gender:"male",displayName:"Marcelo",locale:"es-BO"},{name:"es-BO-SofiaNeural",gender:"female",displayName:"Sofia",locale:"es-BO"},{name:"es-CL-CatalinaNeural",gender:"female",displayName:"Catalina",locale:"es-CL"},{name:"es-CL-LorenzoNeural",gender:"male",displayName:"Lorenzo",locale:"es-CL"},{name:"es-CO-GonzaloNeural",gender:"male",displayName:"Gonzalo",locale:"es-CO"},{name:"es-CO-SalomeNeural",gender:"female",displayName:"Salome",locale:"es-CO"},{name:"es-ES-XimenaNeural",gender:"female",displayName:"Ximena",locale:"es-ES"},{name:"es-CR-JuanNeural",gender:"male",displayName:"Juan",locale:"es-CR"},{name:"es-CR-MariaNeural",gender:"female",displayName:"María",locale:"es-CR"},{name:"es-CU-BelkysNeural",gender:"female",displayName:"Belkys",locale:"es-CU"},{name:"es-CU-ManuelNeural",gender:"male",displayName:"Manuel",locale:"es-CU"},{name:"es-DO-EmilioNeural",gender:"male",displayName:"Emilio",locale:"es-DO"},{name:"es-DO-RamonaNeural",gender:"female",displayName:"Ramona",locale:"es-DO"},{name:"es-EC-AndreaNeural",gender:"female",displayName:"Andrea",locale:"es-EC"},{name:"es-EC-LuisNeural",gender:"male",displayName:"Luis",locale:"es-EC"},{name:"es-SV-LorenaNeural",gender:"female",displayName:"Lorena",locale:"es-SV"},{name:"es-SV-RodrigoNeural",gender:"male",displayName:"Rodrigo",locale:"es-SV"},{name:"es-GQ-JavierNeural",gender:"male",displayName:"Javier",locale:"es-GQ"},{name:"es-GQ-TeresaNeural",gender:"female",displayName:"Teresa",locale:"es-GQ"},{name:"es-GT-AndresNeural",gender:"male",displayName:"Andrés",locale:"es-GT"},{name:"es-GT-MartaNeural",gender:"female",displayName:"Marta",locale:"es-GT"},{name:"es-HN-CarlosNeural",gender:"male",displayName:"Carlos",locale:"es-HN"},{name:"es-HN-KarlaNeural",gender:"female",displayName:"Karla",locale:"es-HN"},{name:"es-MX-DaliaNeural",gender:"female",displayName:"Dalia",locale:"es-MX"},{name:"es-MX-JorgeNeural",gender:"male",displayName:"Jorge",locale:"es-MX"},{name:"es-NI-FedericoNeural",gender:"male",displayName:"Federico",locale:"es-NI"},{name:"es-NI-YolandaNeural",gender:"female",displayName:"Yolanda",locale:"es-NI"},{name:"es-PA-MargaritaNeural",gender:"female",displayName:"Margarita",locale:"es-PA"},{name:"es-PA-RobertoNeural",gender:"male",displayName:"Roberto",locale:"es-PA"},{name:"es-PY-MarioNeural",gender:"male",displayName:"Mario",locale:"es-PY"},{name:"es-PY-TaniaNeural",gender:"female",displayName:"Tania",locale:"es-PY"},{name:"es-PE-AlexNeural",gender:"male",displayName:"Alex",locale:"es-PE"},{name:"es-PE-CamilaNeural",gender:"female",displayName:"Camila",locale:"es-PE"},{name:"es-PR-KarinaNeural",gender:"female",displayName:"Karina",locale:"es-PR"},{name:"es-PR-VictorNeural",gender:"male",displayName:"Víctor",locale:"es-PR"},{name:"es-US-AlonsoNeural",gender:"male",displayName:"Alonso",locale:"es-US"},{name:"es-US-PalomaNeural",gender:"female",displayName:"Paloma",locale:"es-US"},{name:"es-UY-MateoNeural",gender:"male",displayName:"Mateo",locale:"es-UY"},{name:"es-UY-ValentinaNeural",gender:"female",displayName:"Valentina",locale:"es-UY"},{name:"es-VE-PaolaNeural",gender:"female",displayName:"Paola",locale:"es-VE"},{name:"es-VE-SebastianNeural",gender:"male",displayName:"Sebastián",locale:"es-VE"},{name:"su-ID-JajangNeural",gender:"male",displayName:"Jajang",locale:"su-ID"},{name:"su-ID-TutiNeural",gender:"female",displayName:"Tuti",locale:"su-ID"},{name:"sw-KE-RafikiNeural",gender:"male",displayName:"Rafiki",locale:"sw-KE"},{name:"sw-KE-ZuriNeural",gender:"female",displayName:"Zuri",locale:"sw-KE"},{name:"sw-TZ-DaudiNeural",gender:"male",displayName:"Daudi",locale:"sw-TZ"},{name:"sw-TZ-RehemaNeural",gender:"female",displayName:"Rehema",locale:"sw-TZ"},{name:"sv-SE-MattiasNeural",gender:"male",displayName:"Mattias",locale:"sv-SE"},{name:"sv-SE-SofieNeural",gender:"female",displayName:"Sofie",locale:"sv-SE"},{name:"ta-IN-PallaviNeural",gender:"female",displayName:"பல்லவி",locale:"ta-IN"},{name:"ta-IN-ValluvarNeural",gender:"male",displayName:"வள்ளுவர்",locale:"ta-IN"},{name:"ta-MY-KaniNeural",gender:"female",displayName:"கனி",locale:"ta-MY"},{name:"ta-MY-SuryaNeural",gender:"male",displayName:"சூர்யா",locale:"ta-MY"},{name:"ta-SG-AnbuNeural",gender:"male",displayName:"அன்பு",locale:"ta-SG"},{name:"ta-SG-VenbaNeural",gender:"female",displayName:"வெண்பா",locale:"ta-SG"},{name:"ta-LK-KumarNeural",gender:"male",displayName:"குமார்",locale:"ta-LK"},{name:"ta-LK-SaranyaNeural",gender:"female",displayName:"சரண்யா",locale:"ta-LK"},{name:"te-IN-MohanNeural",gender:"male",displayName:"మోహన్",locale:"te-IN"},{name:"te-IN-ShrutiNeural",gender:"female",displayName:"శ్రుతి",locale:"te-IN"},{name:"th-TH-NiwatNeural",gender:"male",displayName:"นิวัฒน์",locale:"th-TH"},{name:"th-TH-PremwadeeNeural",gender:"female",displayName:"เปรมวดี",locale:"th-TH"},{name:"tr-TR-EmelNeural",gender:"female",displayName:"Emel",locale:"tr-TR"},{name:"tr-TR-AhmetNeural",gender:"male",displayName:"Ahmet",locale:"tr-TR"},{name:"uk-UA-OstapNeural",gender:"male",displayName:"Остап",locale:"uk-UA"},{name:"uk-UA-PolinaNeural",gender:"female",displayName:"Поліна",locale:"uk-UA"},{name:"ur-IN-GulNeural",gender:"female",displayName:"گل",locale:"ur-IN"},{name:"ur-IN-SalmanNeural",gender:"male",displayName:"سلمان",locale:"ur-IN"},{name:"ur-PK-AsadNeural",gender:"male",displayName:"اسد",locale:"ur-PK"},{name:"ur-PK-UzmaNeural",gender:"female",displayName:"عظمیٰ",locale:"ur-PK"},{name:"uz-UZ-MadinaNeural",gender:"female",displayName:"Madina",locale:"uz-UZ"},{name:"uz-UZ-SardorNeural",gender:"male",displayName:"Sardor",locale:"uz-UZ"},{name:"vi-VN-HoaiMyNeural",gender:"female",displayName:"Hoài My",locale:"vi-VN"},{name:"vi-VN-NamMinhNeural",gender:"male",displayName:"Nam Minh",locale:"vi-VN"},{name:"cy-GB-AledNeural",gender:"male",displayName:"Aled",locale:"cy-GB"},{name:"cy-GB-NiaNeural",gender:"female",displayName:"Nia",locale:"cy-GB"},{name:"zu-ZA-ThandoNeural",gender:"female",displayName:"Thando",locale:"zu-ZA"},{name:"zu-ZA-ThembaNeural",gender:"male",displayName:"Themba",locale:"zu-ZA"},{name:"as-IN-YashicaNeural",gender:"female",displayName:"যাশিকা",locale:"as-IN"},{name:"as-IN-PriyomNeural",gender:"male",displayName:"প্ৰিয়ম",locale:"as-IN"},{name:"ca-ES-AlbaNeural",gender:"female",displayName:"Alba",locale:"ca-ES"},{name:"de-DE-ChristophNeural",gender:"male",displayName:"Christoph",locale:"de-DE"},{name:"de-DE-ElkeNeural",gender:"female",displayName:"Elke",locale:"de-DE"},{name:"de-DE-GiselaNeural",gender:"female",displayName:"Gisela",locale:"de-DE"},{name:"de-DE-KasperNeural",gender:"male",displayName:"Kasper",locale:"de-DE"},{name:"de-DE-KlarissaNeural",gender:"female",displayName:"Klarissa",locale:"de-DE"},{name:"de-DE-KlausNeural",gender:"male",displayName:"Klaus",locale:"de-DE"},{name:"de-DE-LouisaNeural",gender:"female",displayName:"Louisa",locale:"de-DE"},{name:"de-DE-MajaNeural",gender:"female",displayName:"Maja",locale:"de-DE"},{name:"de-DE-RalfNeural",gender:"male",displayName:"Ralf",locale:"de-DE"},{name:"de-DE-TanjaNeural",gender:"female",displayName:"Tanja",locale:"de-DE"},{name:"en-AU-WilliamNeural",gender:"male",displayName:"William",locale:"en-AU"},{name:"en-AU-AnnetteNeural",gender:"female",displayName:"Annette",locale:"en-AU"},{name:"en-AU-CarlyNeural",gender:"female",displayName:"Carly",locale:"en-AU"},{name:"en-AU-DarrenNeural",gender:"male",displayName:"Darren",locale:"en-AU"},{name:"en-AU-DuncanNeural",gender:"male",displayName:"Duncan",locale:"en-AU"},{name:"en-AU-ElsieNeural",gender:"female",displayName:"Elsie",locale:"en-AU"},{name:"en-AU-FreyaNeural",gender:"female",displayName:"Freya",locale:"en-AU"},{name:"en-AU-JoanneNeural",gender:"female",displayName:"Joanne",locale:"en-AU"},{name:"en-AU-KenNeural",gender:"male",displayName:"Ken",locale:"en-AU"},{name:"en-AU-KimNeural",gender:"female",displayName:"Kim",locale:"en-AU"},{name:"en-AU-NeilNeural",gender:"male",displayName:"Neil",locale:"en-AU"},{name:"en-AU-TimNeural",gender:"male",displayName:"Tim",locale:"en-AU"},{name:"en-AU-TinaNeural",gender:"female",displayName:"Tina",locale:"en-AU"},{name:"en-GB-AdaMultilingualNeural",gender:"female",displayName:"Ada Multilingual",locale:"en-GB"},{name:"en-GB-OllieMultilingualNeural",gender:"male",displayName:"Ollie Multilingual",locale:"en-GB"},{name:"en-GB-AbbiNeural",gender:"female",displayName:"Abbi",locale:"en-GB"},{name:"en-GB-AlfieNeural",gender:"male",displayName:"Alfie",locale:"en-GB"},{name:"en-GB-BellaNeural",gender:"female",displayName:"Bella",locale:"en-GB"},{name:"en-GB-ElliotNeural",gender:"male",displayName:"Elliot",locale:"en-GB"},{name:"en-GB-EthanNeural",gender:"male",displayName:"Ethan",locale:"en-GB"},{name:"en-GB-HollieNeural",gender:"female",displayName:"Hollie",locale:"en-GB"},{name:"en-GB-NoahNeural",gender:"male",displayName:"Noah",locale:"en-GB"},{name:"en-GB-OliverNeural",gender:"male",displayName:"Oliver",locale:"en-GB"},{name:"en-GB-OliviaNeural",gender:"female",displayName:"Olivia",locale:"en-GB"},{name:"en-GB-MiaNeural",gender:"female",displayName:"Mia",locale:"en-GB"},{name:"en-IN-AartiIndicNeural",gender:"female",displayName:"Aarti Indic",locale:"en-IN"},{name:"en-IN-ArjunIndicNeural",gender:"male",displayName:"Arjun Indic",locale:"en-IN"},{name:"en-IN-NeerjaIndicNeural",gender:"female",displayName:"Neerja Indic",locale:"en-IN"},{name:"en-IN-PrabhatIndicNeural",gender:"male",displayName:"Prabhat Indic",locale:"en-IN"},{name:"en-IN-AaravNeural",gender:"male",displayName:"Aarav",locale:"en-IN"},{name:"en-IN-AashiNeural",gender:"female",displayName:"Aashi",locale:"en-IN"},{name:"en-IN-AartiNeural",gender:"female",displayName:"Aarti",locale:"en-IN"},{name:"en-IN-ArjunNeural",gender:"male",displayName:"Arjun",locale:"en-IN"},{name:"en-IN-AnanyaNeural",gender:"female",displayName:"Ananya",locale:"en-IN"},{name:"en-IN-KavyaNeural",gender:"female",displayName:"Kavya",locale:"en-IN"},{name:"en-IN-KunalNeural",gender:"male",displayName:"Kunal",locale:"en-IN"},{name:"en-IN-RehaanNeural",gender:"male",displayName:"Rehaan",locale:"en-IN"},{name:"en-US-AmandaMultilingualNeural",gender:"female",displayName:"Amanda Multilingual",locale:"en-US"},{name:"en-US-AdamMultilingualNeural",gender:"male",displayName:"Adam Multilingual",locale:"en-US"},{name:"en-US-PhoebeMultilingualNeural",gender:"female",displayName:"Phoebe Multilingual",locale:"en-US"},{name:"en-US-AlloyTurboMultilingualNeural",gender:"male",displayName:"Alloy Turbo Multilingual",locale:"en-US"},{name:"en-US-EchoTurboMultilingualNeural",gender:"male",displayName:"Echo Turbo Multilingual",locale:"en-US"},{name:"en-US-FableTurboMultilingualNeural",gender:"female",displayName:"Fable Turbo Multilingual",locale:"en-US"},{name:"en-US-OnyxTurboMultilingualNeural",gender:"male",displayName:"Onyx Turbo Multilingual",locale:"en-US"},{name:"en-US-NovaTurboMultilingualNeural",gender:"female",displayName:"Nova Turbo Multilingual",locale:"en-US"},{name:"en-US-ShimmerTurboMultilingualNeural",gender:"female",displayName:"Shimmer Turbo Multilingual",locale:"en-US"},{name:"en-US-JasonNeural",gender:"male",displayName:"Jason",locale:"en-US"},{name:"en-US-KaiNeural",gender:"male",displayName:"Kai",locale:"en-US"},{name:"en-US-LunaNeural",gender:"female",displayName:"Luna",locale:"en-US"},{name:"en-US-TonyNeural",gender:"male",displayName:"Tony",locale:"en-US"},{name:"en-US-NancyNeural",gender:"female",displayName:"Nancy",locale:"en-US"},{name:"en-US-CoraMultilingualNeural",gender:"female",displayName:"Cora Multilingual",locale:"en-US"},{name:"en-US-ChristopherMultilingualNeural",gender:"male",displayName:"Christopher Multilingual",locale:"en-US"},{name:"en-US-BrandonMultilingualNeural",gender:"male",displayName:"Brandon Multilingual",locale:"en-US"},{name:"en-US-AshleyNeural",gender:"female",displayName:"Ashley",locale:"en-US"},{name:"en-US-BrandonNeural",gender:"male",displayName:"Brandon",locale:"en-US"},{name:"en-US-CoraNeural",gender:"female",displayName:"Cora",locale:"en-US"},{name:"en-US-DavisMultilingualNeural",gender:"male",displayName:"Davis Multilingual",locale:"en-US"},{name:"en-US-DerekMultilingualNeural",gender:"male",displayName:"Derek Multilingual",locale:"en-US"},{name:"en-US-DustinMultilingualNeural",gender:"male",displayName:"Dustin Multilingual",locale:"en-US"},{name:"en-US-ElizabethNeural",gender:"female",displayName:"Elizabeth",locale:"en-US"},{name:"en-US-JacobNeural",gender:"male",displayName:"Jacob",locale:"en-US"},{name:"en-US-JennyMultilingualNeural",gender:"female",displayName:"Jenny Multilingual",locale:"en-US"},{name:"en-US-LewisMultilingualNeural",gender:"male",displayName:"Lewis Multilingual",locale:"en-US"},{name:"en-US-LolaMultilingualNeural",gender:"female",displayName:"Lola Multilingual",locale:"en-US"},{name:"en-US-MonicaNeural",gender:"female",displayName:"Monica",locale:"en-US"},{name:"en-US-NancyMultilingualNeural",gender:"female",displayName:"Nancy Multilingual",locale:"en-US"},{name:"en-US-RyanMultilingualNeural",gender:"male",displayName:"Ryan Multilingual",locale:"en-US"},{name:"en-US-SamuelMultilingualNeural",gender:"male",displayName:"Samuel Multilingual",locale:"en-US"},{name:"en-US-SerenaMultilingualNeural",gender:"female",displayName:"Serena Multilingual",locale:"en-US"},{name:"en-US-SteffanMultilingualNeural",gender:"male",displayName:"Steffan Multilingual",locale:"en-US"},{name:"en-US-AIGenerate1Neural",gender:"male",displayName:"AIGenerate1",locale:"en-US"},{name:"en-US-AIGenerate2Neural",gender:"female",displayName:"AIGenerate2",locale:"en-US"},{name:"en-US-AshTurboMultilingualNeural",gender:"male",displayName:"Ash Turbo Multilingual",locale:"en-US"},{name:"en-US-BlueNeural",gender:"female",displayName:"Blue",locale:"en-US"},{name:"en-US-EvelynMultilingualNeural",gender:"female",displayName:"Evelyn Multilingual",locale:"en-US"},{name:"es-ES-ArabellaMultilingualNeural",gender:"female",displayName:"Arabella Multilingual",locale:"es-ES"},{name:"es-ES-IsidoraMultilingualNeural",gender:"female",displayName:"Isidora Multilingual",locale:"es-ES"},{name:"es-ES-TristanMultilingualNeural",gender:"male",displayName:"Tristan Multilingual",locale:"es-ES"},{name:"es-ES-XimenaMultilingualNeural",gender:"female",displayName:"Ximena Multilingual",locale:"es-ES"},{name:"es-ES-DarioNeural",gender:"male",displayName:"Dario",locale:"es-ES"},{name:"es-ES-EliasNeural",gender:"male",displayName:"Elias",locale:"es-ES"},{name:"es-ES-EstrellaNeural",gender:"female",displayName:"Estrella",locale:"es-ES"},{name:"es-ES-IreneNeural",gender:"female",displayName:"Irene",locale:"es-ES"},{name:"es-ES-LaiaNeural",gender:"female",displayName:"Laia",locale:"es-ES"},{name:"es-ES-LiaNeural",gender:"female",displayName:"Lia",locale:"es-ES"},{name:"es-ES-NilNeural",gender:"male",displayName:"Nil",locale:"es-ES"},{name:"es-ES-SaulNeural",gender:"male",displayName:"Saul",locale:"es-ES"},{name:"es-ES-TeoNeural",gender:"male",displayName:"Teo",locale:"es-ES"},{name:"es-ES-TrianaNeural",gender:"female",displayName:"Triana",locale:"es-ES"},{name:"es-ES-VeraNeural",gender:"female",displayName:"Vera",locale:"es-ES"},{name:"es-MX-DaliaMultilingualNeural",gender:"female",displayName:"Dalia Multilingual",locale:"es-MX"},{name:"es-MX-JorgeMultilingualNeural",gender:"male",displayName:"Jorge Multilingual",locale:"es-MX"},{name:"es-MX-BeatrizNeural",gender:"female",displayName:"Beatriz",locale:"es-MX"},{name:"es-MX-CandelaNeural",gender:"female",displayName:"Candela",locale:"es-MX"},{name:"es-MX-CarlotaNeural",gender:"female",displayName:"Carlota",locale:"es-MX"},{name:"es-MX-CecilioNeural",gender:"male",displayName:"Cecilio",locale:"es-MX"},{name:"es-MX-GerardoNeural",gender:"male",displayName:"Gerardo",locale:"es-MX"},{name:"es-MX-LarissaNeural",gender:"female",displayName:"Larissa",locale:"es-MX"},{name:"es-MX-LibertoNeural",gender:"male",displayName:"Liberto",locale:"es-MX"},{name:"es-MX-LucianoNeural",gender:"male",displayName:"Luciano",locale:"es-MX"},{name:"es-MX-MarinaNeural",gender:"female",displayName:"Marina",locale:"es-MX"},{name:"es-MX-NuriaNeural",gender:"female",displayName:"Nuria",locale:"es-MX"},{name:"es-MX-PelayoNeural",gender:"male",displayName:"Pelayo",locale:"es-MX"},{name:"es-MX-RenataNeural",gender:"female",displayName:"Renata",locale:"es-MX"},{name:"es-MX-YagoNeural",gender:"male",displayName:"Yago",locale:"es-MX"},{name:"eu-ES-AinhoaNeural",gender:"female",displayName:"Ainhoa",locale:"eu-ES"},{name:"eu-ES-AnderNeural",gender:"male",displayName:"Ander",locale:"eu-ES"},{name:"fi-FI-SelmaNeural",gender:"female",displayName:"Selma",locale:"fi-FI"},{name:"fr-FR-LucienMultilingualNeural",gender:"male",displayName:"Lucien Multilingual",locale:"fr-FR"},{name:"fr-FR-AlainNeural",gender:"male",displayName:"Alain",locale:"fr-FR"},{name:"fr-FR-BrigitteNeural",gender:"female",displayName:"Brigitte",locale:"fr-FR"},{name:"fr-FR-CelesteNeural",gender:"female",displayName:"Celeste",locale:"fr-FR"},{name:"fr-FR-ClaudeNeural",gender:"male",displayName:"Claude",locale:"fr-FR"},{name:"fr-FR-CoralieNeural",gender:"female",displayName:"Coralie",locale:"fr-FR"},{name:"fr-FR-JacquelineNeural",gender:"female",displayName:"Jacqueline",locale:"fr-FR"},{name:"fr-FR-JeromeNeural",gender:"male",displayName:"Jerome",locale:"fr-FR"},{name:"fr-FR-JosephineNeural",gender:"female",displayName:"Josephine",locale:"fr-FR"},{name:"fr-FR-MauriceNeural",gender:"male",displayName:"Maurice",locale:"fr-FR"},{name:"fr-FR-YvesNeural",gender:"male",displayName:"Yves",locale:"fr-FR"},{name:"fr-FR-YvetteNeural",gender:"female",displayName:"Yvette",locale:"fr-FR"},{name:"hi-IN-AaravNeural",gender:"male",displayName:"आरव ",locale:"hi-IN"},{name:"hi-IN-AnanyaNeural",gender:"female",displayName:"अनन्या",locale:"hi-IN"},{name:"hi-IN-AartiNeural",gender:"female",displayName:"आरती",locale:"hi-IN"},{name:"hi-IN-ArjunNeural",gender:"male",displayName:"अर्जुन",locale:"hi-IN"},{name:"hi-IN-KavyaNeural",gender:"female",displayName:"काव्या",locale:"hi-IN"},{name:"hi-IN-KunalNeural",gender:"male",displayName:"कुनाल ",locale:"hi-IN"},{name:"hi-IN-RehaanNeural",gender:"male",displayName:"रेहान",locale:"hi-IN"},{name:"hy-AM-AnahitNeural",gender:"female",displayName:"Անահիտ",locale:"hy-AM"},{name:"hy-AM-HaykNeural",gender:"male",displayName:"Հայկ",locale:"hy-AM"},{name:"it-IT-AlessioMultilingualNeural",gender:"male",displayName:"Alessio Multilingual",locale:"it-IT"},{name:"it-IT-IsabellaMultilingualNeural",gender:"female",displayName:"Isabella Multilingual",locale:"it-IT"},{name:"it-IT-MarcelloMultilingualNeural",gender:"male",displayName:"Marcello Multilingual",locale:"it-IT"},{name:"it-IT-CalimeroNeural",gender:"male",displayName:"Calimero",locale:"it-IT"},{name:"it-IT-CataldoNeural",gender:"male",displayName:"Cataldo",locale:"it-IT"},{name:"it-IT-FabiolaNeural",gender:"female",displayName:"Fabiola",locale:"it-IT"},{name:"it-IT-FiammaNeural",gender:"female",displayName:"Fiamma",locale:"it-IT"},{name:"it-IT-GianniNeural",gender:"male",displayName:"Gianni",locale:"it-IT"},{name:"it-IT-GiuseppeNeural",gender:"male",displayName:"Giuseppe",locale:"it-IT"},{name:"it-IT-ImeldaNeural",gender:"female",displayName:"Imelda",locale:"it-IT"},{name:"it-IT-IrmaNeural",gender:"female",displayName:"Irma",locale:"it-IT"},{name:"it-IT-LisandroNeural",gender:"male",displayName:"Lisandro",locale:"it-IT"},{name:"it-IT-PalmiraNeural",gender:"female",displayName:"Palmira",locale:"it-IT"},{name:"it-IT-PierinaNeural",gender:"female",displayName:"Pierina",locale:"it-IT"},{name:"it-IT-RinaldoNeural",gender:"male",displayName:"Rinaldo",locale:"it-IT"},{name:"ja-JP-AoiNeural",gender:"female",displayName:"碧衣",locale:"ja-JP"},{name:"ja-JP-DaichiNeural",gender:"male",displayName:"大智",locale:"ja-JP"},{name:"ja-JP-MayuNeural",gender:"female",displayName:"真夕",locale:"ja-JP"},{name:"ja-JP-NaokiNeural",gender:"male",displayName:"直紀",locale:"ja-JP"},{name:"ja-JP-ShioriNeural",gender:"female",displayName:"志織",locale:"ja-JP"},{name:"ja-JP-MasaruMultilingualNeural",gender:"male",displayName:"勝 多言語",locale:"ja-JP"},{name:"ko-KR-BongJinNeural",gender:"male",displayName:"봉진",locale:"ko-KR"},{name:"ko-KR-GookMinNeural",gender:"male",displayName:"국민",locale:"ko-KR"},{name:"ko-KR-HyunsuNeural",gender:"male",displayName:"현수",locale:"ko-KR"},{name:"ko-KR-JiMinNeural",gender:"female",displayName:"지민",locale:"ko-KR"},{name:"ko-KR-SeoHyeonNeural",gender:"female",displayName:"서현",locale:"ko-KR"},{name:"ko-KR-YuJinNeural",gender:"female",displayName:"유진",locale:"ko-KR"},{name:"nb-NO-IselinNeural",gender:"female",displayName:"Iselin",locale:"nb-NO"},{name:"or-IN-SubhasiniNeural",gender:"female",displayName:"ସୁଭାସିନୀ",locale:"or-IN"},{name:"or-IN-SukantNeural",gender:"male",displayName:"ସୁକାନ୍ତ",locale:"or-IN"},{name:"pa-IN-OjasNeural",gender:"male",displayName:"ਓਜਸ",locale:"pa-IN"},{name:"pa-IN-VaaniNeural",gender:"female",displayName:"ਵਾਨੀ",locale:"pa-IN"},{name:"pl-PL-AgnieszkaNeural",gender:"female",displayName:"Agnieszka",locale:"pl-PL"},{name:"pt-BR-MacerioMultilingualNeural",gender:"male",displayName:"Macerio Multilingual",locale:"pt-BR"},{name:"pt-BR-BrendaNeural",gender:"female",displayName:"Brenda",locale:"pt-BR"},{name:"pt-BR-DonatoNeural",gender:"male",displayName:"Donato",locale:"pt-BR"},{name:"pt-BR-ElzaNeural",gender:"female",displayName:"Elza",locale:"pt-BR"},{name:"pt-BR-FabioNeural",gender:"male",displayName:"Fabio",locale:"pt-BR"},{name:"pt-BR-GiovannaNeural",gender:"female",displayName:"Giovanna",locale:"pt-BR"},{name:"pt-BR-HumbertoNeural",gender:"male",displayName:"Humberto",locale:"pt-BR"},{name:"pt-BR-JulioNeural",gender:"male",displayName:"Julio",locale:"pt-BR"},{name:"pt-BR-LeilaNeural",gender:"female",displayName:"Leila",locale:"pt-BR"},{name:"pt-BR-LeticiaNeural",gender:"female",displayName:"Leticia",locale:"pt-BR"},{name:"pt-BR-ManuelaNeural",gender:"female",displayName:"Manuela",locale:"pt-BR"},{name:"pt-BR-NicolauNeural",gender:"male",displayName:"Nicolau",locale:"pt-BR"},{name:"pt-BR-ThalitaNeural",gender:"female",displayName:"Thalita",locale:"pt-BR"},{name:"pt-BR-ValerioNeural",gender:"male",displayName:"Valerio",locale:"pt-BR"},{name:"pt-BR-YaraNeural",gender:"female",displayName:"Yara",locale:"pt-BR"},{name:"pt-PT-FernandaNeural",gender:"female",displayName:"Fernanda",locale:"pt-PT"},{name:"sr-Latn-RS-NicholasNeural",gender:"male",displayName:"Nicholas",locale:"sr-Latn-RS"},{name:"sr-Latn-RS-SophieNeural",gender:"female",displayName:"Sophie",locale:"sr-Latn-RS"},{name:"sv-SE-HilleviNeural",gender:"female",displayName:"Hillevi",locale:"sv-SE"},{name:"th-TH-AcharaNeural",gender:"female",displayName:"อัจฉรา",locale:"th-TH"},{name:"wuu-CN-XiaotongNeural",gender:"female",displayName:"晓彤",locale:"wuu-CN"},{name:"wuu-CN-YunzheNeural",gender:"male",displayName:"云哲",locale:"wuu-CN"},{name:"zh-CN-XiaochenNeural",gender:"female",displayName:"晓辰",locale:"zh-CN"},{name:"zh-CN-XiaochenMultilingualNeural",gender:"female",displayName:"晓辰 多语言",locale:"zh-CN"},{name:"zh-CN-XiaohanNeural",gender:"female",displayName:"晓涵",locale:"zh-CN"},{name:"zh-CN-XiaomengNeural",gender:"female",displayName:"晓梦",locale:"zh-CN"},{name:"zh-CN-XiaomoNeural",gender:"female",displayName:"晓墨",locale:"zh-CN"},{name:"zh-CN-XiaoqiuNeural",gender:"female",displayName:"晓秋",locale:"zh-CN"},{name:"zh-CN-XiaorouNeural",gender:"female",displayName:"晓柔",locale:"zh-CN"},{name:"zh-CN-XiaoruiNeural",gender:"female",displayName:"晓睿",locale:"zh-CN"},{name:"zh-CN-XiaoshuangNeural",gender:"female",displayName:"晓双",locale:"zh-CN"},{name:"zh-CN-XiaoxiaoDialectsNeural",gender:"female",displayName:"晓晓 ",locale:"zh-CN"},{name:"zh-CN-XiaoxiaoMultilingualNeural",gender:"female",displayName:"晓晓 多语言",locale:"zh-CN"},{name:"zh-CN-XiaoyanNeural",gender:"female",displayName:"晓颜",locale:"zh-CN"},{name:"zh-CN-XiaoyouNeural",gender:"female",displayName:"晓悠",locale:"zh-CN"},{name:"zh-CN-XiaoyuMultilingualNeural",gender:"female",displayName:"晓宇 多语言",locale:"zh-CN"},{name:"zh-CN-XiaozhenNeural",gender:"female",displayName:"晓甄",locale:"zh-CN"},{name:"zh-CN-YunfengNeural",gender:"male",displayName:"云枫",locale:"zh-CN"},{name:"zh-CN-YunhaoNeural",gender:"male",displayName:"云皓",locale:"zh-CN"},{name:"zh-CN-YunjieNeural",gender:"male",displayName:"云杰",locale:"zh-CN"},{name:"zh-CN-YunxiaoMultilingualNeural",gender:"male",displayName:"云霄 多语言",locale:"zh-CN"},{name:"zh-CN-YunyeNeural",gender:"male",displayName:"云野",locale:"zh-CN"},{name:"zh-CN-YunyiMultilingualNeural",gender:"male",displayName:"云逸 多语言",locale:"zh-CN"},{name:"zh-CN-YunzeNeural",gender:"male",displayName:"云泽",locale:"zh-CN"},{name:"zh-CN-YunfanMultilingualNeural",gender:"male",displayName:"云帆 多语言",locale:"zh-CN"},{name:"zh-CN-guangxi-YunqiNeural",gender:"male",displayName:"云奇 广西",locale:"zh-CN"},{name:"zh-CN-henan-YundengNeural",gender:"male",displayName:"云登 河南",locale:"zh-CN"},{name:"zh-CN-liaoning-YunbiaoNeural",gender:"male",displayName:"云彪 辽宁",locale:"zh-CN"},{name:"zh-CN-shandong-YunxiangNeural",gender:"male",displayName:"云翔 山东",locale:"zh-CN"},{name:"zh-CN-sichuan-YunxiNeural",gender:"male",displayName:"云希 四川",locale:"zh-CN"}],SelfHostedVoiceList:["de-DE-AmalaNeural","de-DE-BerndNeural","de-DE-ConradNeural","de-DE-KatjaNeural","en-GB-LibbyNeural","en-GB-RyanNeural","en-GB-SoniaNeural","en-US-AmberNeural","en-US-AriaNeural","en-US-ChristopherNeural","en-US-DavisNeural","en-US-EricNeural","en-US-GuyNeural","en-US-JaneNeural","en-US-JennyNeural","en-US-MichelleNeural","en-US-SaraNeural","es-ES-AbrilNeural","es-ES-AlvaroNeural","es-ES-ArnauNeural","es-ES-ElviraNeural","fr-FR-DeniseNeural","fr-FR-HenriNeural","it-IT-BenignoNeural","it-IT-DiegoNeural","it-IT-ElsaNeural","it-IT-IsabellaNeural","ja-JP-KeitaNeural","ja-JP-NanamiNeural","ko-KR-InJoonNeural","ko-KR-SoonBokNeural","ko-KR-SunHiNeural","pt-BR-AntonioNeural","pt-BR-FranciscaNeural","pt-PT-DuarteNeural","pt-PT-RaquelNeural","ru-RU-DariyaNeural","ru-RU-DmitryNeural","ru-RU-SvetlanaNeural","yue-CN-XiaoMinNeural","yue-CN-YunSongNeural","zh-CN-henan-YundengNeural","zh-CN-liaoning-XiaobeiNeural","zh-CN-shaanxi-XiaoniNeural","zh-CN-shandong-YunxiangNeural","zh-CN-sichuan-YunxiNeural","zh-CN-XiaoxiaoNeural","zh-CN-YunxiNeural","zh-HK-HiuMaanNeural","zh-HK-WanLungNeural","zh-TW-HsiaoChenNeural","zh-TW-YunJheNeural","zf_xiaoxiao","zm_yunxi","zf_xiaoni","zf_xiaobei"],CloudDictList:[{id:"basic-english-irish",name:"Basic English-Irish Dictionary",translation:"简明英爱词典",source:"Pat Griffin"},{id:"english-italian",name:"English-Italian Dictionary",translation:"简明英意词典",source:"Pat Griffin"},{id:"cc-cedict",name:"CC-CEDICT",translation:"简明中英词典",source:"www.mdbg.net"},{id:"et-tedict",name:"ET-TEDICT",translation:"简明中英英中词典",source:"cdict-1.0-1.i386.rpm"},{id:"jmdict",name:"Japanese English Dictionary",translation:"简明日英词典",source:"JMDict"},{id:"moby",name:"Moby Thesaurus",translation:"Moby Thesaurus",source:"Chua Welic"},{id:"wordnet",name:"Wordnet",translation:"Wordnet",source:"Chua Welic"},{id:"opted",name:"Online Plain Text English Dictionary",translation:"简明英英词典",source:"Chua Welic"},{id:"english-arabic",name:"English-Arabic Dictionary",translation:"简明英阿词典",source:"Khaldoun Mahmoud"},{id:"tcm_textbook",name:"中医教材仓库",translation:"中医教材仓库",source:"Fredrik Jornebo"},{id:"ecdict",name:"ECDICT",translation:"简明英汉字典增强版",source:"GitHub-skywind3000"}]};class x{constructor(e){this.config=e,this.driveId="",this.taskQueue=new k(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getDriveId(){return m(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const a=this.config.access_token,t=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${a}`}});return this.driveId=t.data.default_drive_id,this.driveId}))}getFolderIdByPath(a){return m(this,void 0,void 0,(function*(){const t=this.config.access_token,o=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:a},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const n=a.split("/").filter((e=>e));let r="",l="root";for(const a of n){r+="/"+a;try{l=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:r},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.file_id}catch(i){l=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,parent_file_id:l,name:a,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.file_id}}return l}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+a);let n=[],r="",l=!0;for(;l;){const a=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:i,marker:r||void 0},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}),s=a.data.items.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];n=n.concat(s),r=a.data.next_marker,l=!!r}return[...new Set(n.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+a);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(a){var t;return m(this,void 0,void 0,(function*(){try{const o=this.config.access_token,i=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:a},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(t=n.data)||void 0===t?void 0:t.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:i,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:C.adriveClientId,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class I extends x{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token,i=yield this.getDriveId(),n=t.substring(0,t.lastIndexOf("/")),r=t.substring(t.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(t);const l=yield this.getFolderIdByPath(this.baseFolder+"/"+n),s=yield a.arrayBuffer(),d=s.byteLength,c=yield crypto.subtle.digest("SHA-1",s),u=Array.from(new Uint8Array(c)).map((e=>e.toString(16).padStart(2,"0"))).join(""),m=(e=>{function a(e,a){const t=(65535&e)+(65535&a);return(e>>16)+(a>>16)+(t>>16)<<16|65535&t}function t(e,t,o,i,n,r){return a((l=a(a(t,e),a(i,r)))<<(s=n)|l>>>32-s,o);var l,s}function o(e,a,o,i,n,r,l){return t(a&o|~a&i,e,a,n,r,l)}function i(e,a,o,i,n,r,l){return t(a&i|o&~i,e,a,n,r,l)}function n(e,a,o,i,n,r,l){return t(a^o^i,e,a,n,r,l)}function r(e,a,o,i,n,r,l){return t(o^(a|~i),e,a,n,r,l)}const l=function(e){const a=e.length,t=1+(a+8>>6),o=new Array(16*t).fill(0);for(let t=0;t>2]|=e.charCodeAt(t)<>2]|=128<{let a="";for(let t=0;t<4;t++)a+=("0"+(e>>8*t&255).toString(16)).slice(-2);return a})).join("")})(o),p=Number(BigInt("0x"+m.slice(0,16))%BigInt(d||1)),h=new Uint8Array(s.slice(p,Math.min(p+8,d))),g=btoa(String.fromCharCode(...h)),f=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:i,parent_file_id:l,name:r,type:"file",check_name_mode:"ignore",size:d,content_hash:u,content_hash_name:"sha1",proof_code:g,proof_version:"v1",part_info_list:[{part_number:1}]},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),{file_id:y,upload_id:N,rapid_upload:v,part_info_list:b}=f.data;return v?(console.info("阿里云盘秒传成功"),!0):(yield fetch(b[0].upload_url,{method:"PUT",body:s,headers:{"Content-Length":d.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:i,file_id:y,upload_id:N},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token,o=yield this.getDriveId(),i=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:this.baseFolder+"/"+a},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.file_id,n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});return(yield e.get(n.data.url,{responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}})).data}catch(e){return console.error("Error downloading file:",e),!1}}))))))}}class F{constructor(e){this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFolderIdByPath(a){return m(this,void 0,void 0,(function*(){if(""==a)return"0";const t=this.config.access_token,o=a.split("/");let i="0";for(const a of o){const o=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(o,{headers:{Authorization:`Bearer ${t}`}})).data.entries.find((e=>e.name===a&&"folder"===e.type));if(n)i=n.id;else{const o={name:a,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return i}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;for(;o.startsWith("/");)o=o.substring(1);let i=yield this.getFolderIdByPath(o),n=[],r=0,l=!0;const s=1e3;for(;l;){const a=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:s,offset:r},headers:{Authorization:`Bearer ${t}`}}),o=a.data.entries||[];n=n.concat(o),r+=o.length,l=o.length===s&&a.data.total_count>r}return[...new Set(n.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=a.substring(0,a.lastIndexOf("/")),i=a.substring(a.lastIndexOf("/")+1);let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const r=yield this.getFolderIdByPath(n);if(!r)return!0;const l=`https://api.box.com/2.0/folders/${r}/items?fields=id,name&type=file&limit=1000`,s=(yield e.get(l,{headers:{Authorization:`Bearer ${t}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!s||(yield e.delete(`https://api.box.com/2.0/files/${s.id}`,{headers:{Authorization:`Bearer ${t}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:C.boxClientId,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class R extends F{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token,i=t.substring(0,t.lastIndexOf("/")),n=t.substring(t.lastIndexOf("/")+1);let r=this.baseFolder+"/"+i;for(;r.startsWith("/");)r=r.substring(1);const l=yield this.getFolderIdByPath(r);if(!l)throw new Error("Folder not found");const s=(yield this.listFiles(i)).find((e=>e===n));s&&(yield this.deleteFileWithoutQueue(i+"/"+n));let d=new File([a],n,{lastModified:(new Date).getTime(),type:a.type});const c=new FormData;c.append("file",d),c.append("parent_id",l);const u=yield e.post("https://upload.box.com/api/2.0/files/content",c,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token,o=a.substring(0,a.lastIndexOf("/")),i=a.substring(a.lastIndexOf("/")+1);let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const r=yield this.getFolderIdByPath(n);if(!r)return console.error("Folder not found"),!0;const l=`https://api.box.com/2.0/folders/${r}/items?fields=id,name&type=file&limit=1000`,s=(yield e.get(l,{headers:{Authorization:`Bearer ${t}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!s)return console.error("File not found:",i),!0;const d=yield e({url:`https://api.box.com/2.0/files/${s.id}/content`,method:"get",headers:{Authorization:`Bearer ${t}`},responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return d.status>=300?(console.error("Error occurred during file download:",d),!1):d.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class O{constructor(e){this.config=e,this.taskQueue=new k(3)}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=[],i=!0,n=null;for(;i;){let r;r=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+a,limit:2e3},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});const l=r.data.entries||[];o=o.concat(l),i=r.data.has_more,n=r.data.cursor}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+a},{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${C.dropboxClientId}&redirect_uri=${e}`}}class _ extends O{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=t.split("/").pop()||"",n=new File([a],i,{lastModified:(new Date).getTime(),type:a.type});const r=yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+t,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0});return!(r.status>=300)||(console.error("Error occurred during file upload:",r),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token,o=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"post",headers:{Authorization:`Bearer ${t}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+a})},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ${constructor(e){this.folderExistsCache=new Set,this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){var t,o;return m(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);let n=[],r=0;const l=1e3;let s=!0;for(;s;){const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:a?`/${a}`:"/",limit:l,offset:r,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),c=(null===(t=d.data._embedded)||void 0===t?void 0:t.items)||[];n=n.concat(c);const u=(null===(o=d.data._embedded)||void 0===o?void 0:o.total)||0;r+=c.length,s=r({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);const o=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${t}`,"Content-Type":"application/json"},params:{path:a?`/${a}`:"/",permanently:!1}});return 202===o.status||204===o.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(a){var t,o;return m(this,void 0,void 0,(function*(){try{const i=this.config.access_token,n=a.split("/").filter((e=>e.length>0));let r="";for(const a of n)if(r+="/"+a,!this.folderExistsCache.has(r))try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:r}}),this.folderExistsCache.add(r)}catch(a){if(404!==(null===(t=a.response)||void 0===t?void 0:t.status))return console.error("Error checking directory:",a),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(r)}`,null,{headers:{Authorization:`OAuth ${i}`}}),this.folderExistsCache.add(r)}catch(e){if(409!==(null===(o=e.response)||void 0===o?void 0:o.status))return console.error("Error creating directory:",e),!1;this.folderExistsCache.add(r)}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${C.yandexClientId}&redirect_uri=${e}&force_confirm=true`}}class M extends ${constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=this.baseFolder+"/"+t;for(;i.startsWith("/");)i=i.substring(1);const n=i.substring(0,i.lastIndexOf("/"));if(n){if(!(yield this.ensureDirectoryExists(n)))return console.error("Failed to create directory:",n),!1}const r=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:`/${i}`,overwrite:!0}});if(200!==r.status)return console.error("Error getting upload URL:",r),!1;const l=r.data.href;let s=t.split("/").pop()||"",d=new File([a],s,{lastModified:(new Date).getTime(),type:a.type});const c=yield e.put(l,d,{headers:{"Content-Type":a.type||"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;for(;o.startsWith("/");)o=o.substring(1);const i=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${t}`,"Content-Type":"application/json"},params:{path:`/${o}`}});if(200!==i.status)return console.error("Error getting download URL:",i),!1;const n=i.data.href,r=yield e({url:n,method:"get",maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return r.status>=300?(console.error("Error occurred during file download:",r),!1):r.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class U{constructor(e){this.isExp=!1,this.folderIdCache=new Map,this.config=e,this.taskQueue=new k(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFileId(a,t){return m(this,void 0,void 0,(function*(){const o=this.config.access_token,i=`https://www.googleapis.com/drive/v3/files?q=name='${a}'+and+'${t}'+in+parents&fields=files(id,name)`;try{const a=yield e.get(i,{headers:{Authorization:"Bearer "+o}});if(0===a.data.files.length)return"";const t=a.data.files;return t.length>0?t[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(a){return m(this,void 0,void 0,(function*(){a=this.baseFolder+"/"+a;const t=this.config.access_token;if(""===a)return"root";if(this.folderIdCache.has(a))return this.folderIdCache.get(a);const o=a.split("/").filter((e=>""!==e.trim()));let i="root",n="";for(const a of o){if(n=n?n+"/"+a:a,this.folderIdCache.has(n)){i=this.folderIdCache.get(n);continue}let o=yield this.getFolderId(a,i);if(!o){const n={name:a,mimeType:"application/vnd.google-apps.folder",parents:[i]};try{o=(yield e.post("https://www.googleapis.com/drive/v3/files",n,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${a}:`,e),e}}this.folderIdCache.set(n,o),i=o}return i}))}getFolderId(a,t){return m(this,void 0,void 0,(function*(){const o=this.config.access_token,i=`https://www.googleapis.com/drive/v3/files?q=name='${a=encodeURIComponent(a)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${t}'+in+parents&fields=files(id,name)`;try{const a=(yield e.get(i,{headers:{Authorization:`Bearer ${o}`}})).data.files;return a.length>0?a[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=yield this.checkFolder(a),i=[],n="",r=!0;for(;r;){let a=`https://www.googleapis.com/drive/v3/files?q='${o}'+in+parents&fields=nextPageToken,files(id,name,size,mimeType)&pageSize=1000`;n&&(a+=`&pageToken=${n}`);const l=yield e.get(a,{headers:{Authorization:`Bearer ${t}`}}),s=l.data.files||[];i=i.concat(s),n=l.data.nextPageToken,r=!!n}return[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(a){return m(this,void 0,void 0,(function*(){const t=a.split("/").pop()||"",o=a.split("/").slice(0,-1).join("/"),i=yield this.checkFolder(o),n=this.config.access_token,r=yield this.getFileId(t,i);if(""===r)return console.error("File not found:",t),!0;try{const a=yield e.delete(`https://www.googleapis.com/drive/v3/files/${r}`,{headers:{Authorization:`Bearer ${n}`}});return console.error("File deleted:",a),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${C.googleClientId}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class B extends U{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=t.split("/").pop()||"",n=new File([a],i,{lastModified:(new Date).getTime(),type:a.type}),r=t.split(".").pop(),l=p(r||""),s=t.split("/")[0],d=yield this.checkFolder(s),c=yield this.getFileId(i||"",d);const u={mimeType:l,name:i,parents:[d]},m=c?`https://www.googleapis.com/upload/drive/v3/files/${c}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",h=(yield e({method:c?"PATCH":"POST",url:m,data:c?null:JSON.stringify(u),headers:{Authorization:"Bearer "+o,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,g=yield this.getData(n);if(0===Object.keys(g).length)return!1;const f=yield e.put(h,g.data,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/zip","Content-Range":`bytes 0-${g.fileSize-1}/${g.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(f.status>=300)||(console.error("Error occurred during file download:",f),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token;let o=a.split("/").pop(),i=a.split("/")[0],n=yield this.checkFolder(i),r=yield this.getFileId(o||"",n);if(!r)return console.error("File not found:",o),!0;const l=`https://www.googleapis.com/drive/v3/files/${r}?alt=media`,s=yield e.get(l,{headers:{Authorization:"Bearer "+t},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return s.status>=300?(console.error("Error occurred during file download:",s),!1):s.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getData(e){return m(this,void 0,void 0,(function*(){return e?new Promise(((a,t)=>{const o=new FileReader;o.onload=t=>a({fileName:e.name,mimeType:e.type,fileSize:e.size,data:t.target.result}),o.onerror=e=>t(e),o.readAsArrayBuffer(e)})):{}}))}}class z{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=2){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getStorage(){return m(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new a({email:e,password:t,userAgent:"KoodoReader/1.0"}).ready,this.storage}))}getRoot(){return m(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;if(""===this.baseFolder)return this.root=e,this.root;let a=e.children.find((e=>e.name===this.baseFolder&&e.directory));return a||(a=yield e.mkdir(this.baseFolder)),this.root=a,this.root}))}createFolder(e,a){return m(this,void 0,void 0,(function*(){const t=`${e.nodeId}_${a}`;if(this.folderCreationLocks.has(t))return yield this.folderCreationLocks.get(t);const o=(()=>m(this,void 0,void 0,(function*(){try{let t=e.children.find((e=>e.name===a&&e.directory));return t||(t=yield e.mkdir(a),t)}finally{this.folderCreationLocks.delete(t)}})))();return this.folderCreationLocks.set(t,o),yield o}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){try{let a=yield this.getRoot();if(e){const t=e.split("/").filter((e=>e));for(const e of t){const t=a.children.find((a=>a.name===e&&a.directory));if(!t)return[];a=t}}return a.children.map((e=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return m(this,void 0,void 0,(function*(){try{let a=yield this.getRoot();const t=e.split("/"),o=t.pop();for(const e of t){if(!e)continue;const t=a.children.find((a=>a.name===e&&a.directory));if(!t)return!0;a=t}const i=a.children.find((e=>e.name===o&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class D extends z{constructor(e){super(e)}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const i=a.split("/"),n=i.pop()||"";for(const e of i){if(!e)continue;let a=o.children.find((a=>a.name===e&&a.directory));a||(a=yield this.createFolder(o,e)),o=a}const r=new File([e],n,{lastModified:(new Date).getTime(),type:e.type}),l=yield e.arrayBuffer(),s=new Uint8Array(l),d=t.from(s),c=o.children.find((e=>e.name===n&&!e.directory));return c&&(yield c.delete()),yield o.upload({name:n,size:r.size},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let a=yield this.getRoot();const t=e.split("/"),o=t.pop()||"";for(const e of t){if(!e)continue;const t=a.children.find((a=>a.name===e&&a.directory));if(!t)return!0;a=t}const i=a.children.find((e=>e.name===o&&!e.directory));if(!i)return!0;const n=yield i.downloadBuffer();return this.taskQueue.setDownloadedSize(n.size),n.buffer}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class L{constructor(e){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.taskQueue=new k(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);let o,i=[];if(""===a)o=`${this.baseUrl}/children`;else{const e=encodeURIComponent(a);o=`${this.baseUrl}:/${e}:/children`}for(;o;){const a=yield e.get(o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(a.status>=300)break;const n=a.data.value||[];i=i.concat(n),o=a.data["@odata.nextLink"]||""}return[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;for(a=this.baseFolder+"/"+a;a.startsWith("/");)a=a.substring(1);const o=yield e.delete(`${this.baseUrl}:/${a}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${C.microsoftClientId}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${e}`}}class P extends L{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.access_token;let i=t.split("/").pop()||"",n=new File([a],i,{lastModified:(new Date).getTime(),type:a.type}),r=this.baseFolder+"/"+t;for(;r.startsWith("/");)r=r.substring(1);const l=this.baseUrl+":/"+r+":/createUploadSession",s=yield e.post(l,null,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let d=n.size;const c=n.type,u=s.data.uploadUrl,m=yield e.put(u,n,{headers:{"Content-Type":c,"Content-Range":`bytes 0-${d-1}/${d}`},maxContentLength:1/0,maxBodyLength:1/0});return!(m.status>=300)||(console.error("Error occurred during file download:",m),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;for(;o.startsWith("/");)o=o.substring(1);const i=`${this.baseUrl}:/${o}:/content`,n=yield e.get(i,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+t},maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error occurred during file download:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class j{downloadFile(e,a){return m(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return m(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}getAuthUrl(){return""}}class K{constructor(e){this.baseUrl="https://api.pcloud.com",this.config=e,this.taskQueue=new k(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}retryOperation(e,a=3){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}checkFolderExists(a,t){return m(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:t,path:`/${a}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(a,t){return m(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/createfolderifnotexists`,{params:{access_token:t,path:`/${a}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:t,path:"/"+a,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/deletefile`,{params:{access_token:t,path:"/"+a}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${C.pcloudClientId}&response_type=code&redirect_uri=${e}`}}class H extends K{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=this.config.refresh_token,i=t.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,o))){if(!(yield this.createFolder(i,o)))return!1}let n=t.split("/").pop()||"",r=new File([a],n,{lastModified:(new Date).getTime(),type:a.type});const l=new FormData;l.append("file",r);const s=yield e.post(`${this.baseUrl}/uploadfile`,l,{params:{access_token:o,path:`/${i}`,renew:1},maxContentLength:1/0,maxBodyLength:1/0});return 0===s.data.result||(console.error("Error uploading file:",s.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/getfilelink`,{params:{access_token:t,path:`/${a}`}});if(0!==o.data.result)return console.error("Error getting file link:",o.data),!0;const i=`https://${o.data.hosts[0]}${o.data.path}`,n=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class J{constructor(e){this.config=e,this.taskQueue=new k(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=0){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}shouldUsePathStyle(){try{if(this.config.forcePathStyle&&"no"!==this.config.forcePathStyle)return!0;let e=this.config.endpoint;const a=new URL(e),t=a.hostname,o=/^(\d{1,3}\.){3}\d{1,3}$/.test(t),i=""!==a.port;return!o&&i}catch(e){return!0}}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){let{endpoint:a,region:t,bucketName:n,accessKeyId:r,secretAccessKey:l,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;let d=s+"/"+e;for(;d.startsWith("/");)d=d.substring(1);""===d||d.endsWith("/")||(d+="/");const c=new o({endpoint:a,region:t,credentials:{accessKeyId:r,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle()});try{let e,a=[],t=[],o=!0;for(;o;){const r=yield c.send(new i({Bucket:n,Prefix:d,Delimiter:"/",ContinuationToken:e}));r.Contents&&(a=a.concat(r.Contents)),r.CommonPrefixes&&(t=t.concat(r.CommonPrefixes)),e=r.NextContinuationToken,o=!!e}let r=[];return a.forEach((e=>{if(!e.Key.endsWith("/")){const a=e.Key.substring(d.length);a.includes("/")||r.push({name:a,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),t.forEach((e=>{const a=e.Prefix.substring(d.length).replace(/\/$/,"");a&&r.push({name:a,size:0,type:"folder",modified:""})})),r}catch(e){return console.error(e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){let{endpoint:a,region:t,bucketName:i,accessKeyId:r,secretAccessKey:l,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const d=new o({endpoint:a,region:t,credentials:{accessKeyId:r,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield d.send(new n({Bucket:i,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class W extends J{constructor(e){super(e)}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:n,accessKeyId:l,secretAccessKey:s,dir:d}=this.config;const c=new o({endpoint:t,region:i,credentials:{accessKeyId:l,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let u=d+"/"+a;for(;u.startsWith("/");)u=u.substring(1);try{let a=yield c.send(new r({Bucket:n,Key:u,Body:e}));return 200===a.$metadata.httpStatusCode||(console.error("Error uploading file:",a),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:a,region:t,bucketName:i,accessKeyId:n,secretAccessKey:r,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const d=new o({endpoint:a,region:t,credentials:{accessKeyId:n,secretAccessKey:r},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{const e=yield d.send(new l({Bucket:i,Key:c}));if(!e.Body)return console.error("No response body"),!1;const a=yield e.Body.transformToByteArray();return this.taskQueue.setDownloadedSize(a.length),a.buffer}catch(a){return console.error("Error downloading file:",a,e),!1}}))))))}))}}class q{constructor(e){this.config=e,this.taskQueue=new k(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=this.baseFolder;a&&""!==a.trim()&&(o=o+"/"+a),o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));let i=[],n=0;const r=1e3;for(;;){const a=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:t,dir:"/"+o,start:n,limit:r,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(a.status>=300||0!==a.data.errno){console.error("百度网盘API错误:",a.data);break}const l=a.data.list||[];if(0===l.length)break;if(i=i.concat(l),l.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path,fs_id:e.fs_id})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));const i=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+o])}),n=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${t}&opera=delete`,i.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==n.data.errno)return console.error("百度网盘删除文件API错误:",n.data),-9===n.data.errno?console.error("文件不存在"):111===n.data.errno?console.error("有其他异步任务正在执行"):-7===n.data.errno&&console.error("文件名非法"),!1;const r=n.data.info||[];for(const e of r)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${C.duboxClientId}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}const G=4194304;class Q extends q{constructor(e){super(e)}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){var o;try{const o=this.config.access_token;let i=this.baseFolder+"/"+t;i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));const n=yield a.arrayBuffer(),r=n.byteLength,l=new Uint8Array(n),{contentMd5:s,sliceMd5:d,blockList:c}=this.calculateFileMd5(l,r),u=new URLSearchParams({path:"/"+i,size:r.toString(),isdir:"0",autoinit:"1",rtype:"3",block_list:JSON.stringify(c),"content-md5":s,"slice-md5":d,local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),m=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=${o}`,u.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==m.data.errno)return console.error("预上传失败:",m.data),!1;const p=m.data.uploadid,h=m.data.block_list||[];if(0===h.length)return!0;const g=yield this.getUploadDomain(o,"/"+i,p);if(!g)return console.error("获取上传域名失败"),!1;for(const a of h){const t=a*G,n=Math.min(G,r-t),s=l.slice(t,t+n),d=new FormData;d.append("file",new Blob([s],{type:"application/octet-stream"}),`chunk_${a}`);const u=`${g}/rest/2.0/pcs/superfile2?method=upload&access_token=${o}&type=tmpfile&path=${encodeURIComponent("/"+i)}&uploadid=${p}&partseq=${a}`,m=yield e.post(u,d,{headers:{"User-Agent":"pan.baidu.com"},maxContentLength:1/0,maxBodyLength:1/0,timeout:0});if(m.status>=300)throw new Error(`分片上传失败: ${JSON.stringify(m.data)}`);const h=m.data.md5,f=c[a];h&&h!==f&&console.warn(`分片 ${a} MD5不匹配: 期望 ${f}, 实际 ${h}`)}const f=new URLSearchParams({path:"/"+i,size:r.toString(),isdir:"0",block_list:JSON.stringify(c),uploadid:p,rtype:"3",local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),y=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=${o}`,f.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});return 0===y.data.errno||(console.error("创建文件失败:",y.data),!1)}catch(e){return console.error("文件上传过程中发生错误:",(null===(o=e.response)||void 0===o?void 0:o.data)||e.message||e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){var t;this.taskQueue.setDownloadedSize(0);try{const o=this.config.access_token;let i=this.baseFolder+"/"+a;i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));const n=yield this.listFileInfos(a.substring(0,a.lastIndexOf("/"))),r=i.split("/").pop(),l=n.find((e=>e.name===r));if(!l)return console.error("文件不存在:",a),!1;const s=yield e.get("https://pan.baidu.com/rest/2.0/xpan/multimedia",{params:{method:"filemetas",access_token:o,fsids:JSON.stringify([l.fs_id]),dlink:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==s.data.errno||!(null===(t=s.data.list)||void 0===t?void 0:t[0]))return console.error("获取下载链接失败:",s.data),!1;const d=s.data.list[0].dlink;return(yield e.get(d,{responseType:"arraybuffer",params:{access_token:o},headers:{"User-Agent":"pan.baidu.com"},onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}})).data}catch(e){return console.error("下载文件时发生错误:",e),!1}}))))))}))}getUploadDomain(a,t,o){return m(this,void 0,void 0,(function*(){try{const i=yield e.get("https://d.pcs.baidu.com/rest/2.0/pcs/file",{params:{method:"locateupload",appid:"250528",access_token:a,path:t,uploadid:o,upload_version:"2.0"},headers:{"User-Agent":"pan.baidu.com"}});if(0!==i.data.error_code)return console.error("获取上传域名失败:",i.data),null;const n=i.data.servers||[],r=n.find((e=>e.server.startsWith("https://")));return r?r.server:n.length>0?n[0].server:(console.error("没有可用的上传服务器"),null)}catch(e){return console.error("获取上传域名时出错:",e),null}}))}calculateFileMd5(e,a){const t=[];let o="",i=0;for(;i=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getUploadCredentials(a){return m(this,void 0,void 0,(function*(){try{const t=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${a}`}});return t.status>=300||!t.data.state?(console.error("Error getting upload credentials:",t.data),null):t.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,a,t=new Date(Date.now()+36e5)){const o={expiration:t.toISOString(),conditions:[{bucket:e},{key:a},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(o)}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${C.yiyiwuClientId}&response_type=code&redirect_uri=${e}`}}class X extends Y{constructor(e){super(e)}sha1Hex(e){return m(this,void 0,void 0,(function*(){const a=yield crypto.subtle.digest("SHA-1",e);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}calculateFileSha1(e){return m(this,void 0,void 0,(function*(){try{const a=yield e.arrayBuffer();return this.sha1Hex(a)}catch(e){return console.error("Error calculating file SHA1:",e),""}}))}calculatePreSha1(e){return m(this,void 0,void 0,(function*(){try{const a=e.slice(0,131072),t=yield a.arrayBuffer();return this.sha1Hex(t)}catch(e){return console.error("Error calculating pre SHA1:",e),""}}))}calculateOSSSignature(e,a){const t=s.enc.Base64.stringify(s.enc.Utf8.parse(a));return s.HmacSHA1(t,e).toString(s.enc.Base64)}handleSecondAuth(e,a,t,o,i,n,r,l){return m(this,void 0,void 0,(function*(){try{if(!a.sign_check)return console.error("No sign_check provided for second authentication"),null;const[s,d]=a.sign_check.split("-"),c=parseInt(s),u=parseInt(d),m=t.slice(c,u+1),p=yield m.arrayBuffer(),h=(yield this.sha1Hex(p)).toUpperCase();return yield this.initializeUpload(e,o,i,n,r,l,a.sign_key,h,a.pick_code)}catch(e){return console.error("Error during second authentication:",e),null}}))}uploadToObjectStorage(a,t,o,i){var n;return m(this,void 0,void 0,(function*(){try{const n=i.endpoint,r=o.bucket,l=o.object;let s;if(n.includes(r))s=n;else{s=`https://${r}.${n.replace(/^https?:\/\//,"")}`}const d=this.generateOSSPolicy(r,l),c=this.calculateOSSSignature(i.AccessKeySecret,d),u=btoa(d),m=new FormData;if(m.append("key",l),m.append("policy",u),m.append("OSSAccessKeyId",i.AccessKeyId),m.append("signature",c),m.append("x-oss-security-token",i.SecurityToken),m.append("success_action_status","200"),o.callback&&o.callback.callback){const e=btoa(o.callback.callback);if(m.append("callback",e),o.callback.callback_var){const e=JSON.parse(o.callback.callback_var);for(const[a,t]of Object.entries(e))m.append(a,String(t))}}const p=new File([a],t,{type:a.type});m.append("file",p);const h=yield e.post(s,m,{maxContentLength:1/0,maxBodyLength:1/0});return 200===h.status||204===h.status||(console.error("Upload failed with status:",h.status),!1)}catch(e){return console.error("Error uploading file via REST API:",(null===(n=e.response)||void 0===n?void 0:n.data)||e.message||e),!1}}))}uploadFile(e,a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){var t;try{const t=this.config.access_token;let o=this.baseFolder+"/"+a;o.startsWith("/")||(o="/"+o);const i=e.size,n=yield this.calculateFileSha1(e),r=yield this.calculatePreSha1(e),l=a.split("/").pop()||a,s=o.substring(0,o.lastIndexOf("/"))||"/";let d=yield this.getFolderInfo(s,!0),c="0";if(d)c=d.file_id;else{let e=yield this.createFolder(s);if(!e)return console.error("Failed to create folder:",s),!1;c=e}yield this.deleteFileWithoutQueue(a);let u=yield this.initializeUpload(c,l,i,n,r,t);if(!u)return console.error("Failed to initialize upload"),!1;if((6===u.status||7===u.status||8===u.status)&&(u=yield this.handleSecondAuth(c,u,e,l,i,n,r,t),!u))return console.error("Second authentication failed"),!1;if(2===u.status)return console.info(`File ${a} uploaded successfully via instant upload.`),!0;const m=yield this.getUploadCredentials(t);if(!m)return console.error("Failed to get upload credentials"),!1;return(yield this.uploadToObjectStorage(e,l,u,m))?(console.info(`File ${a} uploaded successfully.`),!0):(console.error("Failed to upload to object storage"),!1)}catch(e){return console.error("Error occurred during file upload:",(null===(t=e.response)||void 0===t?void 0:t.data)||e.message||e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let t=this.baseFolder+"/"+a;t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t);const o=yield this.getFolderInfo(t,!1);if(!o||!o.pick_code)return console.error("Failed to get file info or pick_code for:",a),!1;const i=yield this.getFileDownloadUrl(o.pick_code);if(!i)return console.error("Failed to get download URL for:",a),!1;const n=yield e.get(i.url,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}initializeUpload(a,t,o,i,n,r,l,s,d){return m(this,void 0,void 0,(function*(){try{const c=new FormData;c.append("file_name",t),c.append("file_size",o.toString()),a?c.append("target","U_1_"+a):c.append("target","U_1_0"),c.append("fileid",i),c.append("preid",n),c.append("topupload","0"),d&&c.append("pick_code",d),l&&c.append("sign_key",l),s&&c.append("sign_val",s);const u=yield e.post(`${this.baseUrl}/open/upload/init`,c,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"multipart/form-data"}});return u.status>=300||!u.data.state?(console.error("Error initializing upload:",u.data),null):u.data.data}catch(e){return console.error("Error occurred during upload initialization:",e),null}}))}createFolder(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=a.replace(/^\/+|\/+$/g,"");if(!o)return"";const i=o.split("/");let n="",r="0";for(const a of i){n=n?`${n}/${a}`:a;const o=yield this.getFolderInfo(n,!0);if(o&&o.file_id)r=o.file_id;else{const o=new FormData;o.append("pid",r),o.append("file_name",a);const i=yield e.post(`${this.baseUrl}/open/folder/add`,o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});if(i.status>=300||!i.data.state)return console.error("Error creating folder:",i.data),"";r=i.data.data.file_id}}return r}catch(e){return console.error("Error occurred during folder creation:",e),""}}))}getFolderInfo(a,t){return m(this,void 0,void 0,(function*(){if(""===a||"/"===a)return{file_id:"0"};a.startsWith("/")||(a="/"+a);try{const t=this.config.access_token,o=new FormData;o.append("path",a);const i=yield e.post(`${this.baseUrl}/open/folder/get_info`,o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});return i.status>=300||!i.data.state||0===i.data.data.length?(console.error("Error getting file info:",i.data),null):i.data.data}catch(e){return console.error("Error occurred during get file info:",e),null}}))}getFileDownloadUrl(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token,o=new FormData;o.append("pick_code",a);const i=yield e.post(`${this.baseUrl}/open/ufile/downurl`,o,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});if(i.status>=300)return console.error("Error getting download URL:",i.data),null;const n=i.data.data,r=Object.keys(n)[0];return r&&n[r]?n[r].url:(console.error("No file data found in download URL response"),null)}catch(e){return console.error("Error occurred during get download URL:",e.message||e),null}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;(a=this.baseFolder+"/"+a).startsWith("/")||(a="/"+a);let o=[],i=0;const n=1150;let r=!0,l=yield this.getFolderInfo(a,!0),s="";if(l)s=l.file_id;else{let e=yield this.createFolder(a);if(!e)return console.error("Failed to create folder:",a),[];s=e}if(!s)return console.error("Failed to get or create folder ID:",a),[];let d=s;for(;r;){const a={offset:i,limit:n,cur:1,show_dir:1};d&&(a.cid=d);const l=yield e.get(`${this.baseUrl}/open/ufile/files`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},params:a});if(l.status>=300)break;const s=l.data.data||[];o=o.concat(s),s.length({name:e.fn,size:e.fs||0,type:"0"===e.fc?"folder":"file",modified:new Date(1e3*e.upt).toISOString()})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{const t=this.config.access_token;a=this.baseFolder+"/"+a;const o=yield this.getFolderInfo(a,!1);if(!o)return!0;const i=new FormData;i.append("file_ids",o.file_id);const n=yield e.post(`${this.baseUrl}/open/ufile/delete`,i,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"multipart/form-data"}});return!(n.status>=300||!n.data.state)||(console.error("Error deleting file:",n),!1)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}}class V{constructor(e){let{username:a,password:t,url:o,dir:i,AuthType:n,createClient:r}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,i=i&&"KoodoReader"===this.baseFolder?i:this.baseFolder,this.username=a,this.password=t,this.url=o,this.dir=i,this.taskQueue=new k(5),this.AuthType=n,this.createClient=r}getClient(){return m(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(a){return m(this,void 0,void 0,(function*(){try{const t=yield e.head(a,{maxRedirects:0,validateStatus:()=>!0,timeout:5e3});return t.request&&t.request.responseURL&&t.request.responseURL!==a?t.request.responseURL:t.status>=300&&t.status<400&&t.headers.location?t.headers.location:a}catch(e){return console.info("Error handling URL redirection:",e),a}}))}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){const a=yield this.getClient();try{const t=a.getDirectoryContents(this.dir+"/"+e),o=new Promise(((e,a)=>{setTimeout((()=>a(new Error("WebDAV list directory timeout"))),5e3)}));return(yield Promise.race([t,o])).filter((a=>"."!==a.filename&&".."!==a.filename&&a.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}catch(t){return t.response&&404===t.response.status&&(yield a.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",t),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){const a=yield this.getClient();try{return yield a.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return m(this,void 0,void 0,(function*(){let a=yield this.getClient();try{const t=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let o="";for(const e of t)o=o?`${o}/${e}`:e,(yield a.exists(`/${o}`))||(yield a.createDirectory(`/${o}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class Z extends V{constructor(e){super(Object.assign(Object.assign({},e),{AuthType:d,createClient:c}))}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{let o=this.dir+"/"+t,i=yield this.getClient();const n=i.exists(o.substring(0,o.lastIndexOf("/"))),r=new Promise(((e,a)=>{setTimeout((()=>a(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([n,r]))&&(yield this.ensureDirectoryExists(o.substring(0,o.lastIndexOf("/"))));let l=t.split("/").pop()||"",s=new File([a],l,{lastModified:(new Date).getTime(),type:a.type}),d=i.getFileUploadLink(this.dir+"/"+t);const c=new URL(d);c.search="",d=c.toString();const u=btoa(this.username+":"+this.password),m=yield e.put(d,s,{headers:{Authorization:"Basic "+u},maxContentLength:1/0,maxBodyLength:1/0});return!(m.status>=300)||(console.error("Error occurred during file upload:",m),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===a.indexOf("."))return new ArrayBuffer(0);try{const t=btoa(this.username+":"+this.password);let o=this.url.endsWith("/")?this.url:this.url+"/",i=this.dir.startsWith("/")?this.dir.substring(1):this.dir;const n=yield e({url:o+i+"/"+a,method:"get",headers:{Authorization:"Basic "+t},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return n.status>=300?(console.error("Error occurred during file download:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ee{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.taskQueue=new k(3)}retryOperation(e,a=1){return m(this,void 0,void 0,(function*(){let t=0;for(;;){const o=yield e();if(o)return o;if(t>=a)return this.taskQueue.hasFailedTasks=!0,o;t++;const i=1e3*Math.pow(2,t);console.info(`Retry attempt ${t} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return m(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(a){return m(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:a},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(a){return m(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:a.split("/").slice(0,-1).join("/")||"",filename:a.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}class ae extends ee{constructor(e){super(e)}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(a,t){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){try{const o=t.split("/").pop()||"",i=t.substring(0,t.lastIndexOf("/"))||"";let n=this.listFiles("");const r=new Promise(((e,a)=>{setTimeout((()=>a(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([n,r]);let l=new File([a],o,{lastModified:(new Date).getTime(),type:a.type});const s=new FormData;s.append("file",l);const d=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(i)}`,s,{headers:{Authorization:this.getAuthHeader(),"Content-Type":"multipart/form-data"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(a){return m(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>m(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const t=a.split("/").pop()||"",o=a.substring(0,a.lastIndexOf("/"))||"",i=yield e({url:`${this.url}/download`,method:"GET",params:{dir:o,filename:t},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const te=["book","config","cover","font"];class oe{constructor(e,a){this.type=e,this.remote="dropbox"===e?new _(a):"microsoft"===e?new P(a):"google"===e?new B(a):"microsoft_exp"===e?new P(Object.assign(Object.assign({},a),{isExp:!0})):"google_exp"===e?new B(Object.assign(Object.assign({},a),{isExp:!0})):"s3compatible"===e?new W(a):"webdav"===e?new Z(a):"docker"===e?new ae(a):"boxnet"===e?new R(a):"mega"===e?new D(a):"adrive"===e?new I(a):"pcloud"===e?new H(a):"dubox"===e?new Q(a):"yandex"===e?new M(a):"yiyiwu"===e?new X(a):new j}downloadFile(e,a){return m(this,void 0,void 0,(function*(){if("cover"!==a){if(!(yield this.listFiles(a)).find((a=>e.indexOf(a)>-1)))return!1}return yield this.remote.downloadFile(a+"/"+e)}))}uploadFile(e,a,t){return m(this,void 0,void 0,(function*(){return 0===t.size||(yield this.remote.uploadFile(t,a+"/"+e))}))}deleteFile(e,a){return m(this,void 0,void 0,(function*(){return!(yield this.listFiles(a)).find((a=>e.indexOf(a)>-1))||(yield this.remote.deleteFile(a+"/"+e))}))}listFiles(e){return m(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return m(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}isExist(e,a){return m(this,void 0,void 0,(function*(){return(yield this.listFiles(a)).find((a=>-1!==a.indexOf(e)))}))}downloadAllFiles(){return m(this,void 0,void 0,(function*(){for(let e of te){let a=yield this.listFiles(e);for(let t of a)yield this.downloadFile(t,e)}}))}getAuthUrl(e){return this.remote.getAuthUrl?this.remote.getAuthUrl(e):""}getStats(){return this.remote.taskQueue.getStats()}clearQueue(){return this.remote.taskQueue.clearQueue()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const ie={words:['ALTER TABLE words ADD COLUMN "sentence" text']},ne={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},re={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},le={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function se(e){for(const a in e)e.hasOwnProperty(a)&&(e[`temp-${a}`]=e[a]);return e}const de={notes:e=>{let a=Object.assign({},e);return a.date=JSON.parse(e.date),a.tag=JSON.parse(e.tag),a},bookmarks:e=>e,books:e=>e,plugins:e=>{let a=Object.assign({},e);return e.autoValue||delete a.autoValue,e.langList?a.langList=JSON.parse(e.langList):delete a.langList,e.voiceList?a.voiceList=JSON.parse(e.voiceList):delete a.voiceList,a.config=JSON.parse(e.config),a},words:e=>{let a=Object.assign({},e);return a.date=JSON.parse(e.date),void 0===a.sentence&&(a.sentence=""),a}};var ce={sqlStatement:{createTableStatement:se({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "sentence" text,\n "chapter" text\n );\n '}),migrateStatement:se(ie),getAllStatement:se({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:se({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:se({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:se({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, sentence, chapter) VALUES (@key, @bookKey, @date, @word, @sentence, @chapter)"}),deleteAllStatement:se({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:se({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, sentence = @sentence, chapter = @chapter WHERE key = @key"}),deleteStatement:se({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:se({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:se(ne),getByBookKeyStatement:se(re),getByBookKeysStatement:se({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),getKeysStatement:se({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:se({notes:(e,a,t,o)=>`SELECT * FROM notes ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,bookmarks:(e,a,t,o)=>`SELECT * FROM bookmarks ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,books:(e,a,t,o)=>`SELECT * FROM books ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,plugins:(e,a,t,o)=>`SELECT * FROM plugins ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`,words:(e,a,t,o)=>`SELECT * FROM words ORDER BY ${e} ${a} LIMIT ${t} OFFSET ${o}`}),getByKeysStatement:se({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,a)=>`WHEN ? THEN ${a}`)).join(" ")} END`}),deleteByBookKeyStatement:se(le)},jsonToSqlite:se({notes:e=>{let a=Object.assign({},e);return a.date=JSON.stringify(e.date),a.tag=JSON.stringify(e.tag),a},bookmarks:e=>e,books:e=>{let a=Object.assign({},e);return a.page=e.page||0,a},plugins:e=>{let a=Object.assign({},e);return e.autoValue||(a.autoValue=null),e.langList?a.langList=JSON.stringify(e.langList):a.langList=null,e.voiceList?a.voiceList=JSON.stringify(e.voiceList):a.voiceList=null,a.config=JSON.stringify(e.config),a},words:e=>{let a=Object.assign({},e);return a.date=JSON.stringify(e.date),void 0===a.sentence&&(a.sentence=""),a}}),sqliteToJson:se(de)};const ue=E.testUrl,me=E.cloudCNUrl;class pe{constructor(e,a,t){this.TokenService=e,this.ConfigService=a,this.baseUrl="china"===t?me:ue,this.serverRegion=t,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}refreshUserToken(){return m(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let a=(yield e.post(this.baseUrl+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===a.code&&(yield this.TokenService.setToken("access_token",a.data.access_token),yield this.TokenService.setToken("refresh_token",a.data.refresh_token),yield this.TokenService.setToken("expires_at",(1e3*a.data.expires_at).toString()),this.accessToken=a.data.access_token,this.refreshToken=a.data.refresh_token,this.expiresAt=1e3*a.data.expires_at),a}))}requestWithRetry(e){return m(this,void 0,void 0,(function*(){return pe.requestQueue||(pe.requestQueue=[]),new Promise(((a,t)=>{pe.requestQueue.push({config:e,resolve:a,reject:t}),pe.processingQueue||this.processQueue()}))}))}isTokenValid(){return m(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return m(this,void 0,void 0,(function*(){if(!pe.processingQueue){pe.processingQueue=!0;try{for(;pe.requestQueue.length>0;){const e=pe.requestQueue.shift();try{let a=yield this.executeRequest(e.config);e.resolve(a)}catch(a){e.reject(a)}}}finally{pe.processingQueue=!1}}}))}executeRequest(a){return m(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let t="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);if(a.baseURL=this.baseUrl,a.headers)a.headers.Authorization="Bearer "+this.accessToken,a.headers["X-Request-ID"]=t;else{let e=this.ConfigService.getItem("appVersion"),o=this.ConfigService.getItem("appPlatform");a.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":t,"X-App-Version":e||"1.0.0","X-App-Platform":o||"web"}}let o=(yield e(a)).data;if(402===o.code){let t=yield this.refreshUserToken();if(200===t.code){return a.headers=a.headers||{},a.headers.Authorization="Bearer "+this.accessToken,(yield e(a)).data}return t}return 200!==o.code&&console.error("Request error:",o),o}catch(e){return console.error("Request execution error:",e),"Network Error"===e.message?{code:503,message:"network error",data:null,msg:"Network error, please try again later. 网络错误,请稍后再试。"}:{code:500,message:e.message||"Unknown error",msg:e.message||"Unknown error",data:null}}}))}requestWithStream(e,a,t){return m(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>m(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let o=this.accessToken||"",i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,r)=>{let l=this.ConfigService.getItem("appVersion"),s=this.ConfigService.getItem("appPlatform");const d=new t(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":i,"X-App-Version":l||"1.0.0","X-App-Platform":s||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});d.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),d.addEventListener("message",(e=>m(this,void 0,void 0,(function*(){if(!e.data)return;const t=JSON.parse(e.data);t.done?(d.close(),n(t)):a(t.data)})))),d.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);a(t.data),n(t),d.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,a){return m(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>m(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let t=this.accessToken||"",o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,n)=>m(this,void 0,void 0,(function*(){let n=this.ConfigService.getItem("appVersion"),r=this.ConfigService.getItem("appPlatform");var l=new u(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+t,"X-Request-ID":o,"X-App-Version":n||"1.0.0","X-App-Platform":r||"web"},payload:JSON.stringify(e.data),method:"POST"});l.addEventListener("message",(e=>m(this,void 0,void 0,(function*(){if(!e.data)return;const t=JSON.parse(e.data);t.done?(l.close(),i(t)):a(t.data)})))),l.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),l.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);a(t.data),i(t),l.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}pe.processingQueue=!1,pe.requestQueue=[];class he extends pe{constructor(e,a,t){super(e,a,t)}getTransStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getTransFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithFetch(t,a)}))}getDictionary(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_llm_dict",data:e};return yield this.requestWithRetry(a)}))}getBatchTrans(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_llm_batch_trans",data:e};return yield this.requestWithRetry(a)}))}getSplitSentence(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_llm_split_sentence",data:e};return yield this.requestWithRetry(a)}))}getAnswerStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getAnswerFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithFetch(t,a)}))}getSummaryStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getSummaryFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithFetch(t,a)}))}getDictionaryStream(e,a,t){return m(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_dict_stream",data:e};return yield this.requestWithStream(o,a,t)}))}getDictionaryFetch(e,a){return m(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_dict_stream",data:e};return yield this.requestWithFetch(t,a)}))}getGoogleFont(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_google_font",data:e};return yield this.requestWithRetry(a)}))}sendToKindle(e,a){return m(this,void 0,void 0,(function*(){let t=new FormData;t.append("file",e.file),t.append("email",e.email),t.append("file_name",e.fileName);const o={method:"post",url:"/api/v1/pro/reader/send_to_kindle",headers:{"Content-Type":"multipart/form-data"},data:t,onUploadProgress:a?t=>{var o;const i=t.total||(null===(o=e.file)||void 0===o?void 0:o.size)||0;i>0&&a(Math.min(t.loaded/i,1))}:void 0};return yield this.requestWithRetry(o)}))}detectLanguage(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/detect_language",data:e};return yield this.requestWithRetry(a)}))}getTTSAudio(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_tts_audio",data:e};return yield this.executeRequest(a)}))}getOcrResult(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_ocr_result",data:e};return yield this.executeRequest(a)}))}getOcrResultV2(e){return m(this,void 0,void 0,(function*(){let a=new FormData;a.append("file",e.file);const t={method:"post",url:"/api/v1/pro/reader/get_ocr_result_v2",headers:{"Content-Type":"multipart/form-data"},data:a};return yield this.executeRequest(t)}))}analyzeText(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/analyze_text",data:e};return yield this.requestWithRetry(a)}))}getBookMetadata(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/get_book_metadata",data:e};return yield this.requestWithRetry(a)}))}analyzeBookTitle(e){return m(this,void 0,void 0,(function*(){const a={method:"post",url:"/api/v1/pro/reader/analyze_book_title",data:e};return yield this.requestWithRetry(a)}))}}class ge extends pe{constructor(e,a,t){super(e,a,t),this.serverRegion=t}encryptToken(e){return m(this,void 0,void 0,(function*(){let a=e.token,t=v.encode(a),{extracted:o,remaining:i}=function(e){let a="",t="",o=[],i=1;for(;i<=e.length;)o.push(i-1),i*=2;for(let i=0;i-1){let t=a.split("#");e.encrypted_token=t[1]}const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let o=yield this.requestWithRetry(t);if(a.indexOf("#")>-1&&o.data&&o.data.token){let e=a.split("#"),t=function(e,a){let t="",o=[],i=1,n=e.length+a.length;for(;i<=n;)o.push(i-1),i*=2;let r=0,l=0;for(let i=0;i{let o="";if("github"===e?o=`https://github.com/login/oauth/authorize?client_id=${C.githubClientId}&redirect_uri=${t}&scope=${T.github.scopes.join(" ")}&response_type=code`:"google"===e?o=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${t}&prompt=consent&response_type=code&client_id=${C.googleClientId}&scope=${T.google.scopes.join(" ")}&access_type=offline`:"facebook"===e?o=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${C.facebookClientId}&redirect_uri=${t}&scope=&response_type=code`:"microsoft"===e&&(o=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${C.microsoftClientId}&scope=${T.microsoft.scopes.join(" ")}&response_type=code&redirect_uri=${t}`),"manual"===a)return o;let i=JSON.stringify({deeplink:"desktop"===a?"koodo-reader://callback":"browser"===a?`${C.callbackUrl}#/login`:"",service:e});return`${o}&state=${"state|"+encodeURIComponent(i)}`}};class Ne{static CompareDatabase(e,a,t){return m(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.bookmarks"))),r=Object.keys(e).filter((e=>e.startsWith("database.sqlite.plugins"))),l=Object.keys(e).filter((e=>e.startsWith("database.sqlite.words"))),s=Object.keys(a).filter((e=>e.startsWith("database.sqlite.books"))),d=Object.keys(a).filter((e=>e.startsWith("database.sqlite.notes"))),c=Object.keys(a).filter((e=>e.startsWith("database.sqlite.bookmarks"))),u=Object.keys(a).filter((e=>e.startsWith("database.sqlite.plugins"))),m=Object.keys(a).filter((e=>e.startsWith("database.sqlite.words"))),p={books:Array.from(new Set(o.concat(s))),notes:Array.from(new Set(i.concat(d))),bookmarks:Array.from(new Set(n.concat(c))),plugins:Array.from(new Set(r.concat(u))),words:Array.from(new Set(l.concat(m)))},h={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},g=["books","notes","bookmarks","plugins","words"];for(let o of g)for(let i of p[o]){let n=i.split(".")[3],r=e[i],l=a[i];r?l?("save"===l.operation&&("update"!==r.operation&&"delete"!==r.operation||h[o].upload.push(n)),"delete"===l.operation&&("save"===r.operation&&(h[o].delete.push(n),e[i]=l),"update"===r.operation&&(r.timel.time&&(h[o].conflict.push(n),"cloud"===t?(h[o].delete.push(n),e[i]=l):h[o].upload.push(n))),r.operation),"update"===l.operation&&("save"===r.operation&&(h[o].update.push(n),e[i]=l),"update"===r.operation&&(r.timel.time&&h[o].upload.push(n)),"delete"===r.operation&&(r.timel.time&&h[o].upload.push(n)))):h[o].upload.push(n):(h[o].save.push(n),e[i]=l)}return{compareResult:h,syncRecords:e}}))}static CompareConfig(e,a,t){return m(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),n=Object.keys(e).filter((e=>e.startsWith("config.objectConfig"))),r=Object.keys(e).filter((e=>e.startsWith("config.mapConfig"))),l=Object.keys(a).filter((e=>e.startsWith("config.readerConfig"))),s=Object.keys(a).filter((e=>e.startsWith("config.listConfig"))),d=Object.keys(a).filter((e=>e.startsWith("config.objectConfig"))),c=Object.keys(a).filter((e=>e.startsWith("config.mapConfig"))),u={readerConfig:Array.from(new Set(o.concat(l))),listConfig:Array.from(new Set(i.concat(s))),objectConfig:Array.from(new Set(n.concat(d))),mapConfig:Array.from(new Set(r.concat(c)))},m={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],save:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],save:[],upload:[]}},p=["readerConfig","listConfig"];for(let t of p)for(let o of u[t]){let i=o,n=e[o],r=a[o];n?r?n.timer.time&&m[t].upload.push(i):m[t].upload.push(i):(m[t].update.push(i),e[o]=r)}let h=["objectConfig","mapConfig"];for(let o of h)for(let i of u[o]){let n=i,r=e[i],l=a[i];r?l?("delete"===l.operation&&("update"===r.operation&&(r.timel.time&&(m[o].conflict.push(n),"cloud"===t?(m[o].delete.push(n),e[i]=l):m[o].upload.push(n))),r.operation),"update"===l.operation&&("update"===r.operation&&(r.timel.time&&m[o].upload.push(n)),"delete"===r.operation&&(r.timel.time&&m[o].upload.push(n)))):m[o].upload.push(n):(m[o].update.push(n),e[i]=l)}return{compareResult:m,syncRecords:e}}))}static compareAll(e,a,t,o,i){return m(this,void 0,void 0,(function*(){let n="cloud";if("yes"===t.getReaderConfig("isKeepLocal")){n="local";let e=t.getObjectConfig(yield o.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),a=yield i.getCloudConfig("config"),r=JSON.parse(a.cloudSyncTime||"{}");delete r[yield o.getFingerprint()],Object.values(r).filter((a=>"local"===a.conflictMode&&a.time>e.time)).length>0&&(n="cloud")}let{compareResult:r,syncRecords:l}=yield this.CompareDatabase(e,a,n),{compareResult:s,syncRecords:d}=yield this.CompareConfig(l,a,n),c=Object.assign(Object.assign({},r),s);return t.setAllSyncRecord(d),"local"===n&&(c.books.conflict.length>0||c.notes.conflict.length>0||c.bookmarks.conflict.length>0||c.plugins.conflict.length>0||c.words.conflict.length>0||c.objectConfig.conflict.length>0||c.mapConfig.conflict.length>0)?t.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):t.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),c}))}static startSync(e,a,t,o,i,n){return m(this,void 0,void 0,(function*(){let r=yield this.syncConfig(e,a,t,i,n,o);if(e.books.save.length>0||e.books.upload.length>0){let e=yield this.syncCover(a,n,i),t=yield this.syncBook(a,i);return[...r,...e,...t]}return r}))}static syncConfig(e,a,t,o,i,n){return m(this,void 0,void 0,(function*(){let r=[];for(let a of h){if(e[a].save.length+e[a].update.length>0){let o=yield n.getCloudDatabase(a);for(let i of e[a].save){let e=o.find((e=>e.key===i));e&&(yield t.saveRecord(e,a))}for(let i of e[a].update){let e=o.find((e=>e.key===i));e&&(yield t.updateRecord(e,a,!1))}}if(e[a].delete.length>0)for(let n of e[a].delete)"books"===a&&(yield o.deleteOfflineBook(n),yield i.deleteOfflineCover(n)),yield t.deleteRecord(n,a);yield t.dumpDatabase(a,!0)}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let t=yield n.getCloudConfig("config");for(let o of e.readerConfig.update){let e=o.split(".")[3];t.readerConfig&&a.setReaderConfig(e,JSON.parse(t.readerConfig)[e],!1)}for(let o of e.listConfig.update){let e=o.split(".")[3];t[e]&&a.setAllListConfig(JSON.parse(t[e]),e,!1)}for(let o of e.objectConfig.update){let e=o.split(".")[3],i=o.split(".")[2];t[i]&&JSON.parse(t[i])&&JSON.parse(t[i])[e]&&a.setObjectConfig(e,JSON.parse(t[i])[e],i,!1)}for(let o of e.mapConfig.update){let e=o.split(".")[3],i=o.split(".")[2];if(t[i]&&JSON.parse(t[i])&&JSON.parse(t[i])[e]){let o=JSON.parse(t[i])[e];a.setOneMapConfig(e,o,i,!1)}}}if(e.objectConfig.delete.length>0||e.mapConfig.delete.length>0){for(let t of e.objectConfig.delete){let e=t.split(".")[3],o=t.split(".")[2];a.deleteObjectConfig(e,o)}for(let t of e.mapConfig.delete){let e=t.split(".")[3],o=t.split(".")[2];a.deleteMapConfig(e,o)}}for(let a of h)e[a].upload.length>0&&r.push((()=>n.uploadDatabase(a)));return r.push((()=>n.uploadConfig("config"))),r.push((()=>n.uploadConfig("sync"))),r}))}static syncCover(e,a,t){return m(this,void 0,void 0,(function*(){let t=yield a.getLocalCoverList(),o=yield a.getCloudCoverList(),i=Array.from(new Set([...t,...o])),n=[];for(let r of i)t.includes(r)&&!o.includes(r)&&n.push((()=>a.uploadCover(r))),!t.includes(r)&&o.includes(r)&&"adrive"!==e.getItem("defaultSyncOption")&&n.push((()=>a.downloadCover(r)));return n}))}static syncBook(e,a){return m(this,void 0,void 0,(function*(){let t=yield a.getLocalBookList(),o=yield a.getCloudBookList(),i=[],n=Array.from(new Set([...t,...o]));for(let r of n){if(t.includes(r)&&!o.includes(r)){let e=r.split(".")[0],t=r.split(".")[1];i.push((()=>a.uploadBook(e,t)))}let n="yes"===e.getReaderConfig("autoOffline");if(!t.includes(r)&&o.includes(r)&&n&&"adrive"!==e.getItem("defaultSyncOption")){let e=r.split(".")[0],t=r.split(".")[1]||"epub";i.push((()=>a.offlineBook(e,t.toUpperCase())))}}return i}))}static runTasksWithLimit(e,a,t){return m(this,void 0,void 0,(function*(){if("ftp"!==t&&"adrive"!==t){const t=[],o=[];for(const i of e){const e=i().then((a=>(o.splice(o.indexOf(e),1),a)));t.push(e),o.push(e),o.length>=a&&(yield Promise.race(o))}return Promise.all(t)}for(let a of e)yield a()}))}}class ve{constructor(e,a){this.bookKey="",this.sessionStart=0,this.unregisterUnload=null,this.configService=e,this.platform=a}getDailySeconds(e,a){const t=((this.configService.getAllMapConfig("readingStats")||{})[a]||[]).find((a=>a.startsWith(e+"-")));if(!t)return 0;const o=t.split("-");return parseInt(o[o.length-1],10)||0}setDailySeconds(e,a,t){const o=(this.configService.getAllMapConfig("readingStats")||{})[a]||[],i=`${e}-${t}`,n=o.filter((a=>!a.startsWith(e+"-")));this.configService.setOneMapConfig(a,[...n,i],"readingStats")}start(e){this.bookKey=e,this.sessionStart=Date.now(),this.unregisterUnload=this.platform.registerUnloadHandler((()=>{var e,a;this.commit(),null===(a=(e=this.platform).onBeforeClose)||void 0===a||a.call(e)}))}stop(){var e;this.commit(),null===(e=this.unregisterUnload)||void 0===e||e.call(this),this.unregisterUnload=null,this.bookKey="",this.sessionStart=0}commit(){if(!this.bookKey||!this.sessionStart)return;const e=Date.now()-this.sessionStart;if(e<1e3)return void(this.sessionStart=0);const a=Math.round(e/1e3);this.sessionStart=0;const t=this.configService.getObjectConfig(this.bookKey,"readingTime",0);this.configService.setObjectConfig(this.bookKey,t+a,"readingTime");const o=function(){const e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}(),i=this.getDailySeconds(this.bookKey,o);this.setDailySeconds(this.bookKey,o,i+a)}getTotalSeconds(e){return this.configService.getObjectConfig(e,"readingTime",0)}getDailySecondsForBook(e,a){return this.getDailySeconds(e,a)}getDayStats(e){return((this.configService.getAllMapConfig("readingStats")||{})[e]||[]).map((e=>{const a=e.lastIndexOf("-");return{bookKey:e.substring(0,a),seconds:parseInt(e.substring(a+1),10)||0}}))}getAllDates(){const e=this.configService.getAllMapConfig("readingStats");return Object.keys(e||{})}}const be="Koodo Reader",ke="application/vnd.koreader.v1+json";class Se extends Error{constructor(e,a,t,o){super(e),this.name="KOReaderRequestError",this.status=a,this.code=t,this.body=o}}const Ee=e=>{const a=(e||"").trim();if(!a)return"";return(/^https?:\/\//i.test(a)?a:`https://${a}`).replace(/\/+$/,"")},Ce=e=>{const a="number"==typeof e?e:parseFloat((e||"0")+"");return!isFinite(a)||isNaN(a)?0:a>1&&a<=100?Math.min(Math.max(a/100,0),1):Math.min(Math.max(a,0),1)},Te=(e,a={})=>m(void 0,void 0,void 0,(function*(){const t=yield fetch(e,a);return t.ok||(yield(e=>m(void 0,void 0,void 0,(function*(){let a=null;try{a=yield e.json()}catch(t){try{a=yield e.text()}catch(e){a=null}}const t=(null==a?void 0:a.message)||(null==a?void 0:a.error)||(null==a?void 0:a.msg)||("string"==typeof a?a:"")||e.statusText||"Request failed";throw console.error(`[KOReader] HTTP ${e.status} error: ${t}`,null!=a?a:"(no body)"),new Se(t,e.status,null==a?void 0:a.code,a)})))(t)),204===t.status?{}:yield t.json()})),we=e=>({Accept:ke,"Content-Type":"application/json","x-auth-user":e.username,"x-auth-key":e.passwordHash});class Ae{constructor(e,a,t){this.getKOReaderSyncConfig=()=>{let e;try{e=this.ConfigService.getObjectConfig("koReaderSyncConfig","thirdpartyToken",{})}catch(e){return console.error("[KOReader] Failed to read koReaderSyncConfig:",e),null}if(!e||"object"!=typeof e)return console.error("[KOReader] koReaderSyncConfig is missing or invalid"),null;const a=Ee(e.serverUrl||""),t=(e.username||"").trim(),o=(e.passwordHash||"").trim();return a&&t&&o?{serverUrl:a,username:t,passwordHash:o}:(console.error("[KOReader] Incomplete config — missing fields"),null)},this.getLocalRecordLocation=e=>this.ConfigService.getObjectConfig(e,"recordLocation",{})||{},this.persistKOReaderMetadata=(e,a,t)=>{const o=Object.assign(Object.assign({},a),{percentage:t.percentage.toString(),xpath:t.progress,timestamp:t.timestamp||parseInt(Date.now()/1e3+"")});this.ConfigService.setObjectConfig(e,o,"recordLocation")},this.authUser=e=>m(this,void 0,void 0,(function*(){return yield Te(`${e.serverUrl}/users/auth`,{method:"GET",headers:we(e)})})),this.createUser=e=>m(this,void 0,void 0,(function*(){return yield Te(`${e.serverUrl}/users/create`,{method:"POST",headers:{Accept:ke,"Content-Type":"application/json"},body:JSON.stringify({username:e.username,password:e.passwordHash})})})),this.getBookProgress=(e,a)=>m(this,void 0,void 0,(function*(){const t=yield Te(`${e.serverUrl}/syncs/progress/${encodeURIComponent(a)}`,{method:"GET",headers:we(e)});return t&&0!==Object.keys(t).length?{document:a,percentage:Ce(t.percentage),progress:t.progress||"",device:t.device||"",device_id:t.device_id||"",timestamp:t.timestamp||0}:null})),this.updateBookProgress=(e,a)=>m(this,void 0,void 0,(function*(){yield Te(`${e.serverUrl}/syncs/progress`,{method:"PUT",headers:we(e),body:JSON.stringify({document:a.document,percentage:a.percentage,progress:a.progress,device:a.device||be,device_id:a.device_id||"",timestamp:a.timestamp||parseInt(Date.now()/1e3+"")})})})),this.buildLocalUploadPayload=(e,a,t,o)=>m(this,void 0,void 0,(function*(){const i=Ce(a.percentage),n=a.xpath||"",r=this.ConfigService.getObjectConfig(e.key,"koreaderBooks",{});if(!r.document){let a=yield o(e);if(!a)return console.error(`[KOReader] Cannot build upload payload for "${e.name}": failed to compute partial MD5`),null;r.document=a,this.ConfigService.setObjectConfig(e.key,r,"koreaderBooks")}return n?{document:r.document,percentage:i,progress:n,device:be,device_id:t,timestamp:a.timestamp||parseInt(Date.now()/1e3+"")}:(console.error(`[KOReader] Cannot build upload payload for "${e.name}": no xpath/progress recorded (localRecord.xpath is empty)`),null)})),this.resolveDeviceId=()=>m(this,void 0,void 0,(function*(){try{return(yield this.TokenService.getFingerprint())||"koodo-reader"}catch(e){return console.error("[KOReader] Failed to get device fingerprint, using fallback ID:",e),"koodo-reader"}})),this.verifyAndBuildKOReaderSyncConfig=e=>m(this,void 0,void 0,(function*(){const a={serverUrl:Ee(e.serverUrl),username:(e.username||"").trim(),passwordHash:(e.password||"").trim()?s.MD5((e.password||"").trim()).toString():(e.passwordHash||"").trim()};if(!a.serverUrl||!a.username||!a.passwordHash)throw new Error("Please fill in all fields");try{return yield this.authUser(a),a}catch(e){console.error(`[KOReader] Auth failed for user "${a.username}" at ${a.serverUrl}, attempting to create user:`,e);try{return yield this.createUser(a),yield this.authUser(a),a}catch(o){if((t=o)instanceof Se&&(2002===t.code||(t.message||"").toLowerCase().includes("already exists")))throw console.error(`[KOReader] User "${a.username}" already exists but auth failed. Original auth error:`,e),e;throw console.error(`[KOReader] Failed to create user "${a.username}":`,o),o}}var t})),this.syncKOReaderProgress=e=>m(this,void 0,void 0,(function*(){const a=this.getKOReaderSyncConfig();if(!a)throw new Error("Please configure the KOReader sync server first");yield this.authUser(a);const t=yield this.resolveDeviceId(),o=(yield this.DatabaseService.getAllRecords("books"))||[],i={checkedBooks:0,matchedBooks:0,pulledBooks:0,pushedBooks:0,skippedBooks:0};for(const n of o)try{i.checkedBooks++;const o=this.getLocalRecordLocation(n.key);if(!o||!o.xpath){console.error(`[KOReader] Skipping "${n.name}": no local reading progress (xpath) found`),i.skippedBooks++;continue}const r=this.ConfigService.getObjectConfig(n.key,"koreaderBooks",{});if(!r.document){let a=yield e(n);if(!a){console.error(`[KOReader] Skipping "${n.name}": failed to compute partial MD5 for document ID`),i.skippedBooks++;continue}r.document=a,this.ConfigService.setObjectConfig(n.key,r,"koreaderBooks")}let l=r.document;const s=yield this.getBookProgress(a,l),d=(null==s?void 0:s.timestamp)||0,c=o.timestamp||0;if(s){if(i.matchedBooks++,d>c)this.persistKOReaderMetadata(n.key,o,s),i.pulledBooks++;else{if(!(d{if("number"!=typeof e){const[a,t]=e.split("-");return{styleType:a,color:t}}if(e>=0&&e-1,t=parseInt(xe[e].split("-")[1]);return{styleType:a?"background":"underline",color:a?Ie[t]:Fe[t]}}return{styleType:"background",color:"#FEF3CD"}},this.formatHighlightValue=e=>`${e.styleType}-${e.color}`,this.getNoteHighlightString=()=>this.ConfigService.getReaderConfig(Me)||"background-#FEF3CD",this.getNoteHighlightValue=()=>{const e=this.getNoteHighlightString();if(!e)return Ue;const[a,t]=e.split("-");return{styleType:a,color:t}},this.saveNoteHighlightValue=e=>{this.ConfigService.setReaderConfig(Me,`${e.styleType}-${e.color}`)},this.getTtsHighlightString=()=>this.ConfigService.getReaderConfig(_e)||Re,this.getTtsHighlightValue=()=>{const e=this.getTtsHighlightString();if(!e)return Oe;const[a,t]=e.split("-");return{styleType:a,color:t}},this.saveTtsHighlightValue=e=>{this.ConfigService.setReaderConfig(_e,`${e.styleType}-${e.color}`)},this.getSearchHighlightString=()=>this.ConfigService.getReaderConfig($e)||Re,this.getSearchHighlightValue=()=>{const e=this.ConfigService.getReaderConfig($e);if(!e)return Oe;const[a,t]=e.split("-");return{styleType:a,color:t}},this.saveSearchHighlightValue=e=>{this.ConfigService.setReaderConfig($e,`${e.styleType}-${e.color}`)},this.buildHighlightStyleForType=(e,a,t)=>{let o="background",i="#FEF3CD";if("number"==typeof e){if(e>=0&&e-1,t=parseInt(xe[e].split("-")[1]);o=a?"background":"underline",i=a?Ie[t]:Fe[t]}}else o=e.split("-")[0],i=e.split("-")[1];const n="background"===o?((e,a)=>{const t=e.replace("#",""),o=3===t.length?t.split("").map((e=>e+e)).join(""):t;return 6!==o.length?e:`rgba(${parseInt(o.slice(0,2),16)}, ${parseInt(o.slice(2,4),16)}, ${parseInt(o.slice(4,6),16)}, ${a})`})(i,.8):i;switch(o){case"background":return a?`background: ${n}; mix-blend-mode: multiply;`:`background: ${n};`;case"underline":return a?t?`border-right: 2px solid ${n};`:`border-bottom: 2px solid ${n};`:`text-decoration: underline; text-decoration-color: ${n}; text-decoration-thickness: 2px; text-decoration-skip-ink: none;`;case"strikethrough":return a?`background: linear-gradient(transparent calc(50% - 1px), ${n} calc(50% - 1px), ${n} calc(50% + 1px), transparent calc(50% + 1px));`:t?`background: linear-gradient(to right, transparent calc(50% - 1px), ${n} calc(50% - 1px), ${n} calc(50% + 1px), transparent calc(50% + 1px));`:`text-decoration: line-through; text-decoration-color: ${n}; text-decoration-thickness: 2px; text-decoration-skip-ink: none;`;case"wavy":const e=i.replace("#","%23");if(a){return`background-image: ${`url("data:image/svg+xml,%3Csvg xmlns='http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width='6' height='3'%3E%3Cpath d='M0 2 Q1.5 0 3 2 Q4.5 4 6 2' fill='none' stroke='${e}' stroke-width='1.5'%2F%3E%3C%2Fsvg%3E")`}; background-repeat: repeat-x; background-position: bottom; background-size: 6px 3px;`}if(t){return`background-image: ${`url("data:image/svg+xml,%3Csvg xmlns='http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width='3' height='6'%3E%3Cpath d='M2 0 Q0 1.5 2 3 Q4 4.5 2 6' fill='none' stroke='${e}' stroke-width='1.5'%2F%3E%3C%2Fsvg%3E")`}; background-repeat: repeat-y; background-position: right; background-size: 3px 6px;`}return`text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: ${n}; text-decoration-thickness: 2px; text-decoration-skip-ink: none;`;default:return`background: ${n};`}},this.buildHighlightPreviewStyle=(e,a)=>{switch(e){case"background":default:return{background:a};case"underline":return{textDecoration:"underline",textDecorationColor:a,textDecorationThickness:"2px",textDecorationSkipInk:"none"};case"strikethrough":return{textDecoration:"line-through",textDecorationColor:a,textDecorationThickness:"2px",textDecorationSkipInk:"none"};case"wavy":return{textDecorationLine:"underline",textDecorationStyle:"wavy",textDecorationColor:a,textDecorationThickness:"2px",textDecorationSkipInk:"none"}}},this.convertNumberToHighlightValue=e=>this.getHighlightValue(e),this.buildTtsHighlightStyle=(e,a)=>this.buildHighlightStyleForType(this.getTtsHighlightString(),e,a),this.buildTtsHighlightPreviewStyle=(e,a)=>this.buildHighlightPreviewStyle(e,a),this.buildSearchHighlightStyle=(e,a)=>this.buildHighlightStyleForType(this.getSearchHighlightString(),e,a),this.buildSearchHighlightPreviewStyle=(e,a)=>this.buildHighlightPreviewStyle(e,a),this.ConfigService=e}}const ze=(De=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,a){localStorage.setItem(e,a)}static removeItem(e){localStorage.removeItem(e)}},Le="browser",class extends De{static getReaderConfig(e){return w.includes(e)&&"undefined"!=typeof window&&window.currentBookKey&&this.getAllListConfig("seperateStyleBooks").includes(window.currentBookKey)?this.getObjectConfig(window.currentBookKey,"seperateStyleConfig",{})[e]:JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,a,t=!0){if(w.includes(e)&&"undefined"!=typeof window&&window.currentBookKey&&this.getAllListConfig("seperateStyleBooks").includes(window.currentBookKey)){let o=this.getObjectConfig(window.currentBookKey,"seperateStyleConfig",{});return o[e]=a,void this.setObjectConfig(window.currentBookKey,o,"seperateStyleConfig",t)}let o=JSON.parse(this.getItem("readerConfig")||"{}");o[e]=a,this.setItem("readerConfig",JSON.stringify(o)),t&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:Le,key:e},{operation:"update",time:Date.now()})}static getAllListConfig(e){return("{}"!==this.getItem(e)&&this.getItem(e)?JSON.parse(this.getItem(e)||""):[])||[]}static deleteListConfig(e,a){let t=this.getAllListConfig(a);const o=t.indexOf(e);o>-1&&t.splice(o,1),this.setAllListConfig(t,a)}static setListConfig(e,a){let t=this.getAllListConfig(a);const o=t.indexOf(e);o>-1?(t.splice(o,1),t.unshift(e)):t.unshift(e),this.setAllListConfig(t,a)}static setAllListConfig(e,a,t=!0){this.setItem(a,JSON.stringify(e)),t&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:a},{operation:"update",time:Date.now()})}static setObjectConfig(e,a,t,o=!0){let i=this.getAllObjectConfig(t);i[e]=a,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(i,t)}static getObjectConfig(e,a,t){return this.getAllObjectConfig(a)[e]||t}static getAllObjectConfig(e){let a=this.getItem(e);return JSON.parse(a)||{}}static setAllObjectConfig(e,a){this.setItem(a,JSON.stringify(e))}static deleteObjectConfig(e,a){let t=this.getAllObjectConfig(a);delete t[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:a,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(t,a)}static getAllMapConfig(e){let a=this.getItem(e);return JSON.parse(a)||{}}static getMapConfig(e,a){return this.getAllMapConfig(a)[e]||[]}static setAllMapConfig(e,a){this.setItem(a,JSON.stringify(e))}static setMapConfig(e,a,t){let o=this.getAllMapConfig(t);void 0===o[e]&&(o[e]=[]),a&&-1===o[e].indexOf(a)&&o[e].unshift(a),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,t)}static setOneMapConfig(e,a,t,o=!0){let i=this.getAllMapConfig(t);i[e]=a,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,t)}static deleteFromMapConfig(e,a,t){let o=this.getAllMapConfig(t),i=o[e].indexOf(a);o[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,t)}static deleteFromAllMapConfig(e,a){let t=this.getAllMapConfig(a);Object.keys(t).forEach((o=>{let i=t[o].indexOf(e);i>-1&&(t[o].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:a,key:o},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(t,a)}static deleteMapConfig(e,a){let t=this.getAllMapConfig(a);delete t[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:a,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(t,a)}static getFromAllMapConfig(e,a){let t=this.getAllMapConfig(a),o=[];for(let a in t)t[a]&&t[a].indexOf(e)>-1&&o.push(a);return o}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,a){const t=e.type+"."+e.catergory+"."+e.name+"."+e.key;let o=JSON.parse(this.getItem("syncRecord")||"{}");o[t]=a,this.setItem("syncRecord",JSON.stringify(o))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var De,Le;class Pe{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("notionSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Notion] notionSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Notion] Failed to read notionSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableNotionSync")}resolveDatabaseId(e,a){return m(this,void 0,void 0,(function*(){const t=yield fetch(`https://api.notion.com/v1/blocks/${a}/children`,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Notion-Version":"2022-06-28"}});if(!t.ok){const e=yield t.json().catch((()=>null));throw console.error(`[Notion] resolveDatabaseId failed for page ${a}: HTTP ${t.status} ${t.statusText}`,JSON.stringify(e)),new Error(`Notion resolve database error: ${t.status} ${t.statusText}`)}const o=yield t.json(),i=(o.results||[]).find((e=>"child_database"===e.type));if(!i)throw console.error(`[Notion] No child_database block found under page ${a}. Available block types:`,JSON.stringify((o.results||[]).map((e=>e.type)))),new Error(`No child database found in page ${a}. Please provide a Database ID directly.`);return i.id}))}findOrCreatePage(e,a,t){return m(this,void 0,void 0,(function*(){const o=`${t}`,i=yield fetch(`https://api.notion.com/v1/databases/${a}/query`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({filter:{property:"title",title:{equals:o}}})});if(!i.ok){const o=yield i.json().catch((()=>({})));if(400===i.status&&"validation_error"===(null==o?void 0:o.code)&&"string"==typeof(null==o?void 0:o.message)&&o.message.includes("is a page, not a database")){console.error(`[Notion] Provided databaseId "${a}" is a page, not a database. Resolving child database...`);const o=yield this.resolveDatabaseId(e,a);return this.findOrCreatePage(e,o,t)}throw console.error(`[Notion] Database query failed for databaseId "${a}" (book: "${t}"): HTTP ${i.status} ${i.statusText}`,JSON.stringify(o)),new Error(`Notion API error: ${i.status} ${i.statusText}`)}const n=yield i.json();if(n.results&&n.results.length>0)return n.results[0].id;const r=yield fetch("https://api.notion.com/v1/pages",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({parent:{database_id:a},properties:{title:{title:[{text:{content:o}}]}}})});if(!r.ok){const e=yield r.json().catch((()=>null));throw console.error(`[Notion] Failed to create page for book "${t}" in database "${a}": HTTP ${r.status} ${r.statusText}`,JSON.stringify(e)),new Error(`Notion create page error: ${r.status} ${r.statusText}`)}return(yield r.json()).id}))}appendBlocks(e,a,t,o){return m(this,void 0,void 0,(function*(){const i=!t.notes||0===t.notes.length,n=[];n.push({object:"block",type:"divider",divider:{}}),o&&n.push({object:"block",type:"heading_3",heading_3:{rich_text:[{type:"text",text:{content:o}}]}}),n.push({object:"block",type:"quote",quote:{rich_text:[{type:"text",text:{content:t.text||""}}]}}),!i&&t.notes&&n.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`📝 ${t.notes}`}}]}});const r=`${t.date.year}-${String(t.date.month).padStart(2,"0")}-${String(t.date.day).padStart(2,"0")}`;n.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`Added on ${r}`},annotations:{italic:!0,color:"gray"}}]}});const l=yield fetch(`https://api.notion.com/v1/blocks/${a}/children`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({children:n})});if(!l.ok){const e=yield l.json().catch((()=>null));throw console.error(`[Notion] Failed to append blocks to page ${a}: HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),new Error(`Notion append blocks error: ${l.status} ${l.statusText}`)}}))}syncNote(e,a){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const t=this.getConfig();if(!t)return!1;try{const o=yield this.findOrCreatePage(t.token,t.databaseId,a);return yield this.appendBlocks(t.token,o,e,e.chapter||""),!0}catch(e){return console.error(`[Notion] Sync failed for book "${a}":`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}class je{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("yuqueSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Yuque] yuqueSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Yuque] Failed to read yuqueSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableYuqueSync")}generateDocSlug(e){return m(this,void 0,void 0,(function*(){const a=(e||"").trim()||"untitled",t=a.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").replace(/[-_.]{2,}/g,"-").replace(/^[-_.]+|[-_.]+$/g,"")||"book",o=(yield y(a)).slice(0,16),i=t,n=190-o.length-1;return`${i.substring(0,n).replace(/^[-_.]+|[-_.]+$/g,"")||"book"}-${o}`}))}findOrCreateDoc(e,a,t){return m(this,void 0,void 0,(function*(){const o=`${t}`,i=yield this.generateDocSlug(t);try{const t=yield fetch(`${je.API_BASE}/repos/${a}/docs/${i}`,{method:"GET",headers:{"X-Auth-Token":e,"Content-Type":"application/json"}});if(t.ok){const e=yield t.json();return{id:e.data.id,slug:e.data.slug,body:e.data.body||""}}if(404!==t.status){const e=yield t.json().catch((()=>null));console.error(`[Yuque] Unexpected error fetching doc "${i}" in repo "${a}": HTTP ${t.status} ${t.statusText}`,JSON.stringify(e))}}catch(e){console.error(`[Yuque] Network error fetching doc "${i}" in repo "${a}":`,JSON.stringify(e))}const n=yield fetch(`${je.API_BASE}/repos/${a}/docs`,{method:"POST",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({title:o,slug:i,body:`# ${o}\n\n`,format:"markdown"})});if(!n.ok){const e=yield n.json().catch((()=>null));throw console.error(`[Yuque] Failed to create doc "${o}" in repo "${a}": HTTP ${n.status} ${n.statusText}`,JSON.stringify(e)),new Error(`Yuque create doc error: ${n.status} ${n.statusText}`)}const r=yield n.json();return{id:r.data.id,slug:r.data.slug,body:r.data.body||""}}))}formatNoteMarkdown(e){const a=!e.notes||0===e.notes.length,t=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let o="\n---\n\n";return e.chapter&&(o+=`### ${e.chapter}\n\n`),o+=`> ${e.text||""}\n\n`,!a&&e.notes&&(o+=`📝 ${e.notes}\n\n`),o+=`*Added on ${t}*\n\n`,o}updateDoc(e,a,t,o){return m(this,void 0,void 0,(function*(){const i=yield fetch(`${je.API_BASE}/repos/${a}/docs/${t}`,{method:"PUT",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({body:o,format:"markdown"})});if(!i.ok){const e=yield i.json().catch((()=>null));throw console.error(`[Yuque] Failed to update doc ${t} in repo "${a}": HTTP ${i.status} ${i.statusText}`,JSON.stringify(e)),new Error(`Yuque update doc error: ${i.status} ${i.statusText}`)}}))}syncNote(e,a){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const t=this.getConfig();if(!t)return!1;try{const o=yield this.findOrCreateDoc(t.token,t.namespace,a),i=this.formatNoteMarkdown(e),n=o.body+i;return yield this.updateDoc(t.token,t.namespace,o.id,n),!0}catch(e){return console.error(`[Yuque] Sync failed for book "${a}":`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}je.API_BASE="https://www.yuque.com/api/v2";class Ke{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("readwiseSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Readwise] readwiseSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Readwise] Failed to read readwiseSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableReadwiseSync")}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const i=`${a}`,n=!e.notes||0===e.notes.length,r={text:e.text||"",title:i,author:t||"Unknown",source_type:"koodo-reader",category:"books",highlighted_at:`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`};if(!n&&e.notes&&(r.note=e.notes),e.chapter){const a=parseInt(e.chapter,10);isNaN(a)||(r.location_type="order",r.location=a)}try{const e=yield fetch(`${Ke.API_BASE}/highlights/`,{method:"POST",headers:{Authorization:`Token ${o.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({highlights:[r]})});if(!e.ok){const a=yield e.json().catch((()=>null));throw console.error(`[Readwise] Failed to sync highlight for book "${i}": HTTP ${e.status} ${e.statusText}`,JSON.stringify(a)),new Error(`Readwise API error: ${e.status} ${e.statusText}`)}return!0}catch(a){return console.error(`[Readwise] Sync failed for book "${i}" (text: "${(e.text||"").substring(0,50)}..."):`,JSON.stringify(a instanceof Error?a.message:a)),!1}}))}}Ke.API_BASE="https://readwise.io/api/v2";class He{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("imaSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[IMA] imaSyncConfig is empty or not set"),null):e}catch(e){return console.error("[IMA] Failed to read imaSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableImaSync")}getHeaders(e){return{"Content-Type":"application/json","ima-openapi-clientid":e.clientId,"ima-openapi-apikey":e.apiKey}}formatNoteMarkdown(e,a,t){const o=!e.notes||0===e.notes.length,i=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let n="\n---\n\n";return e.chapter&&(n+=`### ${e.chapter}\n\n`),n+=`> ${e.text||""}\n\n`,!o&&e.notes&&(n+=`**Note:** ${e.notes}\n\n`),n+=`*${i}*\n`,n}findNoteByTitle(e,a){var t,o,i,n;return m(this,void 0,void 0,(function*(){try{const r=JSON.stringify({search_type:0,query_info:{title:a},start:0,end:20}),l=yield fetch(`${He.API_BASE}/search_note`,{method:"POST",headers:this.getHeaders(e),body:r});if(!l.ok){const e=yield l.json().catch((()=>null));return console.error(`[IMA] search_note failed for title "${a}": HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),null}const s=yield l.json();if(0!==s.code)return console.error(`[IMA] search_note returned error code ${s.code} for title "${a}":`,JSON.stringify(null!==(t=s.msg)&&void 0!==t?t:s)),null;const d=((null===(o=s.data)||void 0===o?void 0:o.search_note_infos)||[]).find((e=>{var t;return a.includes(null===(t=e.note_book_info)||void 0===t?void 0:t.title.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,""))}));return null!==(n=null===(i=null==d?void 0:d.note_book_info)||void 0===i?void 0:i.note_id)&&void 0!==n?n:null}catch(e){return console.error(`[IMA] Network error in search_note for title "${a}":`,JSON.stringify(e)),null}}))}createNote(e,a,t){var o,i,n;return m(this,void 0,void 0,(function*(){try{const r={content_format:1,content:`# ${a}\n\n${t}`};e.folderId&&(r.folder_id=e.folderId);const l=yield fetch(`${He.API_BASE}/import_doc`,{method:"POST",headers:this.getHeaders(e),body:JSON.stringify(r)});if(!l.ok){const e=yield l.json().catch((()=>null));return console.error(`[IMA] import_doc failed for note "${a}": HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),null}const s=yield l.json();return 0!==s.code?(console.error(`[IMA] import_doc returned error code ${s.code} for note "${a}":`,JSON.stringify(null!==(o=s.msg)&&void 0!==o?o:s)),null):null!==(n=null===(i=s.data)||void 0===i?void 0:i.note_id)&&void 0!==n?n:null}catch(e){return console.error(`[IMA] Network error in import_doc for note "${a}":`,JSON.stringify(e)),null}}))}appendNote(e,a,t){var o;return m(this,void 0,void 0,(function*(){try{const i=yield fetch(`${He.API_BASE}/append_doc`,{method:"POST",headers:this.getHeaders(e),body:JSON.stringify({note_id:a,content_format:1,content:t})});if(!i.ok){const e=yield i.json().catch((()=>null));return console.error(`[IMA] append_doc failed for noteId "${a}": HTTP ${i.status} ${i.statusText}`,JSON.stringify(e)),!1}const n=yield i.json();return 0===n.code||(console.error(`[IMA] append_doc returned error code ${n.code} for noteId "${a}":`,JSON.stringify(null!==(o=n.msg)&&void 0!==o?o:n)),!1)}catch(e){return console.error(`[IMA] Network error in append_doc for noteId "${a}":`,JSON.stringify(e)),!1}}))}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const i=this.formatNoteMarkdown(e,a,t);let n=yield this.findNoteByTitle(o,a);if(n){const e=yield this.appendNote(o,n,i);return e||console.error(`[IMA] Failed to append to existing note "${a}" (noteId: ${n})`),e}return n=yield this.createNote(o,a,i),n||console.error(`[IMA] Failed to create note for book "${a}"`),null!==n}))}}He.API_BASE="https://ima.qq.com/openapi/note/v1";class Je{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("siyuanSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[SiYuan] siyuanSyncConfig is empty or not set"),null):e}catch(e){return console.error("[SiYuan] Failed to read siyuanSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableSiYuanSync")}getHeaders(e){return{"Content-Type":"application/json",Authorization:`Token ${e}`}}findOrCreateNotebook(e,a){var t,o;return m(this,void 0,void 0,(function*(){const i=yield fetch(`${e}/api/notebook/lsNotebooks`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({})});if(!i.ok){const a=yield i.json().catch((()=>null));throw console.error(`[SiYuan] lsNotebooks failed at ${e}: HTTP ${i.status} ${i.statusText}`,JSON.stringify(a)),new Error(`SiYuan list notebooks failed: ${i.status} ${i.statusText}`)}const n=yield i.json();if(0!==n.code)throw console.error(`[SiYuan] lsNotebooks returned error code ${n.code}:`,JSON.stringify(n.msg)),new Error(`SiYuan list notebooks error: ${n.msg}`);const r=(null!==(o=null===(t=n.data)||void 0===t?void 0:t.notebooks)&&void 0!==o?o:[]).find((e=>"Koodo Reader"===e.name));if(r)return r.id;const l=yield fetch(`${e}/api/notebook/createNotebook`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({name:"Koodo Reader"})});if(!l.ok){const a=yield l.json().catch((()=>null));throw console.error(`[SiYuan] createNotebook failed at ${e}: HTTP ${l.status} ${l.statusText}`,JSON.stringify(a)),new Error(`SiYuan create notebook failed: ${l.status} ${l.statusText}`)}const s=yield l.json();if(0!==s.code)throw console.error(`[SiYuan] createNotebook returned error code ${s.code}:`,JSON.stringify(s.msg)),new Error(`SiYuan create notebook error: ${s.msg}`);return s.data.notebook.id}))}findOrCreateDoc(e,a,t,o,i,n){return m(this,void 0,void 0,(function*(){const i=yield fetch(`${e}/api/query/sql`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({stmt:`SELECT id FROM blocks WHERE type='d' AND hpath='${o.replace(/'/g,"''")}' LIMIT 1`})});if(i.ok){const e=yield i.json();if(0!==e.code)console.error(`[SiYuan] SQL query for doc "${o}" returned error code ${e.code}:`,JSON.stringify(e.msg));else if(e.data&&e.data.length>0)return e.data[0].id}else{const e=yield i.json().catch((()=>null));console.error(`[SiYuan] SQL query for doc "${o}" failed: HTTP ${i.status} ${i.statusText}`,JSON.stringify(e))}const r=n?`**Author:** ${n}\n`:"",l=yield fetch(`${e}/api/filetree/createDocWithMd`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({notebook:t,path:o,markdown:r})});if(!l.ok){const e=yield l.json().catch((()=>null));throw console.error(`[SiYuan] createDocWithMd failed for "${o}" in notebook "${t}": HTTP ${l.status} ${l.statusText}`,JSON.stringify(e)),new Error(`SiYuan create doc failed: ${l.status} ${l.statusText}`)}const s=yield l.json();if(0!==s.code)throw console.error(`[SiYuan] createDocWithMd returned error code ${s.code} for "${o}":`,JSON.stringify(s.msg)),new Error(`SiYuan create doc error: ${s.msg}`);return s.data}))}appendMarkdownToDoc(e,a,t,o){return m(this,void 0,void 0,(function*(){const i=yield fetch(`${e}/api/block/appendBlock`,{method:"POST",headers:this.getHeaders(a),body:JSON.stringify({data:o,dataType:"markdown",parentID:t})});if(!i.ok){const e=yield i.json().catch((()=>null));throw console.error(`[SiYuan] appendBlock failed for docId "${t}": HTTP ${i.status} ${i.statusText}`,JSON.stringify(e)),new Error(`SiYuan append block failed: ${i.status} ${i.statusText}`)}const n=yield i.json();if(0!==n.code)throw console.error(`[SiYuan] appendBlock returned error code ${n.code} for docId "${t}":`,JSON.stringify(n.msg)),new Error(`SiYuan append block error: ${n.msg}`)}))}formatNoteMarkdown(e){const a=!e.notes||0===e.notes.length,t=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let o="---\n\n";return e.chapter&&(o+=`### ${e.chapter}\n\n`),o+=`> ${e.text||""}\n\n`,!a&&e.notes&&(o+=`📝 ${e.notes}\n\n`),o+=`*Added on ${t}*\n\n`,o}sanitizePathComponent(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const{serverUrl:i,token:n}=o;if(!i||!n)return console.error("[SiYuan] Sync skipped: config is missing serverUrl or token",JSON.stringify({hasServerUrl:!!i,hasToken:!!n})),!1;try{const o=yield this.findOrCreateNotebook(i,n),r=`/${this.sanitizePathComponent(a)}`,l=yield this.findOrCreateDoc(i,n,o,r,a,t),s=this.formatNoteMarkdown(e);return yield this.appendMarkdownToDoc(i,n,l,s),!0}catch(e){return console.error(`[SiYuan] Sync failed for book "${a}" at ${o.serverUrl}:`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}class We{constructor(e,a){this.databaseService=e,this.notionSync=new Pe(a),this.yuqueSync=new je(a),this.readwiseSync=new Ke(a),this.imaSync=new He(a),this.siyuanSync=new Je(a)}getExtraServices(){return[]}getEnabledServices(){const e=[];return this.notionSync.isEnabled()&&e.push({name:"Notion",sync:this.notionSync.syncNote.bind(this.notionSync)}),this.yuqueSync.isEnabled()&&e.push({name:"Yuque",sync:this.yuqueSync.syncNote.bind(this.yuqueSync)}),this.readwiseSync.isEnabled()&&e.push({name:"Readwise",sync:this.readwiseSync.syncNote.bind(this.readwiseSync)}),this.imaSync.isEnabled()&&e.push({name:"IMA",sync:this.imaSync.syncNote.bind(this.imaSync)}),this.siyuanSync.isEnabled()&&e.push({name:"SiYuan",sync:this.siyuanSync.syncNote.bind(this.siyuanSync)}),[...e,...this.getExtraServices()]}syncNote(e,a){return m(this,void 0,void 0,(function*(){const t=this.getEnabledServices();if(0===t.length)return;let o="Unknown Book",i="";if(a||e.bookKey)try{const t=yield this.databaseService.getRecord(a||e.bookKey,"books");t&&t.name&&(o=t.name),t&&t.author&&(i=t.author)}catch(t){console.error(`[NoteSync] Failed to resolve book info for key: ${a||e.bookKey}`,JSON.stringify(t))}const n=(yield Promise.allSettled(t.map((a=>m(this,void 0,void 0,(function*(){var t,n,r,l;try{const r=yield a.sync(e,o,i);return r||console.error(`[NoteSync] ${a.name} sync returned false for book "${o}" (noteId: ${null!==(n=null!==(t=e.noteKey)&&void 0!==t?t:e.key)&&void 0!==n?n:"unknown"})`),{name:a.name,success:r}}catch(t){return console.error(`[NoteSync] ${a.name} sync threw an error for book "${o}" (noteId: ${null!==(l=null!==(r=e.noteKey)&&void 0!==r?r:e.key)&&void 0!==l?l:"unknown"}):`,JSON.stringify(t)),{name:a.name,success:!1}}})))))).filter((e=>"rejected"===e.status||"fulfilled"===e.status&&!e.value.success)).map((e=>"fulfilled"===e.status?e.value.name:"Unknown"));n.length>0&&console.error(`[NoteSync] Sync failed for services: ${n.join(", ")} | book: "${o}"`)}))}}class qe{constructor(e,a,t){this.configService=e,this.fs=a,this.path=t}getConfig(){try{const e=this.configService.getObjectConfig("markdownSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?(console.error("[Markdown] markdownSyncConfig is empty or not set"),null):e}catch(e){return console.error("[Markdown] Failed to read markdownSyncConfig:",JSON.stringify(e)),null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableMarkdownSync")}formatNoteMarkdown(e){const a=!e.notes||0===e.notes.length,t=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let o="\n---\n\n";return e.chapter&&(o+=`### ${e.chapter}\n\n`),o+=`> ${e.text||""}\n\n`,!a&&e.notes&&(o+=`📝 ${e.notes}\n\n`),o+=`*Added on ${t}*\n\n`,o}sanitizeFileName(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()}syncNote(e,a,t){return m(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const o=this.getConfig();if(!o)return!1;const i=o.folder;if(!i)return console.error("[Markdown] Sync skipped: markdownSyncConfig.folder is not set"),!1;const n=this.fs,r=this.path;try{const o=this.sanitizeFileName(a),l=r.join(i,`${o}.md`);if(!n.existsSync(l)){const e=`# ${a}\n`,o=t?`**Author:** ${t}\n\n`:"\n";try{n.writeFileSync(l,e+o,"utf-8")}catch(e){return console.error(`[Markdown] Failed to create file "${l}" for book "${a}":`,JSON.stringify(e)),!1}}const s=this.formatNoteMarkdown(e);try{n.appendFileSync(l,s,"utf-8")}catch(e){return console.error(`[Markdown] Failed to append to file "${l}" for book "${a}":`,JSON.stringify(e)),!1}return!0}catch(e){return console.error(`[Markdown] Sync failed for book "${a}" in folder "${i}":`,JSON.stringify(e instanceof Error?e.message:e)),!1}}))}}class Ge extends We{constructor(e,a,t,o){super(e,a),this.markdownSync=new qe(a,t,o)}getExtraServices(){return this.markdownSync.isEnabled()?[{name:"Markdown",sync:this.markdownSync.syncNote.bind(this.markdownSync)}]:[]}}class Qe{constructor(a){this.syncWordToEudic=(a,t)=>m(this,void 0,void 0,(function*(){var o,i,n,r,l,s,d,c,u,m;if("yes"===this.configService.getReaderConfig("isEnableEudicSync"))try{let c;try{c=this.configService.getObjectConfig("eudicSyncConfig","thirdpartyToken",{})}catch(e){return void console.error("[Eudic] Failed to read eudicSyncConfig:",JSON.stringify(e))}if(!c||!c.accessToken)return void console.error("[Eudic] Sync skipped: config is missing or accessToken is not set",JSON.stringify({hasConfig:!!c}));const u=c.language||"en",m={Authorization:`NIS ${c.accessToken}`,"Content-Type":"application/json","User-Agent":"Mozilla/5.0"};let p="0";const h=(c.categoryName||"").trim();if(h)if(void 0!==c.categoryId)p=c.categoryId;else try{const a=(null===(o=(yield e.get(`https://api.frdic.com/api/open/v1/studylist/category?language=${u}`,{headers:m})).data)||void 0===o?void 0:o.data)||[],t=a.find((e=>e.name===h));t?p=t.id:console.error(`[Eudic] Category "${h}" not found among available categories:`,JSON.stringify(a.map((e=>e.name))));const i=Object.assign(Object.assign({},c),{categoryId:p});this.configService.setObjectConfig("eudicSyncConfig",i,"thirdpartyToken")}catch(e){console.error("[Eudic] Failed to fetch category list:",null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.status,JSON.stringify(null!==(r=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.data)&&void 0!==r?r:e))}try{yield e.post("https://api.frdic.com/api/open/v1/studylist/word",{language:u,word:a,context_line:t||"",category_ids:[p]},{headers:m})}catch(e){throw console.error(`[Eudic] Failed to add word "${a}" to study list (category: ${p}):`,null===(l=null==e?void 0:e.response)||void 0===l?void 0:l.status,JSON.stringify(null!==(d=null===(s=null==e?void 0:e.response)||void 0===s?void 0:s.data)&&void 0!==d?d:e)),e}}catch(e){console.error("[Eudic] Sync error for word:",a,null===(c=null==e?void 0:e.response)||void 0===c?void 0:c.status,JSON.stringify(null!==(m=null===(u=null==e?void 0:e.response)||void 0===u?void 0:u.data)&&void 0!==m?m:e))}})),this.syncWordToAnki=(a,t,o,i,n="")=>m(this,void 0,void 0,(function*(){var r,l,s,d,c,u,m,p,h,g;if("yes"===this.configService.getReaderConfig("isEnableAnkiSync"))try{let h;try{h=this.configService.getObjectConfig("ankiSyncConfig","thirdpartyToken",{})}catch(e){return void console.error("[Anki] Failed to read ankiSyncConfig:",JSON.stringify(e))}if(!h||!h.deckName)return void console.error("[Anki] Sync skipped: config is missing or deckName is not set",JSON.stringify({hasConfig:!!h}));const g=h.host||"127.0.0.1",f=`http://${g}:${h.port||"8765"}`,y=h.deckName,N="Koodo Reader Word",v=(a,t={})=>{const o={action:a,version:6,params:t};return h.apiKey&&(o.key=h.apiKey),e.post(f,o)};if(!h.modelName)try{const e=yield v("modelNames");if(!((null===(r=e.data)||void 0===r?void 0:r.result)||[]).includes(N))try{yield v("createModel",{modelName:N,inOrderFields:["Word","Sentence","Book","Chapter","Definition"],cardTemplates:[{Name:"Card 1",Front:"{{Word}}

{{Sentence}}

{{Book}}
{{Chapter}}",Back:"{{Definition}}"}]})}catch(e){throw console.error(`[Anki] Failed to create model "${N}":`,JSON.stringify(null!==(s=null===(l=null==e?void 0:e.response)||void 0===l?void 0:l.data)&&void 0!==s?s:e)),e}this.configService.setObjectConfig("ankiSyncConfig",Object.assign(Object.assign({},h),{modelName:N}),"thirdpartyToken")}catch(e){throw console.error(`[Anki] Failed to fetch model names from ${f}:`,JSON.stringify(null!==(c=null===(d=null==e?void 0:e.response)||void 0===d?void 0:d.data)&&void 0!==c?c:e)),e}try{const e=yield v("addNote",{note:{deckName:y,modelName:N,fields:{Word:a,Sentence:t||"",Book:o||"",Chapter:i||"",Definition:n||""},options:{allowDuplicate:!1},tags:[]}});(null===(u=e.data)||void 0===u?void 0:u.error)&&console.error(`[Anki] addNote returned an error for word "${a}" in deck "${y}":`,JSON.stringify(e.data.error))}catch(e){throw console.error(`[Anki] Failed to add note for word "${a}" to deck "${y}" at ${f}:`,JSON.stringify(null!==(p=null===(m=null==e?void 0:e.response)||void 0===m?void 0:m.data)&&void 0!==p?p:e)),e}}catch(e){console.error("[Anki] Sync error for word:",a,JSON.stringify(null!==(g=null===(h=null==e?void 0:e.response)||void 0===h?void 0:h.data)&&void 0!==g?g:e))}})),this.syncWordToMaiMemo=a=>m(this,void 0,void 0,(function*(){var t,o,i,n,r,l,s,d,c,u,m,p,h,g,f,y,N,v,b,k;if("yes"===this.configService.getReaderConfig("isEnableMaiMemoSync"))try{let v;try{v=this.configService.getObjectConfig("maimemoSyncConfig","thirdpartyToken",{})}catch(e){return void console.error("[MaiMemo] Failed to read maimemoSyncConfig:",JSON.stringify(e))}if(!v||!v.accessToken||!v.notepadName)return void console.error("[MaiMemo] Sync skipped: config is missing accessToken or notepadName",JSON.stringify({hasConfig:!!v}));const b=v.accessToken,k=v.notepadName.trim(),S={Authorization:`Bearer ${b}`,"Content-Type":"application/json",Accept:"application/json"};let E=v.notepadId||"";if(!E)try{const l=yield e.get("https://open.maimemo.com/open/api/v1/memo/notepads",{headers:S}),s=((null===(o=null===(t=l.data)||void 0===t?void 0:t.data)||void 0===o?void 0:o.notepads)||[]).find((e=>"PUBLISHED"===e.status&&e.title===k));if(s)E=s.id;else{if(E=null===(r=null===(n=null===(i=(yield e.post("https://open.maimemo.com/open/api/v1/memo/notepads",{notepad:{status:"PUBLISHED",content:a,title:k,brief:k,tags:[]}},{headers:S})).data)||void 0===i?void 0:i.data)||void 0===n?void 0:n.notepad)||void 0===r?void 0:r.id,!E)return void console.error("[MaiMemo] Created notepad but no id returned")}this.configService.setObjectConfig("maimemoSyncConfig",Object.assign(Object.assign({},v),{notepadId:E}),"thirdpartyToken")}catch(e){return void console.error("[MaiMemo] Failed to resolve notepadId:",null===(l=null==e?void 0:e.response)||void 0===l?void 0:l.status,JSON.stringify(null!==(d=null===(s=null==e?void 0:e.response)||void 0===s?void 0:s.data)&&void 0!==d?d:e))}try{let t="";try{t=(null===(m=null===(u=null===(c=(yield e.get(`https://open.maimemo.com/open/api/v1/memo/notepads/${E}`,{headers:S})).data)||void 0===c?void 0:c.data)||void 0===u?void 0:u.notepad)||void 0===m?void 0:m.content)||""}catch(e){return void console.error("[MaiMemo] Failed to fetch notepad content:",null===(p=null==e?void 0:e.response)||void 0===p?void 0:p.status,JSON.stringify(null!==(g=null===(h=null==e?void 0:e.response)||void 0===h?void 0:h.data)&&void 0!==g?g:e))}const o=t.split("\n").map((e=>e.trim())).filter((e=>e.length>0));if(o.includes(a))return;o.push(a),yield e.post(`https://open.maimemo.com/open/api/v1/memo/notepads/${E}`,{id:E,notepad:{status:"PUBLISHED",content:o.join("\n"),title:k,brief:k,tags:[]}},{headers:S})}catch(e){throw console.error(`[MaiMemo] Failed to add word "${a}" to notepad "${k}" (${E}):`,null===(f=null==e?void 0:e.response)||void 0===f?void 0:f.status,JSON.stringify(null!==(N=null===(y=null==e?void 0:e.response)||void 0===y?void 0:y.data)&&void 0!==N?N:e)),e}}catch(e){console.error("[MaiMemo] Sync error for word:",a,null===(v=null==e?void 0:e.response)||void 0===v?void 0:v.status,JSON.stringify(null!==(k=null===(b=null==e?void 0:e.response)||void 0===b?void 0:b.data)&&void 0!==k?k:e))}})),this.configService=a}}class Ye extends Qe{}export{S as CommonTool,ze as ConfigService,Be as HighlightUtil,Ae as KOReaderUtil,A as KookitConfig,ye as LoginHelper,Ge as NoteSyncManager,he as ReaderRequest,ve as ReadingTimeUtil,ce as SqlStatement,Ne as SyncHelper,oe as SyncUtil,ge as ThirdpartyRequest,fe as UserRequest,Ye as WordSyncManager}; diff --git a/src/assets/lib/kookit-extra.min.mjs b/src/assets/lib/kookit-extra.min.mjs index 9c8a7667..31f55b13 100644 --- a/src/assets/lib/kookit-extra.min.mjs +++ b/src/assets/lib/kookit-extra.min.mjs @@ -1 +1 @@ -import e from"axios";import t from"fs";import i from"path";import{promisify as o}from"util";import r from"stream";import{Client as s}from"basic-ftp";import{S3Client as n,ListObjectsV2Command as a,DeleteObjectCommand as d,PutObjectCommand as l,GetObjectCommand as c}from"@aws-sdk/client-s3";import{AuthType as u,createClient as h}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as g}from"megajs";import y from"crypto";import m from"os";import{SSE as v}from"sse.js";import k from"electron-store";function b(e,t,i,o){return new(i||(i=Promise))((function(r,s){function n(e){try{d(o.next(e))}catch(e){s(e)}}function a(e){try{d(o.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(n,a)}d((o=o.apply(e,t||[])).next())}))}const F=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,w={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let t="",i=0;const o=this._stringToUtf8Bytes(e),r=o.length;for(;i>2,d=(3&e)<<4|s>>4,l=(15&s)<<2|n>>6,c=63&n;t+=this._chars.charAt(a),t+=this._chars.charAt(d),t+=i-2>=r?"=":this._chars.charAt(l),t+=i-1>=r?"=":this._chars.charAt(c)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const t=[];let i=0;const o=e.length;for(;i>4,d=(15&r)<<4|s>>2,l=(3&s)<<6|n;t.push(a),-1!==s&&t.push(d),-1!==n&&t.push(l)}return this._utf8BytesToString(t)},_stringToUtf8Bytes(e){const t=[];for(let i=0;i>6),t.push(128|63&o);else if(55296==(64512&o)&&i+1>18),t.push(128|e>>12&63),t.push(128|e>>6&63),t.push(128|63&e)}else t.push(239,191,189),i--}else t.push(224|o>>12),t.push(128|o>>6&63),t.push(128|63&o)}return t},_utf8BytesToString(e){let t="",i=0;for(;i65535){const i=e-65536;t+=String.fromCharCode(55296|i>>10),t+=String.fromCharCode(56320|1023&i)}else t+=String.fromCharCode(e)}else t+="�"}else t+="�"}return t},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}};class E{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return b(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,i)=>{if(this.hasFailedTasks)return void t(void 0);const o=()=>b(this,void 0,void 0,(function*(){if(this.hasFailedTasks)return this.completedTasks++,void t(void 0);try{this.runningTasks++;const i=yield e();return this.completedTasks++,t(i),i}catch(e){throw this.completedTasks++,i(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0;){const e=this.queue.shift();e&&e()}else if(this.queue.length>0&&this.runningTasks=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=[],r=!0,s=null;for(;r;){let n;n=s?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:s},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});const a=n.data.entries||[];o=o.concat(a),r=n.data.has_more,s=n.data.cursor}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${x}&redirect_uri=${e}`}}const j=o(r.pipeline);class D extends Q{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token,n=t.createReadStream(i.join(this.storagePath,o));return yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+r,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token,n=t.createWriteStream(i.join(this.storagePath,r)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${s}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+o})},maxContentLength:1/0,maxBodyLength:1/0});let d=0;return a.data.on("data",(e=>{d+=e.length,this.taskQueue.setDownloadedSize(d)})),yield j(a.data,n),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class B{constructor(e){this.config=e,this.storagePath=e.storagePath,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client&&!1===this.client.closed)return this.client;let{url:e,username:t,password:i,dir:o,ssl:r,port:n}=this.config;const a=new s(0);a.ftp.verbose=!0;const d=a.access({host:e,port:parseInt(n),user:t,password:i,secure:"1"===r}),l=new Promise(((e,t)=>{setTimeout((()=>t(new Error("FTP connection timeout"))),5e3)}));return yield Promise.race([d,l]),this.client=a,a}catch(e){throw console.error("Error connecting to FTP server:",e),this.client=null,e}}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;const r=yield this.getClient(),s=()=>b(this,void 0,void 0,(function*(){yield r.ensureDir(i.dirname(o+"/"+t)),yield r.cd("/"),yield r.uploadFrom(i.join(this.storagePath,e),o+"/"+t)}));try{return yield s(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;const s=yield this.getClient(),n=t.createWriteStream(i.join(this.storagePath,o)),a=()=>b(this,void 0,void 0,(function*(){s.trackProgress((e=>{this.taskQueue.setDownloadedSize(e.bytes||0)})),yield s.downloadTo(n,r+"/"+e),s.trackProgress()}));try{return yield a(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.listFilesWithoutQueue(e)}))))))}))}listFilesWithoutQueue(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),o=()=>b(this,void 0,void 0,(function*(){return yield i.list(t+"/"+e)}));try{return(yield o()).map((e=>({name:e.name,size:e.size||0,type:e.isFile?"file":"folder",modified:e.modifiedAt?e.modifiedAt.toISOString():""})))}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),o=()=>b(this,void 0,void 0,(function*(){yield i.remove(t+"/"+e)}));try{return yield o(),!0}catch(e){return console.error(e),!1}}))}}class M{constructor(e){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let o,r=[];if(""===t)o=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);o=`${this.baseUrl}:/${e}:/children`}for(;o;){const t=yield e.get(o,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];r=r.concat(s),o=t.data["@odata.nextLink"]||""}return[...new Set(r.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const o=yield e.delete(`${this.baseUrl}:/${t}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${I}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${e}`}}const U=209715200;class W extends M{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=this.config.access_token;let a=this.baseFolder+"/"+r;for(;a.startsWith("/");)a=a.substring(1);const d=i.join(this.storagePath,o),l=yield this.getFileSize(d),c=a.split(".").pop(),u=(F(c||""),`${this.baseUrl}:/${a}:/createUploadSession`),h=(yield e.post(u,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.uploadUrl;n=yield t.promises.open(d,"r");let p=0,f=Buffer.alloc(U);for(;pthis.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token;let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const a=`${this.baseUrl}:/${n}:/content`;let d=(yield fetch(a,{headers:{Authorization:"Bearer "+s},redirect:"manual"})).headers.get("location");if(d){const o=yield e.get(d,{responseType:"stream"});let s=0;const n=t.createWriteStream(i.join(this.storagePath,r));return o.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),yield new Promise(((e,t)=>{o.data.pipe(n),n.on("finish",(()=>{e()})),n.on("error",t)})),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class N{constructor(e){this.isExp=!1,this.folderIdCache=new Map,this.config=e,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getFileId(t,i){return b(this,void 0,void 0,(function*(){const o=this.config.access_token,r=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${i}'+in+parents&fields=files(id,name)`;try{const t=yield e.get(r,{headers:{Authorization:"Bearer "+o}});if(0===t.data.files.length)return"";const i=t.data.files;return i.length>0?i[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return b(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const i=this.config.access_token;if(""===t)return"root";if(this.folderIdCache.has(t))return this.folderIdCache.get(t);const o=t.split("/").filter((e=>""!==e.trim()));let r="root",s="";for(const t of o){if(s=s?s+"/"+t:t,this.folderIdCache.has(s)){r=this.folderIdCache.get(s);continue}let o=yield this.getFolderId(t,r);if(!o){const s={name:t,mimeType:"application/vnd.google-apps.folder",parents:[r]};try{o=(yield e.post("https://www.googleapis.com/drive/v3/files",s,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}this.folderIdCache.set(s,o),r=o}return r}))}getFolderId(t,i){return b(this,void 0,void 0,(function*(){const o=this.config.access_token,r=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${i}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(r,{headers:{Authorization:`Bearer ${o}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=yield this.checkFolder(t),r=[],s="",n=!0;for(;n;){let t=`https://www.googleapis.com/drive/v3/files?q='${o}'+in+parents&fields=nextPageToken,files(id,name,size,mimeType)&pageSize=1000`;s&&(t+=`&pageToken=${s}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${i}`}}),d=a.data.files||[];r=r.concat(d),s=a.data.nextPageToken,n=!!s}return[...new Set(r.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return b(this,void 0,void 0,(function*(){const i=t.split("/").pop()||"",o=t.split("/").slice(0,-1).join("/"),r=yield this.checkFolder(o),s=this.config.access_token,n=yield this.getFileId(i,r);if(""===n)return console.error("File not found:",i),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${n}`,{headers:{Authorization:`Bearer ${s}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${$}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class K extends N{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token;let n=o.split("/").pop(),a=r.split(".").pop(),d=F(a||""),l=r.split("/").slice(0,-1).join("/"),c=yield this.checkFolder(l),u=yield this.getFileId(n||"",c);const h={mimeType:d,name:n,parents:[c]},p=u?`https://www.googleapis.com/upload/drive/v3/files/${u}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:u?"PATCH":"POST",url:p,data:u?null:JSON.stringify(h),headers:{Authorization:"Bearer "+s,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let g=yield this.getFileSize(i.join(this.storagePath,o));const y=t.createReadStream(i.join(this.storagePath,o));yield e.put(f,y,{headers:{Authorization:"Bearer "+s,"Content-Type":"application/zip","Content-Range":`bytes 0-${g-1}/${g}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during upload:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token;let n=o.split("/").pop(),a=o.split("/").slice(0,-1).join("/"),d=yield this.checkFolder(a),l=yield this.getFileId(n||"",d);if(!l)return console.error("File not found"),!0;const c=`https://www.googleapis.com/drive/v3/files/${l}?alt=media`;return new Promise((o=>{const n=t.createWriteStream(i.join(this.storagePath,r));e({url:c,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{let t=0;e.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),e.data.pipe(n),n.on("finish",(()=>{o(!0)})),n.on("error",(()=>{o(!1)}))})).catch((e=>{console.error("Error downloading file:",e),o(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class H{constructor(e){this.config=e,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}shouldUsePathStyle(){try{if(this.config.forcePathStyle&&"no"!==this.config.forcePathStyle)return!0;let e=this.config.endpoint;const t=new URL(e),i=t.hostname,o=/^(\d{1,3}\.){3}\d{1,3}$/.test(i),r=""!==t.port;return!o&&r}catch(e){return!0}}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:o,accessKeyId:r,secretAccessKey:s,dir:d}=this.config;d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let l=d+"/"+e;for(;l.startsWith("/");)l=l.substring(1);""===l||l.endsWith("/")||(l+="/");const c=new n({endpoint:t,region:i,credentials:{accessKeyId:r,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});try{let e,t=[],i=[],r=!0;for(;r;){const s=yield c.send(new a({Bucket:o,Prefix:l,Delimiter:"/",ContinuationToken:e}));s.Contents&&(t=t.concat(s.Contents)),s.CommonPrefixes&&(i=i.concat(s.CommonPrefixes)),e=s.NextContinuationToken,r=!!e}let s=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(l.length);t.includes("/")||s.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),i.forEach((e=>{const t=e.Prefix.substring(l.length).replace(/\/$/,"");t&&s.push({name:t,size:0,type:"folder",modified:""})})),s}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:o,accessKeyId:r,secretAccessKey:s,dir:a}=this.config;a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;const l=new n({endpoint:t,region:i,credentials:{accessKeyId:r,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});let c=a+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield l.send(new d({Bucket:o,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class q extends H{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){let{endpoint:r,region:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:u}=this.config;const h=new n({endpoint:r,region:s,credentials:{accessKeyId:d,secretAccessKey:c},forcePathStyle:this.shouldUsePathStyle()});u=u&&"KoodoReader"===this.baseFolder?u:this.baseFolder;let p=u+"/"+o;for(;p.startsWith("/");)p=p.substring(1);try{let o=yield h.send(new l({Bucket:a,Key:p,Body:t.createReadStream(i.join(this.storagePath,e))}));return 200===o.$metadata.httpStatusCode||(console.error("Error uploading file:",o),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:r,region:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:u}=this.config;u=u&&"KoodoReader"===this.baseFolder?u:this.baseFolder;const h=(e,t,i,o)=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){const s=yield e.send(new c({Bucket:t,Key:i}));let n=0;s.Body?(s.Body.on("data",(e=>{n+=e.length,this.taskQueue.setDownloadedSize(n)})),s.Body.pipe(o),o.on("finish",(e=>{e&&r(!1),r(!0)}))):r(!1)})))),p=()=>new Promise(((c,p)=>{const f=new n({region:s,endpoint:r,credentials:{accessKeyId:d,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle()});let g=t.createWriteStream(i.join(this.storagePath,o)),y=u+"/"+e;for(;y.startsWith("/");)y=y.substring(1);h(f,a,y,g).then((e=>{c(!0)})).catch((e=>{console.error(e),c(!1)}))}));try{return yield p()}catch(e){return console.error(e),!1}}))))))}))}}class J{constructor(e){let{username:t,password:i,url:o,dir:r,AuthType:s,createClient:n}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder,this.username=t,this.password=i,this.url=o,this.dir=r,this.taskQueue=new E(5),this.AuthType=s,this.createClient=n}getClient(){return b(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(t){return b(this,void 0,void 0,(function*(){try{const i=yield e.head(t,{maxRedirects:0,validateStatus:()=>!0,timeout:5e3});return i.request&&i.request.responseURL&&i.request.responseURL!==t?i.request.responseURL:i.status>=300&&i.status<400&&i.headers.location?i.headers.location:t}catch(e){return console.info("Error handling URL redirection:",e),t}}))}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{const i=t.getDirectoryContents(this.dir+"/"+e),o=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV list directory timeout"))),5e3)}));return(yield Promise.race([i,o])).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}catch(i){return i.response&&404===i.response.status&&(yield t.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",i),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return yield t.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return b(this,void 0,void 0,(function*(){let t=yield this.getClient();try{const i=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let o="";for(const e of i)o=o?`${o}/${e}`:e,(yield t.exists(`/${o}`))||(yield t.createDirectory(`/${o}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class V extends J{constructor(e){super(Object.assign(Object.assign({},e),{AuthType:u,createClient:h})),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let s=yield this.getClient();const n=s.exists(i.dirname(this.dir+"/"+r)),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([n,a]))&&(yield this.ensureDirectoryExists(i.dirname(this.dir+"/"+r)));let d=t.readFileSync(i.join(this.storagePath,o)),l=i.extname(o).substring(1),c=F(l),u=s.createWriteStream(this.dir+"/"+r,{headers:{"content-type":c,"content-length":d.length}});return t.createReadStream(i.join(this.storagePath,o)).pipe(u),new Promise(((t,i)=>{u.on("finish",(()=>{t(!0)})),u.on("error",(i=>b(this,void 0,void 0,(function*(){console.error("Error occurred during file upload:",i);try{let i=s.getFileUploadLink(this.dir+"/"+r);const o=new URL(i);o.search="",i=o.toString();const n=Buffer.from(this.username+":"+this.password,"binary").toString("base64");yield e.put(i,d,{headers:{Authorization:"Basic "+n,"Content-Type":c,"Content-Length":d.length},maxContentLength:1/0,maxBodyLength:1/0});t(!0)}catch(e){console.error("Error occurred during file upload:",e),t(!1)}}))))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===e.indexOf("."))return new ArrayBuffer(0);try{let r=yield this.getClient();if(!1===(yield r.exists(this.dir+"/"+e)))return!0;let s=0,n=t.createWriteStream(i.join(this.storagePath,o)),a=r.createReadStream(this.dir+"/"+e);return a.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),a.pipe(n),new Promise(((e,t)=>{n.on("finish",(()=>{e(!0)})),n.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class X{constructor(e){this.folderExistsCache=new Set,this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){var i,o;return b(this,void 0,void 0,(function*(){try{const r=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let s=[],n=0;const a=1e3;let d=!0;for(;d;){const l=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",limit:a,offset:n,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),c=(null===(i=l.data._embedded)||void 0===i?void 0:i.items)||[];s=s.concat(c);const u=(null===(o=l.data._embedded)||void 0===o?void 0:o.total)||0;n+=c.length,d=n({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const o=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",permanently:!1}});return 202===o.status||204===o.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(t){var i,o;return b(this,void 0,void 0,(function*(){try{const r=this.config.access_token,s=t.split("/").filter((e=>e.length>0));let n="";for(const t of s)if(n+="/"+t,!this.folderExistsCache.has(n))try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:n}}),this.folderExistsCache.add(n)}catch(t){if(404!==(null===(i=t.response)||void 0===i?void 0:i.status))return console.error("Error checking directory:",t),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(n)}`,null,{headers:{Authorization:`OAuth ${r}`}}),this.folderExistsCache.add(n)}catch(e){if(409!==(null===(o=e.response)||void 0===o?void 0:o.status))return console.error("Error creating directory:",e),!1;this.folderExistsCache.add(n)}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${R}&redirect_uri=${e}&force_confirm=true`}}const Y=o(r.pipeline);class G extends X{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token;let n=this.baseFolder+"/"+r;for(;n.startsWith("/");)n=n.substring(1);const a=n.substring(0,n.lastIndexOf("/"));if(a){if(!(yield this.ensureDirectoryExists(a)))return console.error("Failed to create directory:",a),!1}const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${s}`,"Content-Type":"application/json"},params:{path:`/${n}`,overwrite:!0}});if(200!==d.status)return console.error("Error getting upload URL:",d),!1;const l=d.data.href,c=t.createReadStream(i.join(this.storagePath,o));return yield e.put(l,c,{headers:{"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let s=this.baseFolder+"/"+o;for(;s.startsWith("/");)s=s.substring(1);try{const o=this.config.access_token,n=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:`/${s}`}});if(200!==n.status)return console.error("Error getting download URL:",n),!1;const a=n.data.href,d=t.createWriteStream(i.join(this.storagePath,r)),l=yield e({url:a,method:"GET",responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});let c=0;return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),yield Y(l.data,d),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class Z{constructor(e){this.config=e,this.storagePath=e.storagePath,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client)return this.client;let{url:e,username:t,password:i,dir:o,port:r}=this.config;const s=new p,n=s.connect({host:e||"",port:r||22,username:t||"",password:i||""}),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("SFTP connection timeout"))),5e3)}));return yield Promise.race([n,a]),this.client=s,s}catch(e){throw console.error("Error connecting to SFTP server:",e),this.client=null,e}}))}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a=t.createReadStream(i.join(this.storagePath,e)),d="/"+r+"/"+o,l="/"+r+"/"+i.dirname(o);(yield s.exists(l))||(yield s.mkdir(l,!0)),s.put(a,d).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let{dir:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a="/"+r+"/"+e,d=i.join(this.storagePath,o),l=t.createWriteStream(d);s.get(a,l).then((()=>{this.taskQueue.setDownloadedSize(l.bytesWritten||0),n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();const o=()=>new Promise(((o,r)=>b(this,void 0,void 0,(function*(){let r="/"+t+"/"+e;(yield i.exists(r))||(yield i.mkdir(r,!0),o([])),i.list(r).then((e=>{o(e.map((e=>({name:e.name,size:e.size||0,type:"d"===e.type?"folder":"file",modified:e.modifyTime}))))})).catch((e=>b(this,void 0,void 0,(function*(){console.error(e.message,"list file error"),o([])}))))}))));try{return yield o()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();try{return yield new Promise(((o,r)=>{let s="/"+t+"/"+e;i.delete(s).then((()=>{o(!0)})).catch((e=>{console.error(e.message),o(!1)}))}))}catch(e){return console.error(e),!1}}))}}class ee{downloadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}getAuthUrl(){return""}}class te{constructor(e){this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){if(""==t)return"0";const i=this.config.access_token,o=t.split("/");let r="0";for(const t of o){const o=`https://api.box.com/2.0/folders/${r}/items?fields=id,name&type=folder&limit=1000`;try{const s=(yield e.get(o,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(s)r=s.id;else{const o={name:t,parent:{id:r},type:"folder"};r=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return r}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=this.baseFolder+"/"+t;for(;o.startsWith("/");)o=o.substring(1);let r=yield this.getFolderIdByPath(o),s=[],n=0,a=!0;const d=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${r}/items`,{params:{limit:d,offset:n},headers:{Authorization:`Bearer ${i}`}}),o=t.data.entries||[];s=s.concat(o),n+=o.length,a=o.length===d&&t.data.total_count>n}return[...new Set(s.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=t.substring(0,t.lastIndexOf("/")),r=t.substring(t.lastIndexOf("/")+1);let s=this.baseFolder+"/"+o;for(;s.startsWith("/");)s=s.substring(1);const n=yield this.getFolderIdByPath(s);if(!n)return!0;const a=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,d=(yield e.get(a,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===r&&"file"===e.type));return!d||(yield e.delete(`https://api.box.com/2.0/files/${d.id}`,{headers:{Authorization:`Bearer ${i}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:_,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class ie extends te{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token,n=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)throw new Error("Folder not found");const c=yield this.listFiles(n);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const u=new f,h=JSON.stringify({name:a,parent:{id:l}});u.append("attributes",h),u.append("file",t.createReadStream(i.join(this.storagePath,o)));const p=yield e.post("https://upload.box.com/api/2.0/files/content",u,{headers:Object.assign({Authorization:`Bearer ${s}`},u.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(p.status>=300)||(console.error("Error occurred during file upload:",p),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token,n=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${l}/items?fields=id,name&type=file&limit=1000`,u=(yield e.get(c,{headers:{Authorization:`Bearer ${s}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!u)return console.error("File not found:",a),!0;const h=yield e({url:`https://api.box.com/2.0/files/${u.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${s}`}});return yield new Promise(((e,o)=>{let s=0;const n=t.createWriteStream(i.join(this.storagePath,r));h.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),h.data.pipe(n),n.on("finish",e),n.on("error",o)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class oe{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=2){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getStorage(){return b(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new g({email:e,password:t,userAgent:"KoodoReader/1.0"}).ready,this.storage}))}getRoot(){return b(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),this.root=t,this.root}))}createFolder(e,t){return b(this,void 0,void 0,(function*(){const i=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(i))return yield this.folderCreationLocks.get(i);const o=(()=>b(this,void 0,void 0,(function*(){try{let i=e.children.find((e=>e.name===t&&e.directory));return i||(i=yield e.mkdir(t),i)}finally{this.folderCreationLocks.delete(i)}})))();return this.folderCreationLocks.set(i,o),yield o}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const i=e.split("/").filter((e=>e));for(const e of i){const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return[];t=i}}return t.children.map((e=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const i=e.split("/"),o=i.pop();for(const e of i){if(!e)continue;const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return!0;t=i}const r=t.children.find((e=>e.name===o&&!e.directory));return!r||(yield r.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class re extends oe{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let r=yield this.getRoot();const s=o.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;let t=r.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(r,e)),r=t}const a=r.children.find((e=>e.name===n&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(i.join(this.storagePath,e)),l=t.statSync(i.join(this.storagePath,e)).size;return yield r.upload({name:n,size:l},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let r=yield this.getRoot();const s=e.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;const t=r.children.find((t=>t.name===e&&t.directory));if(!t)return!0;r=t}const a=r.children.find((e=>e.name===n&&!e.directory));if(!a)return!0;const d=t.createWriteStream(i.join(this.storagePath,o));let l=0;return new Promise((e=>{const t=a.download();t.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),t.pipe(d),d.on("finish",(()=>e(!0))),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class se{constructor(e){this.config=e,this.driveId="",this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getDriveId(){return b(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=this.config.access_token,i=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=i.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){const i=this.config.access_token,o=yield this.getDriveId();try{try{const r=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(r.data)return r.data.file_id}catch(r){const s=t.split("/").filter((e=>e));let n="",a="root";for(const t of s){n+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:n},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.file_id}catch(r){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=yield this.getDriveId(),r=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let s=[],n="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:r,marker:n||void 0},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),d=t.data.items.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];s=s.concat(d),n=t.data.next_marker,a=!!n}return[...new Set(s.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=yield this.getDriveId(),r=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!r||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:r},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var i;return b(this,void 0,void 0,(function*(){try{const o=this.config.access_token,r=yield this.getDriveId(),s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:r,file_path:t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(i=s.data)||void 0===i?void 0:i.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:r,file_id:s.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:L,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class ne extends se{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token,n=yield this.getDriveId(),a=r.substring(0,r.lastIndexOf("/")),d=r.substring(r.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(r);const l=yield this.getFolderIdByPath(this.baseFolder+"/"+a),c=i.join(this.storagePath,o),u=yield t.promises.readFile(c),h=u.length,p=y.createHash("sha1").update(u).digest("hex"),f=y.createHash("md5").update(s).digest("hex"),g=Number(BigInt("0x"+f.slice(0,16))%BigInt(h||1)),m=u.slice(g,Math.min(g+8,h)).toString("base64"),v=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:l,name:d,type:"file",check_name_mode:"ignore",size:h,content_hash:p,content_hash_name:"sha1",proof_code:m,proof_version:"v1",part_info_list:[{part_number:1}]},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),{file_id:k,upload_id:b,rapid_upload:F,part_info_list:w}=v.data;return F?(console.info("阿里云盘秒传成功"),!0):(yield fetch(w[0].upload_url,{method:"PUT",body:u,headers:{"Content-Length":h.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:k,upload_id:b},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token,n=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:this.baseFolder+"/"+o},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:n,file_id:a},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),l=yield e({url:d.data.url,method:"get",responseType:"stream"});let c=0;const u=t.createWriteStream(i.join(this.storagePath,r+".temp"));return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),l.data.pipe(u),new Promise((e=>{u.on("finish",(()=>{t.renameSync(i.join(this.storagePath,r+".temp"),i.join(this.storagePath,r)),e(!0)})),u.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class ae{constructor(e){this.baseUrl="https://api.pcloud.com",this.config=e,this.taskQueue=new E(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}checkFolderExists(t,i){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:i,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,i){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/createfolderifnotexists`,{params:{access_token:i,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:i,path:"/"+t,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/deletefile`,{params:{access_token:i,path:"/"+t}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${C}&response_type=code&redirect_uri=${e}`}}class de extends ae{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.refresh_token,n=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(n,s))){if(!(yield this.createFolder(n,s)))return!1}const a=i.join(this.storagePath,o),d=t.createReadStream(a),l=t.statSync(a),c=i.basename(o),u=yield e({method:"put",url:`${this.baseUrl}/uploadfile`,params:{access_token:s,path:`/${n}`,renew:1,filename:c},data:d,headers:{"Content-Length":l.size,"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return 0===u.data.result||(console.error("Error uploading file:",u.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/getfilelink`,{params:{access_token:s,path:`/${o}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!1;const a=i.join(this.storagePath,r),d=t.createWriteStream(a),l=`https://${n.data.hosts[0]}${n.data.path}`,c=yield e({method:"get",url:l,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{let t=0;c.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),c.data.pipe(d),d.on("finish",(()=>{e(!0)})),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class le{constructor(e){this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=this.baseFolder;t&&""!==t.trim()&&(o=o+"/"+t),o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));let r=[],s=0;const n=1e3;for(;;){const t=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:i,dir:"/"+o,start:s,limit:n,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(t.status>=300||0!==t.data.errno){console.error("百度网盘API错误:",t.data);break}const a=t.data.list||[];if(0===a.length)break;if(r=r.concat(a),a.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path,fs_id:e.fs_id})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=this.baseFolder+"/"+t;o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));const r=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+o])}),s=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${i}&opera=delete`,r.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==s.data.errno)return console.error("百度网盘删除文件API错误:",s.data),-9===s.data.errno?console.error("文件不存在"):111===s.data.errno?console.error("有其他异步任务正在执行"):-7===s.data.errno&&console.error("文件名非法"),!1;const n=s.data.info||[];for(const e of n)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${P}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}const ce=4194304;class ue extends le{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=this.config.access_token;let a=this.baseFolder+"/"+r;a=a.replace(/\/+/g,"/"),a.startsWith("/")&&(a=a.substring(1));const d=i.join(this.storagePath,o),l=yield this.getFileSize(d),{contentMd5:c,sliceMd5:u,blockList:h}=yield this.calculateFileMd5(d,l),p=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",autoinit:"1",rtype:"3",block_list:JSON.stringify(h),"content-md5":c,"slice-md5":u,local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),g=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=${s}`,p.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==g.data.errno)return console.error("预上传失败:",g.data),-7===g.data.errno?console.error("文件或目录名错误或无权访问"):-10===g.data.errno&&console.error("容量不足"),!1;const y=g.data.uploadid,m=g.data.block_list||[];if(0===m.length)return!0;const v=yield this.getUploadDomain(s,"/"+a,y);if(!v)return console.error("获取上传域名失败"),!1;n=yield t.promises.open(d,"r");for(const t of m){const i=t*ce,o=Math.min(ce,l-i),r=Buffer.alloc(o),{bytesRead:d}=yield n.read(r,0,o,i);if(0===d)break;const c=r.slice(0,d),u=h[t],p=new f;p.append("file",c,{filename:`chunk_${t}`,contentType:"application/octet-stream",knownLength:c.length});const g=`${v}/rest/2.0/pcs/superfile2?method=upload&access_token=${s}&type=tmpfile&path=${encodeURIComponent("/"+a)}&uploadid=${y}&partseq=${t}`,m=yield e.post(g,p,{headers:Object.assign(Object.assign({"User-Agent":"pan.baidu.com"},p.getHeaders()),{"Content-Length":p.getLengthSync().toString()}),maxContentLength:1/0,maxBodyLength:1/0,timeout:0});if(m.status>=300)throw 31024===m.data.errno?console.error("没有申请上传权限"):31299===m.data.errno?console.error("第一个分片的大小小于4MB"):31364===m.data.errno?console.error("超出分片大小限制"):31363===m.data.errno&&console.error("分片缺失"),new Error(`分片上传失败: ${JSON.stringify(m.data)}`);const k=m.data.md5;k&&k!==u&&console.warn(`分片 ${t} MD5不匹配: 期望 ${u}, 实际 ${k}`)}const k=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",block_list:JSON.stringify(h),uploadid:y,rtype:"3",local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),b=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=${s}`,k.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});return 0===b.data.errno||(console.error("创建文件失败:",b.data),-7===b.data.errno?console.error("文件或目录名错误或无权访问"):-8===b.data.errno?console.error("文件或目录已存在"):-10===b.data.errno?console.error("云端容量已满"):10===b.data.errno?console.error("创建文件失败,一般是分片问题"):31190===b.data.errno?console.error("文件不存在,一般是分片上传阶段有问题"):31355===b.data.errno?console.error("参数异常,一般是uploadid参数传的有问题"):31365===b.data.errno&&console.error("文件总大小超限"),!1)}catch(e){return console.error("文件上传过程中发生错误:",(null===(s=e.response)||void 0===s?void 0:s.data)||e.message||e),!1}finally{n&&(yield n.close())}}))))))}))}getUploadDomain(t,i,o){return b(this,void 0,void 0,(function*(){try{const r=yield e.get("https://d.pcs.baidu.com/rest/2.0/pcs/file",{params:{method:"locateupload",appid:"250528",access_token:t,path:i,uploadid:o,upload_version:"2.0"},headers:{"User-Agent":"pan.baidu.com"}});if(0!==r.data.error_code)return console.error("获取上传域名失败:",r.data),null;const s=r.data.servers||[],n=s.find((e=>e.server.startsWith("https://")));return n?n.server:s.length>0?s[0].server:(console.error("没有可用的上传服务器"),null)}catch(e){return console.error("获取上传域名时出错:",e),null}}))}calculateFileMd5(e,i){return b(this,void 0,void 0,(function*(){const o=yield t.promises.open(e,"r");try{const e=y.createHash("md5"),t=[];let r="",s=0;for(;sthis.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;this.taskQueue.setDownloadedSize(0);try{const n=this.config.access_token;let a,d=this.baseFolder+"/"+o;d=d.replace(/\/+/g,"/"),d.startsWith("/")&&(d=d.substring(1));let l=yield this.listFileInfos(o.substring(0,o.lastIndexOf("/")));const c=d.split("/").pop(),u=l.find((e=>e.name===c));if(!u)return console.error("文件不存在:",o),!1;const h=yield e.get("https://pan.baidu.com/rest/2.0/xpan/multimedia",{params:{method:"filemetas",access_token:n,fsids:JSON.stringify([u.fs_id]),dlink:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==h.data.errno||!(null===(s=h.data.list)||void 0===s?void 0:s[0]))return console.error("获取下载链接失败:",h.data),!1;a=h.data.list[0];const p=a.dlink,f=yield e.get(p,{responseType:"stream",params:{access_token:n},headers:{"User-Agent":"pan.baidu.com"}});let g=0;const y=t.createWriteStream(i.join(this.storagePath,r));f.data.on("data",(e=>{g+=e.length,this.taskQueue.setDownloadedSize(g)})),yield new Promise(((e,t)=>{f.data.pipe(y),y.on("finish",(()=>{e()})),y.on("error",t)}));return(yield this.getFileSize(i.join(this.storagePath,r)))===a.size||(console.error("Downloaded file size does not match expected size."),yield t.promises.unlink(i.join(this.storagePath,r)),!1)}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class he{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.taskQueue=new E(3)}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}const pe=o(r.pipeline);class fe extends he{constructor(e){super(e),this.storagePath=e.storagePath}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{r.split("/").pop();const s=r.substring(0,r.lastIndexOf("/"))||"";let n=this.listFiles("");const a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([n,a]);const d=t.createReadStream(i.join(this.storagePath,o)),l=new f;l.append("file",d);const c=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(s)}`,l,{headers:Object.assign(Object.assign({},l.getHeaders()),{Authorization:this.getAuthHeader()}),maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=o.split("/").pop()||"",n=o.substring(0,o.lastIndexOf("/"))||"",a=t.createWriteStream(i.join(this.storagePath,r)),d=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:s},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"stream"});if(d.status>=300)return console.error("Error occurred during file download:",d),a.destroy(),t.existsSync(i.join(this.storagePath,r))&&t.unlinkSync(i.join(this.storagePath,r)),!1;let l=0;return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield pe(d.data,a),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ge{constructor(e){this.baseUrl="https://proapi.115.com",this.config=e,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getUploadCredentials(t){return b(this,void 0,void 0,(function*(){try{const i=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${t}`}});return i.status>=300||!i.data.state?(console.error("Error getting upload credentials:",i.data),null):i.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,t,i=new Date(Date.now()+36e5)){const o={expiration:i.toISOString(),conditions:[{bucket:e},{key:t},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(o)}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${A}&response_type=code&redirect_uri=${e}`}}class ye extends ge{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var o;try{const o=this.config.access_token;let r=this.baseFolder+"/"+t;r.startsWith("/")||(r="/"+r);let s=i.dirname(r),n=yield this.getFolderInfo(s,!0),a="0";if(n)a=n.file_id;else{let e=yield this.createFolder(s);if(!e)return console.error("Failed to create folder:",s),!1;a=e}const d=i.join(this.storagePath,e),l=yield this.getFileSize(d),c=yield this.calculateFileSha1(d),u=yield this.calculatePreSha1(d),h=i.basename(t);yield this.deleteFileWithoutQueue(t);let p=yield this.initializeUpload(a,h,l,c,u,o);if(!p)return console.error("Failed to initialize upload"),!1;if((6===p.status||7===p.status||8===p.status)&&(p=yield this.handleSecondAuth(a,p,d,h,l,c,u,o),!p))return console.error("Second authentication failed"),!1;if(2===p.status)return console.info(`File ${e} uploaded successfully via instant upload.`),!0;const f=yield this.getUploadCredentials(o);if(!f)return console.error("Failed to get upload credentials"),!1;return(yield this.uploadToObjectStorage(d,p,f))?(console.info(`File ${e} uploaded successfully.`),!0):(console.error("Failed to upload to object storage"),!1)}catch(e){return console.error("Error occurred during file upload:",(null===(o=e.response)||void 0===o?void 0:o.data)||e.message||e),!1}}))))))}))}calculateFileSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{const r=y.createHash("sha1"),s=t.createReadStream(e);s.on("data",(e=>{r.update(e)})),s.on("end",(()=>{i(r.digest("hex"))})),s.on("error",(e=>{o(e)}))}))}))}calculatePreSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{const r=y.createHash("sha1"),s=t.createReadStream(e,{start:0,end:131071});s.on("data",(e=>{r.update(e)})),s.on("end",(()=>{i(r.digest("hex"))})),s.on("error",(e=>{o(e)}))}))}))}handleSecondAuth(e,i,o,r,s,n,a,d){return b(this,void 0,void 0,(function*(){try{if(!i.sign_check)return console.error("No sign_check provided for second authentication"),null;const[l,c]=i.sign_check.split("-"),u=parseInt(l),h=parseInt(c),p=Buffer.alloc(h-u+1),f=yield t.promises.open(o,"r");try{yield f.read(p,0,p.length,u);const t=y.createHash("sha1");t.update(p);const o=t.digest("hex").toUpperCase();return yield this.initializeUpload(e,r,s,n,a,d,i.sign_key,o,i.pick_code)}finally{yield f.close()}}catch(e){return console.error("Error during second authentication:",e),null}}))}calculateOSSSignature(e,t){const i=Buffer.from(t).toString("base64");return y.createHmac("sha1",e).update(i).digest("base64")}uploadToObjectStorage(o,r,s){var n;return b(this,void 0,void 0,(function*(){try{const n=s.endpoint,a=r.bucket,d=r.object;let l;if(n.includes(a))l=n;else{l=`https://${a}.${n.replace(/^https?:\/\//,"")}`}const c=this.generateOSSPolicy(a,d),u=this.calculateOSSSignature(s.AccessKeySecret,c),h=Buffer.from(c).toString("base64"),p=new f;if(p.append("key",d),p.append("policy",h),p.append("OSSAccessKeyId",s.AccessKeyId),p.append("signature",u),p.append("x-oss-security-token",s.SecurityToken),p.append("success_action_status","200"),r.callback&&r.callback.callback){const e=Buffer.from(r.callback.callback).toString("base64");if(p.append("callback",e),r.callback.callback_var){const e=JSON.parse(r.callback.callback_var);for(const[t,i]of Object.entries(e))p.append(t,String(i))}}const g=t.createReadStream(o);p.append("file",g,i.basename(o));const y=yield e.post(l,p,{headers:Object.assign({},p.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return 200===y.status||204===y.status||(console.error("Upload failed with status:",y.status),!1)}catch(e){return console.error("Error uploading file via REST API:",(null===(n=e.response)||void 0===n?void 0:n.data)||e.message||e),!1}}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let s=this.baseFolder+"/"+o;s=s.replace(/\/+/g,"/"),s.startsWith("/")||(s="/"+s);const n=yield this.getFolderInfo(s,!1);if(!n||!n.pick_code)return console.error("Failed to get file info or pick_code for:",o),!1;const a=yield this.getFileDownloadUrl(n.pick_code);if(!a)return console.error("Failed to get download URL for:",o),!1;const d=yield e.get(a.url,{responseType:"stream"});let l=0;const c=t.createWriteStream(i.join(this.storagePath,r));return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield new Promise(((e,t)=>{d.data.pipe(c),c.on("finish",(()=>{e()})),c.on("error",t)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;(t=this.baseFolder+"/"+t).startsWith("/")||(t="/"+t);let o=[],r=0;const s=1150;let n=!0,a=yield this.getFolderInfo(t,!0),d="";if(a)d=a.file_id;else{let e=yield this.createFolder(t);if(!e)return console.error("Failed to create folder:",t),[];d=e}if(!d)return console.error("Failed to get or create folder ID:",t),[];let l=d;for(;n;){const t={offset:r,limit:s,cur:1,show_dir:1};l&&(t.cid=l);const a=yield e.get(`${this.baseUrl}/open/ufile/files`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},params:t});if(a.status>=300)break;const d=a.data.data||[];o=o.concat(d),d.length({name:e.fn,size:e.fs||0,type:"0"===e.fc?"folder":"file",modified:new Date(1e3*e.upt).toISOString()})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}getFileDownloadUrl(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=new f;o.append("pick_code",t);const r=yield e.post(`${this.baseUrl}/open/ufile/downurl`,o,{headers:Object.assign({Authorization:`Bearer ${i}`},o.getHeaders())});if(r.status>=300)return console.error("Error getting download URL:",r.data),null;const s=r.data.data,n=Object.keys(s)[0];return n&&s[n]?s[n].url:(console.error("No file data found in download URL response"),null)}catch(e){return console.error("Error occurred during get download URL:",e),null}}))}initializeUpload(t,i,o,r,s,n,a,d,l){return b(this,void 0,void 0,(function*(){try{const c=new f;c.append("file_name",i),c.append("file_size",o.toString()),t?c.append("target","U_1_"+t):c.append("target","U_1_0"),c.append("fileid",r),c.append("preid",s),c.append("topupload","0"),l&&c.append("pick_code",l),a&&c.append("sign_key",a),d&&c.append("sign_val",d);const u=yield e.post(`${this.baseUrl}/open/upload/init`,c,{headers:Object.assign({Authorization:`Bearer ${n}`},c.getHeaders())});return u.status>=300||!u.data.state?(console.error("Error initializing upload:",u.data),null):u.data.data}catch(e){return console.error("Error occurred during upload initialization:",e),null}}))}createFolder(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=t.replace(/^\/+|\/+$/g,"");if(!o)return"";const r=o.split("/");let s="",n="0";for(const t of r){s=s?`${s}/${t}`:t;const o=yield this.getFolderInfo(s,!0);if(o&&o.file_id)n=o.file_id;else{const o=new f;o.append("pid",n),o.append("file_name",t);const r=yield e.post(`${this.baseUrl}/open/folder/add`,o,{headers:Object.assign({Authorization:`Bearer ${i}`},o.getHeaders())});if(r.status>=300||!r.data.state)return console.error("Error creating folder:",r.data),"";n=r.data.data.file_id}}return n}catch(e){return console.error("Error occurred during folder creation:",e),""}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;t=this.baseFolder+"/"+t;let o=yield this.getFolderInfo(t,!1);if(!o)return!0;let r=new f;r.append("file_ids",o.file_id);const s=yield e.post(`${this.baseUrl}/open/ufile/delete`,r,{headers:Object.assign({Authorization:`Bearer ${i}`},r.getHeaders())});return!(s.status>=300||!s.data.state)||(console.error("Error deleting file:",s),!1)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getFolderInfo(t,i){return b(this,void 0,void 0,(function*(){if(""===t||"/"===t)return{file_id:"0"};t.startsWith("/")||(t="/"+t);try{const i=this.config.access_token;let o=new f;o.append("path",t);const r=yield e.post(`${this.baseUrl}/open/folder/get_info`,o,{headers:Object.assign(Object.assign({},o.getHeaders()),{Authorization:`Bearer ${i}`})});return r.status>=300||!r.data.state||0===r.data.data.length?(console.error("Error getting file info:",r.data),null):r.data.data}catch(e){return console.error("Error occurred during get file info:",e),null}}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}const me=()=>{let e="";if("darwin"===process.platform){const o=i.join(m.homedir(),"Library","Mobile Documents","iCloud~com~koodoreader~expo","Documents");t.existsSync(o)&&(e=o)}return e&&t.existsSync(e)&&t.existsSync(e)?e:""};class ve{constructor(e){this.config=e,this.storagePath=e.storagePath,this.taskQueue=new E(5)}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){let s=me();if(!s)return console.error("iCloud Drive path not found"),void r(!1);let n=s+"/"+o,a=s+"/"+i.dirname(o);t.existsSync(a)||t.mkdirSync(a,{recursive:!0}),t.existsSync(n)&&t.unlinkSync(n),t.copyFile(i.join(this.storagePath,e),n,(e=>{e?(console.error("Error uploading file:",e),r(!1)):r(!0)}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){let s=me();if(!s)return console.error("iCloud Drive path not found"),void r(!1);let n=s+"/"+e,a=i.join(this.storagePath,o);if(!t.existsSync(n))return console.error("File does not exist in iCloud:",e),void r(!1);t.existsSync(a)&&t.unlinkSync(a),t.copyFile(n,a,(e=>{if(e)console.error("Error downloading file:",e),r(!1);else{let e=t.statSync(a);this.taskQueue.setDownloadedSize(e.size),r(!0)}}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const o=()=>new Promise(((o,r)=>b(this,void 0,void 0,(function*(){let r=me();if(!r)return console.error("iCloud Drive path not found"),void o([]);let s=r+"/"+e;t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.readdir(s,{withFileTypes:!0},((e,r)=>{if(e)return console.error("Error reading directory:",e),void o([]);let n=r.map((e=>{let o=i.join(s,e.name),r=t.statSync(o);return{name:e.name,size:r.size,type:e.isDirectory()?"folder":"file",modified:r.mtime.toISOString()}}));o(n)}))}))));try{return yield o()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){try{return yield new Promise(((i,o)=>{let r=me();if(!r)return console.error("iCloud Drive path not found"),void i(!1);let s=r+"/"+e;t.unlink(s,(e=>{e?(console.error("Error deleting file:",e),i(!1)):i(!0)}))}))}catch(e){return console.error(e),!1}}))}}class ke{constructor(e){this.config=e,this.storagePath=e.storagePath,this.drivePath=e.drivePath,this.taskQueue=new E(5)}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void r(!1);let s=this.drivePath+"/"+o,n=this.drivePath+"/"+i.dirname(o);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),t.existsSync(s)&&t.unlinkSync(s),t.copyFile(i.join(this.storagePath,e),s,(e=>{e?(console.error("Error uploading file:",e),r(!1)):r(!0)}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void r(!1);let s=this.drivePath+"/"+e,n=i.join(this.storagePath,o);if(!t.existsSync(s))return console.error("File does not exist in path:",e),void r(!1);t.existsSync(n)&&t.unlinkSync(n),t.copyFile(s,n,(e=>{if(e)console.error("Error downloading file:",e),r(!1);else{let e=t.statSync(n);this.taskQueue.setDownloadedSize(e.size),r(!0)}}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const o=()=>new Promise(((o,r)=>b(this,void 0,void 0,(function*(){if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void o([]);let r=this.drivePath+"/"+e;t.existsSync(r)||t.mkdirSync(r,{recursive:!0}),t.readdir(r,{withFileTypes:!0},((e,s)=>{if(e)return console.error("Error reading directory:",e),void o([]);let n=s.map((e=>{let o=i.join(r,e.name),s=t.statSync(o);return{name:e.name,size:s.size,type:e.isDirectory()?"folder":"file",modified:s.mtime.toISOString()}}));o(n)}))}))));try{return yield o()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){const i=()=>new Promise(((i,o)=>{if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void i(!1);let r=this.drivePath+"/"+e;t.unlink(r,(e=>{e?(console.error("Error deleting file:",e),i(!1)):i(!0)}))}));try{return yield i()}catch(e){return console.error(e),!1}}))}}const be=["book","config","cover","font"];class Fe{constructor(e,t){this.type=e,this.storagePath=t.storagePath,this.remote="dropbox"===e?new D(t):"microsoft"===e?new W(t):"google"===e?new K(t):"microsoft_exp"===e?new W(Object.assign(Object.assign({},t),{isExp:!0})):"google_exp"===e?new K(Object.assign(Object.assign({},t),{isExp:!0})):"s3compatible"===e?new q(t):"webdav"===e?new V(t):"docker"===e?new fe(t):"ftp"===e?new B(t):"sftp"===e?new Z(t):"boxnet"===e?new ie(t):"mega"===e?new re(t):"adrive"===e?new ne(t):"pcloud"===e?new de(t):"dubox"===e?new ue(t):"yandex"===e?new G(t):"yiyiwu"===e?new ye(t):"icloud"===e?new ve(t):"folder"===e?new ke(t):new ee}downloadFile(e,o,r){return b(this,void 0,void 0,(function*(){if(t.existsSync(i.join(this.storagePath+"/"+r))||t.mkdirSync(i.join(this.storagePath+"/"+r)),"cover"!==r){if(!(yield this.listFiles(r)).find((t=>e.indexOf(t)>-1)))return!1}return yield this.remote.downloadFile(r+"/"+e,r+"/"+o)}))}uploadFile(e,o,r){return b(this,void 0,void 0,(function*(){const s=i.join(this.storagePath,r,e);return!(!t.existsSync(s)||0!==t.statSync(s).size)||(yield this.remote.uploadFile(r+"/"+e,r+"/"+o))}))}deleteFile(e,t){return b(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.deleteFile(t+"/"+e))}))}isExist(e,t){return b(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}downloadAllFiles(){return b(this,void 0,void 0,(function*(){for(let e of be){let t=yield this.listFiles(e);for(let i of t)yield this.downloadFile(i,i,e)}}))}getAuthUrl(e){return this.remote.getAuthUrl(e)}getStats(){return this.remote.taskQueue.getStats()}clearQueue(){return this.remote.taskQueue.clearQueue()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const we={words:['ALTER TABLE words ADD COLUMN "sentence" text']},Ee={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},Se={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},Te={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function Oe(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const xe={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),void 0===t.sentence&&(t.sentence=""),t}};var Re={sqlStatement:{createTableStatement:Oe({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "sentence" text,\n "chapter" text\n );\n '}),migrateStatement:Oe(we),getAllStatement:Oe({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:Oe({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:Oe({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:Oe({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, sentence, chapter) VALUES (@key, @bookKey, @date, @word, @sentence, @chapter)"}),deleteAllStatement:Oe({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Oe({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, sentence = @sentence, chapter = @chapter WHERE key = @key"}),deleteStatement:Oe({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:Oe({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:Oe(Ee),getByBookKeyStatement:Oe(Se),getByBookKeysStatement:Oe({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),getKeysStatement:Oe({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:Oe({notes:(e,t,i,o)=>`SELECT * FROM notes ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,bookmarks:(e,t,i,o)=>`SELECT * FROM bookmarks ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,books:(e,t,i,o)=>`SELECT * FROM books ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,plugins:(e,t,i,o)=>`SELECT * FROM plugins ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,words:(e,t,i,o)=>`SELECT * FROM words ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`}),getByKeysStatement:Oe({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`}),deleteByBookKeyStatement:Oe(Te)},jsonToSqlite:Oe({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),void 0===t.sentence&&(t.sentence=""),t}}),sqliteToJson:Oe(xe)};const Ce=S,_e=T;class Pe{constructor(e,t,i){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===i?_e:Ce,this.serverRegion=i,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}refreshUserToken(){return b(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(this.baseUrl+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),yield this.TokenService.setToken("expires_at",(1e3*t.data.expires_at).toString()),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token,this.expiresAt=1e3*t.data.expires_at),t}))}requestWithRetry(e){return b(this,void 0,void 0,(function*(){return Pe.requestQueue||(Pe.requestQueue=[]),new Promise(((t,i)=>{Pe.requestQueue.push({config:e,resolve:t,reject:i}),Pe.processingQueue||this.processQueue()}))}))}isTokenValid(){return b(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return b(this,void 0,void 0,(function*(){if(!Pe.processingQueue){Pe.processingQueue=!0;try{for(;Pe.requestQueue.length>0;){const e=Pe.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{Pe.processingQueue=!1}}}))}executeRequest(t){return b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);if(t.baseURL=this.baseUrl,t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=i;else{let e=this.ConfigService.getItem("appVersion"),o=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":i,"X-App-Version":e||"1.0.0","X-App-Platform":o||"web"}}let o=(yield e(t)).data;if(402===o.code){let i=yield this.refreshUserToken();if(200===i.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return i}return 200!==o.code&&console.error("Request error:",o),o}catch(e){return console.error("Request execution error:",e),"Network Error"===e.message?{code:503,message:"network error",data:null,msg:"Network error, please try again later. 网络错误,请稍后再试。"}:{code:500,message:e.message||"Unknown error",msg:e.message||"Unknown error",data:null}}}))}requestWithStream(e,t,i){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let o=this.accessToken||"",r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((s,n)=>{let a=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const l=new i(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":r,"X-App-Version":a||"1.0.0","X-App-Platform":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});l.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),l.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(l.close(),s(i)):t(i.data)})))),l.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const i=JSON.parse(e.data);t(i.data),s(i),l.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let i=this.accessToken||"",o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((r,s)=>b(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");var a=new v(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+i,"X-Request-ID":o,"X-App-Version":s||"1.0.0","X-App-Platform":n||"web"},payload:JSON.stringify(e.data),method:"POST"});a.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(a.close(),r(i)):t(i.data)})))),a.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),a.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const i=JSON.parse(e.data);t(i.data),r(i),a.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}Pe.processingQueue=!1,Pe.requestQueue=[];class Ae extends Pe{constructor(e,t,i){super(e,t,i),this.serverRegion=i}encryptToken(e){return b(this,void 0,void 0,(function*(){let t=e.token,i=w.encode(t),{extracted:o,remaining:r}=function(e){let t="",i="",o=[],r=1;for(;r<=e.length;)o.push(r-1),r*=2;for(let r=0;r-1){let i=t.split("#");e.encrypted_token=i[1]}const i={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let o=yield this.requestWithRetry(i);if(t.indexOf("#")>-1&&o.data&&o.data.token){let e=t.split("#"),i=function(e,t){let i="",o=[],r=1,s=e.length+t.length;for(;r<=s;)o.push(r-1),r*=2;let n=0,a=0;for(let r=0;r-1&&i.splice(o,1),this.setAllListConfig(i,t)}static setListConfig(e,t){let i=this.getAllListConfig(t);const o=i.indexOf(e);o>-1?(i.splice(o,1),i.unshift(e)):i.unshift(e),this.setAllListConfig(i,t)}static setAllListConfig(e,t,i=!0){this.setItem(t,JSON.stringify(e)),i&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,i,o=!0){let r=this.getAllObjectConfig(i);r[e]=t,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(r,i)}static getObjectConfig(e,t,i){return this.getAllObjectConfig(t)[e]||i}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let i=this.getAllObjectConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(i,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,i){let o=this.getAllMapConfig(i);void 0===o[e]&&(o[e]=[]),t&&-1===o[e].indexOf(t)&&o[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,i)}static setOneMapConfig(e,t,i,o=!0){let r=this.getAllMapConfig(i);r[e]=t,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(r,i)}static deleteFromMapConfig(e,t,i){let o=this.getAllMapConfig(i),r=o[e].indexOf(t);o[e].splice(r,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,i)}static deleteFromAllMapConfig(e,t){let i=this.getAllMapConfig(t);Object.keys(i).forEach((o=>{let r=i[o].indexOf(e);r>-1&&(i[o].splice(r,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:o},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(i,t)}static deleteMapConfig(e,t){let i=this.getAllMapConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(i,t)}static getFromAllMapConfig(e,t){let i=this.getAllMapConfig(t),o=[];for(let t in i)i[t]&&i[t].indexOf(e)>-1&&o.push(t);return o}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,t){const i=e.type+"."+e.catergory+"."+e.name+"."+e.key;let o=JSON.parse(this.getItem("syncRecord")||"{}");o[i]=t,this.setItem("syncRecord",JSON.stringify(o))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var Le,ze;export{$e as ConfigService,Re as SqlStatement,Fe as SyncUtil,Ae as ThirdpartyRequest}; +import e from"axios";import t from"fs";import i from"path";import{promisify as o}from"util";import r from"stream";import{Client as s}from"basic-ftp";import{S3Client as n,ListObjectsV2Command as a,DeleteObjectCommand as d,PutObjectCommand as l,GetObjectCommand as c}from"@aws-sdk/client-s3";import{AuthType as u,createClient as h}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as g}from"megajs";import y from"crypto";import m from"os";import{SSE as v}from"sse.js";import k from"electron-store";function b(e,t,i,o){return new(i||(i=Promise))((function(r,s){function n(e){try{d(o.next(e))}catch(e){s(e)}}function a(e){try{d(o.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(n,a)}d((o=o.apply(e,t||[])).next())}))}const F=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,w={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let t="",i=0;const o=this._stringToUtf8Bytes(e),r=o.length;for(;i>2,d=(3&e)<<4|s>>4,l=(15&s)<<2|n>>6,c=63&n;t+=this._chars.charAt(a),t+=this._chars.charAt(d),t+=i-2>=r?"=":this._chars.charAt(l),t+=i-1>=r?"=":this._chars.charAt(c)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const t=[];let i=0;const o=e.length;for(;i>4,d=(15&r)<<4|s>>2,l=(3&s)<<6|n;t.push(a),-1!==s&&t.push(d),-1!==n&&t.push(l)}return this._utf8BytesToString(t)},_stringToUtf8Bytes(e){const t=[];for(let i=0;i>6),t.push(128|63&o);else if(55296==(64512&o)&&i+1>18),t.push(128|e>>12&63),t.push(128|e>>6&63),t.push(128|63&e)}else t.push(239,191,189),i--}else t.push(224|o>>12),t.push(128|o>>6&63),t.push(128|63&o)}return t},_utf8BytesToString(e){let t="",i=0;for(;i65535){const i=e-65536;t+=String.fromCharCode(55296|i>>10),t+=String.fromCharCode(56320|1023&i)}else t+=String.fromCharCode(e)}else t+="�"}else t+="�"}return t},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}};class E{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return b(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,i)=>{if(this.hasFailedTasks)return void t(void 0);const o=()=>b(this,void 0,void 0,(function*(){if(this.hasFailedTasks)return this.completedTasks++,void t(void 0);try{this.runningTasks++;const i=yield e();return this.completedTasks++,t(i),i}catch(e){throw this.completedTasks++,i(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0;){const e=this.queue.shift();e&&e()}else if(this.queue.length>0&&this.runningTasks=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=[],r=!0,s=null;for(;r;){let n;n=s?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:s},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});const a=n.data.entries||[];o=o.concat(a),r=n.data.has_more,s=n.data.cursor}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${x}&redirect_uri=${e}`}}const j=o(r.pipeline);class D extends Q{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token,n=t.createReadStream(i.join(this.storagePath,o));return yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+r,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token,n=t.createWriteStream(i.join(this.storagePath,r)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${s}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+o})},maxContentLength:1/0,maxBodyLength:1/0});let d=0;return a.data.on("data",(e=>{d+=e.length,this.taskQueue.setDownloadedSize(d)})),yield j(a.data,n),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class B{constructor(e){this.config=e,this.storagePath=e.storagePath,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client&&!1===this.client.closed)return this.client;let{url:e,username:t,password:i,dir:o,ssl:r,port:n}=this.config;const a=new s(0);a.ftp.verbose=!0;const d=a.access({host:e,port:parseInt(n),user:t,password:i,secure:"1"===r}),l=new Promise(((e,t)=>{setTimeout((()=>t(new Error("FTP connection timeout"))),5e3)}));return yield Promise.race([d,l]),this.client=a,a}catch(e){throw console.error("Error connecting to FTP server:",e),this.client=null,e}}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;const r=yield this.getClient(),s=()=>b(this,void 0,void 0,(function*(){yield r.ensureDir(i.dirname(o+"/"+t)),yield r.cd("/"),yield r.uploadFrom(i.join(this.storagePath,e),o+"/"+t)}));try{return yield s(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;const s=yield this.getClient(),n=t.createWriteStream(i.join(this.storagePath,o)),a=()=>b(this,void 0,void 0,(function*(){s.trackProgress((e=>{this.taskQueue.setDownloadedSize(e.bytes||0)})),yield s.downloadTo(n,r+"/"+e),s.trackProgress()}));try{return yield a(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.listFilesWithoutQueue(e)}))))))}))}listFilesWithoutQueue(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),o=()=>b(this,void 0,void 0,(function*(){return yield i.list(t+"/"+e)}));try{return(yield o()).map((e=>({name:e.name,size:e.size||0,type:e.isFile?"file":"folder",modified:e.modifiedAt?e.modifiedAt.toISOString():""})))}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),o=()=>b(this,void 0,void 0,(function*(){yield i.remove(t+"/"+e)}));try{return yield o(),!0}catch(e){return console.error(e),!1}}))}}class M{constructor(e){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let o,r=[];if(""===t)o=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);o=`${this.baseUrl}:/${e}:/children`}for(;o;){const t=yield e.get(o,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];r=r.concat(s),o=t.data["@odata.nextLink"]||""}return[...new Set(r.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const o=yield e.delete(`${this.baseUrl}:/${t}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${I}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${e}`}}const U=209715200;class W extends M{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=this.config.access_token;let a=this.baseFolder+"/"+r;for(;a.startsWith("/");)a=a.substring(1);const d=i.join(this.storagePath,o),l=yield this.getFileSize(d),c=a.split(".").pop(),u=(F(c||""),`${this.baseUrl}:/${a}:/createUploadSession`),h=(yield e.post(u,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.uploadUrl;n=yield t.promises.open(d,"r");let p=0,f=Buffer.alloc(U);for(;pthis.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token;let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const a=`${this.baseUrl}:/${n}:/content`;let d=(yield fetch(a,{headers:{Authorization:"Bearer "+s},redirect:"manual"})).headers.get("location");if(d){const o=yield e.get(d,{responseType:"stream"});let s=0;const n=t.createWriteStream(i.join(this.storagePath,r));return o.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),yield new Promise(((e,t)=>{o.data.pipe(n),n.on("finish",(()=>{e()})),n.on("error",t)})),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class N{constructor(e){this.isExp=!1,this.folderIdCache=new Map,this.config=e,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getFileId(t,i){return b(this,void 0,void 0,(function*(){const o=this.config.access_token,r=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${i}'+in+parents&fields=files(id,name)`;try{const t=yield e.get(r,{headers:{Authorization:"Bearer "+o}});if(0===t.data.files.length)return"";const i=t.data.files;return i.length>0?i[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return b(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const i=this.config.access_token;if(""===t)return"root";if(this.folderIdCache.has(t))return this.folderIdCache.get(t);const o=t.split("/").filter((e=>""!==e.trim()));let r="root",s="";for(const t of o){if(s=s?s+"/"+t:t,this.folderIdCache.has(s)){r=this.folderIdCache.get(s);continue}let o=yield this.getFolderId(t,r);if(!o){const s={name:t,mimeType:"application/vnd.google-apps.folder",parents:[r]};try{o=(yield e.post("https://www.googleapis.com/drive/v3/files",s,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}this.folderIdCache.set(s,o),r=o}return r}))}getFolderId(t,i){return b(this,void 0,void 0,(function*(){const o=this.config.access_token,r=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${i}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(r,{headers:{Authorization:`Bearer ${o}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=yield this.checkFolder(t),r=[],s="",n=!0;for(;n;){let t=`https://www.googleapis.com/drive/v3/files?q='${o}'+in+parents&fields=nextPageToken,files(id,name,size,mimeType)&pageSize=1000`;s&&(t+=`&pageToken=${s}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${i}`}}),d=a.data.files||[];r=r.concat(d),s=a.data.nextPageToken,n=!!s}return[...new Set(r.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return b(this,void 0,void 0,(function*(){const i=t.split("/").pop()||"",o=t.split("/").slice(0,-1).join("/"),r=yield this.checkFolder(o),s=this.config.access_token,n=yield this.getFileId(i,r);if(""===n)return console.error("File not found:",i),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${n}`,{headers:{Authorization:`Bearer ${s}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${$}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class K extends N{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token;let n=o.split("/").pop(),a=r.split(".").pop(),d=F(a||""),l=r.split("/").slice(0,-1).join("/"),c=yield this.checkFolder(l),u=yield this.getFileId(n||"",c);const h={mimeType:d,name:n,parents:[c]},p=u?`https://www.googleapis.com/upload/drive/v3/files/${u}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:u?"PATCH":"POST",url:p,data:u?null:JSON.stringify(h),headers:{Authorization:"Bearer "+s,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let g=yield this.getFileSize(i.join(this.storagePath,o));const y=t.createReadStream(i.join(this.storagePath,o));yield e.put(f,y,{headers:{Authorization:"Bearer "+s,"Content-Type":"application/zip","Content-Range":`bytes 0-${g-1}/${g}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during upload:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token;let n=o.split("/").pop(),a=o.split("/").slice(0,-1).join("/"),d=yield this.checkFolder(a),l=yield this.getFileId(n||"",d);if(!l)return console.error("File not found"),!0;const c=`https://www.googleapis.com/drive/v3/files/${l}?alt=media`;return new Promise((o=>{const n=t.createWriteStream(i.join(this.storagePath,r));e({url:c,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{let t=0;e.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),e.data.pipe(n),n.on("finish",(()=>{o(!0)})),n.on("error",(()=>{o(!1)}))})).catch((e=>{console.error("Error downloading file:",e),o(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class H{constructor(e){this.config=e,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}shouldUsePathStyle(){try{if(this.config.forcePathStyle&&"no"!==this.config.forcePathStyle)return!0;let e=this.config.endpoint;const t=new URL(e),i=t.hostname,o=/^(\d{1,3}\.){3}\d{1,3}$/.test(i),r=""!==t.port;return!o&&r}catch(e){return!0}}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:o,accessKeyId:r,secretAccessKey:s,dir:d}=this.config;d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let l=d+"/"+e;for(;l.startsWith("/");)l=l.substring(1);""===l||l.endsWith("/")||(l+="/");const c=new n({endpoint:t,region:i,credentials:{accessKeyId:r,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});try{let e,t=[],i=[],r=!0;for(;r;){const s=yield c.send(new a({Bucket:o,Prefix:l,Delimiter:"/",ContinuationToken:e}));s.Contents&&(t=t.concat(s.Contents)),s.CommonPrefixes&&(i=i.concat(s.CommonPrefixes)),e=s.NextContinuationToken,r=!!e}let s=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(l.length);t.includes("/")||s.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),i.forEach((e=>{const t=e.Prefix.substring(l.length).replace(/\/$/,"");t&&s.push({name:t,size:0,type:"folder",modified:""})})),s}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:o,accessKeyId:r,secretAccessKey:s,dir:a}=this.config;a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;const l=new n({endpoint:t,region:i,credentials:{accessKeyId:r,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});let c=a+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield l.send(new d({Bucket:o,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class q extends H{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){let{endpoint:r,region:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:u}=this.config;const h=new n({endpoint:r,region:s,credentials:{accessKeyId:d,secretAccessKey:c},forcePathStyle:this.shouldUsePathStyle()});u=u&&"KoodoReader"===this.baseFolder?u:this.baseFolder;let p=u+"/"+o;for(;p.startsWith("/");)p=p.substring(1);try{let o=yield h.send(new l({Bucket:a,Key:p,Body:t.createReadStream(i.join(this.storagePath,e))}));return 200===o.$metadata.httpStatusCode||(console.error("Error uploading file:",o),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:r,region:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:u}=this.config;u=u&&"KoodoReader"===this.baseFolder?u:this.baseFolder;const h=(e,t,i,o)=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){const s=yield e.send(new c({Bucket:t,Key:i}));let n=0;s.Body?(s.Body.on("data",(e=>{n+=e.length,this.taskQueue.setDownloadedSize(n)})),s.Body.pipe(o),o.on("finish",(e=>{e&&r(!1),r(!0)}))):r(!1)})))),p=()=>new Promise(((c,p)=>{const f=new n({region:s,endpoint:r,credentials:{accessKeyId:d,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle()});let g=t.createWriteStream(i.join(this.storagePath,o)),y=u+"/"+e;for(;y.startsWith("/");)y=y.substring(1);h(f,a,y,g).then((e=>{c(!0)})).catch((e=>{console.error(e),c(!1)}))}));try{return yield p()}catch(e){return console.error(e),!1}}))))))}))}}class J{constructor(e){let{username:t,password:i,url:o,dir:r,AuthType:s,createClient:n}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder,this.username=t,this.password=i,this.url=o,this.dir=r,this.taskQueue=new E(5),this.AuthType=s,this.createClient=n}getClient(){return b(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(t){return b(this,void 0,void 0,(function*(){try{const i=yield e.head(t,{maxRedirects:0,validateStatus:()=>!0,timeout:5e3});return i.request&&i.request.responseURL&&i.request.responseURL!==t?i.request.responseURL:i.status>=300&&i.status<400&&i.headers.location?i.headers.location:t}catch(e){return console.info("Error handling URL redirection:",e),t}}))}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{const i=t.getDirectoryContents(this.dir+"/"+e),o=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV list directory timeout"))),5e3)}));return(yield Promise.race([i,o])).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}catch(i){return i.response&&404===i.response.status&&(yield t.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",i),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return yield t.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return b(this,void 0,void 0,(function*(){let t=yield this.getClient();try{const i=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let o="";for(const e of i)o=o?`${o}/${e}`:e,(yield t.exists(`/${o}`))||(yield t.createDirectory(`/${o}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class V extends J{constructor(e){super(Object.assign(Object.assign({},e),{AuthType:u,createClient:h})),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let s=yield this.getClient();const n=s.exists(i.dirname(this.dir+"/"+r)),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([n,a]))&&(yield this.ensureDirectoryExists(i.dirname(this.dir+"/"+r)));let d=t.readFileSync(i.join(this.storagePath,o)),l=i.extname(o).substring(1),c=F(l),u=s.createWriteStream(this.dir+"/"+r,{headers:{"content-type":c,"content-length":d.length}});return t.createReadStream(i.join(this.storagePath,o)).pipe(u),new Promise(((t,i)=>{u.on("finish",(()=>{t(!0)})),u.on("error",(i=>b(this,void 0,void 0,(function*(){console.error("Error occurred during file upload:",i);try{let i=s.getFileUploadLink(this.dir+"/"+r);const o=new URL(i);o.search="",i=o.toString();const n=Buffer.from(this.username+":"+this.password,"binary").toString("base64");yield e.put(i,d,{headers:{Authorization:"Basic "+n,"Content-Type":c,"Content-Length":d.length},maxContentLength:1/0,maxBodyLength:1/0});t(!0)}catch(e){console.error("Error occurred during file upload:",e),t(!1)}}))))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===e.indexOf("."))return new ArrayBuffer(0);try{let r=yield this.getClient();if(!1===(yield r.exists(this.dir+"/"+e)))return!0;let s=0,n=t.createWriteStream(i.join(this.storagePath,o)),a=r.createReadStream(this.dir+"/"+e);return a.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),a.pipe(n),new Promise(((e,t)=>{n.on("finish",(()=>{e(!0)})),n.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class X{constructor(e){this.folderExistsCache=new Set,this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){var i,o;return b(this,void 0,void 0,(function*(){try{const r=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let s=[],n=0;const a=1e3;let d=!0;for(;d;){const l=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",limit:a,offset:n,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),c=(null===(i=l.data._embedded)||void 0===i?void 0:i.items)||[];s=s.concat(c);const u=(null===(o=l.data._embedded)||void 0===o?void 0:o.total)||0;n+=c.length,d=n({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const o=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",permanently:!1}});return 202===o.status||204===o.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(t){var i,o;return b(this,void 0,void 0,(function*(){try{const r=this.config.access_token,s=t.split("/").filter((e=>e.length>0));let n="";for(const t of s)if(n+="/"+t,!this.folderExistsCache.has(n))try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:n}}),this.folderExistsCache.add(n)}catch(t){if(404!==(null===(i=t.response)||void 0===i?void 0:i.status))return console.error("Error checking directory:",t),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(n)}`,null,{headers:{Authorization:`OAuth ${r}`}}),this.folderExistsCache.add(n)}catch(e){if(409!==(null===(o=e.response)||void 0===o?void 0:o.status))return console.error("Error creating directory:",e),!1;this.folderExistsCache.add(n)}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${R}&redirect_uri=${e}&force_confirm=true`}}const Y=o(r.pipeline);class G extends X{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token;let n=this.baseFolder+"/"+r;for(;n.startsWith("/");)n=n.substring(1);const a=n.substring(0,n.lastIndexOf("/"));if(a){if(!(yield this.ensureDirectoryExists(a)))return console.error("Failed to create directory:",a),!1}const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${s}`,"Content-Type":"application/json"},params:{path:`/${n}`,overwrite:!0}});if(200!==d.status)return console.error("Error getting upload URL:",d),!1;const l=d.data.href,c=t.createReadStream(i.join(this.storagePath,o));return yield e.put(l,c,{headers:{"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let s=this.baseFolder+"/"+o;for(;s.startsWith("/");)s=s.substring(1);try{const o=this.config.access_token,n=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:`/${s}`}});if(200!==n.status)return console.error("Error getting download URL:",n),!1;const a=n.data.href,d=t.createWriteStream(i.join(this.storagePath,r)),l=yield e({url:a,method:"GET",responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});let c=0;return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),yield Y(l.data,d),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class Z{constructor(e){this.config=e,this.storagePath=e.storagePath,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client)return this.client;let{url:e,username:t,password:i,dir:o,port:r}=this.config;const s=new p,n=s.connect({host:e||"",port:r||22,username:t||"",password:i||""}),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("SFTP connection timeout"))),5e3)}));return yield Promise.race([n,a]),this.client=s,s}catch(e){throw console.error("Error connecting to SFTP server:",e),this.client=null,e}}))}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a=t.createReadStream(i.join(this.storagePath,e)),d="/"+r+"/"+o,l="/"+r+"/"+i.dirname(o);(yield s.exists(l))||(yield s.mkdir(l,!0)),s.put(a,d).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let{dir:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a="/"+r+"/"+e,d=i.join(this.storagePath,o),l=t.createWriteStream(d);s.get(a,l).then((()=>{this.taskQueue.setDownloadedSize(l.bytesWritten||0),n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();const o=()=>new Promise(((o,r)=>b(this,void 0,void 0,(function*(){let r="/"+t+"/"+e;(yield i.exists(r))||(yield i.mkdir(r,!0),o([])),i.list(r).then((e=>{o(e.map((e=>({name:e.name,size:e.size||0,type:"d"===e.type?"folder":"file",modified:e.modifyTime}))))})).catch((e=>b(this,void 0,void 0,(function*(){console.error(e.message,"list file error"),o([])}))))}))));try{return yield o()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();try{return yield new Promise(((o,r)=>{let s="/"+t+"/"+e;i.delete(s).then((()=>{o(!0)})).catch((e=>{console.error(e.message),o(!1)}))}))}catch(e){return console.error(e),!1}}))}}class ee{downloadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}getAuthUrl(){return""}}class te{constructor(e){this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){if(""==t)return"0";const i=this.config.access_token,o=t.split("/");let r="0";for(const t of o){const o=`https://api.box.com/2.0/folders/${r}/items?fields=id,name&type=folder&limit=1000`;try{const s=(yield e.get(o,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(s)r=s.id;else{const o={name:t,parent:{id:r},type:"folder"};r=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return r}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=this.baseFolder+"/"+t;for(;o.startsWith("/");)o=o.substring(1);let r=yield this.getFolderIdByPath(o),s=[],n=0,a=!0;const d=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${r}/items`,{params:{limit:d,offset:n},headers:{Authorization:`Bearer ${i}`}}),o=t.data.entries||[];s=s.concat(o),n+=o.length,a=o.length===d&&t.data.total_count>n}return[...new Set(s.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=t.substring(0,t.lastIndexOf("/")),r=t.substring(t.lastIndexOf("/")+1);let s=this.baseFolder+"/"+o;for(;s.startsWith("/");)s=s.substring(1);const n=yield this.getFolderIdByPath(s);if(!n)return!0;const a=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,d=(yield e.get(a,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===r&&"file"===e.type));return!d||(yield e.delete(`https://api.box.com/2.0/files/${d.id}`,{headers:{Authorization:`Bearer ${i}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:_,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class ie extends te{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token,n=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)throw new Error("Folder not found");const c=yield this.listFiles(n);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const u=new f,h=JSON.stringify({name:a,parent:{id:l}});u.append("attributes",h),u.append("file",t.createReadStream(i.join(this.storagePath,o)));const p=yield e.post("https://upload.box.com/api/2.0/files/content",u,{headers:Object.assign({Authorization:`Bearer ${s}`},u.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(p.status>=300)||(console.error("Error occurred during file upload:",p),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token,n=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${l}/items?fields=id,name&type=file&limit=1000`,u=(yield e.get(c,{headers:{Authorization:`Bearer ${s}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!u)return console.error("File not found:",a),!0;const h=yield e({url:`https://api.box.com/2.0/files/${u.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${s}`}});return yield new Promise(((e,o)=>{let s=0;const n=t.createWriteStream(i.join(this.storagePath,r));h.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),h.data.pipe(n),n.on("finish",e),n.on("error",o)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class oe{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=2){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getStorage(){return b(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new g({email:e,password:t,userAgent:"KoodoReader/1.0"}).ready,this.storage}))}getRoot(){return b(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),this.root=t,this.root}))}createFolder(e,t){return b(this,void 0,void 0,(function*(){const i=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(i))return yield this.folderCreationLocks.get(i);const o=(()=>b(this,void 0,void 0,(function*(){try{let i=e.children.find((e=>e.name===t&&e.directory));return i||(i=yield e.mkdir(t),i)}finally{this.folderCreationLocks.delete(i)}})))();return this.folderCreationLocks.set(i,o),yield o}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const i=e.split("/").filter((e=>e));for(const e of i){const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return[];t=i}}return t.children.map((e=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const i=e.split("/"),o=i.pop();for(const e of i){if(!e)continue;const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return!0;t=i}const r=t.children.find((e=>e.name===o&&!e.directory));return!r||(yield r.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class re extends oe{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let r=yield this.getRoot();const s=o.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;let t=r.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(r,e)),r=t}const a=r.children.find((e=>e.name===n&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(i.join(this.storagePath,e)),l=t.statSync(i.join(this.storagePath,e)).size;return yield r.upload({name:n,size:l},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let r=yield this.getRoot();const s=e.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;const t=r.children.find((t=>t.name===e&&t.directory));if(!t)return!0;r=t}const a=r.children.find((e=>e.name===n&&!e.directory));if(!a)return!0;const d=t.createWriteStream(i.join(this.storagePath,o));let l=0;return new Promise((e=>{const t=a.download();t.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),t.pipe(d),d.on("finish",(()=>e(!0))),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class se{constructor(e){this.config=e,this.driveId="",this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getDriveId(){return b(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=this.config.access_token,i=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=i.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){const i=this.config.access_token,o=yield this.getDriveId();try{try{const r=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(r.data)return r.data.file_id}catch(r){const s=t.split("/").filter((e=>e));let n="",a="root";for(const t of s){n+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:n},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.file_id}catch(r){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=yield this.getDriveId(),r=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let s=[],n="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:r,marker:n||void 0},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),d=t.data.items.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];s=s.concat(d),n=t.data.next_marker,a=!!n}return[...new Set(s.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=yield this.getDriveId(),r=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!r||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:r},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var i;return b(this,void 0,void 0,(function*(){try{const o=this.config.access_token,r=yield this.getDriveId(),s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:r,file_path:t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(i=s.data)||void 0===i?void 0:i.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:r,file_id:s.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:L,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class ne extends se{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.access_token,n=yield this.getDriveId(),a=r.substring(0,r.lastIndexOf("/")),d=r.substring(r.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(r);const l=yield this.getFolderIdByPath(this.baseFolder+"/"+a),c=i.join(this.storagePath,o),u=yield t.promises.readFile(c),h=u.length,p=y.createHash("sha1").update(u).digest("hex"),f=y.createHash("md5").update(s).digest("hex"),g=Number(BigInt("0x"+f.slice(0,16))%BigInt(h||1)),m=u.slice(g,Math.min(g+8,h)).toString("base64"),v=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:l,name:d,type:"file",check_name_mode:"ignore",size:h,content_hash:p,content_hash_name:"sha1",proof_code:m,proof_version:"v1",part_info_list:[{part_number:1}]},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),{file_id:k,upload_id:b,rapid_upload:F,part_info_list:w}=v.data;return F?(console.info("阿里云盘秒传成功"),!0):(yield fetch(w[0].upload_url,{method:"PUT",body:u,headers:{"Content-Length":h.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:k,upload_id:b},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.access_token,n=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:this.baseFolder+"/"+o},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:n,file_id:a},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),l=yield e({url:d.data.url,method:"get",responseType:"stream"});let c=0;const u=t.createWriteStream(i.join(this.storagePath,r+".temp"));return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),l.data.pipe(u),new Promise((e=>{u.on("finish",(()=>{t.renameSync(i.join(this.storagePath,r+".temp"),i.join(this.storagePath,r)),e(!0)})),u.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class ae{constructor(e){this.baseUrl="https://api.pcloud.com",this.config=e,this.taskQueue=new E(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}checkFolderExists(t,i){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:i,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,i){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/createfolderifnotexists`,{params:{access_token:i,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:i,path:"/"+t,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.refresh_token,o=yield e.get(`${this.baseUrl}/deletefile`,{params:{access_token:i,path:"/"+t}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${C}&response_type=code&redirect_uri=${e}`}}class de extends ae{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=this.config.refresh_token,n=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(n,s))){if(!(yield this.createFolder(n,s)))return!1}const a=i.join(this.storagePath,o),d=t.createReadStream(a),l=t.statSync(a),c=i.basename(o),u=yield e({method:"put",url:`${this.baseUrl}/uploadfile`,params:{access_token:s,path:`/${n}`,renew:1,filename:c},data:d,headers:{"Content-Length":l.size,"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return 0===u.data.result||(console.error("Error uploading file:",u.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/getfilelink`,{params:{access_token:s,path:`/${o}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!1;const a=i.join(this.storagePath,r),d=t.createWriteStream(a),l=`https://${n.data.hosts[0]}${n.data.path}`,c=yield e({method:"get",url:l,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{let t=0;c.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),c.data.pipe(d),d.on("finish",(()=>{e(!0)})),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class le{constructor(e){this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=this.baseFolder;t&&""!==t.trim()&&(o=o+"/"+t),o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));let r=[],s=0;const n=1e3;for(;;){const t=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:i,dir:"/"+o,start:s,limit:n,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(t.status>=300||0!==t.data.errno){console.error("百度网盘API错误:",t.data);break}const a=t.data.list||[];if(0===a.length)break;if(r=r.concat(a),a.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path,fs_id:e.fs_id})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;let o=this.baseFolder+"/"+t;o=o.replace(/\/+/g,"/"),o.startsWith("/")&&(o=o.substring(1));const r=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+o])}),s=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${i}&opera=delete`,r.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==s.data.errno)return console.error("百度网盘删除文件API错误:",s.data),-9===s.data.errno?console.error("文件不存在"):111===s.data.errno?console.error("有其他异步任务正在执行"):-7===s.data.errno&&console.error("文件名非法"),!1;const n=s.data.info||[];for(const e of n)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${P}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}const ce=4194304;class ue extends le{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=this.config.access_token;let a=this.baseFolder+"/"+r;a=a.replace(/\/+/g,"/"),a.startsWith("/")&&(a=a.substring(1));const d=i.join(this.storagePath,o),l=yield this.getFileSize(d),{contentMd5:c,sliceMd5:u,blockList:h}=yield this.calculateFileMd5(d,l),p=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",autoinit:"1",rtype:"3",block_list:JSON.stringify(h),"content-md5":c,"slice-md5":u,local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),g=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=${s}`,p.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==g.data.errno)return console.error("预上传失败:",g.data),-7===g.data.errno?console.error("文件或目录名错误或无权访问"):-10===g.data.errno&&console.error("容量不足"),!1;const y=g.data.uploadid,m=g.data.block_list||[];if(0===m.length)return!0;const v=yield this.getUploadDomain(s,"/"+a,y);if(!v)return console.error("获取上传域名失败"),!1;n=yield t.promises.open(d,"r");for(const t of m){const i=t*ce,o=Math.min(ce,l-i),r=Buffer.alloc(o),{bytesRead:d}=yield n.read(r,0,o,i);if(0===d)break;const c=r.slice(0,d),u=h[t],p=new f;p.append("file",c,{filename:`chunk_${t}`,contentType:"application/octet-stream",knownLength:c.length});const g=`${v}/rest/2.0/pcs/superfile2?method=upload&access_token=${s}&type=tmpfile&path=${encodeURIComponent("/"+a)}&uploadid=${y}&partseq=${t}`,m=yield e.post(g,p,{headers:Object.assign(Object.assign({"User-Agent":"pan.baidu.com"},p.getHeaders()),{"Content-Length":p.getLengthSync().toString()}),maxContentLength:1/0,maxBodyLength:1/0,timeout:0});if(m.status>=300)throw 31024===m.data.errno?console.error("没有申请上传权限"):31299===m.data.errno?console.error("第一个分片的大小小于4MB"):31364===m.data.errno?console.error("超出分片大小限制"):31363===m.data.errno&&console.error("分片缺失"),new Error(`分片上传失败: ${JSON.stringify(m.data)}`);const k=m.data.md5;k&&k!==u&&console.warn(`分片 ${t} MD5不匹配: 期望 ${u}, 实际 ${k}`)}const k=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",block_list:JSON.stringify(h),uploadid:y,rtype:"3",local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),b=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=${s}`,k.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});return 0===b.data.errno||(console.error("创建文件失败:",b.data),-7===b.data.errno?console.error("文件或目录名错误或无权访问"):-8===b.data.errno?console.error("文件或目录已存在"):-10===b.data.errno?console.error("云端容量已满"):10===b.data.errno?console.error("创建文件失败,一般是分片问题"):31190===b.data.errno?console.error("文件不存在,一般是分片上传阶段有问题"):31355===b.data.errno?console.error("参数异常,一般是uploadid参数传的有问题"):31365===b.data.errno&&console.error("文件总大小超限"),!1)}catch(e){return console.error("文件上传过程中发生错误:",(null===(s=e.response)||void 0===s?void 0:s.data)||e.message||e),!1}finally{n&&(yield n.close())}}))))))}))}getUploadDomain(t,i,o){return b(this,void 0,void 0,(function*(){try{const r=yield e.get("https://d.pcs.baidu.com/rest/2.0/pcs/file",{params:{method:"locateupload",appid:"250528",access_token:t,path:i,uploadid:o,upload_version:"2.0"},headers:{"User-Agent":"pan.baidu.com"}});if(0!==r.data.error_code)return console.error("获取上传域名失败:",r.data),null;const s=r.data.servers||[],n=s.find((e=>e.server.startsWith("https://")));return n?n.server:s.length>0?s[0].server:(console.error("没有可用的上传服务器"),null)}catch(e){return console.error("获取上传域名时出错:",e),null}}))}calculateFileMd5(e,i){return b(this,void 0,void 0,(function*(){const o=yield t.promises.open(e,"r");try{const e=y.createHash("md5"),t=[];let r="",s=0;for(;sthis.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;this.taskQueue.setDownloadedSize(0);try{const n=this.config.access_token;let a,d=this.baseFolder+"/"+o;d=d.replace(/\/+/g,"/"),d.startsWith("/")&&(d=d.substring(1));let l=yield this.listFileInfos(o.substring(0,o.lastIndexOf("/")));const c=d.split("/").pop(),u=l.find((e=>e.name===c));if(!u)return console.error("文件不存在:",o),!1;const h=yield e.get("https://pan.baidu.com/rest/2.0/xpan/multimedia",{params:{method:"filemetas",access_token:n,fsids:JSON.stringify([u.fs_id]),dlink:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==h.data.errno||!(null===(s=h.data.list)||void 0===s?void 0:s[0]))return console.error("获取下载链接失败:",h.data),!1;a=h.data.list[0];const p=a.dlink,f=yield e.get(p,{responseType:"stream",params:{access_token:n},headers:{"User-Agent":"pan.baidu.com"}});let g=0;const y=t.createWriteStream(i.join(this.storagePath,r));f.data.on("data",(e=>{g+=e.length,this.taskQueue.setDownloadedSize(g)})),yield new Promise(((e,t)=>{f.data.pipe(y),y.on("finish",(()=>{e()})),y.on("error",t)}));return(yield this.getFileSize(i.join(this.storagePath,r)))===a.size||(console.error("Downloaded file size does not match expected size."),yield t.promises.unlink(i.join(this.storagePath,r)),!1)}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class he{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.taskQueue=new E(3)}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}const pe=o(r.pipeline);class fe extends he{constructor(e){super(e),this.storagePath=e.storagePath}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{r.split("/").pop();const s=r.substring(0,r.lastIndexOf("/"))||"";let n=this.listFiles("");const a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([n,a]);const d=t.createReadStream(i.join(this.storagePath,o)),l=new f;l.append("file",d);const c=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(s)}`,l,{headers:Object.assign(Object.assign({},l.getHeaders()),{Authorization:this.getAuthHeader()}),maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=o.split("/").pop()||"",n=o.substring(0,o.lastIndexOf("/"))||"",a=t.createWriteStream(i.join(this.storagePath,r)),d=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:s},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"stream"});if(d.status>=300)return console.error("Error occurred during file download:",d),a.destroy(),t.existsSync(i.join(this.storagePath,r))&&t.unlinkSync(i.join(this.storagePath,r)),!1;let l=0;return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield pe(d.data,a),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ge{constructor(e){this.baseUrl="https://proapi.115.com",this.config=e,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}getUploadCredentials(t){return b(this,void 0,void 0,(function*(){try{const i=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${t}`}});return i.status>=300||!i.data.state?(console.error("Error getting upload credentials:",i.data),null):i.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,t,i=new Date(Date.now()+36e5)){const o={expiration:i.toISOString(),conditions:[{bucket:e},{key:t},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(o)}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${A}&response_type=code&redirect_uri=${e}`}}class ye extends ge{constructor(e){super(e),this.storagePath=e.storagePath}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var o;try{const o=this.config.access_token;let r=this.baseFolder+"/"+t;r.startsWith("/")||(r="/"+r);let s=i.dirname(r),n=yield this.getFolderInfo(s,!0),a="0";if(n)a=n.file_id;else{let e=yield this.createFolder(s);if(!e)return console.error("Failed to create folder:",s),!1;a=e}const d=i.join(this.storagePath,e),l=yield this.getFileSize(d),c=yield this.calculateFileSha1(d),u=yield this.calculatePreSha1(d),h=i.basename(t);yield this.deleteFileWithoutQueue(t);let p=yield this.initializeUpload(a,h,l,c,u,o);if(!p)return console.error("Failed to initialize upload"),!1;if((6===p.status||7===p.status||8===p.status)&&(p=yield this.handleSecondAuth(a,p,d,h,l,c,u,o),!p))return console.error("Second authentication failed"),!1;if(2===p.status)return console.info(`File ${e} uploaded successfully via instant upload.`),!0;const f=yield this.getUploadCredentials(o);if(!f)return console.error("Failed to get upload credentials"),!1;return(yield this.uploadToObjectStorage(d,p,f))?(console.info(`File ${e} uploaded successfully.`),!0):(console.error("Failed to upload to object storage"),!1)}catch(e){return console.error("Error occurred during file upload:",(null===(o=e.response)||void 0===o?void 0:o.data)||e.message||e),!1}}))))))}))}calculateFileSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{const r=y.createHash("sha1"),s=t.createReadStream(e);s.on("data",(e=>{r.update(e)})),s.on("end",(()=>{i(r.digest("hex"))})),s.on("error",(e=>{o(e)}))}))}))}calculatePreSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{const r=y.createHash("sha1"),s=t.createReadStream(e,{start:0,end:131071});s.on("data",(e=>{r.update(e)})),s.on("end",(()=>{i(r.digest("hex"))})),s.on("error",(e=>{o(e)}))}))}))}handleSecondAuth(e,i,o,r,s,n,a,d){return b(this,void 0,void 0,(function*(){try{if(!i.sign_check)return console.error("No sign_check provided for second authentication"),null;const[l,c]=i.sign_check.split("-"),u=parseInt(l),h=parseInt(c),p=Buffer.alloc(h-u+1),f=yield t.promises.open(o,"r");try{yield f.read(p,0,p.length,u);const t=y.createHash("sha1");t.update(p);const o=t.digest("hex").toUpperCase();return yield this.initializeUpload(e,r,s,n,a,d,i.sign_key,o,i.pick_code)}finally{yield f.close()}}catch(e){return console.error("Error during second authentication:",e),null}}))}calculateOSSSignature(e,t){const i=Buffer.from(t).toString("base64");return y.createHmac("sha1",e).update(i).digest("base64")}uploadToObjectStorage(o,r,s){var n;return b(this,void 0,void 0,(function*(){try{const n=s.endpoint,a=r.bucket,d=r.object;let l;if(n.includes(a))l=n;else{l=`https://${a}.${n.replace(/^https?:\/\//,"")}`}const c=this.generateOSSPolicy(a,d),u=this.calculateOSSSignature(s.AccessKeySecret,c),h=Buffer.from(c).toString("base64"),p=new f;if(p.append("key",d),p.append("policy",h),p.append("OSSAccessKeyId",s.AccessKeyId),p.append("signature",u),p.append("x-oss-security-token",s.SecurityToken),p.append("success_action_status","200"),r.callback&&r.callback.callback){const e=Buffer.from(r.callback.callback).toString("base64");if(p.append("callback",e),r.callback.callback_var){const e=JSON.parse(r.callback.callback_var);for(const[t,i]of Object.entries(e))p.append(t,String(i))}}const g=t.createReadStream(o);p.append("file",g,i.basename(o));const y=yield e.post(l,p,{headers:Object.assign({},p.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return 200===y.status||204===y.status||(console.error("Upload failed with status:",y.status),!1)}catch(e){return console.error("Error uploading file via REST API:",(null===(n=e.response)||void 0===n?void 0:n.data)||e.message||e),!1}}))}downloadFile(o,r){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let s=this.baseFolder+"/"+o;s=s.replace(/\/+/g,"/"),s.startsWith("/")||(s="/"+s);const n=yield this.getFolderInfo(s,!1);if(!n||!n.pick_code)return console.error("Failed to get file info or pick_code for:",o),!1;const a=yield this.getFileDownloadUrl(n.pick_code);if(!a)return console.error("Failed to get download URL for:",o),!1;const d=yield e.get(a.url,{responseType:"stream"});let l=0;const c=t.createWriteStream(i.join(this.storagePath,r));return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield new Promise(((e,t)=>{d.data.pipe(c),c.on("finish",(()=>{e()})),c.on("error",t)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;(t=this.baseFolder+"/"+t).startsWith("/")||(t="/"+t);let o=[],r=0;const s=1150;let n=!0,a=yield this.getFolderInfo(t,!0),d="";if(a)d=a.file_id;else{let e=yield this.createFolder(t);if(!e)return console.error("Failed to create folder:",t),[];d=e}if(!d)return console.error("Failed to get or create folder ID:",t),[];let l=d;for(;n;){const t={offset:r,limit:s,cur:1,show_dir:1};l&&(t.cid=l);const a=yield e.get(`${this.baseUrl}/open/ufile/files`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},params:t});if(a.status>=300)break;const d=a.data.data||[];o=o.concat(d),d.length({name:e.fn,size:e.fs||0,type:"0"===e.fc?"folder":"file",modified:new Date(1e3*e.upt).toISOString()})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}getFileDownloadUrl(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=new f;o.append("pick_code",t);const r=yield e.post(`${this.baseUrl}/open/ufile/downurl`,o,{headers:Object.assign({Authorization:`Bearer ${i}`},o.getHeaders())});if(r.status>=300)return console.error("Error getting download URL:",r.data),null;const s=r.data.data,n=Object.keys(s)[0];return n&&s[n]?s[n].url:(console.error("No file data found in download URL response"),null)}catch(e){return console.error("Error occurred during get download URL:",e),null}}))}initializeUpload(t,i,o,r,s,n,a,d,l){return b(this,void 0,void 0,(function*(){try{const c=new f;c.append("file_name",i),c.append("file_size",o.toString()),t?c.append("target","U_1_"+t):c.append("target","U_1_0"),c.append("fileid",r),c.append("preid",s),c.append("topupload","0"),l&&c.append("pick_code",l),a&&c.append("sign_key",a),d&&c.append("sign_val",d);const u=yield e.post(`${this.baseUrl}/open/upload/init`,c,{headers:Object.assign({Authorization:`Bearer ${n}`},c.getHeaders())});return u.status>=300||!u.data.state?(console.error("Error initializing upload:",u.data),null):u.data.data}catch(e){return console.error("Error occurred during upload initialization:",e),null}}))}createFolder(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=t.replace(/^\/+|\/+$/g,"");if(!o)return"";const r=o.split("/");let s="",n="0";for(const t of r){s=s?`${s}/${t}`:t;const o=yield this.getFolderInfo(s,!0);if(o&&o.file_id)n=o.file_id;else{const o=new f;o.append("pid",n),o.append("file_name",t);const r=yield e.post(`${this.baseUrl}/open/folder/add`,o,{headers:Object.assign({Authorization:`Bearer ${i}`},o.getHeaders())});if(r.status>=300||!r.data.state)return console.error("Error creating folder:",r.data),"";n=r.data.data.file_id}}return n}catch(e){return console.error("Error occurred during folder creation:",e),""}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const i=this.config.access_token;t=this.baseFolder+"/"+t;let o=yield this.getFolderInfo(t,!1);if(!o)return!0;let r=new f;r.append("file_ids",o.file_id);const s=yield e.post(`${this.baseUrl}/open/ufile/delete`,r,{headers:Object.assign({Authorization:`Bearer ${i}`},r.getHeaders())});return!(s.status>=300||!s.data.state)||(console.error("Error deleting file:",s),!1)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getFolderInfo(t,i){return b(this,void 0,void 0,(function*(){if(""===t||"/"===t)return{file_id:"0"};t.startsWith("/")||(t="/"+t);try{const i=this.config.access_token;let o=new f;o.append("path",t);const r=yield e.post(`${this.baseUrl}/open/folder/get_info`,o,{headers:Object.assign(Object.assign({},o.getHeaders()),{Authorization:`Bearer ${i}`})});return r.status>=300||!r.data.state||0===r.data.data.length?(console.error("Error getting file info:",r.data),null):r.data.data}catch(e){return console.error("Error occurred during get file info:",e),null}}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}const me=()=>{let e="";if("darwin"===process.platform){const o=i.join(m.homedir(),"Library","Mobile Documents","iCloud~com~koodoreader~expo","Documents");t.existsSync(o)&&(e=o)}return e&&t.existsSync(e)&&t.existsSync(e)?e:""};class ve{constructor(e){this.config=e,this.storagePath=e.storagePath,this.taskQueue=new E(5)}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){let s=me();if(!s)return console.error("iCloud Drive path not found"),void r(!1);let n=s+"/"+o,a=s+"/"+i.dirname(o);t.existsSync(a)||t.mkdirSync(a,{recursive:!0}),t.existsSync(n)&&t.unlinkSync(n),t.copyFile(i.join(this.storagePath,e),n,(e=>{e?(console.error("Error uploading file:",e),r(!1)):r(!0)}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){let s=me();if(!s)return console.error("iCloud Drive path not found"),void r(!1);let n=s+"/"+e,a=i.join(this.storagePath,o);if(!t.existsSync(n))return console.error("File does not exist in iCloud:",e),void r(!1);t.existsSync(a)&&t.unlinkSync(a),t.copyFile(n,a,(e=>{if(e)console.error("Error downloading file:",e),r(!1);else{let e=t.statSync(a);this.taskQueue.setDownloadedSize(e.size),r(!0)}}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const o=()=>new Promise(((o,r)=>b(this,void 0,void 0,(function*(){let r=me();if(!r)return console.error("iCloud Drive path not found"),void o([]);let s=r+"/"+e;t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.readdir(s,{withFileTypes:!0},((e,r)=>{if(e)return console.error("Error reading directory:",e),void o([]);let n=r.map((e=>{let o=i.join(s,e.name),r=t.statSync(o);return{name:e.name,size:r.size,type:e.isDirectory()?"folder":"file",modified:r.mtime.toISOString()}}));o(n)}))}))));try{return yield o()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){try{return yield new Promise(((i,o)=>{let r=me();if(!r)return console.error("iCloud Drive path not found"),void i(!1);let s=r+"/"+e;t.unlink(s,(e=>{e?(console.error("Error deleting file:",e),i(!1)):i(!0)}))}))}catch(e){return console.error(e),!1}}))}}class ke{constructor(e){this.config=e,this.storagePath=e.storagePath,this.drivePath=e.drivePath,this.taskQueue=new E(5)}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let i=0;for(;;){const o=yield e();if(o)return o;if(i>=t)return this.taskQueue.hasFailedTasks=!0,o;i++;const r=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${r}ms`),yield new Promise((e=>setTimeout(e,r)))}}))}uploadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void r(!1);let s=this.drivePath+"/"+o,n=this.drivePath+"/"+i.dirname(o);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),t.existsSync(s)&&t.unlinkSync(s),t.copyFile(i.join(this.storagePath,e),s,(e=>{e?(console.error("Error uploading file:",e),r(!1)):r(!0)}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=()=>new Promise(((r,s)=>b(this,void 0,void 0,(function*(){if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void r(!1);let s=this.drivePath+"/"+e,n=i.join(this.storagePath,o);if(!t.existsSync(s))return console.error("File does not exist in path:",e),void r(!1);t.existsSync(n)&&t.unlinkSync(n),t.copyFile(s,n,(e=>{if(e)console.error("Error downloading file:",e),r(!1);else{let e=t.statSync(n);this.taskQueue.setDownloadedSize(e.size),r(!0)}}))}))));try{return yield r()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const o=()=>new Promise(((o,r)=>b(this,void 0,void 0,(function*(){if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void o([]);let r=this.drivePath+"/"+e;t.existsSync(r)||t.mkdirSync(r,{recursive:!0}),t.readdir(r,{withFileTypes:!0},((e,s)=>{if(e)return console.error("Error reading directory:",e),void o([]);let n=s.map((e=>{let o=i.join(r,e.name),s=t.statSync(o);return{name:e.name,size:s.size,type:e.isDirectory()?"folder":"file",modified:s.mtime.toISOString()}}));o(n)}))}))));try{return yield o()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){const i=()=>new Promise(((i,o)=>{if(!this.drivePath||!t.existsSync(this.drivePath))return console.error("Drive path not found"),void i(!1);let r=this.drivePath+"/"+e;t.unlink(r,(e=>{e?(console.error("Error deleting file:",e),i(!1)):i(!0)}))}));try{return yield i()}catch(e){return console.error(e),!1}}))}}const be=["book","config","cover","font"];class Fe{constructor(e,t){this.type=e,this.storagePath=t.storagePath,this.remote="dropbox"===e?new D(t):"microsoft"===e?new W(t):"google"===e?new K(t):"microsoft_exp"===e?new W(Object.assign(Object.assign({},t),{isExp:!0})):"google_exp"===e?new K(Object.assign(Object.assign({},t),{isExp:!0})):"s3compatible"===e?new q(t):"webdav"===e?new V(t):"docker"===e?new fe(t):"ftp"===e?new B(t):"sftp"===e?new Z(t):"boxnet"===e?new ie(t):"mega"===e?new re(t):"adrive"===e?new ne(t):"pcloud"===e?new de(t):"dubox"===e?new ue(t):"yandex"===e?new G(t):"yiyiwu"===e?new ye(t):"icloud"===e?new ve(t):"folder"===e?new ke(t):new ee}downloadFile(e,o,r){return b(this,void 0,void 0,(function*(){if(t.existsSync(i.join(this.storagePath+"/"+r))||t.mkdirSync(i.join(this.storagePath+"/"+r)),"cover"!==r){if(!(yield this.listFiles(r)).find((t=>e.indexOf(t)>-1)))return!1}return yield this.remote.downloadFile(r+"/"+e,r+"/"+o)}))}uploadFile(e,o,r){return b(this,void 0,void 0,(function*(){const s=i.join(this.storagePath,r,e);return!(!t.existsSync(s)||0!==t.statSync(s).size)||(yield this.remote.uploadFile(r+"/"+e,r+"/"+o))}))}deleteFile(e,t){return b(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.deleteFile(t+"/"+e))}))}isExist(e,t){return b(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}downloadAllFiles(){return b(this,void 0,void 0,(function*(){for(let e of be){let t=yield this.listFiles(e);for(let i of t)yield this.downloadFile(i,i,e)}}))}getAuthUrl(e){return this.remote.getAuthUrl(e)}getStats(){return this.remote.taskQueue.getStats()}clearQueue(){return this.remote.taskQueue.clearQueue()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const we={words:['ALTER TABLE words ADD COLUMN "sentence" text']},Ee={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},Se={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},Te={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function Oe(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const xe={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),void 0===t.sentence&&(t.sentence=""),t}};var Re={sqlStatement:{createTableStatement:Oe({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "sentence" text,\n "chapter" text\n );\n '}),migrateStatement:Oe(we),getAllStatement:Oe({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:Oe({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:Oe({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:Oe({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, sentence, chapter) VALUES (@key, @bookKey, @date, @word, @sentence, @chapter)"}),deleteAllStatement:Oe({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Oe({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, sentence = @sentence, chapter = @chapter WHERE key = @key"}),deleteStatement:Oe({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:Oe({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:Oe(Ee),getByBookKeyStatement:Oe(Se),getByBookKeysStatement:Oe({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),getKeysStatement:Oe({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:Oe({notes:(e,t,i,o)=>`SELECT * FROM notes ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,bookmarks:(e,t,i,o)=>`SELECT * FROM bookmarks ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,books:(e,t,i,o)=>`SELECT * FROM books ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,plugins:(e,t,i,o)=>`SELECT * FROM plugins ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`,words:(e,t,i,o)=>`SELECT * FROM words ORDER BY ${e} ${t} LIMIT ${i} OFFSET ${o}`}),getByKeysStatement:Oe({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`}),deleteByBookKeyStatement:Oe(Te)},jsonToSqlite:Oe({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),void 0===t.sentence&&(t.sentence=""),t}}),sqliteToJson:Oe(xe)};const Ce=T,_e=S;class Pe{constructor(e,t,i){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===i?_e:Ce,this.serverRegion=i,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}refreshUserToken(){return b(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(this.baseUrl+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),yield this.TokenService.setToken("expires_at",(1e3*t.data.expires_at).toString()),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token,this.expiresAt=1e3*t.data.expires_at),t}))}requestWithRetry(e){return b(this,void 0,void 0,(function*(){return Pe.requestQueue||(Pe.requestQueue=[]),new Promise(((t,i)=>{Pe.requestQueue.push({config:e,resolve:t,reject:i}),Pe.processingQueue||this.processQueue()}))}))}isTokenValid(){return b(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return b(this,void 0,void 0,(function*(){if(!Pe.processingQueue){Pe.processingQueue=!0;try{for(;Pe.requestQueue.length>0;){const e=Pe.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{Pe.processingQueue=!1}}}))}executeRequest(t){return b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);if(t.baseURL=this.baseUrl,t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=i;else{let e=this.ConfigService.getItem("appVersion"),o=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":i,"X-App-Version":e||"1.0.0","X-App-Platform":o||"web"}}let o=(yield e(t)).data;if(402===o.code){let i=yield this.refreshUserToken();if(200===i.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return i}return 200!==o.code&&console.error("Request error:",o),o}catch(e){return console.error("Request execution error:",e),"Network Error"===e.message?{code:503,message:"network error",data:null,msg:"Network error, please try again later. 网络错误,请稍后再试。"}:{code:500,message:e.message||"Unknown error",msg:e.message||"Unknown error",data:null}}}))}requestWithStream(e,t,i){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let o=this.accessToken||"",r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((s,n)=>{let a=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const l=new i(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":r,"X-App-Version":a||"1.0.0","X-App-Platform":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});l.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),l.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(l.close(),s(i)):t(i.data)})))),l.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const i=JSON.parse(e.data);t(i.data),s(i),l.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let i=this.accessToken||"",o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((r,s)=>b(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");var a=new v(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+i,"X-Request-ID":o,"X-App-Version":s||"1.0.0","X-App-Platform":n||"web"},payload:JSON.stringify(e.data),method:"POST"});a.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(a.close(),r(i)):t(i.data)})))),a.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),a.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const i=JSON.parse(e.data);t(i.data),r(i),a.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}Pe.processingQueue=!1,Pe.requestQueue=[];class Ae extends Pe{constructor(e,t,i){super(e,t,i),this.serverRegion=i}encryptToken(e){return b(this,void 0,void 0,(function*(){let t=e.token,i=w.encode(t),{extracted:o,remaining:r}=function(e){let t="",i="",o=[],r=1;for(;r<=e.length;)o.push(r-1),r*=2;for(let r=0;r-1){let i=t.split("#");e.encrypted_token=i[1]}const i={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let o=yield this.requestWithRetry(i);if(t.indexOf("#")>-1&&o.data&&o.data.token){let e=t.split("#"),i=function(e,t){let i="",o=[],r=1,s=e.length+t.length;for(;r<=s;)o.push(r-1),r*=2;let n=0,a=0;for(let r=0;r-1&&i.splice(o,1),this.setAllListConfig(i,t)}static setListConfig(e,t){let i=this.getAllListConfig(t);const o=i.indexOf(e);o>-1?(i.splice(o,1),i.unshift(e)):i.unshift(e),this.setAllListConfig(i,t)}static setAllListConfig(e,t,i=!0){this.setItem(t,JSON.stringify(e)),i&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,i,o=!0){let r=this.getAllObjectConfig(i);r[e]=t,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(r,i)}static getObjectConfig(e,t,i){return this.getAllObjectConfig(t)[e]||i}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let i=this.getAllObjectConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(i,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,i){let o=this.getAllMapConfig(i);void 0===o[e]&&(o[e]=[]),t&&-1===o[e].indexOf(t)&&o[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,i)}static setOneMapConfig(e,t,i,o=!0){let r=this.getAllMapConfig(i);r[e]=t,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(r,i)}static deleteFromMapConfig(e,t,i){let o=this.getAllMapConfig(i),r=o[e].indexOf(t);o[e].splice(r,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,i)}static deleteFromAllMapConfig(e,t){let i=this.getAllMapConfig(t);Object.keys(i).forEach((o=>{let r=i[o].indexOf(e);r>-1&&(i[o].splice(r,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:o},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(i,t)}static deleteMapConfig(e,t){let i=this.getAllMapConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(i,t)}static getFromAllMapConfig(e,t){let i=this.getAllMapConfig(t),o=[];for(let t in i)i[t]&&i[t].indexOf(e)>-1&&o.push(t);return o}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,t){const i=e.type+"."+e.catergory+"."+e.name+"."+e.key;let o=JSON.parse(this.getItem("syncRecord")||"{}");o[i]=t,this.setItem("syncRecord",JSON.stringify(o))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var Le,ze;export{$e as ConfigService,Re as SqlStatement,Fe as SyncUtil,Ae as ThirdpartyRequest}; diff --git a/src/components/popups/popupAssist/component.tsx b/src/components/popups/popupAssist/component.tsx index a3a59ed8..27c8cd53 100644 --- a/src/components/popups/popupAssist/component.tsx +++ b/src/components/popups/popupAssist/component.tsx @@ -467,7 +467,6 @@ class PopupAssist extends React.Component { } toast.loading(this.props.t("Please wait"), { id: "report-feedback" }); try { - console.log("Reporting answer:", this.props.userInfo); await axios.post("https://api.koodoreader.com/api/llm_report", { answer: content, question: userMessage?.content || "",