diff --git "a/dist/index.js" "b/dist/index.js" --- "a/dist/index.js" +++ "b/dist/index.js" @@ -1,26 +1,23 @@ -var Ft=Object.create;var ae=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Wt=Object.getPrototypeOf,Kt=Object.prototype.hasOwnProperty;var Y=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var xe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gt=(e,t)=>{for(var r in t)ae(e,r,{get:t[r],enumerable:!0})},Jt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of zt(t))!Kt.call(e,n)&&n!==r&&ae(e,n,{get:()=>t[n],enumerable:!(s=Vt(t,n))||s.enumerable});return e};var Yt=(e,t,r)=>(r=e!=null?Ft(Wt(e)):{},Jt(t||!e||!e.__esModule?ae(r,"default",{value:e,enumerable:!0}):r,e));var et=Te((kn,xr)=>{xr.exports={name:"dotenv",version:"17.0.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var nt=Te((Rn,v)=>{var ge=Y("fs"),ee=Y("path"),Tr=Y("os"),Pr=Y("crypto"),vr=et(),we=vr.version,kr=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Rr(e){let t={},r=e.toString();r=r.replace(/\r\n?/mg,` -`);let s;for(;(s=kr.exec(r))!=null;){let n=s[1],o=s[2]||"";o=o.trim();let i=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),i==='"'&&(o=o.replace(/\\n/g,` -`),o=o.replace(/\\r/g,"\r")),t[n]=o}return t}function Cr(e){e=e||{};let t=ot(e);e.path=t;let r=_.configDotenv(e);if(!r.parsed){let i=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw i.code="MISSING_DATA",i}let s=st(e).split(","),n=s.length,o;for(let i=0;i=n)throw a}return _.parse(o)}function Hr(e){console.error(`[dotenv@${we}][WARN] ${e}`)}function L(e){console.log(`[dotenv@${we}][DEBUG] ${e}`)}function rt(e){console.log(`[dotenv@${we}] ${e}`)}function st(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function Or(e,t){let r;try{r=new URL(t)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let s=r.password;if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let n=r.searchParams.get("environment");if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let o=`DOTENV_VAULT_${n.toUpperCase()}`,i=e.parsed[o];if(!i){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:i,key:s}}function ot(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)ge.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=ee.resolve(process.cwd(),".env.vault");return ge.existsSync(t)?t:null}function tt(e){return e[0]==="~"?ee.join(Tr.homedir(),e.slice(1)):e}function Ar(e){let t=!!(e&&e.debug),r=!!(e&&e.quiet);(t||!r)&&rt("Loading env from encrypted .env.vault");let s=_._parseVault(e),n=process.env;return e&&e.processEnv!=null&&(n=e.processEnv),_.populate(n,s,e),{parsed:s}}function $r(e){let t=ee.resolve(process.cwd(),".env"),r="utf8",s=!!(e&&e.debug),n=!!(e&&e.quiet);e&&e.encoding?r=e.encoding:s&&L("No encoding is specified. UTF-8 is used by default");let o=[t];if(e&&e.path)if(!Array.isArray(e.path))o=[tt(e.path)];else{o=[];for(let u of e.path)o.push(tt(u))}let i,a={};for(let u of o)try{let f=_.parse(ge.readFileSync(u,{encoding:r}));_.populate(a,f,e)}catch(f){s&&L(`Failed to load ${u} ${f.message}`),i=f}let l=process.env;e&&e.processEnv!=null&&(l=e.processEnv);let c=_.populate(l,a,e);if(s||!n){let u=Object.keys(c).length,f=[];for(let h of o)try{let m=ee.relative(process.cwd(),h);f.push(m)}catch(m){s&&L(`Failed to load ${h} ${m.message}`),i=m}rt(`injecting env (${u}) from ${f.join(",")} \u2013 [tip] encrypt with dotenvx: https://dotenvx.com`)}return i?{parsed:a,error:i}:{parsed:a}}function Ir(e){if(st(e).length===0)return _.configDotenv(e);let t=ot(e);return t?_._configVault(e):(Hr(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),_.configDotenv(e))}function Nr(e,t){let r=Buffer.from(t.slice(-64),"hex"),s=Buffer.from(e,"base64"),n=s.subarray(0,12),o=s.subarray(-16);s=s.subarray(12,-16);try{let i=Pr.createDecipheriv("aes-256-gcm",r,n);return i.setAuthTag(o),`${i.update(s)}${i.final()}`}catch(i){let a=i instanceof RangeError,l=i.message==="Invalid key length",c=i.message==="Unsupported state or unable to authenticate data";if(a||l){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(c){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw i}}function Mr(e,t,r={}){let s=!!(r&&r.debug),n=!!(r&&r.override),o={};if(typeof t!="object"){let i=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw i.code="OBJECT_REQUIRED",i}for(let i of Object.keys(t))Object.prototype.hasOwnProperty.call(e,i)?(n===!0&&(e[i]=t[i],o[i]=t[i]),s&&L(n===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):(e[i]=t[i],o[i]=t[i]);return o}var _={configDotenv:$r,_configVault:Ar,_parseVault:Cr,config:Ir,decrypt:Nr,parse:Rr,populate:Mr};v.exports.configDotenv=_.configDotenv;v.exports._configVault=_._configVault;v.exports._parseVault=_._parseVault;v.exports.config=_.config;v.exports.decrypt=_.decrypt;v.exports.parse=_.parse;v.exports.populate=_.populate;v.exports=_});import ye from"node:fs";function Dr(){ye.existsSync(j.logDir)||ye.mkdirSync(j.logDir,{recursive:!0})}function Br(...e){return e.map(t=>typeof t=="object"&&t!==null?JSON.stringify(t,null,2):String(t)).join(" ")}async function Lr(e,t){if(!j.enableFile)return;Dr();let s=`[${new Date().toISOString()}] [${e}] ${t} -`;try{await ye.promises.appendFile(j.logFile,s)}catch(n){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",n)}}function jr(e,...t){if(!j.enableConsole)return;let r={[O.DEBUG]:console.debug,[O.INFO]:console.log,[O.WARN]:console.warn,[O.ERROR]:console.error}[e]||console.log,s=new Date().toLocaleTimeString();r(`[${s}] [${e}]`,...t)}function at(e,...t){let r=Br(...t);jr(e,...t),Lr(e,r)}var O,j,d,I,U=xe(()=>{O={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},j={logFile:"./logs/app.log",logDir:"./logs",enableConsole:!0,enableFile:!0,logLevel:process.env.LOG_LEVEL||O.INFO};d=(...e)=>at(O.INFO,...e),I=(...e)=>at(O.ERROR,...e)});var ut={};Gt(ut,{checkCookieAvailability:()=>Vr,ensureDirectoryExists:()=>lt,getHumanReadableTimestamp:()=>ct,loadCookies:()=>_e,saveScreenshot:()=>be,waitForUserInput:()=>zr});import F from"node:fs";import Ur from"node:path";import Fr from"node:readline";function ct(){return new Date().toISOString().replace(/T/,"_").replace(/:/g,"-").replace(/\..+/,"")}function lt(e){F.existsSync(e)||(F.mkdirSync(e,{recursive:!0}),d(`\u5DF2\u521B\u5EFA\u76EE\u5F55: ${e}`))}function Vr(e,t){if(t)try{return JSON.parse(t),d("\u53D1\u73B0\u5E76\u9A8C\u8BC1\u4E86\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 COOKIES\u3002"),!0}catch(r){I("\u73AF\u5883\u53D8\u91CF COOKIES \u683C\u5F0F\u65E0\u6548 (\u5FC5\u987B\u662F JSON \u6570\u7EC4\u5B57\u7B26\u4E32):",r.message)}return F.existsSync(e)?(d(`\u53D1\u73B0 Cookie \u6587\u4EF6: ${e}`),!0):(I(`Cookie \u6587\u4EF6\u4E0D\u5B58\u5728: ${e}\uFF0C\u4E14\u672A\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002`),d("\u8BF7\u5148\u8FD0\u884C `npm run login` \u6216\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002"),!1)}function _e(e,t){try{if(t)return d("\u4ECE\u73AF\u5883\u53D8\u91CF COOKIES \u52A0\u8F7D Cookie..."),JSON.parse(t);if(F.existsSync(e))return d(`\u4ECE\u6587\u4EF6\u52A0\u8F7D Cookie: ${e}`),JSON.parse(F.readFileSync(e,"utf8"))}catch(r){throw I("\u52A0\u8F7D Cookie \u5931\u8D25:",r),new Error("\u65E0\u6CD5\u52A0\u8F7D\u6216\u89E3\u6790 Cookie\u3002")}return[]}async function be(e,t,r="screenshot"){lt(t);let s=ct(),n=Ur.join(t,`${r}_${s}.png`);return await e.screenshot({path:n,fullPage:!0}),d(`\u622A\u56FE\u5DF2\u4FDD\u5B58: ${n}`),n}function zr(){let e=Fr.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question("",()=>{e.close(),t()})})}var te=xe(()=>{U()});var R=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function Pe(){return{root:{key:""},static:new R}}function ve(e){let[t,...r]=e.split("/");return r[r.length-1]===""?r.slice(0,-1):r}function Xt(e,t){let r=new R;for(let[s,n]of t){let o=s<0?e.slice(-1*s).join("/"):e[s];if(typeof n=="string")r[n]=o;else{let i=o.match(n);if(i)for(let a in i.groups)r[a]=i.groups[a]}}return r}function ke(e,t="",r,s){let n=ve(r),o=e.root,i=0,a=[];for(let c=0;c0;o.methods||(o.methods=new R),o.methods[t]||(o.methods[t]=[]),o.methods[t].push({data:s||null,paramsMap:l?a:void 0}),l||(e.static[r]=o)}function Qt(e){if(!e.includes(":",1))return e.slice(1);let t=e.replace(/:(\w+)/g,(r,s)=>`(?<${s}>[^/]+)`).replace(/\./g,"\\.");return new RegExp(`^${t}$`)}function Re(e,t="",r,s){r[r.length-1]==="/"&&(r=r.slice(0,-1));let n=e.static[r];if(n&&n.methods){let a=n.methods[t]||n.methods[""];if(a!==void 0)return a[0]}let o=ve(r),i=ce(e,e.root,t,o,0)?.[0];if(i!==void 0)return s?.params===!1?i:{data:i.data,params:i.paramsMap?Xt(o,i.paramsMap):void 0}}function ce(e,t,r,s,n){if(n===s.length){if(t.methods){let i=t.methods[r]||t.methods[""];if(i)return i}if(t.param&&t.param.methods){let i=t.param.methods[r]||t.param.methods[""];if(i){let a=i[0].paramsMap;if(a?.[a?.length-1]?.[2])return i}}if(t.wildcard&&t.wildcard.methods){let i=t.wildcard.methods[r]||t.wildcard.methods[""];if(i){let a=i[0].paramsMap;if(a?.[a?.length-1]?.[2])return i}}return}let o=s[n];if(t.static){let i=t.static[o];if(i){let a=ce(e,i,r,s,n+1);if(a)return a}}if(t.param){let i=ce(e,t.param,r,s,n+1);if(i)return i}if(t.wildcard&&t.wildcard.methods)return t.wildcard.methods[r]||t.wildcard.methods[""]}function Ce(e="/"){let t=[],r=0;for(let s of e.split("/"))s&&(s==="*"?t.push(`(?<_${r++}>[^/]*)`):s.startsWith("**")?t.push(s==="**"?"?(?<_>.*)":`?(?<${s.slice(3)}>.+)`):s.includes(":")?t.push(s.replace(/:(\w+)/g,(n,o)=>`(?<${o}>[^/]+)`).replace(/\./g,"\\.")):t.push(s));return new RegExp(`^/${t.join("/")}/?$`)}function Oe(e){let t=e.port??globalThis.process?.env.PORT??3e3,r=typeof t=="number"?t:Number.parseInt(t,10),s=e.hostname??globalThis.process?.env.HOST;return{port:r,hostname:s}}function Ae(e,t,r){if(!(!e||!t))return e.includes(":")&&(e=`[${e}]`),`http${r?"s":""}://${e}:${t}/`}function $e(e,t){if(!t||(e.silent??globalThis.process?.env?.TEST))return;let r=new URL(t),s=r.hostname==="[::]"||r.hostname==="0.0.0.0";s&&(r.hostname="localhost",t=r.href);let n="\u279C Listening on:",o=s?" (all interfaces)":"";globalThis.process.stdout?.isTTY&&(n=`\x1B[32m${n}\x1B[0m`,t=`\x1B[36m${t}\x1B[0m`,o=`\x1B[2m${o}\x1B[0m`),console.log(` ${n} ${t}${o}`)}function Ie(e){if(!e.tls||e.protocol==="http")return;let t=He(e.tls.cert),r=He(e.tls.key);if(!t&&!r){if(e.protocol==="https")throw new TypeError("TLS `cert` and `key` must be provided for `https` protocol.");return}if(!t||!r)throw new TypeError("TLS `cert` and `key` must be provided together.");return{cert:t,key:r,passphrase:e.tls.passphrase}}function He(e){if(!e)return;if(typeof e!="string")throw new TypeError("TLS certificate and key must be strings in PEM format or file paths.");if(e.startsWith("-----BEGIN "))return e;let{readFileSync:t}=process.getBuiltinModule("node:fs");return t(e,"utf8")}function Ne(){let e=new Set;return{waitUntil:t=>{e.add(t.catch(console.error).finally(()=>{e.delete(t)}))},wait:()=>Promise.all(e)}}function Me(e){let t=e.options.fetch,r=e.options.middleware||[];return r.length===0?t:s=>qe(s,t,r,0)}function qe(e,t,r,s){return s===r.length?t(e):r[s](e,()=>qe(e,t,r,s+1))}var le=(()=>{let e=class{#r;#t;_pathname;_urlqindex;_query;_search;constructor(s){this.#r=s}get _url(){return this.#t||(this.#t=new globalThis.URL(this.#r)),this.#t}toString(){return this._url.toString()}toJSON(){return this.toString()}get pathname(){if(this.#t)return this.#t.pathname;if(this._pathname===void 0){let s=this.#r,n=s.indexOf("://");if(n===-1)return this._url.pathname;let o=s.indexOf("/",n+4);if(o===-1)return this._url.pathname;let i=this._urlqindex=s.indexOf("?",o);this._pathname=s.slice(o,i===-1?void 0:i)}return this._pathname}set pathname(s){this._pathname=void 0,this._url.pathname=s}get searchParams(){return this.#t?this.#t.searchParams:(this._query||(this._query=new URLSearchParams(this.search)),this._query)}get search(){if(this.#t)return this.#t.search;if(this._search===void 0){let s=this._urlqindex;s===-1||s===this.#r.length-1?this._search="":this._search=s===void 0?this._url.search:this.#r.slice(s)}return this._search}set search(s){this._search=void 0,this._query=void 0,this._url.search=s}},t=["hash","host","hostname","href","origin","password","port","protocol","username"];for(let r of t)Object.defineProperty(e.prototype,r,{get(){return this._url[r]},set(s){this._url[r]=s}});return Object.setPrototypeOf(e,globalThis.URL),e})();var De=e=>{let t=e.options.error;t&&e.options.middleware.unshift((r,s)=>{try{let n=s();return n instanceof Promise?n.catch(o=>t(o)):n}catch(n){return t(n)}})};function $(e){if(Array.isArray(e))return e.flatMap(u=>$(u));if(typeof e!="string")return[];let t=[],r=0,s,n,o,i,a,l=()=>{for(;r(n=e.charAt(r),n!=="="&&n!==";"&&n!==",");for(;r=e.length)&&t.push(e.slice(s))}return t}async function Be(e,t){if(!t)return e.statusCode=500,ue(e);if(t.nodeResponse){let s=t.nodeResponse();if(Le(e,s.status,s.statusText,s.headers.flat()),s.body){if(s.body instanceof ReadableStream)return je(s.body,e);if(typeof s.body?.pipe=="function")return s.body.pipe(e),new Promise(n=>e.on("close",n));e.write(s.body)}return ue(e)}let r=[];for(let[s,n]of t.headers)if(s==="set-cookie")for(let o of $(n))r.push(["set-cookie",o]);else r.push([s,n]);return Le(e,t.status,t.statusText,r.flat()),t.body?je(t.body,e):ue(e)}function Le(e,t,r,s){e.headersSent||(e.req?.httpVersion==="2.0"?e.writeHead(t,s.flat()):e.writeHead(t,r,s.flat()))}function ue(e){return new Promise(t=>e.end(t))}function je(e,t){if(t.destroyed){e.cancel();return}let r=e.getReader();function s(o){r.cancel(o).catch(()=>{}),o&&t.destroy(o)}function n({done:o,value:i}){try{o?t.end():t.write(i)?r.read().then(n,s):t.once("drain",()=>r.read().then(n,s))}catch(a){s(a instanceof Error?a:void 0)}}return t.on("close",s),t.on("error",s),r.read().then(n,s),r.closed.finally(()=>{t.off("close",s),t.off("error",s)})}var de=Symbol.for("nodejs.util.inspect.custom"),Zt=(()=>{let e=class{_node;constructor(r){this._node=r}append(r,s){r=q(r);let n=this._node.req.headers,o=n[r];o?Array.isArray(o)?o.push(s):n[r]=[o,s]:n[r]=s}delete(r){r=q(r),this._node.req.headers[r]=void 0}get(r){return r=q(r),this._node.req.headers[r]===void 0?null:M(this._node.req.headers[r])}getSetCookie(){let r=this._node.req.headers["set-cookie"];return!r||r.length===0?[]:$(r)}has(r){return r=q(r),!!this._node.req.headers[r]}set(r,s){r=q(r),this._node.req.headers[r]=s}get count(){throw new Error("Method not implemented.")}getAll(r){throw new Error("Method not implemented.")}toJSON(){let r=this._node.req.headers,s={};for(let n in r)r[n]&&(s[n]=M(r[n]));return s}forEach(r,s){let n=this._node.req.headers;for(let o in n)n[o]&&r.call(s,M(n[o]),o,this)}*entries(){let r=this._node.req.headers,s=this._node.req.httpVersion==="2.0";for(let n in r)(!s||n[0]!==":")&&(yield[n,M(r[n])])}*keys(){let r=Object.keys(this._node.req.headers);for(let s of r)yield s}*values(){let r=Object.values(this._node.req.headers);for(let s of r)yield M(s)}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}get[Symbol.toStringTag](){return"Headers"}[de](){return Object.fromEntries(this.entries())}};return Object.setPrototypeOf(e.prototype,globalThis.Headers.prototype),e})();function M(e){return Array.isArray(e)?e.join(", "):typeof e=="string"?e:String(e??"")}function q(e){if(e[0]===":")throw new TypeError(`${JSON.stringify(e)} is an invalid header name.`);return e.toLowerCase()}var er=(()=>{let e=class{_node;_hash="";_username="";_password="";_protocol;_hostname;_port;_pathname;_search;_searchParams;constructor(r){this._node=r}get hash(){return this._hash}set hash(r){this._hash=r}get username(){return this._username}set username(r){this._username=r}get password(){return this._password}set password(r){this._password=r}get host(){return this._node.req.headers.host||this._node.req.headers[":authority"]||""}set host(r){this._hostname=void 0,this._port=void 0,this._node.req.headers.host=r}get hostname(){if(this._hostname===void 0){let[r,s]=Fe(this._node.req.headers.host);this._port===void 0&&s&&(this._port=String(Number.parseInt(s)||"")),this._hostname=r||"localhost"}return this._hostname}set hostname(r){this._hostname=r}get port(){if(this._port===void 0){let[r,s]=Fe(this._node.req.headers.host);this._hostname===void 0&&r&&(this._hostname=r),this._port=s||String(this._node.req.socket?.localPort||"")}return this._port}set port(r){this._port=String(Number.parseInt(r)||"")}get pathname(){if(this._pathname===void 0){let[r,s]=Ue(this._node.req.url||"/");this._pathname=r,this._search===void 0&&(this._search=s)}return this._pathname}set pathname(r){r[0]!=="/"&&(r="/"+r),r!==this._pathname&&(this._pathname=r,this._node.req.url=r+this.search)}get search(){if(this._search===void 0){let[r,s]=Ue(this._node.req.url||"/");this._search=s,this._pathname===void 0&&(this._pathname=r)}return this._search}set search(r){r==="?"?r="":r&&r[0]!=="?"&&(r="?"+r),r!==this._search&&(this._search=r,this._searchParams=void 0,this._node.req.url=this.pathname+r)}get searchParams(){return this._searchParams||(this._searchParams=new URLSearchParams(this.search)),this._searchParams}set searchParams(r){this._searchParams=r,this._search=r.toString()}get protocol(){return this._protocol||(this._protocol=this._node.req.socket?.encrypted||this._node.req.headers["x-forwarded-proto"]==="https"?"https:":"http:"),this._protocol}set protocol(r){this._protocol=r}get origin(){return`${this.protocol}//${this.host}`}set origin(r){}get href(){return`${this.protocol}//${this.host}${this.pathname}${this.search}`}set href(r){let s=new globalThis.URL(r);this._protocol=s.protocol,this.username=s.username,this.password=s.password,this._hostname=s.hostname,this._port=s.port,this.pathname=s.pathname,this.search=s.search,this.hash=s.hash}toString(){return this.href}toJSON(){return this.href}get[Symbol.toStringTag](){return"URL"}[de](){return this.href}};return Object.setPrototypeOf(e.prototype,globalThis.URL.prototype),e})();function Ue(e){let t=(e||"/").replace(/\\/g,"/"),r=t.indexOf("?");return r===-1?[t,""]:[t.slice(0,r),t.slice(r)]}function Fe(e){let t=(e||"").split(":");return[t[0],String(Number.parseInt(t[1])||"")]}var tr=(()=>{let e=["cache","credentials","destination","integrity","keepalive","mode","redirect","referrer","referrerPolicy"],t=class{#r;#t;#e=!1;#s;#o;#n;#i;#a;#c;#l;#u;_node;runtime;constructor(s){this._node=s,this.runtime={name:"node",node:s}}get ip(){return this._node.req.socket?.remoteAddress}get headers(){return this.#t||(this.#t=new Zt(this._node)),this.#t}clone(){return new t({...this._node})}get _url(){return this.#r||(this.#r=new er(this._node)),this.#r}get url(){return this._url.href}get method(){return this._node.req.method||"GET"}get signal(){return this.#s||(this.#s=new AbortController,this._node.req.once("close",()=>{this.#s?.abort()})),this.#s.signal}get bodyUsed(){return this.#e}get _hasBody(){if(this.#o!==void 0)return this.#o;let s=this._node.req.method?.toUpperCase();return!s||!(s==="PATCH"||s==="POST"||s==="PUT"||s==="DELETE")?(this.#o=!1,!1):!Number.parseInt(this._node.req.headers["content-length"]||"")&&!(this._node.req.headers["transfer-encoding"]||"").split(",").map(o=>o.trim()).filter(Boolean).includes("chunked")?(this.#o=!1,!1):(this.#o=!0,!0)}get body(){return this._hasBody?(this.#u||(this.#e=!0,this.#u=new ReadableStream({start:s=>{this._node.req.on("data",n=>{s.enqueue(n)}).once("error",n=>{s.error(n),this.#s?.abort()}).once("close",()=>{this.#s?.abort()}).once("end",()=>{s.close()})}})),this.#u):null}bytes(){if(!this.#n){let s=this.body;this.#n=s?rr(s):Promise.resolve(new Uint8Array)}return this.#n}arrayBuffer(){return this.bytes().then(s=>s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength))}blob(){return this.#i||(this.#i=this.bytes().then(s=>new Blob([s],{type:this._node.req.headers["content-type"]}))),this.#i}formData(){return this.#a||(this.#a=new Response(this.body,{headers:this.headers}).formData()),this.#a}text(){return this.#l||(this.#l=this.bytes().then(s=>new TextDecoder().decode(s))),this.#l}json(){return this.#c||(this.#c=this.text().then(s=>JSON.parse(s))),this.#c}get[Symbol.toStringTag](){return"Request"}[de](){return{method:this.method,url:this.url,headers:this.headers}}};for(let r of e)Object.defineProperty(t.prototype,r,{enumerable:!0,configurable:!1});return Object.setPrototypeOf(t.prototype,globalThis.Request.prototype),t})();async function rr(e){let t=[];return await e.pipeTo(new WritableStream({write(r){t.push(r)}})),Buffer.concat(t)}var D=(()=>{let e="content-type",t="application/json",r=[[e,t]],s=class{#r;#t;constructor(o,i){this.#r=o,this.#t=i}static json(o,i){if(i?.headers){if(!i.headers[e]){let a=new Headers(i.headers);a.has(e)||a.set(e,t),i={...i,headers:a}}}else i=i?{...i}:{},i.headers=r;return new s(JSON.stringify(o),i)}static error(){return globalThis.Response.error()}static redirect(o,i){return globalThis.Response.redirect(o,i)}nodeResponse(){let o=this.#t?.status??200,i=this.#t?.statusText??"",a=[],l=this.#t?.headers;if(this.#s)for(let[f,h]of this.#s)if(f==="set-cookie")for(let m of $(h))a.push(["set-cookie",m]);else a.push([f,h]);else if(l){let f=Array.isArray(l)?l:l.entries?l.entries():Object.entries(l);for(let[h,m]of f)if(h==="set-cookie")for(let T of $(m))a.push(["set-cookie",T]);else a.push([h,m])}let c=this.#r,u;if(c)if(typeof c=="string")u=c;else if(c instanceof ReadableStream)u=c;else if(c instanceof ArrayBuffer)u=Buffer.from(c);else if(c instanceof Uint8Array)u=Buffer.from(c);else if(c instanceof DataView)u=Buffer.from(c.buffer);else if(c instanceof Blob)u=c.stream(),c.type&&a.push(["content-type",c.type]);else if(typeof c.pipe=="function")u=c;else{let f=new globalThis.Response(c);u=f.body;for(let[h,m]of f.headers)a.push([h,m])}return this.#r=void 0,this.#t=void 0,this.#s=void 0,this.#e=void 0,{status:o,statusText:i,headers:a,body:u}}#e;#s;clone(){return this.#e?this.#e.clone():this.#s?new s(this.#r,{...this.#t,headers:this.#s}):new s(this.#r,this.#t)}get#o(){return this.#e||(this.#e=this.#s?new globalThis.Response(this.#r,{...this.#t,headers:this.#s}):new globalThis.Response(this.#r,this.#t),this.#r=void 0,this.#t=void 0,this.#s=void 0),this.#e}get headers(){return this.#e?this.#e.headers:(this.#s||(this.#s=new Headers(this.#t?.headers)),this.#s)}get ok(){if(this.#e)return this.#e.ok;let o=this.#t?.status??200;return o>=200&&o<300}get redirected(){return this.#e?this.#e.redirected:!1}get status(){return this.#e?this.#e.status:this.#t?.status??200}get statusText(){return this.#e?this.#e.statusText:this.#t?.statusText??""}get type(){return this.#e?this.#e.type:"default"}get url(){return this.#e?this.#e.url:""}#n(o){let i=this.#r;return i==null?null:i instanceof o?i:!1}get body(){if(this.#e)return this.#e.body;let o=this.#n(ReadableStream);return o!==!1?o:this.#o.body}get bodyUsed(){return this.#e?this.#e.bodyUsed:!1}arrayBuffer(){if(this.#e)return this.#e.arrayBuffer();let o=this.#n(ArrayBuffer);return o!==!1?Promise.resolve(o||new ArrayBuffer(0)):this.#o.arrayBuffer()}blob(){if(this.#e)return this.#e.blob();let o=this.#n(Blob);return o!==!1?Promise.resolve(o||new Blob):this.#o.blob()}bytes(){if(this.#e)return this.#e.bytes();let o=this.#n(Uint8Array);return o!==!1?Promise.resolve(o||new Uint8Array):this.#o.bytes()}formData(){if(this.#e)return this.#e.formData();let o=this.#n(FormData);return o!==!1?Promise.resolve(o||new FormData):this.#o.formData()}text(){if(this.#e)return this.#e.text();let o=this.#r;return o==null?Promise.resolve(""):typeof o=="string"?Promise.resolve(o):this.#o.text()}json(){return this.#e?this.#e.json():this.text().then(o=>JSON.parse(o))}};return Object.setPrototypeOf(s.prototype,globalThis.Response.prototype),s})();function Ve(e){return new sr(e)}var sr=class{runtime="node";options;node;serveOptions;fetch;#r;#t;#e;constructor(e){this.options={...e,middleware:[...e.middleware||[]]};for(let l of e.plugins||[])l(this);De(this);let t=this.fetch=Me(this);this.#e=Ne();let r=(l,c)=>{let u=new tr({req:l,res:c});u.waitUntil=this.#e.waitUntil;let f=t(u);return f instanceof Promise?f.then(h=>Be(c,h)):Be(c,f)},s=Ie(this.options),{port:n,hostname:o}=Oe(this.options);this.serveOptions={port:n,host:o,exclusive:!this.options.reusePort,...s?{cert:s.cert,key:s.key,passphrase:s.passphrase}:{},...this.options.node};let i;if(this.#r=!!this.serveOptions.cert&&this.options.protocol!=="http",this.options.node?.http2??this.#r)if(this.#r){let{createSecureServer:l}=process.getBuiltinModule("node:http2");i=l({allowHTTP1:!0,...this.serveOptions},r)}else throw new Error("node.http2 option requires tls certificate!");else if(this.#r){let{createServer:l}=process.getBuiltinModule("node:https");i=l(this.serveOptions,r)}else{let{createServer:l}=process.getBuiltinModule("node:http");i=l(this.serveOptions,r)}this.node={server:i,handler:r},e.manual||this.serve()}serve(){if(this.#t)return Promise.resolve(this.#t).then(()=>this);this.#t=new Promise(e=>{this.node.server.listen(this.serveOptions,()=>{$e(this.options,this.url),e()})})}get url(){let e=this.node?.server?.address();if(e)return typeof e=="string"?e:Ae(e.address,e.port,this.#r)}ready(){return Promise.resolve(this.#t).then(()=>this)}async close(e){await Promise.all([this.#e.wait(),new Promise((t,r)=>{let s=this.node?.server;if(!s)return t();e&&"closeAllConnections"in s&&s.closeAllConnections(),s.close(n=>n?r(n):t())})])}};function We(e){e.config=Object.freeze(e.config),e._addRoute=()=>{throw new Error("Cannot add routes after the server init.")}}var Ke=class{app;req;url;context;static __is_event__=!0;_res;constructor(e,t,r){this.context=t||new R,this.req=e,this.app=r;let s=e._url;this.url=s&&s instanceof URL?s:new le(e.url)}get res(){return this._res||(this._res=new or),this._res}get runtime(){return this.req.runtime}waitUntil(e){this.req.waitUntil?.(e)}toString(){return`[${this.req.method}] ${this.req.url}`}toJSON(){return this.toString()}get node(){return this.req.runtime?.node}get headers(){return this.req.headers}get path(){return this.url.pathname+this.url.search}get method(){return this.req.method}},or=class{status;statusText;_headers;get headers(){return this._headers||(this._headers=new Headers),this._headers}},nr=/[^\u0009\u0020-\u007E]/g;function Ge(e=""){return e.replace(nr,"")}function Je(e,t=200){return!e||(typeof e=="string"&&(e=+e),e<100||e>599)?t:e}var C=class Ye extends Error{status;statusText;headers;cause;data;body;unhandled;static isError(t){return t?.constructor?.name==="HTTPError"}static status(t,r,s){return new Ye({...s,statusText:r,status:t})}constructor(t,r){let s,n;typeof t=="string"?(s=t,n=r):n=t;let o=Je(n?.status||n?.cause?.status||n?.status||n?.statusCode,500),i=Ge(n?.statusText||n?.cause?.statusText||n?.statusText||n?.statusMessage),a=s||n?.message||n?.cause?.message||n?.statusText||n?.statusMessage||["HTTPError",o,i].filter(Boolean).join(" ");super(a,{cause:n}),this.cause=n,Error.captureStackTrace?.(this,this.constructor),this.status=o,this.statusText=i||void 0;let l=n?.headers||n?.cause?.headers;this.headers=l?new Headers(l):void 0,this.unhandled=n?.unhandled??n?.cause?.unhandled??void 0,this.data=n?.data,this.body=n?.body}get statusCode(){return this.status}get statusMessage(){return this.statusText}toJSON(){let t=this.unhandled;return{status:this.status,statusText:this.statusText,unhandled:t,message:t?"HTTPError":this.message,data:t?void 0:this.data,...t?void 0:this.body}}};function ir(e,t){try{return t in e}catch{return!1}}function ar(e,t){if(e==null)return!0;if(t!=="object")return t==="boolean"||t==="number"||t==="string";if(typeof e.toJSON=="function"||Array.isArray(e))return!0;if(typeof e.pipe=="function"||typeof e.pipeTo=="function")return!1;if(e instanceof R)return!0;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}var B=Symbol.for("h3.notFound"),cr=Symbol.for("h3.handled");function X(e,t,r={}){if(e&&e instanceof Promise)return e.catch(o=>o).then(o=>X(o,t,r));let s=Xe(e,t,r);if(s instanceof Promise)return X(s,t,r);let{onResponse:n}=r;return n?Promise.resolve(n(s,t)).then(()=>s):s}function Xe(e,t,r,s){if(e===cr)return new D(null);if(e===B&&(e=new C({status:404,message:`Cannot find any route matching [${t.req.method}] ${t.url}`})),e&&e instanceof Error){let o=C.isError(e),i=o?e:new C(e);o||(i.unhandled=!0,e?.stack&&(i.stack=e.stack));let{onError:a}=r;return a&&!s?Promise.resolve(a(i,t)).catch(l=>l).then(l=>Xe(l??e,t,r,!0)):dr(i,r.debug)}let n=t.res._headers;if(!(e instanceof Response)){let o=ur(e,t,r),i=t.res.status;return new D(ze(t.req.method,i)?null:o.body,{status:i,statusText:t.res.statusText,headers:o.headers&&n?he(o.headers,n):o.headers||n})}return n?new D(ze(t.req.method,e.status)?null:e.body,{status:e.status,statusText:e.statusText,headers:he(n,e.headers)}):e}function he(e,t){let r=new Headers(e);for(let[s,n]of t)s==="set-cookie"?r.append(s,n):r.set(s,n);return r}var lr=new Headers({"content-length":"0"}),Q=new Headers({"content-type":"application/json;charset=UTF-8"});function ur(e,t,r){if(e==null)return{body:"",headers:lr};let s=typeof e;if(s==="string")return{body:e};if(e instanceof Uint8Array)return t.res.headers.set("content-length",e.byteLength.toString()),{body:e};if(ar(e,s))return{body:JSON.stringify(e,void 0,r.debug?2:void 0),headers:Q};if(s==="bigint")return{body:e.toString(),headers:Q};if(e instanceof Blob){let n={"content-type":e.type,"content-length":e.size.toString()},o=e.name;return o&&(o=encodeURIComponent(o),n["content-disposition"]=`filename="${o}"; filename*=UTF-8''${o}`),{body:e.stream(),headers:n}}return s==="symbol"?{body:e.toString()}:s==="function"?{body:`${e.name}()`}:{body:e}}function ze(e,t){return e==="HEAD"||t===100||t===101||t===102||t===204||t===205||t===304}function dr(e,t){return new D(JSON.stringify({...e.toJSON(),stack:t&&e.stack?e.stack.split(` -`).map(r=>r.trim()):void 0},void 0,t?2:void 0),{status:e.status,statusText:e.statusText,headers:e.headers?he(Q,e.headers):Q})}function hr(e,t={}){let r=fr(t);return!r&&(e.length>1||e.constructor?.name==="AsyncFunction")?e:(s,n)=>{if(r&&!r(s))return n();let o=e(s,n);return o===void 0||o===B?n():o}}function fr(e){if(!e.route&&!e.method&&!e.match)return;let t=e.route?Ce(e.route):void 0,r=e.method?.toUpperCase();return s=>{if(r&&s.req.method!==r||e.match&&!e.match(s))return!1;if(!t)return!0;let n=s.url.pathname.match(t);return n?(n.groups&&(s.context.middlewareParams={...s.context.middlewareParams,...n.groups}),!0):!1}}function fe(e,t,r,s=0){if(s===t.length)return r(e);let n=t[s],o=()=>fe(e,t,r,s+1),i=n(e,o);return i===void 0||i===B?o():i instanceof Promise?i.then(a=>a===void 0||a===B?o():a):i}var Qe=(()=>{let e=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"];class t{_middleware;_routes=[];config;constructor(s={}){this._middleware=[],this.config=s,this.fetch=this.fetch.bind(this),this._fetch=this._fetch.bind(this),this.handler=this.handler.bind(this),s.plugins?.forEach(n=>n(this))}fetch(s,n){try{return Promise.resolve(this._fetch(s,n))}catch(o){return Promise.reject(o)}}_fetch(s,n,o){let i=mr(s,n),a=new Ke(i,o,this),l;try{if(this.config.onRequest){let c=this.config.onRequest(a);l=c instanceof Promise?c.then(()=>this.handler(a)):this.handler(a)}else l=this.handler(a)}catch(c){l=Promise.reject(c)}return X(l,a,this.config)}register(s){return s(this),this}_findRoute(s){}_addRoute(s){this._routes.push(s)}handler(s){let n=this._findRoute(s);n&&(s.context.params=n.params,s.context.matchedRoute=n.data);let o=n?.data.middleware?[...this._middleware,...n.data.middleware]:this._middleware;return fe(s,o,()=>n?n.data.handler(s):B)}mount(s,n){if("handler"in n){n._middleware.length>0&&this._middleware.push((o,i)=>o.url.pathname.startsWith(s)?fe(o,n._middleware,i):i());for(let o of n._routes)this._addRoute({...o,route:s+o.route})}else{let o="fetch"in n?n.fetch:n;this.all(`${s}/**`,i=>{let a=new URL(i.url);return a.pathname=a.pathname.slice(s.length)||"/",o(new Request(a,i.req))})}return this}all(s,n,o){return this.on("",s,n,o)}on(s,n,o,i){let a=(s||"").toUpperCase();return n=new URL(n,"h://_").pathname,this._addRoute({method:a,route:n,handler:o,middleware:i?.middleware,meta:{...o.meta,...i?.meta}}),this}use(s,n,o){let i,a,l;return typeof s=="string"?(i=s,a=n,l=o):(a=s,l=n),this._middleware.push(hr(a,i?{...l,route:i}:l)),this}}for(let r of e)t.prototype[r.toLowerCase()]=function(s,n,o){return this.on(r,s,n,o)};return t})(),me=class extends Qe{_rou3;constructor(e={}){super(e),this._rou3=Pe()}_findRoute(e){return Re(this._rou3,e.req.method,e.url.pathname)}_addRoute(e){ke(this._rou3,e.method,e.route,e),super._addRoute(e)}};function mr(e,t){if(typeof e=="string"){let r=e;if(r[0]==="/"){let s=t?.headers?new Headers(t.headers):void 0,n=s?.get("host")||"localhost";r=`${s?.get("x-forwarded-proto")==="https"?"https":"http"}://${n}${r}`}return new Request(r,t)}else if(t||e instanceof URL)return new Request(e,t);return e}function pr(e){let t=new URLSearchParams(e),r=new R;for(let[s,n]of t.entries())ir(r,s)?(Array.isArray(r[s])||(r[s]=[r[s]]),r[s].push(n)):r[s]=n;return r}async function pe(e){let t=await e.req.text();if(!t)return;if((e.req.headers.get("content-type")||"").startsWith("application/x-www-form-urlencoded"))return pr(t);try{return JSON.parse(t)}catch{throw new C({status:400,statusText:"Bad Request",message:"Invalid JSON body"})}}function gr(e){return!e||e==="/"?"/":e[0]==="/"?e:`/${e}`}function wr(e){return!e||e==="/"?"/":e[e.length-1]==="/"?e.slice(0,-1):e}var yr={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".txt":"text/plain",".xml":"application/xml",".gif":"image/gif",".ico":"image/vnd.microsoft.icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".mp4":"video/mp4",".webm":"video/webm",".zip":"application/zip",".pdf":"application/pdf"};function _r(e){let t=e.split("/").pop();if(!t)return;let r=t.lastIndexOf(".");if(r!==-1)return t.slice(r)}function br(e){return e?yr[e]:void 0}async function Z(e,t){if(t.headers){let c=Array.isArray(t.headers)?t.headers:typeof t.headers.entries=="function"?t.headers.entries():Object.entries(t.headers);for(let[u,f]of c)e.res.headers.set(u,f)}if(e.req.method!=="GET"&&e.req.method!=="HEAD"){if(t.fallthrough)return;throw e.res.headers.set("allow","GET, HEAD"),new C({status:405})}let r=decodeURI(gr(wr(e.url.pathname))),s=Sr(e.req.headers.get("accept-encoding")||"",t.encodings);s.length>1&&e.res.headers.set("vary","accept-encoding");let n=r,o,i=Er(r,s,t.indexNames||["/index.html"]);for(let c of i){let u=await t.getMeta(c);if(u){o=u,n=c;break}}if(!o){if(t.fallthrough)return;throw new C({statusCode:404})}if(o.mtime){let c=new Date(o.mtime),u=e.req.headers.get("if-modified-since");if(u&&new Date(u)>=c)return e.res.status=304,e.res.statusText="Not Modified","";e.res.headers.get("last-modified")||e.res.headers.set("last-modified",c.toUTCString())}if(o.etag&&!e.res.headers.has("etag")&&e.res.headers.set("etag",o.etag),o.etag&&e.req.headers.get("if-none-match")===o.etag)return e.res.status=304,e.res.statusText="Not Modified","";if(!e.res.headers.get("content-type"))if(o.type)e.res.headers.set("content-type",o.type);else{let c=_r(n),u=c?t.getType?.(c)??br(c):void 0;u&&e.res.headers.set("content-type",u)}return o.encoding&&!e.res.headers.get("content-encoding")&&e.res.headers.set("content-encoding",o.encoding),o.size!==void 0&&o.size>0&&!e.req.headers.get("content-length")&&e.res.headers.set("content-length",o.size+""),e.req.method==="HEAD"?"":await t.getContents(n)}function Sr(e,t){return!t||!e?[]:String(e||"").split(",").map(r=>t[r.trim()]).filter(Boolean)}function Er(e,t,r){let s=[];for(let n of["",...r])for(let o of[...t,""])s.push(`${e}${n}${o}`);return s}function S(e,t){return new C(e,t)}function Ze(e,t){return We(e),Ve({fetch:e._fetch,...t})}import{stat as Bt,readFile as Lt}from"node:fs/promises";import{join as jt}from"node:path";import{chromium as Wr}from"playwright";var it=Yt(nt(),1);it.default.config();var qr={server:{port:parseInt(process.env.PORT||"3096",10),host:process.env.HOST||"localhost"},browser:{headless:(process.env.HEADLESS||"true").toLowerCase()!=="false",timeout:parseInt(process.env.TIMEOUT||"30000",10),executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,args:["--disable-blink-features=AutomationControlled","--no-sandbox","--disable-dev-shm-usage","--disable-infobars","--disable-extensions"],userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},cookieFile:"./cookies.json",cookiesFromEnv:process.env.COOKIES,screenshotDir:"./screenshots",aiStudio:{url:process.env.AI_STUDIO_URL||"https://aistudio.google.com/prompts/new_chat",responseTimeout:parseInt(process.env.RESPONSE_TIMEOUT||"600000",10),pageTimeout:parseInt(process.env.PAGE_TIMEOUT||"30000",10)},api:{defaultModel:process.env.DEFAULT_MODEL||"gemini-pro",maxTokens:65536,temperature:1,token:process.env.API_TOKEN},models:{"gemini-2.5-pro":{displayName:"Gemini 2.5 Pro",id:"gemini-2.5-pro",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-pro",parent:null},"gemini-2.5-flash":{displayName:"Gemini 2.5 Flash",id:"gemini-2.5-flash",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-flash",parent:null},"gemini-pro":{displayName:"Gemini Pro",id:"gemini-pro",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-pro",parent:null},"gemini-flash":{displayName:"Gemini Flash",id:"gemini-flash",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-flash",parent:null}},debug:{logRequests:process.env.DEBUG_REQUESTS==="true",logResponses:process.env.DEBUG_RESPONSES==="true",saveScreenshots:process.env.SAVE_SCREENSHOTS==="true"}},p=qr;te();U();var A=null,N=null,re=class{constructor(t=5){this.maxSize=t,this.availablePages=[],this.busyPages=new Set,this.totalPages=0}async getPage(){if(this.availablePages.length>0){let t=this.availablePages.pop();return this.busyPages.add(t),d(`\u4ECE\u9875\u9762\u6C60\u83B7\u53D6\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),t}if(this.totalPages{let r=()=>{if(this.availablePages.length>0){let s=this.availablePages.pop();this.busyPages.add(s),d(`\u7B49\u5F85\u540E\u83B7\u53D6\u5230\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),t(s)}else setTimeout(r,100)};r()})}async releasePage(t){if(!this.busyPages.has(t)){d("\u5C1D\u8BD5\u91CA\u653E\u4E0D\u5728\u5FD9\u788C\u5217\u8868\u4E2D\u7684\u9875\u9762");return}if(t._needsRemoval){d("\u9875\u9762\u88AB\u6807\u8BB0\u4E3A\u9700\u8981\u79FB\u9664\uFF0C\u5C06\u4ECE\u6C60\u4E2D\u79FB\u9664"),await this.removePage(t);return}try{await this.cleanupPage(t),this.busyPages.delete(t),this.availablePages.push(t),d(`\u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D\uFF0C\u53EF\u7528\u9875\u9762\u6570: ${this.availablePages.length}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`)}catch(r){d(`\u6E05\u7406\u9875\u9762\u65F6\u51FA\u9519\uFF0C\u5C06\u5173\u95ED\u8BE5\u9875\u9762: ${r.message}`),await this.removePage(t)}}async cleanupPage(t){try{t.removeAllListeners();try{await t.evaluate(()=>{Object.keys(window).forEach(s=>{(s.startsWith("__handleStreamChunk")||s.startsWith("__onStreamChunk")||s.startsWith("__onStreamEnd"))&&delete window[s]}),window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor),delete window.__handleStreamChunk,delete window.__onStreamChunk,delete window.__onStreamEnd,delete window.__streamCallbacks})}catch(r){d(`\u6E05\u7406\u9875\u9762\u72B6\u6001\u65F6\u51FA\u73B0evaluate\u9519\u8BEF: ${r.message}`)}d("\u9875\u9762\u72B6\u6001\u5DF2\u6E05\u7406")}catch(r){throw new Error(`\u6E05\u7406\u9875\u9762\u5931\u8D25: ${r.message}`)}}async removePage(t){try{this.busyPages.delete(t);let r=this.availablePages.indexOf(t);r>-1&&this.availablePages.splice(r,1),await t.close(),this.totalPages--,d(`\u9875\u9762\u5DF2\u4ECE\u6C60\u4E2D\u79FB\u9664\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}`)}catch(r){d(`\u5173\u95ED\u9875\u9762\u65F6\u51FA\u9519: ${r.message}`)}}async cleanup(){d("\u5F00\u59CB\u6E05\u7406\u9875\u9762\u6C60...");for(let t of this.busyPages)try{await t.close()}catch(r){d(`\u5173\u95ED\u5FD9\u788C\u9875\u9762\u65F6\u51FA\u9519: ${r.message}`)}for(let t of this.availablePages)try{await t.close()}catch(r){d(`\u5173\u95ED\u53EF\u7528\u9875\u9762\u65F6\u51FA\u9519: ${r.message}`)}this.busyPages.clear(),this.availablePages=[],this.totalPages=0,d("\u9875\u9762\u6C60\u6E05\u7406\u5B8C\u6210")}getStatus(){return{total:this.totalPages,available:this.availablePages.length,busy:this.busyPages.size,maxSize:this.maxSize}}},x=null;async function Kr(){if(!A){A=await Wr.launch({headless:p.browser.headless,timeout:p.browser.timeout,args:p.browser.args,executablePath:p.browser.executablePath}),N=await A.newContext({userAgent:p.browser.userAgent});let e=_e(p.cookieFile,p.cookiesFromEnv);await N.addCookies(e)}return{browser:A,context:N}}function ht(e=5){return x||(x=new re(e),d(`\u9875\u9762\u6C60\u5DF2\u521D\u59CB\u5316\uFF0C\u6700\u5927\u9875\u9762\u6570: ${e}`)),x}function ft(){return x||(x=new re,d("\u9875\u9762\u6C60\u5DF2\u81EA\u52A8\u521D\u59CB\u5316\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E")),x}async function se(){let t=await ft().getPage();return await t.bringToFront(),t}async function V(e,t,r={}){let s=e.url();console.log("\u5F53\u524D\u9875\u9762URL:",s),console.log("\u76EE\u6807URL:",t);try{return s!==t?(console.log("\u9875\u9762URL\u4E0D\u5339\u914D\uFF0C\u9700\u8981\u5BFC\u822A..."),await e.goto(t,{waitUntil:"load",timeout:3e4,...r}),console.log("\u9875\u9762\u5BFC\u822A\u5B8C\u6210"),!0):(console.log("\u9875\u9762\u5DF2\u5728\u76EE\u6807URL\uFF0C\u8FDB\u884C\u5237\u65B0\u4EE5\u786E\u4FDD\u6700\u65B0\u72B6\u6001..."),await e.bringToFront(),await e.reload({waitUntil:"load",timeout:3e4,...r}),console.log("\u9875\u9762\u5237\u65B0\u5B8C\u6210"),!0)}catch{}return!1}async function z(e){await ft().releasePage(e)}function W(){return x?x.getStatus():{total:0,available:0,busy:0,maxSize:0}}async function dt(){x&&(await x.cleanup(),x=null),N&&(await N.close(),N=null),A&&(await A.close(),A=null)}async function mt(e,t={}){let{minClicks:r=1,maxClicks:s=3,minDelay:n=300,maxDelay:o=500,referenceElement:i=null}=t;try{d("\u5F00\u59CB\u6A21\u62DF\u4EBA\u7C7B\u968F\u673A\u70B9\u51FB\u884C\u4E3A...");let a=Math.floor(Math.random()*(s-r+1))+r;d(`\u5C06\u8FDB\u884C ${a} \u6B21\u968F\u673A\u70B9\u51FB`);let l=null;if(i)try{let c=await i.boundingBox();c&&(l={x:c.x-50,y:Math.max(0,c.y-200),width:c.width+50,height:300},d(`\u4F7F\u7528\u8F93\u5165\u6846\u9644\u8FD1\u7684\u5B89\u5168\u533A\u57DF: x=${l.x}, y=${l.y}, w=${l.width}, h=${l.height}`))}catch(c){d(`\u83B7\u53D6\u53C2\u8003\u5143\u7D20\u4F4D\u7F6E\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: ${c.message}`)}if(!l){let c=e.viewportSize(),u=c?.width||1280,f=c?.height||720;l={x:u*.3,y:f*.3,width:u*.4,height:f*.2},d(`\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: x=${l.x}, y=${l.y}, w=${l.width}, h=${l.height}`)}for(let c=0;c{let g=document.elementFromPoint(T.x,T.y);if(!g)return{safe:!0};let y=g.tagName.toLowerCase(),b=g.hasAttribute("href"),P=g.hasAttribute("onclick")||g.onclick,E=y==="button"||g.type==="button",w=y==="a"||b,k=["input","textarea","select"].includes(y);return{safe:!E&&!w&&!P&&!k,tagName:y,hasHref:b,hasOnClick:P,isButton:E,isLink:w,isInput:k}},{x:u,y:f});if(h.safe?(await e.mouse.move(u,f,{steps:Math.floor(Math.random()*10)+5}),await e.waitForTimeout(Math.floor(Math.random()*200)+100),await e.mouse.click(u,f),d(`\u5B89\u5168\u70B9\u51FB\u5B8C\u6210: (${u}, ${f})`)):d(`\u8DF3\u8FC7\u4E0D\u5B89\u5168\u7684\u70B9\u51FB\u4F4D\u7F6E (${u}, ${f}): ${h.tagName}`),c.5?"down":"up",m=Math.floor(Math.random()*300)+100;d(`\u6A21\u62DF\u6EDA\u52A8: ${h}, \u8DDD\u79BB: ${m}px`),await e.mouse.wheel(0,h==="down"?m:-m)}else if(u<.6&&s){let h=Math.floor(Math.random()*l),m=Math.floor(Math.random()*c);d(`\u6A21\u62DF\u9F20\u6807\u79FB\u52A8\u5230: (${h}, ${m})`),await e.mouse.move(h,m,{steps:Math.floor(Math.random()*15)+5})}else if(u<.8&&n){let h=Math.floor(Math.random()*(l*.8))+l*.1,m=Math.floor(Math.random()*(c*.8))+c*.1;d(`\u6A21\u62DF\u968F\u673A\u70B9\u51FB: (${h}, ${m})`),await e.mouse.click(h,m)}let f=Math.floor(Math.random()*800)+200;await e.waitForTimeout(f)}d("\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u6A21\u62DF\u5B8C\u6210")}catch(i){d(`\u6A21\u62DF\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u65F6\u51FA\u73B0\u9519\u8BEF: ${i.message}`)}}async function oe(e,t=5e3){try{d("\u68C0\u67E5\u662F\u5426\u6709\u6B22\u8FCE\u5BF9\u8BDD\u6846\u9700\u8981\u5173\u95ED...");let r="mat-dialog-container",s='button[mat-dialog-close][aria-label="close"]';if(await e.locator(r).first().isVisible({timeout:t})){d("\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846\uFF0C\u5C1D\u8BD5\u5173\u95ED...");let o=e.locator(s).first();return await o.isVisible({timeout:2e3})?(await o.click(),d("\u5DF2\u901A\u8FC7\u5173\u95ED\u6309\u94AE\u5173\u95ED\u6B22\u8FCE\u5BF9\u8BDD\u6846"),await e.waitForTimeout(1e3),!0):(d("\u672A\u627E\u5230\u5173\u95ED\u6309\u94AE\uFF0C\u5C1D\u8BD5\u6309ESC\u952E\u5173\u95ED\u5BF9\u8BDD\u6846"),await e.keyboard.press("Escape"),await e.waitForTimeout(1e3),!0)}else return d("\u672A\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846"),!1}catch(r){return d("\u5904\u7406\u6B22\u8FCE\u5BF9\u8BDD\u6846\u65F6\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u6267\u884C:",r.message),!1}}async function gt(e,t,r){try{d("\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u5230\u9875\u9762\u4E2D...");try{await e.evaluate(()=>{Object.keys(window).forEach(i=>{(i.startsWith("__onStreamChunk_")||i.startsWith("__onStreamEnd_"))&&delete window[i]}),delete window.__onStreamChunk,delete window.__onStreamEnd})}catch{}let s=Date.now()+"_"+Math.random().toString(36).substr(2,9),n=`__onStreamChunk_${s}`,o=`__onStreamEnd_${s}`;await e.exposeFunction(n,t),await e.exposeFunction(o,r),await e.evaluate(()=>{window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor);let i=window.XMLHttpRequest.prototype.open,a=window.XMLHttpRequest.prototype.send,l=["MakerSuiteService/GenerateContent","GenerateContent","streamGenerateContent","generateContent"],c=/\[\s*null\s*,\s*null\s*,\s*null\s*,\s*\[\s*"/,u="__END_OF_STREAM__",f=!1;window.__streamInterceptor={activate:()=>{f||(console.log("\u{1F3AF} \u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668..."),f=!0,window.XMLHttpRequest.prototype.open=function(h,m,...T){return this._url=m,this._method=h,console.log(`[XHR] \u8BF7\u6C42: ${h} ${m}`),i.apply(this,[h,m,...T])},window.XMLHttpRequest.prototype.send=function(...h){let m=this._url?this._url.toString():"",T=l.some(g=>m.includes(g));if(this._url&&T){console.log("\u{1F3AF} [XHR Stream] \u62E6\u622A\u5230\u76EE\u6807\u8BF7\u6C42:",m),console.log("\u{1F3AF} [XHR Stream] \u51C6\u5907\u63A5\u6536\u6D41\u5F0F\u6570\u636E...");let g=0,y="",b=!1,P=null,E=()=>{if(b)return;b=!0,console.log("[Stream] \u5224\u5B9A\u6D41\u5DF2\u7ED3\u675F"),clearTimeout(P);let w=y.slice(g);w&&window.__streamInterceptor.sendChunk(w),window.__streamInterceptor.sendChunk(u)};this.addEventListener("progress",()=>{if(!b)try{y=this.responseText||"";let w=y.slice(g);if(w){if(console.log(`[Stream] \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${w.length}\uFF0CHTTP\u72B6\u6001: ${this.status}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${w.substring(0,100)}...`),window.__streamInterceptor.sendChunk(w),g=y.length,this.status>=400&&this.readyState===4){console.log(`[Stream] progress\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u7ED3\u675F\u6D41`),E();return}c.test(w)&&(console.log("[Stream] \u2705 \u68C0\u6D4B\u5230\u6700\u7EC8 ID \u7B7E\u540D\u5757\uFF0C\u786E\u8BA4\u6D41\u7ED3\u675F"),E())}}catch(w){console.error("[Stream] \u5904\u7406progress\u4E8B\u4EF6\u65F6\u51FA\u9519:",w)}}),this.addEventListener("readystatechange",()=>{if(!b&&(console.log(`[Stream] readyState: ${this.readyState}, status: ${this.status}`),this.readyState===3||this.readyState===4))try{let w=this.responseText||"",k=w.slice(g);if(k&&(console.log(`[Stream] readyState ${this.readyState} \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${k.length}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${k.substring(0,200)}...`),window.__streamInterceptor.sendChunk(k),g=w.length,y=w,c.test(k)&&(console.log("[Stream] \u2705 readyState\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230\u6700\u7EC8\u7B7E\u540D"),E())),this.readyState===4&&!b)if(console.log(`[Stream] \u8BF7\u6C42\u5B8C\u6210\uFF0CHTTP\u72B6\u6001\u7801: ${this.status}`),this.status>=400){if(console.log(`[Stream] \u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u5904\u7406\u9519\u8BEF\u54CD\u5E94`),y&&y!==w){let ie=y.slice(g);ie&&(console.log(`[Stream] \u53D1\u9001\u5269\u4F59\u9519\u8BEF\u54CD\u5E94\u6570\u636E: ${ie}`),window.__streamInterceptor.sendChunk(ie))}E()}else b||(console.log("[Stream] \u6B63\u5E38\u8BF7\u6C42\u5B8C\u6210\uFF0C\u8BBE\u7F6E\u4FDD\u9669\u8BA1\u65F6\u5668"),P=setTimeout(E,1e3))}catch(w){console.error("[Stream] \u5904\u7406readystatechange\u4E8B\u4EF6\u65F6\u51FA\u9519:",w)}}),this.addEventListener("load",()=>{b||(console.log('[Stream] "load" \u4E8B\u4EF6\u89E6\u53D1\uFF0C\u542F\u52A8\u6700\u7EC8\u786E\u8BA4\u8BA1\u65F6\u5668'),P=setTimeout(E,1500))}),this.addEventListener("error",w=>{console.error("[Stream] XHR \u8BF7\u6C42\u51FA\u9519:",w),b||E()}),this.addEventListener("abort",()=>{console.log("[Stream] XHR \u8BF7\u6C42\u88AB\u4E2D\u6B62"),b||E()})}return a.apply(this,h)})},deactivate:()=>{f&&(console.log("\u{1F504} \u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668..."),window.XMLHttpRequest.prototype.open=i,window.XMLHttpRequest.prototype.send=a,f=!1)},sendChunk:h=>{try{console.log(`[Stream] \u53D1\u9001\u6570\u636E\u5757\u5230Playwright\uFF0C\u957F\u5EA6: ${h.length}`),window.__handleStreamChunk?window.__handleStreamChunk(h):console.error("[Stream] __handleStreamChunk \u51FD\u6570\u4E0D\u5B58\u5728")}catch(m){console.error("[Stream] \u53D1\u9001\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}}},window.__streamCallbacks={onChunk:null,onEnd:null},window.__handleStreamChunk=function(h){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",h.length,"\u5B57\u7B26"),h==="__END_OF_STREAM__"?window.__streamCallbacks.onEnd&&window.__streamCallbacks.onEnd():window.__streamCallbacks.onChunk&&window.__streamCallbacks.onChunk(h)}catch(m){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}},console.log("[Stream] \u62E6\u622A\u5668\u548C\u5904\u7406\u51FD\u6570\u5DF2\u521B\u5EFA\u5B8C\u6210")}),await e.evaluate(i=>{window.__streamCallbacks.onChunk=window[i],console.log("[Stream] onChunk\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",i)},n),await e.evaluate(i=>{window.__streamCallbacks.onEnd=window[i],console.log("[Stream] onEnd\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",i)},o),d("\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u6CE8\u5165\u5B8C\u6210")}catch(s){throw d(`\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u65F6\u51FA\u9519: ${s.message}`),s}}async function wt(e){try{await e.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.activate(),window.__handleStreamChunk||(console.log("[Stream] \u91CD\u65B0\u521B\u5EFA __handleStreamChunk \u51FD\u6570"),window.__handleStreamChunk=function(t){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",t.length,"\u5B57\u7B26"),t==="__END_OF_STREAM__"?window.__onStreamEnd&&window.__onStreamEnd():window.__onStreamChunk&&window.__onStreamChunk(t)}catch(r){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",r)}},console.log("[Stream] __handleStreamChunk \u51FD\u6570\u5DF2\u91CD\u65B0\u521B\u5EFA"))}),d("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u6FC0\u6D3B")}catch(t){throw d(`\u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${t.message}`),t}}async function yt(e){try{await e.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.deactivate()}),d("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u505C\u7528")}catch(t){d(`\u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${t.message}`)}}function _t(){process.on("SIGINT",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await dt(),process.exit(0)}),process.on("SIGTERM",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await dt(),process.exit(0)})}U();var bt=null;function St(e=1e4){if(bt){d("\u9875\u9762\u6C60\u76D1\u63A7\u5DF2\u5728\u8FD0\u884C\u4E2D\u3002");return}d(`\u5F00\u59CB\u76D1\u63A7\u9875\u9762\u6C60\u72B6\u6001\uFF0C\u95F4\u9694: ${e}ms`),bt=setInterval(()=>{let t=W(),r=new Date().toLocaleTimeString(),s=t.total>0?(t.busy/t.total*100).toFixed(1):0;d(`[${r}] \u9875\u9762\u6C60\u72B6\u6001: \u603B\u8BA1=${t.total}, \u53EF\u7528=${t.available}, \u5FD9\u788C=${t.busy}, \u4F7F\u7528\u7387=${s}%`)},e)}function Et(){let e=W(),t=new Date().toLocaleString(),r=e.total>0?(e.busy/e.total*100).toFixed(1):0;console.log(` ---- \u9875\u9762\u6C60\u72B6\u6001 @ ${t} --- - \u603B\u9875\u9762\u6570: ${e.total} - \u53EF\u7528\u9875\u9762\u6570: ${e.available} - \u5FD9\u788C\u9875\u9762\u6570: ${e.busy} - \u6700\u5927\u9875\u9762\u6570: ${e.maxSize} - \u4F7F\u7528\u7387: ${r}% +var Le=Object.defineProperty;var Q=(t,e)=>()=>(t&&(e=t(t=0)),e);var He=(t,e)=>{for(var o in e)Le(t,o,{get:e[o],enumerable:!0})};import W from"node:fs";function ze(){W.existsSync(I.logDir)||W.mkdirSync(I.logDir,{recursive:!0})}function Ge(...t){return t.map(e=>typeof e=="object"&&e!==null?JSON.stringify(e,null,2):String(e)).join(" ")}async function Ue(t,e){if(!I.enableFile)return;ze();let r=`[${new Date().toISOString()}] [${t}] ${e} +`;try{await W.promises.appendFile(I.logFile,r)}catch(i){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",i)}}function je(t,...e){if(!I.enableConsole)return;let o={[$.DEBUG]:console.debug,[$.INFO]:console.log,[$.WARN]:console.warn,[$.ERROR]:console.error}[t]||console.log,r=new Date().toLocaleTimeString();o(`[${r}] [${t}]`,...e)}function Z(t,...e){let o=Ge(...e);je(t,...e),Ue(t,o)}var $,I,n,T,k=Q(()=>{$={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},I={logFile:"./logs/app.log",logDir:"./logs",enableConsole:!0,enableFile:!0,logLevel:process.env.LOG_LEVEL||$.INFO};n=(...t)=>Z($.INFO,...t),T=(...t)=>Z($.ERROR,...t)});var oe={};He(oe,{checkCookieAvailability:()=>We,ensureDirectoryExists:()=>te,getHumanReadableTimestamp:()=>ee,loadCookies:()=>K,saveScreenshot:()=>X,waitForUserInput:()=>Ke});import R from"node:fs";import Be from"node:path";import qe from"node:readline";function ee(){return new Date().toISOString().replace(/T/,"_").replace(/:/g,"-").replace(/\..+/,"")}function te(t){R.existsSync(t)||(R.mkdirSync(t,{recursive:!0}),n(`\u5DF2\u521B\u5EFA\u76EE\u5F55: ${t}`))}function We(t,e){if(e)try{return JSON.parse(e),n("\u53D1\u73B0\u5E76\u9A8C\u8BC1\u4E86\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 COOKIES\u3002"),!0}catch(o){T("\u73AF\u5883\u53D8\u91CF COOKIES \u683C\u5F0F\u65E0\u6548 (\u5FC5\u987B\u662F JSON \u6570\u7EC4\u5B57\u7B26\u4E32):",o.message)}return R.existsSync(t)?(n(`\u53D1\u73B0 Cookie \u6587\u4EF6: ${t}`),!0):(T(`Cookie \u6587\u4EF6\u4E0D\u5B58\u5728: ${t}\uFF0C\u4E14\u672A\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002`),n("\u8BF7\u5148\u8FD0\u884C `npm run login` \u6216\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002"),!1)}function K(t,e){try{if(e)return n("\u4ECE\u73AF\u5883\u53D8\u91CF COOKIES \u52A0\u8F7D Cookie..."),JSON.parse(e);if(R.existsSync(t))return n(`\u4ECE\u6587\u4EF6\u52A0\u8F7D Cookie: ${t}`),JSON.parse(R.readFileSync(t,"utf8"))}catch(o){throw T("\u52A0\u8F7D Cookie \u5931\u8D25:",o),new Error("\u65E0\u6CD5\u52A0\u8F7D\u6216\u89E3\u6790 Cookie\u3002")}return[]}async function X(t,e,o="screenshot"){te(e);let r=ee(),i=Be.join(e,`${o}_${r}.png`);return await t.screenshot({path:i,fullPage:!0}),n(`\u622A\u56FE\u5DF2\u4FDD\u5B58: ${i}`),i}function Ke(){let t=qe.createInterface({input:process.stdin,output:process.stdout});return new Promise(e=>{t.question("",()=>{t.close(),e()})})}var F=Q(()=>{k()});import{H3 as ot,serve as rt,serveStatic as ke}from"h3";import{stat as Re,readFile as Ae}from"node:fs/promises";import{join as Oe}from"node:path";import{chromium as Xe}from"playwright";import De from"dotenv";De.config();var Fe={server:{port:parseInt(process.env.PORT||"3096",10),host:process.env.HOST||"localhost"},browser:{headless:(process.env.HEADLESS||"true").toLowerCase()!=="false",timeout:parseInt(process.env.TIMEOUT||"30000",10),executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,args:["--disable-blink-features=AutomationControlled","--no-sandbox","--disable-dev-shm-usage","--disable-infobars","--disable-extensions"],userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},cookieFile:"./cookies.json",cookiesFromEnv:process.env.COOKIES,screenshotDir:"./screenshots",aiStudio:{url:process.env.AI_STUDIO_URL||"https://aistudio.google.com/prompts/new_chat",responseTimeout:parseInt(process.env.RESPONSE_TIMEOUT||"600000",10),pageTimeout:parseInt(process.env.PAGE_TIMEOUT||"30000",10)},api:{defaultModel:process.env.DEFAULT_MODEL||"gemini-pro",maxTokens:65536,temperature:1,token:process.env.API_TOKEN},models:{"gemini-2.5-pro":{displayName:"Gemini 2.5 Pro",id:"gemini-2.5-pro",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-pro",parent:null},"gemini-2.5-flash":{displayName:"Gemini 2.5 Flash",id:"gemini-2.5-flash",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-flash",parent:null},"gemini-pro":{displayName:"Gemini Pro",id:"gemini-pro",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-pro",parent:null},"gemini-flash":{displayName:"Gemini Flash",id:"gemini-flash",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-flash",parent:null}},debug:{logRequests:process.env.DEBUG_REQUESTS==="true",logResponses:process.env.DEBUG_RESPONSES==="true",saveScreenshots:process.env.SAVE_SCREENSHOTS==="true"}},c=Fe;F();k();var v=null,M=null,z=class{constructor(e=5){this.maxSize=e,this.availablePages=[],this.busyPages=new Set,this.totalPages=0}async getPage(){if(this.availablePages.length>0){let e=this.availablePages.pop();return this.busyPages.add(e),n(`\u4ECE\u9875\u9762\u6C60\u83B7\u53D6\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e}if(this.totalPages{let o=()=>{if(this.availablePages.length>0){let r=this.availablePages.pop();this.busyPages.add(r),n(`\u7B49\u5F85\u540E\u83B7\u53D6\u5230\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e(r)}else setTimeout(o,100)};o()})}async releasePage(e){if(!this.busyPages.has(e)){n("\u5C1D\u8BD5\u91CA\u653E\u4E0D\u5728\u5FD9\u788C\u5217\u8868\u4E2D\u7684\u9875\u9762");return}if(e._needsRemoval){n("\u9875\u9762\u88AB\u6807\u8BB0\u4E3A\u9700\u8981\u79FB\u9664\uFF0C\u5C06\u4ECE\u6C60\u4E2D\u79FB\u9664"),await this.removePage(e);return}try{await this.cleanupPage(e),this.busyPages.delete(e),this.availablePages.push(e),n(`\u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D\uFF0C\u53EF\u7528\u9875\u9762\u6570: ${this.availablePages.length}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`)}catch(o){n(`\u6E05\u7406\u9875\u9762\u65F6\u51FA\u9519\uFF0C\u5C06\u5173\u95ED\u8BE5\u9875\u9762: ${o.message}`),await this.removePage(e)}}async cleanupPage(e){try{e.removeAllListeners();try{await e.evaluate(()=>{Object.keys(window).forEach(r=>{(r.startsWith("__handleStreamChunk")||r.startsWith("__onStreamChunk")||r.startsWith("__onStreamEnd"))&&delete window[r]}),window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor),delete window.__handleStreamChunk,delete window.__onStreamChunk,delete window.__onStreamEnd,delete window.__streamCallbacks})}catch(o){n(`\u6E05\u7406\u9875\u9762\u72B6\u6001\u65F6\u51FA\u73B0evaluate\u9519\u8BEF: ${o.message}`)}n("\u9875\u9762\u72B6\u6001\u5DF2\u6E05\u7406")}catch(o){throw new Error(`\u6E05\u7406\u9875\u9762\u5931\u8D25: ${o.message}`)}}async removePage(e){try{this.busyPages.delete(e);let o=this.availablePages.indexOf(e);o>-1&&this.availablePages.splice(o,1),await e.close(),this.totalPages--,n(`\u9875\u9762\u5DF2\u4ECE\u6C60\u4E2D\u79FB\u9664\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}`)}catch(o){n(`\u5173\u95ED\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}}async cleanup(){n("\u5F00\u59CB\u6E05\u7406\u9875\u9762\u6C60...");for(let e of this.busyPages)try{await e.close()}catch(o){n(`\u5173\u95ED\u5FD9\u788C\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}for(let e of this.availablePages)try{await e.close()}catch(o){n(`\u5173\u95ED\u53EF\u7528\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}this.busyPages.clear(),this.availablePages=[],this.totalPages=0,n("\u9875\u9762\u6C60\u6E05\u7406\u5B8C\u6210")}getStatus(){return{total:this.totalPages,available:this.availablePages.length,busy:this.busyPages.size,maxSize:this.maxSize}}},b=null;async function Je(){if(!v){v=await Xe.launch({headless:c.browser.headless,timeout:c.browser.timeout,args:c.browser.args,executablePath:c.browser.executablePath}),M=await v.newContext({userAgent:c.browser.userAgent});let t=K(c.cookieFile,c.cookiesFromEnv);await M.addCookies(t)}return{browser:v,context:M}}function ne(t=5){return b||(b=new z(t),n(`\u9875\u9762\u6C60\u5DF2\u521D\u59CB\u5316\uFF0C\u6700\u5927\u9875\u9762\u6570: ${t}`)),b}function ae(){return b||(b=new z,n("\u9875\u9762\u6C60\u5DF2\u81EA\u52A8\u521D\u59CB\u5316\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E")),b}async function G(){let e=await ae().getPage();return await e.bringToFront(),e}async function A(t,e,o={}){let r=t.url();console.log("\u5F53\u524D\u9875\u9762URL:",r),console.log("\u76EE\u6807URL:",e);try{return r!==e?(console.log("\u9875\u9762URL\u4E0D\u5339\u914D\uFF0C\u9700\u8981\u5BFC\u822A..."),await t.goto(e,{waitUntil:"load",timeout:3e4,...o}),console.log("\u9875\u9762\u5BFC\u822A\u5B8C\u6210"),!0):(console.log("\u9875\u9762\u5DF2\u5728\u76EE\u6807URL\uFF0C\u8FDB\u884C\u5237\u65B0\u4EE5\u786E\u4FDD\u6700\u65B0\u72B6\u6001..."),await t.bringToFront(),await t.reload({waitUntil:"load",timeout:3e4,...o}),console.log("\u9875\u9762\u5237\u65B0\u5B8C\u6210"),!0)}catch{}return!1}async function O(t){await ae().releasePage(t)}function N(){return b?b.getStatus():{total:0,available:0,busy:0,maxSize:0}}async function re(){b&&(await b.cleanup(),b=null),M&&(await M.close(),M=null),v&&(await v.close(),v=null)}async function se(t,e={}){let{minClicks:o=1,maxClicks:r=3,minDelay:i=300,maxDelay:a=500,referenceElement:s=null}=e;try{n("\u5F00\u59CB\u6A21\u62DF\u4EBA\u7C7B\u968F\u673A\u70B9\u51FB\u884C\u4E3A...");let h=Math.floor(Math.random()*(r-o+1))+o;n(`\u5C06\u8FDB\u884C ${h} \u6B21\u968F\u673A\u70B9\u51FB`);let d=null;if(s)try{let l=await s.boundingBox();l&&(d={x:l.x-50,y:Math.max(0,l.y-200),width:l.width+50,height:300},n(`\u4F7F\u7528\u8F93\u5165\u6846\u9644\u8FD1\u7684\u5B89\u5168\u533A\u57DF: x=${d.x}, y=${d.y}, w=${d.width}, h=${d.height}`))}catch(l){n(`\u83B7\u53D6\u53C2\u8003\u5143\u7D20\u4F4D\u7F6E\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: ${l.message}`)}if(!d){let l=t.viewportSize(),p=l?.width||1280,f=l?.height||720;d={x:p*.3,y:f*.3,width:p*.4,height:f*.2},n(`\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: x=${d.x}, y=${d.y}, w=${d.width}, h=${d.height}`)}for(let l=0;l{let w=document.elementFromPoint(C.x,C.y);if(!w)return{safe:!0};let y=w.tagName.toLowerCase(),S=w.hasAttribute("href"),E=w.hasAttribute("onclick")||w.onclick,_=y==="button"||w.type==="button",g=y==="a"||S,x=["input","textarea","select"].includes(y);return{safe:!_&&!g&&!E&&!x,tagName:y,hasHref:S,hasOnClick:E,isButton:_,isLink:g,isInput:x}},{x:p,y:f});if(u.safe?(await t.mouse.move(p,f,{steps:Math.floor(Math.random()*10)+5}),await t.waitForTimeout(Math.floor(Math.random()*200)+100),await t.mouse.click(p,f),n(`\u5B89\u5168\u70B9\u51FB\u5B8C\u6210: (${p}, ${f})`)):n(`\u8DF3\u8FC7\u4E0D\u5B89\u5168\u7684\u70B9\u51FB\u4F4D\u7F6E (${p}, ${f}): ${u.tagName}`),l.5?"down":"up",m=Math.floor(Math.random()*300)+100;n(`\u6A21\u62DF\u6EDA\u52A8: ${u}, \u8DDD\u79BB: ${m}px`),await t.mouse.wheel(0,u==="down"?m:-m)}else if(p<.6&&r){let u=Math.floor(Math.random()*d),m=Math.floor(Math.random()*l);n(`\u6A21\u62DF\u9F20\u6807\u79FB\u52A8\u5230: (${u}, ${m})`),await t.mouse.move(u,m,{steps:Math.floor(Math.random()*15)+5})}else if(p<.8&&i){let u=Math.floor(Math.random()*(d*.8))+d*.1,m=Math.floor(Math.random()*(l*.8))+l*.1;n(`\u6A21\u62DF\u968F\u673A\u70B9\u51FB: (${u}, ${m})`),await t.mouse.click(u,m)}let f=Math.floor(Math.random()*800)+200;await t.waitForTimeout(f)}n("\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u6A21\u62DF\u5B8C\u6210")}catch(s){n(`\u6A21\u62DF\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u65F6\u51FA\u73B0\u9519\u8BEF: ${s.message}`)}}async function U(t,e=5e3){try{n("\u68C0\u67E5\u662F\u5426\u6709\u6B22\u8FCE\u5BF9\u8BDD\u6846\u9700\u8981\u5173\u95ED...");let o="mat-dialog-container",r='button[mat-dialog-close][aria-label="close"]';if(await t.locator(o).first().isVisible({timeout:e})){n("\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846\uFF0C\u5C1D\u8BD5\u5173\u95ED...");let a=t.locator(r).first();return await a.isVisible({timeout:2e3})?(await a.click(),n("\u5DF2\u901A\u8FC7\u5173\u95ED\u6309\u94AE\u5173\u95ED\u6B22\u8FCE\u5BF9\u8BDD\u6846"),await t.waitForTimeout(1e3),!0):(n("\u672A\u627E\u5230\u5173\u95ED\u6309\u94AE\uFF0C\u5C1D\u8BD5\u6309ESC\u952E\u5173\u95ED\u5BF9\u8BDD\u6846"),await t.keyboard.press("Escape"),await t.waitForTimeout(1e3),!0)}else return n("\u672A\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846"),!1}catch(o){return n("\u5904\u7406\u6B22\u8FCE\u5BF9\u8BDD\u6846\u65F6\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u6267\u884C:",o.message),!1}}async function le(t,e,o){try{n("\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u5230\u9875\u9762\u4E2D...");try{await t.evaluate(()=>{Object.keys(window).forEach(s=>{(s.startsWith("__onStreamChunk_")||s.startsWith("__onStreamEnd_"))&&delete window[s]}),delete window.__onStreamChunk,delete window.__onStreamEnd})}catch{}let r=Date.now()+"_"+Math.random().toString(36).substr(2,9),i=`__onStreamChunk_${r}`,a=`__onStreamEnd_${r}`;await t.exposeFunction(i,e),await t.exposeFunction(a,o),await t.evaluate(()=>{window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor);let s=window.XMLHttpRequest.prototype.open,h=window.XMLHttpRequest.prototype.send,d=["MakerSuiteService/GenerateContent","GenerateContent","streamGenerateContent","generateContent"],l=/\[\s*null\s*,\s*null\s*,\s*null\s*,\s*\[\s*"/,p="__END_OF_STREAM__",f=!1;window.__streamInterceptor={activate:()=>{f||(console.log("\u{1F3AF} \u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668..."),f=!0,window.XMLHttpRequest.prototype.open=function(u,m,...C){return this._url=m,this._method=u,console.log(`[XHR] \u8BF7\u6C42: ${u} ${m}`),s.apply(this,[u,m,...C])},window.XMLHttpRequest.prototype.send=function(...u){let m=this._url?this._url.toString():"",C=d.some(w=>m.includes(w));if(this._url&&C){console.log("\u{1F3AF} [XHR Stream] \u62E6\u622A\u5230\u76EE\u6807\u8BF7\u6C42:",m),console.log("\u{1F3AF} [XHR Stream] \u51C6\u5907\u63A5\u6536\u6D41\u5F0F\u6570\u636E...");let w=0,y="",S=!1,E=null,_=()=>{if(S)return;S=!0,console.log("[Stream] \u5224\u5B9A\u6D41\u5DF2\u7ED3\u675F"),clearTimeout(E);let g=y.slice(w);g&&window.__streamInterceptor.sendChunk(g),window.__streamInterceptor.sendChunk(p)};this.addEventListener("progress",()=>{if(!S)try{y=this.responseText||"";let g=y.slice(w);if(g){if(console.log(`[Stream] \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${g.length}\uFF0CHTTP\u72B6\u6001: ${this.status}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${g.substring(0,100)}...`),window.__streamInterceptor.sendChunk(g),w=y.length,this.status>=400&&this.readyState===4){console.log(`[Stream] progress\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u7ED3\u675F\u6D41`),_();return}l.test(g)&&(console.log("[Stream] \u2705 \u68C0\u6D4B\u5230\u6700\u7EC8 ID \u7B7E\u540D\u5757\uFF0C\u786E\u8BA4\u6D41\u7ED3\u675F"),_())}}catch(g){console.error("[Stream] \u5904\u7406progress\u4E8B\u4EF6\u65F6\u51FA\u9519:",g)}}),this.addEventListener("readystatechange",()=>{if(!S&&(console.log(`[Stream] readyState: ${this.readyState}, status: ${this.status}`),this.readyState===3||this.readyState===4))try{let g=this.responseText||"",x=g.slice(w);if(x&&(console.log(`[Stream] readyState ${this.readyState} \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${x.length}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${x.substring(0,200)}...`),window.__streamInterceptor.sendChunk(x),w=g.length,y=g,l.test(x)&&(console.log("[Stream] \u2705 readyState\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230\u6700\u7EC8\u7B7E\u540D"),_())),this.readyState===4&&!S)if(console.log(`[Stream] \u8BF7\u6C42\u5B8C\u6210\uFF0CHTTP\u72B6\u6001\u7801: ${this.status}`),this.status>=400){if(console.log(`[Stream] \u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u5904\u7406\u9519\u8BEF\u54CD\u5E94`),y&&y!==g){let q=y.slice(w);q&&(console.log(`[Stream] \u53D1\u9001\u5269\u4F59\u9519\u8BEF\u54CD\u5E94\u6570\u636E: ${q}`),window.__streamInterceptor.sendChunk(q))}_()}else S||(console.log("[Stream] \u6B63\u5E38\u8BF7\u6C42\u5B8C\u6210\uFF0C\u8BBE\u7F6E\u4FDD\u9669\u8BA1\u65F6\u5668"),E=setTimeout(_,1e3))}catch(g){console.error("[Stream] \u5904\u7406readystatechange\u4E8B\u4EF6\u65F6\u51FA\u9519:",g)}}),this.addEventListener("load",()=>{S||(console.log('[Stream] "load" \u4E8B\u4EF6\u89E6\u53D1\uFF0C\u542F\u52A8\u6700\u7EC8\u786E\u8BA4\u8BA1\u65F6\u5668'),E=setTimeout(_,1500))}),this.addEventListener("error",g=>{console.error("[Stream] XHR \u8BF7\u6C42\u51FA\u9519:",g),S||_()}),this.addEventListener("abort",()=>{console.log("[Stream] XHR \u8BF7\u6C42\u88AB\u4E2D\u6B62"),S||_()})}return h.apply(this,u)})},deactivate:()=>{f&&(console.log("\u{1F504} \u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668..."),window.XMLHttpRequest.prototype.open=s,window.XMLHttpRequest.prototype.send=h,f=!1)},sendChunk:u=>{try{console.log(`[Stream] \u53D1\u9001\u6570\u636E\u5757\u5230Playwright\uFF0C\u957F\u5EA6: ${u.length}`),window.__handleStreamChunk?window.__handleStreamChunk(u):console.error("[Stream] __handleStreamChunk \u51FD\u6570\u4E0D\u5B58\u5728")}catch(m){console.error("[Stream] \u53D1\u9001\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}}},window.__streamCallbacks={onChunk:null,onEnd:null},window.__handleStreamChunk=function(u){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",u.length,"\u5B57\u7B26"),u==="__END_OF_STREAM__"?window.__streamCallbacks.onEnd&&window.__streamCallbacks.onEnd():window.__streamCallbacks.onChunk&&window.__streamCallbacks.onChunk(u)}catch(m){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}},console.log("[Stream] \u62E6\u622A\u5668\u548C\u5904\u7406\u51FD\u6570\u5DF2\u521B\u5EFA\u5B8C\u6210")}),await t.evaluate(s=>{window.__streamCallbacks.onChunk=window[s],console.log("[Stream] onChunk\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",s)},i),await t.evaluate(s=>{window.__streamCallbacks.onEnd=window[s],console.log("[Stream] onEnd\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",s)},a),n("\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u6CE8\u5165\u5B8C\u6210")}catch(r){throw n(`\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u65F6\u51FA\u9519: ${r.message}`),r}}async function ce(t){try{await t.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.activate(),window.__handleStreamChunk||(console.log("[Stream] \u91CD\u65B0\u521B\u5EFA __handleStreamChunk \u51FD\u6570"),window.__handleStreamChunk=function(e){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",e.length,"\u5B57\u7B26"),e==="__END_OF_STREAM__"?window.__onStreamEnd&&window.__onStreamEnd():window.__onStreamChunk&&window.__onStreamChunk(e)}catch(o){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",o)}},console.log("[Stream] __handleStreamChunk \u51FD\u6570\u5DF2\u91CD\u65B0\u521B\u5EFA"))}),n("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u6FC0\u6D3B")}catch(e){throw n(`\u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${e.message}`),e}}async function ue(t){try{await t.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.deactivate()}),n("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u505C\u7528")}catch(e){n(`\u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${e.message}`)}}function me(){process.on("SIGINT",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await re(),process.exit(0)}),process.on("SIGTERM",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await re(),process.exit(0)})}k();var de=null;function pe(t=1e4){if(de){n("\u9875\u9762\u6C60\u76D1\u63A7\u5DF2\u5728\u8FD0\u884C\u4E2D\u3002");return}n(`\u5F00\u59CB\u76D1\u63A7\u9875\u9762\u6C60\u72B6\u6001\uFF0C\u95F4\u9694: ${t}ms`),de=setInterval(()=>{let e=N(),o=new Date().toLocaleTimeString(),r=e.total>0?(e.busy/e.total*100).toFixed(1):0;n(`[${o}] \u9875\u9762\u6C60\u72B6\u6001: \u603B\u8BA1=${e.total}, \u53EF\u7528=${e.available}, \u5FD9\u788C=${e.busy}, \u4F7F\u7528\u7387=${r}%`)},t)}function he(){let t=N(),e=new Date().toLocaleString(),o=t.total>0?(t.busy/t.total*100).toFixed(1):0;console.log(` +--- \u9875\u9762\u6C60\u72B6\u6001 @ ${e} --- + \u603B\u9875\u9762\u6570: ${t.total} + \u53EF\u7528\u9875\u9762\u6570: ${t.available} + \u5FD9\u788C\u9875\u9762\u6570: ${t.busy} + \u6700\u5927\u9875\u9762\u6570: ${t.maxSize} + \u4F7F\u7528\u7387: ${o}% ------------------------------------ - `)}function xt(e){let t=e.node.res.getHeaders();if(t["access-control-allow-origin"]||e.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),t["access-control-allow-methods"]||e.node.res.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t["access-control-allow-headers"]||e.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t["access-control-max-age"]||e.node.res.setHeader("Access-Control-Max-Age","86400"),e.node.req.method==="OPTIONS")return e.node.res.statusCode=204,e.node.res.end()}function Tt(e){e.node.res.setHeader("Content-Type","text/event-stream"),e.node.res.setHeader("Cache-Control","no-cache"),e.node.res.setHeader("Connection","keep-alive"),e.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),e.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization")}function Pt(e){let t=W(),r=t.total>0?Math.round(t.busy/t.total*100):0;return{status:"ok",timestamp:new Date().toISOString(),version:process.env.npm_package_version||"1.0.0",pagePool:{...t,utilization:`${r}%`}}}function vt(e){let{messages:t,stream:r=!1,model:s=p.api.defaultModel,temperature:n=p.api.temperature}=e;if(!t||!Array.isArray(t)||t.length===0)throw S({statusCode:400,statusMessage:"Invalid request: `messages` must be a non-empty array."});return{prompt:t.map(i=>!i.role||!i.content?"":`${i.role}: ${i.content}`).join(` + `)}function fe(t){let e=t.node.res.getHeaders();if(e["access-control-allow-origin"]||t.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),e["access-control-allow-methods"]||t.node.res.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),e["access-control-allow-headers"]||t.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e["access-control-max-age"]||t.node.res.setHeader("Access-Control-Max-Age","86400"),t.node.req.method==="OPTIONS")return t.node.res.statusCode=204,t.node.res.end()}function we(t){t.node.res.setHeader("Content-Type","text/event-stream"),t.node.res.setHeader("Cache-Control","no-cache"),t.node.res.setHeader("Connection","keep-alive"),t.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),t.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization")}function ge(t){let e=N(),o=e.total>0?Math.round(e.busy/e.total*100):0;return{status:"ok",timestamp:new Date().toISOString(),version:process.env.npm_package_version||"1.0.0",pagePool:{...e,utilization:`${o}%`}}}import{readBody as et,createError as tt}from"h3";import{createError as Ve}from"h3";function ye(t){let{messages:e,stream:o=!1,model:r=c.api.defaultModel,temperature:i=c.api.temperature}=t;if(!e||!Array.isArray(e)||e.length===0)throw Ve({statusCode:400,statusMessage:"Invalid request: `messages` must be a non-empty array."});return{prompt:e.map(s=>!s.role||!s.content?"":`${s.role}: ${s.content}`).join(` -`),stream:r,model:s,temperature:n,messages:t}}function kt(e){if(!p.api.token){process.env.NODE_ENV==="production"&&console.warn("\u8B66\u544A: API_TOKEN \u672A\u5728\u751F\u4EA7\u73AF\u5883\u4E2D\u914D\u7F6E\uFF0CAPI \u5BF9\u5916\u5F00\u653E\uFF01");return}let t=e.node.req.headers.authorization;if(!t)throw S({statusCode:401,statusMessage:"Unauthorized: Missing Authorization header."});let[r,s]=t.split(" ");if(r!=="Bearer"||!s)throw S({statusCode:401,statusMessage:"Unauthorized: Invalid Authorization header format. Expected: Bearer ."});if(s!==p.api.token)throw S({statusCode:401,statusMessage:"Unauthorized: Invalid API token."})}var K=class{constructor(t,r={}){this.page=t,this.options={enableHumanSimulation:!0,...r},this.modelMapping=Object.fromEntries(Object.entries(p.models).map(([s,n])=>[s,n.displayName]))}async waitForPageLoad(){try{return await this.page.waitForSelector("body",{timeout:15e3}),await oe(this.page),!0}catch(t){return console.error("\u9875\u9762\u52A0\u8F7D\u8D85\u65F6\u6216\u5931\u8D25:",t),!1}}async findInputElement(){try{await this.page.waitForSelector("footer ms-prompt-input-wrapper",{timeout:1e4}),console.log("\u8F93\u5165\u6846\u7684\u7236\u5BB9\u5668\u5DF2\u52A0\u8F7D\u3002")}catch{console.warn("\u7B49\u5F85\u8F93\u5165\u6846\u7236\u5BB9\u5668\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u67E5\u627E...")}let t=['ms-prompt-input-wrapper textarea[aria-label*="prompt"]','textarea[placeholder="Start typing a prompt"]','textarea[aria-label="Start typing a prompt"]',"footer textarea",'textarea[placeholder*="prompt"]','textarea[aria-label*="prompt"]','div[contenteditable="true"]',"textarea"];for(let r of t)try{let s=this.page.locator(r),n=await s.count();if(n>0){console.log(`\u9009\u62E9\u5668 "${r}" \u627E\u5230\u4E86 ${n} \u4E2A\u5143\u7D20\u3002\u6B63\u5728\u68C0\u67E5\u53EF\u89C1\u6027\u548C\u53EF\u7528\u6027...`);for(let o=0;o(te(),ut));await r(this.page,p.screenshotDir,"find-input-failed")}return null}async findSendButton(){let t=['button[aria-label="Run"]',"button.run-button",'button[aria-label*="Send"]','button[data-testid*="send"]'];for(let r of t){let s=this.page.locator(r);if(await s.count()>0){let n=s.first();if(!await n.isDisabled())return n}}return console.error("\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002"),null}async fillMessage(t){let r=await this.findInputElement();if(!r)throw new Error("\u65E0\u6CD5\u627E\u5230\u8F93\u5165\u6846\u3002");try{return this.options.enableHumanSimulation&&await mt(this.page,{referenceElement:r}),await r.fill(t),await this.page.waitForTimeout(200),console.log("\u6D88\u606F\u586B\u5145\u5B8C\u6210\u3002"),!0}catch(s){return console.error("\u586B\u5145\u6D88\u606F\u5931\u8D25:",s),!1}}async waitForSendButtonEnabled(t=1e4){try{return await this.page.locator('button[aria-label="Run"]:not([disabled]), button.run-button:not([disabled])').waitFor({state:"visible",timeout:t}),console.log("\u53D1\u9001\u6309\u94AE\u5DF2\u53EF\u7528\u3002"),!0}catch{return console.warn("\u7B49\u5F85\u53D1\u9001\u6309\u94AE\u53EF\u7528\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u3002"),!1}}async sendMessage(){this.options.enableHumanSimulation&&await pt(this.page,{includeScrolling:!1,duration:1500});let t=await this.findSendButton();if(!t)throw new Error("\u65E0\u6CD5\u627E\u5230\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002");try{return await t.click(),console.log("\u6D88\u606F\u5DF2\u53D1\u9001\u3002"),!0}catch(r){console.error("\u70B9\u51FB\u53D1\u9001\u6309\u94AE\u5931\u8D25:",r);try{return console.log("\u5C1D\u8BD5\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E (Ctrl+Enter) \u53D1\u9001..."),await this.page.keyboard.press("Control+Enter"),console.log("\u5DF2\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u3002"),!0}catch(s){return console.error("\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u4E5F\u5931\u8D25:",s),!1}}}async setModel(t){try{let r=this.modelMapping[t]||t,s=this.page.locator("ms-model-selector-two-column");if(await s.count()===0)return console.log("\u672A\u627E\u5230\u6A21\u578B\u9009\u62E9\u5668\uFF0C\u8DF3\u8FC7\u6A21\u578B\u8BBE\u7F6E\u3002"),!1;if((await s.locator(".model-option-content .gmat-body-medium").textContent())?.trim()===r)return console.log("\u5F53\u524D\u5DF2\u662F\u76EE\u6807\u6A21\u578B\uFF0C\u65E0\u9700\u5207\u6362\u3002"),!0;await s.click({timeout:5e3});let o=this.page.locator(".mat-mdc-select-panel");await o.waitFor({state:"visible",timeout:5e3});let i=o.locator("mat-option.model-option",{hasText:r});return await i.count()>0?(await i.first().click({timeout:5e3}),await this.page.waitForTimeout(1e3),console.log(`\u6A21\u578B\u5DF2\u6210\u529F\u8BBE\u7F6E\u4E3A: ${r}`),!0):(console.log(`\u672A\u5728\u4E0B\u62C9\u83DC\u5355\u4E2D\u627E\u5230\u76EE\u6807\u6A21\u578B: ${r}`),await this.page.keyboard.press("Escape"),!1)}catch(r){console.error("\u8BBE\u7F6E\u6A21\u578B\u65F6\u53D1\u751F\u9519\u8BEF:",r);try{await this.page.keyboard.press("Escape")}catch{}return!1}}async setTemperature(t){try{let r=this.page.locator('[data-test-id="temperatureSliderContainer"]');if(await r.count()===0)return console.log("\u672A\u627E\u5230\u6E29\u5EA6\u8BBE\u7F6E\u5BB9\u5668\uFF0C\u8DF3\u8FC7\u3002"),!1;let s=r.locator('input[type="number"]');return await s.count()>0?(await s.fill(t.toString()),await s.dispatchEvent("change"),console.log(`\u6E29\u5EA6\u5DF2\u8BBE\u7F6E\u4E3A: ${t}`),!0):(console.log("\u672A\u627E\u5230\u6E29\u5EA6\u6570\u5B57\u8F93\u5165\u6846\uFF0C\u8DF3\u8FC7\u8BBE\u7F6E\u3002"),!1)}catch(r){return console.error("\u8BBE\u7F6E\u6E29\u5EA6\u65F6\u51FA\u9519:",r),!1}}async processMessage(t,r={}){if(console.log("\u5F00\u59CB\u5904\u7406\u6D88\u606F..."),!await this.waitForPageLoad())throw new Error("\u9875\u9762\u52A0\u8F7D\u5931\u8D25\u3002");if(r.model&&await this.setModel(r.model),r.temperature!==void 0&&await this.setTemperature(r.temperature),!await this.fillMessage(t))throw new Error("\u6D88\u606F\u586B\u5199\u5931\u8D25\u3002");if(await this.waitForSendButtonEnabled(),!await this.sendMessage())throw new Error("\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002");return console.log("\u6D88\u606F\u53D1\u9001\u6210\u529F\uFF0C\u7B49\u5F85\u7F51\u7EDC\u62E6\u622A\u83B7\u53D6\u54CD\u5E94\u3002"),!0}};function Gr(e){return e.includes("The caller does not have permission")?(console.warn("\u68C0\u6D4B\u5230\u6743\u9650\u9519\u8BEF\uFF0C\u5C06\u89E6\u53D1\u91CD\u8BD5\u673A\u5236\u3002"),{permissionError:!0,content:"\u65E0\u6743\u8BBF\u95EE AI Studio\u3002\u8BF7\u68C0\u67E5 Cookie \u6216\u767B\u5F55\u72B6\u6001\u3002"}):null}function Rt(e){let t=[];if(!e)return t;if(Array.isArray(e)){if(e.length>=2&&e[0]===null&&typeof e[1]=="string"&&e[1]&&e[1]!=="model"){let r=e.length>2?"thinking":"text";t.push({type:r,content:e[1].replace(/\\n/g,` -`).replace(/\\"/g,'"')})}for(let r of e)t.push(...Rt(r))}return t}function Se(e){let t=Gr(e);if(t)return t;try{let o=e.trim().replace(/\n/g,",").replace(/,+/g,",");o.endsWith(",")&&(o=o.slice(0,-1)),o.startsWith("[")||(o="["+o),o.endsWith("]")||(o=o+"]"),o=o.replace(/,]/g,"]").replace(/\[,/g,"[");let i=JSON.parse(o),a=Rt(i);if(a.length>0){let l=!1;return a.map(c=>(l?c.type="text":c.type==="text"&&(l=!0),c))}}catch{}let r=/\[null,\s*"((?:\\"|[^"])*)"/g,s=[],n;for(;(n=r.exec(e))!==null;)try{let o=n[1].replace(/\\n/g,` -`).replace(/\\"/g,'"');if(o&&o!=="model"){let i=o.trim().startsWith("**")?"thinking":"text";s.push({type:i,content:o})}}catch{}if(s.length>0){let o=!1;return s.map(i=>(o?i.type="text":i.type==="text"&&(o=!0),i))}return null}function Ct(e,t,r="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:r,choices:[{index:0,delta:{content:e||"",type:t||"text"},logprobs:null,finish_reason:null}]}}function Ee(e,t="gemini-pro"){return{object:"error",message:e,type:"invalid_request_error",model:t}}function Ht(e,t="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,message:{role:"assistant",content:e},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}var ne=3,Ot=1e3;function At(e){let t=e.message.toLowerCase();return["timeout","navigation failed","page crashed","target closed","element not found","is not visible","\u65E0\u6CD5\u627E\u5230","not find","cannot find"].some(s=>t.includes(s))}function Jr(e){let t=e.message.toLowerCase();return["permission","unauthorized","\u65E0\u6743\u8BBF\u95EE","cookie","\u767B\u5F55"].some(s=>t.includes(s))}async function Yr(e){console.log("\u9875\u9762\u72B6\u6001\u5F02\u5E38\u6216\u9047\u5230\u6743\u9650\u95EE\u9898\uFF0C\u5F00\u59CB\u91CD\u7F6E...");try{await e.reload({waitUntil:"networkidle",timeout:2e4}),console.log("\u9875\u9762\u5237\u65B0\u6210\u529F\u3002")}catch(t){console.warn("\u9875\u9762\u5237\u65B0\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u65B0\u5BFC\u822A:",t.message);try{await V(e,p.aiStudio.url,{timeout:p.aiStudio.pageTimeout}),console.log("\u91CD\u65B0\u5BFC\u822A\u6210\u529F\u3002")}catch(r){throw console.error("\u9875\u9762\u91CD\u7F6E\u5931\u8D25\uFF1A\u5237\u65B0\u548C\u91CD\u65B0\u5BFC\u822A\u5747\u544A\u5931\u8D25\u3002",r),new Error("Failed to reset page state.")}}}async function $t(e,t,r){let s=null,n=null;try{s=await se();for(let o=1;o<=ne;o++)try{console.log(`[\u5C1D\u8BD5 ${o}/${ne}] \u5F00\u59CB\u5904\u7406\u8BF7\u6C42...`),(o===1||!s.url().includes("aistudio.google.com"))&&await V(s,p.aiStudio.url,{timeout:p.aiStudio.pageTimeout});let i=await r(s,e,t);return await z(s),i}catch(i){if(n=i,console.warn(`[\u5C1D\u8BD5 ${o}/${ne}] \u5931\u8D25: ${i.message}`),(Jr(i)||At(i))&&osetTimeout(a,Ot));else throw console.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\u6216\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u5C06\u629B\u51FA\u5F02\u5E38\u3002"),i}}catch(o){throw console.error("\u5904\u7406 AI Studio \u8BF7\u6C42\u6700\u7EC8\u5931\u8D25:",o),s&&(At(o)&&(s._needsRemoval=!0),await z(s)),n||o}}async function It(e,t,r={}){let s=r.model||p.api.defaultModel;try{await $t(e,r,async(n,o,i)=>new Promise(async(a,l)=>{let c=!1,u="",f=new Set,h=g=>{c||(c=!0,yt(n).catch(console.error),g?l(g):a())},m=g=>{if(c)return;u+=g;let y=Se(u);if(y?.permissionError)return h(new Error(y.content));if(Array.isArray(y)&&y.length>0)for(let b of y){let P=`${b.type}::${b.content}`;b.content?.trim()&&!f.has(P)&&(t.enqueue(`data: ${JSON.stringify(Ct(b.content,b.type,s))} +`),stream:o,model:r,temperature:i,messages:e}}import{createError as J}from"h3";function Se(t){if(!c.api.token){process.env.NODE_ENV==="production"&&console.warn("\u8B66\u544A: API_TOKEN \u672A\u5728\u751F\u4EA7\u73AF\u5883\u4E2D\u914D\u7F6E\uFF0CAPI \u5BF9\u5916\u5F00\u653E\uFF01");return}let e=t.node.req.headers.authorization;if(!e)throw J({statusCode:401,statusMessage:"Unauthorized: Missing Authorization header."});let[o,r]=e.split(" ");if(o!=="Bearer"||!r)throw J({statusCode:401,statusMessage:"Unauthorized: Invalid Authorization header format. Expected: Bearer ."});if(r!==c.api.token)throw J({statusCode:401,statusMessage:"Unauthorized: Invalid API token."})}var L=class{constructor(e,o={}){this.page=e,this.options={enableHumanSimulation:!0,...o},this.modelMapping=Object.fromEntries(Object.entries(c.models).map(([r,i])=>[r,i.displayName]))}async waitForPageLoad(){try{return await this.page.waitForSelector("body",{timeout:15e3}),await U(this.page),!0}catch(e){return console.error("\u9875\u9762\u52A0\u8F7D\u8D85\u65F6\u6216\u5931\u8D25:",e),!1}}async findInputElement(){try{await this.page.waitForSelector("footer ms-prompt-input-wrapper",{timeout:1e4}),console.log("\u8F93\u5165\u6846\u7684\u7236\u5BB9\u5668\u5DF2\u52A0\u8F7D\u3002")}catch{console.warn("\u7B49\u5F85\u8F93\u5165\u6846\u7236\u5BB9\u5668\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u67E5\u627E...")}let e=['ms-prompt-input-wrapper textarea[aria-label*="prompt"]','textarea[placeholder="Start typing a prompt"]','textarea[aria-label="Start typing a prompt"]',"footer textarea",'textarea[placeholder*="prompt"]','textarea[aria-label*="prompt"]','div[contenteditable="true"]',"textarea"];for(let o of e)try{let r=this.page.locator(o),i=await r.count();if(i>0){console.log(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u4E86 ${i} \u4E2A\u5143\u7D20\u3002\u6B63\u5728\u68C0\u67E5\u53EF\u89C1\u6027\u548C\u53EF\u7528\u6027...`);for(let a=0;a(F(),oe));await o(this.page,c.screenshotDir,"find-input-failed")}return null}async findSendButton(){let e=['button[aria-label="Run"]',"button.run-button",'button[aria-label*="Send"]','button[data-testid*="send"]'];for(let o of e){let r=this.page.locator(o);if(await r.count()>0){let i=r.first();if(!await i.isDisabled())return i}}return console.error("\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002"),null}async fillMessage(e){let o=await this.findInputElement();if(!o)throw new Error("\u65E0\u6CD5\u627E\u5230\u8F93\u5165\u6846\u3002");try{return this.options.enableHumanSimulation&&await se(this.page,{referenceElement:o}),await o.fill(e),await this.page.waitForTimeout(200),console.log("\u6D88\u606F\u586B\u5145\u5B8C\u6210\u3002"),!0}catch(r){return console.error("\u586B\u5145\u6D88\u606F\u5931\u8D25:",r),!1}}async waitForSendButtonEnabled(e=1e4){try{return await this.page.locator('button[aria-label="Run"]:not([disabled]), button.run-button:not([disabled])').waitFor({state:"visible",timeout:e}),console.log("\u53D1\u9001\u6309\u94AE\u5DF2\u53EF\u7528\u3002"),!0}catch{return console.warn("\u7B49\u5F85\u53D1\u9001\u6309\u94AE\u53EF\u7528\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u3002"),!1}}async sendMessage(){this.options.enableHumanSimulation&&await ie(this.page,{includeScrolling:!1,duration:1500});let e=await this.findSendButton();if(!e)throw new Error("\u65E0\u6CD5\u627E\u5230\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002");try{return await e.click(),console.log("\u6D88\u606F\u5DF2\u53D1\u9001\u3002"),!0}catch(o){console.error("\u70B9\u51FB\u53D1\u9001\u6309\u94AE\u5931\u8D25:",o);try{return console.log("\u5C1D\u8BD5\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E (Ctrl+Enter) \u53D1\u9001..."),await this.page.keyboard.press("Control+Enter"),console.log("\u5DF2\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u3002"),!0}catch(r){return console.error("\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u4E5F\u5931\u8D25:",r),!1}}}async setModel(e){try{let o=this.modelMapping[e]||e,r=this.page.locator("ms-model-selector-two-column");if(await r.count()===0)return console.log("\u672A\u627E\u5230\u6A21\u578B\u9009\u62E9\u5668\uFF0C\u8DF3\u8FC7\u6A21\u578B\u8BBE\u7F6E\u3002"),!1;if((await r.locator(".model-option-content .gmat-body-medium").textContent())?.trim()===o)return console.log("\u5F53\u524D\u5DF2\u662F\u76EE\u6807\u6A21\u578B\uFF0C\u65E0\u9700\u5207\u6362\u3002"),!0;await r.click({timeout:5e3});let a=this.page.locator(".mat-mdc-select-panel");await a.waitFor({state:"visible",timeout:5e3});let s=a.locator("mat-option.model-option",{hasText:o});return await s.count()>0?(await s.first().click({timeout:5e3}),await this.page.waitForTimeout(1e3),console.log(`\u6A21\u578B\u5DF2\u6210\u529F\u8BBE\u7F6E\u4E3A: ${o}`),!0):(console.log(`\u672A\u5728\u4E0B\u62C9\u83DC\u5355\u4E2D\u627E\u5230\u76EE\u6807\u6A21\u578B: ${o}`),await this.page.keyboard.press("Escape"),!1)}catch(o){console.error("\u8BBE\u7F6E\u6A21\u578B\u65F6\u53D1\u751F\u9519\u8BEF:",o);try{await this.page.keyboard.press("Escape")}catch{}return!1}}async setTemperature(e){try{let o=this.page.locator('[data-test-id="temperatureSliderContainer"]');if(await o.count()===0)return console.log("\u672A\u627E\u5230\u6E29\u5EA6\u8BBE\u7F6E\u5BB9\u5668\uFF0C\u8DF3\u8FC7\u3002"),!1;let r=o.locator('input[type="number"]');return await r.count()>0?(await r.fill(e.toString()),await r.dispatchEvent("change"),console.log(`\u6E29\u5EA6\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`),!0):(console.log("\u672A\u627E\u5230\u6E29\u5EA6\u6570\u5B57\u8F93\u5165\u6846\uFF0C\u8DF3\u8FC7\u8BBE\u7F6E\u3002"),!1)}catch(o){return console.error("\u8BBE\u7F6E\u6E29\u5EA6\u65F6\u51FA\u9519:",o),!1}}async processMessage(e,o={}){if(console.log("\u5F00\u59CB\u5904\u7406\u6D88\u606F..."),!await this.waitForPageLoad())throw new Error("\u9875\u9762\u52A0\u8F7D\u5931\u8D25\u3002");if(o.model&&await this.setModel(o.model),o.temperature!==void 0&&await this.setTemperature(o.temperature),!await this.fillMessage(e))throw new Error("\u6D88\u606F\u586B\u5199\u5931\u8D25\u3002");if(await this.waitForSendButtonEnabled(),!await this.sendMessage())throw new Error("\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002");return console.log("\u6D88\u606F\u53D1\u9001\u6210\u529F\uFF0C\u7B49\u5F85\u7F51\u7EDC\u62E6\u622A\u83B7\u53D6\u54CD\u5E94\u3002"),!0}};function Ye(t){return t.includes("The caller does not have permission")?(console.warn("\u68C0\u6D4B\u5230\u6743\u9650\u9519\u8BEF\uFF0C\u5C06\u89E6\u53D1\u91CD\u8BD5\u673A\u5236\u3002"),{permissionError:!0,content:"\u65E0\u6743\u8BBF\u95EE AI Studio\u3002\u8BF7\u68C0\u67E5 Cookie \u6216\u767B\u5F55\u72B6\u6001\u3002"}):null}function _e(t){let e=[];if(!t)return e;if(Array.isArray(t)){if(t.length>=2&&t[0]===null&&typeof t[1]=="string"&&t[1]&&t[1]!=="model"){let o=t.length>2?"thinking":"text";e.push({type:o,content:t[1].replace(/\\n/g,` +`).replace(/\\"/g,'"')})}for(let o of t)e.push(..._e(o))}return e}function V(t){let e=Ye(t);if(e)return e;try{let a=t.trim().replace(/\n/g,",").replace(/,+/g,",");a.endsWith(",")&&(a=a.slice(0,-1)),a.startsWith("[")||(a="["+a),a.endsWith("]")||(a=a+"]"),a=a.replace(/,]/g,"]").replace(/\[,/g,"[");let s=JSON.parse(a),h=_e(s);if(h.length>0){let d=!1;return h.map(l=>(d?l.type="text":l.type==="text"&&(d=!0),l))}}catch{}let o=/\[null,\s*"((?:\\"|[^"])*)"/g,r=[],i;for(;(i=o.exec(t))!==null;)try{let a=i[1].replace(/\\n/g,` +`).replace(/\\"/g,'"');if(a&&a!=="model"){let s=a.trim().startsWith("**")?"thinking":"text";r.push({type:s,content:a})}}catch{}if(r.length>0){let a=!1;return r.map(s=>(a?s.type="text":s.type==="text"&&(a=!0),s))}return null}function be(t,e,o="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,delta:{content:t||"",type:e||"text"},logprobs:null,finish_reason:null}]}}function Y(t,e="gemini-pro"){return{object:"error",message:t,type:"invalid_request_error",model:e}}function Ee(t,e="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}var j=3,Ce=1e3;function xe(t){let e=t.message.toLowerCase();return["timeout","navigation failed","page crashed","target closed","element not found","is not visible","\u65E0\u6CD5\u627E\u5230","not find","cannot find"].some(r=>e.includes(r))}function Qe(t){let e=t.message.toLowerCase();return["permission","unauthorized","\u65E0\u6743\u8BBF\u95EE","cookie","\u767B\u5F55"].some(r=>e.includes(r))}async function Ze(t){console.log("\u9875\u9762\u72B6\u6001\u5F02\u5E38\u6216\u9047\u5230\u6743\u9650\u95EE\u9898\uFF0C\u5F00\u59CB\u91CD\u7F6E...");try{await t.reload({waitUntil:"networkidle",timeout:2e4}),console.log("\u9875\u9762\u5237\u65B0\u6210\u529F\u3002")}catch(e){console.warn("\u9875\u9762\u5237\u65B0\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u65B0\u5BFC\u822A:",e.message);try{await A(t,c.aiStudio.url,{timeout:c.aiStudio.pageTimeout}),console.log("\u91CD\u65B0\u5BFC\u822A\u6210\u529F\u3002")}catch(o){throw console.error("\u9875\u9762\u91CD\u7F6E\u5931\u8D25\uFF1A\u5237\u65B0\u548C\u91CD\u65B0\u5BFC\u822A\u5747\u544A\u5931\u8D25\u3002",o),new Error("Failed to reset page state.")}}}async function Pe(t,e,o){let r=null,i=null;try{r=await G();for(let a=1;a<=j;a++)try{console.log(`[\u5C1D\u8BD5 ${a}/${j}] \u5F00\u59CB\u5904\u7406\u8BF7\u6C42...`),(a===1||!r.url().includes("aistudio.google.com"))&&await A(r,c.aiStudio.url,{timeout:c.aiStudio.pageTimeout});let s=await o(r,t,e);return await O(r),s}catch(s){if(i=s,console.warn(`[\u5C1D\u8BD5 ${a}/${j}] \u5931\u8D25: ${s.message}`),(Qe(s)||xe(s))&&asetTimeout(h,Ce));else throw console.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\u6216\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u5C06\u629B\u51FA\u5F02\u5E38\u3002"),s}}catch(a){throw console.error("\u5904\u7406 AI Studio \u8BF7\u6C42\u6700\u7EC8\u5931\u8D25:",a),r&&(xe(a)&&(r._needsRemoval=!0),await O(r)),i||a}}async function $e(t,e,o={}){let r=o.model||c.api.defaultModel;try{await Pe(t,o,async(i,a,s)=>new Promise(async(h,d)=>{let l=!1,p="",f=new Set,u=w=>{l||(l=!0,ue(i).catch(console.error),w?d(w):h())},m=w=>{if(l)return;p+=w;let y=V(p);if(y?.permissionError)return u(new Error(y.content));if(Array.isArray(y)&&y.length>0)for(let S of y){let E=`${S.type}::${S.content}`;S.content?.trim()&&!f.has(E)&&(e.enqueue(`data: ${JSON.stringify(be(S.content,S.type,r))} -`),f.add(P))}},T=()=>{c||(console.log("\u6D41\u5DF2\u7ED3\u675F\uFF0C\u53D1\u9001 [DONE] \u4FE1\u53F7\u3002"),t.enqueue(`data: [DONE] +`),f.add(E))}},C=()=>{l||(console.log("\u6D41\u5DF2\u7ED3\u675F\uFF0C\u53D1\u9001 [DONE] \u4FE1\u53F7\u3002"),e.enqueue(`data: [DONE] -`),t.close(),h())};try{await gt(n,m,T),await wt(n),await new K(n).processMessage(o,i),setTimeout(()=>{c||h(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},p.aiStudio.responseTimeout)}catch(g){h(g)}}))}catch(n){if(t.desiredSize!==null)try{t.enqueue(`data: ${JSON.stringify(Ee(n.message,s))} +`),e.close(),u())};try{await le(i,m,C),await ce(i),await new L(i).processMessage(a,s),setTimeout(()=>{l||u(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},c.aiStudio.responseTimeout)}catch(w){u(w)}}))}catch(i){if(e.desiredSize!==null)try{e.enqueue(`data: ${JSON.stringify(Y(i.message,r))} -`),t.enqueue(`data: [DONE] +`),e.enqueue(`data: [DONE] -`),t.close()}catch(o){console.error("\u5173\u95ED\u6D41\u63A7\u5236\u5668\u65F6\u51FA\u9519:",o)}}}async function Nt(e,t={}){let r=t.model||p.api.defaultModel;try{return await $t(e,t,async(s,n,o)=>new Promise(async(i,a)=>{let l="",c=async u=>{if(u.url().includes("GenerateContent"))try{let f=await u.text(),h=Se(f);if(h?.permissionError)return a(new Error(h.content));Array.isArray(h)&&(l+=h.filter(m=>m.type==="text").map(m=>m.content).join("")),s.removeListener("response",c),i(Ht(l,r))}catch(f){a(f)}};s.on("response",c);try{await new K(s).processMessage(n,o),setTimeout(()=>{s.removeListener("response",c),a(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},p.aiStudio.responseTimeout)}catch(u){s.removeListener("response",c),a(u)}}))}catch(s){return Ee(s.message,r)}}async function Mt(e){try{kt(e);let t=await pe(e),{prompt:r,stream:s,model:n,temperature:o}=vt(t);return s?(Tt(e),new ReadableStream({start(a){It(r,a,{model:n,temperature:o})}})):await Nt(r,{model:n,temperature:o})}catch(t){throw console.error("\u5904\u7406\u804A\u5929\u8BF7\u6C42\u65F6\u51FA\u9519:",t),t.statusCode?t:S({statusCode:500,statusMessage:t.message||"An internal server error occurred."})}}async function qt(e){try{let t=Object.values(p.models).map(r=>({id:r.id,object:r.object,created:r.created,owned_by:r.owned_by,permission:r.permission,root:r.root,parent:r.parent}));return t.sort((r,s)=>s.created-r.created),{object:"list",data:t}}catch(t){throw console.error("\u83B7\u53D6\u6A21\u578B\u5217\u8868\u65F6\u51FA\u9519:",t),S({statusCode:500,statusMessage:"Failed to retrieve models list."})}}async function Dt(e){try{let t=e.context.params?.model;if(!t)throw S({statusCode:400,statusMessage:"Model ID is required."});let r=p.models[t];if(!r)throw S({statusCode:404,statusMessage:`Model '${t}' not found.`});return{id:r.id,object:r.object,created:r.created,owned_by:r.owned_by,permission:r.permission,root:r.root,parent:r.parent}}catch(t){throw console.error(`\u83B7\u53D6\u6A21\u578B '${e.context.params?.model}' \u4FE1\u606F\u65F6\u51FA\u9519:`,t),t.statusCode?t:S({statusCode:500,statusMessage:"Failed to retrieve model information."})}}te();U();var H=new me,Ut=process.cwd();_t();H.use("*",xt);H.get("/health",Pt);H.get("/v1/models",qt);H.get("/v1/models/:model",Dt);H.post("/v1/chat/completions",Mt);H.get("/screenshots/**",e=>{let t=e.path.substring(12),r=jt(Ut,"screenshots",t);return Z(e,{getContents:()=>Lt(r),getMeta:async()=>{let s=await Bt(r).catch(()=>{});if(s?.isFile())return{size:s.size,mtime:s.mtimeMs}}})});H.get("/**",e=>{let t=e.path==="/"?"index.html":e.path,r=jt(Ut,"public",t);return Z(e,{getContents:()=>Lt(r),getMeta:async()=>{let s=await Bt(r).catch(()=>{});if(s?.isFile())return{size:s.size,mtime:s.mtimeMs}}})});d("\u{1F527} \u521D\u59CB\u5316\u9875\u9762\u6C60...");ht(5);process.env.NODE_ENV!=="production"&&(d("\u{1F4CA} \u542F\u52A8\u9875\u9762\u6C60\u76D1\u63A7..."),St(1e4));var G=p.server.port,J=p.server.host;Ze(H,{port:G,host:J});d(`\u{1F680} \u670D\u52A1\u5668\u8FD0\u884C\u5728 http://${J}:${G}`);d(`\u{1F3E0} \u7BA1\u7406\u9762\u677F: http://${J}:${G}/`);d(`\u{1F4CB} \u5065\u5EB7\u68C0\u67E5: http://${J}:${G}/health`);d(`\u{1F4AC} \u804A\u5929\u7AEF\u70B9: http://${J}:${G}/v1/chat/completions`);d(`\u{1F3AF} AI Studio URL: ${p.aiStudio.url}`);d(`\u{1F30D} \u73AF\u5883: ${process.env.NODE_ENV||"development"}`);async function Xr(){let e;try{d("\u{1F4F8} \u5F00\u59CB\u83B7\u53D6AI Studio\u9875\u9762\u622A\u56FE..."),e=await se(),d(`\u{1F310} \u667A\u80FD\u5BFC\u822A\u5230: ${p.aiStudio.url}`),await V(e,p.aiStudio.url,{timeout:p.aiStudio.pageTimeout}),await oe(e),await e.waitForTimeout(2e3);let t=await be(e,"./screenshots","aistudio-startup");d(`\u2705 AI Studio\u622A\u56FE\u5DF2\u4FDD\u5B58: ${t}`)}catch(t){I("\u274C \u622A\u56FEAI Studio\u9875\u9762\u65F6\u51FA\u9519:",t.message)}finally{e&&(await z(e),d("\u{1F504} \u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D"))}}setTimeout(()=>{d(` -\u{1F4CA} \u521D\u59CB\u9875\u9762\u6C60\u72B6\u6001:`),Et()},1e3);setTimeout(()=>{Xr()},2e3); +`),e.close()}catch(a){console.error("\u5173\u95ED\u6D41\u63A7\u5236\u5668\u65F6\u51FA\u9519:",a)}}}async function ve(t,e={}){let o=e.model||c.api.defaultModel;try{return await Pe(t,e,async(r,i,a)=>new Promise(async(s,h)=>{let d="",l=async p=>{if(p.url().includes("GenerateContent"))try{let f=await p.text(),u=V(f);if(u?.permissionError)return h(new Error(u.content));Array.isArray(u)&&(d+=u.filter(m=>m.type==="text").map(m=>m.content).join("")),r.removeListener("response",l),s(Ee(d,o))}catch(f){h(f)}};r.on("response",l);try{await new L(r).processMessage(i,a),setTimeout(()=>{r.removeListener("response",l),h(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},c.aiStudio.responseTimeout)}catch(p){r.removeListener("response",l),h(p)}}))}catch(r){return Y(r.message,o)}}async function Te(t){try{Se(t);let e=await et(t),{prompt:o,stream:r,model:i,temperature:a}=ye(e);return r?(we(t),new ReadableStream({start(h){$e(o,h,{model:i,temperature:a})}})):await ve(o,{model:i,temperature:a})}catch(e){throw console.error("\u5904\u7406\u804A\u5929\u8BF7\u6C42\u65F6\u51FA\u9519:",e),e.statusCode?e:tt({statusCode:500,statusMessage:e.message||"An internal server error occurred."})}}import{createError as B}from"h3";async function Me(t){try{let e=Object.values(c.models).map(o=>({id:o.id,object:o.object,created:o.created,owned_by:o.owned_by,permission:o.permission,root:o.root,parent:o.parent}));return e.sort((o,r)=>r.created-o.created),{object:"list",data:e}}catch(e){throw console.error("\u83B7\u53D6\u6A21\u578B\u5217\u8868\u65F6\u51FA\u9519:",e),B({statusCode:500,statusMessage:"Failed to retrieve models list."})}}async function Ie(t){try{let e=t.context.params?.model;if(!e)throw B({statusCode:400,statusMessage:"Model ID is required."});let o=c.models[e];if(!o)throw B({statusCode:404,statusMessage:`Model '${e}' not found.`});return{id:o.id,object:o.object,created:o.created,owned_by:o.owned_by,permission:o.permission,root:o.root,parent:o.parent}}catch(e){throw console.error(`\u83B7\u53D6\u6A21\u578B '${t.context.params?.model}' \u4FE1\u606F\u65F6\u51FA\u9519:`,e),e.statusCode?e:B({statusCode:500,statusMessage:"Failed to retrieve model information."})}}F();k();var P=new ot,Ne=process.cwd();me();P.use("*",fe);P.get("/health",ge);P.get("/v1/models",Me);P.get("/v1/models/:model",Ie);P.post("/v1/chat/completions",Te);P.get("/screenshots/**",t=>{let e=t.path.substring(12),o=Oe(Ne,"screenshots",e);return ke(t,{getContents:()=>Ae(o),getMeta:async()=>{let r=await Re(o).catch(()=>{});if(r?.isFile())return{size:r.size,mtime:r.mtimeMs}}})});P.get("/**",t=>{let e=t.path==="/"?"index.html":t.path,o=Oe(Ne,"public",e);return ke(t,{getContents:()=>Ae(o),getMeta:async()=>{let r=await Re(o).catch(()=>{});if(r?.isFile())return{size:r.size,mtime:r.mtimeMs}}})});n("\u{1F527} \u521D\u59CB\u5316\u9875\u9762\u6C60...");ne(5);process.env.NODE_ENV!=="production"&&(n("\u{1F4CA} \u542F\u52A8\u9875\u9762\u6C60\u76D1\u63A7..."),pe(1e4));var H=c.server.port,D=c.server.host;rt(P,{port:H,host:D});n(`\u{1F680} \u670D\u52A1\u5668\u8FD0\u884C\u5728 http://${D}:${H}`);n(`\u{1F3E0} \u7BA1\u7406\u9762\u677F: http://${D}:${H}/`);n(`\u{1F4CB} \u5065\u5EB7\u68C0\u67E5: http://${D}:${H}/health`);n(`\u{1F4AC} \u804A\u5929\u7AEF\u70B9: http://${D}:${H}/v1/chat/completions`);n(`\u{1F3AF} AI Studio URL: ${c.aiStudio.url}`);n(`\u{1F30D} \u73AF\u5883: ${process.env.NODE_ENV||"development"}`);async function nt(){let t;try{n("\u{1F4F8} \u5F00\u59CB\u83B7\u53D6AI Studio\u9875\u9762\u622A\u56FE..."),t=await G(),n(`\u{1F310} \u667A\u80FD\u5BFC\u822A\u5230: ${c.aiStudio.url}`),await A(t,c.aiStudio.url,{timeout:c.aiStudio.pageTimeout}),await U(t),await t.waitForTimeout(2e3);let e=await X(t,"./screenshots","aistudio-startup");n(`\u2705 AI Studio\u622A\u56FE\u5DF2\u4FDD\u5B58: ${e}`)}catch(e){T("\u274C \u622A\u56FEAI Studio\u9875\u9762\u65F6\u51FA\u9519:",e.message)}finally{t&&(await O(t),n("\u{1F504} \u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D"))}}setTimeout(()=>{n(` +\u{1F4CA} \u521D\u59CB\u9875\u9762\u6C60\u72B6\u6001:`),he()},1e3);setTimeout(()=>{nt()},2e3);