/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/picgo@3.1.0/dist/index.cjs.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";require("dotenv/config");var e=require("fs-extra"),t=require("path"),i=require("events"),n=require("os"),r=require("commander"),o=require("inquirer"),s=require("image-size-next"),a=require("url"),c=require("node:process"),l=require("node:util"),_=require("chalk"),u=require("lodash"),E=require("comment-json"),d=require("axios"),p=require("node:crypto"),I=require("crypto"),g=require("util"),C=require("node:fs/promises"),f=require("@picgo/store"),h=require("dayjs"),L=require("mime-types"),O=require("md5"),U=require("node:path"),m=require("node:fs"),D=require("write-file-atomic"),N=require("resolve"),P=require("child_process"),A=require("is-wsl"),S=require("form-data"),T=require("https"),R=require("tunnel"),y=require("cross-spawn"),M=require("js-yaml"),G=require("@picgo/i18n"),B=require("@hono/node-server"),w=require("@hono/node-server/serve-static"),x=require("hono"),b=require("hono/logger"),v=require("hono/cors");function $(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(i){if("default"!==i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}}),t.default=e,Object.freeze(t)}var F=$(p);const H=e=>{const t=`${!0===e.global?"g":""}${!0===e.ignoreCase?"i":""}`;return new RegExp(e.match,t)},Y=(e,t,i)=>{if(e.imgUrl)for(const n of t){if(!(!1!==n.enable))continue;let t;try{t=H(n)}catch(e){i.log.error(e);continue}if(!t.test(e.imgUrl))continue;const r=e.imgUrl,o=r.replace(t,n.replace);if(o!==r&&void 0===e.originImgUrl&&(e.originImgUrl=r),e.imgUrl=o,""===o){const e=i.i18n?.translate("URL_REWRITE_EMPTY_RESULT")??"URL_REWRITE_EMPTY_RESULT";i.log.warn(e)}break}};function k(e,t){return e.map(e=>{const i={...e};if("function"==typeof e.choices){const n=e.choices;i.choices=i=>{try{return n(i)}catch(i){return t?.onError?.(e.name,"choices",i),[{name:e.name,value:null}]}}}if("function"==typeof e.default){const n=e.default;i.default=i=>{try{return n(i)}catch(i){return void t?.onError?.(e.name,"default",i)}}}return i})}const V={handle:e=>{const t=e.cmd;t.program.command("install <plugins...>").description("install picgo plugin").alias("add").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action((t,i)=>{const{proxy:n,registry:r}=i,o={npmProxy:n,npmRegistry:r};e.pluginHandler.install(t,o).catch(t=>{e.log.error(t)})}),t.program.command("uninstall <plugins...>").alias("rm").description("uninstall picgo plugin").action(t=>{e.pluginHandler.uninstall(t).catch(t=>{e.log.error(t)})}),t.program.command("update <plugins...>").description("update picgo plugin").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action((t,i)=>{const{proxy:n,registry:r}=i,o={npmProxy:n,npmRegistry:r};e.pluginHandler.update(t,o).catch(t=>{e.log.error(t)})})}},K={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},q=/^wsl(?:\$|\.localhost)[\\/]/i,j=(e,t=process.platform)=>{if("win32"!==t||!q.test(e))return e;return`\\\\${e.replaceAll("/","\\").replace(/\\+/g,"\\")}`},W=e=>e.startsWith("http://")||e.startsWith("https://"),Q=e=>{if(!e)return"";try{return new a.URL(e).href}catch(t){if(e.startsWith("//"))try{return new a.URL("http:"+e).href.slice(5)}catch(e){}return encodeURI(e)}},z=(...e)=>e.join("").replace(/\/{2,}/g,"/").split("/").map(e=>encodeURIComponent(e)).join("/"),J=e=>{try{const{width:t=0,height:i=0,type:n}=s.imageSize(e);return{real:!0,width:t,height:i,extname:n?`.${n}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},X=async i=>{const n=j(i);try{return{extname:t.extname(n),fileName:t.basename(n),filePath:n,buffer:await e.readFile(n),success:!0}}catch{return{reason:`read file ${n} error`,success:!1}}},Z=async(e,i)=>{e=Q(e);let n,r=!1,o="";const s=new Promise((s,c)=>{(async()=>{try{const c=await i.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then(e=>{const t=e.headers["content-type"];return t?.includes("image")&&(r=!0,o=`.${t.split("image/")[1]}`),e.data});clearTimeout(n);const l=new a.URL(e).pathname,_=decodeURIComponent(t.basename(l));s(r?{buffer:c,fileName:_,extname:o||t.extname(_)||".png",success:!0}:{buffer:c,fileName:_,extname:t.extname(_)||".png",success:!0})}catch(t){clearTimeout(n),s({success:!1,reason:`request ${e} error, ${t?.message??""}`})}})().catch(c)}),c=new Promise(t=>{n=setTimeout(()=>{t({success:!1,reason:`request ${e} timeout`})},1e4)});return Promise.race([s,c])},ee=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":te(e)?"simple":"unknown",te=i=>{if(t.isAbsolute(i))return!1;const n=t.join(process.cwd(),i);return!e.existsSync(n)&&(!i.includes("/")&&!i.includes("\\"))},ie=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,ne=(i,n=console)=>{switch(ee(i)){case"normal":case"scope":return i;case"simple":return ie(i);default:{let r=i;return t.isAbsolute(i)&&e.existsSync(i)?oe(r):(r=t.join(process.cwd(),i),e.existsSync(r)?oe(r):(n.warn(`Can't find plugin ${i}`),""))}}},re=(i,n=console)=>{switch(ee(i)){case"normal":return se(i);case"scope":return se(i,!0);case"simple":return se(ie(i));default:{if(!e.existsSync(i))return n.warn(`Can't find plugin: ${i}`),"";const r=t.posix.join(i,"package.json");if(e.existsSync(r)){const t=e.readJSONSync(r)||{};return t.name?.includes("picgo-plugin-")?t.name:(n.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return n.warn(`Can't find plugin: ${i}`),""}}},oe=e=>e.split(t.sep).join("/"),se=(e,t=!1)=>{if(e.includes("@")){let i=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(i=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const n=e.match(i);return n?n[2]:(console.warn("can not remove plugin version"),e)}return e},ae=[],ce=e=>ae.some(t=>e.startsWith(t)),le=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function _e(e){try{return JSON.parse(e)}catch(t){return e}}const ue=(e=0)=>isNaN(Number(e))?0:Number(e),Ee=()=>"development"===process.env.NODE_ENV;var de,pe,Ie,ge,Ce,fe,he=Object.freeze({__proto__:null,configBlackList:ae,forceNumber:ue,getFSFile:X,getImageSize:J,getNormalPluginName:re,getPluginNameType:ee,getProcessPluginName:ne,getURLFile:Z,handleCompletePluginName:ie,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleUnixStylePath:oe,handleUrlEncode:Q,handleUrlPathSafeEncode:z,isConfigKeyInBlackList:ce,isDev:Ee,isInputConfigValid:le,isProd:()=>"production"===process.env.NODE_ENV,isSimpleName:te,isUrl:W,removePluginVersion:se,safeParse:_e});exports.AlbumListOrder=void 0,(de=exports.AlbumListOrder||(exports.AlbumListOrder={})).ASC="asc",de.DESC="desc",exports.AlbumListSort=void 0,(pe=exports.AlbumListSort||(exports.AlbumListSort={})).NEWEST="newest",pe.OLDEST="oldest",pe.FILE_NAME="fileName",exports.OutputFormat=void 0,(Ie=exports.OutputFormat||(exports.OutputFormat={})).PRETTY="pretty",Ie.JSON="json",exports.ILogType=void 0,(ge=exports.ILogType||(exports.ILogType={})).success="success",ge.info="info",ge.warn="warn",ge.error="error",ge.debug="debug",exports.IBuildInEvent=void 0,(Ce=exports.IBuildInEvent||(exports.IBuildInEvent={})).UPLOAD_PROGRESS="uploadProgress",Ce.FILE_UPLOAD_PROGRESS="fileUploadProgress",Ce.FAILED="failed",Ce.BEFORE_TRANSFORM="beforeTransform",Ce.BEFORE_UPLOAD="beforeUpload",Ce.AFTER_UPLOAD="afterUpload",Ce.CLOUD_IMPORT_PROGRESS="cloudImportProgress",Ce.CLOUD_ALBUM_UPDATED="cloudAlbumUpdated",Ce.FINISHED="finished",Ce.INSTALL="install",Ce.UNINSTALL="uninstall",Ce.UPDATE="update",Ce.NOTIFICATION="notification",exports.LifecycleStep=void 0,(fe=exports.LifecycleStep||(exports.LifecycleStep={})).IDLE="idle",fe.BEFORE_TRANSFORM="beforeTransform",fe.TRANSFORM="transform",fe.BEFORE_UPLOAD="beforeUpload",fe.UPLOAD="upload",fe.AFTER_UPLOAD="afterUpload",exports.IBusEvent=void 0,(exports.IBusEvent||(exports.IBusEvent={})).CONFIG_CHANGE="CONFIG_CHANGE";const Le="picgo-clipboard-images",Oe="picgo-cloud",Ue="picgoCloudAutoImport",me=1048576,De=(e,t,i,n)=>{if("length"===i||"prototype"===i)return;if("arguments"===i||"caller"===i)return;const r=Object.getOwnPropertyDescriptor(e,i),o=Object.getOwnPropertyDescriptor(t,i);!Ne(r,o)&&n||Object.defineProperty(e,i,o)},Ne=function(e,t){return void 0===e||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Pe=(e,t)=>`/* Wrapped ${e}*/\n${t}`,Ae=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Se=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name");function Te(e,t,{ignoreNonConfigurable:i=!1}={}){const{name:n}=e;for(const n of Reflect.ownKeys(t))De(e,t,n,i);return((e,t)=>{const i=Object.getPrototypeOf(t);i!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,i)})(e,t),((e,t,i)=>{const n=""===i?"":`with ${i.trim()}() `,r=Pe.bind(null,n,t.toString());Object.defineProperty(r,"name",Se);const{writable:o,enumerable:s,configurable:a}=Ae;Object.defineProperty(e,"toString",{value:r,writable:o,enumerable:s,configurable:a})})(e,t,n),e}const Re=new WeakMap,ye=(e,t={})=>{if("function"!=typeof e)throw new TypeError("Expected a function");let i,n=0;const r=e.displayName||e.name||"<anonymous>",o=function(...s){if(Re.set(o,++n),1===n)i=e.apply(this,s),e=void 0;else if(!0===t.throw)throw new Error(`Function \`${r}\` can only be called once`);return i};return Te(o,e),Re.set(o,n),o};ye.callCount=e=>{if(!Re.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Re.get(e)};const Me=[];Me.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Me.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Me.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");const Ge=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,Be=Symbol.for("signal-exit emitter"),we=globalThis,xe=Object.defineProperty.bind(Object);class be{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(we[Be])return we[Be];xe(we,Be,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const i=this.listeners[e],n=i.indexOf(t);-1!==n&&(0===n&&1===i.length?i.length=0:i.splice(n,1))}emit(e,t,i){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(const r of this.listeners[e])n=!0===r(t,i)||n;return"exit"===e&&(n=this.emit("afterExit",t,i)||n),n}}class ve{}const $e=globalThis.process,{onExit:Fe}=(He=Ge($e)?new class extends ve{#e="win32"===$e.platform?"SIGINT":"SIGHUP";#t=new be;#i;#n;#r;#o={};#s=!1;constructor(e){super(),this.#i=e,this.#o={};for(const t of Me)this.#o[t]=()=>{const i=this.#i.listeners(t);let{count:n}=this.#t;const r=e;if("object"==typeof r.__signal_exit_emitter__&&"number"==typeof r.__signal_exit_emitter__.count&&(n+=r.__signal_exit_emitter__.count),i.length===n){this.unload();const i=this.#t.emit("exit",null,t),n="SIGHUP"===t?this.#e:t;i||e.kill(e.pid,n)}};this.#r=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Ge(this.#i))return()=>{};!1===this.#s&&this.load();const i=t?.alwaysLast?"afterExit":"exit";return this.#t.on(i,e),()=>{this.#t.removeListener(i,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#s){this.#s=!0,this.#t.count+=1;for(const e of Me)try{const t=this.#o[e];t&&this.#i.on(e,t)}catch(e){}this.#i.emit=(e,...t)=>this.#a(e,...t),this.#i.reallyExit=e=>this.#c(e)}}unload(){this.#s&&(this.#s=!1,Me.forEach(e=>{const t=this.#o[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#i.removeListener(e,t)}catch(e){}}),this.#i.emit=this.#n,this.#i.reallyExit=this.#r,this.#t.count-=1)}#c(e){return Ge(this.#i)?(this.#i.exitCode=e||0,this.#t.emit("exit",this.#i.exitCode,null),this.#r.call(this.#i,this.#i.exitCode)):0}#a(e,...t){const i=this.#n;if("exit"===e&&Ge(this.#i)){"number"==typeof t[0]&&(this.#i.exitCode=t[0]);const n=i.call(this.#i,e,...t);return this.#t.emit("exit",this.#i.exitCode,null),n}return i.call(this.#i,e,...t)}}($e):new class extends ve{onExit(){return()=>{}}load(){}unload(){}},{onExit:(e,t)=>He.onExit(e,t),load:()=>He.load(),unload:()=>He.unload()});var He;const Ye=c.stderr.isTTY?c.stderr:c.stdout.isTTY?c.stdout:void 0,ke=Ye?ye(()=>{Fe(()=>{Ye.write("[?25h")},{alwaysLast:!0})}):()=>{};let Ve=!1;const Ke={show:(e=c.stderr)=>{e.isTTY&&(Ve=!1,e.write("[?25h"))},hide:(e=c.stderr)=>{e.isTTY&&(ke(),Ve=!0,e.write("[?25l"))},toggle:(e,t)=>{void 0!==e&&(Ve=e),Ve?Ke.show(t):Ke.hide(t)}};var qe={dots:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},dots2:{interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},dots3:{interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},dots4:{interval:80,frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},dots5:{interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},dots6:{interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},dots7:{interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},dots8:{interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},dots9:{interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},dots10:{interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},dots11:{interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},dots12:{interval:80,frames:["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},dots13:{interval:80,frames:["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},dots14:{interval:80,frames:["⠉⠉","⠈⠙","⠀⠹","⠀⢸","⠀⣰","⢀⣠","⣀⣀","⣄⡀","⣆⠀","⡇⠀","⠏⠀","⠋⠁"]},dots8Bit:{interval:80,frames:["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},dotsCircle:{interval:80,frames:["⢎ ","⠎⠁","⠊⠑","⠈⠱"," ⡱","⢀⡰","⢄⡠","⢆⡀"]},sand:{interval:80,frames:["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["⠂","-","–","—","–","-"]},rollingLine:{interval:80,frames:["/  "," - "," \\ ","  |","  |"," \\ "," - ","/  "]},pipe:{interval:100,frames:["┤","┘","┴","└","├","┌","┬","┐"]},simpleDots:{interval:400,frames:[".  ",".. ","...","   "]},simpleDotsScrolling:{interval:200,frames:[".  ",".. ","..."," ..","  .","   "]},star:{interval:70,frames:["✶","✸","✹","✺","✹","✷"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","´","-","_","_","_"]},hamburger:{interval:100,frames:["☱","☲","☴"]},growVertical:{interval:120,frames:["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},growHorizontal:{interval:120,frames:["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","°","O","o","."]},noise:{interval:100,frames:["▓","▒","░"]},bounce:{interval:120,frames:["⠁","⠂","⠄","⠂"]},boxBounce:{interval:120,frames:["▖","▘","▝","▗"]},boxBounce2:{interval:100,frames:["▌","▀","▐","▄"]},triangle:{interval:50,frames:["◢","◣","◤","◥"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["◜","◠","◝","◞","◡","◟"]},circle:{interval:120,frames:["◡","⊙","◠"]},squareCorners:{interval:180,frames:["◰","◳","◲","◱"]},circleQuarters:{interval:120,frames:["◴","◷","◶","◵"]},circleHalves:{interval:50,frames:["◐","◓","◑","◒"]},squish:{interval:100,frames:["╫","╪"]},toggle:{interval:250,frames:["⊶","⊷"]},toggle2:{interval:80,frames:["▫","▪"]},toggle3:{interval:120,frames:["□","■"]},toggle4:{interval:100,frames:["■","□","▪","▫"]},toggle5:{interval:100,frames:["▮","▯"]},toggle6:{interval:300,frames:["ဝ","၀"]},toggle7:{interval:80,frames:["⦾","⦿"]},toggle8:{interval:100,frames:["◍","◌"]},toggle9:{interval:100,frames:["◉","◎"]},toggle10:{interval:100,frames:["㊂","㊀","㊁"]},toggle11:{interval:50,frames:["⧇","⧆"]},toggle12:{interval:120,frames:["☗","☖"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["←","↖","↑","↗","→","↘","↓","↙"]},arrow2:{interval:80,frames:["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},arrow3:{interval:120,frames:["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},bouncingBar:{interval:80,frames:["[    ]","[=   ]","[==  ]","[=== ]","[====]","[ ===]","[  ==]","[   =]","[    ]","[   =]","[  ==]","[ ===]","[====]","[=== ]","[==  ]","[=   ]"]},bouncingBall:{interval:80,frames:["( ●    )","(  ●   )","(   ●  )","(    ● )","(     ●)","(    ● )","(   ●  )","(  ●   )","( ●    )","(●     )"]},smiley:{interval:200,frames:["😄 ","😝 "]},monkey:{interval:300,frames:["🙈 ","🙈 ","🙉 ","🙊 "]},hearts:{interval:100,frames:["💛 ","💙 ","💜 ","💚 ","💗 "]},clock:{interval:100,frames:["🕛 ","🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},earth:{interval:180,frames:["🌍 ","🌎 ","🌏 "]},material:{interval:17,frames:["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},moon:{interval:80,frames:["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},runner:{interval:140,frames:["🚶 ","🏃 "]},pong:{interval:80,frames:["▐⠂       ▌","▐⠈       ▌","▐ ⠂      ▌","▐ ⠠      ▌","▐  ⡀     ▌","▐  ⠠     ▌","▐   ⠂    ▌","▐   ⠈    ▌","▐    ⠂   ▌","▐    ⠠   ▌","▐     ⡀  ▌","▐     ⠠  ▌","▐      ⠂ ▌","▐      ⠈ ▌","▐       ⠂▌","▐       ⠠▌","▐       ⡀▌","▐      ⠠ ▌","▐      ⠂ ▌","▐     ⠈  ▌","▐     ⠂  ▌","▐    ⠠   ▌","▐    ⡀   ▌","▐   ⠠    ▌","▐   ⠂    ▌","▐  ⠈     ▌","▐  ⠂     ▌","▐ ⠠      ▌","▐ ⡀      ▌","▐⠠       ▌"]},shark:{interval:120,frames:["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},christmas:{interval:400,frames:["🌲","🎄"]},grenade:{interval:80,frames:["،  ","′  "," ´ "," ‾ ","  ⸌","  ⸊","  |","  ⁎","  ⁕"," ෴ ","  ⁓","   ","   ","   "]},point:{interval:125,frames:["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},layer:{interval:150,frames:["-","=","≡"]},betaWave:{interval:80,frames:["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},fingerDance:{interval:160,frames:["🤘 ","🤟 ","🖖 ","✋ ","🤚 ","👆 "]},fistBump:{interval:80,frames:["🤜　　　　🤛 ","🤜　　　　🤛 ","🤜　　　　🤛 ","　🤜　　🤛　 ","　　🤜🤛　　 ","　🤜✨🤛　　 ","🤜　✨　🤛　 "]},soccerHeader:{interval:80,frames:[" 🧑⚽️       🧑 ","🧑  ⚽️      🧑 ","🧑   ⚽️     🧑 ","🧑    ⚽️    🧑 ","🧑     ⚽️   🧑 ","🧑      ⚽️  🧑 ","🧑       ⚽️🧑  ","🧑      ⚽️  🧑 ","🧑     ⚽️   🧑 ","🧑    ⚽️    🧑 ","🧑   ⚽️     🧑 ","🧑  ⚽️      🧑 "]},mindblown:{interval:160,frames:["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ ","　 ","　 ","　 "]},speaker:{interval:160,frames:["🔈 ","🔉 ","🔊 ","🔉 "]},orangePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 "]},bluePulse:{interval:100,frames:["🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},orangeBluePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 ","🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},timeTravel:{interval:100,frames:["🕛 ","🕚 ","🕙 ","🕘 ","🕗 ","🕖 ","🕕 ","🕔 ","🕓 ","🕒 ","🕑 ","🕐 "]},aesthetic:{interval:80,frames:["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},dwarfFortress:{interval:80,frames:[" ██████£££  ","☺██████£££  ","☺██████£££  ","☺▓█████£££  ","☺▓█████£££  ","☺▒█████£££  ","☺▒█████£££  ","☺░█████£££  ","☺░█████£££  ","☺ █████£££  "," ☺█████£££  "," ☺█████£££  "," ☺▓████£££  "," ☺▓████£££  "," ☺▒████£££  "," ☺▒████£££  "," ☺░████£££  "," ☺░████£££  "," ☺ ████£££  ","  ☺████£££  ","  ☺████£££  ","  ☺▓███£££  ","  ☺▓███£££  ","  ☺▒███£££  ","  ☺▒███£££  ","  ☺░███£££  ","  ☺░███£££  ","  ☺ ███£££  ","   ☺███£££  ","   ☺███£££  ","   ☺▓██£££  ","   ☺▓██£££  ","   ☺▒██£££  ","   ☺▒██£££  ","   ☺░██£££  ","   ☺░██£££  ","   ☺ ██£££  ","    ☺██£££  ","    ☺██£££  ","    ☺▓█£££  ","    ☺▓█£££  ","    ☺▒█£££  ","    ☺▒█£££  ","    ☺░█£££  ","    ☺░█£££  ","    ☺ █£££  ","     ☺█£££  ","     ☺█£££  ","     ☺▓£££  ","     ☺▓£££  ","     ☺▒£££  ","     ☺▒£££  ","     ☺░£££  ","     ☺░£££  ","     ☺ £££  ","      ☺£££  ","      ☺£££  ","      ☺▓££  ","      ☺▓££  ","      ☺▒££  ","      ☺▒££  ","      ☺░££  ","      ☺░££  ","      ☺ ££  ","       ☺££  ","       ☺££  ","       ☺▓£  ","       ☺▓£  ","       ☺▒£  ","       ☺▒£  ","       ☺░£  ","       ☺░£  ","       ☺ £  ","        ☺£  ","        ☺£  ","        ☺▓  ","        ☺▓  ","        ☺▒  ","        ☺▒  ","        ☺░  ","        ☺░  ","        ☺   ","        ☺  &","        ☺ ☼&","       ☺ ☼ &","       ☺☼  &","      ☺☼  & ","      ‼   & ","     ☺   &  ","    ‼    &  ","   ☺    &   ","  ‼     &   "," ☺     &    ","‼      &    ","      &     ","      &     ","     &   ░  ","     &   ▒  ","    &    ▓  ","    &    £  ","   &    ░£  ","   &    ▒£  ","  &     ▓£  ","  &     ££  "," &     ░££  "," &     ▒££  ","&      ▓££  ","&      £££  ","      ░£££  ","      ▒£££  ","      ▓£££  ","      █£££  ","     ░█£££  ","     ▒█£££  ","     ▓█£££  ","     ██£££  ","    ░██£££  ","    ▒██£££  ","    ▓██£££  ","    ███£££  ","   ░███£££  ","   ▒███£££  ","   ▓███£££  ","   ████£££  ","  ░████£££  ","  ▒████£££  ","  ▓████£££  ","  █████£££  "," ░█████£££  "," ▒█████£££  "," ▓█████£££  "," ██████£££  "," ██████£££  "]},fish:{interval:80,frames:["~~~~~~~~~~~~~~~~~~~~","> ~~~~~~~~~~~~~~~~~~","º> ~~~~~~~~~~~~~~~~~","(º> ~~~~~~~~~~~~~~~~","((º> ~~~~~~~~~~~~~~~","<((º> ~~~~~~~~~~~~~~","><((º> ~~~~~~~~~~~~~"," ><((º> ~~~~~~~~~~~~","~ ><((º> ~~~~~~~~~~~","~~ <>((º> ~~~~~~~~~~","~~~ ><((º> ~~~~~~~~~","~~~~ <>((º> ~~~~~~~~","~~~~~ ><((º> ~~~~~~~","~~~~~~ <>((º> ~~~~~~","~~~~~~~ ><((º> ~~~~~","~~~~~~~~ <>((º> ~~~~","~~~~~~~~~ ><((º> ~~~","~~~~~~~~~~ <>((º> ~~","~~~~~~~~~~~ ><((º> ~","~~~~~~~~~~~~ <>((º> ","~~~~~~~~~~~~~ ><((º>","~~~~~~~~~~~~~~ <>((º","~~~~~~~~~~~~~~~ ><((","~~~~~~~~~~~~~~~~ <>(","~~~~~~~~~~~~~~~~~ ><","~~~~~~~~~~~~~~~~~~ <","~~~~~~~~~~~~~~~~~~~~"]}};const je=function({onlyFirst:e=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",e?void 0:"g")}();const We=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Qe=[12288,12288,65281,65376,65504,65510],ze=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],Je=(e,t)=>{let i=0,n=Math.floor(e.length/2)-1;for(;i<=n;){const r=Math.floor((i+n)/2),o=2*r;if(t<e[o])n=r-1;else{if(!(t>e[o+1]))return!0;i=r+1}}return!1},Xe=We[0],Ze=We.at(-1),et=Qe[0],tt=Qe.at(-1),it=ze[0],nt=ze.at(-1),[rt,ot]=function(e){let t=e[0],i=e[1];for(let n=0;n<e.length;n+=2){const r=e[n],o=e[n+1];if(19968>=r&&19968<=o)return[r,o];o-r>i-t&&(t=r,i=o)}return[t,i]}(ze);function st(e,{ambiguousAsWide:t=!1}={}){return function(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}(e),(e=>!(e<et||e>tt)&&Je(Qe,e))(e)||(e=>e>=rt&&e<=ot||!(e<it||e>nt)&&Je(ze,e))(e)||t&&(e=>!(e<Xe||e>Ze)&&Je(We,e))(e)?2:1}const at=new Intl.Segmenter,ct=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,lt=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,_t=/^\p{RGI_Emoji}$/v,ut=/^[\d#*]\u20E3$/,Et=/\p{Extended_Pictographic}/gu;function dt(e){if(e.length>50)return!1;if(ut.test(e))return!0;if(e.includes("‍")){const t=e.match(Et);return null!==t&&t.length>=2}return!1}function pt(e){return e.replace(lt,"")}function It(e){return ct.test(e)}function gt(e,t){let i=0;if(e.length>1)for(const n of e.slice(1))n>="＀"&&n<="￯"&&(i+=st(n.codePointAt(0),t));return i}function Ct(e,t={}){if("string"!=typeof e||0===e.length)return 0;const{ambiguousIsNarrow:i=!0,countAnsiEscapeCodes:n=!1}=t;let r=e;if(n||!r.includes("")&&!r.includes("")||(r=function(e){if("string"!=typeof e)throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(je,"")}(r)),0===r.length)return 0;if(/^[\u0020-\u007E]*$/.test(r))return r.length;let o=0;const s={ambiguousAsWide:!i};for(const{segment:e}of at.segment(r)){if(It(e))continue;if(_t.test(e)||dt(e)){o+=2;continue}o+=st(pt(e).codePointAt(0),s),o+=gt(e,s)}return o}const ft=new class{#l=0;#_;#u=!1;#E=!1;#d=e=>{if(!e?.length)return;3===("string"==typeof e?e.codePointAt(0):e[0])&&(c.listenerCount("SIGINT")>0?c.emit("SIGINT"):c.kill(c.pid,"SIGINT"))};start(){this.#l++,1===this.#l&&this.#p()}stop(){0!==this.#l&&0===--this.#l&&this.#I()}#p(){const{stdin:e}=c;"win32"!==c.platform&&e?.isTTY&&"function"==typeof e.setRawMode?(this.#_=e,this.#u=e.isPaused(),this.#E=Boolean(e.isRaw),e.setRawMode(!0),e.prependListener("data",this.#d),this.#u&&e.resume()):this.#_=void 0}#I(){if(!this.#_)return;const e=this.#_;e.off("data",this.#d),e.isTTY&&e.setRawMode?.(this.#E),this.#u&&e.pause(),this.#_=void 0,this.#u=!1,this.#E=!1}};var ht=Object.freeze(ft);const Lt=new Map;class Ot{#g=0;#C=-1;#f=0;#h;#L;#O;#U;#m=new Map;#D=!1;#N;#P;#A=!1;color;#S(e){this.#D=!0;try{return e()}finally{this.#D=!1}}#T(){this.isSpinning&&this.render()}#R(e,t){if(null==e)return"";if("string"==typeof e)return e;if(Buffer.isBuffer(e)||ArrayBuffer.isView(e)){const i="string"==typeof t&&t&&"buffer"!==t?t:"utf8";return Buffer.from(e).toString(i)}return String(e)}#y(e){if(!e)return!1;const t=e.at(-1);return"\n"===t||"\r"===t}#M(){this.#P||(this.#P=setTimeout(()=>{this.#P=void 0,this.isSpinning&&this.#T()},200),"function"==typeof this.#P?.unref&&this.#P.unref())}#G(){this.#P&&(clearTimeout(this.#P),this.#P=void 0)}#B(e,t,i,n){return this.#w(i," ")+e+("string"==typeof t?(e?" ":"")+t:"")+this.#x(n," ")}constructor(e){"string"==typeof e&&(e={text:e}),this.#h={color:"cyan",stream:c.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#h.color,this.#O=this.#h.stream,"boolean"!=typeof this.#h.isEnabled&&(this.#h.isEnabled=function({stream:e=process.stdout}={}){return Boolean(e&&e.isTTY&&"dumb"!==process.env.TERM&&!("CI"in process.env))}({stream:this.#O})),"boolean"!=typeof this.#h.isSilent&&(this.#h.isSilent=!1);const t=this.#h.interval;this.spinner=this.#h.spinner,this.#h.interval=t,this.text=this.#h.text,this.prefixText=this.#h.prefixText,this.suffixText=this.#h.suffixText,this.indent=this.#h.indent,"test"===c.env.NODE_ENV&&(this._stream=this.#O,this._isEnabled=this.#h.isEnabled,Object.defineProperty(this,"_linesToClear",{get(){return this.#g},set(e){this.#g=e}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#C}}),Object.defineProperty(this,"_lineCount",{get(){const e=this.#O.columns??80,t="function"==typeof this.#h.prefixText?"":this.#h.prefixText,i="function"==typeof this.#h.suffixText?"":this.#h.suffixText,n="string"==typeof t&&""!==t?t+" ":"",r="string"==typeof i&&""!==i?" "+i:"",o=" ".repeat(this.#h.indent)+n+"-"+("string"==typeof this.#h.text?" "+this.#h.text:"")+r;return this.#b(o,e)}}))}get indent(){return this.#h.indent}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#h.indent=e}get interval(){return this.#h.interval??this.#L.interval??100}get spinner(){return this.#L}set spinner(e){if(this.#C=-1,this.#h.interval=void 0,"object"==typeof e){if(!Array.isArray(e.frames)||0===e.frames.length||e.frames.some(e=>"string"!=typeof e))throw new Error("The given spinner must have a non-empty `frames` array of strings");if(void 0!==e.interval&&!(Number.isInteger(e.interval)&&e.interval>0))throw new Error("`spinner.interval` must be a positive integer if provided");this.#L=e}else if(function(){const{env:e}=c,{TERM:t,TERM_PROGRAM:i}=e;return"win32"!==c.platform?"linux"!==t:Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||"{cmd::Cmder}"===e.ConEmuTask||"Terminus-Sublime"===i||"vscode"===i||"xterm-256color"===t||"alacritty"===t||"rxvt-unicode"===t||"rxvt-unicode-256color"===t||"JetBrains-JediTerm"===e.TERMINAL_EMULATOR}())if(void 0===e)this.#L=qe.dots;else{if("default"===e||!qe[e])throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);this.#L=qe[e]}else this.#L=qe.line}get text(){return this.#h.text}set text(e=""){this.#h.text=e}get prefixText(){return this.#h.prefixText}set prefixText(e=""){this.#h.prefixText=e}get suffixText(){return this.#h.suffixText}set suffixText(e=""){this.#h.suffixText=e}get isSpinning(){return void 0!==this.#U}#v(e,t,i=!1){const n="function"==typeof e?e():e;return"string"==typeof n&&""!==n?i?t+n:n+t:""}#w(e=this.#h.prefixText,t=" "){return this.#v(e,t,!1)}#x(e=this.#h.suffixText,t=" "){return this.#v(e,t,!0)}#b(e,t){let i=0;for(const n of l.stripVTControlCharacters(e).split("\n"))i+=Math.max(1,Math.ceil(Ct(n)/t));return i}get isEnabled(){return this.#h.isEnabled&&!this.#h.isSilent}set isEnabled(e){if("boolean"!=typeof e)throw new TypeError("The `isEnabled` option must be a boolean");this.#h.isEnabled=e}get isSilent(){return this.#h.isSilent}set isSilent(e){if("boolean"!=typeof e)throw new TypeError("The `isSilent` option must be a boolean");this.#h.isSilent=e}frame(){const e=Date.now();(-1===this.#C||e-this.#f>=this.interval)&&(this.#C=(this.#C+1)%this.#L.frames.length,this.#f=e);const{frames:t}=this.#L;let i=t[this.#C];this.color&&(i=_[this.color](i));return this.#w(this.#h.prefixText," ")+i+("string"==typeof this.text?" "+this.text:"")+this.#x(this.#h.suffixText," ")}clear(){return this.isEnabled&&this.#O.isTTY?(this.#S(()=>{this.#O.cursorTo(0);for(let e=0;e<this.#g;e++)e>0&&this.#O.moveCursor(0,-1),this.#O.clearLine(1);this.#h.indent&&this.#O.cursorTo(this.#h.indent)}),this.#g=0,this):this}#$(e){if(!e||this.#m.has(e)||!e.isTTY||"function"!=typeof e.write)return;Lt.has(e)&&console.warn("[ora] Multiple concurrent spinners detected. This may cause visual corruption. Use one spinner at a time.");const t=e.write;this.#m.set(e,t),Lt.set(e,this),e.write=(i,n,r)=>this.#F(e,t,i,n,r)}#H(){if(!this.isEnabled||this.#m.size>0)return;const e=new Set([this.#O,c.stdout,c.stderr]);for(const t of e)this.#$(t)}#Y(){for(const[e,t]of this.#m)e.write=t,Lt.get(e)===this&&Lt.delete(e);this.#m.clear()}#F(e,t,i,n,r){if("function"==typeof n&&(r=n,n=void 0),this.#D)return t.call(e,i,n,r);this.clear();const o=this.#R(i,n),s=this.#y(o),a=t.call(e,i,n,r);return s?this.#G():o.length>0&&this.#M(),this.isSpinning&&!this.#P&&this.render(),a}render(){if(!this.isEnabled||this.#N||this.#P)return this;const e=this.#O.isTTY;let t=!1;try{e&&(this.#S(()=>this.#O.write("[?2026h")),t=!0),this.clear();let i=this.frame();const n=this.#O.columns??80,r=this.#b(i,n),o=this.#O.rows;if(o&&o>1&&r>o){const e=i.split("\n"),t=o-1;i=[...e.slice(0,t),"... (content truncated to fit terminal)"].join("\n")}!1===this.#S(()=>this.#O.write(i))&&this.#O.isTTY&&(this.#N=()=>{this.#N=void 0,this.#T()},this.#O.once("drain",this.#N)),this.#g=this.#b(i,n)}finally{t&&this.#S(()=>this.#O.write("[?2026l"))}return this}start(e){if(e&&(this.text=e),this.isSilent)return this;if(!this.isEnabled){const e=this.text?"-":"",t=" ".repeat(this.#h.indent)+this.#B(e,this.text,this.#h.prefixText,this.#h.suffixText);return""!==t.trim()&&this.#S(()=>this.#O.write(t+"\n")),this}return this.isSpinning||(this.#h.hideCursor&&Ke.hide(this.#O),this.#h.discardStdin&&c.stdin.isTTY&&(ht.start(),this.#A=!0),this.#H(),this.render(),this.#U=setInterval(this.render.bind(this),this.interval)),this}stop(){return clearInterval(this.#U),this.#U=void 0,this.#C=-1,this.#f=0,this.#G(),this.#Y(),this.#N&&(this.#O.removeListener("drain",this.#N),this.#N=void 0),this.isEnabled&&(this.clear(),this.#h.hideCursor&&Ke.show(this.#O)),this.#A&&(this.#A=!1,ht.stop()),this}succeed(e){return this.stopAndPersist({symbol:"✅",text:e})}fail(e){return this.stopAndPersist({symbol:"❌️",text:e})}warn(e){return this.stopAndPersist({symbol:"⚠️",text:e})}info(e){return this.stopAndPersist({symbol:"ℹ️",text:e})}stopAndPersist(e={}){if(this.isSilent)return this;const t=e.symbol??" ",i=e.text??this.text,n=e.prefixText??this.#h.prefixText,r=e.suffixText??this.#h.suffixText,o=this.#B(t,i,n,r)+"\n";return this.stop(),this.#S(()=>this.#O.write(o)),this}}function Ut(e){return new Ot(e)}const mt=e=>{const t=Ut({text:""}),i=e.verbose||!process.stdout.isTTY,n=n=>{if(i)return t.isSpinning&&t.stop(),void console.log(e.formatVerboseText(n));const r=((e,t)=>{const i=t>0?Math.min(Math.max(e/t,0),1):0,n=Math.round(20*i),r=20-n;return"█".repeat(n)+"░".repeat(r)})(n.current,n.total);t.text=`${r} ${e.formatBarText(n)}`,t.isSpinning||t.start()};return e.ctx.on(e.event,n),{spinner:t,dispose:()=>{e.ctx.off(e.event,n),t.isSpinning&&t.stop()}}},Dt=e=>(e/me).toFixed(1),Nt=e=>{const i=j(e);return W(i)?i:t.resolve(i)},Pt=(e,t)=>{const i=t.resumed?e.i18n.translate("PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX"):"";return{fileName:t.fileName,loadedMB:Dt(t.current),totalMB:Dt(t.total),partsCompleted:String(t.partsCompleted),totalParts:String(t.totalParts),resumedSuffix:i}},At={handle:t=>{t.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").option("--format <format>","output format: pretty | json","pretty").option("--uploader <type>","uploader type to use").option("--configName <name>","uploader configuration name to use").option("--configId <id>","uploader configuration ID to use").option("--verbose","Force per-event progress lines (one console.log per progress tick) instead of an in-place spinner. Non-TTY stdout (pipes, CI) automatically falls back to this mode regardless of the flag — --verbose is for the niche case of wanting line-by-line history on an interactive TTY (debugging multipart retries, AI agents tailing output, etc.).",!1).action(async(i,n)=>{const r=i.map(Nt).filter(i=>{const n=e.existsSync(i)||W(i);return n||t.log.warn(`${i} does not exist.`),n}),o=mt({ctx:t,event:exports.IBuildInEvent.FILE_UPLOAD_PROGRESS,verbose:!0===n.verbose,formatBarText:e=>t.i18n.translate("PICGO_CLOUD_UPLOAD_PROGRESS_BAR",Pt(t,e)),formatVerboseText:e=>t.i18n.translate("PICGO_CLOUD_UPLOAD_VERBOSE",Pt(t,e))});try{await t.upload(r,{outputFormat:"json"===n.format?exports.OutputFormat.JSON:exports.OutputFormat.PRETTY,uploader:n.uploader,configName:n.configName,configId:n.configId})}catch(e){if(t.log.error(e instanceof Error?e:new Error(String(e))),process.argv.includes("--debug"))throw e}finally{o.dispose()}})}},St=e=>async t=>{try{await e.cloud.login(t)}catch(t){e.log.error(t)}},Tt=e=>async()=>{try{e.cloud.logout()}catch(t){e.log.error(t)}};var Rt,yt,Mt,Gt,Bt,wt,xt;exports.SyncStatus=void 0,(Rt=exports.SyncStatus||(exports.SyncStatus={})).SUCCESS="success",Rt.CONFLICT="conflict",Rt.FAILED="failed",exports.ConflictType=void 0,(yt=exports.ConflictType||(exports.ConflictType={})).CLEAN="clean",yt.CONFLICT="conflict",yt.ADDED="added",yt.DELETED="deleted",yt.MODIFIED="modified",exports.E2EVersion=void 0,(Mt=exports.E2EVersion||(exports.E2EVersion={}))[Mt.NONE=0]="NONE",Mt[Mt.V1=1]="V1",exports.EncryptionMethod=void 0,(Gt=exports.EncryptionMethod||(exports.EncryptionMethod={})).AUTO="auto",Gt.SSE="sse",Gt.E2EE="e2ee",exports.E2EAskPinReason=void 0,(Bt=exports.E2EAskPinReason||(exports.E2EAskPinReason={})).SETUP="setup",Bt.DECRYPT="decrypt",Bt.RETRY="retry",function(e){e.GUI="gui",e.CLI="cli"}(wt||(wt={})),function(e){e.AccountFrozen="ACCOUNT_FROZEN",e.ConfigConflict="CONFIG_CONFLICT",e.ConfigNotFound="CONFIG_NOT_FOUND",e.DuplicateId="DUPLICATE_ID",e.GraceRestricted="GRACE_RESTRICTED",e.ImportDisabled="IMPORT_DISABLED",e.PlanIneligible="PLAN_INELIGIBLE",e.PlanRequired="PLAN_REQUIRED",e.QuotaExceeded="QUOTA_EXCEEDED"}(xt||(xt={}));const bt=process.env.PICGO_API_URL||"https://api.picgo.app",vt=process.env.PICGO_CLOUD_URL||"https://cloud.picgo.app",$t=e=>"object"==typeof e&&null!==e,Ft=(e,t)=>"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t,Ht=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e||e instanceof Date){const t=new Date(e).getTime();return Number.isNaN(t)?void 0:t}},Yt=e=>(e?.plan??0)>0,kt=e=>{let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},Vt=e=>$t(e),Kt=e=>{const t=e,i=t?.response?.data;return Vt(i)?i:void 0},qt=e=>{const t=e,i=t?.response?.status??t?.status;return"number"==typeof i?i:void 0},jt=e=>{const t=e,i=t?.apiCode??Kt(e)?.code??t?.code;return"string"==typeof i?i:void 0},Wt=(e,t="Request failed")=>{const i=Kt(e)?.message??(e instanceof Error?e.message:void 0)??($t(e)&&"string"==typeof e.message?e.message:void 0);return"string"==typeof i&&""!==i.trim()?i:t},Qt=(e,t)=>{const i=new Error(e,void 0===t?void 0:{cause:t});return i.status=qt(t),i.apiCode=jt(t),i};class zt{ctx;baseURL;constructor(e,t=bt){this.ctx=e,this.baseURL=t}resolveUrl(e){return new URL(e,this.baseURL).toString()}async request(e,t){const i=t??this.ctx.getConfig("settings.picgoCloud.token"),n={...e.headers||{}};i&&(n.Authorization=`Bearer ${i}`,process.env.ENABLE_PICGO_CLOUD_DEV_MODE&&(n["CF-Access-Client-Id"]=process.env.CF_ACCESS_CLIENT_ID||"",n["CF-Access-Client-Secret"]=process.env.CF_ACCESS_CLIENT_SECRET||""));try{return await this.ctx.request({...e,url:this.resolveUrl(e.url||""),headers:n})}catch(e){if((e=>"object"==typeof e&&null!==e&&("statusCode"in e||"response"in e||"message"in e))(e))throw(e=>{const t=e.response?.body,i=Vt(t)&&"string"==typeof t.message?t.message:e.message||"Request failed",n=new Error(i),r=e.response?.status??e.statusCode??0;return n.name="AxiosError",n.isAxiosError=!0,n.status=r,Vt(t)&&"string"==typeof t.code?n.code=t.code:"string"==typeof e.code&&(n.code=e.code),n.response={status:r,data:t},n})(e);throw e}}}class Jt{client;ctx;appType=wt.CLI;constructor(e){this.client=new zt(e),this.ctx=e}async fetchConfig(){this.appType=this.ctx.GUI_VERSION?wt.GUI:wt.CLI;const e=Date.now();try{const t=await this.client.request({method:"GET",url:"/api/config",params:{appType:this.appType}});return t?.config&&""!==t.config.trim()?(this.ctx.log.debug(`[ConfigService] Config fetched successfully in ${Date.now()-e} ms, version: ${t.version}`),t):null}catch(t){if(this.ctx.log.debug(`[ConfigService] Failed to fetch config in ${Date.now()-e} ms`),d.isAxiosError(t)){const e=qt(t),i=jt(t);if(404===e||i===xt.ConfigNotFound)return null;const n=Wt(t);throw this.ctx.log.warn("[ConfigService] Failed to fetch config:",n),Qt(n,t)}throw t}}async updateConfig(e,t,i){this.appType=this.ctx.GUI_VERSION?wt.GUI:wt.CLI;const n=Date.now();try{const r=await this.client.request({method:"PUT",url:"/api/config",data:{appType:this.appType,config:e,baseVersion:t,historyLimit:10,...i??{}}});return this.ctx.log.debug(`[ConfigService] Config updated successfully in ${Date.now()-n} ms, new version: ${r.version}`),{success:!0,version:r.version}}catch(e){if(this.ctx.log.debug(`[ConfigService] Failed to update config in ${Date.now()-n} ms`),d.isAxiosError(e)){const i=e.response?.data;if(jt(e)===xt.ConfigConflict)return{success:!1,conflict:!0,version:"number"==typeof i?.currentVersion?i.currentVersion:t};const n=Wt(e);throw this.ctx.log.warn("[ConfigService] Failed to update config:",n),Qt(n,e)}throw e}}}const Xt=(e,t)=>!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t),Zt=e=>{const t=Object.getPrototypeOf(e),i=Object.create(t);for(const t of Object.getOwnPropertySymbols(e)){const n=Object.getOwnPropertyDescriptor(e,t);n&&Object.defineProperty(i,t,n)}return i},ei=(e,t)=>{const i=Zt(e),n=[],r=new Set;for(const t of Object.keys(e))r.has(t)||(n.push(t),r.add(t));for(const e of Object.keys(t))r.has(e)||(n.push(e),r.add(e));for(const r of n){if(!Xt(t,r)){delete i[r];continue}const n=Xt(e,r)?e[r]:void 0,o=t[r];u.isPlainObject(n)&&u.isPlainObject(o)?i[r]=ei(n,o):i[r]=o}return i},ti=(e,t)=>u.isEqual(e,t)?exports.ConflictType.CLEAN:void 0===e&&void 0!==t?exports.ConflictType.ADDED:void 0!==e&&void 0===t?exports.ConflictType.DELETED:exports.ConflictType.MODIFIED;class ii{static merge3Way(e,t,i,n="root"){if(u.isEqual(t,i)){const r=ti(e,t);return{value:t,conflict:!1,diffNode:r===exports.ConflictType.CLEAN?void 0:{key:n,status:r,snapshotValue:e,localValue:t,remoteValue:i}}}const r=u.isPlainObject(t),o=u.isPlainObject(i),s=u.isPlainObject(e);if(u.isEqual(e,t)){if(r&&o){const r=ei(t,i),o=ti(e,r);return{value:r,conflict:!1,diffNode:o===exports.ConflictType.CLEAN?void 0:{key:n,status:o,snapshotValue:e,localValue:t,remoteValue:i}}}const s=ti(e,i);return{value:i,conflict:!1,diffNode:s===exports.ConflictType.CLEAN?void 0:{key:n,status:s,snapshotValue:e,localValue:t,remoteValue:i}}}if(u.isEqual(e,i)){const r=ti(e,t);return{value:t,conflict:!1,diffNode:r===exports.ConflictType.CLEAN?void 0:{key:n,status:r,snapshotValue:e,localValue:t,remoteValue:i}}}if(r&&o&&(s||null==e)){const r=s?e:{},o=t,a=i,c=[],l=new Set;for(const e of Object.keys(o))l.has(e)||(c.push(e),l.add(e));for(const e of Object.keys(a))l.has(e)||(c.push(e),l.add(e));for(const e of Object.keys(r))l.has(e)||(c.push(e),l.add(e));const _=Zt(o),u=[];let E=!1;for(const e of c){const t=Xt(r,e)?r[e]:void 0,i=Xt(o,e)?o[e]:void 0,n=Xt(a,e)?a[e]:void 0,s=ii.merge3Way(t,i,n,e);s.conflict&&(E=!0),void 0===s.value?delete _[e]:_[e]=s.value,s.diffNode&&s.diffNode.status!==exports.ConflictType.CLEAN&&u.push(s.diffNode)}const d=E?exports.ConflictType.CONFLICT:ti(e,_);return{value:_,conflict:E,diffNode:d===exports.ConflictType.CLEAN?void 0:{key:n,status:d,snapshotValue:e,localValue:t,remoteValue:i,children:u.length?u:void 0}}}return{value:t,conflict:!0,diffNode:{key:n,status:exports.ConflictType.CONFLICT,snapshotValue:e,localValue:t,remoteValue:i}}}}class ni extends Error{constructor(e){super(e),this.name=new.target.name}}class ri extends ni{constructor(e="Encrypted config payload is corrupted"){super(e)}}class oi extends ni{constructor(e="Unsupported E2E version"){super(e)}}class si extends ni{constructor(e="PIN handler is required for E2E operations"){super(e)}}class ai extends ni{constructor(e="Encryption switch confirmation handler is required"){super(e)}}class ci extends ni{constructor(e="Invalid PIN input"){super(e)}}class li extends ni{constructor(e="Maximum retry attempts exceeded"){super(e)}}class _i extends ni{constructor(e="Failed to decrypt payload"){super(e)}}class ui extends ni{value;constructor(e){super("Invalid encryption method"),this.value=e}}const Ei=12,di="aes-256-gcm";class pi{generateE2EPayload(e,t){const i=I.randomBytes(16),n=I.randomBytes(32),r=this.wrapDEK(n,t,i),o=this.encryptConfig(e,n);return{payload:{e2eVersion:exports.E2EVersion.V1,clientKekSalt:i.toString("base64"),clientDekEncrypted:r,config:o},dek:n}}encryptConfig(e,t){return this.encryptWithKey(Buffer.from(e,"utf8"),t)}decryptConfig(e,t){return this.decryptWithKey(e,t).toString("utf8")}wrapDEK(e,t,i){const n=this.deriveKEK(t,i);return this.encryptWithKey(e,n)}unwrapDEK(e,t,i){const n=this.deriveKEK(t,i);return this.decryptWithKey(e,n)}decodeSalt(e){const t=Buffer.from(e,"base64");if(16!==t.length)throw new ri("Invalid salt length");return t}deriveKEK(e,t){return I.pbkdf2Sync(e,t,6e5,32,"sha256")}encryptWithKey(e,t){const i=I.randomBytes(Ei),n=I.createCipheriv(di,t,i),r=Buffer.concat([n.update(e),n.final()]),o=n.getAuthTag();return Buffer.concat([i,o,r]).toString("base64")}decryptWithKey(e,t){const i=Buffer.from(e,"base64");if(i.length<28)throw new ri("Encrypted payload is too short");const n=i.subarray(0,Ei),r=i.subarray(Ei,28),o=i.subarray(28);try{const e=I.createDecipheriv(di,t,n);return e.setAuthTag(r),Buffer.concat([e.update(o),e.final()])}catch(e){const t=e instanceof Error?e.message:"Failed to decrypt payload";throw new _i(t)}}}const Ii="settings.picgoCloud.encryptionMethod",gi=["settings.picgoCloud.token",Ii],Ci=(e,t,i={})=>{const n=u.cloneDeep(e),r=!0===i.cleanupEmptyParents;return gi.forEach(e=>{const i=u.get(t,e);void 0!==i?u.set(n,e,i):(u.unset(n,e),r&&((e,t)=>{const i=t.split(".");for(let t=i.length-1;t>0;t-=1){const n=i.slice(0,t).join("."),r=u.get(e,n);if(!u.isPlainObject(r)||0!==Object.keys(r).length)break;u.unset(e,n)}})(n,e))}),n},fi=(e,t)=>{if(e)return e;const i=(e=>{const t=u.get(e,Ii);if(void 0!==t){if(t===exports.EncryptionMethod.AUTO||t===exports.EncryptionMethod.SSE||t===exports.EncryptionMethod.E2EE)return t;throw new ui(t)}})(t);return i??exports.EncryptionMethod.AUTO},hi=async t=>{if(await e.pathExists(t)){const i=await e.readFile(t,"utf8");return E.parse(i)}return{}},Li=async t=>{if(!await e.pathExists(t))return{version:0,updatedAt:"",data:{}};const i=await hi(t);return(e=>{if(!u.isPlainObject(e))return!1;const t=e;return"number"==typeof t.version&&Object.prototype.hasOwnProperty.call(t,"data")})(i)?{version:i.version,updatedAt:"string"==typeof i.updatedAt?i.updatedAt:"",data:i.data??{}}:{version:0,updatedAt:"",data:i}},Oi=async(t,i,n)=>{await(async(t,i)=>{const n=E.stringify(i,null,2);await e.writeFile(t,n,"utf8")})(t,{version:n,updatedAt:(new Date).toISOString(),data:i})};class Ui{ctx;snapshotPath;configService;onAskPin;onAskEncryptionSwitch;e2eService;currentRemoteVersion=0;originalRemote=null;remoteE2EVersion=exports.E2EVersion.NONE;remoteClientKekSalt;remoteClientDekEncrypted;cachedDEK;cachedClientDekEncrypted;constructor(e,i={}){this.ctx=e,this.snapshotPath=t.join(e.baseDir,"config.snapshot.json"),this.configService=new Jt(e),this.onAskPin=i.onAskPin,this.onAskEncryptionSwitch=i.onAskEncryptionSwitch,this.e2eService=new pi}async sync(t={},i=0){try{const n=await hi(this.ctx.configPath);if(!u.isPlainObject(n))return{status:exports.SyncStatus.FAILED,message:"Local config is not a valid JSON object"};const r=n,o=fi(t.encryptionMethod,r),s=await e.pathExists(this.snapshotPath),a=await Li(this.snapshotPath),c=await this.fetchRemoteConfig();if(c&&!u.isPlainObject(c))return{status:exports.SyncStatus.FAILED,message:"Remote config is not a valid JSON object"};if(this.originalRemote=c||null,!this.originalRemote){const e=!s;e?this.ctx.log.info("First time sync detected. Initializing remote config..."):this.ctx.log.warn("Remote config missing (sync chain broken). Re-initializing from Local...");try{const e=await this.buildPushPayload(r,o);await this.pushRemoteConfig(e.configStr,e.e2eFields)}catch(e){if("Remote config modified by another device"===(e instanceof Error?e.message:String(e)))return i<1?(this.ctx.log.warn("Conflict detected during sync. Retrying automatically..."),this.sync(t,i+1)):{status:exports.SyncStatus.FAILED,message:"Sync failed: Remote config is changing too frequently. Please try again later."};throw e}return await Oi(this.snapshotPath,r,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:e?"Config sync initialized":"Remote config restored from local",mergedConfig:r}}if(this.originalRemote&&this.isEncryptionModeSwitch(o)&&!t.skipEncryptionSwitchConfirm){if(!await this.confirmEncryptionSwitch(o))return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED")}}const l=Ci(this.originalRemote,r);this.ctx.log.info("Merging configs for sync...");const _=ii.merge3Way(a.data,r,l);if(_.conflict)return{status:exports.SyncStatus.CONFLICT,message:"Config sync conflict detected",diffTree:_.diffNode};const E=_.value;!u.isEqual(r,E)&&this.ctx.saveConfig(E);const d=Ci(E,this.originalRemote,{cleanupEmptyParents:!0});if(this.isEncryptionModeSwitch(o)||!u.isEqual(this.originalRemote,d))try{const e=await this.buildPushPayload(d,o);await this.pushRemoteConfig(e.configStr,e.e2eFields)}catch(e){if("Remote config modified by another device"===(e instanceof Error?e.message:String(e)))return i<1?(this.ctx.log.warn("Conflict detected during sync. Retrying automatically..."),this.sync(t,i+1)):{status:exports.SyncStatus.FAILED,message:"Sync failed: Remote config is changing too frequently. Please try again later."};throw e}return await Oi(this.snapshotPath,E,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:"Config sync success",mergedConfig:E}}catch(e){if(e instanceof ui)return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_INVALID_ENCRYPTION_METHOD",{value:`"${String(e.value)}"`})};if(e instanceof ai)return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER")};const t=e instanceof Error?e.message:String(e);return{status:exports.SyncStatus.FAILED,message:t}}}async applyResolvedConfig(e,t={}){try{if(!u.isPlainObject(e))return{status:exports.SyncStatus.FAILED,message:"Resolved config is not a valid JSON object"};const i=await hi(this.ctx.configPath);if(!u.isPlainObject(i))return{status:exports.SyncStatus.FAILED,message:"Local config is not a valid JSON object"};const n=Ci(e,i);if(this.ctx.saveConfig(n),!this.originalRemote){const e=await this.fetchRemoteConfig();if(e&&!u.isPlainObject(e))return{status:exports.SyncStatus.FAILED,message:"Remote config is not a valid JSON object"};this.originalRemote=e||null}const r=this.originalRemote?Ci(n,this.originalRemote,{cleanupEmptyParents:!0}):n,o=t.useE2E??this.remoteE2EVersion===exports.E2EVersion.V1?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE,s=await this.buildPushPayload(r,o);return await this.pushRemoteConfig(s.configStr,s.e2eFields),await Oi(this.snapshotPath,n,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:"Config conflict resolved",mergedConfig:n}}catch(e){const t=e instanceof Error?e.message:String(e);return{status:exports.SyncStatus.FAILED,message:t}}}async fetchRemoteConfig(){this.ctx.log.info("Fetching remote config for sync...");const e=await this.configService.fetchConfig();if(!e)return this.currentRemoteVersion=0,this.setRemoteE2EState(exports.E2EVersion.NONE),null;this.currentRemoteVersion=e.version;if((e=>{if(e===exports.E2EVersion.V1)return exports.E2EVersion.V1;if(e===exports.E2EVersion.NONE||void 0===e)return exports.E2EVersion.NONE;if("number"==typeof e)throw new oi(`Unsupported E2E version: ${e}`);return exports.E2EVersion.NONE})(e.encryption?.e2eVersion)===exports.E2EVersion.V1){const t=(e=>{if(!e.encryption?.clientKekSalt)throw new ri("Missing clientKekSalt for encrypted config");return e.encryption.clientKekSalt})(e),i=(e=>{if(!e.encryption?.clientDekEncrypted)throw new ri("Missing clientDekEncrypted for encrypted config");return e.encryption.clientDekEncrypted})(e);this.setRemoteE2EState(exports.E2EVersion.V1,t,i);const n=await this.decryptRemoteConfig(e.config,t,i);return E.parse(n)}return this.setRemoteE2EState(exports.E2EVersion.NONE),E.parse(e.config)}async pushRemoteConfig(e,t){this.ctx.log.info("Pushing merged config to remote...");const i=await this.configService.updateConfig(e,this.currentRemoteVersion,t);if(i.conflict)throw this.currentRemoteVersion=i.version,new Error("Remote config modified by another device");this.currentRemoteVersion=i.version,this.applyE2EStateAfterPush(t)}applyE2EStateAfterPush(e){e.e2eVersion===exports.E2EVersion.V1&&e.clientKekSalt&&e.clientDekEncrypted?this.setRemoteE2EState(exports.E2EVersion.V1,e.clientKekSalt,e.clientDekEncrypted):e.e2eVersion===exports.E2EVersion.NONE&&this.setRemoteE2EState(exports.E2EVersion.NONE)}setRemoteE2EState(e,t,i){this.remoteE2EVersion=e,this.remoteClientKekSalt=t,this.remoteClientDekEncrypted=i,i&&i===this.cachedClientDekEncrypted||(this.cachedDEK=void 0,this.cachedClientDekEncrypted=void 0)}async confirmEncryptionSwitch(e){if(!this.onAskEncryptionSwitch)throw new ai;const t=this.remoteE2EVersion===exports.E2EVersion.V1?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE,i=this.shouldUseE2E(e)?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE;return this.onAskEncryptionSwitch({from:t,to:i})}async buildPushPayload(e,t){const i=E.stringify(e);if(!this.shouldUseE2E(t))return{configStr:i,e2eFields:{e2eVersion:exports.E2EVersion.NONE}};if(this.remoteE2EVersion===exports.E2EVersion.V1&&this.remoteClientKekSalt&&this.remoteClientDekEncrypted){const e=await this.ensureDEK(this.remoteClientKekSalt,this.remoteClientDekEncrypted);return{configStr:this.e2eService.encryptConfig(i,e),e2eFields:{e2eVersion:exports.E2EVersion.V1,clientKekSalt:this.remoteClientKekSalt,clientDekEncrypted:this.remoteClientDekEncrypted}}}const n=await this.askPin(exports.E2EAskPinReason.SETUP,0),{payload:r,dek:o}=this.e2eService.generateE2EPayload(i,n);return this.cachedDEK=o,this.cachedClientDekEncrypted=r.clientDekEncrypted,{configStr:r.config,e2eFields:{e2eVersion:r.e2eVersion,clientKekSalt:r.clientKekSalt,clientDekEncrypted:r.clientDekEncrypted}}}shouldUseE2E(e){return e===exports.EncryptionMethod.E2EE||e!==exports.EncryptionMethod.SSE&&this.remoteE2EVersion===exports.E2EVersion.V1}isEncryptionModeSwitch(e){return this.shouldUseE2E(e)!==(this.remoteE2EVersion===exports.E2EVersion.V1)}async decryptRemoteConfig(e,t,i){const n=await this.ensureDEK(t,i);try{return this.e2eService.decryptConfig(e,n)}catch(e){if(e instanceof _i)throw new ri("Failed to decrypt remote config payload");throw e}}async ensureDEK(e,t){if(this.cachedDEK&&this.cachedClientDekEncrypted===t)return this.cachedDEK;const i=this.e2eService.decodeSalt(e);for(let e=0;e<4;e+=1){const n=0===e?exports.E2EAskPinReason.DECRYPT:exports.E2EAskPinReason.RETRY,r=await this.askPin(n,e);try{const e=this.e2eService.unwrapDEK(t,r,i);return this.cachedDEK=e,this.cachedClientDekEncrypted=t,e}catch(e){if(e instanceof _i)continue;throw e}}throw new li}async askPin(e,t){if(!this.onAskPin)throw new si;const i=await this.onAskPin(e,t);if(null==i||0===i.length)throw new ci;return i}}const mi=e=>{if(void 0===e)return"undefined";try{return JSON.stringify(e)}catch{return g.inspect(e,{depth:4,breakLength:120,maxArrayLength:50})}},Di=(e,t=0)=>{const i=" ".repeat(2*t),n=e.status===exports.ConflictType.CONFLICT?_.red:e.status===exports.ConflictType.ADDED?_.green:e.status===exports.ConflictType.DELETED?_.gray:e.status===exports.ConflictType.MODIFIED?_.yellow:_.white;if(console.log(`${i}${n(`[${e.status}]`)} ${e.key}`),e.status!==exports.ConflictType.CONFLICT||e.children&&0!==e.children.length||(console.log(`${i}  ${_.gray("snapshot:")} ${mi(e.snapshotValue)}`),console.log(`${i}  ${_.cyan("local :")} ${mi(e.localValue)}`),console.log(`${i}  ${_.magenta("remote:")} ${mi(e.remoteValue)}`)),e.children?.length)for(const i of e.children)Di(i,t+1)},Ni=e=>e.option("--encrypt [method]","encryption method (auto|sse|e2ee)").option("--skip-encryption-switch-confirm","skip encryption switch confirmation"),Pi=e=>async t=>{const i=t.encrypt;let n;if(void 0!==i){const t="string"==typeof i?i:void 0;if(t!==exports.EncryptionMethod.AUTO&&t!==exports.EncryptionMethod.SSE&&t!==exports.EncryptionMethod.E2EE){const i=t??"undefined";return void e.log.error(e.i18n.translate("CONFIG_SYNC_INVALID_ENCRYPTION_METHOD",{value:`"${i}"`}))}n=t,e.saveConfig({"settings.picgoCloud.encryptionMethod":t})}const r=new Ui(e,{onAskPin:async(t,i)=>{if(t===exports.E2EAskPinReason.SETUP){for(let t=0;t<3;t+=1){const{pin:t}=await e.cmd.inquirer.prompt([{type:"password",name:"pin",message:"Set up E2E encryption. Enter PIN",mask:"*"}]),{confirmPin:i}=await e.cmd.inquirer.prompt([{type:"password",name:"confirmPin",message:"Confirm PIN",mask:"*"}]);if(t===i)return t;e.log.warn("PIN confirmation does not match. Please try again.")}return null}const n=t===exports.E2EAskPinReason.DECRYPT?"Enter PIN to decrypt config":`Incorrect PIN. Retry (${i}/3)`,{pin:r}=await e.cmd.inquirer.prompt([{type:"password",name:"pin",message:n,mask:"*"}]);return r},onAskEncryptionSwitch:async({from:t,to:i})=>{const n=e.i18n.translate(t===exports.EncryptionMethod.E2EE?"CONFIG_SYNC_ENCRYPTION_METHOD_E2EE":"CONFIG_SYNC_ENCRYPTION_METHOD_SSE"),r=e.i18n.translate(i===exports.EncryptionMethod.E2EE?"CONFIG_SYNC_ENCRYPTION_METHOD_E2EE":"CONFIG_SYNC_ENCRYPTION_METHOD_SSE"),o=e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE"),s=e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_BODY",{from:n,to:r}),{confirm:a}=await e.cmd.inquirer.prompt([{type:"list",name:"confirm",message:`${o}\n\n${s}`,choices:[{name:e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM"),value:!0},{name:e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL"),value:!1}]}]);return a}}),o=await r.sync({encryptionMethod:n,skipEncryptionSwitchConfirm:t.skipEncryptionSwitchConfirm});if(o.status!==exports.SyncStatus.SUCCESS){if(o.status===exports.SyncStatus.CONFLICT){e.log.warn(o.message||"Config sync conflict detected."),o.diffTree&&Di(o.diffTree);const{strategy:t}=await e.cmd.inquirer.prompt([{type:"list",name:"strategy",message:"Choose a strategy to resolve conflicts",choices:[{name:"Use Local",value:"local"},{name:"Use Remote",value:"remote"},{name:"Abort",value:"abort"}]}]);if("abort"===t)return void e.log.warn("Config sync aborted.");const i="local"===t?o.diffTree?.localValue:o.diffTree?.remoteValue;if(!i||!u.isPlainObject(i))return void e.log.error("Invalid resolved config, please resolve it manually.");let s;if(n===exports.EncryptionMethod.E2EE)s={useE2E:!0};else if(n===exports.EncryptionMethod.SSE)s={useE2E:!1};else{const t=e.getConfig("settings.picgoCloud.encryptionMethod");t===exports.EncryptionMethod.E2EE?s={useE2E:!0}:t===exports.EncryptionMethod.SSE&&(s={useE2E:!1})}const a=await r.applyResolvedConfig(i,s);return a.status===exports.SyncStatus.SUCCESS?void e.log.success(a.message||"Config sync resolved!"):void e.log.error(a.message||"Failed to apply resolved config")}e.log.error(o.message||"Config sync failed")}else e.log.success(o.message||"Config sync success!")},Ai={handle:e=>{const t=e.cmd.program.command("config").description("manage picgo config");Ni(t.command("sync").description("sync config with picgo cloud (shortcut for cloud config sync)")).action(Pi(e))}},Si=e=>e.trim(),Ti=e=>Si(e).toLowerCase(),Ri=(e,t)=>{const i=Ti(t);return e.find(e=>Ti(e)===i)},yi=async(e,t,i,n)=>{const r=k(t,{onError:(t,i,n)=>{const r=n instanceof Error?n.message:String(n);e.log.warn(`[plugin-config] ${t}.${i} threw during CLI prompt: ${r}`)}}),o=await e.cmd.inquirer.prompt(r),s="transformer"===i?`transformer.${n}`:n;e.saveConfig({[s]:o}),"transformer"===i&&e.saveConfig({"picBed.transformer":n})},Mi={handle:e=>{e.cmd.program.command("set").arguments("<module> [name] [configName]").description("configure config of picgo modules (uploader/transformer/plugin)").action(async(t,i,n)=>{try{switch(t){case"uploader":{const t=i||(await e.cmd.inquirer.prompt([{type:"list",name:"uploaderType",choices:e.helper.uploader.getIdList(),message:"Choose an uploader",default:e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"}])).uploaderType,r=e.helper.uploader.get(t);if(!r)return e.log.error(`No uploader named ${t}`);if(!r.config)return e.log.error(`Uploader ${t} has no config`);const o=e.uploaderConfig.getConfigList(t),s=o.map(e=>e._configName);let a="string"==typeof n?Si(n):"";if(!a)if(s.length>0){const t=await e.cmd.inquirer.prompt([{type:"list",name:"configChoice",message:"Choose a config",choices:[{name:"[Create New Config]",value:"__CREATE__"},...s]}]);if("__CREATE__"===t.configChoice){const t=await e.cmd.inquirer.prompt([{type:"input",name:"newConfigName",message:"Enter config name",validate:e=>{const t=Si(e);return t?!Ri(s,t)||`Config name ${t} already exists`:"Config name can not be empty"}}]);a=Si(t.newConfigName)}else a=String(t.configChoice)}else{const t=await e.cmd.inquirer.prompt([{type:"input",name:"newConfigName",message:"Enter config name",validate:e=>!!Si(e)||"Config name can not be empty"}]);a=Si(t.newConfigName)}const c=Ri(s,a);if(c){const i=o.find(e=>Ti(e._configName)===Ti(c));i&&e.setConfig({[`picBed.${t}`]:i})}const l=k(r.config(e),{onError:(t,i,n)=>{const r=n instanceof Error?n.message:String(n);e.log.warn(`[plugin-config] ${t}.${i} threw during CLI prompt: ${r}`)}}),_=await e.cmd.inquirer.prompt(l);e.uploaderConfig.createOrUpdate(t,a,_)}break;case"transformer":if(i){const n=e.helper.transformer.get(i);if(!n)return e.log.error(`No transformer named ${i}`);n.config&&await yi(e,n.config(e),t,i)}else{const i=[{type:"list",name:"transformer",choices:e.helper.transformer.getIdList(),message:"Choose a transformer"}],n=await e.cmd.inquirer.prompt(i),r=e.helper.transformer.get(n.transformer);r?.config&&await yi(e,r.config(e),t,n.transformer)}break;case"plugin":if(i){if(i.includes("picgo-plugin-")||(i=`picgo-plugin-${i}`),!Object.keys(e.getConfig("picgoPlugins")).includes(i))return e.log.error(`No plugin named ${i}`);e.pluginLoader.getPlugin(i)?.config&&await yi(e,e.pluginLoader.getPlugin(i).config(e),"plugin",i)}else{const t=[{type:"list",name:"plugin",choices:e.pluginLoader.getFullList(),message:"Choose a plugin"}],i=await e.cmd.inquirer.prompt(t);e.pluginLoader.getPlugin(i.plugin)?.config&&await yi(e,e.pluginLoader.getPlugin(i.plugin).config(e),"plugin",i.plugin)}break;default:return e.log.warn(`No module named ${t}`),e.log.warn("Available modules are uploader|transformer|plugin")}e.log.success("Configure config successfully!"),"plugin"===t&&e.log.info("If you want to use this config, please run 'picgo use plugins'")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},Gi={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module] [name] [configName]").description("use a module (uploader/transformer/plugin) of picgo").action(async(i,n,r)=>{try{if("uploader"===i&&n)return e.uploaderConfig.use(n,r),void e.log.success("Activated config successfully!");const o=["uploader","transformer","plugins"];let s=[];const a={uploader:{type:"list",name:"uploader",message:"Use an uploader",choices:e.helper.uploader.getIdList(),default:e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"},transformer:{type:"list",name:"transformer",message:"Use a transformer",choices:e.helper.transformer.getIdList(),default:e.getConfig("picBed.transformer")||"path"},plugins:{type:"checkbox",name:"plugins",message:"Use plugins",choices:e.pluginLoader.getFullList(),default:Object.keys(e.getConfig("picgoPlugins")).filter(t=>e.getConfig(`picgoPlugins.${t}`))}};if(i){if("uploader"!==i&&"transformer"!==i&&"plugins"!==i)return e.log.warn(`No module named ${i}`),e.log.warn(`Available modules are ${o.join("|")}`);s.push(a[i])}else s=o.map(e=>a[e]);const c=await t.inquirer.prompt(s);if(c.plugins){const t=c.plugins,i=e.getConfig("picgoPlugins");Object.keys(i).forEach(e=>{i[e]=t.includes(e)}),e.saveConfig({picgoPlugins:i})}if(c.uploader){const i=c.uploader,n=e.uploaderConfig.getConfigList(i);if(n.length>1){const r=e.uploaderConfig.getActiveConfig(i),o=await t.inquirer.prompt([{type:"list",name:"uploaderConfigName",message:"Use an uploader config",choices:n.map(e=>e._configName),default:r?._configName}]);e.uploaderConfig.use(i,o.uploaderConfigName)}else e.uploaderConfig.use(i)}void 0!==c.transformer&&e.saveConfig({"picBed.transformer":c.transformer||"path"}),e.log.success("Configure config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},Bi={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",t=>{e.setConfig({"picBed.proxy":t})})}},wi={handle:e=>{e.cmd.program.command("i18n").arguments("[lang]").description("change picgo language").action(async(t="")=>{const i=e.i18n.getLanguageList();if(!t){const t=[{type:"list",name:"i18n",choices:i,message:"Choose a language",default:e.getConfig("settings.language")||"zh-CN"}],n=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(n.i18n),void e.log.success(`Language set to ${n.i18n}`)}if(!i.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)})}},xi={handle:e=>{e.cmd.program.command("server").description("run PicGo as a standalone server").helpOption("--help","display help for command").option("-p, --port <n>","server port").option("-h, --host <s>","server host").option("-i, --ignore-existing-external-server","ignore existing PicGo server instance").option("--secret <s>","server authentication secret").action(async t=>{try{e.setConfig({"picgoInternal.serverMode":!0});const i=t.port?Number(t.port):void 0,n=t.host;await e.server.listen(i,n,t.ignoreExistingExternalServer,t.secret)}catch(t){e.unsetConfig("picgoInternal","serverMode"),e.log.error(t)}})}},bi={handle:e=>{e.cmd.program.command("login").description("login to cloud.picgo.app (shortcut for cloud login)").arguments("[token]").action(St(e))}},vi={handle:e=>{e.cmd.program.command("logout").description("logout from cloud.picgo.app (shortcut for cloud logout)").action(Tt(e))}},$i=e=>e.trim(),Fi=e=>$i(e).toLowerCase(),Hi=(e,t)=>{const i=e.getConfig("picBed.current"),n=[];for(const r of t){i===r?n.push(_.green.bold(`+ ${r} [Current Uploader]`)):n.push(`+ ${r}`);const t=e.uploaderConfig.getConfigList(r);if(0===t.length){n.push(_.grey("  (No configs found)"));continue}const o=e.getConfig(`uploader.${r}.defaultId`);for(const e of t)e._id===o?n.push(_.blue(`  * ${e._configName} [Default Config]`)):n.push(`    ${e._configName}`)}return`\n${n.join("\n")}`},Yi={handle:e=>{const t=e.cmd,i=t.program.command("uploader").description("manage uploader configurations").action(async()=>{try{const i=[{name:"List all configurations",value:"list"},{name:"Rename config",value:"rename"},{name:"Copy config",value:"copy"},{name:"Delete config",value:"delete"}],n=await t.inquirer.prompt([{type:"list",name:"operation",message:"Choose an operation:",choices:i}]);if("list"===n.operation){const t=e.uploaderConfig.listUploaderTypes();return void console.log(Hi(e,t))}const r=e.uploaderConfig.listUploaderTypes().filter(t=>e.uploaderConfig.getConfigList(t).length>0);if(0===r.length)return void e.log.warn("No configs found");const o=await t.inquirer.prompt([{type:"list",name:"type",message:"Choose an uploader:",choices:r}]),s=String(o.type),a=e.uploaderConfig.getConfigList(s).map(e=>e._configName),c=await t.inquirer.prompt([{type:"list",name:"configName",message:"rename"===n.operation?"Choose a config to rename:":"copy"===n.operation?"Choose a config to copy:":"Choose a config to delete:",choices:a}]),l=String(c.configName);if("rename"===n.operation){const i=await t.inquirer.prompt([{type:"input",name:"newName",message:"Enter new name:",validate:e=>{const t=$i(e);if(!t)return"Config name can not be empty";return!a.some(e=>Fi(e)===Fi(t)&&Fi(e)!==Fi(l))||`Config name ${t} already exists`}}]);return e.uploaderConfig.rename(s,l,String(i.newName)),void e.log.success("Rename config successfully!")}if("copy"===n.operation){const i=await t.inquirer.prompt([{type:"input",name:"newName",message:"Enter new name:",validate:e=>{const t=$i(e);if(!t)return"Config name can not be empty";return!a.some(e=>Fi(e)===Fi(t))||`Config name ${t} already exists`}}]);return e.uploaderConfig.copy(s,l,String(i.newName)),void e.log.success("Copy config successfully!")}if(!(await t.inquirer.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete ${l}?`,default:!1}])).confirm)return;e.uploaderConfig.remove(s,l),e.log.success("Delete config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}});i.command("list [type]").description("list uploader configurations").action(async t=>{try{const i=e.uploaderConfig.listUploaderTypes();if("string"==typeof t&&t)return i.includes(t)?void console.log(Hi(e,[t])):void e.log.error(`Type ${t} not found`);console.log(Hi(e,i))}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),i.command("rename <type> <oldName> <newName>").description("rename a config").action(async(t,i,n)=>{try{e.uploaderConfig.rename(t,i,n),e.log.success("Rename config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),i.command("copy <type> <configName> <newConfigName>").description("copy a config (does not switch current uploader)").action(async(t,i,n)=>{try{e.uploaderConfig.copy(t,i,n),e.log.success("Copy config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),i.command("rm <type> <configName>").description("remove a config").action(async(t,i)=>{try{e.uploaderConfig.remove(t,i),e.log.success("Delete config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},ki=e=>Ut({text:e}).start(),Vi=async(e,t)=>{try{(e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim();if(!t)throw new Error([e.i18n.translate("CLOUD_COMMAND_LOGIN_REQUIRED"),e.i18n.translate("CLOUD_COMMAND_LOGIN_HINT")].join("\n"))})(e),await t()}catch(t){e.log.error(t instanceof Error?t:new Error(String(t)))}},Ki=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)),qi=e=>{if("string"!=typeof e||""===e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0},ji=e=>({current:String(e.current),total:String(e.total),batchIndex:String(e.batchIndex),batchTotal:String(e.batchTotal),created:String(e.created),skipped:String(e.skipped),failed:String(e.failed)}),Wi=(e,t)=>mt({ctx:e,event:exports.IBuildInEvent.CLOUD_IMPORT_PROGRESS,verbose:t,formatBarText:t=>e.i18n.translate("CLOUD_ALBUM_IMPORT_PROGRESS_BAR",ji(t)),formatVerboseText:t=>e.i18n.translate("CLOUD_ALBUM_IMPORT_VERBOSE_BATCH",ji(t))}),Qi=(e,t)=>{console.log(e.i18n.translate("CLOUD_ALBUM_IMPORT_SUMMARY_TITLE"));const i=[["CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL",t.total],["CLOUD_ALBUM_IMPORT_SUMMARY_CREATED",t.created],["CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED",t.skipped],["CLOUD_ALBUM_IMPORT_SUMMARY_INVALID",t.invalid],["CLOUD_ALBUM_IMPORT_SUMMARY_FAILED",t.failed],["CLOUD_ALBUM_IMPORT_SUMMARY_PENDING",t.pending]];for(const[t,n]of i)console.log(`${e.i18n.translate(t)}: ${n}`);t.pending>0&&console.log(e.i18n.translate("CLOUD_ALBUM_IMPORT_RETRY_HINT"))},zi=e=>{console.log(JSON.stringify(e,null,2))},Ji=e=>{console.log(JSON.stringify(e))},Xi=["active-pro","active-pro-yearly","active-pro-cancel","active-grant","active-grant-lifetime","grace","frozen","pending-cleanup"];function Zi(){const e=process.env.PICGO_MOCK_LIFECYCLE;if(e)return Xi.includes(e)?e:void 0}const en=e=>new Date(Date.now()+864e5*e).toISOString();class tn{client;ctx;constructor(e){this.client=new zt(e),this.ctx=e}async whoami(e){const t=Zi();return t?(this.ctx.log.warn(`[MOCK] UserService.whoami scenario=${t}`),{user:"Mock User",avatar:null,plan:2,autoImport:"active-pro"===(i=t)||"active-pro-yearly"===i||"active-pro-cancel"===i}):await this.client.request({method:"GET",url:"/api/whoami"},e);var i}async setAutoImport(e,t){const i=await this.client.request({method:"PUT",url:"/api/profile/me",data:{extra:{autoImport:e}}},t);return{user:i.user.name,avatar:i.user.image,autoImport:e}}async verifyToken(e){try{const t=await this.whoami(e);return this.ctx.log.success("Welcome:",t.user??"Unknown user"),!0}catch{return!1}}async getUserConfig(e){try{const t=await this.client.request({method:"GET",url:"/api/config"},e);return JSON.parse(t.config)}catch{throw new Error("Failed to fetch user config from server")}}}const nn=e=>e.argument("[dbPath]","path to the local PicGo album database, usually called picgo.db").option("--json-file <path>","read import data from a JSON file").option("--data <json>","read import data from an inline JSON string").option("--verbose","print batch details instead of the progress bar").option("--enable-auto-import","enable auto import before importing when needed").option("--format <format>","output format: pretty | json","pretty"),rn=e=>async(t,i)=>{await Vi(e,async()=>{const n=ki(e.i18n.translate("CLOUD_ALBUM_IMPORT_LOADING_SOURCE"));let r;try{r=await on(e,t,i),n.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE",{count:String(r.items.length)}))}catch(e){throw n.fail(e instanceof Error?e.message:String(e)),e}const o=ki(e.i18n.translate("CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT"));await _n(e,!0===i.enableAutoImport,o);const s=Wi(e,!0===i.verbose);s.spinner.text=e.i18n.translate("CLOUD_ALBUM_IMPORT_UPLOADING"),s.spinner.start();try{const t=await e.cloud.album.import(r.items);s.spinner.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_UPLOADING_DONE")),r.galleryStore&&await ln(r.galleryStore,t.items),"json"===i.format?Ji(t):Qi(e,t)}catch(e){throw s.spinner.fail(e instanceof Error?e.message:String(e)),e}finally{s.dispose()}})},on=async(e,t,i)=>{const n=[t,i.jsonFile,i.data].filter(e=>"string"==typeof e&&""!==e.trim());if(0===n.length)throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED"));if(n.length>1)throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT"));return"string"==typeof t&&""!==t.trim()?await sn(e,t):"string"==typeof i.jsonFile&&""!==i.jsonFile.trim()?{items:await an(e,i.jsonFile)}:{items:cn(e,i.data??"")}},sn=async(i,n)=>{const r=t.resolve(n);if(!await e.pathExists(r))throw new Error(i.i18n.translate("CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE",{path:r}));const o=new f.DBStore(r,"gallery"),s=await o.get();return{galleryStore:o,items:s.data.filter(e=>!0!==e._importToPicGoCloud)}},an=async(e,i)=>{const n=t.resolve(i);try{const t=await C.readFile(n,"utf8");return cn(e,t)}catch{throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE",{path:n}))}},cn=(e,t)=>{const i=e.i18n.translate("CLOUD_ALBUM_IMPORT_INVALID_JSON");let n;try{n=JSON.parse(t)}catch{throw new Error(i)}if(!Array.isArray(n))throw new Error(i);return n},ln=async(e,t)=>{const i=t.map(e=>e.id).filter(e=>"string"==typeof e&&""!==e.trim());0!==i.length&&await e.updateMany(i.map(e=>({id:e,_importToPicGoCloud:!0})))},_n=async(e,t,i)=>{const n=await e.cloud.getUserInfo();if(!Yt(n))throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_PLAN_REQUIRED"));if(n?.autoImport)return void i.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE"));if(t)return i.text=e.i18n.translate("CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT"),await un(e),void i.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED"));i.stop();if(!(await e.cmd.inquirer.prompt([{type:"confirm",name:"enableAutoImport",message:e.i18n.translate("CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT"),default:!0}])).enableAutoImport)throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED"));const r=ki(e.i18n.translate("CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT"));try{await un(e),r.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED"))}catch(e){throw r.fail(e instanceof Error?e.message:String(e)),e}},un=async e=>{const t=new tn(e);await t.setAutoImport(!0),await e.cloud.refreshUserInfo()},En={asc:exports.AlbumListOrder.ASC,desc:exports.AlbumListOrder.DESC},dn={newest:exports.AlbumListSort.NEWEST,oldest:exports.AlbumListSort.OLDEST,fileName:exports.AlbumListSort.FILE_NAME},pn=e=>e.option("--content-type <contentType>","filter by content type").option("--type <uploader-type>",'filter by uploader type. For example: "picgo-cloud", "smms", "imgur"').option("--ext <ext>","filter by extension").option("--search <keyword>","filter by keyword").option("--file-name <fileName>","filter by file name").option("--limit <limit>","set the page size").option("--offset <offset>","set the page offset").option("--sort <field>","sort by newest, oldest, or fileName").option("--order <order>","sort order: asc or desc").option("--format <format>","output format: pretty | json","pretty"),In=e=>{const t=e.url;return"string"==typeof t&&""!==t.trim()?t:e.imgUrl??""},gn=e=>async t=>{await Vi(e,async()=>{const i=Ki({contentType:t.contentType,type:t.type,ext:t.ext,search:t.search,fileName:t.fileName,limit:qi(t.limit),offset:qi(t.offset),sort:fn(t.sort),order:Cn(t.order)}),n=ki(e.i18n.translate("CLOUD_ALBUM_LIST_LOADING")),r=await e.cloud.album.list(i);if(n.succeed(e.i18n.translate("CLOUD_ALBUM_LIST_DONE")),"json"===t.format)return void Ji(r);const o=Math.max(2,...r.items.map(e=>(e.id??"").length));console.log(`${"ID".padEnd(o)}  URL`);for(const e of r.items){const t=(e.id??"").padEnd(o),i=In(e);console.log(`${t}  ${i}`)}console.log(`\nTotal: ${r.total}  Limit: ${r.limit}  Offset: ${r.offset}`)})},Cn=e=>e?En[e]:void 0,fn=e=>e?dn[e]:void 0,hn={logged_in:0,logged_out:1,invalid:2,error:3},Ln=e=>async(t={})=>{const i=await(async e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim();if(!t)return{status:"logged_out",loggedIn:!1};try{const t=await e.cloud.getUserInfo();return t?{status:"logged_in",loggedIn:!0,user:t.user,plan:t.plan}:{status:"invalid",loggedIn:!1}}catch(e){return{status:"error",loggedIn:!1,message:e instanceof Error?e.message:String(e)}}})(e);return"json"===t.format?Ji((e=>{const t={status:e.status,loggedIn:e.loggedIn};return"logged_in"===e.status&&(t.user=e.user??null,"number"==typeof e.plan&&(t.plan=e.plan)),"error"===e.status&&e.message&&(t.message=e.message),t})(i)):((e,t)=>{switch(t.status){case"logged_in":e.log.success(e.i18n.translate("CLOUD_AUTH_STATUS_LOGGED_IN",{user:t.user??""}));break;case"logged_out":e.log.warn(e.i18n.translate("CLOUD_AUTH_STATUS_LOGGED_OUT")),e.log.info(e.i18n.translate("CLOUD_COMMAND_LOGIN_HINT"));break;case"invalid":e.log.warn(e.i18n.translate("CLOUD_AUTH_STATUS_INVALID")),e.log.info(e.i18n.translate("CLOUD_COMMAND_LOGIN_HINT"));break;case"error":e.log.error(e.i18n.translate("CLOUD_AUTH_STATUS_ERROR",{message:t.message??""}))}})(e,i),process.exitCode=hn[i.status],i},On={handle:e=>{const t=e.cmd.program.command("cloud").description("manage PicGo Cloud");t.command("login").description("login to cloud.picgo.app (alias: picgo login)").arguments("[token]").action(St(e)),t.command("logout").description("logout from cloud.picgo.app (alias: picgo logout)").action(Tt(e));const i=t.command("album").description("manage cloud album data");((e,t)=>{nn(t.command("import").description("import local album data into PicGo Cloud")).action(rn(e))})(e,i),((e,t)=>{pn(t.command("list").description("list cloud album items")).action(gn(e))})(e,i),((e,t)=>{t.command("get").description("get one cloud album item").argument("<id>").option("--format <format>","output format: pretty | json","pretty").action(async(t,i)=>{await Vi(e,async()=>{const n=ki(e.i18n.translate("CLOUD_ALBUM_GET_LOADING")),r=await e.cloud.album.get(t);n.succeed(e.i18n.translate("CLOUD_ALBUM_GET_DONE")),"json"===i.format?Ji(r):zi(r)})})})(e,i),((e,t)=>{t.command("update").description("update one cloud album item").argument("<id>").option("--fileName <fileName>","update the file name").option("--imgUrl <imgUrl>","update the image url").option("--originImgUrl <originImgUrl>","update the original image url").option("--contentType <contentType>","update the content type").option("--width <width>","update the width").option("--height <height>","update the height").option("--format <format>","output format: pretty | json","pretty").action(async(t,i)=>{await Vi(e,async()=>{const n=Ki({fileName:i.fileName,imgUrl:i.imgUrl,originImgUrl:i.originImgUrl,contentType:i.contentType,width:qi(i.width),height:qi(i.height)}),r=ki(e.i18n.translate("CLOUD_ALBUM_UPDATE_LOADING")),o=await e.cloud.album.update(t,n);r.succeed(e.i18n.translate("CLOUD_ALBUM_UPDATE_DONE")),"json"===i.format?Ji(o):zi(o)})})})(e,i),((e,t)=>{t.command("delete").description("delete cloud album items").argument("<id...>").option("--force","skip the confirmation prompt").option("--format <format>","output format: pretty | json","pretty").action(async(t,i)=>{await Vi(e,async()=>{if(!0!==i.force&&!(await e.cmd.inquirer.prompt([{type:"confirm",name:"confirm",message:e.i18n.translate("CLOUD_ALBUM_DELETE_CONFIRM",{count:String(t.length)}),default:!1}])).confirm)return;const n=ki(e.i18n.translate("CLOUD_ALBUM_DELETE_LOADING"));await e.cloud.album.delete(1===t.length?t[0]:t),n.succeed(e.i18n.translate("CLOUD_ALBUM_DELETE_DONE"));const r={deleted:t};"json"===i.format?Ji(r):zi(r)})})})(e,i),((e,t)=>{t.command("retry").description("retry pending cloud album imports").option("--verbose","print batch details instead of the progress bar").option("--format <format>","output format: pretty | json","pretty").action(async t=>{await Vi(e,async()=>{const i=ki(e.i18n.translate("CLOUD_ALBUM_RETRY_LOADING_PENDING")),n=await e.cloud.album.getPending();if(0===n.length)return void i.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_NO_PENDING"));i.succeed(e.i18n.translate("CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE",{count:String(n.length)}));const r=Wi(e,!0===t.verbose);r.spinner.text=e.i18n.translate("CLOUD_ALBUM_RETRY_UPLOADING"),r.spinner.start();try{const i=await e.cloud.album.retryPending();r.spinner.succeed(e.i18n.translate("CLOUD_ALBUM_RETRY_UPLOADING_DONE")),"json"===t.format?Ji(i):Qi(e,i)}catch(e){throw r.spinner.fail(e instanceof Error?e.message:String(e)),e}finally{r.dispose()}})})})(e,i);((e,t)=>{const i=Ln(e);t.command("status").description("check PicGo Cloud login status (non-blocking)").option("--format <format>","output format: pretty | json","pretty").action(async e=>{await i(e)})})(e,t.command("auth").description("manage PicGo Cloud auth"));const n=t.command("config").description("manage cloud config");Ni(n.command("sync").description("sync config with picgo cloud (alias: picgo config sync)")).action(Pi(e)),pn(t.command("list").description("list cloud album items (shortcut for cloud album list)")).action(gn(e)),nn(t.command("import").description("import local album data (shortcut for cloud album import)")).action(rn(e))}},Un=e=>"json"===e.format,mn=e=>t=>{const i=(e=>e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||Oe)(e);return Un(t)?console.log(JSON.stringify({uploader:i})):console.log(i),i},Dn=e=>t=>{const i=(e=>{const t=e.getConfig("picgoPlugins")||{};return Object.keys(t).map(e=>({name:e,enabled:!!t[e]}))})(e);return Un(t)?console.log(JSON.stringify({plugins:i})):0===i.length?console.log(e.i18n.translate("GET_PLUGINS_EMPTY")):i.forEach(({name:e,enabled:t})=>{console.log(`${e}\t${t?"enabled":"disabled"}`)}),i},Nn={handle:e=>{const t=e.cmd.program.command("get").description("get current picgo module config (uploader/transformer/plugins)");t.command("uploader").description("get current uploader type").option("--format <format>","output format: pretty | json","pretty").action(t=>{mn(e)(t)}),t.command("transformer").description("get current transformer").option("--format <format>","output format: pretty | json","pretty").action(t=>{(e=>t=>{const i=(e=>e.getConfig("picBed.transformer")||"path")(e);return Un(t)?console.log(JSON.stringify({transformer:i})):console.log(i),i})(e)(t)}),t.command("plugins").description("list installed plugins with enabled/disabled state").option("--format <format>","output format: pretty | json","pretty").action(t=>{Dn(e)(t)})}};class Pn{static currentPlugin;list;pluginIdMap;name;constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){if(!e)throw new TypeError("id is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} duplicate id: ${e}!`);this.list.set(e,t),Pn.currentPlugin&&(this.pluginIdMap.has(Pn.currentPlugin)?this.pluginIdMap.get(Pn.currentPlugin)?.push(e):this.pluginIdMap.set(Pn.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);t?.forEach(e=>{this.list.delete(e)})}}getName(){return this.name}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}const An=(e=null)=>{Pn.currentPlugin=e};class Sn{name="commander";static currentPlugin;list=new Map;pluginIdMap=new Map;ctx;program;inquirer;constructor(e){this.program=new r.Command,this.inquirer=o,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("3.1.0","-v, --version").option("-d, --debug","debug mode",()=>{this.ctx.setConfig({debug:!0})}).option("-s, --silent","silent mode",()=>{this.ctx.setConfig({silent:!0})}).on("command:*",()=>{this.ctx.log.error(`Invalid command: ${this.program.args.join(" ")}\nSee --help for a list of available commands.`),process.exit(1)}),(e=this.ctx).cmd.register("pluginHandler",V),e.cmd.register("configPath",K),e.cmd.register("config",Ai),e.cmd.register("setting",Mi),e.cmd.register("upload",At),e.cmd.register("use",Gi),e.cmd.register("proxy",Bi),e.cmd.register("i18n",wi),e.cmd.register("server",xi),e.cmd.register("login",bi),e.cmd.register("logout",vi),e.cmd.register("cloud",On),e.cmd.register("uploader",Yi),e.cmd.register("get",Nn)}register(e,t){if(!e)throw new TypeError("name is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} plugin duplicate id: ${e}!`);this.list.set(e,t);const i=Pn.currentPlugin;null!==i&&(this.pluginIdMap.has(i)?this.pluginIdMap.get(i)?.push(e):this.pluginIdMap.set(i,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);t?.forEach(e=>{this.list.delete(e)})}}loadCommands(){this.getList().forEach(e=>{try{e.handle(this.ctx)}catch(e){this.ctx.log.error(e)}})}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}class Tn{level={[exports.ILogType.success]:"green",[exports.ILogType.info]:"blue",[exports.ILogType.warn]:"yellow",[exports.ILogType.error]:"red",[exports.ILogType.debug]:"magenta"};ctx;consoleOutput;respectSilent;logLevel;logPath;logPathOverride;constructor(e,t={}){this.ctx=e,this.consoleOutput=t.consoleOutput??!0,this.respectSilent=t.respectSilent??!0,this.logPathOverride=t.logPath}handleLog(e,...i){this.logLevel=this.ctx.getConfig("settings.logLevel");const n=this.ctx.getConfig("silent");if((!this.respectSilent||!n)&&this.checkLogLevel(e,this.logLevel)){const r=_[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);this.consoleOutput&&!n&&console.log(r,...i),this.logPath=this.logPathOverride||this.ctx.getConfig("settings.logPath")||t.join(this.ctx.baseDir,"./picgo.log"),setTimeout(()=>{try{const t=this.checkLogFileIsLarge(this.logPath);if(t.isLarge){const e=`Log file is too large (> ${t.logFileSizeLimit/1024/1024||"10"} MB), recreate log file`;this.consoleOutput&&!n&&console.log(_.yellow("[PicGo WARN]:"),e),this.recreateLogFile(this.logPath),i.unshift(e)}this.handleWriteLog(this.logPath,e,...i)}catch(e){console.error("[PicGo Error] on checking log file size",e)}},0)}}checkLogFileIsLarge(t){if(e.existsSync(t)){const i=e.statSync(t).size,n=1024*ue(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:i>n,logFileSize:i,logFileSizeLimit:n}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,i,...n){try{let r=`${h().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${i.toUpperCase()}] `;n.forEach(e=>{e instanceof Error&&"error"===i?r+=`\n------Error Stack Begin------\n${g.format(e?.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),r+=`${e} `)}),r+="\n",e.appendFileSync(t,r)}catch(e){console.error("[PicGo Error] on writing log file",e)}}checkLogLevel(e,t){return void 0===t||"all"===t||(Array.isArray(t)?t.some(t=>t===e||"all"===t):e===t)}success(...e){return this.handleLog(exports.ILogType.success,...e)}info(...e){return this.handleLog(exports.ILogType.info,...e)}error(...e){return this.handleLog(exports.ILogType.error,...e)}warn(...e){return this.handleLog(exports.ILogType.warn,...e)}debug(...e){Ee()&&this.handleLog(exports.ILogType.debug,...e)}createLogger(e={}){return new Tn(this.ctx,e)}}const Rn=(e,t)=>{const i=void 0===t?{getConfig:e.getConfig.bind(e),saveConfig:e.saveConfig.bind(e),removeConfig:e.removeConfig.bind(e),setConfig:e.setConfig.bind(e),unsetConfig:e.unsetConfig.bind(e)}:((e,t)=>{const i=u.cloneDeep(e.getConfig());u.set(i,"picBed.uploader",t.uploader),u.set(i,"picBed.current",t.uploader),void 0!==t.config&&u.set(i,`picBed.${t.uploader}`,u.cloneDeep(t.config));const n=t=>{le(t)?Object.keys(t).forEach(n=>{if(ce(n))return void e.log.warn(e.i18n.translate("CONFIG_KEY_READ_ONLY",{name:n}));const r=u.cloneDeep(t[n]);u.set(i,n,r)}):e.log.warn(e.i18n.translate("CONFIG_INVALID_FORMAT"))},r=(t,n)=>{t&&n&&(ce(t)?e.log.warn(e.i18n.translate("CONFIG_KEY_CANNOT_UNSET",{key:t})):u.unset(u.get(i,t),n))};return{getConfig:e=>e?u.get(i,e):i,saveConfig:t=>{le(t)?(e.saveConfig(u.cloneDeep(t)),n(u.cloneDeep(t))):e.saveConfig(t)},removeConfig:(t,i)=>{e.removeConfig(t,i),t&&i&&!ce(t)&&r(t,i)},setConfig:e=>{n(e)},unsetConfig:r}})(e,t);return{configPath:e.configPath,baseDir:e.baseDir,log:e.log,cmd:e.cmd,server:e.server,cloud:e.cloud,uploaderConfig:e.uploaderConfig,output:[],input:[],pluginLoader:e.pluginLoader,pluginHandler:e.pluginHandler,Request:e.Request,helper:e.helper,VERSION:e.VERSION,GUI_VERSION:e.GUI_VERSION,request:e.request,openUrl:e.openUrl.bind(e),i18n:e.i18n,...i,upload:e.upload.bind(e),addListener:e.addListener.bind(e),on:e.on.bind(e),once:e.once.bind(e),removeListener:e.removeListener.bind(e),off:e.off.bind(e),removeAllListeners:e.removeAllListeners.bind(e),setMaxListeners:e.setMaxListeners.bind(e),getMaxListeners:e.getMaxListeners.bind(e),listeners:e.listeners.bind(e),rawListeners:e.rawListeners.bind(e),emit:e.emit.bind(e),listenerCount:e.listenerCount.bind(e),prependListener:e.prependListener.bind(e),prependOnceListener:e.prependOnceListener.bind(e),eventNames:e.eventNames.bind(e)}};var yn;exports.UploadOptionErrorCode=void 0,(yn=exports.UploadOptionErrorCode||(exports.UploadOptionErrorCode={})).InvalidOption="INVALID_UPLOAD_OPTION",yn.UnknownUploader="UNKNOWN_UPLOADER",yn.ConfigNotFound="UPLOAD_CONFIG_NOT_FOUND",yn.AmbiguousConfig="UPLOAD_CONFIG_AMBIGUOUS";class Mn extends Error{code;constructor(e,t){super(t),this.name="UploadOptionError",this.code=e}}const Gn=(e,t,i)=>{if(void 0!==i){if("string"!=typeof i||""===i.trim())throw new Mn(exports.UploadOptionErrorCode.InvalidOption,e.i18n.translate("UPLOAD_OPTION_INVALID_PARAMETER",{parameter:t}));return"configName"===t?i.trim():i}},Bn=e=>({uploader:e.uploader,config:structuredClone(e.config)}),wn=e=>e.map(({uploader:e,config:t})=>`${e}/${t._configName} (${t._id})`).join(", "),xn=(e,t,i)=>{const n=[];for(const r of t)for(const t of e.uploaderConfig.getConfigList(r))i(t)&&n.push({uploader:r,config:t});return n},bn=(e,t,i)=>{throw new Mn(exports.UploadOptionErrorCode.ConfigNotFound,e.i18n.translate("UPLOAD_OPTION_CONFIG_NOT_FOUND",{selectors:t,scope:i}))},vn=(e,t,i,n)=>{throw new Mn(exports.UploadOptionErrorCode.AmbiguousConfig,e.i18n.translate("UPLOAD_OPTION_CONFIG_AMBIGUOUS",{selector:t,scope:i,candidates:wn(n)}))},$n=(e,t)=>{const i=((e,t)=>{if(void 0===t)return;const i=Gn(e,"uploader",t.uploader),n=Gn(e,"configName",t.configName),r=Gn(e,"configId",t.configId);return void 0!==i||void 0!==n||void 0!==r?{uploader:i,configName:n,configId:r}:void 0})(e,t);if(void 0===i)return;const n=[...new Set(e.uploaderConfig.listUploaderTypes())],{uploader:r,configName:o,configId:s}=i;if(void 0!==r&&!n.includes(r))throw new Mn(exports.UploadOptionErrorCode.UnknownUploader,e.i18n.translate("UPLOAD_OPTION_UNKNOWN_UPLOADER",{uploader:r,uploaders:`[${n.join(", ")}]`}));const a=void 0===r?n:[r],c=((e,t)=>void 0!==e?`uploader="${e}"`:`uploader=[${t.join(", ")}]`)(r,n);if(void 0===s&&void 0===o&&void 0!==r){const t=e.uploaderConfig.getActiveConfig(r);return void 0!==t?Bn({uploader:r,config:t}):r===Oe?{uploader:r}:bn(e,e.i18n.translate("UPLOAD_OPTION_ACTIVE_CONFIG"),c)}let l=[];if(void 0!==s&&(l=xn(e,a,e=>e._id===s),1===l.length))return Bn(l[0]);if(void 0!==o){const t=o.toLowerCase(),i=xn(e,a,e=>"string"==typeof e._configName&&e._configName.trim().toLowerCase()===t);if(1===i.length)return Bn(i[0]);if(i.length>1){const t=[void 0===s?void 0:`configId="${s}"`,`configName="${o}"`].filter(e=>void 0!==e).join(", ");return vn(e,t,c,i)}}if(l.length>1&&void 0===o)return vn(e,`configId="${s}"`,c,l);const _=[void 0===s?void 0:`configId="${s}"`,void 0===o?void 0:`configName="${o}"`].filter(e=>void 0!==e).join(", ");return bn(e,_,c)},Fn=new Set([Ue]);class Hn extends i.EventEmitter{ctx;constructor(e){super(),this.ctx=e}async start(e,t){const i=$n(this.ctx,t),n=Rn(this.ctx,i);let r=exports.LifecycleStep.IDLE;try{if(!Array.isArray(e))throw new Error("Input must be an array.");return n.input=e,n.output=[],r=exports.LifecycleStep.BEFORE_TRANSFORM,await this.beforeTransform(n),r=exports.LifecycleStep.TRANSFORM,await this.doTransform(n),r=exports.LifecycleStep.BEFORE_UPLOAD,await this.beforeUpload(n),r=exports.LifecycleStep.UPLOAD,await this.doUpload(n),r=exports.LifecycleStep.AFTER_UPLOAD,await this.afterUpload(n,t),n}catch(e){if(r===exports.LifecycleStep.UPLOAD&&n.output.some(e=>void 0!==e.imgUrl))try{r=exports.LifecycleStep.AFTER_UPLOAD,await this.afterUpload(n,t)}catch{}if(n.log.warn(exports.IBuildInEvent.FAILED),n.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),n.emit(exports.IBuildInEvent.FAILED,e),n.log.error(e),n.getConfig("debug"))throw e;return n}}async beforeTransform(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,0),e.emit(exports.IBuildInEvent.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let i=t,n=e.helper.transformer.get(t);return n||(n=e.helper.transformer.get("path"),i="path",e.log.warn(`Can't find transformer - ${t}, switch to default transformer - path`)),e.log.info(`Transforming... Current transformer is [${i}]`),await(n?.handle(e)),e}async beforeUpload(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(exports.IBuildInEvent.BEFORE_UPLOAD,e),await this.handlePlugins(e.helper.beforeUploadPlugins,e),e}async doUpload(e){let t=e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||Oe,i=e.helper.uploader.get(t),n=t;i||(t=Oe,n=Oe,i=e.helper.uploader.get(Oe),e.log.warn(`Can't find uploader - ${t}, switch to default uploader - ${Oe}`)),e.log.info(`Uploading... Current uploader is [${n}]`),await(i?.handle(e));for(const i of e.output)i.type=t;return e}async afterUpload(e,t){e.emit(exports.IBuildInEvent.AFTER_UPLOAD,e),e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,100),(e=>{const t=e.getConfig("settings.urlRewrite.rules");if(Array.isArray(t)&&0!==t.length)for(const i of e.output)Y(i,t,e)})(e),await this.handlePlugins(e.helper.afterUploadPlugins,e);const i=this.buildSuccessMessage(e,t);for(const t of e.output)delete t.base64Image,delete t.buffer;return e.emit(exports.IBuildInEvent.FINISHED,e),e.log.success(`\n${i}`),await this.handlePlugins(e.helper.afterFinishPlugins,e,{consoleOutput:!1}),e}buildSuccessMessage(e,t){if(t?.outputFormat===exports.OutputFormat.JSON)return JSON.stringify(e.output.map(e=>({imgUrl:e.imgUrl,origin:e.origin,fileName:e.fileName,type:e.type,contentType:e.contentType,size:e.size,width:e.width,height:e.height,extname:e.extname})));let i="";const n=e.output.length,r=!0===e.getConfig("settings.encodeOutputURL");for(let t=0;t<n;t++)void 0!==e.output[t].imgUrl&&(i+=r?Q(e.output[t].imgUrl):e.output[t].imgUrl,t!==n-1&&(i+="\n"));return i}async handlePlugins(e,t,i){const n=e.getList(),r=e.getIdList(),o=e.getName();if(!1===i?.consoleOutput){const e=t.log.createLogger?.({consoleOutput:!1});e&&(t.log=e)}return await Promise.all(n.map(async(e,i)=>{try{Fn.has(r[i])||t.log.info(`${o}: ${r[i]} running`),await e.handle(t)}catch(e){throw t.log.error(`${o}: ${r[i]} error`),e}})),t}}const Yn=(e,t,i,n="")=>{const r=n||"s.ee";return{method:"POST",url:`https://${r}${"s.ee"===r?"/api/v1/file/upload":"/api/v2/upload"}`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:i},formData:{smfile:{value:t,options:{filename:e}}}}},kn=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const i=e.output;for(const n of i)if(n.fileName&&n.buffer){let i=n.buffer;!i&&n.base64Image&&(i=Buffer.from(n.base64Image,"base64"));const r=Yn(n.fileName,i,t?.token,t?.backupDomain);try{const t=await e.request(r),i=JSON.parse(t);if(200!==i.code&&"success"!==i.message)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:i.message}),new Error(i.message);delete n.base64Image,delete n.buffer,n.imgUrl=i.data.url}catch(t){throw e.log.error(t),t}}return e},Vn=e=>{const t=e.getConfig("picBed.smms")||{};return[{name:"token",message:"api token",type:"password",get alias(){return e.i18n.translate("PICBED_SMMS_TOKEN")},default:t.token||"",required:!0},{name:"backupDomain",type:"input",get prefix(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},get message(){return e.i18n.translate("PICBED_SMMS_MESSAGE_BACKUP_DOMAIN")},get alias(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},default:t.backupDomain||"",required:!1}]};const Kn=e=>L.lookup(e)||"application/octet-stream",qn=(e,t,i,n)=>{const r=e.secretId,o=e.secretKey,s=e.appId,a=e.bucket;let c,l="";if(e.version&&"v4"!==e.version){const r=Math.floor((new Date).getTime()/1e3);l=`${r};${r+86400}`;const s=I.createHmac("sha1",o).update(l).digest("hex"),a=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,u=`put\n/${e.path}${t}\n\ncontent-length=${n}&content-type=${_=i,encodeURIComponent(_).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}&host=${e.bucket}.${a}\n`,E=`sha1\n${l}\n${I.createHash("sha1").update(u).digest("hex")}\n`;c=I.createHmac("sha1",s).update(E).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,i=`a=${s}&b=${a}&k=${r}&e=${t+3600}&t=${t}&r=${e}&f=`,n=I.createHmac("sha1",o).update(i).digest(),l=Buffer.concat([n,Buffer.from(i)]);c=Buffer.from(l).toString("base64")}var _;return{signature:c,appId:s,bucket:a,signTime:l}},jn=(e,t,i,n,r)=>{const o=e.area,s=e.path;if(e.version&&"v4"!==e.version){const o=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`;return{method:"PUT",url:`http://${e.bucket}.${o}/${z(s,t)}`,headers:{Host:`${e.bucket}.${o}`,Authorization:`q-sign-algorithm=sha1&q-ak=${e.secretId}&q-sign-time=${i.signTime}&q-key-time=${i.signTime}&q-header-list=content-length;content-type;host&q-url-param-list=&q-signature=${i.signature}`,contentType:Kn(t),contentLength:n.byteLength,"User-Agent":`PicGo;${r};null;null`},body:n,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${o}.file.myqcloud.com/files/v2/${i.appId}/${i.bucket}/${z(s,t)}`,headers:{Host:`${o}.file.myqcloud.com`,Authorization:i.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${r};null;null`},formData:{op:"upload",filecontent:n},resolveWithFullResponse:!0}},Wn=async e=>{const t=e.getConfig("picBed.tcyun");if(!t)throw new Error("Can't find tencent COS config");try{const i=e.output,n=t.customUrl,r=t.path,o=!t.version||"v4"===t.version;for(const s of i)if(s.fileName&&s.buffer){let i=s.buffer;!i&&s.base64Image&&(i=Buffer.from(s.base64Image,"base64"));const a=qn(t,s.fileName,Kn(s.fileName),i.byteLength);if(!a)return!1;const c=jn(t,s.fileName,a,i,e.GUI_VERSION||e.VERSION),l=await e.request(c).then(e=>e).catch(t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}}));let _;if(_=o&&"string"==typeof l?JSON.parse(l):l,400===_.statusCode)throw _?.body?.err?_.body.err:new Error(_?.body?.msg||_?.body?.message);const u=t.options||"",E=t.slim||"";if(o&&"SUCCESS"===_.message)delete s.base64Image,delete s.buffer,s.imgUrl=n?`${n}/${r}${s.fileName}`:`${_.data.source_url}${u}`;else{if(o||!_||200!==_.statusCode)throw new Error(l.body.msg);if(delete s.base64Image,delete s.buffer,n)s.imgUrl=`${n}/${encodeURI(r)}${z(s.fileName)}${u}`;else{const e=t.endpoint?t.endpoint:`cos.${t.area}.myqcloud.com`;s.imgUrl=`https://${t.bucket}.${e}/${encodeURI(r)}${z(s.fileName)}${u}`}}E&&(s.imgUrl+=u?"&imageSlim":"?imageSlim")}return e}catch(i){if(!t.version||"v4"===t.version)try{const t=JSON.parse(i.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:t.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw i}},Qn=e=>{const t=e.getConfig("picBed.tcyun")||{};return[{name:"version",type:"list",alias:e.i18n.translate("PICBED_TENCENTCLOUD_VERSION"),choices:["v4","v5"],default:"v5",required:!1},{name:"secretId",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETID")},default:t.secretId||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"appId",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},default:t.appId||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_APPID")},required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_AREA")},required:!0},{name:"endpoint",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},default:t.endpoint||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT")},required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},default:t.path||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_PATH")},required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},default:t.customUrl||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL")},required:!1},{name:"options",type:"input",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_OPTIONS")},required:!1},{name:"slim",type:"confirm",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},required:!1,get confirmText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CONFIRM")},get cancelText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CANCEL")},get tips(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_TIP")}}]};const zn=(e,t,i)=>{const n=t.path||"",{token:r,repo:o}=t;return{method:"PUT",url:`https://api.github.com/repos/${o}/contents/${z(n,e)}`,headers:{Authorization:`token ${r}`,"User-Agent":"PicGo","Content-Type":L.lookup(e)},body:i,json:!0}},Jn=async e=>{const t=e.getConfig("picBed.github");if(!t)throw new Error("Can't find github config");try{const i=e.output;for(const n of i)if(n.fileName&&n.buffer){const i=n.base64Image||Buffer.from(n.buffer).toString("base64"),r={message:"Upload by PicGo",branch:t.branch,content:i,path:t.path+encodeURI(n.fileName)},o=zn(n.fileName,t,r);try{const i=await e.request(o);if(!i)throw new Error("Server error, please try again");delete n.base64Image,delete n.buffer,t.customUrl?n.imgUrl=`${t.customUrl}/${z(t.path||"",n.fileName)}`:n.imgUrl=i.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete n.base64Image,delete n.buffer,t.customUrl?n.imgUrl=`${t.customUrl}/${z(t.path||"",n.fileName)}`:n.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${z(t.path||"",n.fileName)}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},Xn=e=>{const t=e.getConfig("picBed.github")||{};return[{name:"repo",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_REPO")},get alias(){return e.i18n.translate("PICBED_GITHUB_REPO")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_REPO")},default:t.repo||"",required:!0},{name:"branch",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get alias(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_BRANCH")},default:t.branch||"master",required:!0},{name:"token",type:"password",get alias(){return e.i18n.translate("PICBED_GITHUB_TOKEN")},default:t.token||"",required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_PATH")},get alias(){return e.i18n.translate("PICBED_GITHUB_PATH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1}]};function Zn(e,t,i,n){const r=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),o=e.path||"";return{method:"POST",url:`http://upload${r}.qiniup.com/putb64/-1/key/${Buffer.from(o+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${i}`,"Content-Type":L.lookup(t)||"application/octet-stream"},body:n}}function er(e){return e.replace(/\//g,"_").replace(/\+/g,"-")}function tr(e){const t=e.accessKey,i=e.secretKey,n={scope:e.bucket,deadline:3600+Math.floor(Date.now()/1e3)},r=(o=JSON.stringify(n),er(Buffer.from(o).toString("base64")));var o;const s=er(function(e,t){const i=p.createHmac("sha1",t);return i.update(e),i.digest("base64")}(r,i));return[t,s,r].join(":")}const ir=async e=>{const t=e.getConfig("picBed.qiniu");if(!t)throw new Error("Can't find qiniu config");try{const i=e.output;for(const n of i)if(n.fileName&&n.buffer){const i=n.base64Image||Buffer.from(n.buffer).toString("base64"),r=Zn(t,n.fileName,tr(t),i),o=await e.request(r),s=JSON.parse(o);if(!s?.key)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:s.msg}),e.log.error("qiniu error",s),new Error("Upload failed");{delete n.base64Image,delete n.buffer;const e=t.url,i=t.options;n.imgUrl=`${e}/${s.key}${i}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const i=t.response.body;e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:i.error})}throw t}},nr=e=>{const t=e.getConfig("picBed.qiniu")||{};return[{name:"accessKey",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_ACCESSKEY")},default:t.accessKey||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_QINIU_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_BUCKET")},default:t.bucket||"",required:!0},{name:"url",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_URL")},get alias(){return e.i18n.translate("PICBED_QINIU_URL")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_URL")},default:t.url||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_AREA")},get alias(){return e.i18n.translate("PICBED_QINIU_AREA")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_AREA")},default:t.area||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get alias(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_PATH")},get alias(){return e.i18n.translate("PICBED_QINIU_PATH")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_PATH")},default:t.path||"",required:!1}]};const rr=(e,t,i)=>{const n={method:"POST",url:"https://api.imgur.com/3/image",headers:{Authorization:`Client-ID ${e.clientId}`,"content-type":"multipart/form-data",Host:"api.imgur.com","User-Agent":"PicGo"},formData:{image:i,type:"base64",name:t}};return e.proxy&&(n.proxy=e.proxy),n},or=async e=>{const t=e.getConfig("picBed.imgur");if(!t)throw new Error("Can't find imgur config");try{const i=e.output;for(const n of i)if(n.fileName&&n.buffer){const i=n.base64Image||Buffer.from(n.buffer).toString("base64"),r=rr(t,n.fileName,i),o=await e.request(r),s="string"==typeof o?JSON.parse(o):o;if(!s.success)throw new Error("Server error, please try again");delete n.base64Image,delete n.buffer,n.imgUrl=s.data.link}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),t?.response?.data||t}},sr=e=>{const t=e.getConfig("picBed.imgur")||{};return[{name:"clientId",type:"input",get alias(){return e.i18n.translate("PICBED_IMGUR_CLIENTID")},default:t.clientId||"",required:!0},{name:"proxy",type:"input",get prefix(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get alias(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get message(){return e.i18n.translate("PICBED_IMGUR_MESSAGE_PROXY")},default:t.proxy||"",required:!1}]};const ar=(e,t)=>{const i=(new Date).toUTCString(),n=L.lookup(t);if(!n)throw Error(`No mime type found for file ${t}`);const r=`PUT\n\n${n}\n${i}\n/${e.bucket}/${e.path}${t}`,o=I.createHmac("sha1",e.accessKeySecret).update(r).digest("base64");return`OSS ${e.accessKeyId}:${o}`},cr=(e,t,i,n)=>{const r=e.path||"";return{method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${z(r,t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:i,Date:(new Date).toUTCString(),"Content-Type":L.lookup(t)},body:n,resolveWithFullResponse:!0}},lr=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const i=e.output,n=t.customUrl,r=t.path||"";for(const o of i)if(o.fileName&&o.buffer){const i=ar(t,o.fileName);let s=o.buffer;!s&&o.base64Image&&(s=Buffer.from(o.base64Image,"base64"));const a=cr(t,o.fileName,i,s);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");{delete o.base64Image,delete o.buffer;const e=t.options||"";o.imgUrl=n?`${n}/${z(r,o.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${z(r,o.fileName)}${e}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},_r=e=>{const t=e.getConfig("picBed.aliyun")||{};return[{name:"accessKeyId",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYID")},default:t.accessKeyId||"",required:!0},{name:"accessKeySecret",type:"password",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYSECRET")},default:t.accessKeySecret||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_AREA")},required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_OPTIONS")},default:t.options||"",required:!1}]};const ur=(e,t)=>{const i=e.path||"",n=e.operator,r=e.password,o=O(r),s=(new Date).toUTCString(),a=`PUT&${`/${e.bucket}/${z(i,t)}`}&${s}`;return`UPYUN ${n}:${I.createHmac("sha1",o).update(a).digest("base64")}`},Er=(e,t,i,n)=>{const r=e.bucket,o=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${r}/${z(o,t)}`,headers:{Authorization:i,Date:(new Date).toUTCString(),"Content-Type":L.lookup(t)||"application/octet-stream"},body:n,resolveWithFullResponse:!0}},dr=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const i=e.output,n=t.path||"";for(const r of i)if(r.fileName&&r.buffer){let i=r.buffer;!i&&r.base64Image&&(i=Buffer.from(r.base64Image,"base64"));const o=ur(t,r.fileName),s=Er(t,r.fileName,o,i);if(200!==(await e.request(s)).statusCode)throw new Error("Upload failed");delete r.base64Image,delete r.buffer,r.imgUrl=`${t.url}/${z(n,r.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const i=_e(t.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:"object"==typeof i?i.code:i}),text:"http://docs.upyun.com/api/errno/"})}throw t}},pr=e=>{const t=e.getConfig("picBed.upyun")||{};return[{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_BUCKET")},default:t.bucket||"",required:!0},{name:"operator",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get prefix(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPERATOR")},default:t.operator||"",required:!0},{name:"password",type:"password",get prefix(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},get alias(){return e.i18n.translate("PICBED_UPYUN_PASSWORD")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},default:t.password||"",required:!0},{name:"url",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_URL")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_URL")},default:t.url||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get alias(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_PATH")},get alias(){return e.i18n.translate("PICBED_UPYUN_PATH")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PATH")},default:t.path||"",required:!1}]};const Ir=(e,t)=>`${e}:${t}`,gr=e=>{const t=e.indexOf(":");return-1===t?null:{userId:e.slice(0,t),fingerprint:e.slice(t+1)}};class Cr{ctx;constructor(e){this.ctx=e}get(e,t){return this.read().sessions[Ir(e,t)]??null}set(e,t,i){const n=this.read();n.sessions[Ir(e,t)]=i,this.write(n)}remove(e,t){const i=this.read(),n=Ir(e,t);n in i.sessions&&(delete i.sessions[n],this.write(i))}appendCompletedPart(e,t,i){const n=this.read(),r=Ir(e,t),o=n.sessions[r];if(!o)return;const s=[...o.completedParts.filter(e=>e.partNumber!==i.partNumber),i];n.sessions[r]={...o,completedParts:s},this.write(n)}sweepExpired(e=Date.now()){const t=this.read();let i=!1;for(const[n,r]of Object.entries(t.sessions))e-r.createdAt>6048e5&&(delete t.sessions[n],i=!0);i&&this.write(t)}listForUser(e){const t=this.read(),i=`${e}:`,n=[];for(const[e,r]of Object.entries(t.sessions)){if(!e.startsWith(i))continue;const t=gr(e);t&&n.push({fingerprint:t.fingerprint,session:r})}return n}getFilePath(){return U.join(this.ctx.baseDir,"picgo-cloud-multipart-pending.json")}read(){const e=this.getFilePath();if(!m.existsSync(e))return{v:1,sessions:{}};try{const t=m.readFileSync(e,"utf8"),i=JSON.parse(t);return(e=>{if("object"!=typeof e||null===e)return!1;const t=e.v,i=e.sessions;return 1===t&&"object"==typeof i&&null!==i})(i)?i:{v:1,sessions:{}}}catch{return{v:1,sessions:{}}}}write(e){const t=this.getFilePath();try{D.sync(t,JSON.stringify(e,null,2)+"\n")}catch{}}}const fr=[1e3,2e3,4e3];class hr extends Error{status;constructor(e,t){super(e),this.name="PartHttpError",this.status=t}}const Lr=(e,t)=>new Promise((i,n)=>{const r=setTimeout(()=>{t.removeEventListener("abort",o),i()},e),o=()=>{clearTimeout(r),n(new Error("Aborted"))};t.addEventListener("abort",o,{once:!0})}),Or=e=>p.createHash("sha1").update(e).digest("hex").slice(0,16),Ur=e=>{const t=new Map;for(const i of e)t.set(i.partNumber,i);return t};class mr{ctx;authClient;storage;diagLogger;constructor(e){this.ctx=e,this.authClient=new zt(e),this.storage=new Cr(e),this.diagLogger=e.log.createLogger?.({consoleOutput:!1,respectSilent:!1})}async abort(e,t){const i=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(i)try{await this.authClient.request({method:"POST",url:"/api/upload/multipart/abort",data:{uploadId:e,objectKey:t}},i)}catch(t){this.diagLogger?.warn(`[multipart-abort] failed for ${e}: ${Wt(t)}`)}}listPending(){const e=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!e)return[];const t=Or(e);return this.storage.listForUser(t).map(e=>e.session)}removePending(e){const t=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!t)return;const i=Or(t);this.storage.remove(i,e)}getInternals(){return{ctx:this.ctx,authClient:this.authClient,storage:this.storage,diagLogger:this.diagLogger}}}async function Dr(e,t){const i=e.getConfig("settings.picgoCloud.token")?.trim();if(!i)throw new Error(e.i18n.translate("PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED"));const n=t.fileName?.trim();if(!n)throw new Error(e.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME"));let r;try{r=(e=>{if(e.buffer)return e.buffer;if(e.base64Image)return Buffer.from(e.base64Image,"base64");throw new Error("missing-file-data")})(t)}catch{throw new Error(e.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA"))}const o=((e,t)=>{const i=e.contentType?.trim()||e.mimeType?.trim();if(i)return i;const n=L.lookup(t);return"string"==typeof n?n:"application/octet-stream"})(t,n),s=Or(i),a=(e=>p.createHash("sha1").update(e).digest("hex"))(r),c=e.cloud.uploader,{authClient:l,storage:_,diagLogger:u}=c.getInternals();_.sweepExpired();const E=_.get(s,a),d=null!==E;let I,g;if(d)I=E,u?.info(`[multipart] resuming ${n}: ${I.completedParts.length}/${I.partCount} parts done`),g=await Tr(e,l,i,I,u);else{const t=await Sr(e,l,i,r.length,n,o,u);I=t.session,g=t.partUrls,_.set(s,a,I)}const C=await Mr({state:I,userId:s,fingerprint:a,fileName:n,buffer:r,partUrls:g,completed:new Map(I.completedParts.map(e=>[e.partNumber,e])),emitProgress:t=>Ar(e,n,I,Nr(I),t),refreshUrls:()=>yr(e,l,i,I,g,u),diagLogger:u,internalAbort:new AbortController,authClient:l,ctx:e,token:i,resumed:d});I.completedParts=[...C.values()];const f=await wr(e,l,i,I,n,t,u);return _.remove(s,a),f}const Nr=e=>e.completedParts,Pr=(e,t,i)=>{const n=Wt(i,"").trim();return""!==n?n:e.i18n.translate(t)},Ar=(e,t,i,n,r)=>{const o=n.reduce((e,t)=>{const n=(t.partNumber-1)*i.partSize;return e+(Math.min(n+i.partSize,i.size)-n)},0),s=i.size>0?Math.min(o/i.size,1):0,a={fileName:t,current:o,total:i.size,fraction:s,partsCompleted:n.length,totalParts:i.partCount,resumed:r};e.emit(exports.IBuildInEvent.FILE_UPLOAD_PROGRESS,a)},Sr=async(e,t,i,n,r,o,s)=>{try{const s=await t.request({method:"POST",url:"/api/upload/multipart/initiate",data:{filename:r,contentType:o,sizeBytes:n}},i);if(!(s.success&&s.uploadId&&s.objectKey&&s.publicId&&s.url&&s.partSize&&s.partCount&&s.parts))throw new Error(s.message||e.i18n.translate("PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE"));return{session:{v:1,uploadId:s.uploadId,objectKey:s.objectKey,publicId:s.publicId,url:s.url,filename:r,size:n,contentType:o,partSize:s.partSize,partCount:s.partCount,completedParts:[],createdAt:Date.now()},partUrls:Ur(s.parts)}}catch(t){throw xr(e,t),s?.error(`[multipart-initiate] status=${qt(t)??"?"} code=${jt(t)??"-"} server="${Wt(t)}"`),Qt(Pr(e,"PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE",t),t)}},Tr=async(e,t,i,n,r)=>{const o=new Set(n.completedParts.map(e=>e.partNumber)),s=[];for(let e=1;e<=n.partCount;e++)o.has(e)||s.push(e);return 0===s.length?new Map:Rr(e,t,i,n,s,r)},Rr=async(e,t,i,n,r,o)=>{try{const e=await t.request({method:"POST",url:"/api/upload/multipart/part-urls",data:{uploadId:n.uploadId,objectKey:n.objectKey,partNumbers:r}},i);if(!e.success||!e.parts)throw new Error(e.message||"invalid part-urls response");return Ur(e.parts)}catch(t){throw xr(e,t),o?.error(`[multipart-part-urls] status=${qt(t)??"?"} code=${jt(t)??"-"} server="${Wt(t)}"`),Qt(Pr(e,"PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED",t),t)}},yr=async(e,t,i,n,r,o)=>{const s=new Set(n.completedParts.map(e=>e.partNumber)),a=[];for(let e=1;e<=n.partCount;e++)s.has(e)||a.push(e);const c=await Rr(e,t,i,n,a,o);for(const[e,t]of c)r.set(e,t)},Mr=async e=>{const{state:t,userId:i,fingerprint:n,buffer:r,partUrls:o,completed:s,diagLogger:a,internalAbort:c,ctx:l,resumed:_}=e,u=new Set(s.keys()),E=[];for(let e=1;e<=t.partCount;e++)u.has(e)||E.push(e);if(Ar(l,e.fileName,t,[...s.values()],_),0===E.length)return s;let d=null;const p=async()=>{if(d)await d;else{d=e.refreshUrls();try{await d}finally{d=null}}},I={value:null},g=async E=>{const d=(E-1)*t.partSize,I=Math.min(d+t.partSize,t.size),g=r.subarray(d,I);for(let r=0;r<=fr.length;r++){if(c.signal.aborted)throw new Error("Aborted");const d=o.get(E);if(!d)throw new Error(`missing presign for part ${E}`);try{const r=await Br(l,d,g,E),o={partNumber:E,etag:r};s.set(E,o),u.add(E),e.diagLogger?.info(`[multipart] part ${E} done etag=${r}`);return e.ctx.cloud.uploader.getInternals().storage.appendCompletedPart(i,n,o),void Ar(l,e.fileName,t,[...s.values()],_)}catch(o){if(c.signal.aborted)throw o;if(o instanceof hr&&403===o.status){a?.info(`[multipart] part ${E} presign expired (403), refreshing`),await p();continue}if(o instanceof hr&&404===o.status){a?.warn(`[multipart] session ${t.uploadId} not found on server (404); clearing local entry`);throw e.ctx.cloud.uploader.getInternals().storage.remove(i,n),Qt(l.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND"),o)}if(a?.warn(`[multipart] part ${E} attempt ${r} failed: ${qt(o)??"?"} ${Wt(o)}`),r<fr.length){try{await Lr(fr[r],c.signal)}catch{throw o}continue}throw a?.error(`[multipart-part] part ${E} failed after retries: status=${qt(o)??"?"} server="${Wt(o)}"`),Qt(l.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED"),o)}}throw Qt(l.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED"),new Error("exhausted attempts"))},C=[],f=Math.min(3,E.length);for(let e=0;e<f;e++)C.push((async()=>{for(;E.length>0;){if(c.signal.aborted)return;const e=E.shift();if(void 0===e)return;try{await g(e)}catch(e){return null!==I.value||Gr(e)||(I.value=e instanceof Error?e:new Error(String(e))),void c.abort()}}})());await Promise.all(C);const h=I.value;if(null!==h)throw h;return s},Gr=e=>e instanceof Error&&"Aborted"===e.message,Br=async(e,t,i,n)=>{try{const r={method:t.method,url:t.url,data:i,headers:t.headers??{},resolveWithFullResponse:!0,maxContentLength:1/0,maxBodyLength:1/0},o=(await e.request(r)).headers??{},s=o.etag??o.ETag??o.Etag;if(!s)throw new Error(`part ${n} response missing ETag header`);return s}catch(e){const t=qt(e);if("number"==typeof t)throw new hr(`part ${n} HTTP ${t}`,t);throw e}},wr=async(e,t,i,n,r,o,s)=>{if(n.completedParts.length!==n.partCount)throw Qt(e.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED"),new Error("part count mismatch at complete"));const a=[...n.completedParts].sort((e,t)=>e.partNumber-t.partNumber);try{await t.request({method:"POST",url:"/api/upload/multipart/complete",data:{uploadId:n.uploadId,objectKey:n.objectKey,parts:a}},i)}catch(t){throw xr(e,t),s?.error(`[multipart-complete] status=${qt(t)??"?"} code=${jt(t)??"-"} server="${Wt(t)}"`),Qt(Pr(e,"PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED",t),t)}try{const e=await t.request({method:"POST",url:"/api/album-items/complete",data:{objectKey:n.objectKey,publicId:n.publicId,filename:r,..."number"==typeof o.width?{width:o.width}:{},..."number"==typeof o.height?{height:o.height}:{}}},i),s=e.data?.item,a=s?.imgUrl;if(!e.success||"string"!=typeof a||0===a.length)throw new Error(e.message||"invalid album-items complete response");return{imgUrl:a,..."number"==typeof s?.width?{width:s.width}:{},..."number"==typeof s?.height?{height:s.height}:{},..."number"==typeof s?.size?{size:s.size}:{},..."string"==typeof s?.contentType?{contentType:s.contentType}:{}}}catch(t){throw xr(e,t),s?.error(`[album-items-complete] status=${qt(t)??"?"} code=${jt(t)??"-"} server="${Wt(t)}"`),Qt(Pr(e,"PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE",t),t)}},xr=(e,t)=>{if(!d.isAxiosError(t))return;if(401===qt(t))throw e.removeConfig("settings.picgoCloud","token"),Qt(e.i18n.translate("PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED"),t)};class br{ctx;client;constructor(e){this.ctx=e,this.client=new zt(e)}async upload(e){const t=this.getToken(),i=this.getFileName(e),n=this.getImageBuffer(e),r=this.getContentType(e,i);if(n.length>=10485760)return await Dr(this.ctx,e);const o=Date.now(),s=await this.callAuthenticatedStep(async()=>await this.client.request({method:"POST",url:"/api/upload/presign",data:{filename:i,...r?{contentType:r}:{}}},t));if(this.ctx.log.debug("Presign duration",Date.now()-o,"ms"),!(s.success&&s.objectKey&&s.publicId&&s.uploadUrl))throw new Error(s.message||this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE"));const a=this.buildUploadHeaders(s.headers,r),c=Date.now();await async function(e,t,i){const n=t.onUploadProgress,r=i.partsCompleted??-1,o=i.totalParts??-1,s=i.resumed??!1,a={...t,onUploadProgress:t=>{n?.(t);const a=("number"==typeof t.total?t.total:void 0)??i.totalBytes??0,c=t.loaded,l=a>0?Math.min(c/a,1):0,_={fileName:i.fileName,current:c,total:a,fraction:l,partsCompleted:r,totalParts:o,resumed:s};e.emit(exports.IBuildInEvent.FILE_UPLOAD_PROGRESS,_)}};return e.request(a)}(this.ctx,{method:"PUT",url:s.uploadUrl,data:n,headers:a,resolveWithFullResponse:!0},{fileName:i,totalBytes:n.length}),this.ctx.log.debug("Upload duration",Date.now()-c,"ms");const l=Date.now(),_=await this.callAuthenticatedStep(async()=>await this.client.request({method:"POST",url:"/api/album-items/complete",data:{objectKey:s.objectKey,publicId:s.publicId,filename:i,..."number"==typeof e.width?{width:e.width}:{},..."number"==typeof e.height?{height:e.height}:{}}},t)),u=Date.now();this.ctx.log.debug("Complete duration",u-l,"ms"),this.ctx.log.debug("All duration",u-o,"ms");const E=_.data?.item,d=E?.imgUrl;if(!_.success||"string"!=typeof d||0===d.length)throw new Error(_.message||this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE"));return{imgUrl:d,..."number"==typeof E?.width?{width:E.width}:{},..."number"==typeof E?.height?{height:E.height}:{},..."number"==typeof E?.size?{size:E.size}:{},..."string"==typeof E?.contentType?{contentType:E.contentType}:{}}}getToken(){const e=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!e)throw new Error(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED"));return e}getFileName(e){const t=e.fileName?.trim();if(!t)throw new Error(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME"));return t}getImageBuffer(e){if(e.buffer)return e.buffer;if(e.base64Image)return Buffer.from(e.base64Image,"base64");throw new Error(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA"))}getContentType(e,t){const i=e.contentType?.trim()||e.mimeType?.trim();if(i)return i;const n=L.lookup(t);return"string"==typeof n?n:void 0}buildUploadHeaders(e,t){const i={...e||{}};if(!t)return i;return Object.keys(i).some(e=>"content-type"===e.toLowerCase())||(i["Content-Type"]=t),i}async callAuthenticatedStep(e){try{return await e()}catch(e){if(d.isAxiosError(e)){if(401===qt(e))throw this.ctx.removeConfig("settings.picgoCloud","token"),Qt(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED"),e);const t=Wt(e);if(""!==t.trim())throw Qt(t,e)}throw e}}}const vr=e=>U.join(e.baseDir,"picgo-cloud-import-list.log"),$r=e=>({total:e.total,created:e.created,skipped:e.skipped,invalid:e.invalid,failed:e.failed,pending:e.pending}),Fr=async(e,t)=>{const i={...t,source:"upload",timestamp:(new Date).toISOString()},n=e.log.createLogger?.({logPath:vr(e),consoleOutput:!1,respectSilent:!1});n?.info(JSON.stringify(i))},Hr=()=>[],Yr=async e=>{const t=new br(e);for(const i of e.output)try{const e=await t.upload(i);delete i.base64Image,delete i.buffer,i.imgUrl=e.imgUrl,void 0!==e.width&&(i.width=e.width),void 0!==e.height&&(i.height=e.height),void 0!==e.size&&(i.size=e.size),void 0!==e.contentType&&(i.contentType=e.contentType)}catch(t){if(t instanceof Error)throw e.log.error(t),t;throw new Error(e.i18n.translate("UPLOAD_FAILED"))}return e},kr=e=>{const t="string"==typeof e.GUI_VERSION&&""!==e.GUI_VERSION.trim(),i=!0===e.getConfig("picgoInternal.serverMode");return t||i},Vr=async e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim(),i=e.output.filter(e=>e.type!==Oe);if(!t||0===i.length)return(e=>e.some(e=>e.type===Oe))(e.output)&&e.emit(exports.IBuildInEvent.CLOUD_ALBUM_UPDATED,{items:[]}),void await Fr(e,{status:"skipped",itemCount:i.length,reason:t?"no_eligible_items":"missing_token"});try{const t=await e.cloud.getUserInfo();if(!Yt(t))return void await Fr(e,{status:"skipped",itemCount:i.length,reason:"plan_required"});if(!t?.autoImport)return void await Fr(e,{status:"skipped",itemCount:i.length,reason:"auto_import_disabled"});(e=>{for(const t of e)"string"==typeof t.id&&""!==t.id.trim()||(t.id=p.randomUUID())})(i);const n=await e.cloud.album.import(i);if(n.failed>0)return await Fr(e,{status:"partial",itemCount:i.length,result:$r(n)}),void e.emit(exports.IBuildInEvent.CLOUD_ALBUM_UPDATED,{items:n.items});const r=await e.cloud.album.retryPending();await Fr(e,{status:"success",itemCount:i.length,result:$r(n),retryPending:$r(r)});const o=[...n.items,...r.items];e.emit(exports.IBuildInEvent.CLOUD_ALBUM_UPDATED,{items:o})}catch(t){const n=Wt(t),r=qt(t),o=jt(t);if(!(401===r||403===r||o===xt.DuplicateId))try{await e.cloud.album.addToPending(i)}catch{}await Fr(e,{status:"failed",itemCount:i.length,error:{message:n,..."number"==typeof r?{status:r}:{},..."string"==typeof o?{code:o}:{}}})}},Kr=e=>{(e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim();t&&e.cloud.getUserInfo().catch(()=>{})})(e)},qr=e=>{kr(e)&&setImmediate(()=>{(()=>Vr(e))().catch(()=>{})})},jr=async e=>{kr(e)||await Vr(e)};const Wr=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:lr,config:_r})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:Wn,config:Qn})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:kn,config:Vn})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:Jn,config:Xn})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:ir,config:nr})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:or,config:sr})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:dr,config:pr})}(e),function(e){e.helper.uploader.register(Oe,{name:"PicGo Cloud",handle:Yr,config:Hr}),e.on(exports.IBuildInEvent.BEFORE_UPLOAD,Kr),e.on(exports.IBuildInEvent.AFTER_UPLOAD,qr),e.helper.afterFinishPlugins.register(Ue,{handle:jr})}(e)}}),Qr=(e,t,i)=>{const n=J(t);return n.real||("string"==typeof i?e.log.warn(`can't get ${i}'s image size`):e.log.warn("can't get image size"),e.log.warn("fallback to 200 * 200")),n};var zr={handle:async e=>{const t=e.output;return await Promise.all(e.input.map(async(i,n)=>{let r;if(r=Buffer.isBuffer(i)?{success:!0,buffer:i,fileName:"",extname:""}:W(i)?await Z(i,e):await X(i),r.success&&r.buffer){const o=Qr(e,r.buffer,i),s=r.extname||o.extname||".png";t[n]={buffer:r.buffer,fileName:r.fileName||`${h().format("YYYYMMDDHHmmssSSS")}${s}`,width:o.width,height:o.height,filePath:r.filePath,extname:s,size:r.buffer?.length||0,contentType:L.lookup(s)||"application/octet-stream",origin:"string"==typeof i?i:void 0}}else e.log.error(r.reason)})),e.output=t.filter(e=>e),e}};var Jr={handle:async e=>(e.output.push(...e.input),e)};class Xr{ctx;list=[];fullList=new Set;pluginMap=new Map;constructor(e){this.ctx=e,this.init()}init(){const i=t.join(this.ctx.baseDir,"package.json");if(!e.existsSync(i)){const t={name:"picgo-plugins",description:"picgo-plugins",repository:"https://github.com/PicGo/PicGo-Core",license:"MIT"};e.writeFileSync(i,JSON.stringify(t),"utf8")}}resolvePlugin(e,i){try{return N.sync(i,{basedir:e.baseDir})}catch(n){return t.join(e.baseDir,"node_modules",i)}}load(){const i=t.join(this.ctx.baseDir,"package.json"),n=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(n))return!1;const r=e.readJSONSync(i),o=Object.keys(r.dependencies||{}),s=Object.keys(r.devDependencies||{}),a=o.concat(s).filter(t=>{if(!/^picgo-plugin-|^@[^/]+\/picgo-plugin-/.test(t))return!1;const i=this.resolvePlugin(this.ctx,t);return e.existsSync(i)});for(const e of a)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),An(e);const i=t(this.ctx);this.pluginMap.set(e,i),i.register(this.ctx)}else if(!0===this.ctx.getConfig(`picgoPlugins.${e}`)||void 0===this.ctx.getConfig(`picgoPlugins.${e}`)){this.list.push(e),An(e),this.getPlugin(e).register(this.ctx);const t=`picgoPlugins[${e}]`;this.ctx.saveConfig({[t]:!0})}}catch(t){this.pluginMap.delete(e),this.list=this.list.filter(t=>t!==e),this.fullList.delete(e),this.ctx.log.error(t),this.ctx.emit(exports.IBuildInEvent.NOTIFICATION,{title:`Plugin ${e} Load Error`,body:t})}}else this.ctx.log.warn("Please provide valid plugin")}unregisterPlugin(e){this.list=this.list.filter(t=>t!==e),this.fullList.delete(e),this.pluginMap.delete(e),An(e),this.ctx.helper.uploader.unregister(e),this.ctx.helper.transformer.unregister(e),this.ctx.helper.beforeTransformPlugins.unregister(e),this.ctx.helper.beforeUploadPlugins.unregister(e),this.ctx.helper.afterUploadPlugins.unregister(e),this.ctx.helper.afterFinishPlugins.unregister(e),this.ctx.cmd.unregister(e),this.ctx.removeConfig("picgoPlugins",e)}getPlugin(e){if(this.pluginMap.has(e))return this.pluginMap.get(e);const i=t.join(this.ctx.baseDir,"node_modules/"),n=require(i+e)(this.ctx);return this.pluginMap.set(e,n),n}getList(){return this.list}hasPlugin(e){return this.fullList.has(e)}getFullList(){return[...this.fullList]}}const Zr={darwin:'-- From https://github.com/mushanshitiancai/vscode-paste-image\nproperty fileTypes : {{«class PNGf», ".png"}}\n\non run argv\n\tif argv is {} then\n\t\treturn ""\n\tend if\n\n\tif ((clipboard info) as string) contains "«class furl»" then\n\t\treturn POSIX path of (the clipboard as «class furl»)\n\telse\n\t\tset imagePath to (item 1 of argv)\n\t\tset theType to getType()\n\n\t\tif theType is not missing value then\n\t\t\ttry\n\t\t\t\tset myFile to (open for access imagePath with write permission)\n\t\t\t\tset eof myFile to 0\n\t\t\t\twrite (the clipboard as (first item of theType)) to myFile\n\t\t\t\tclose access myFile\n\t\t\t\treturn (POSIX path of imagePath)\n\t\t\ton error\n\t\t\t\ttry\n\t\t\t\t\tclose access myFile\n\t\t\t\tend try\n\t\t\t\treturn "no image"\n\t\t\tend try\n\t\telse\n\t\t\treturn "no image"\n\t\tend if\n\tend if\nend run\n\non getType()\n\trepeat with aType in fileTypes\n\t\trepeat with theInfo in (clipboard info)\n\t\t\tif (first item of theInfo) is equal to (first item of aType) then return aType\n\t\tend repeat\n\tend repeat\n\treturn missing value\nend getType\n',win32:'\nparam($imagePath)\n\n# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\n\nAdd-Type -Assembly PresentationCore\n$img = [Windows.Clipboard]::GetImage()\n\nif ($img -eq $null) {\n    "no image"\n    Exit 1\n}\n\nif (-not $imagePath) {\n    "no image"\n    Exit 1\n}\n\n$fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n$stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n$encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n$encoder.Save($stream) | out-null\n$stream.Dispose() | out-null\n\n$imagePath\n',win10:'# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\nparam($imagePath)\n\n# https://github.com/PowerShell/PowerShell/issues/7233\n# fix the output encoding bug\n[console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding\n\nAdd-Type -Assembly PresentationCore\nfunction main {\n    $img = [Windows.Clipboard]::GetImage()\n\n    if ($img -eq $null) {\n        "no image"\n        Exit 1\n    }\n\n    if (-not $imagePath) {\n        "no image"\n        Exit 1\n    }\n\n    $fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n    $stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n    $encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n    $encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n    $encoder.Save($stream) | out-null\n    $stream.Dispose() | out-null\n\n    $imagePath\n    # fix windows 10 native cmd crash bug when "picgo upload"\n    # https://github.com/PicGo/PicGo-Core/issues/32\n    Exit 1\n}\n\ntry {\n    # For WIN10\n    $file = Get-Clipboard -Format FileDropList\n    if ($file -ne $null) {\n        Convert-Path $file\n        Exit 1\n    }\n} catch {\n    # For WIN7 WIN8 WIN10\n    main\n}\n\nmain',linux:'#!/bin/sh\nif [ "$XDG_SESSION_TYPE" = "x11" ]; then\n  # require xclip(see http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script/677212#677212)\n  command -v xclip >/dev/null 2>&1 || { echo >&1 "no xclip"; exit 1; }\n  # write image in clipboard to file (see http://unix.stackexchange.com/questions/145131/copy-image-from-clipboard-to-file)\n  filePath=`xclip -selection clipboard -o 2>/dev/null | grep ^file:// | cut -c8-`\n  if [ ! -n "$filePath" ] ;then\n    if\n        xclip -selection clipboard -target image/png -o >/dev/null 2>&1\n    then\n        xclip -selection clipboard -target image/png -o >$1 2>/dev/null\n        echo $1\n    else\n        echo "no image"\n    fi\n  else\n    echo $filePath\n  fi\nelif [ "$XDG_SESSION_TYPE" = "wayland" ]; then\n  command -v wl-paste >/dev/null 2>&1 || { echo >&1 "no wl-clipboard"; exit 1; }\n  isImage=`wl-paste --list-types | grep image`\n  if [ -n "$isImage" ]; then\n    wl-paste --type image/png > $1 2>/dev/null\n    echo $1\n  else\n    echo "no image"\n    exit 1\n  fi\nelse\n  # fallback for unsupported session types\n  echo >&2 "Error: Unsupported session type \'$XDG_SESSION_TYPE\'."\n  echo >&2 "Solution: The variable of XDG_SESSION_TYPE must set as \'x11\' or \'wayland\'."\n  exit 1\nfi\n',wsl:'#!/bin/sh\n# grab the paths\nscriptPath=$(echo $0 | awk \'{ print substr( $0, 1, length($0)-6 ) }\')"windows10.ps1"\nimagePath=$(echo $1 | awk \'{ print substr( $0, 1, length($0)-18 ) }\')\nimageName=$(echo $1 | awk \'{ print substr( $0, length($0)-17, length($0) ) }\')\n\n# run the powershell script\nres=$(powershell.exe -noprofile -noninteractive -nologo -sta -executionpolicy unrestricted -file $(wslpath -w $scriptPath) $(wslpath -w $imagePath)"\\\\"$imageName)\n\n# note that there is a return symbol in powershell result\nnoImage=$(echo "no image\\r")\n\n# check whether image exists\nif [ "$res" = "$noImage" ] ;then\n    echo "no image"\nelse\n    echo $(wslpath -u -a "${res}")\nfi\n'},eo={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const to=async i=>{!function(i){const n=t.join(i.baseDir,Le);e.existsSync(n)||e.mkdirSync(n)}(i);const r=(o=i.baseDir,U.join(o,Le,`${h().format("YYYYMMDDHHmmssSSS")}.png`));var o;return await new Promise((o,s)=>{const a=(()=>{const e=process.platform;if(A)return"wsl";if("win32"===e)return"10"===n.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),c=t.join(i.baseDir,eo[a]);let l;e.existsSync(c)||e.writeFileSync(c,Zr[a],"utf8"),l="darwin"===a?P.spawn("osascript",[c,r]):"win32"===a||"win10"===a?P.spawn("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",c,r]):P.spawn("sh",[c,r]),l.stdout.on("data",n=>{if("linux"===a&&"no xclip or wl-clipboard"===n.toString().trim())return i.emit(exports.IBuildInEvent.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),s(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const c=n.toString().trim();let l=!1;if(t.basename(c)!==t.basename(r)&&e.existsSync(c)&&(l=!0),"no image"!==c&&!e.existsSync(c))return s(new Error(`Can't find ${c}`));o({imgPath:c,shouldKeepAfterUploading:l})})})},io=new i.EventEmitter,no=new T.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function ro(e,t,i){"object"==typeof i&&"value"in i&&"options"in i?e.append(t,i.value,i.options):e.append(t,i)}function oo(e){return{...e,statusCode:e.status,body:e.data}}function so(e){const t={method:e?.config?.method?.toUpperCase()||"",url:e?.config?.url||"",statusCode:e?.response?.status||0,message:e?.message||"",stack:e?.stack||{},response:{status:e?.response?.status||0,statusCode:e?.response?.status||0,body:e?.response?.data||""}};return Promise.reject(t)}class ao{ctx;proxy="";options={};constructor(e){this.ctx=e,this.init(),io.on(exports.IBusEvent.CONFIG_CHANGE,e=>{switch(e.configName){case"picBed":e.value?.proxy&&(this.proxy=e.value.proxy);break;case"picBed.proxy":this.proxy=e.value}})}init(){const e=this.ctx.getConfig("picBed.proxy");e&&(this.proxy=e)}handleProxy(){if(this.proxy)try{const e=new a.URL(this.proxy);return{host:e.hostname,port:parseInt(e.port||"0",10),protocol:e.protocol}}catch(e){}return!1}request(e){this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.withCredentials=!0,this.options.proxy&&e.url?.startsWith("https://")?(this.options.httpsAgent=R.httpsOverHttp({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=no;const t=d.create(this.options);t.interceptors.response.use(oo,so);const i=function(e){let t=!1;const i={...e,url:e.url||"",headers:e.headers||{}};if(e.proxy){let n=e.proxy;if("string"==typeof n){try{n=new a.URL(e.proxy)}catch(e){n=!1,i.proxy=!1,console.error(e)}t=!0}n&&(e.url?.startsWith("https://")?(i.proxy=!1,i.httpsAgent=R.httpsOverHttp({proxy:{host:n?.hostname,port:parseInt(n?.port,10)}})):i.proxy={host:n.hostname,port:parseInt(n.port,10),protocol:"http"})}if("formData"in e){const n=new S;for(const t in e.formData)ro(n,t,e.formData[t]);i.data=n,i.headers=Object.assign(i.headers||{},n.getHeaders()),t=!0,delete i.formData}return"body"in e&&(i.data=e.body,t=!0,delete i.body),"qs"in e&&(i.params=e.qs,t=!0),i.__isOldOptions=t,i}(e);return t.interceptors.request.use(function(e){let t="";return e?.headers?.contentType?(t=e.headers.contentType,delete e.headers.contentType):e?.headers?.ContentType?(t=e.headers.ContentType,delete e.headers.ContentType):e?.headers?.["content-type"]&&(t=e.headers["content-type"],delete e.headers["content-type"]),""!==t&&e.headers&&(e.headers["Content-Type"]=t),e}),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?t.request(i):t.request(i).then(t=>i.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data)}}class co{ctx;db;constructor(e){if(this.ctx=e,this.db=new f.JSONStore(this.ctx.configPath),!this.db.has("picBed"))try{this.db.set("picBed",{uploader:Oe,current:Oe})}catch(e){throw this.ctx.log.error(e),e}if(!this.db.has("picgoPlugins"))try{this.db.set("picgoPlugins",{})}catch(e){throw this.ctx.log.error(e),e}}read(e){return this.db.read(e)}get(e=""){return this.read(!0),this.db.get(e)}set(e,t){return this.read(!0),this.db.set(e,t)}has(e){return this.read(!0),this.db.has(e)}unset(e,t){return this.read(!0),this.db.unset(e,t)}saveConfig(e){Object.keys(e).forEach(t=>{this.set(t,e[t])})}removeConfig(e){Object.keys(e).forEach(t=>{this.unset(t,e[t])})}}class lo{ctx;constructor(e){this.ctx=e}async install(e,t={},i){const n=[],r=e.map(e=>_o(this.ctx,e)).filter(e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(n.push(e.pkgName),this.ctx.log.success(`PicGo has already installed ${e.pkgName}`),!1):!!e.success),o=r.map(e=>e.fullName),s=r.map(e=>e.pkgName);if(o.length>0){const e=await this.execCommand("install",o,this.ctx.baseDir,t,i);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:t});return{success:!1,body:t}}s.forEach(e=>{this.ctx.pluginLoader.registerPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...s,...n]});return{success:!0,body:[...s,...n]}}if(0===n.length){const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:e});return{success:!1,body:e}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...s,...n]});return{success:!0,body:[...s,...n]}}async uninstall(e,t){const i=e.map(e=>_o(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(i.length>0){const e=await this.execCommand("uninstall",i,this.ctx.baseDir,void 0,t);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:t});return{success:!1,body:t}}i.forEach(e=>{this.ctx.pluginLoader.unregisterPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS")),this.ctx.emit("uninstallSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS"),body:i});return{success:!0,body:i}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:e});return{success:!1,body:e}}}async update(e,t={},i){const n=e.map(e=>_o(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(n.length>0){const e=await this.execCommand("update",n,this.ctx.baseDir,t,i);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:t});return{success:!1,body:t}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS")),this.ctx.emit("updateSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS"),body:n});return{success:!0,body:n}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:e});return{success:!1,body:e}}}async execCommand(e,t,i,n={},r={}){const o=n.npmRegistry||this.ctx.getConfig("settings.npmRegistry"),s=n.npmProxy||this.ctx.getConfig("settings.npmProxy");return await new Promise(n=>{let a=[e].concat(t).concat("--color=always").concat("--save");o&&(a=a.concat(`--registry=${o}`)),s&&(a=a.concat(`--proxy=${s}`));try{const e=y("npm",a,{cwd:i,env:Object.assign({},process.env,r)});let t="";e.stdout?.on("data",e=>{t+=e}).pipe(process.stdout),e.stderr?.on("data",e=>{t+=e}).pipe(process.stderr),e.on("close",e=>{n(e?{code:e,data:t}:{code:0,data:t})}),e.on("error",e=>{this.ctx.log.error(e),this.ctx.log.error("NPM is not installed"),this.ctx.emit(exports.IBuildInEvent.FAILED,"NPM is not installed")})}catch(e){this.ctx.log.error(e),this.ctx.emit(exports.IBuildInEvent.FAILED,e)}})}}const _o=(e,t)=>{const i={success:!1,fullName:"",pkgName:""},n=ne(t,e.log);if(!n)return i;const r=re(n,e.log);return r?{success:!0,fullName:n,pkgName:r}:i},uo={"zh-CN":{UPLOAD_FAILED:"上传失败",CHECK_SETTINGS:"请检查你的配置项是否正确",CHECK_SETTINGS_AND_NETWORK:"请检查你的配置项以及网络",UPLOAD_FAILED_REASON:"错误码：${code}，请打开浏览器粘贴地址查看相关原因",SERVER_ERROR:"服务端出错，请重试",AUTH_FAILED:"认证失败",CONFIG_INVALID_FORMAT:"配置格式无效，请重新配置。",CONFIG_KEY_READ_ONLY:"无法修改 config.${name}。",CONFIG_KEY_CANNOT_UNSET:"无法删除 config.${key}。",UPLOAD_OPTION_INVALID_PARAMETER:"上传参数“${parameter}”无效：请提供一个非空字符串值。",UPLOAD_OPTION_ACTIVE_CONFIG:"当前配置（优先使用默认 ID，其次使用首个已保存配置）",UPLOAD_OPTION_UNKNOWN_UPLOADER:"图床“${uploader}”尚未注册。可用图床：${uploaders}。",UPLOAD_OPTION_CONFIG_NOT_FOUND:"在${scope}中找不到匹配${selectors}的上传配置。",UPLOAD_OPTION_CONFIG_AMBIGUOUS:"${scope}中的上传配置${selector}存在歧义。匹配项：${candidates}。请指定图床或唯一的配置 ID。",CLOUD_LOGIN_CANCELLED:"登录已取消",CLOUD_LOGIN_IN_PROGRESS:"登录正在进行中",CLOUD_LOGIN_INVALID_TOKEN:"无效的 token",CLOUD_LOGIN_SUCCESS:"登录成功！",CLOUD_LOGOUT_SUCCESS:"退出登录成功！",CLOUD_LOGIN_SERVER_START_FAILED:"启动登录服务失败",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"无法自动打开浏览器：${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"请在浏览器中打开该链接：${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State 校验失败或缺失，请求已拦截",CLOUD_LOGIN_STATE_INVALID:"State 无效，请重新登录。",CLOUD_LOGIN_TOKEN_MISSING:"回调中缺少 token。",CLOUD_LOGIN_CODE_MISSING:"回调中缺少 code。",CLOUD_LOGIN_EXCHANGE_FAILED:"登录 code 交换失败。",CLOUD_LOGIN_NOT_IN_PROGRESS:"当前没有进行中的登录流程。",CLOUD_LOGIN_PAGE_TITLE:"PicGo 登录",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"授权成功！",CLOUD_LOGIN_RESULT_FAILED_TITLE:"授权失败",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"你可以关闭此窗口并返回 PicGo。",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"请先登录 PicGo Cloud 后再使用该图床。",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"PicGo Cloud 登录状态已失效，请重新登录后再试。",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloud 返回的上传凭证无效。",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloud 返回的完成上传响应无效。",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"缺少文件名，无法上传到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"缺少图片数据，无法上传到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloud 返回的分片上传初始化响应无效。",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"分片上传会话已失效，请重新上传。",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"分片上传中某个分片重试多次仍失败。",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"分片上传完成请求失败。",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"上传 ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"上传 ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} parts)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:"（续传）",CLOUD_ALBUM_PENDING_INVALID_FILE:"待重试队列文件无效，已按空队列处理：${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"云端相册导入功能未开启，请先启用自动导入。",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"云端相册导入需要 PicGo Cloud 付费套餐。",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"自动导入未完全完成，当前待重试队列共有 ${count} 条记录。",CLOUD_COMMAND_LOGIN_REQUIRED:"请先登录 PicGo Cloud。",CLOUD_COMMAND_LOGIN_HINT:"请先执行 `picgo login`（或 `picgo cloud login`）后再重试。",CLOUD_AUTH_STATUS_LOGGED_IN:"已登录 PicGo Cloud（用户：${user}）",CLOUD_AUTH_STATUS_LOGGED_OUT:"未登录 PicGo Cloud。",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloud 登录状态已失效，请重新登录。",CLOUD_AUTH_STATUS_ERROR:"无法检测 PicGo Cloud 登录状态：${message}",GET_PLUGINS_EMPTY:"没有已安装的插件。",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"云端相册导入功能未开启，是否立即开启？",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"正在开启云端相册自动导入...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"已开启云端相册自动导入。",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"这些数据已经导入过 PicGo Cloud。",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"正在导入 ${current}/${total}（批次 ${batchIndex}/${batchTotal}）",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"批次 ${batchIndex}/${batchTotal}：已处理 ${current}/${total}，成功 ${created}，跳过 ${skipped}，失败 ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"导入结果",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"总数",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"成功创建",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"跳过",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"无效",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"失败",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"待重试",CLOUD_ALBUM_IMPORT_RETRY_HINT:"你可以执行 `picgo cloud album retry` 继续重试待处理条目。",CLOUD_ALBUM_IMPORT_NO_PENDING:"没有待重试的条目。",CLOUD_ALBUM_LIST_LOADING:"正在获取云端相册列表...",CLOUD_ALBUM_LIST_DONE:"已获取云端相册列表",CLOUD_ALBUM_GET_LOADING:"正在获取云端相册数据...",CLOUD_ALBUM_GET_DONE:"已获取云端相册数据",CLOUD_ALBUM_UPDATE_LOADING:"正在更新云端相册数据...",CLOUD_ALBUM_UPDATE_DONE:"已更新云端相册数据",CLOUD_ALBUM_DELETE_LOADING:"正在删除云端相册数据...",CLOUD_ALBUM_DELETE_DONE:"已删除云端相册数据",CLOUD_ALBUM_DELETE_CONFIRM:"确定从云端相册删除 ${count} 条记录？",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"请提供导入来源：数据库路径、`--json-file` 或 `--data`。",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"数据库路径、`--json-file` 和 `--data` 只能选择一种。",CLOUD_ALBUM_IMPORT_INVALID_JSON:"导入数据不是合法的 JSON 数组。",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"读取导入 JSON 文件失败：${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"正在加载导入数据...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"已加载 ${count} 条数据",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"正在检查云端导入状态...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"云端导入状态检查完毕",CLOUD_ALBUM_IMPORT_UPLOADING:"正在导入到云端...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"云端导入完成",CLOUD_ALBUM_RETRY_LOADING_PENDING:"正在加载待重试队列...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"已加载 ${count} 条待重试数据",CLOUD_ALBUM_RETRY_UPLOADING:"正在重试导入...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"重试导入完成",SERVER_INVALID_JSON_BODY:"JSON 请求体无效",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"请求体无效：需要 { list: string[] }",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-data 的 files 字段未找到文件",SERVER_FORMDATA_FILES_MUST_BE_FILES:"form-data 无效：files 必须是文件",SERVER_AUTH_ENABLED:"[PicGo Server] 认证已启用。",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 警告：认证已关闭，任何人都可以上传图片。",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] 未授权的请求，来源 ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 警告：通过 URL 参数传递 secret 不安全，请使用 Authorization Header。",URL_REWRITE_EMPTY_RESULT:"URL 重写结果为空，请检查你的规则配置",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"设定Token",PICBED_SMMS_BACKUP_DOMAIN:"备用上传域名",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 sm.ms",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"设定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"设定KeySecret",PICBED_ALICLOUD_BUCKET:"设定Bucket",PICBED_ALICLOUD_AREA:"设定存储区域",PICBED_ALICLOUD_PATH:"设定存储路径",PICBED_ALICLOUD_CUSTOMURL:"设定自定义域名",PICBED_ALICLOUD_OPTIONS:"设定网址后缀",PICBED_ALICLOUD_MESSAGE_AREA:"例如：oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如：test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如：?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如：https://test.com",PICBED_TENCENTCLOUD:"腾讯云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"设定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"设定SecretKey",PICBED_TENCENTCLOUD_APPID:"设定AppId",PICBED_TENCENTCLOUD_BUCKET:"设定Bucket",PICBED_TENCENTCLOUD_AREA:"设定存储区域",PICBED_TENCENTCLOUD_ENDPOINT:"设定Endpoint",PICBED_TENCENTCLOUD_PATH:"设定存储路径",PICBED_TENCENTCLOUD_OPTIONS:"设定网址后缀",PICBED_TENCENTCLOUD_CUSTOMURL:"设定自定义域名",PICBED_TENCENTCLOUD_SLIM:"极智压缩",PICBED_TENCENTCLOUD_SLIM_TIP:"图片极智压缩，详情请参考[文档说明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"开启",PICBED_TENCENTCLOUD_SLIM_CANCEL:"关闭",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如：1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如：ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如：cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如：test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如：https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如：?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"设定Token",PICBED_GITHUB_REPO:"设定仓库名",PICBED_GITHUB_PATH:"设定存储路径",PICBED_GITHUB_BRANCH:"设定分支名",PICBED_GITHUB_CUSTOMURL:"设定自定义域名",PICBED_GITHUB_MESSAGE_REPO:"格式：username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如：main",PICBED_GITHUB_MESSAGE_PATH:"例如：test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如：https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"设定AccessKey",PICBED_QINIU_SECRETKEY:"设定SecretKey",PICBED_QINIU_BUCKET:"设定Bucket",PICBED_QINIU_PATH:"设定存储路径",PICBED_QINIU_URL:"设定访问网址",PICBED_QINIU_OPTIONS:"设定网址后缀",PICBED_QINIU_AREA:"设定存储区域",PICBED_QINIU_MESSAGE_PATH:"例如：test/",PICBED_QINIU_MESSAGE_AREA:"例如：z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如：?imageslim",PICBED_QINIU_MESSAGE_URL:"例如：https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"设定ClientId",PICBED_IMGUR_PROXY:"设定代理",PICBED_IMGUR_MESSAGE_PROXY:"例如：http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"设定Bucket",PICBED_UPYUN_OPERATOR:"设定操作员",PICBED_UPYUN_PASSWORD:"设定操作员密码",PICBED_UPYUN_PATH:"设定存储路径",PICBED_UPYUN_URL:"设定加速域名",PICBED_UPYUN_OPTIONS:"设定网址后缀",PICBED_UPYUN_MESSAGE_OPERATOR:"例如：me",PICBED_UPYUN_MESSAGE_PASSWORD:"输入操作员密码",PICBED_UPYUN_MESSAGE_URL:"例如：http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如：!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如：test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安装成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安装失败",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安装失败，失败码为${code}，错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安装失败，请输入合法插件名或合法安装路径",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸载成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸载失败",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸载失败，失败码为${code}，错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸载失败，请输入合法插件名",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失败",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失败，失败码为${code}，错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失败，请输入合法插件名",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:'配置无效：settings.picgoCloud.encryptionMethod 必须是 "auto"、"sse" 或 "e2ee" 之一，当前为：${value}',CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"端到端加密",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"服务端加密",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"确认切换加密方式吗？",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:"您正在从“${from}”切换为“${to}”。\n\n注意：切换加密模式将清空您所有的云端历史版本记录。\n这是因为旧的历史版本无法在新模式下被解密或验证。\n切换后，系统将立即为您创建一份新的备份作为起点。",CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"确认切换并清空历史",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"取消",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"已取消切换加密方式",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"需要提供加密方式切换确认处理器"},"zh-TW":{UPLOAD_FAILED:"上傳失敗",CHECK_SETTINGS:"請檢查你的設定是否正確",CHECK_SETTINGS_AND_NETWORK:"請檢查你的設定及網路",UPLOAD_FAILED_REASON:"錯誤碼：${code}，請打開瀏覽器貼上地址查看相關原因",SERVER_ERROR:"伺服器出錯，請重試",AUTH_FAILED:"認證失敗",CONFIG_INVALID_FORMAT:"設定格式無效，請重新設定。",CONFIG_KEY_READ_ONLY:"無法修改 config.${name}。",CONFIG_KEY_CANNOT_UNSET:"無法刪除 config.${key}。",UPLOAD_OPTION_INVALID_PARAMETER:"上傳參數「${parameter}」無效：請提供一個非空字串值。",UPLOAD_OPTION_ACTIVE_CONFIG:"目前設定（優先使用預設 ID，其次使用第一個已儲存設定）",UPLOAD_OPTION_UNKNOWN_UPLOADER:"圖床「${uploader}」尚未註冊。可用圖床：${uploaders}。",UPLOAD_OPTION_CONFIG_NOT_FOUND:"在${scope}中找不到符合${selectors}的上傳設定。",UPLOAD_OPTION_CONFIG_AMBIGUOUS:"${scope}中的上傳設定${selector}存在歧義。符合項目：${candidates}。請指定圖床或唯一的設定 ID。",CLOUD_LOGIN_CANCELLED:"登入已取消",CLOUD_LOGIN_IN_PROGRESS:"登入正在進行中",CLOUD_LOGIN_INVALID_TOKEN:"無效的 token",CLOUD_LOGIN_SUCCESS:"登入成功！",CLOUD_LOGOUT_SUCCESS:"登出成功！",CLOUD_LOGIN_SERVER_START_FAILED:"啟動登入服務失敗",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"無法自動打開瀏覽器：${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"請在瀏覽器中打開此連結：${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State 驗證失敗或缺失，請求已攔截",CLOUD_LOGIN_STATE_INVALID:"State 無效，請重新登入。",CLOUD_LOGIN_TOKEN_MISSING:"回呼中缺少 token。",CLOUD_LOGIN_CODE_MISSING:"回呼中缺少 code。",CLOUD_LOGIN_EXCHANGE_FAILED:"登入 code 交換失敗。",CLOUD_LOGIN_NOT_IN_PROGRESS:"目前沒有進行中的登入流程。",CLOUD_LOGIN_PAGE_TITLE:"PicGo 登入",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"授權成功！",CLOUD_LOGIN_RESULT_FAILED_TITLE:"授權失敗",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"你可以關閉此視窗並返回 PicGo。",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"請先登入 PicGo Cloud 後再使用此圖床。",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"PicGo Cloud 登入狀態已失效，請重新登入後再試。",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloud 回傳的上傳憑證無效。",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloud 回傳的完成上傳回應無效。",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"缺少檔名，無法上傳到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"缺少圖片資料，無法上傳到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloud 回傳的分片上傳初始化回應無效。",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"分片上傳工作階段已失效，請重新上傳。",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"分片上傳中某個分片重試多次仍失敗。",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"分片上傳完成請求失敗。",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"上傳 ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"上傳 ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} parts)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:"（續傳）",CLOUD_ALBUM_PENDING_INVALID_FILE:"待重試佇列檔案無效，已視為空佇列處理：${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"雲端相簿匯入功能未開啟，請先啟用自動匯入。",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"雲端相簿匯入需要 PicGo Cloud 付費方案。",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"自動匯入未完全完成，目前待重試佇列共有 ${count} 筆記錄。",CLOUD_COMMAND_LOGIN_REQUIRED:"請先登入 PicGo Cloud。",CLOUD_COMMAND_LOGIN_HINT:"請先執行 `picgo login`（或 `picgo cloud login`）後再重試。",CLOUD_AUTH_STATUS_LOGGED_IN:"已登入 PicGo Cloud（使用者：${user}）",CLOUD_AUTH_STATUS_LOGGED_OUT:"未登入 PicGo Cloud。",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloud 登入狀態已失效，請重新登入。",CLOUD_AUTH_STATUS_ERROR:"無法檢測 PicGo Cloud 登入狀態：${message}",GET_PLUGINS_EMPTY:"沒有已安裝的外掛。",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"雲端相簿匯入功能未開啟，是否立即開啟？",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"正在開啟雲端相簿自動匯入...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"已開啟雲端相簿自動匯入。",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"這些資料已經匯入過 PicGo Cloud。",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"正在匯入 ${current}/${total}（批次 ${batchIndex}/${batchTotal}）",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"批次 ${batchIndex}/${batchTotal}：已處理 ${current}/${total}，成功 ${created}，跳過 ${skipped}，失敗 ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"匯入結果",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"總數",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"成功建立",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"跳過",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"無效",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"失敗",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"待重試",CLOUD_ALBUM_IMPORT_RETRY_HINT:"你可以執行 `picgo cloud album retry` 繼續重試待處理項目。",CLOUD_ALBUM_IMPORT_NO_PENDING:"沒有待重試的項目。",CLOUD_ALBUM_LIST_LOADING:"正在取得雲端相簿列表...",CLOUD_ALBUM_LIST_DONE:"已取得雲端相簿列表",CLOUD_ALBUM_GET_LOADING:"正在取得雲端相簿資料...",CLOUD_ALBUM_GET_DONE:"已取得雲端相簿資料",CLOUD_ALBUM_UPDATE_LOADING:"正在更新雲端相簿資料...",CLOUD_ALBUM_UPDATE_DONE:"已更新雲端相簿資料",CLOUD_ALBUM_DELETE_LOADING:"正在刪除雲端相簿資料...",CLOUD_ALBUM_DELETE_DONE:"已刪除雲端相簿資料",CLOUD_ALBUM_DELETE_CONFIRM:"確定要從雲端相簿刪除 ${count} 筆記錄嗎？",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"請提供一種匯入來源：資料庫路徑、`--json-file` 或 `--data`。",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"資料庫路徑、`--json-file` 和 `--data` 只能擇一使用。",CLOUD_ALBUM_IMPORT_INVALID_JSON:"匯入資料必須是合法的 JSON 陣列。",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"讀取匯入 JSON 檔案失敗：${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"正在載入匯入資料...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"已載入 ${count} 筆資料",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"正在檢查雲端匯入狀態...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"雲端匯入狀態檢查完畢",CLOUD_ALBUM_IMPORT_UPLOADING:"正在匯入至雲端...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"雲端匯入完成",CLOUD_ALBUM_RETRY_LOADING_PENDING:"正在載入待重試佇列...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"已載入 ${count} 筆待重試資料",CLOUD_ALBUM_RETRY_UPLOADING:"正在重試匯入...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"重試匯入完成",SERVER_INVALID_JSON_BODY:"JSON 請求內容無效",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"請求內容無效：需要 { list: string[] }",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-data 的 files 欄位未找到檔案",SERVER_FORMDATA_FILES_MUST_BE_FILES:"form-data 無效：files 必須是檔案",SERVER_AUTH_ENABLED:"[PicGo Server] 認證已啟用。",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 警告：認證已關閉，任何人都可以上傳圖片。",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] 未授權的請求，來源 ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 警告：透過 URL 參數傳遞 secret 不安全，請使用 Authorization Header。",URL_REWRITE_EMPTY_RESULT:"URL 重寫結果為空，請檢查你的規則設定",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"設定Token",PICBED_SMMS_BACKUP_DOMAIN:"備用上傳網址",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 sm.ms",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"設定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"設定KeySecret",PICBED_ALICLOUD_BUCKET:"設定Bucket",PICBED_ALICLOUD_AREA:"設定儲存區域",PICBED_ALICLOUD_PATH:"設定儲存路徑",PICBED_ALICLOUD_CUSTOMURL:"設定自訂網址",PICBED_ALICLOUD_OPTIONS:"設定網址後綴",PICBED_ALICLOUD_MESSAGE_AREA:"例如：oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如：test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如：?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如：https://test.com",PICBED_TENCENTCLOUD:"騰訊云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"設定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"設定SecretKey",PICBED_TENCENTCLOUD_APPID:"設定AppId",PICBED_TENCENTCLOUD_BUCKET:"設定Bucket",PICBED_TENCENTCLOUD_AREA:"設定儲存區域",PICBED_TENCENTCLOUD_ENDPOINT:"設定Endpoint",PICBED_TENCENTCLOUD_PATH:"設定儲存路徑",PICBED_TENCENTCLOUD_OPTIONS:"設定網址後綴",PICBED_TENCENTCLOUD_SLIM:"極智壓縮",PICBED_TENCENTCLOUD_SLIM_CANCEL:"關閉",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"開啓",PICBED_TENCENTCLOUD_SLIM_TIP:"圖片極智壓縮，詳情請參考[文檔說明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_CUSTOMURL:"設定自訂網址",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如：1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如：ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如：cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如：test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如：https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如：?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"設定Token",PICBED_GITHUB_REPO:"設定倉庫名稱",PICBED_GITHUB_PATH:"設定儲存路徑",PICBED_GITHUB_BRANCH:"設定分支名稱",PICBED_GITHUB_CUSTOMURL:"設定自訂網址",PICBED_GITHUB_MESSAGE_REPO:"格式：username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如：main",PICBED_GITHUB_MESSAGE_PATH:"例如：test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如：https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"設定AccessKey",PICBED_QINIU_SECRETKEY:"設定SecretKey",PICBED_QINIU_BUCKET:"設定Bucket",PICBED_QINIU_PATH:"設定儲存路徑",PICBED_QINIU_URL:"設定訪問網址",PICBED_QINIU_OPTIONS:"設定網址後綴",PICBED_QINIU_AREA:"設定儲存區域",PICBED_QINIU_MESSAGE_PATH:"例如：test/",PICBED_QINIU_MESSAGE_AREA:"例如：z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如：?imageslim",PICBED_QINIU_MESSAGE_URL:"例如：https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"設定ClientId",PICBED_IMGUR_PROXY:"設定PROXY",PICBED_IMGUR_MESSAGE_PROXY:"例如：http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"設定Bucket",PICBED_UPYUN_OPERATOR:"設定操作員",PICBED_UPYUN_PASSWORD:"設定操作員密碼",PICBED_UPYUN_PATH:"設定儲存路徑",PICBED_UPYUN_URL:"設定加速網址",PICBED_UPYUN_OPTIONS:"設定網址後綴",PICBED_UPYUN_MESSAGE_OPERATOR:"例如：me",PICBED_UPYUN_MESSAGE_PASSWORD:"輸入操作員密碼",PICBED_UPYUN_MESSAGE_URL:"例如：http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如：!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如：test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安裝成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安裝失敗",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安裝失敗，失敗碼為${code}，錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安裝失敗，請輸入正確的插件名稱或正確的安裝路徑",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸載成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸載失敗",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸載失敗，失敗碼為${code}，錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸載失敗，請輸入正確的插件名稱",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失敗",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失敗，失敗碼為${code}，錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失敗，請輸入正確的插件名稱",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"設定無效：settings.picgoCloud.encryptionMethod 必須是「auto」、「sse」或「e2ee」之一，目前為：${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"端對端加密",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"伺服器端加密",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"確認切換加密方式嗎？",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:"您正在從「${from}」切換為「${to}」。\n\n注意：切換加密模式將清空您所有的雲端歷史版本記錄。\n這是因為舊的歷史版本無法在新模式下被解密或驗證。\n切換後，系統將立即為您建立一份新的備份作為起點。",CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"確認切換並清空歷史",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"取消",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"已取消切換加密方式",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"需要提供加密方式切換確認處理器"},en:{UPLOAD_FAILED:"Upload failed",CHECK_SETTINGS:"Please check your settings",CHECK_SETTINGS_AND_NETWORK:"Please check your settings and network",UPLOAD_FAILED_REASON:"Error code: ${code}, please open the browser and paste the address to see the reason",SERVER_ERROR:"Server error, please try again later",AUTH_FAILED:"Authentication failed",CONFIG_INVALID_FORMAT:"Invalid configuration format. Please reconfigure.",CONFIG_KEY_READ_ONLY:"config.${name} cannot be modified.",CONFIG_KEY_CANNOT_UNSET:"config.${key} cannot be unset.",UPLOAD_OPTION_INVALID_PARAMETER:'Invalid upload option parameter "${parameter}": provide one non-empty string value.',UPLOAD_OPTION_ACTIVE_CONFIG:"the active configuration (default ID, then first saved configuration)",UPLOAD_OPTION_UNKNOWN_UPLOADER:'Uploader "${uploader}" is not registered. Available uploaders: ${uploaders}.',UPLOAD_OPTION_CONFIG_NOT_FOUND:"No upload configuration matched ${selectors} in ${scope}.",UPLOAD_OPTION_CONFIG_AMBIGUOUS:"Upload configuration ${selector} is ambiguous in ${scope}. Matches: ${candidates}. Specify an uploader or a unique configuration ID.",CLOUD_LOGIN_CANCELLED:"Login cancelled",CLOUD_LOGIN_IN_PROGRESS:"Login is already in progress",CLOUD_LOGIN_INVALID_TOKEN:"Invalid token",CLOUD_LOGIN_SUCCESS:"Login success!",CLOUD_LOGOUT_SUCCESS:"Logout success!",CLOUD_LOGIN_SERVER_START_FAILED:"Failed to start PicGo server for login",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"Failed to open browser automatically: ${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"Please open this url in browser: ${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State mismatch or missing. Request blocked.",CLOUD_LOGIN_STATE_INVALID:"Invalid state. Please try logging in again.",CLOUD_LOGIN_TOKEN_MISSING:"Token missing in callback.",CLOUD_LOGIN_CODE_MISSING:"Code missing in callback.",CLOUD_LOGIN_EXCHANGE_FAILED:"Failed to exchange login code.",CLOUD_LOGIN_NOT_IN_PROGRESS:"Login flow is not in progress.",CLOUD_LOGIN_PAGE_TITLE:"PicGo Auth",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"Authorization Successful!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"Authorization Failed",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"You can now close this window and return to PicGo.",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"Please log in to PicGo Cloud before using this uploader.",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"Your PicGo Cloud session has expired. Please log in again and retry.",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloud returned an invalid upload presign response.",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloud returned an invalid upload completion response.",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"Missing file name. Unable to upload to PicGo Cloud.",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"Missing image data. Unable to upload to PicGo Cloud.",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloud returned an invalid multipart upload initiate response.",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"Multipart upload session has expired. Please upload again.",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"A part failed to upload after multiple retries.",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"Multipart upload completion request failed.",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"Uploading ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"Uploading ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} parts)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:" (resumed)",CLOUD_ALBUM_PENDING_INVALID_FILE:"Pending import queue file is invalid and has been treated as empty: ${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"Cloud album auto import is disabled. Please enable auto import first.",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"Cloud album import requires a paid PicGo Cloud plan.",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"Automatic import did not finish completely. The pending queue now contains ${count} item(s).",CLOUD_COMMAND_LOGIN_REQUIRED:"Please log in to PicGo Cloud first.",CLOUD_COMMAND_LOGIN_HINT:"Run `picgo login` (or `picgo cloud login`) and try again.",CLOUD_AUTH_STATUS_LOGGED_IN:"Logged in to PicGo Cloud (user: ${user})",CLOUD_AUTH_STATUS_LOGGED_OUT:"Not logged in to PicGo Cloud.",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloud session is invalid. Please log in again.",CLOUD_AUTH_STATUS_ERROR:"Failed to check PicGo Cloud status: ${message}",GET_PLUGINS_EMPTY:"No installed plugins.",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"Cloud album auto import is disabled. Enable it now?",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"Enabling cloud album auto import...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"Cloud album auto import has been enabled.",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"These items have already been imported to PicGo Cloud.",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"Importing ${current}/${total} (batch ${batchIndex}/${batchTotal})",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"Batch ${batchIndex}/${batchTotal}: processed ${current}/${total}, created ${created}, skipped ${skipped}, failed ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"Import summary",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"Total",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"Created",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"Skipped",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"Invalid",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"Failed",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"Pending",CLOUD_ALBUM_IMPORT_RETRY_HINT:"Run `picgo cloud album retry` to retry the pending items.",CLOUD_ALBUM_IMPORT_NO_PENDING:"There are no pending items to retry.",CLOUD_ALBUM_LIST_LOADING:"Fetching cloud album list...",CLOUD_ALBUM_LIST_DONE:"Fetched cloud album list",CLOUD_ALBUM_GET_LOADING:"Fetching cloud album item...",CLOUD_ALBUM_GET_DONE:"Fetched cloud album item",CLOUD_ALBUM_UPDATE_LOADING:"Updating cloud album item...",CLOUD_ALBUM_UPDATE_DONE:"Updated cloud album item",CLOUD_ALBUM_DELETE_LOADING:"Deleting cloud album item(s)...",CLOUD_ALBUM_DELETE_DONE:"Deleted cloud album item(s)",CLOUD_ALBUM_DELETE_CONFIRM:"Delete ${count} item(s) from the cloud album?",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"Provide one import source: a database path, `--json-file`, or `--data`.",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"Only one import source is allowed: database path, `--json-file`, or `--data`.",CLOUD_ALBUM_IMPORT_INVALID_JSON:"Import data must be a valid JSON array.",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"Failed to read the import JSON file: ${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"Loading import data...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"Loaded ${count} item(s)",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"Checking cloud import status...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"Cloud import status verified",CLOUD_ALBUM_IMPORT_UPLOADING:"Importing to cloud...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"Cloud import finished",CLOUD_ALBUM_RETRY_LOADING_PENDING:"Loading pending items...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"Loaded ${count} pending item(s)",CLOUD_ALBUM_RETRY_UPLOADING:"Retrying import...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"Retry import finished",SERVER_INVALID_JSON_BODY:"Invalid JSON body",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"Invalid request body: { list: string[] } required",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"No files found in form-data: files",SERVER_FORMDATA_FILES_MUST_BE_FILES:"Invalid form-data: files must be file(s)",SERVER_AUTH_ENABLED:"[PicGo Server] Authentication enabled.",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] Warning: Authentication disabled. Anyone can upload images.",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] Unauthorized request from ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] Warning: Passing secret via URL query is insecure. Please use Authorization header.",URL_REWRITE_EMPTY_RESULT:"URL rewrite produced an empty result, please check your rule config",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"Set Token",PICBED_SMMS_BACKUP_DOMAIN:"Set Backup Upload Domain",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"Ex. sm.ms",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"Set KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"Set KeySecret",PICBED_ALICLOUD_BUCKET:"Set Bucket",PICBED_ALICLOUD_AREA:"Set Area",PICBED_ALICLOUD_PATH:"Set Path",PICBED_ALICLOUD_CUSTOMURL:"Set Custom URL",PICBED_ALICLOUD_OPTIONS:"Set URL Suffix",PICBED_ALICLOUD_MESSAGE_AREA:"Ex. oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"Ex. test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"Ex. ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"Choose COS version",PICBED_TENCENTCLOUD_SECRETID:"Set SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"Set SecretKey",PICBED_TENCENTCLOUD_APPID:"Set AppId",PICBED_TENCENTCLOUD_BUCKET:"Set Bucket",PICBED_TENCENTCLOUD_AREA:"Set Area",PICBED_TENCENTCLOUD_ENDPOINT:"Set Endpoint",PICBED_TENCENTCLOUD_PATH:"Set Path",PICBED_TENCENTCLOUD_OPTIONS:"Set URL Suffix",PICBED_TENCENTCLOUD_SLIM:"Set ImageSlim",PICBED_TENCENTCLOUD_SLIM_TIP:"Image extremely intelligent compression, please refer to the [document description](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"OPEN",PICBED_TENCENTCLOUD_SLIM_CANCEL:"CLOSE",PICBED_TENCENTCLOUD_CUSTOMURL:"Set Custom URL",PICBED_TENCENTCLOUD_MESSAGE_APPID:"Ex. 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"Ex. ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"Ex. cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"Ex. test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"Ex. http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"Ex. ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Set Token",PICBED_GITHUB_REPO:"Set Repo Name",PICBED_GITHUB_PATH:"Set Path",PICBED_GITHUB_BRANCH:"Set Branch",PICBED_GITHUB_CUSTOMURL:"Set Custom URL",PICBED_GITHUB_MESSAGE_REPO:"Ex. username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"Ex. main",PICBED_GITHUB_MESSAGE_PATH:"Ex. test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"Set AccessKey",PICBED_QINIU_SECRETKEY:"Set SecretKey",PICBED_QINIU_BUCKET:"Set Bucket",PICBED_QINIU_PATH:"Set Path",PICBED_QINIU_URL:"Set URL",PICBED_QINIU_OPTIONS:"Set URL Suffix",PICBED_QINIU_AREA:"Set Area",PICBED_QINIU_MESSAGE_PATH:"Ex. test/",PICBED_QINIU_MESSAGE_AREA:"Ex. z0",PICBED_QINIU_MESSAGE_OPTIONS:"Ex. ?imageslim",PICBED_QINIU_MESSAGE_URL:"Ex. https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"Set ClientId",PICBED_IMGUR_PROXY:"Set Proxy",PICBED_IMGUR_MESSAGE_PROXY:"Ex. http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Set Bucket",PICBED_UPYUN_OPERATOR:"Set Operator",PICBED_UPYUN_PASSWORD:"Set Operator Password",PICBED_UPYUN_PATH:"Set Path",PICBED_UPYUN_URL:"Set URL",PICBED_UPYUN_OPTIONS:"Set URL Suffix",PICBED_UPYUN_MESSAGE_OPERATOR:"Ex. me",PICBED_UPYUN_MESSAGE_PASSWORD:"Please type the operator password",PICBED_UPYUN_MESSAGE_URL:"Ex. http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"Ex. !imgslim",PICBED_UPYUN_MESSAGE_PATH:"Ex. test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"Plugin installed successfully",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"Plugin installation failed",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"Plugin installation failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"Plugin installation failed, please enter a valid plugin name or valid installation path",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"Plugin uninstalled successfully",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"Plugin uninstall failed",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"Plugin uninstall failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"Plugin uninstall failed, please enter a valid plugin name",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"Plugin updated successfully",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"Plugin update failed",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"Plugin update failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"Plugin update failed, please enter a valid plugin name",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"Invalid configuration: settings.picgoCloud.encryptionMethod must be one of 'auto', 'sse', 'e2ee'. Found: ${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"End-to-end encryption",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"Server-side encryption",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"Confirm switch encryption method?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:'You are switching from "${from}" to "${to}".\n\nNote: Switching encryption modes will clear all your cloud history versions.\nThis is because older history versions cannot be decrypted or verified under the new mode.\nAfter switching, the system will immediately create a new backup as the starting point.',CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"Confirm switch and clear history",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"Cancel",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"Encryption switch cancelled by user",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"Encryption switch confirmation handler is required"},ko:{UPLOAD_FAILED:"업로드 실패",CHECK_SETTINGS:"설정을 확인해 주세요",CHECK_SETTINGS_AND_NETWORK:"설정과 네트워크를 확인해 주세요",UPLOAD_FAILED_REASON:"오류 코드: ${code}, 브라우저를 열고 주소를 붙여넣어 원인을 확인해 주세요",SERVER_ERROR:"서버 오류, 나중에 다시 시도해 주세요",AUTH_FAILED:"인증 실패",CONFIG_INVALID_FORMAT:"설정 형식이 올바르지 않습니다. 다시 설정해 주세요.",CONFIG_KEY_READ_ONLY:"config.${name}은(는) 수정할 수 없습니다.",CONFIG_KEY_CANNOT_UNSET:"config.${key}은(는) 삭제할 수 없습니다.",UPLOAD_OPTION_INVALID_PARAMETER:'업로드 매개변수 "${parameter}"이(가) 올바르지 않습니다. 비어 있지 않은 문자열 값 하나를 입력해 주세요.',UPLOAD_OPTION_ACTIVE_CONFIG:"현재 설정(기본 ID, 이후 첫 번째 저장된 설정)",UPLOAD_OPTION_UNKNOWN_UPLOADER:'업로더 "${uploader}"이(가) 등록되지 않았습니다. 사용 가능한 업로더: ${uploaders}.',UPLOAD_OPTION_CONFIG_NOT_FOUND:"${scope}에서 ${selectors}과(와) 일치하는 업로드 설정을 찾을 수 없습니다.",UPLOAD_OPTION_CONFIG_AMBIGUOUS:"${scope}의 업로드 설정 ${selector}이(가) 모호합니다. 일치 항목: ${candidates}. 업로더 또는 고유한 설정 ID를 지정해 주세요.",CLOUD_LOGIN_CANCELLED:"로그인이 취소되었습니다",CLOUD_LOGIN_IN_PROGRESS:"로그인이 이미 진행 중입니다",CLOUD_LOGIN_INVALID_TOKEN:"유효하지 않은 토큰",CLOUD_LOGIN_SUCCESS:"로그인 성공!",CLOUD_LOGOUT_SUCCESS:"로그아웃 성공!",CLOUD_LOGIN_SERVER_START_FAILED:"PicGo 로그인 서버 시작 실패",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"브라우저를 자동으로 열 수 없습니다: ${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"이 URL을 브라우저에서 열어 주세요: ${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State 불일치 또는 누락. 요청이 차단되었습니다.",CLOUD_LOGIN_STATE_INVALID:"유효하지 않은 State. 다시 로그인해 주세요.",CLOUD_LOGIN_TOKEN_MISSING:"콜백에 토큰이 없습니다.",CLOUD_LOGIN_CODE_MISSING:"콜백에 코드가 없습니다.",CLOUD_LOGIN_EXCHANGE_FAILED:"로그인 코드 교환에 실패했습니다.",CLOUD_LOGIN_NOT_IN_PROGRESS:"진행 중인 로그인 흐름이 없습니다.",CLOUD_LOGIN_PAGE_TITLE:"PicGo 인증",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"인증 성공!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"인증 실패",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"이 창을 닫고 PicGo로 돌아가세요.",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"이 업로더를 사용하려면 먼저 PicGo Cloud에 로그인해 주세요.",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"PicGo Cloud 세션이 만료되었습니다. 다시 로그인한 후 재시도해 주세요.",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloud에서 유효하지 않은 업로드 사전 서명 응답을 반환했습니다.",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloud에서 유효하지 않은 업로드 완료 응답을 반환했습니다.",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"파일 이름이 없습니다. PicGo Cloud에 업로드할 수 없습니다.",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"이미지 데이터가 없습니다. PicGo Cloud에 업로드할 수 없습니다.",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloud에서 유효하지 않은 멀티파트 업로드 초기화 응답을 반환했습니다.",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"멀티파트 업로드 세션이 만료되었습니다. 다시 업로드해 주세요.",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"파트 업로드가 여러 번 재시도 후 실패했습니다.",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"멀티파트 업로드 완료 요청이 실패했습니다.",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"업로드 중 ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"업로드 중 ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} 파트)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:" (이어서 업로드)",CLOUD_ALBUM_PENDING_INVALID_FILE:"대기 중인 가져오기 대기열 파일이 유효하지 않아 빈 것으로 처리되었습니다: ${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"클라우드 앨범 자동 가져오기가 비활성화되어 있습니다. 먼저 자동 가져오기를 활성화해 주세요.",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"클라우드 앨범 가져오기는 PicGo Cloud 유료 요금제가 필요합니다.",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"자동 가져오기가 완전히 완료되지 않았습니다. 현재 대기 중인 항목이 ${count}개 있습니다.",CLOUD_COMMAND_LOGIN_REQUIRED:"먼저 PicGo Cloud에 로그인해 주세요.",CLOUD_COMMAND_LOGIN_HINT:"`picgo login`(또는 `picgo cloud login`)을 실행한 후 다시 시도해 주세요.",CLOUD_AUTH_STATUS_LOGGED_IN:"PicGo Cloud에 로그인됨 (사용자: ${user})",CLOUD_AUTH_STATUS_LOGGED_OUT:"PicGo Cloud에 로그인되어 있지 않습니다.",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloud 세션이 유효하지 않습니다. 다시 로그인해 주세요.",CLOUD_AUTH_STATUS_ERROR:"PicGo Cloud 상태 확인 실패: ${message}",GET_PLUGINS_EMPTY:"설치된 플러그인이 없습니다.",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"클라우드 앨범 자동 가져오기가 비활성화되어 있습니다. 지금 활성화하시겠습니까?",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"클라우드 앨범 자동 가져오기를 활성화하는 중...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"클라우드 앨범 자동 가져오기가 활성화되었습니다.",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"이 항목들은 이미 PicGo Cloud로 가져온 항목입니다.",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"가져오기 중 ${current}/${total} (배치 ${batchIndex}/${batchTotal})",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"배치 ${batchIndex}/${batchTotal}: 처리 ${current}/${total}, 생성 ${created}, 건너뜀 ${skipped}, 실패 ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"가져오기 요약",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"총계",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"생성됨",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"건너뜀",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"유효하지 않음",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"실패",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"대기 중",CLOUD_ALBUM_IMPORT_RETRY_HINT:"`picgo cloud album retry`를 실행하여 대기 중인 항목을 재시도하세요.",CLOUD_ALBUM_IMPORT_NO_PENDING:"재시도할 대기 중인 항목이 없습니다.",CLOUD_ALBUM_LIST_LOADING:"클라우드 앨범 목록을 가져오는 중...",CLOUD_ALBUM_LIST_DONE:"클라우드 앨범 목록을 가져왔습니다",CLOUD_ALBUM_GET_LOADING:"클라우드 앨범 항목을 가져오는 중...",CLOUD_ALBUM_GET_DONE:"클라우드 앨범 항목을 가져왔습니다",CLOUD_ALBUM_UPDATE_LOADING:"클라우드 앨범 항목을 업데이트하는 중...",CLOUD_ALBUM_UPDATE_DONE:"클라우드 앨범 항목을 업데이트했습니다",CLOUD_ALBUM_DELETE_LOADING:"클라우드 앨범 항목을 삭제하는 중...",CLOUD_ALBUM_DELETE_DONE:"클라우드 앨범 항목을 삭제했습니다",CLOUD_ALBUM_DELETE_CONFIRM:"클라우드 앨범에서 ${count}개 항목을 삭제하시겠습니까?",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"가져오기 소스를 제공해 주세요: 데이터베이스 경로, `--json-file` 또는 `--data`.",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"가져오기 소스는 하나만 허용됩니다: 데이터베이스 경로, `--json-file` 또는 `--data`.",CLOUD_ALBUM_IMPORT_INVALID_JSON:"가져오기 데이터는 유효한 JSON 배열이어야 합니다.",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"가져오기 JSON 파일 읽기 실패: ${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"가져오기 데이터를 로드하는 중...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"${count}개 항목을 로드했습니다",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"클라우드 가져오기 상태를 확인하는 중...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"클라우드 가져오기 상태 확인 완료",CLOUD_ALBUM_IMPORT_UPLOADING:"클라우드로 가져오는 중...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"클라우드 가져오기 완료",CLOUD_ALBUM_RETRY_LOADING_PENDING:"대기 중인 항목을 로드하는 중...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"대기 중인 항목 ${count}개를 로드했습니다",CLOUD_ALBUM_RETRY_UPLOADING:"가져오기를 재시도하는 중...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"가져오기 재시도 완료",SERVER_INVALID_JSON_BODY:"유효하지 않은 JSON 본문",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"유효하지 않은 요청 본문: { list: string[] } 필요",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-data의 files 필드에서 파일을 찾을 수 없습니다",SERVER_FORMDATA_FILES_MUST_BE_FILES:"유효하지 않은 form-data: files는 파일이어야 합니다",SERVER_AUTH_ENABLED:"[PicGo Server] 인증이 활성화되었습니다.",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 경고: 인증이 비활성화되었습니다. 누구나 이미지를 업로드할 수 있습니다.",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] ${ip}에서 인증되지 않은 요청",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 경고: URL 쿼리로 시크릿을 전달하는 것은 안전하지 않습니다. Authorization 헤더를 사용해 주세요.",URL_REWRITE_EMPTY_RESULT:"URL 재작성 결과가 비어 있습니다. 규칙 설정을 확인해 주세요",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"Token 설정",PICBED_SMMS_BACKUP_DOMAIN:"백업 업로드 도메인 설정",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"예: sm.ms",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"KeyId 설정",PICBED_ALICLOUD_ACCESSKEYSECRET:"KeySecret 설정",PICBED_ALICLOUD_BUCKET:"Bucket 설정",PICBED_ALICLOUD_AREA:"저장 영역 설정",PICBED_ALICLOUD_PATH:"저장 경로 설정",PICBED_ALICLOUD_CUSTOMURL:"사용자 지정 URL 설정",PICBED_ALICLOUD_OPTIONS:"URL 접미사 설정",PICBED_ALICLOUD_MESSAGE_AREA:"예: oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"예: test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"예: ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"예: https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"COS 버전 선택",PICBED_TENCENTCLOUD_SECRETID:"SecretId 설정",PICBED_TENCENTCLOUD_SECRETKEY:"SecretKey 설정",PICBED_TENCENTCLOUD_APPID:"AppId 설정",PICBED_TENCENTCLOUD_BUCKET:"Bucket 설정",PICBED_TENCENTCLOUD_AREA:"저장 영역 설정",PICBED_TENCENTCLOUD_ENDPOINT:"Endpoint 설정",PICBED_TENCENTCLOUD_PATH:"저장 경로 설정",PICBED_TENCENTCLOUD_OPTIONS:"URL 접미사 설정",PICBED_TENCENTCLOUD_SLIM:"ImageSlim 설정",PICBED_TENCENTCLOUD_SLIM_TIP:"이미지 극한 지능 압축, [문서 설명](https://cloud.tencent.com/document/product/436/49259)을 참고해 주세요",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"열기",PICBED_TENCENTCLOUD_SLIM_CANCEL:"닫기",PICBED_TENCENTCLOUD_CUSTOMURL:"사용자 지정 URL 설정",PICBED_TENCENTCLOUD_MESSAGE_APPID:"예: 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"예: ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"예: cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"예: test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"예: http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"예: ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Token 설정",PICBED_GITHUB_REPO:"저장소 이름 설정",PICBED_GITHUB_PATH:"저장 경로 설정",PICBED_GITHUB_BRANCH:"브랜치 설정",PICBED_GITHUB_CUSTOMURL:"사용자 지정 URL 설정",PICBED_GITHUB_MESSAGE_REPO:"예: username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"예: main",PICBED_GITHUB_MESSAGE_PATH:"예: test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"예: https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"AccessKey 설정",PICBED_QINIU_SECRETKEY:"SecretKey 설정",PICBED_QINIU_BUCKET:"Bucket 설정",PICBED_QINIU_PATH:"저장 경로 설정",PICBED_QINIU_URL:"URL 설정",PICBED_QINIU_OPTIONS:"URL 접미사 설정",PICBED_QINIU_AREA:"저장 영역 설정",PICBED_QINIU_MESSAGE_PATH:"예: test/",PICBED_QINIU_MESSAGE_AREA:"예: z0",PICBED_QINIU_MESSAGE_OPTIONS:"예: ?imageslim",PICBED_QINIU_MESSAGE_URL:"예: https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"ClientId 설정",PICBED_IMGUR_PROXY:"프록시 설정",PICBED_IMGUR_MESSAGE_PROXY:"예: http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Bucket 설정",PICBED_UPYUN_OPERATOR:"운영자 설정",PICBED_UPYUN_PASSWORD:"운영자 비밀번호 설정",PICBED_UPYUN_PATH:"저장 경로 설정",PICBED_UPYUN_URL:"URL 설정",PICBED_UPYUN_OPTIONS:"URL 접미사 설정",PICBED_UPYUN_MESSAGE_OPERATOR:"예: me",PICBED_UPYUN_MESSAGE_PASSWORD:"운영자 비밀번호를 입력해 주세요",PICBED_UPYUN_MESSAGE_URL:"예: http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"예: !imgslim",PICBED_UPYUN_MESSAGE_PATH:"예: test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"플러그인 설치 성공",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"플러그인 설치 실패",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"플러그인 설치 실패, 오류 코드: ${code}, 오류 로그: \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"플러그인 설치 실패, 유효한 플러그인 이름 또는 유효한 설치 경로를 입력해 주세요",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"플러그인 제거 성공",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"플러그인 제거 실패",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"플러그인 제거 실패, 오류 코드: ${code}, 오류 로그: \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"플러그인 제거 실패, 유효한 플러그인 이름을 입력해 주세요",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"플러그인 업데이트 성공",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"플러그인 업데이트 실패",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"플러그인 업데이트 실패, 오류 코드: ${code}, 오류 로그: \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"플러그인 업데이트 실패, 유효한 플러그인 이름을 입력해 주세요",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"유효하지 않은 설정: settings.picgoCloud.encryptionMethod는 'auto', 'sse', 'e2ee' 중 하나여야 합니다. 현재 값: ${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"종단간 암호화",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"서버 측 암호화",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"암호화 방식을 전환하시겠습니까?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:'"${from}"에서 "${to}"(으)로 전환합니다.\n\n참고: 암호화 모드를 전환하면 클라우드 기록 버전이 모두 삭제됩니다.\n이는 이전 기록 버전을 새 모드에서 복호화하거나 검증할 수 없기 때문입니다.\n전환 후에는 시스템이 즉시 새로운 백업을 시작점으로 생성합니다.',CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"전환 확인 및 기록 삭제",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"취소",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"사용자가 암호화 전환을 취소했습니다",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"암호화 방식 전환 확인 핸들러가 필요합니다"},ja:{UPLOAD_FAILED:"アップロード失敗",CHECK_SETTINGS:"設定を確認してください",CHECK_SETTINGS_AND_NETWORK:"設定とネットワークを確認してください",UPLOAD_FAILED_REASON:"エラーコード: ${code}、ブラウザを開いてアドレスを貼り付けて原因を確認してください",SERVER_ERROR:"サーバーエラーが発生しました。後でもう一度お試しください",AUTH_FAILED:"認証失敗",CONFIG_INVALID_FORMAT:"設定形式が無効です。再設定してください。",CONFIG_KEY_READ_ONLY:"config.${name}は変更できません。",CONFIG_KEY_CANNOT_UNSET:"config.${key}は削除できません。",UPLOAD_OPTION_INVALID_PARAMETER:"アップロードパラメーター「${parameter}」が無効です。空でない文字列を1つ指定してください。",UPLOAD_OPTION_ACTIVE_CONFIG:"現在の設定（デフォルトID、次に最初の保存済み設定）",UPLOAD_OPTION_UNKNOWN_UPLOADER:"アップローダー「${uploader}」は登録されていません。利用可能なアップローダー: ${uploaders}。",UPLOAD_OPTION_CONFIG_NOT_FOUND:"${scope}に${selectors}と一致するアップロード設定がありません。",UPLOAD_OPTION_CONFIG_AMBIGUOUS:"${scope}のアップロード設定${selector}は一意ではありません。一致候補: ${candidates}。アップローダーまたは一意の設定IDを指定してください。",CLOUD_LOGIN_CANCELLED:"ログインがキャンセルされました",CLOUD_LOGIN_IN_PROGRESS:"ログインはすでに進行中です",CLOUD_LOGIN_INVALID_TOKEN:"無効なトークン",CLOUD_LOGIN_SUCCESS:"ログイン成功！",CLOUD_LOGOUT_SUCCESS:"ログアウト成功！",CLOUD_LOGIN_SERVER_START_FAILED:"PicGoログインサーバーの起動に失敗しました",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"ブラウザを自動的に開けませんでした: ${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"このURLをブラウザで開いてください: ${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"Stateの不一致または欠落。リクエストがブロックされました。",CLOUD_LOGIN_STATE_INVALID:"無効なState。再度ログインしてください。",CLOUD_LOGIN_TOKEN_MISSING:"コールバックにトークンがありません。",CLOUD_LOGIN_CODE_MISSING:"コールバックにコードがありません。",CLOUD_LOGIN_EXCHANGE_FAILED:"ログインコードの交換に失敗しました。",CLOUD_LOGIN_NOT_IN_PROGRESS:"進行中のログインフローはありません。",CLOUD_LOGIN_PAGE_TITLE:"PicGo認証",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"認証成功！",CLOUD_LOGIN_RESULT_FAILED_TITLE:"認証失敗",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"このウィンドウを閉じてPicGoに戻ってください。",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"このアップローダーを使用するには、まずPicGo Cloudにログインしてください。",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"PicGo Cloudのセッションが期限切れです。再度ログインしてからリトライしてください。",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloudから無効なアップロード事前署名レスポンスが返されました。",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloudから無効なアップロード完了レスポンスが返されました。",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"ファイル名がありません。PicGo Cloudにアップロードできません。",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"画像データがありません。PicGo Cloudにアップロードできません。",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloudから無効なマルチパートアップロード開始レスポンスが返されました。",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"マルチパートアップロードセッションが期限切れです。再度アップロードしてください。",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"パートのアップロードが複数回のリトライ後に失敗しました。",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"マルチパートアップロード完了リクエストが失敗しました。",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"アップロード中 ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"アップロード中 ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} パート)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:"（再開）",CLOUD_ALBUM_PENDING_INVALID_FILE:"保留中のインポートキューファイルが無効なため、空として処理されました: ${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"クラウドアルバムの自動インポートが無効です。先に自動インポートを有効にしてください。",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"クラウドアルバムのインポートにはPicGo Cloudの有料プランが必要です。",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"自動インポートが完全に完了していません。現在保留中の項目が${count}件あります。",CLOUD_COMMAND_LOGIN_REQUIRED:"先にPicGo Cloudにログインしてください。",CLOUD_COMMAND_LOGIN_HINT:"`picgo login`（または`picgo cloud login`）を実行してからリトライしてください。",CLOUD_AUTH_STATUS_LOGGED_IN:"PicGo Cloudにログイン中（ユーザー: ${user}）",CLOUD_AUTH_STATUS_LOGGED_OUT:"PicGo Cloudにログインしていません。",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloudのセッションが無効です。再度ログインしてください。",CLOUD_AUTH_STATUS_ERROR:"PicGo Cloudのステータス確認に失敗しました: ${message}",GET_PLUGINS_EMPTY:"インストール済みのプラグインはありません。",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"クラウドアルバムの自動インポートが無効です。今すぐ有効にしますか？",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"クラウドアルバムの自動インポートを有効にしています...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"クラウドアルバムの自動インポートが有効になりました。",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"これらの項目はすでにPicGo Cloudにインポート済みです。",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"インポート中 ${current}/${total}（バッチ ${batchIndex}/${batchTotal}）",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"バッチ ${batchIndex}/${batchTotal}: 処理 ${current}/${total}、作成 ${created}、スキップ ${skipped}、失敗 ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"インポート結果",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"合計",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"作成",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"スキップ",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"無効",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"失敗",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"保留中",CLOUD_ALBUM_IMPORT_RETRY_HINT:"`picgo cloud album retry`を実行して保留中の項目をリトライしてください。",CLOUD_ALBUM_IMPORT_NO_PENDING:"リトライする保留中の項目はありません。",CLOUD_ALBUM_LIST_LOADING:"クラウドアルバム一覧を取得中...",CLOUD_ALBUM_LIST_DONE:"クラウドアルバム一覧を取得しました",CLOUD_ALBUM_GET_LOADING:"クラウドアルバム項目を取得中...",CLOUD_ALBUM_GET_DONE:"クラウドアルバム項目を取得しました",CLOUD_ALBUM_UPDATE_LOADING:"クラウドアルバム項目を更新中...",CLOUD_ALBUM_UPDATE_DONE:"クラウドアルバム項目を更新しました",CLOUD_ALBUM_DELETE_LOADING:"クラウドアルバム項目を削除中...",CLOUD_ALBUM_DELETE_DONE:"クラウドアルバム項目を削除しました",CLOUD_ALBUM_DELETE_CONFIRM:"クラウドアルバムから${count}件の項目を削除しますか？",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"インポートソースを指定してください: データベースパス、`--json-file`、または`--data`。",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"インポートソースは1つだけ指定できます: データベースパス、`--json-file`、または`--data`。",CLOUD_ALBUM_IMPORT_INVALID_JSON:"インポートデータは有効なJSON配列である必要があります。",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"インポートJSONファイルの読み取りに失敗しました: ${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"インポートデータを読み込み中...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"${count}件の項目を読み込みました",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"クラウドインポートのステータスを確認中...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"クラウドインポートのステータス確認完了",CLOUD_ALBUM_IMPORT_UPLOADING:"クラウドにインポート中...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"クラウドインポート完了",CLOUD_ALBUM_RETRY_LOADING_PENDING:"保留中の項目を読み込み中...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"保留中の項目${count}件を読み込みました",CLOUD_ALBUM_RETRY_UPLOADING:"インポートをリトライ中...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"インポートリトライ完了",SERVER_INVALID_JSON_BODY:"無効なJSON本文",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"無効なリクエスト本文: { list: string[] } が必要です",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-dataのfilesフィールドにファイルが見つかりません",SERVER_FORMDATA_FILES_MUST_BE_FILES:"無効なform-data: filesはファイルである必要があります",SERVER_AUTH_ENABLED:"[PicGo Server] 認証が有効になりました。",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 警告: 認証が無効です。誰でも画像をアップロードできます。",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] ${ip}からの未認証リクエスト",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 警告: URLクエリでシークレットを渡すのは安全ではありません。Authorizationヘッダーを使用してください。",URL_REWRITE_EMPTY_RESULT:"URLリライト結果が空です。ルール設定を確認してください",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"Tokenを設定",PICBED_SMMS_BACKUP_DOMAIN:"バックアップアップロードドメインを設定",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例: sm.ms",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"KeyIdを設定",PICBED_ALICLOUD_ACCESSKEYSECRET:"KeySecretを設定",PICBED_ALICLOUD_BUCKET:"Bucketを設定",PICBED_ALICLOUD_AREA:"保存リージョンを設定",PICBED_ALICLOUD_PATH:"保存パスを設定",PICBED_ALICLOUD_CUSTOMURL:"カスタムURLを設定",PICBED_ALICLOUD_OPTIONS:"URLサフィックスを設定",PICBED_ALICLOUD_MESSAGE_AREA:"例: oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例: test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例: ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例: https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"COSバージョンを選択",PICBED_TENCENTCLOUD_SECRETID:"SecretIdを設定",PICBED_TENCENTCLOUD_SECRETKEY:"SecretKeyを設定",PICBED_TENCENTCLOUD_APPID:"AppIdを設定",PICBED_TENCENTCLOUD_BUCKET:"Bucketを設定",PICBED_TENCENTCLOUD_AREA:"保存リージョンを設定",PICBED_TENCENTCLOUD_ENDPOINT:"Endpointを設定",PICBED_TENCENTCLOUD_PATH:"保存パスを設定",PICBED_TENCENTCLOUD_OPTIONS:"URLサフィックスを設定",PICBED_TENCENTCLOUD_SLIM:"ImageSlimを設定",PICBED_TENCENTCLOUD_SLIM_TIP:"画像の極限インテリジェント圧縮については、[ドキュメント](https://cloud.tencent.com/document/product/436/49259)を参照してください",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"オン",PICBED_TENCENTCLOUD_SLIM_CANCEL:"オフ",PICBED_TENCENTCLOUD_CUSTOMURL:"カスタムURLを設定",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例: 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例: ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例: cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例: test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例: http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例: ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Tokenを設定",PICBED_GITHUB_REPO:"リポジトリ名を設定",PICBED_GITHUB_PATH:"保存パスを設定",PICBED_GITHUB_BRANCH:"ブランチを設定",PICBED_GITHUB_CUSTOMURL:"カスタムURLを設定",PICBED_GITHUB_MESSAGE_REPO:"例: username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例: main",PICBED_GITHUB_MESSAGE_PATH:"例: test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例: https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"AccessKeyを設定",PICBED_QINIU_SECRETKEY:"SecretKeyを設定",PICBED_QINIU_BUCKET:"Bucketを設定",PICBED_QINIU_PATH:"保存パスを設定",PICBED_QINIU_URL:"URLを設定",PICBED_QINIU_OPTIONS:"URLサフィックスを設定",PICBED_QINIU_AREA:"保存リージョンを設定",PICBED_QINIU_MESSAGE_PATH:"例: test/",PICBED_QINIU_MESSAGE_AREA:"例: z0",PICBED_QINIU_MESSAGE_OPTIONS:"例: ?imageslim",PICBED_QINIU_MESSAGE_URL:"例: https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"ClientIdを設定",PICBED_IMGUR_PROXY:"プロキシを設定",PICBED_IMGUR_MESSAGE_PROXY:"例: http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Bucketを設定",PICBED_UPYUN_OPERATOR:"オペレーターを設定",PICBED_UPYUN_PASSWORD:"オペレーターパスワードを設定",PICBED_UPYUN_PATH:"保存パスを設定",PICBED_UPYUN_URL:"URLを設定",PICBED_UPYUN_OPTIONS:"URLサフィックスを設定",PICBED_UPYUN_MESSAGE_OPERATOR:"例: me",PICBED_UPYUN_MESSAGE_PASSWORD:"オペレーターパスワードを入力してください",PICBED_UPYUN_MESSAGE_URL:"例: http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例: !imgslim",PICBED_UPYUN_MESSAGE_PATH:"例: test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"プラグインのインストールに成功しました",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"プラグインのインストールに失敗しました",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"プラグインのインストールに失敗しました。エラーコード: ${code}、エラーログ: \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"プラグインのインストールに失敗しました。有効なプラグイン名または有効なインストールパスを入力してください",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"プラグインのアンインストールに成功しました",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"プラグインのアンインストールに失敗しました",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"プラグインのアンインストールに失敗しました。エラーコード: ${code}、エラーログ: \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"プラグインのアンインストールに失敗しました。有効なプラグイン名を入力してください",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"プラグインのアップデートに成功しました",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"プラグインのアップデートに失敗しました",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"プラグインのアップデートに失敗しました。エラーコード: ${code}、エラーログ: \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"プラグインのアップデートに失敗しました。有効なプラグイン名を入力してください",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"無効な設定: settings.picgoCloud.encryptionMethodは'auto'、'sse'、'e2ee'のいずれかである必要があります。現在の値: ${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"エンドツーエンド暗号化",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"サーバー側暗号化",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"暗号化方式を切り替えますか？",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:"「${from}」から「${to}」に切り替えます。\n\n注意: 暗号化モードを切り替えると、クラウドの履歴バージョンがすべて削除されます。\nこれは古い履歴バージョンが新しいモードで復号化または検証できないためです。\n切り替え後、システムは新しいバックアップを開始点として即座に作成します。",CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"切り替えを確認して履歴を削除",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"キャンセル",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"ユーザーにより暗号化の切り替えがキャンセルされました",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"暗号化方式切り替え確認ハンドラーが必要です"}};class Eo{i18n;objectAdapter;ctx;constructor(e){this.ctx=e,this.objectAdapter=new G.ObjectAdapter(uo);let t=this.ctx.getConfig("settings.language")||"en";uo[t]||(t="en"),this.i18n=new G.I18n({adapter:this.objectAdapter,defaultLanguage:t}),this.loadOutsideI18n()}loadOutsideI18n(){const i=this.getOutsideI18nFolder();e.readdirSync(i,{withFileTypes:!0}).forEach(n=>{if(n.isFile()&&n.name.endsWith(".yml")){const r=t.join(i,n.name),o=e.readFileSync(r,"utf8");try{const e=M.load(o);uo[n.name.replace(/\.yml$/,"")]=e}catch(e){console.error(e)}}})}getOutsideI18nFolder(){const i=t.join(this.ctx.baseDir,"i18n-cli");return e.pathExistsSync(i)||e.ensureDirSync(i),i}translate(e,t){return this.i18n.translate(e,t)||e}setLanguage(e){this.i18n.setLanguage(e),this.ctx.saveConfig({"settings.language":e})}addLocale(e,t){const i=this.objectAdapter.getLocale(e);if(!i)return!1;const n=u.merge(i,t);return this.objectAdapter.setLocale(e,n),!0}addLanguage(e,t){return!this.objectAdapter.getLocale(e)&&(this.objectAdapter.setLocale(e,t),uo[e]=t,!0)}getLanguageList(){return Object.keys(uo)}}var po;function Io(e){return Object.values(po).includes(e)}!function(e){e.AUTH_CALLBACK="/auth/callback",e.UPLOAD="/upload",e.HEARTBEAT="/heartbeat"}(po||(po={}));const go=e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}};var Co;!function(e){e[e.Clipboard=0]="Clipboard",e[e.List=1]="List",e[e.Invalid=2]="Invalid"}(Co||(Co={}));const fo=e=>"object"==typeof e&&null!==e&&("arrayBuffer"in e&&"function"==typeof e.arrayBuffer),ho=e=>{const t=e.name;return"string"==typeof t&&""!==t.trim()?t:`${p.randomUUID()}.png`},Lo=e=>{if(e instanceof Mn)return{success:!1,result:[],items:[],code:e.code,message:e.message};if(e instanceof Error)return{success:!1,result:[],items:[],message:e.message};const t=e.map(e=>e.imgUrl).filter(e=>"string"==typeof e&&""!==e),i=e.map(e=>({origin:e.origin,imgUrl:e.imgUrl,fileName:e.fileName,type:e.type,contentType:e.contentType,size:e.size,width:e.width,height:e.height,extname:e.extname}));return 0===t.length?{success:!1,result:t,items:i,message:"All uploads failed"}:{success:!0,result:t,items:i}},Oo=e=>e.success?200:void 0!==e.code?400:500,Uo=e=>({success:!1,result:[],items:[],code:e.code,message:e.message}),mo=["uploader","configName","configId"],Do=(i,n,r)=>{i.post(po.UPLOAD,async i=>{const o=(e,t)=>n.i18n?.translate(e,t)??String(e);try{const s=((e,t)=>{const i={};let n=!1;for(const r of mo){const o=e.searchParams.getAll(r);if(0!==o.length){if(1!==o.length||""===o[0].trim())throw new Mn(exports.UploadOptionErrorCode.InvalidOption,t("UPLOAD_OPTION_INVALID_PARAMETER",{parameter:r}));i[r]=o[0],n=!0}}return n?i:void 0})(new URL(i.req.url),o);$n(n,s);const a=i.req.raw.headers.get("content-type")||"",c=r?.()??(e=>({uploadClipboard:async t=>await e.upload(void 0,t),uploadPaths:async(t,i)=>await e.upload(t,i),getTempDir:()=>t.join(e.baseDir,"picgo-form-images")}))(n);if(a.includes("multipart/form-data")){const r=c.getTempDir?.()??t.join(n.baseDir,"picgo-form-images"),a=t.join(r,p.randomUUID()),l=[];try{const n=(await i.req.formData()).getAll("files");if(0===n.length)return i.json({success:!1,result:[],items:[],message:o("SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD")},400);for(const r of n){if(!fo(r))return i.json({success:!1,result:[],items:[],message:o("SERVER_FORMDATA_FILES_MUST_BE_FILES")},400);const n=ho(r),s=t.basename(n),c=t.join(a,p.randomUUID(),s),_=Buffer.from(await r.arrayBuffer());await e.ensureDir(t.dirname(c)),await e.writeFile(c,_),l.push(c)}const r=await c.uploadPaths(l,s),_=Lo(r);return i.json(_,Oo(_))}catch(e){return e instanceof Mn?i.json(Uo(e),400):(n.log.error(e),i.json({success:!1,result:[],items:[],message:go(e)},500))}finally{try{await e.remove(a)}catch(e){n.log.error(e)}}}const l=await i.req.raw.text().catch(()=>"");if(""===l.trim()){const e=await c.uploadClipboard(s),t=Lo(e);return i.json(t,Oo(t))}let _;try{_=JSON.parse(l)}catch{return i.json({success:!1,result:[],items:[],message:o("SERVER_INVALID_JSON_BODY")},400)}const u=(e=>{if("object"!=typeof e||null===e)return{kind:Co.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"};if(!("list"in e))return{kind:Co.Clipboard};const t=e.list;return void 0===t?{kind:Co.Clipboard}:Array.isArray(t)?0===t.length?{kind:Co.Clipboard}:t.every(e=>"string"==typeof e&&""!==e.trim())?{kind:Co.List,list:t}:{kind:Co.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"}:{kind:Co.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"}})(_);if(u.kind===Co.Invalid)return i.json({success:!1,result:[],items:[],message:o(u.messageKey)},400);if(u.kind===Co.Clipboard){const e=await c.uploadClipboard(s),t=Lo(e);return i.json(t,Oo(t))}const E=await c.uploadPaths(u.list,s),d=Lo(E);return i.json(d,Oo(d))}catch(e){return e instanceof Mn?i.json(Uo(e),400):(n.log.error(e),i.json({success:!1,result:[],items:[],message:go(e)},500))}}),i.post(po.HEARTBEAT,e=>e.json({success:!0,result:"alive"}))};var No;!function(e){e.Authorization="authorization",e.Header="header",e.Query="query",e.None="none"}(No||(No={}));const Po=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);if(Number.isFinite(t))return t}},Ao=e=>{if("string"!=typeof e)return;const t=e.trim();return""===t?void 0:t};class So{app;ctx;server;listeningPort;listeningHost;authSecret;warnedQuerySecret=!1;staticRoutePrefixes=[];uploadAdapter;constructor(e){this.ctx=e,this.app=new x.Hono,this.initMiddleware(),this.initCoreRoutes()}registerGet(e,t,i=!1){this.handleRegister("get",e,t,i)}registerPost(e,t,i=!1){this.handleRegister("post",e,t,i)}registerPut(e,t,i=!1){this.handleRegister("put",e,t,i)}registerDelete(e,t,i=!1){this.handleRegister("delete",e,t,i)}registerMiddleware(e,t){this.app.use(e,t)}setUploadAdapter(e){this.uploadAdapter=e}registerStatic(e,t){const i=e.endsWith("/*")?e:`${e}/*`,n=i.replace(/\/\*$/,"")||"/";this.staticRoutePrefixes.includes(n)||this.staticRoutePrefixes.push(n),this.app.use(i,w.serveStatic({root:t}))}handleRegister(e,t,i,n){!Io(t)||n?this.app[e](t,i):this.ctx.log.warn(`[PicGo Server] Plugin attempted to overwrite builtin route: ${t}. Action denied.`)}mount(e,t){const i=new x.Hono;t(i),this.app.route(e,i)}getServerInfo(){return this.server&&this.listeningHost&&void 0!==this.listeningPort?`http://${this.listeningHost}:${this.listeningPort}/`:""}isListening(){return void 0!==this.server}initMiddleware(){this.app.use(v.cors()),this.app.use((e,t)=>this.handleAuth(e,t)),this.app.use(b.logger())}initCoreRoutes(){Do(this.app,this.ctx,()=>this.uploadAdapter)}t(e,t){return this.ctx.i18n?.translate(e,t)??String(e)}getRequestPath(e){return"string"==typeof e.req.path?e.req.path:new URL(e.req.url).pathname}isStaticPath(e){return this.staticRoutePrefixes.some(t=>!!t&&("/"===t?"/"===e:e===t||e.startsWith(`${t}/`)))}shouldSkipAuth(e,t){return"OPTIONS"===e.toUpperCase()||(""===t||"/"===t||(!!this.isStaticPath(t)||!(!Io(t)||t===po.UPLOAD)))}extractAuthToken(e){const t=e.req.raw.headers;if(t.has("authorization")){const e=(t.get("authorization")??"").match(/^\s*Bearer\s+(.+)$/i);return{source:No.Authorization,token:e?.[1]}}if(t.has("x-picgo-secret"))return{source:No.Header,token:t.get("x-picgo-secret")??""};const i=new URL(e.req.url);return i.searchParams.has("secret")?{source:No.Query,token:i.searchParams.get("secret")??""}:{source:No.None}}warnQuerySecretOnce(){this.warnedQuerySecret||(this.warnedQuerySecret=!0,this.ctx.log.warn(this.t("SERVER_AUTH_QUERY_SECRET_WARNING")))}getClientIp(e){const t=e.req.raw.headers.get("x-forwarded-for");if(t){const e=t.split(",")[0]?.trim();if(e)return e}const i=e.env,n=i.server??i;return n?.incoming?.socket?.remoteAddress??"unknown"}logUnauthorized(e){const t=this.getClientIp(e);this.ctx.log.warn(this.t("SERVER_AUTH_UNAUTHORIZED_REQUEST",{ip:t}))}async handleAuth(e,t){if(!this.authSecret)return await t();const i=e.req.method,n=this.getRequestPath(e);if(this.shouldSkipAuth(i,n))return await t();const{source:r,token:o}=this.extractAuthToken(e);return r===No.Query&&this.warnQuerySecretOnce(),o&&o===this.authSecret?await t():(this.ctx.log.warn(`[PicGo Server] Unauthorized request to ${i} ${n} with token from ${r}`),this.logUnauthorized(e),e.json({success:!1,message:"Unauthorized"},401))}async startServer(e,t){return await new Promise((i,n)=>{const r=B.serve({fetch:this.app.fetch,port:e,hostname:t},e=>{r.off("error",o),i({server:r,port:e.port})});function o(e){r.off("error",o),n(e)}r.once("error",o)})}async isExistingPicGoServer(e,t){const i=`http://${"0.0.0.0"===e||"::"===e?"127.0.0.1":e}:${t}/heartbeat`;try{const e=await d.post(i,void 0,{timeout:1e3});return!0===e?.data?.success&&"alive"===e?.data?.result}catch{return!1}}async listen(e,t,i=!1,n){if(this.server&&void 0!==this.listeningPort)return t&&this.listeningHost&&t!==this.listeningHost&&this.ctx.log.warn(`Server is already listening at http://${this.listeningHost}:${this.listeningPort}`),this.listeningPort;const r=this.ctx.getConfig("settings.server.port"),o=this.ctx.getConfig("settings.server.host"),s=this.ctx.getConfig("settings.server.secret"),a=Po(e)??Po(r)??36677,c=t??("string"==typeof o?o:void 0)??"127.0.0.1";this.authSecret=Ao(n)??Ao(process.env.PICGO_SERVER_SECRET)??Ao(s),this.warnedQuerySecret=!1,this.app=((e,t)=>{const i=new x.Hono,n=[],r=new Map;return e.routes.forEach(e=>{if("ALL"===e.method)return void n.push(e);const i=`${e.method}::${e.path}`,o=r.get(i);if(void 0!==o)Io(e.path)||t.log.warn(`Route conflict detected for [${e.method}] ${e.path}. Overriding previous handler.`),n[o]=e;else{const t=n.push(e)-1;r.set(i,t)}}),n.forEach(e=>{i.on(e.method,e.path,e.handler)}),i})(this.app,this.ctx);const l=async e=>{try{const{server:t,port:i}=await this.startServer(e,c);return this.server=t,this.listeningPort=i,this.listeningHost=c,this.authSecret?this.ctx.log.info(this.t("SERVER_AUTH_ENABLED")):this.ctx.log.warn(this.t("SERVER_AUTH_DISABLED_WARNING")),this.ctx.log.info(`[PicGo Server] Listening at http://${c}:${i}`),i}catch(t){if("EADDRINUSE"===t?.code){if(!i){if(await this.isExistingPicGoServer(c,e))return this.ctx.log.info(`[PicGo Server] Detected existing instance at http://${c}:${e}`),e}return this.ctx.log.warn(`[PicGo Server] port ${e} is busy, trying with port ${e+1}`),await l(e+1)}this.ctx.log.error(t)}};return await l(a)}shutdown(){try{this.server?.close()}catch{}finally{this.server=void 0,this.listeningPort=void 0,this.listeningHost=void 0,this.authSecret=void 0,this.warnedQuerySecret=!1}}}class To{ctx;authState=null;pkceVerifier=null;pending;constructor(e){this.ctx=e,this.registerRoutes()}disposeLoginFlow(){const e=this.pending;if(!e)return;const t=this.ctx.i18n.translate("CLOUD_LOGIN_CANCELLED");e.abortController.abort(new Error(t))}async startLoginFlow(){if(this.pending)throw new Error(this.ctx.i18n.translate("CLOUD_LOGIN_IN_PROGRESS"));const e=this.ctx.server.isListening(),t=new AbortController,i=new Promise((i,n)=>{this.pending={resolve:i,reject:n,shouldShutdown:!e,abortController:t},t.signal.addEventListener("abort",()=>{const e=this.pending;if(!e||e.abortController!==t)return;this.pending=void 0,this.authState=null,this.pkceVerifier=null;const i=t.signal.reason,r=this.ctx.i18n.translate("CLOUD_LOGIN_CANCELLED"),o=i instanceof Error?i:new Error(String(i??r));n(o),e.shouldShutdown&&setTimeout(()=>{this.ctx.server.shutdown()},100)},{once:!0})});let n;try{n=await this.ctx.server.listen(void 0,"127.0.0.1",!0)}catch(e){const n=e instanceof Error?e:new Error(String(e));return t.abort(n),await i}if(void 0===n)return t.abort(new Error(this.ctx.i18n.translate("CLOUD_LOGIN_SERVER_START_FAILED"))),await i;if(t.signal.aborted)return await i;const r=encodeURIComponent(`http://127.0.0.1:${n}/auth/callback`);this.authState=F.randomUUID(),this.pkceVerifier=(()=>{const e=new Uint8Array(32);return p.webcrypto.getRandomValues(e),kt(e)})();const o=encodeURIComponent(await(async e=>{const t=(new TextEncoder).encode(e),i=await p.webcrypto.subtle.digest("SHA-256",t);return kt(new Uint8Array(i))})(this.pkceVerifier)),s=`${vt}?callback=${r}&state=${encodeURIComponent(this.authState)}&challenge=${o}`;if(t.signal.aborted)return await i;try{await this.ctx.openUrl(s)}catch(e){const t=e instanceof Error?e.message:String(e);this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_LOGIN_OPEN_BROWSER_FAILED",{message:t})),this.ctx.log.info(this.ctx.i18n.translate("CLOUD_LOGIN_OPEN_BROWSER_TIP",{url:s}))}return await i}renderResultPage(e,t){const i=e?"#2ecc71":"#e74c3c",n=e?this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_SUCCESS_TITLE"):this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_FAILED_TITLE"),r=e?"✓":"✕";return`\n      <!DOCTYPE html>\n      <html lang="en">\n        <head>\n          <title>${this.ctx.i18n.translate("CLOUD_LOGIN_PAGE_TITLE")}</title>\n          <meta charset="utf-8">\n          <meta name="viewport" content="width=device-width, initial-scale=1">\n          <style>\n            body {\n              font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n              display: flex;\n              justify-content: center;\n              align-items: center;\n              height: 100vh;\n              margin: 0;\n              background: #f0f2f5;\n            }\n            .card {\n              background: white;\n              padding: 40px;\n              border-radius: 8px;\n              box-shadow: 0 2px 10px rgba(0,0,0,0.1);\n              text-align: center;\n              max-width: 440px;\n              width: calc(100% - 48px);\n            }\n            .icon {\n              width: 64px;\n              height: 64px;\n              border-radius: 50%;\n              display: flex;\n              align-items: center;\n              justify-content: center;\n              margin: 0 auto 16px;\n              background: ${i};\n              color: #fff;\n              font-size: 36px;\n              line-height: 1;\n            }\n            h1 {\n              color: ${i};\n              margin: 0 0 12px;\n              font-size: 24px;\n            }\n            p {\n              color: #666;\n              margin: 0 0 24px;\n              line-height: 1.5;\n            }\n            .btn {\n              display: inline-block;\n              padding: 10px 20px;\n              background: #333;\n              color: white;\n              text-decoration: none;\n              border-radius: 4px;\n              font-size: 14px;\n              cursor: pointer;\n              user-select: none;\n            }\n          </style>\n        </head>\n        <body>\n          <div class="card">\n            <div class="icon">${r}</div>\n            <h1>${n}</h1>\n            <p>${t}</p>\n          </div>\n        </body>\n      </html>\n    `}abortPendingLogin(e,t){e.abortController.signal.aborted||e.abortController.abort(new Error(t))}async handleCallback(e){const t=e.req.query("code"),i=e.req.query("state");if(!i||i!==this.authState)return this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_LOGIN_STATE_MISMATCH_WARN")),e.html(this.renderResultPage(!1,this.ctx.i18n.translate("CLOUD_LOGIN_STATE_INVALID")),403);if(!t){const t=this.ctx.i18n.translate("CLOUD_LOGIN_CODE_MISSING"),i=this.pending;return i&&this.abortPendingLogin(i,t),e.html(this.renderResultPage(!1,t),400)}const n=this.pending;if(!n||n.abortController.signal.aborted)return e.html(this.renderResultPage(!1,this.ctx.i18n.translate("CLOUD_LOGIN_NOT_IN_PROGRESS")),409);const r=this.pkceVerifier;if(!r){this.ctx.log.error("PKCE verifier is missing during callback handling");const t=this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED");return this.abortPendingLogin(n,t),e.html(this.renderResultPage(!1,t),500)}try{this.ctx.log.info("API_BASE_URL",bt,"Exchanging login code for token...");const i=await(async(e,t)=>(await d.post("/api/tokens/exchange",{code:e,verifier:t},{baseURL:bt})).data)(t,r);if(!i.token){this.ctx.log.error("Token exchange failed without throwing an error");const t=i.message??this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED");return this.abortPendingLogin(n,t),e.html(this.renderResultPage(!1,t),500)}return this.ctx.saveConfig({"settings.picgoCloud.token":i.token}),this.authState=null,this.pkceVerifier=null,this.pending=void 0,n.resolve(i.token),n.shouldShutdown&&setTimeout(()=>{this.ctx.server.shutdown()},100),e.html(this.renderResultPage(!0,this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE")),200)}catch(t){let i,r;if(d.isAxiosError(t)){r=t.response?.status;const e=t.response?.data;(e=>$t(e)&&"string"==typeof e.message)(e)&&(i=e.message)}const o=this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED"),s=i??o,a=400===r?400:500;return this.abortPendingLogin(n,s),this.ctx.log.error(`Token exchange failed: ${s} (status: ${a})`,t),e.html(this.renderResultPage(!1,s),a)}}registerRoutes(){this.ctx.server.registerGet(po.AUTH_CALLBACK,this.handleCallback.bind(this),!0)}}class Ro{static DEFAULT_LIMIT=20;static DEFAULT_OFFSET=0;static IMPORT_BATCH_SIZE=100;static MAX_IMPORT_ATTEMPTS=3;ctx;client;pendingFilePath;constructor(e,t=new zt(e)){this.ctx=e,this.client=t,this.pendingFilePath=U.join(e.baseDir,"picgo-cloud-import-list-pending.json")}async list(e={}){const t={limit:Ro.DEFAULT_LIMIT,offset:Ro.DEFAULT_OFFSET,...e},i=(n=t,Object.fromEntries(Object.entries(n).filter(([,e])=>null!=e)));var n;const r=await this.client.request({method:"GET",url:"/api/album-items",params:i});return{success:r.success,...r.data}}async get(e){return(await this.client.request({method:"GET",url:`/api/album-items/${e}`})).data.item}async update(e,t){const{extname:i,size:n,...r}=t;return(await this.client.request({method:"PATCH",url:`/api/album-items/${e}`,data:r})).data.item}async batchUpdate(e){if(0===e.length)return{updated:0,skipped:0,items:[]};const t=e.map(({id:e,data:t})=>{const{extname:i,size:n,...r}=t;return{id:e,...r}});return(await this.client.request({method:"PATCH",url:"/api/album-items",data:{items:t}})).data}async delete(e){if(Array.isArray(e)){if(0===e.length)return;await this.client.request({method:"DELETE",url:"/api/album-items",data:{ids:e}})}else await this.client.request({method:"DELETE",url:`/api/album-items/${e}`})}async getStats(){return(await this.client.request({method:"GET",url:"/api/album-items/stats"})).data}async getFilters(){const e=await this.client.request({method:"GET",url:"/api/album-items/filters"});return{success:e.success,...e.data}}async import(e){const t=await this.getPending(),i={total:e.length,created:0,skipped:0,invalid:0,failed:0,pending:t.length,items:[]},n=this.normalizeImportItems(e);if(i.invalid=e.length-n.length,0===n.length)return i;const r=((e,t)=>{const i=[];for(let n=0;n<e.length;n+=t)i.push(e.slice(n,n+t));return i})(n,Ro.IMPORT_BATCH_SIZE);let o=0;for(const[e,t]of r.entries()){const s=await this.importBatchWithRetry(t);if(!s.ok){i.failed+=t.length,o+=t.length;const a=r.slice(e).flat(),c=await this.addToPending(a);return i.pending=c.length,this.emitImportProgress({total:n.length,current:o,batchIndex:e+1,batchTotal:r.length,created:i.created,skipped:i.skipped,failed:i.failed}),this.ctx.log.warn(Wt(s.error)),i}i.created+=s.created,i.skipped+=s.skipped,i.items.push(...s.items),o+=t.length,this.emitImportProgress({total:n.length,current:o,batchIndex:e+1,batchTotal:r.length,created:i.created,skipped:i.skipped,failed:i.failed})}return i.pending=(await this.getPending()).length,i}async getPending(){try{const e=await C.readFile(this.pendingFilePath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>this.isImgInfoLike(e)):(this.warnInvalidPendingFile(),[])}catch(e){if(this.isFileMissing(e))return[];if(e instanceof SyntaxError)return this.warnInvalidPendingFile(),[];throw e}}async addToPending(e){if(0===e.length)return await this.getPending();const t=[...await this.getPending(),...e];return await this.writePending(t),t}async retryPending(){const e=await this.getPending();if(0===e.length)return{total:0,created:0,skipped:0,invalid:0,failed:0,pending:0,items:[]};await this.writePending([]);try{return await this.import(e)}catch(t){throw await this.writePending(e),t}}normalizeImportItems(e){return e.flatMap(e=>{const t="string"==typeof e.imgUrl?e.imgUrl.trim():"";if(""===t)return[];const i="string"==typeof e.id&&""!==e.id.trim()?e.id.trim():p.randomUUID(),n=this.resolveContentType(e),{mimeType:r,createdAt:o,updatedAt:s,origin:a,filePath:c,buffer:l,base64Image:_,_importToPicGoCloud:u,...E}=e,d=Ht(o),I=Ht(s),g=this.buildExtra(e);return[{...E,id:i,imgUrl:t,...n?{contentType:n}:{},...void 0!==d?{createdAt:d}:{},...void 0!==I?{updatedAt:I}:{},...g?{extra:g}:{}}]})}async importBatchWithRetry(e){let t;for(let i=0;i<Ro.MAX_IMPORT_ATTEMPTS;i++)try{const t=await this.client.request({method:"POST",url:"/api/album-items",data:{items:e}});return{ok:!0,...this.normalizeBatchSummary(t,e.length),items:Array.isArray(t.data?.items)?t.data.items:[]}}catch(e){if(this.hasApiErrorCode(e,xt.DuplicateId))throw Qt(this.ctx.i18n.translate("CLOUD_ALBUM_IMPORT_DUPLICATE_ID"),e);if(this.hasApiErrorCode(e,xt.ImportDisabled))throw Qt(this.ctx.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED"),e);if(this.isUnauthorizedError(e))throw Qt(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED"),e);if(this.hasApiErrorCode(e,xt.PlanRequired))throw Qt(Wt(e),e);if(!this.shouldRetry(e))throw e;t=e}return{ok:!1,error:t}}normalizeBatchSummary(e,t){const i=e.data?.created,n=e.data?.skipped;if(void 0===i&&void 0===n)return{created:t,skipped:0};let r=Ft(i,0),o=Ft(n,0);const s=r+o-t;return s>0&&(o>=s?o-=s:(r=Math.max(0,r-(s-o)),o=0)),0===r&&0===o&&(r=t),{created:r,skipped:o}}resolveContentType(e){const t=e.contentType?.trim()||e.mimeType?.trim();if(t&&""!==t)return t;const i=e.extname?.trim();return i&&L.lookup(i)||void 0}buildExtra(e){const t="object"==typeof e.extra&&null!==e.extra?e.extra:{},i="string"==typeof e.origin&&""!==e.origin.trim()?e.origin.trim():void 0,n={...t,...i?{origin:i}:{}};return Object.keys(n).length>0?n:void 0}emitImportProgress(e){const t=e.total>0?Math.min(e.current/e.total,1):0,i={...e,fraction:t};this.ctx.emit(exports.IBuildInEvent.CLOUD_IMPORT_PROGRESS,i)}shouldRetry(e){if(d.isAxiosError(e)){const t=qt(e);return void 0===t||t>=500}return!0}isUnauthorizedError(e){return 401===qt(e)}hasApiErrorCode(e,t){return jt(e)===t}async writePending(e){await D(this.pendingFilePath,`${JSON.stringify(e,null,2)}\n`,{encoding:"utf8"})}warnInvalidPendingFile(){this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_ALBUM_PENDING_INVALID_FILE",{path:this.pendingFilePath}))}isFileMissing(e){return $t(e)&&"ENOENT"===e.code}isImgInfoLike(e){return $t(e)&&"string"==typeof e.id&&""!==e.id.trim()&&"string"==typeof e.imgUrl&&""!==e.imgUrl.trim()}}class yo{client;ctx;constructor(e){this.client=new zt(e),this.ctx=e}async getUsage(e){const t=this.ctx.GUI_VERSION?wt.GUI:wt.CLI,i=Zi();if(i)return this.ctx.log.warn(`[MOCK] BillingService.getUsage scenario=${i}`),function(e,t){const i="grace"===e||"frozen"===e||"pending-cleanup"===e,n=53687091200,r=524288e3;return{plan:"pro",effectiveQuotaPlan:i?"free":"pro",storage:{used:i?Math.round(734003200):Math.round(17179869184),limit:i?r:n},mediaCount:{used:i?5e3:8120,limit:i?200:5e4},monthlyServes:{used:12345,periodStart:en(-15),periodEnd:en(15)},configHistory:{used:5,limit:i?3:50,appType:t}}}(i,t===wt.GUI?"gui":"cli");const n=(await this.client.request({method:"GET",url:"/api/billing/usage",params:{appType:t}},e)).data;return{plan:n.plan,effectiveQuotaPlan:n.effectiveQuotaPlan,storage:n.storage,mediaCount:n.mediaCount,monthlyServes:n.monthlyServes,configHistory:n.configHistory}}async getOverview(e){const t=Zi();if(t)return this.ctx.log.warn(`[MOCK] BillingService.getOverview scenario=${t}`),function(e){switch(e){case"active-pro":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"active",daysRemaining:20,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:en(20),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:{status:"active",currentPeriodEnd:en(20)}};case"active-pro-yearly":return{plan:{paid:"pro",capability:"pro",billingPeriod:"yearly",source:"entitlement"},lifecycle:{phase:"active",daysRemaining:180,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:en(180),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:{status:"active",currentPeriodEnd:en(180)}};case"active-pro-cancel":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"active",daysRemaining:20,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:en(20),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:{status:"scheduled_cancel",currentPeriodEnd:en(20)}};case"active-grant":return{plan:{paid:"free",capability:"pro",billingPeriod:null,source:"admin_grant"},lifecycle:{phase:"active",daysRemaining:30,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:en(30),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:null};case"active-grant-lifetime":return{plan:{paid:"free",capability:"pro",billingPeriod:null,source:"admin_grant"},lifecycle:{phase:"active",daysRemaining:null,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:null,flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:null};case"grace":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"grace",daysRemaining:30,graceEndsAt:en(30),freezeEndsAt:en(90),currentPhaseEndsAt:en(30),flags:{customDomainDisabledByLifecycle:!0,autoImportDisabledByLifecycle:!0}},subscription:{status:"past_due",currentPeriodEnd:en(-3)}};case"frozen":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"frozen",daysRemaining:60,graceEndsAt:en(-30),freezeEndsAt:en(60),currentPhaseEndsAt:en(60),flags:{customDomainDisabledByLifecycle:!0,autoImportDisabledByLifecycle:!0}},subscription:{status:"canceled",currentPeriodEnd:en(-30)}};case"pending-cleanup":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"pending_cleanup",daysRemaining:null,graceEndsAt:en(-90),freezeEndsAt:en(-30),currentPhaseEndsAt:null,flags:{customDomainDisabledByLifecycle:!0,autoImportDisabledByLifecycle:!0}},subscription:null}}}(t);const i=(await this.client.request({method:"GET",url:"/api/billing/me"},e)).data;return{plan:i.plan,lifecycle:i.lifecycle,subscription:i.subscription}}}class Mo{ctx;auth;billingService;albumService;uploaderService;userInfoCache;userInfoPromise;user;constructor(e){this.ctx=e,this.user=new tn(e),this.auth=new To(e),this.billingService=new yo(e)}get album(){return this.albumService||(this.albumService=new Ro(this.ctx)),this.albumService}get uploader(){return this.uploaderService||(this.uploaderService=new mr(this.ctx)),this.uploaderService}async login(e){if(e){if(!await this.user.verifyToken(e))throw new Error(this.ctx.i18n.translate("CLOUD_LOGIN_INVALID_TOKEN"));return this.ctx.saveConfig({"settings.picgoCloud.token":e}),this.clearUserInfoCache(),void this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}const t=this.ctx.getConfig("settings.picgoCloud.token");if(t){if(await this.user.verifyToken(t))return void this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}await this.auth.startLoginFlow(),this.clearUserInfoCache(),this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}logout(){this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGOUT_SUCCESS"))}disposeLoginFlow(){this.auth.disposeLoginFlow()}async getUserInfo(){const e=this.ctx.getConfig("settings.picgoCloud.token");if(!e)return this.clearUserInfoCache(),null;if(void 0!==this.userInfoCache)return this.userInfoCache;this.userInfoPromise||(this.userInfoPromise=this.fetchUserInfo(e));try{return await this.userInfoPromise}finally{this.userInfoPromise=void 0}}async refreshUserInfo(){return this.clearUserInfoCache(),await this.getUserInfo()}async getUsage(){const e=this.ctx.getConfig("settings.picgoCloud.token");if(!e)return null;try{return await this.billingService.getUsage(e)}catch(e){if(d.isAxiosError(e)){if(401===qt(e))return this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),null;const t=Wt(e);if(""!==t.trim())throw Qt(t,e)}throw e}}async getBillingOverview(){const e=this.ctx.getConfig("settings.picgoCloud.token");if(!e)return null;try{return await this.billingService.getOverview(e)}catch(e){if(d.isAxiosError(e)){if(401===qt(e))return this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),null;const t=Wt(e);if(""!==t.trim())throw Qt(t,e)}throw e}}async setAutoImport(e){const t=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!t)throw new Error(this.ctx.i18n.translate("CLOUD_COMMAND_LOGIN_REQUIRED"));if(e){const e=await this.refreshUserInfo();if(!Yt(e))throw Qt(this.ctx.i18n.translate("CLOUD_ALBUM_IMPORT_PLAN_REQUIRED"),{status:403,apiCode:xt.PlanRequired})}const i=await this.user.setAutoImport(e,t),n={...this.userInfoCache,...i};return this.userInfoCache=n,n}async fetchUserInfo(e){try{const t=await this.user.whoami(e);return this.userInfoCache=t,t}catch(e){if(d.isAxiosError(e)){if(401===qt(e))return this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),null;const t=Wt(e);if(""!==t.trim())throw Qt(t,e)}throw e}}clearUserInfoCache(){this.userInfoCache=void 0,this.userInfoPromise=void 0}}const Go=()=>p.randomUUID(),Bo=new Set(["current","uploader","transformer","proxy","list"]),wo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),xo=e=>e.trim(),bo=e=>xo(e).toLowerCase();class vo{ctx;constructor(e){this.ctx=e,this.init()}init(){const e=this.ctx.getConfig("picBed"),t=this.ctx.getConfig("uploader"),i=wo(e)?e:{},n=wo(t)?t:{},r=new Set;for(const e of Object.keys(i))Bo.has(e)||r.add(e);for(const e of Object.keys(n))r.add(e);for(const e of r)this.migrateNormalizeAndSync(e)}listUploaderTypes(){return this.ctx.helper.uploader.getIdList()}getConfigList(e){return this.readTypeStore(e).configList}getActiveConfig(e){const t=this.readTypeStore(e);return this.getActiveConfigFromStore(t)}use(e,t){this.assertUploaderTypeExists(e);const i=this.readTypeStore(e);if(0===i.configList.length)return e!==Oe&&this.ctx.log.warn(`[UploaderConfigManager] No existing configs for uploader type "${e}". Creating a new metadata-only config`+(t?` named "${xo(t)}"`:"")+". Please configure it before uploading."),this.createOrUpdate(e,t,{});const n="string"==typeof t?xo(t):"";if(n){const r=this.findConfigByName(i.configList,n);if(!r)throw new Error(`Config ${t} not found in type ${e}`);return this.activate(e,i,r._id)}const{store:r,changed:o}=this.normalizeTypeStore(i),s=this.getActiveConfigFromStore(r);return s?this.persistTypeAndMirror(e,r,s,{setCurrent:!0,persistStore:o}):this.createOrUpdate(e,t,{})}createOrUpdate(e,t,i={}){this.assertUploaderTypeExists(e);const n=this.readTypeStore(e),r=Date.now(),o="string"==typeof t?xo(t):"",s=o?this.findConfigByName(n.configList,o):void 0;if(s){const t={...s,...i,_id:s._id,_configName:s._configName,_createdAt:s._createdAt,_updatedAt:r},o={configList:n.configList.map(e=>e._id===s._id?t:e),defaultId:t._id};return this.persistTypeAndMirror(e,o,t,{setCurrent:!0,persistStore:!0})}const a=o?this.ensureUniqueNameOrThrow(n.configList,o):this.generateDefaultName(n.configList),c={...i,_id:Go(),_configName:a,_createdAt:r,_updatedAt:r},l={configList:[...n.configList,c],defaultId:c._id};return this.persistTypeAndMirror(e,l,c,{setCurrent:!0,persistStore:!0})}copy(e,t,i){this.assertUploaderTypeExists(e);const n=this.readTypeStore(e),r=this.normalizeTypeStore(n).store,o=xo(t),s=this.findConfigByName(r.configList,o);if(!s)throw new Error(`Config ${t} not found in type ${e}`);const a=xo(i);if(!a)throw new Error("Config name can not be empty");const c=this.ensureUniqueNameOrThrow(r.configList,a),l=Date.now(),_={...s,_id:Go(),_configName:c,_createdAt:l,_updatedAt:l},E={configList:[...r.configList,_],defaultId:r.defaultId},d={[`uploader.${e}`]:E},p=this.getActiveConfigFromStore(E);if(p){const t=this.ctx.getConfig(`picBed.${e}`);u.isEqual(t,p)||(d[`picBed.${e}`]=p)}return this.ctx.saveConfig(d),_}rename(e,t,i){this.assertUploaderTypeExists(e);const n=this.readTypeStore(e),r=xo(t),o=xo(i);if(!o)throw new Error("Config name can not be empty");const s=this.findConfigByName(n.configList,r);if(!s)throw new Error(`Config ${t} not found in type ${e}`);this.ensureUniqueNameOrThrow(n.configList,o,s._id);const a=Date.now(),c={...s,_configName:o,_updatedAt:a},l={configList:n.configList.map(e=>e._id===s._id?c:e),defaultId:n.defaultId};return n.defaultId===s._id?(this.persistTypeAndMirror(e,l,c,{setCurrent:!1,persistStore:!0}),c):(this.ctx.saveConfig({[`uploader.${e}`]:l}),c)}remove(e,t){this.assertUploaderTypeExists(e);const i=this.readTypeStore(e),n=xo(t),r=this.findConfigByName(i.configList,n);if(!r)throw new Error(`Config ${t} not found in type ${e}`);const o=i.configList.filter(e=>e._id!==r._id);if(0===o.length)return this.ctx.saveConfig({[`uploader.${e}`]:{configList:[],defaultId:""}}),this.ctx.removeConfig("picBed",e),void(this.ctx.getConfig("picBed.current")===e&&this.ctx.log.warn(`You are currently using ${e} but have deleted its last config. Please switch to another uploader or create a new config.`));const s={configList:o,defaultId:i.defaultId===r._id?o[0]._id:i.defaultId},a=this.getActiveConfigFromStore(s);a?this.persistTypeAndMirror(e,s,a,{setCurrent:!1,persistStore:!0}):this.ctx.saveConfig({[`uploader.${e}`]:s})}migrateNormalizeAndSync(e){const t=this.ctx.getConfig(`picBed.${e}`);let i=this.readTypeStore(e),n=!1;if(0===i.configList.length&&wo(t)){const e=Date.now(),r={...t,_id:"string"==typeof t._id&&t._id.trim()?t._id:Go(),_configName:"string"==typeof t._configName&&xo(t._configName)?xo(t._configName):"Default",_createdAt:"number"==typeof t._createdAt?t._createdAt:e,_updatedAt:"number"==typeof t._updatedAt?t._updatedAt:e};i={configList:[r],defaultId:r._id},n=!0}const r=this.normalizeTypeStore(i);i=r.store,n=n||r.changed;const o={};n&&(o[`uploader.${e}`]=i);const s=this.getActiveConfigFromStore(i);if(s){const t=this.ctx.getConfig(`picBed.${e}`);u.isEqual(t,s)||(o[`picBed.${e}`]=s)}Object.keys(o).length>0&&this.ctx.saveConfig(o)}assertUploaderTypeExists(e){if(!this.listUploaderTypes().includes(e))throw new Error(`Type ${e} not found`)}readTypeStore(e){const t=this.ctx.getConfig(`uploader.${e}`);if(!wo(t))return{configList:[],defaultId:""};const i=t.configList,n=t.defaultId,r=[];if(Array.isArray(i))for(const e of i)wo(e)&&r.push(e);return{configList:r,defaultId:"string"==typeof n?n:""}}normalizeTypeStore(e){const t=Date.now();let i=!1;const n=new Set,r=new Set,o=e.configList.map(e=>{const o={...e};let s="string"==typeof o._id&&o._id.trim()?o._id:Go();for(;r.has(s);)s=Go();s!==o._id&&(o._id=s,i=!0),r.add(s);const a="number"==typeof o._createdAt?o._createdAt:t,c="number"==typeof o._updatedAt?o._updatedAt:t;a!==o._createdAt&&(o._createdAt=a,i=!0),c!==o._updatedAt&&(o._updatedAt=c,i=!0);let l=("string"==typeof o._configName?xo(o._configName):"")||this.generateDefaultNameFromUsed(n),_=bo(l);if(n.has(_)){const e=l;let r=1;for(;n.has(bo(`${e}-${r}`));)r++;l=`${e}-${r}`,_=bo(l),o._updatedAt=t,i=!0}return l!==o._configName&&(o._configName=l,i=!0),n.add(_),o});let s=e.defaultId;if(o.length>0){o.some(e=>e._id===s)||(s=o[0]._id,i=!0)}else""!==s&&(s="",i=!0);return{store:{configList:o,defaultId:s},changed:i}}generateDefaultName(e){const t=new Set(e.map(e=>bo(e._configName)));return this.generateDefaultNameFromUsed(t)}generateDefaultNameFromUsed(e){const t="Default";if(!e.has(bo(t)))return t;let i=1;for(;e.has(bo(`${t}-${i}`));)i++;return`${t}-${i}`}ensureUniqueNameOrThrow(e,t,i){const n=xo(t);if(!n)throw new Error("Config name can not be empty");const r=bo(n);if(e.some(e=>e._id!==i&&bo(e._configName)===r))throw new Error(`Config name ${t} already exists`);return n}findConfigByName(e,t){const i=bo(t);return e.find(e=>bo(e._configName)===i)}getActiveConfigFromStore(e){if(!e.defaultId)return e.configList[0];return e.configList.find(t=>t._id===e.defaultId)??e.configList[0]}activate(e,t,i){const n=t.configList.find(e=>e._id===i);if(!n)throw new Error(`Config not found for type ${e}`);const r={configList:t.configList,defaultId:i};return this.persistTypeAndMirror(e,r,n,{setCurrent:!0,persistStore:!0})}persistTypeAndMirror(e,t,i,n){const r={};if(n.persistStore&&(r[`uploader.${e}`]=t),i&&(r[`picBed.${e}`]=i),n.setCurrent&&(r["picBed.current"]=e,r["picBed.uploader"]=e),this.ctx.saveConfig(r),i)return i;const o=t.configList[0];if(!o)throw new Error(`No configs found in type ${e}`);return o}}class $o extends i.EventEmitter{_config;lifecycle;db;_pluginLoader;configPath;baseDir;helper;log;cmd;output;input;pluginHandler;server;cloud;uploaderConfig;Request;i18n;VERSION="3.1.0";GUI_VERSION;get pluginLoader(){return this._pluginLoader}constructor(e=""){super(),this.configPath=e,this.output=[],this.input=[],this.helper={transformer:new Pn("transformer"),uploader:new Pn("uploader"),beforeTransformPlugins:new Pn("beforeTransformPlugins"),beforeUploadPlugins:new Pn("beforeUploadPlugins"),afterUploadPlugins:new Pn("afterUploadPlugins"),afterFinishPlugins:new Pn("afterFinishPlugins")},this.initConfigPath(),this.log=new Tn(this),this.cmd=new Sn(this),this.pluginHandler=new lo(this),this.initConfig(),this.init()}initConfigPath(){if(""===this.configPath&&(this.configPath=n.homedir()+"/.picgo/config.json"),".JSON"!==t.extname(this.configPath).toUpperCase())throw this.configPath="",Error("The configuration file only supports JSON format.");this.baseDir=t.dirname(this.configPath);e.pathExistsSync(this.configPath)||e.ensureFileSync(`${this.configPath}`)}initConfig(){this.db=new co(this),this._config=this.db.read(!0)}init(){try{this.i18n=new Eo(this),this.Request=new ao(this),this.server=new So(this),this.cloud=new Mo(this),this._pluginLoader=new Xr(this),An("picgo"),Wr().register(this),{register(e){e.helper.transformer.register("path",zr),e.helper.transformer.register("base64",Jr)}}.register(this),An(""),this._pluginLoader.load(),this.uploaderConfig=new vo(this),this.lifecycle=new Hn(this)}catch(e){throw this.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),this.log.error(e),e}}use(e,t){if(t)return this.pluginLoader.registerPlugin(t,e),this.pluginLoader.getPlugin(t);return e(this)}registerCommands(){""!==this.configPath&&(this.cmd.init(),this.cmd.loadCommands())}getConfig(e){return e?u.get(this._config,e):this._config}saveConfig(e){le(e)?(this.setConfig(e),this.db.saveConfig(e)):this.log.warn("the format of config is invalid, please provide object")}removeConfig(e,t){e&&t&&(ce(e)?this.log.warn(`the config.${e} can't be removed`):(this.unsetConfig(e,t),this.db.unset(e,t)))}setConfig(e){le(e)?Object.keys(e).forEach(t=>{ce(t)&&(this.log.warn(`the config.${t} can't be modified`),delete e[t]),u.set(this._config,t,e[t]),io.emit(exports.IBusEvent.CONFIG_CHANGE,{configName:t,value:e[t]})}):this.log.warn("the format of config is invalid, please provide object")}unsetConfig(e,t){e&&t&&(ce(e)?this.log.warn(`the config.${e} can't be unset`):u.unset(this.getConfig(e),t))}get request(){return this.Request.request.bind(this.Request)}async openUrl(e){const t=(await import("open")).default;this.log.info("Opening browser with URL:",e),await t(e)}async upload(t,i){if(""===this.configPath)return this.log.error("The configuration file only supports JSON format."),[];if(void 0!==t&&0!==t.length){const{output:e}=await this.lifecycle.start(t,i);return e}$n(this,i);try{const{imgPath:t,shouldKeepAfterUploading:n}=await to(this);if("no image"===t)throw new Error("image not found in clipboard");try{const{output:e}=await this.lifecycle.start([t],i);return e}finally{if(!n)try{await e.remove(t)}catch(e){this.log.error(e)}}}catch(e){throw this.emit(exports.IBuildInEvent.FAILED,e),e}}}const Fo={...he,applyUrlRewriteToImgInfo:Y};exports.CloudManager=Mo,exports.Commander=Sn,exports.ConfigMerger=ii,exports.ConfigSyncManager=Ui,exports.CorruptedDataError=ri,exports.DecryptionFailedError=_i,exports.InvalidPinError=ci,exports.Lifecycle=Hn,exports.LifecyclePlugins=Pn,exports.Logger=Tn,exports.MaxRetryExceededError=li,exports.MissingHandlerError=si,exports.PicGo=$o,exports.PicGoUtils=Fo,exports.PluginHandler=lo,exports.PluginLoader=Xr,exports.Request=ao,exports.ServerManager=So,exports.UnsupportedVersionError=oi,exports.UploadOptionError=Mn,exports.evaluatePluginConfig=function(e,t,i){const n={...t??{}};return e.map(e=>{const t={...e};if("function"==typeof e.default)try{t.default=e.default({...n})}catch(n){t.default=void 0,i?.onError?.(e.name,"default",n)}if("function"==typeof e.choices)try{t.choices=e.choices({...n})}catch(n){t.choices=[],i?.onError?.(e.name,"choices",n)}return void 0===n[e.name]&&void 0!==t.default&&(n[e.name]=t.default),t})},exports.resolveUploadOptions=$n;
//# sourceMappingURL=index.cjs.js.map
