deepv-code 1.0.308 → 1.0.309
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/dvcode.js +5 -5
- package/package.json +1 -1
package/bundle/dvcode.js
CHANGED
|
@@ -534,7 +534,7 @@ ${h}`)}return e}),r0e=pIr(MFt);v0e=class extends g0e{create(t,r){var a;let{api_v
|
|
|
534
534
|
`):[]}};xB.NEWLINE_CHARS=new Set([`
|
|
535
535
|
`,"\r"]);xB.NEWLINE_REGEXP=/\r\n|[\n\r]/g;N0e={off:0,error:200,warn:300,info:400,debug:500},LFt=(n,t,r)=>{if(n){if(Kur(N0e,n))return n;kb(r).warn(`${t} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(N0e))}`)}};gIr={error:aK,warn:aK,info:aK,debug:aK},SFt=new WeakMap;mQ=n=>(n.options&&(n.options=Object.assign({},n.options),delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([t,r])=>[t,t.toLowerCase()==="x-goog-api-key"||t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);jHe=class n{constructor(t,r,a){this.iterator=t,this.controller=r,this.client=a}static fromSSEResponse(t,r,a){let i=!1,s=a?kb(a):console;function e(){return RB(this,arguments,function*(){var u,d,I,h;if(i)throw new rf("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{try{for(var G=!0,F=pQ(vIr(t,r)),W;W=yield tu(F.next()),u=W.done,!u;G=!0){h=W.value,G=!1;let R=h;if(!c)if(R.data.startsWith("[DONE]")){c=!0;continue}else try{yield yield tu(JSON.parse(R.data))}catch(y){throw s.error("Could not parse message into JSON:",R.data),s.error("From chunk:",R.raw),y}}}catch(R){d={error:R}}finally{try{!G&&!u&&(I=F.return)&&(yield tu(I.call(F)))}finally{if(d)throw d.error}}c=!0}catch(R){if(MHe(R))return yield tu(void 0);throw R}finally{c||r.abort()}})}return new n(e,r,a)}static fromReadableStream(t,r,a){let i=!1;function s(){return RB(this,arguments,function*(){var u,d,I,h;let c=new xB,G=DFt(t);try{for(var F=!0,W=pQ(G),R;R=yield tu(W.next()),u=R.done,!u;F=!0){h=R.value,F=!1;let y=h;for(let w of c.decode(y))yield yield tu(w)}}catch(y){d={error:y}}finally{try{!F&&!u&&(I=W.return)&&(yield tu(I.call(W)))}finally{if(d)throw d.error}}for(let y of c.flush())yield yield tu(y)})}function e(){return RB(this,arguments,function*(){var u,d,I,h;if(i)throw new rf("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{try{for(var G=!0,F=pQ(s()),W;W=yield tu(F.next()),u=W.done,!u;G=!0){h=W.value,G=!1;let R=h;c||R&&(yield yield tu(JSON.parse(R)))}}catch(R){d={error:R}}finally{try{!G&&!u&&(I=F.return)&&(yield tu(I.call(F)))}finally{if(d)throw d.error}}c=!0}catch(R){if(MHe(R))return yield tu(void 0);throw R}finally{c||r.abort()}})}return new n(e,r,a)}[Symbol.asyncIterator](){return this.iterator()}tee(){let t=[],r=[],a=this.iterator(),i=s=>({next:()=>{if(s.length===0){let e=a.next();t.push(e),r.push(e)}return s.shift()}});return[new n(()=>i(t),this.controller,this.client),new n(()=>i(r),this.controller,this.client)]}toReadableStream(){let t=this,r;return TFt({async start(){r=t[Symbol.asyncIterator]()},async pull(a){try{let{value:i,done:s}=await r.next();if(s)return a.close();let e=eXe(JSON.stringify(i)+`
|
|
536
536
|
`);a.enqueue(e)}catch(i){a.error(i)}},async cancel(){var a;await((a=r.return)===null||a===void 0?void 0:a.call(r))}})}};KHe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
537
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,a,i]=NIr(t,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};qHe=class n extends Promise{constructor(t,r,a=AIr){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=a,this.client=t}_thenUnwrap(t){return new n(this.client,this.responsePromise,async(r,a)=>t(await this.parseResponse(r,a),a))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(this.client,t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};zFt=Symbol("brand.privateNullableHeaders");rK=n=>{let t=new Headers,r=new Set;for(let a of n){let i=new Set;for(let[s,e]of WIr(a)){let o=s.toLowerCase();i.has(o)||(t.delete(s),i.add(o)),e===null?(t.delete(s),r.add(o)):(t.append(s,e),r.delete(o))}}return{[zFt]:!0,values:t,nulls:r}};UHe=n=>{var t,r,a,i,s,e;if(typeof globalThis.process<"u")return(a=(r=(t=globalThis.process.env)===null||t===void 0?void 0:t[n])===null||r===void 0?void 0:r.trim())!==null&&a!==void 0?a:void 0;if(typeof globalThis.Deno<"u")return(e=(s=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||s===void 0?void 0:s.call(i,n))===null||e===void 0?void 0:e.trim()};A0e=class n{constructor(t){var r,a,i,s,e,o,u,{baseURL:d=UHe("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:I=(r=UHe("GEMINI_API_KEY"))!==null&&r!==void 0?r:null,apiVersion:h="v1beta"}=t,c=o0e(t,["baseURL","apiKey","apiVersion"]);let G=Object.assign(Object.assign({apiKey:I,apiVersion:h},c),{baseURL:d||"https://generativelanguage.googleapis.com"});this.baseURL=G.baseURL,this.timeout=(a=G.timeout)!==null&&a!==void 0?a:n.DEFAULT_TIMEOUT,this.logger=(i=G.logger)!==null&&i!==void 0?i:console;let F="warn";this.logLevel=F,this.logLevel=(e=(s=LFt(G.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:LFt(UHe("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&e!==void 0?e:F,this.fetchOptions=G.fetchOptions,this.maxRetries=(o=G.maxRetries)!==null&&o!==void 0?o:2,this.fetch=(u=G.fetch)!==null&&u!==void 0?u:iIr(),this.encoder=oIr,this._options=G,this.apiKey=I,this.apiVersion=h,this.clientAdapter=G.clientAdapter}withOptions(t){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),t))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){if(!(t.has("authorization")||t.has("x-goog-api-key"))&&!(this.apiKey&&t.get("x-goog-api-key"))&&!r.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(t){let r=rK([t.headers]);if(!(r.values.has("authorization")||r.values.has("x-goog-api-key"))){if(this.apiKey)return rK([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return rK([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(t){return Object.entries(t).filter(([r,a])=>typeof a<"u").map(([r,a])=>{if(typeof a=="string"||typeof a=="number"||typeof a=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(a)}`;if(a===null)return`${encodeURIComponent(r)}=`;throw new rf(`Cannot stringify type ${typeof a}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${EB}`}defaultIdempotencyKey(){return`stainless-node-retry-${Uur()}`}makeStatusError(t,r,a,i){return af.generate(t,r,a,i)}buildURL(t,r,a){let i=!this.baseURLOverridden()&&a||this.baseURL,s=zur(t)?new URL(t):new URL(i+(i.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),e=this.defaultQuery();return jur(e)||(r=Object.assign(Object.assign({},e),r)),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(t){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!t.path.startsWith(`/${this.apiVersion}/projects/`)){let r=t.path.slice(this.apiVersion.length+1);t.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${r}`}}async prepareRequest(t,{url:r,options:a}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,a){return this.request(Promise.resolve(a).then(i=>Object.assign({method:t,path:r},i)))}request(t,r=null){return new qHe(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,a){var i,s,e;let o=await t,u=(i=o.maxRetries)!==null&&i!==void 0?i:this.maxRetries;r==null&&(r=u),await this.prepareOptions(o);let{req:d,url:I,timeout:h}=await this.buildRequest(o,{retryCount:u-r});await this.prepareRequest(d,{url:I,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),G=a===void 0?"":`, retryOf: ${a}`,F=Date.now();if(kb(this).debug(`[${c}] sending request`,mQ({retryOfRequestLogID:a,method:o.method,url:I,options:o,headers:d.headers})),!((s=o.signal)===null||s===void 0)&&s.aborted)throw new iK;let W=new AbortController,R=await this.fetchWithTimeout(I,d,h,W).catch(zHe),y=Date.now();if(R instanceof globalThis.Error){let A=`retrying, ${r} attempts remaining`;if(!((e=o.signal)===null||e===void 0)&&e.aborted)throw new iK;let E=MHe(R)||/timed? ?out/i.test(String(R)+("cause"in R?String(R.cause):""));if(r)return kb(this).info(`[${c}] connection ${E?"timed out":"failed"} - ${A}`),kb(this).debug(`[${c}] connection ${E?"timed out":"failed"} (${A})`,mQ({retryOfRequestLogID:a,url:I,durationMs:y-F,message:R.message})),this.retryRequest(o,r,a??c);throw kb(this).info(`[${c}] connection ${E?"timed out":"failed"} - error; no more retries left`),kb(this).debug(`[${c}] connection ${E?"timed out":"failed"} (error; no more retries left)`,mQ({retryOfRequestLogID:a,url:I,durationMs:y-F,message:R.message})),E?new u0e:new YB({cause:R})}let w=`[${c}${G}] ${d.method} ${I} ${R.ok?"succeeded":"failed"} with status ${R.status} in ${y-F}ms`;if(!R.ok){let A=await this.shouldRetry(R);if(r&&A){let m=`retrying, ${r} attempts remaining`;return await sIr(R.body),kb(this).info(`${w} - ${m}`),kb(this).debug(`[${c}] response error (${m})`,mQ({retryOfRequestLogID:a,url:R.url,status:R.status,headers:R.headers,durationMs:y-F})),this.retryRequest(o,r,a??c,R.headers)}let E=A?"error; no more retries left":"error; not retryable";kb(this).info(`${w} - ${E}`);let f=await R.text().catch(m=>zHe(m).message),g=$ur(f),v=g?void 0:f;throw kb(this).debug(`[${c}] response error (${E})`,mQ({retryOfRequestLogID:a,url:R.url,status:R.status,headers:R.headers,message:v,durationMs:Date.now()-F})),this.makeStatusError(R.status,g,v,R.headers)}return kb(this).info(w),kb(this).debug(`[${c}] response start`,mQ({retryOfRequestLogID:a,url:R.url,status:R.status,headers:R.headers,durationMs:y-F})),{response:R,options:o,controller:W,requestLogID:c,retryOfRequestLogID:a,startTime:F}}async fetchWithTimeout(t,r,a,i){let s=r||{},{signal:e,method:o}=s,u=o0e(s,["signal","method"]);e&&e.addEventListener("abort",()=>i.abort());let d=setTimeout(()=>i.abort(),a),I=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body=="object"&&u.body!==null&&Symbol.asyncIterator in u.body,h=Object.assign(Object.assign(Object.assign({signal:i.signal},I?{duplex:"half"}:{}),{method:"GET"}),u);o&&(h.method=o.toUpperCase());try{return await this.fetch.call(void 0,t,h)}finally{clearTimeout(d)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,a,i){var s;let e,o=i?.get("retry-after-ms");if(o){let d=parseFloat(o);Number.isNaN(d)||(e=d)}let u=i?.get("retry-after");if(u&&!e){let d=parseFloat(u);Number.isNaN(d)?e=Date.parse(u)-Date.now():e=d*1e3}if(!(e&&0<=e&&e<60*1e3)){let d=(s=t.maxRetries)!==null&&s!==void 0?s:this.maxRetries;e=this.calculateDefaultRetryTimeoutMillis(r,d)}return await eIr(e),this.makeRequest(t,r-1,a)}calculateDefaultRetryTimeoutMillis(t,r){let s=r-t,e=Math.min(.5*Math.pow(2,s),8),o=1-Math.random()*.25;return e*o*1e3}async buildRequest(t,{retryCount:r=0}={}){var a,i,s;let e=Object.assign({},t),{method:o,path:u,query:d,defaultBaseURL:I}=e,h=this.buildURL(u,d,I);"timeout"in e&&qur("timeout",e.timeout),e.timeout=(a=e.timeout)!==null&&a!==void 0?a:this.timeout;let{bodyHeaders:c,body:G}=this.buildBody({options:e}),F=await this.buildHeaders({options:t,method:o,bodyHeaders:c,retryCount:r});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:o,headers:F},e.signal&&{signal:e.signal}),globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"}),G&&{body:G}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(s=e.fetchOptions)!==null&&s!==void 0?s:{}),url:h,timeout:e.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:a,retryCount:i}){let s={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=t.idempotencyKey);let e=await this.authHeaders(t),o=rK([s,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{}),aIr()),this._options.defaultHeaders,a,t.headers,e]);return this.validateHeaders(o),o.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let a=rK([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&a.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:lIr(t)}:this.encoder({body:t,headers:a})}};A0e.DEFAULT_TIMEOUT=6e4;G0=class extends A0e{constructor(){super(...arguments),this.interactions=new Z0e(this)}};_Ft=G0;G0.GeminiNextGenAPIClient=_Ft;G0.GeminiNextGenAPIClientError=rf;G0.APIError=af;G0.APIConnectionError=YB;G0.APIConnectionTimeoutError=u0e;G0.APIUserAbortError=iK;G0.NotFoundError=m0e;G0.ConflictError=p0e;G0.RateLimitError=f0e;G0.BadRequestError=I0e;G0.AuthenticationError=d0e;G0.InternalServerError=G0e;G0.PermissionDeniedError=h0e;G0.UnprocessableEntityError=b0e;G0.toFile=hIr;G0.Interactions=Z0e;Usi=1024*1024*8;});function yIr(n,t){return{...n,...t}}function PFt(n){let{prompt_id:t,...r}=n;return r}function bQ(n){return Array.isArray(n)?n.map(PFt):n}var W0e=ut(()=>{"use strict";wi();});var jFt={};Lo(jFt,{DEFAULT_PROXY_CONFIG:()=>RIr,getActiveProxyServerUrl:()=>FW,getAvailableProxyServers:()=>FIr,getProxyServerInfo:()=>EIr,getProxyServers:()=>lK,hasAvailableProxyServer:()=>tXe});function lK(){return[{url:"https://api-code.deepvlab.ai",name:"Primary Development Server",region:"default",status:"active"}]}function FW(){let t=lK().find(r=>r.status==="active");if(!t)throw new Error("No active proxy server available. Please contact support.");return t.url}function FIr(){return lK().filter(t=>t.status==="active")}function tXe(){return lK().some(t=>t.status==="active")}function EIr(n){return lK().find(r=>r.url===n)}var RIr,VB=ut(()=>{"use strict";RIr={serverUrl:FW(),timeout:2e5,retryAttempts:3,retryDelay:1e3}});import*as xc from"fs";import*as QN from"path";import*as fQ from"os";function wIr(n){Io.configure(n)}function CIr(n){Io.setUserInfo(n)}function YIr(n){Io.setCliVersion(n)}async function xIr(){return await Io.getUserHeaders()}function VIr(){return Io.getStatus()}var sK,xs,Io,fw=ut(()=>{"use strict";VB();sK=259200,xs=class n{static instance=null;config;userInfo=null;jwtTokenData=null;usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()};userInfoFilePath;jwtTokenFilePath;usageStatsFilePath;refreshPromise=null;cliVersion="unknown";periodicStatusCheckIntervalId=null;onLoginSuccessCallbacks=[];getCliVersion(){return this.cliVersion}getUserAgent(){let t=this.cliVersion,r=process.platform,a=process.arch;return t.startsWith("VSCode-")?`DeepVCode/VSCode/${t.replace("VSCode-","")} (${r}; ${a})`:`DeepVCode/CLI/${t} (${r}; ${a})`}formatTimeRemaining(t){if(t<=0)return"\u5DF2\u8FC7\u671F";let r=Math.floor(t/1e3),a=Math.floor(r/(24*3600)),i=Math.floor(r%(24*3600)/3600),s=Math.floor(r%3600/60),e=r%60;return a>0?`${a}\u5929${i}\u5C0F\u65F6${s}\u5206\u949F`:i>0?`${i}\u5C0F\u65F6${s}\u5206\u949F${e}\u79D2`:s>0?`${s}\u5206\u949F${e}\u79D2`:`${e}\u79D2`}formatAbsoluteTime(t){return new Date(t).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}constructor(){"https://api-code.deepvlab.ai"?.includes("localhost")?(this.userInfoFilePath=QN.join(fQ.homedir(),".deepv","user-info-dev.json"),this.jwtTokenFilePath=QN.join(fQ.homedir(),".deepv","jwt-token-dev.json"),this.usageStatsFilePath=QN.join(fQ.homedir(),".deepv","usage-stats-dev.json")):(this.userInfoFilePath=QN.join(fQ.homedir(),".deepv","user-info.json"),this.jwtTokenFilePath=QN.join(fQ.homedir(),".deepv","jwt-token.json"),this.usageStatsFilePath=QN.join(fQ.homedir(),".deepv","usage-stats.json")),this.cliVersion="1.0.308",this.config={proxyServerUrl:FW()},this.loadUserInfo(),this.loadJwtToken(),this.loadUsageStats(),this.startPeriodicStatusCheck()}startPeriodicStatusCheck(){this.periodicStatusCheckIntervalId=setInterval(()=>{if(this.jwtTokenData){let t=Date.now(),r=this.jwtTokenData.expiresAt-t,a=this.formatTimeRemaining(r),i=this.formatAbsoluteTime(this.jwtTokenData.expiresAt);if(r>0){let s=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-sK*1e3);console.log(`[Login Check] \u{1F4CA} Periodic status check - Credential remaining: ${a} (until ${i}), next renewal: ${s}`)}else console.log(`[Login Check] \u26A0\uFE0F Periodic status check - Credential expired at: ${i}`)}},600*1e3)}static getInstance(){return n.instance||(n.instance=new n),n.instance}loadUserInfo(){try{if(xc.existsSync(this.userInfoFilePath)){let t=xc.readFileSync(this.userInfoFilePath,"utf8");this.userInfo=JSON.parse(t);let r=a=>{if(!a||!a.includes("@"))return a;let[i,s]=a.split("@");return i.length<=2?a:`${i[0]+"*".repeat(i.length-2)+i[i.length-1]}@${s}`}}}catch(t){console.warn("[Login Check] Failed to load user info from local file:",t),this.userInfo=null}}saveUserInfo(){try{let t=QN.dirname(this.userInfoFilePath);xc.existsSync(t)||xc.mkdirSync(t,{recursive:!0}),xc.writeFileSync(this.userInfoFilePath,JSON.stringify(this.userInfo,null,2)),console.log("[Login Check] User info saved to local file")}catch(t){console.error("[Login Check] Failed to save user info:",t)}}loadJwtToken(){try{if(xc.existsSync(this.jwtTokenFilePath)){let t=xc.readFileSync(this.jwtTokenFilePath,"utf8");this.jwtTokenData=JSON.parse(t);let r=Date.now();this.isTokenExpired()?this.jwtTokenData=null:this.isTokenNearExpiry(300)&&console.log("\u26A0\uFE0F Access credential expiring soon, auto-renewal in progress")}else console.log("[Login Check] No stored access credential found, authentication required")}catch(t){console.warn("[Login Check] Failed to load access credential from local file:",t),this.jwtTokenData=null}}saveJwtToken(){try{if(!this.jwtTokenData)return;let t=QN.dirname(this.jwtTokenFilePath);xc.existsSync(t)||xc.mkdirSync(t,{recursive:!0}),xc.writeFileSync(this.jwtTokenFilePath,JSON.stringify(this.jwtTokenData,null,2)),console.log("[Login Check] Access credential data saved to local file")}catch(t){console.error("[Login Check] Failed to save access credential:",t)}}loadUsageStats(){try{if(xc.existsSync(this.usageStatsFilePath)){let t=xc.readFileSync(this.usageStatsFilePath,"utf8");this.usageStats=JSON.parse(t)}}catch(t){console.warn("[Login Check] Failed to load usage stats from local file:",t),this.usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()}}}saveUsageStats(){try{let t=QN.dirname(this.usageStatsFilePath);xc.existsSync(t)||xc.mkdirSync(t,{recursive:!0}),xc.writeFileSync(this.usageStatsFilePath,JSON.stringify(this.usageStats,null,2)),console.log("[Login Check] Usage stats saved to local file")}catch(t){console.error("[Login Check] Failed to save usage stats:",t)}}updateUsageStats(t){t<=0||(this.usageStats.totalCreditsConsumed+=t,this.usageStats.lastUpdated=new Date().toISOString(),this.saveUsageStats(),console.log(`[Usage Stats] Updated total credits consumed: ${this.usageStats.totalCreditsConsumed} (+${t})`))}getUsageStats(){return{...this.usageStats}}checkStartupTokenStatus(){return this.jwtTokenData?{hasToken:!0,isExpired:Date.now()>=this.jwtTokenData.expiresAt,expiresAt:this.jwtTokenData.expiresAt,hasRefreshToken:!!this.jwtTokenData.refreshToken}:{hasToken:!1,isExpired:!0,expiresAt:null,hasRefreshToken:!1}}configure(t){this.config={...this.config,...t},t.userInfo&&(this.userInfo=t.userInfo,this.saveUserInfo(),console.log(`[Login Check] User info configured: ${t.userInfo.name}`)),t.proxyServerUrl&&console.log(`[Login Check] Proxy server URL: ${t.proxyServerUrl}`),t.cliVersion&&(this.cliVersion=t.cliVersion,console.log(`[Login Check] CLI version set: ${t.cliVersion}`))}setUserInfo(t){this.userInfo=t,this.saveUserInfo(),console.log(`[Login Check] User info updated: ${t.name} (${t.email||t.openId||"N/A"})`),this.triggerLoginSuccessCallbacks()}onLoginSuccess(t){this.onLoginSuccessCallbacks.push(t)}triggerLoginSuccessCallbacks(){this.onLoginSuccessCallbacks.forEach(t=>{try{t()}catch(r){console.error("[ProxyAuthManager] Error in login success callback:",r)}})}setCliVersion(t){this.cliVersion=t,console.log(`[Login Check] CLI version updated: ${t}`)}setJwtToken(t){let r=Date.now();this.jwtTokenData={accessToken:t,expiresIn:900,expiresAt:r+900*1e3,savedAt:new Date().toISOString()},this.saveJwtToken(),console.log("[Login Check] Access credential updated")}setJwtTokenData(t){let a=Date.now()+t.expiresIn*1e3;this.jwtTokenData={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn,expiresAt:a,savedAt:new Date().toISOString()},this.saveJwtToken();let i=this.formatTimeRemaining(t.expiresIn*1e3),s=this.formatAbsoluteTime(a),e=this.formatAbsoluteTime(a-sK*1e3),u=!!t.refreshToken?", will auto-renew":", manual login required";console.log(`[Login Check] Access credential updated - valid for: ${i} (until ${s}), next renewal: ${e}${u}`)}async getAccessToken(){if(!this.jwtTokenData)return console.log("[Login Check] No access credential available, authentication required"),null;let t=Date.now(),r=this.jwtTokenData.expiresAt-t,a=this.formatTimeRemaining(r),i=this.jwtTokenData.expiresAt-sK*1e3,s=this.formatAbsoluteTime(i);if(this.isTokenNearExpiry()){console.log(`[Login Check] Access credential expiring soon (remaining: ${a}), starting auto-renewal...`);try{return await this.refreshAccessToken()}catch(e){return console.error("[Login Check] Credential renewal failed:",e),null}}return this.jwtTokenData.accessToken}isTokenExpired(){return this.jwtTokenData?Date.now()>=this.jwtTokenData.expiresAt:!0}isTokenNearExpiry(t=sK){if(!this.jwtTokenData)return!0;let r=this.jwtTokenData.expiresAt-Date.now(),a=r<=t*1e3;if(a){let i=this.formatTimeRemaining(r);console.log(`[Login Check] Credential expiry check: ${i} remaining <= ${t}s threshold, renewal needed: ${a}`)}return a}async refreshAccessToken(){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.performTokenRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performTokenRefresh(){if(!this.jwtTokenData?.refreshToken)throw new Error("No refresh token available");try{console.log("[Login Check] Refreshing access credential...");let t=await fetch(`${this.config.proxyServerUrl}/auth/jwt/refresh`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"DeepCode CLI ProxyAuthManager"},body:JSON.stringify({refreshToken:this.jwtTokenData.refreshToken})});if(!t.ok){if(t.status===401)throw this.clearTokens(),new Error("Refresh credential expired or invalid - authentication required");let u=await t.text();throw new Error(`Credential refresh failed (${t.status}): ${u}`)}let r=await t.json();if(!r.success||!r.data?.accessToken)throw new Error("Invalid refresh response from server");let a=Date.now(),i=!!r.data.refreshToken;this.jwtTokenData={accessToken:r.data.accessToken,refreshToken:r.data.refreshToken||this.jwtTokenData.refreshToken,expiresIn:r.data.expiresIn||900,expiresAt:a+(r.data.expiresIn||900)*1e3,savedAt:new Date().toISOString()},this.saveJwtToken();let s=this.formatTimeRemaining((r.data.expiresIn||900)*1e3),e=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),o=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-sK*1e3);return console.log(`[Login Check] \u2705 Credential renewed successfully - valid for: ${s} (until ${e}), next renewal: ${o}${i?" (refresh credential updated)":" (reusing existing refresh credential)"}`),this.jwtTokenData.accessToken}catch(t){throw console.error("[Login Check] Credential refresh error:",t),t}}clearTokens(){this.jwtTokenData=null;try{xc.existsSync(this.jwtTokenFilePath)&&xc.unlinkSync(this.jwtTokenFilePath)}catch(t){console.warn("[Login Check] Failed to delete access credential file:",t)}}getProxyServerUrl(){return this.config.proxyServerUrl}async getUserHeaders(){let t=await this.getAccessToken(),r=this.getCliVersion(),a=this.getUserAgent();return t?{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Client-Version":r,"User-Agent":a}:{"X-Client-Version":r,"User-Agent":a}}getUserHeadersSync(){let t=this.getCliVersion(),r=this.getUserAgent();return this.jwtTokenData?.accessToken?{Authorization:`Bearer ${this.jwtTokenData.accessToken}`,"Content-Type":"application/json","X-Client-Version":t,"User-Agent":r}:{"X-Client-Version":t,"User-Agent":r}}getUserInfo(){return this.userInfo}isConfigured(){return!!this.userInfo}getStatus(){return{configured:this.isConfigured(),proxyServerUrl:this.config.proxyServerUrl,hasUserInfo:!!this.userInfo,userInfo:this.userInfo}}clear(){this.userInfo=null,this.jwtTokenData=null,this.periodicStatusCheckIntervalId!==null&&(clearInterval(this.periodicStatusCheckIntervalId),this.periodicStatusCheckIntervalId=null);try{xc.existsSync(this.userInfoFilePath)&&xc.unlinkSync(this.userInfoFilePath)}catch(t){console.warn("[Login Check] Failed to delete user info file:",t)}try{xc.existsSync(this.jwtTokenFilePath)&&xc.unlinkSync(this.jwtTokenFilePath)}catch(t){console.warn("[Login Check] Failed to delete access credential file:",t)}console.log("[Login Check] Authentication cleared")}},Io=xs.getInstance()});import{promises as GQ}from"node:fs";import oK from"node:path";import QIr from"os";var jG,y0e,ar,av=ut(()=>{"use strict";(function(n){n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR"})(jG||(jG={}));y0e=class{config;logBuffer=[];constructor(t={}){if(this.config={level:jG.INFO,enableConsole:!0,enableFile:!1,maxFileSize:10,maxFiles:5,...t},this.config.enableFile&&!this.config.filePath){let r=new Date().toISOString().slice(0,19).replace(/[:.]/g,"-");this.config.filePath=oK.join(QIr.homedir(),".deepv","logs",`deepv-${r}.log`)}}formatMessage(t,r,...a){let i=new Date().toISOString(),s=a.map(e=>typeof e=="object"?JSON.stringify(e,null,2):String(e)).join(" ");return`[${i}] [${t}] ${r} ${s}`.trim()}async writeToFile(t){if(!(!this.config.enableFile||!this.config.filePath))try{await GQ.mkdir(oK.dirname(this.config.filePath),{recursive:!0}),await this.rotateLogIfNeeded(),await GQ.appendFile(this.config.filePath,t+`
|
|
537
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,a,i]=NIr(t,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};qHe=class n extends Promise{constructor(t,r,a=AIr){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=a,this.client=t}_thenUnwrap(t){return new n(this.client,this.responsePromise,async(r,a)=>t(await this.parseResponse(r,a),a))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(this.client,t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};zFt=Symbol("brand.privateNullableHeaders");rK=n=>{let t=new Headers,r=new Set;for(let a of n){let i=new Set;for(let[s,e]of WIr(a)){let o=s.toLowerCase();i.has(o)||(t.delete(s),i.add(o)),e===null?(t.delete(s),r.add(o)):(t.append(s,e),r.delete(o))}}return{[zFt]:!0,values:t,nulls:r}};UHe=n=>{var t,r,a,i,s,e;if(typeof globalThis.process<"u")return(a=(r=(t=globalThis.process.env)===null||t===void 0?void 0:t[n])===null||r===void 0?void 0:r.trim())!==null&&a!==void 0?a:void 0;if(typeof globalThis.Deno<"u")return(e=(s=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||s===void 0?void 0:s.call(i,n))===null||e===void 0?void 0:e.trim()};A0e=class n{constructor(t){var r,a,i,s,e,o,u,{baseURL:d=UHe("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:I=(r=UHe("GEMINI_API_KEY"))!==null&&r!==void 0?r:null,apiVersion:h="v1beta"}=t,c=o0e(t,["baseURL","apiKey","apiVersion"]);let G=Object.assign(Object.assign({apiKey:I,apiVersion:h},c),{baseURL:d||"https://generativelanguage.googleapis.com"});this.baseURL=G.baseURL,this.timeout=(a=G.timeout)!==null&&a!==void 0?a:n.DEFAULT_TIMEOUT,this.logger=(i=G.logger)!==null&&i!==void 0?i:console;let F="warn";this.logLevel=F,this.logLevel=(e=(s=LFt(G.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:LFt(UHe("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&e!==void 0?e:F,this.fetchOptions=G.fetchOptions,this.maxRetries=(o=G.maxRetries)!==null&&o!==void 0?o:2,this.fetch=(u=G.fetch)!==null&&u!==void 0?u:iIr(),this.encoder=oIr,this._options=G,this.apiKey=I,this.apiVersion=h,this.clientAdapter=G.clientAdapter}withOptions(t){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),t))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){if(!(t.has("authorization")||t.has("x-goog-api-key"))&&!(this.apiKey&&t.get("x-goog-api-key"))&&!r.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(t){let r=rK([t.headers]);if(!(r.values.has("authorization")||r.values.has("x-goog-api-key"))){if(this.apiKey)return rK([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return rK([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(t){return Object.entries(t).filter(([r,a])=>typeof a<"u").map(([r,a])=>{if(typeof a=="string"||typeof a=="number"||typeof a=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(a)}`;if(a===null)return`${encodeURIComponent(r)}=`;throw new rf(`Cannot stringify type ${typeof a}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${EB}`}defaultIdempotencyKey(){return`stainless-node-retry-${Uur()}`}makeStatusError(t,r,a,i){return af.generate(t,r,a,i)}buildURL(t,r,a){let i=!this.baseURLOverridden()&&a||this.baseURL,s=zur(t)?new URL(t):new URL(i+(i.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),e=this.defaultQuery();return jur(e)||(r=Object.assign(Object.assign({},e),r)),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(t){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!t.path.startsWith(`/${this.apiVersion}/projects/`)){let r=t.path.slice(this.apiVersion.length+1);t.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${r}`}}async prepareRequest(t,{url:r,options:a}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,a){return this.request(Promise.resolve(a).then(i=>Object.assign({method:t,path:r},i)))}request(t,r=null){return new qHe(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,a){var i,s,e;let o=await t,u=(i=o.maxRetries)!==null&&i!==void 0?i:this.maxRetries;r==null&&(r=u),await this.prepareOptions(o);let{req:d,url:I,timeout:h}=await this.buildRequest(o,{retryCount:u-r});await this.prepareRequest(d,{url:I,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),G=a===void 0?"":`, retryOf: ${a}`,F=Date.now();if(kb(this).debug(`[${c}] sending request`,mQ({retryOfRequestLogID:a,method:o.method,url:I,options:o,headers:d.headers})),!((s=o.signal)===null||s===void 0)&&s.aborted)throw new iK;let W=new AbortController,R=await this.fetchWithTimeout(I,d,h,W).catch(zHe),y=Date.now();if(R instanceof globalThis.Error){let A=`retrying, ${r} attempts remaining`;if(!((e=o.signal)===null||e===void 0)&&e.aborted)throw new iK;let E=MHe(R)||/timed? ?out/i.test(String(R)+("cause"in R?String(R.cause):""));if(r)return kb(this).info(`[${c}] connection ${E?"timed out":"failed"} - ${A}`),kb(this).debug(`[${c}] connection ${E?"timed out":"failed"} (${A})`,mQ({retryOfRequestLogID:a,url:I,durationMs:y-F,message:R.message})),this.retryRequest(o,r,a??c);throw kb(this).info(`[${c}] connection ${E?"timed out":"failed"} - error; no more retries left`),kb(this).debug(`[${c}] connection ${E?"timed out":"failed"} (error; no more retries left)`,mQ({retryOfRequestLogID:a,url:I,durationMs:y-F,message:R.message})),E?new u0e:new YB({cause:R})}let w=`[${c}${G}] ${d.method} ${I} ${R.ok?"succeeded":"failed"} with status ${R.status} in ${y-F}ms`;if(!R.ok){let A=await this.shouldRetry(R);if(r&&A){let m=`retrying, ${r} attempts remaining`;return await sIr(R.body),kb(this).info(`${w} - ${m}`),kb(this).debug(`[${c}] response error (${m})`,mQ({retryOfRequestLogID:a,url:R.url,status:R.status,headers:R.headers,durationMs:y-F})),this.retryRequest(o,r,a??c,R.headers)}let E=A?"error; no more retries left":"error; not retryable";kb(this).info(`${w} - ${E}`);let f=await R.text().catch(m=>zHe(m).message),g=$ur(f),v=g?void 0:f;throw kb(this).debug(`[${c}] response error (${E})`,mQ({retryOfRequestLogID:a,url:R.url,status:R.status,headers:R.headers,message:v,durationMs:Date.now()-F})),this.makeStatusError(R.status,g,v,R.headers)}return kb(this).info(w),kb(this).debug(`[${c}] response start`,mQ({retryOfRequestLogID:a,url:R.url,status:R.status,headers:R.headers,durationMs:y-F})),{response:R,options:o,controller:W,requestLogID:c,retryOfRequestLogID:a,startTime:F}}async fetchWithTimeout(t,r,a,i){let s=r||{},{signal:e,method:o}=s,u=o0e(s,["signal","method"]);e&&e.addEventListener("abort",()=>i.abort());let d=setTimeout(()=>i.abort(),a),I=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body=="object"&&u.body!==null&&Symbol.asyncIterator in u.body,h=Object.assign(Object.assign(Object.assign({signal:i.signal},I?{duplex:"half"}:{}),{method:"GET"}),u);o&&(h.method=o.toUpperCase());try{return await this.fetch.call(void 0,t,h)}finally{clearTimeout(d)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,a,i){var s;let e,o=i?.get("retry-after-ms");if(o){let d=parseFloat(o);Number.isNaN(d)||(e=d)}let u=i?.get("retry-after");if(u&&!e){let d=parseFloat(u);Number.isNaN(d)?e=Date.parse(u)-Date.now():e=d*1e3}if(!(e&&0<=e&&e<60*1e3)){let d=(s=t.maxRetries)!==null&&s!==void 0?s:this.maxRetries;e=this.calculateDefaultRetryTimeoutMillis(r,d)}return await eIr(e),this.makeRequest(t,r-1,a)}calculateDefaultRetryTimeoutMillis(t,r){let s=r-t,e=Math.min(.5*Math.pow(2,s),8),o=1-Math.random()*.25;return e*o*1e3}async buildRequest(t,{retryCount:r=0}={}){var a,i,s;let e=Object.assign({},t),{method:o,path:u,query:d,defaultBaseURL:I}=e,h=this.buildURL(u,d,I);"timeout"in e&&qur("timeout",e.timeout),e.timeout=(a=e.timeout)!==null&&a!==void 0?a:this.timeout;let{bodyHeaders:c,body:G}=this.buildBody({options:e}),F=await this.buildHeaders({options:t,method:o,bodyHeaders:c,retryCount:r});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:o,headers:F},e.signal&&{signal:e.signal}),globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"}),G&&{body:G}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(s=e.fetchOptions)!==null&&s!==void 0?s:{}),url:h,timeout:e.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:a,retryCount:i}){let s={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=t.idempotencyKey);let e=await this.authHeaders(t),o=rK([s,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{}),aIr()),this._options.defaultHeaders,a,t.headers,e]);return this.validateHeaders(o),o.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let a=rK([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&a.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:lIr(t)}:this.encoder({body:t,headers:a})}};A0e.DEFAULT_TIMEOUT=6e4;G0=class extends A0e{constructor(){super(...arguments),this.interactions=new Z0e(this)}};_Ft=G0;G0.GeminiNextGenAPIClient=_Ft;G0.GeminiNextGenAPIClientError=rf;G0.APIError=af;G0.APIConnectionError=YB;G0.APIConnectionTimeoutError=u0e;G0.APIUserAbortError=iK;G0.NotFoundError=m0e;G0.ConflictError=p0e;G0.RateLimitError=f0e;G0.BadRequestError=I0e;G0.AuthenticationError=d0e;G0.InternalServerError=G0e;G0.PermissionDeniedError=h0e;G0.UnprocessableEntityError=b0e;G0.toFile=hIr;G0.Interactions=Z0e;Usi=1024*1024*8;});function yIr(n,t){return{...n,...t}}function PFt(n){let{prompt_id:t,...r}=n;return r}function bQ(n){return Array.isArray(n)?n.map(PFt):n}var W0e=ut(()=>{"use strict";wi();});var jFt={};Lo(jFt,{DEFAULT_PROXY_CONFIG:()=>RIr,getActiveProxyServerUrl:()=>FW,getAvailableProxyServers:()=>FIr,getProxyServerInfo:()=>EIr,getProxyServers:()=>lK,hasAvailableProxyServer:()=>tXe});function lK(){return[{url:"https://api-code.deepvlab.ai",name:"Primary Development Server",region:"default",status:"active"}]}function FW(){let t=lK().find(r=>r.status==="active");if(!t)throw new Error("No active proxy server available. Please contact support.");return t.url}function FIr(){return lK().filter(t=>t.status==="active")}function tXe(){return lK().some(t=>t.status==="active")}function EIr(n){return lK().find(r=>r.url===n)}var RIr,VB=ut(()=>{"use strict";RIr={serverUrl:FW(),timeout:2e5,retryAttempts:3,retryDelay:1e3}});import*as xc from"fs";import*as QN from"path";import*as fQ from"os";function wIr(n){Io.configure(n)}function CIr(n){Io.setUserInfo(n)}function YIr(n){Io.setCliVersion(n)}async function xIr(){return await Io.getUserHeaders()}function VIr(){return Io.getStatus()}var sK,xs,Io,fw=ut(()=>{"use strict";VB();sK=259200,xs=class n{static instance=null;config;userInfo=null;jwtTokenData=null;usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()};userInfoFilePath;jwtTokenFilePath;usageStatsFilePath;refreshPromise=null;cliVersion="unknown";periodicStatusCheckIntervalId=null;onLoginSuccessCallbacks=[];getCliVersion(){return this.cliVersion}getUserAgent(){let t=this.cliVersion,r=process.platform,a=process.arch;return t.startsWith("VSCode-")?`DeepVCode/VSCode/${t.replace("VSCode-","")} (${r}; ${a})`:`DeepVCode/CLI/${t} (${r}; ${a})`}formatTimeRemaining(t){if(t<=0)return"\u5DF2\u8FC7\u671F";let r=Math.floor(t/1e3),a=Math.floor(r/(24*3600)),i=Math.floor(r%(24*3600)/3600),s=Math.floor(r%3600/60),e=r%60;return a>0?`${a}\u5929${i}\u5C0F\u65F6${s}\u5206\u949F`:i>0?`${i}\u5C0F\u65F6${s}\u5206\u949F${e}\u79D2`:s>0?`${s}\u5206\u949F${e}\u79D2`:`${e}\u79D2`}formatAbsoluteTime(t){return new Date(t).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}constructor(){"https://api-code.deepvlab.ai"?.includes("localhost")?(this.userInfoFilePath=QN.join(fQ.homedir(),".deepv","user-info-dev.json"),this.jwtTokenFilePath=QN.join(fQ.homedir(),".deepv","jwt-token-dev.json"),this.usageStatsFilePath=QN.join(fQ.homedir(),".deepv","usage-stats-dev.json")):(this.userInfoFilePath=QN.join(fQ.homedir(),".deepv","user-info.json"),this.jwtTokenFilePath=QN.join(fQ.homedir(),".deepv","jwt-token.json"),this.usageStatsFilePath=QN.join(fQ.homedir(),".deepv","usage-stats.json")),this.cliVersion="1.0.309",this.config={proxyServerUrl:FW()},this.loadUserInfo(),this.loadJwtToken(),this.loadUsageStats(),this.startPeriodicStatusCheck()}startPeriodicStatusCheck(){this.periodicStatusCheckIntervalId=setInterval(()=>{if(this.jwtTokenData){let t=Date.now(),r=this.jwtTokenData.expiresAt-t,a=this.formatTimeRemaining(r),i=this.formatAbsoluteTime(this.jwtTokenData.expiresAt);if(r>0){let s=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-sK*1e3);console.log(`[Login Check] \u{1F4CA} Periodic status check - Credential remaining: ${a} (until ${i}), next renewal: ${s}`)}else console.log(`[Login Check] \u26A0\uFE0F Periodic status check - Credential expired at: ${i}`)}},600*1e3)}static getInstance(){return n.instance||(n.instance=new n),n.instance}loadUserInfo(){try{if(xc.existsSync(this.userInfoFilePath)){let t=xc.readFileSync(this.userInfoFilePath,"utf8");this.userInfo=JSON.parse(t);let r=a=>{if(!a||!a.includes("@"))return a;let[i,s]=a.split("@");return i.length<=2?a:`${i[0]+"*".repeat(i.length-2)+i[i.length-1]}@${s}`}}}catch(t){console.warn("[Login Check] Failed to load user info from local file:",t),this.userInfo=null}}saveUserInfo(){try{let t=QN.dirname(this.userInfoFilePath);xc.existsSync(t)||xc.mkdirSync(t,{recursive:!0}),xc.writeFileSync(this.userInfoFilePath,JSON.stringify(this.userInfo,null,2)),console.log("[Login Check] User info saved to local file")}catch(t){console.error("[Login Check] Failed to save user info:",t)}}loadJwtToken(){try{if(xc.existsSync(this.jwtTokenFilePath)){let t=xc.readFileSync(this.jwtTokenFilePath,"utf8");this.jwtTokenData=JSON.parse(t);let r=Date.now();this.isTokenExpired()?this.jwtTokenData=null:this.isTokenNearExpiry(300)&&console.log("\u26A0\uFE0F Access credential expiring soon, auto-renewal in progress")}else console.log("[Login Check] No stored access credential found, authentication required")}catch(t){console.warn("[Login Check] Failed to load access credential from local file:",t),this.jwtTokenData=null}}saveJwtToken(){try{if(!this.jwtTokenData)return;let t=QN.dirname(this.jwtTokenFilePath);xc.existsSync(t)||xc.mkdirSync(t,{recursive:!0}),xc.writeFileSync(this.jwtTokenFilePath,JSON.stringify(this.jwtTokenData,null,2)),console.log("[Login Check] Access credential data saved to local file")}catch(t){console.error("[Login Check] Failed to save access credential:",t)}}loadUsageStats(){try{if(xc.existsSync(this.usageStatsFilePath)){let t=xc.readFileSync(this.usageStatsFilePath,"utf8");this.usageStats=JSON.parse(t)}}catch(t){console.warn("[Login Check] Failed to load usage stats from local file:",t),this.usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()}}}saveUsageStats(){try{let t=QN.dirname(this.usageStatsFilePath);xc.existsSync(t)||xc.mkdirSync(t,{recursive:!0}),xc.writeFileSync(this.usageStatsFilePath,JSON.stringify(this.usageStats,null,2)),console.log("[Login Check] Usage stats saved to local file")}catch(t){console.error("[Login Check] Failed to save usage stats:",t)}}updateUsageStats(t){t<=0||(this.usageStats.totalCreditsConsumed+=t,this.usageStats.lastUpdated=new Date().toISOString(),this.saveUsageStats(),console.log(`[Usage Stats] Updated total credits consumed: ${this.usageStats.totalCreditsConsumed} (+${t})`))}getUsageStats(){return{...this.usageStats}}checkStartupTokenStatus(){return this.jwtTokenData?{hasToken:!0,isExpired:Date.now()>=this.jwtTokenData.expiresAt,expiresAt:this.jwtTokenData.expiresAt,hasRefreshToken:!!this.jwtTokenData.refreshToken}:{hasToken:!1,isExpired:!0,expiresAt:null,hasRefreshToken:!1}}configure(t){this.config={...this.config,...t},t.userInfo&&(this.userInfo=t.userInfo,this.saveUserInfo(),console.log(`[Login Check] User info configured: ${t.userInfo.name}`)),t.proxyServerUrl&&console.log(`[Login Check] Proxy server URL: ${t.proxyServerUrl}`),t.cliVersion&&(this.cliVersion=t.cliVersion,console.log(`[Login Check] CLI version set: ${t.cliVersion}`))}setUserInfo(t){this.userInfo=t,this.saveUserInfo(),console.log(`[Login Check] User info updated: ${t.name} (${t.email||t.openId||"N/A"})`),this.triggerLoginSuccessCallbacks()}onLoginSuccess(t){this.onLoginSuccessCallbacks.push(t)}triggerLoginSuccessCallbacks(){this.onLoginSuccessCallbacks.forEach(t=>{try{t()}catch(r){console.error("[ProxyAuthManager] Error in login success callback:",r)}})}setCliVersion(t){this.cliVersion=t,console.log(`[Login Check] CLI version updated: ${t}`)}setJwtToken(t){let r=Date.now();this.jwtTokenData={accessToken:t,expiresIn:900,expiresAt:r+900*1e3,savedAt:new Date().toISOString()},this.saveJwtToken(),console.log("[Login Check] Access credential updated")}setJwtTokenData(t){let a=Date.now()+t.expiresIn*1e3;this.jwtTokenData={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn,expiresAt:a,savedAt:new Date().toISOString()},this.saveJwtToken();let i=this.formatTimeRemaining(t.expiresIn*1e3),s=this.formatAbsoluteTime(a),e=this.formatAbsoluteTime(a-sK*1e3),u=!!t.refreshToken?", will auto-renew":", manual login required";console.log(`[Login Check] Access credential updated - valid for: ${i} (until ${s}), next renewal: ${e}${u}`)}async getAccessToken(){if(!this.jwtTokenData)return console.log("[Login Check] No access credential available, authentication required"),null;let t=Date.now(),r=this.jwtTokenData.expiresAt-t,a=this.formatTimeRemaining(r),i=this.jwtTokenData.expiresAt-sK*1e3,s=this.formatAbsoluteTime(i);if(this.isTokenNearExpiry()){console.log(`[Login Check] Access credential expiring soon (remaining: ${a}), starting auto-renewal...`);try{return await this.refreshAccessToken()}catch(e){return console.error("[Login Check] Credential renewal failed:",e),null}}return this.jwtTokenData.accessToken}isTokenExpired(){return this.jwtTokenData?Date.now()>=this.jwtTokenData.expiresAt:!0}isTokenNearExpiry(t=sK){if(!this.jwtTokenData)return!0;let r=this.jwtTokenData.expiresAt-Date.now(),a=r<=t*1e3;if(a){let i=this.formatTimeRemaining(r);console.log(`[Login Check] Credential expiry check: ${i} remaining <= ${t}s threshold, renewal needed: ${a}`)}return a}async refreshAccessToken(){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.performTokenRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performTokenRefresh(){if(!this.jwtTokenData?.refreshToken)throw new Error("No refresh token available");try{console.log("[Login Check] Refreshing access credential...");let t=await fetch(`${this.config.proxyServerUrl}/auth/jwt/refresh`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"DeepCode CLI ProxyAuthManager"},body:JSON.stringify({refreshToken:this.jwtTokenData.refreshToken})});if(!t.ok){if(t.status===401)throw this.clearTokens(),new Error("Refresh credential expired or invalid - authentication required");let u=await t.text();throw new Error(`Credential refresh failed (${t.status}): ${u}`)}let r=await t.json();if(!r.success||!r.data?.accessToken)throw new Error("Invalid refresh response from server");let a=Date.now(),i=!!r.data.refreshToken;this.jwtTokenData={accessToken:r.data.accessToken,refreshToken:r.data.refreshToken||this.jwtTokenData.refreshToken,expiresIn:r.data.expiresIn||900,expiresAt:a+(r.data.expiresIn||900)*1e3,savedAt:new Date().toISOString()},this.saveJwtToken();let s=this.formatTimeRemaining((r.data.expiresIn||900)*1e3),e=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),o=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-sK*1e3);return console.log(`[Login Check] \u2705 Credential renewed successfully - valid for: ${s} (until ${e}), next renewal: ${o}${i?" (refresh credential updated)":" (reusing existing refresh credential)"}`),this.jwtTokenData.accessToken}catch(t){throw console.error("[Login Check] Credential refresh error:",t),t}}clearTokens(){this.jwtTokenData=null;try{xc.existsSync(this.jwtTokenFilePath)&&xc.unlinkSync(this.jwtTokenFilePath)}catch(t){console.warn("[Login Check] Failed to delete access credential file:",t)}}getProxyServerUrl(){return this.config.proxyServerUrl}async getUserHeaders(){let t=await this.getAccessToken(),r=this.getCliVersion(),a=this.getUserAgent();return t?{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Client-Version":r,"User-Agent":a}:{"X-Client-Version":r,"User-Agent":a}}getUserHeadersSync(){let t=this.getCliVersion(),r=this.getUserAgent();return this.jwtTokenData?.accessToken?{Authorization:`Bearer ${this.jwtTokenData.accessToken}`,"Content-Type":"application/json","X-Client-Version":t,"User-Agent":r}:{"X-Client-Version":t,"User-Agent":r}}getUserInfo(){return this.userInfo}isConfigured(){return!!this.userInfo}getStatus(){return{configured:this.isConfigured(),proxyServerUrl:this.config.proxyServerUrl,hasUserInfo:!!this.userInfo,userInfo:this.userInfo}}clear(){this.userInfo=null,this.jwtTokenData=null,this.periodicStatusCheckIntervalId!==null&&(clearInterval(this.periodicStatusCheckIntervalId),this.periodicStatusCheckIntervalId=null);try{xc.existsSync(this.userInfoFilePath)&&xc.unlinkSync(this.userInfoFilePath)}catch(t){console.warn("[Login Check] Failed to delete user info file:",t)}try{xc.existsSync(this.jwtTokenFilePath)&&xc.unlinkSync(this.jwtTokenFilePath)}catch(t){console.warn("[Login Check] Failed to delete access credential file:",t)}console.log("[Login Check] Authentication cleared")}},Io=xs.getInstance()});import{promises as GQ}from"node:fs";import oK from"node:path";import QIr from"os";var jG,y0e,ar,av=ut(()=>{"use strict";(function(n){n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR"})(jG||(jG={}));y0e=class{config;logBuffer=[];constructor(t={}){if(this.config={level:jG.INFO,enableConsole:!0,enableFile:!1,maxFileSize:10,maxFiles:5,...t},this.config.enableFile&&!this.config.filePath){let r=new Date().toISOString().slice(0,19).replace(/[:.]/g,"-");this.config.filePath=oK.join(QIr.homedir(),".deepv","logs",`deepv-${r}.log`)}}formatMessage(t,r,...a){let i=new Date().toISOString(),s=a.map(e=>typeof e=="object"?JSON.stringify(e,null,2):String(e)).join(" ");return`[${i}] [${t}] ${r} ${s}`.trim()}async writeToFile(t){if(!(!this.config.enableFile||!this.config.filePath))try{await GQ.mkdir(oK.dirname(this.config.filePath),{recursive:!0}),await this.rotateLogIfNeeded(),await GQ.appendFile(this.config.filePath,t+`
|
|
538
538
|
`,"utf-8")}catch(r){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",r)}}async rotateLogIfNeeded(){if(this.config.filePath)try{if((await GQ.stat(this.config.filePath)).size/(1024*1024)>(this.config.maxFileSize||10)){let a=new Date().toISOString().slice(0,19).replace(/[:.]/g,"-"),i=this.config.filePath.replace(".log",`-${a}.log`);await GQ.rename(this.config.filePath,i),await this.cleanOldLogs()}}catch(t){t.code!=="ENOENT"&&console.error("\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25:",t)}}async cleanOldLogs(){if(this.config.filePath)try{let t=oK.dirname(this.config.filePath),a=(await GQ.readdir(t)).filter(e=>e.startsWith("deepv-")&&e.endsWith(".log")).map(e=>({name:e,path:oK.join(t,e),time:GQ.stat(oK.join(t,e)).then(o=>o.mtime)})),i=await Promise.all(a.map(async e=>({...e,time:await e.time})));i.sort((e,o)=>o.time.getTime()-e.time.getTime());let s=i.slice(this.config.maxFiles||5);for(let e of s)await GQ.unlink(e.path)}catch(t){console.error("\u6E05\u7406\u65E7\u65E5\u5FD7\u5931\u8D25:",t)}}log(t,r,a,...i){if(t<this.config.level)return;let s=this.formatMessage(r,a,...i);this.config.enableConsole&&(t>=jG.ERROR?console.error:t>=jG.WARN?console.warn:t>=jG.INFO?console.log:console.debug)(s),this.config.enableFile&&this.writeToFile(s)}debug(t,...r){this.log(jG.DEBUG,"DEBUG",t,...r)}info(t,...r){this.log(jG.INFO,"INFO",t,...r)}warn(t,...r){this.log(jG.WARN,"WARN",t,...r)}error(t,...r){this.log(jG.ERROR,"ERROR",t,...r)}logApiRequest(t,r){this.debug("API\u8BF7\u6C42",{endpoint:t,timestamp:new Date().toISOString(),requestSize:JSON.stringify(r).length,...process.env.FILE_DEBUG==="1"?{requestData:r}:{}})}logApiResponse(t,r){this.debug("API\u54CD\u5E94",{endpoint:t,timestamp:new Date().toISOString(),responseSize:JSON.stringify(r).length,...process.env.FILE_DEBUG==="1"?{responseData:r}:{}})}},ar=new y0e({level:process.env.FILE_DEBUG==="1"?jG.DEBUG:jG.INFO,enableConsole:!0,enableFile:process.env.LOG_TO_FILE==="true",filePath:process.env.LOG_FILE_PATH})});function Bo(n){return n instanceof Error&&"code"in n}function or(n){if(n instanceof Error)return n.message;try{return String(n)}catch{return"Failed to get error details"}}function nXe(n){if(n&&typeof n=="object"&&"response"in n){let r=HIr(n);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new E0e(r.error.message);case 401:return new BI(r.error.message);case 403:return new F0e(r.error.message);default:}}return n}function HIr(n){return typeof n.response?.data=="string"?JSON.parse(n.response?.data):n.response?.data}var F0e,BI,E0e,Vc=ut(()=>{"use strict";F0e=class extends Error{},BI=class extends Error{},E0e=class extends Error{}});var Ha,KFt,xd,EW=ut(()=>{"use strict";(function(n){n.CHAT_CONVERSATION="chat_conversation",n.WEB_FETCH="web_fetch",n.WEB_SEARCH="web_search",n.CONTENT_SUMMARY="content_summary",n.JSON_GENERATION="json_generation",n.COMPRESSION="compression",n.SUB_AGENT="sub_agent",n.CODE_ASSIST="code_assist",n.EDIT_CORRECTION="edit_correction"})(Ha||(Ha={}));KFt={[Ha.CHAT_CONVERSATION]:"auto",[Ha.WEB_FETCH]:"gemini-2.5-flash",[Ha.WEB_SEARCH]:"gemini-2.5-flash",[Ha.CODE_ASSIST]:"auto",[Ha.CONTENT_SUMMARY]:"gemini-2.5-flash-lite",[Ha.EDIT_CORRECTION]:"gemini-2.5-flash-lite",[Ha.JSON_GENERATION]:"gemini-2.5-flash",[Ha.COMPRESSION]:"gemini-2.5-flash",[Ha.SUB_AGENT]:"auto"},xd=class{static getModelForScene(t){if(t)return KFt[t]}static isClaudeModel(t){return t.includes("claude")||t.includes("anthropic")}static isGeminiModel(t){return t.includes("gemini")&&!this.isClaudeModel(t)}static getSceneDisplayName(t){return{[Ha.CHAT_CONVERSATION]:"\u804A\u5929\u5BF9\u8BDD",[Ha.WEB_FETCH]:"Web\u5185\u5BB9\u83B7\u53D6",[Ha.WEB_SEARCH]:"Web\u641C\u7D22",[Ha.CODE_ASSIST]:"\u4EE3\u7801\u52A9\u624B",[Ha.CONTENT_SUMMARY]:"\u5185\u5BB9\u6458\u8981",[Ha.EDIT_CORRECTION]:"\u7F16\u8F91\u6821\u6B63",[Ha.JSON_GENERATION]:"JSON\u751F\u6210",[Ha.COMPRESSION]:"\u5BF9\u8BDD\u538B\u7F29",[Ha.SUB_AGENT]:"SubAgent\u5B50\u4EE3\u7406"}[t]||t}}});function T5(n){return typeof n=="object"&&n!==null&&"error"in n&&typeof n.error=="object"&&"message"in n.error}function lf(n){return typeof n=="object"&&n!==null&&"message"in n&&typeof n.message=="string"}function HN(n){let t=r=>r.includes("Quota exceeded for quota metric 'Gemini")&&r.includes("Pro Requests'");if(typeof n=="string")return t(n);if(lf(n))return t(n.message);if(T5(n))return t(n.error.message);if(n&&typeof n=="object"&&"response"in n){let r=n;if(r.response&&r.response.data){if(typeof r.response.data=="string")return t(r.response.data);if(typeof r.response.data=="object"&&r.response.data!==null&&"error"in r.response.data){let a=r.response.data;return t(a.error?.message||"")}}}return!1}function XN(n){return typeof n=="string"?n.includes("Quota exceeded for quota metric"):lf(n)?n.message.includes("Quota exceeded for quota metric"):T5(n)?n.error.message.includes("Quota exceeded for quota metric"):!1}function sf(n){if(n&&typeof n=="object"&&"response"in n){let t=n;if(t.response?.status===402&&t.response.data){let r=t.response.data;if(r&&typeof r.error=="string"&&(r.error==="Quota limit exceeded"||r.error==="No quota configuration")&&typeof r.message=="string")return!0}if(t.response?.status===500&&t.response.data){let r=t.response.data;if(r&&typeof r.message=="string"&&r.message.includes("quota exceeded"))return!0}}if(n instanceof Error&&n.message&&(n.message.includes("API request failed (402):")&&(n.message.includes('"error":"Quota limit exceeded"')||n.message.includes('"error":"No quota configuration"'))||n.message.includes("API request failed (500):")&&n.message.includes("quota exceeded")||n.message.includes("Stream API error (500):")&&n.message.includes("quota exceeded")))return!0;if(typeof n=="object"&&n!==null){let t=n;if(t.message&&typeof t.message=="string"&&(t.message.includes("API request failed (402):")&&(t.message.includes('"error":"Quota limit exceeded"')||t.message.includes('"error":"No quota configuration"'))||t.message.includes("API error (402):")&&(t.message.includes('"error":"Quota limit exceeded"')||t.message.includes('"error":"No quota configuration"'))||(t.message.includes("API request failed (500):")||t.message.includes("Stream API error (500):"))&&t.message.includes("quota exceeded"))||(t.error==="Quota limit exceeded"||t.error==="No quota configuration")&&typeof t.message=="string"||t.status===500&&typeof t.message=="string"&&t.message.includes("quota exceeded"))return!0}return typeof n=="string"?n.includes("Quota limit exceeded")||n.includes("No quota configuration")||n.includes("Daily token limit would be exceeded")||n.includes("Daily request limit exceeded")||n.includes("Daily cost limit would be exceeded")||n.includes("500")&&n.includes("quota exceeded"):!1}function cK(n){let t=null;if(n&&typeof n=="object"&&"response"in n){let r=n;if(r.response?.status===402&&r.response.data)t=r.response.data;else if(r.response?.status===500&&r.response.data){let a=r.response.data;a&&typeof a.message=="string"&&a.message.includes("quota exceeded")&&(t=a)}}else if(typeof n=="object"&&n!==null){let r=n;if(r.message&&typeof r.message=="string"&&(r.message.includes("API request failed (402):")||r.message.includes("API request failed (500):")||r.message.includes("Stream API error (500):"))&&(r.message.includes('"error":"Quota limit exceeded"')||r.message.includes('"error":"No quota configuration"')||r.message.includes("quota exceeded")))try{let a=r.message.match(/\{.*\}$/);a&&(t=JSON.parse(a[0]))}catch{}t||(t=n)}if(!t&&n instanceof Error&&n.message&&(n.message.includes("API request failed (402):")||n.message.includes("API request failed (500):")||n.message.includes("Stream API error (500):"))&&(n.message.includes('"error":"Quota limit exceeded"')||n.message.includes('"error":"No quota configuration"')||n.message.includes("quota exceeded")))try{let r=n.message.match(/\{.*\}$/);r&&(t=JSON.parse(r[0]))}catch{}return t?t.message&&t.message.includes("quota exceeded")?XIr(t):kIr(t):null}function XIr(n){let r=(()=>{try{let c=process.env,G=c.LC_ALL||c.LC_CTYPE||c.LANG||"";return G.toLowerCase().includes("zh")||G.toLowerCase().includes("chinese")}catch{return!1}})(),a="",i="",s="",e="",o=n.message||"",u=o.match(/Role:\s*([^,]+)/);u&&(a=u[1].trim());let d=o.match(/Limit:\s*([^,]+)/);d&&(i=d[1].trim());let I=o.match(/Used:\s*([^,]+)/);I&&(s=I[1].trim());let h=o.match(/Cycle:\s*([^,]+)/);if(h&&(e=h[1].trim()),r){let c=`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
539
539
|
`;return c+=`\u{1F6AB} \u5F53\u524D\u6A21\u578B\u7684\u5FAA\u73AF\u914D\u989D\u5DF2\u7528\u5C3D (Cycle Quota Exceeded)
|
|
540
540
|
`,a&&(c+=`\u{1F464} \u89D2\u8272\u4FE1\u606F: ${a}
|
|
@@ -703,7 +703,7 @@ ${s}`;break;case"retry":SVt(s)&&(r[i]=s);break;case"id":BVt(s)&&(r[i]=s);break;c
|
|
|
703
703
|
|
|
704
704
|
Please check your Feishu authentication token and try again.
|
|
705
705
|
If the problem persists, you may need to re-authenticate.`);throw a.isAuthError=!0,a.statusCode=401,a}throw t}async generateContentStream(t,r){let a=xd.getModelForScene(r),i=this.config?.getModel(),s;if(i&&as(i)?(t.model&&as(t.model)?s=t.model:s=i,console.log(`[DeepV Server] (Stream) User is using custom model, overriding scene model for ${r}: ${s}`)):s=t.model||a||i||"auto",as(s)&&this.config){let o=this.config.getCustomModelConfig(s);if(o)return console.log("[DeepV Server] Custom model detected, using streaming mode"),tQt(o,t,t.config?.abortSignal)}return process.env.DEEPV_CLOUD_MODE==="true"?this._generateContent(t,r):N3r(t.model)?this._generateContentStream(t,r):this._generateContent(t,r)}async _generateContent(t,r){let a=await this.generateContent(t,r);return(async function*(){yield a})()}async _generateContentStream(t,r){try{let a=xd.getModelForScene(r),i=this.config?.getModel(),s;i&&as(i)?(t.model&&as(t.model)?s=t.model:s=i,console.log(`[DeepV Server] (_Stream) User is using custom model, overriding scene model for ${r}: ${s}`)):s=t.model||a||i||"auto",process.env.DEBUG&&console.log(`[\u{1F3AF} Model Resolution (Stream)] Using model: ${s} for scene: ${r}`);let e={model:s,contents:this.cleanContents(bQ(t.contents)),config:{...t.config,stream:!0,httpOptions:{...t.config?.httpOptions,headers:{...t.config?.httpOptions?.headers,"X-Scene-Type":r,"X-Scene-Display":xd.getSceneDisplayName(r)}}}};ar.info(`[DeepV Server] Starting stream with model: ${s}`);let o=await this.callStreamAPI("/v1/chat/stream",e,t.config?.abortSignal);return this.createStreamGenerator(o,t.config?.abortSignal)}catch(a){return ar.error("[DeepV Server] Stream request failed",{error:a}),this.handleStreamError(a)}}async callStreamAPI(t,r,a){return Lb(()=>this.executeStreamAPICall(t,r,a),{shouldRetry:i=>{if(sf(i)||i.message.includes("cancelled by user")||i.name==="AbortError"||i.message.includes("401")||i instanceof BI||i.message.includes("451")||i.message.includes("REGION_BLOCKED"))return!1;if(i.message.includes("429")||i.message.match(/5\d{2}/))return!0;let s=i.message.toLowerCase(),e=i?.cause?.code||i?.code;return!!(s.includes("terminated")||s.includes("socket hang up")||s.includes("connection closed")||s.includes("other side closed")||e&&["ECONNRESET","ECONNABORTED","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"].includes(e)||i instanceof TypeError&&i.message.includes("fetch failed"))}})}async executeStreamAPICall(t,r,a){let i=await Io.getUserHeaders(),s=`${Io.getProxyServerUrl()}${t}`;if(process.env.DEBUG){console.log("\u{1F50D} [DeepV Debug Stream] Proxy environment variables:"),console.log(" HTTP_PROXY:",process.env.HTTP_PROXY),console.log(" HTTPS_PROXY:",process.env.HTTPS_PROXY),console.log(" http_proxy:",process.env.http_proxy),console.log(" https_proxy:",process.env.https_proxy),console.log(" Target URL:",s);let d=(0,nQt.getGlobalDispatcher)();console.log("\u{1F50D} [DeepV Debug Stream] Global dispatcher:",d?.constructor?.name||"undefined"),d&&"uri"in d&&console.log(" Dispatcher URI:",d.uri)}let e=new AbortController,o=null;if(a)if(a.aborted)e.abort();else{let d=()=>{process.env.DEBUG&&console.log("[DeepV Server] Stream request cancelled by user"),e.abort()};a.addEventListener("abort",d),o=()=>a.removeEventListener("abort",d)}let u=Date.now();try{ar.debug("[DeepV Server] Making stream API call",{endpoint:t,url:s,model:r.model});let d=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...i},body:JSON.stringify(r),signal:e.signal});if(!d.ok){let h=await d.text();if(d.status===401)throw console.error("[DeepV Server] Stream 401 Unauthorized - triggering auth dialog"),this.authHandler&&await this.authHandler(),new BI("Authentication required - please re-authenticate");if(d.status===451)throw console.error("[DeepV Server] Stream 451 Region Blocked - IMMEDIATE ABORT"),e.abort(),new Error(`REGION_BLOCKED_451: ${h}`);let c=new Error(`Stream API error (${d.status}): ${h}`);throw c.status=d.status,c}let I=Date.now()-u;return ar.debug("[DeepV Server] Stream API call initiated",{endpoint:t,duration:`${I}ms`,status:d.status}),d}catch(d){let I=Date.now()-u;throw o&&o(),d instanceof Error&&(d.message.includes("cancelled by user")||d.name==="AbortError")?(console.log("\u26A0\uFE0F \u6D41\u5F0F\u4EFB\u52A1\u5DF2\u53D6\u6D88"),d):(d instanceof Error&&d.message.includes("abort")?ar.warn("[DeepV Server] Stream API aborted",{endpoint:t,duration:`${I}ms`,reason:d.message}):ar.error("[DeepV Server] Stream API call failed",{endpoint:t,duration:`${I}ms`,error:d instanceof Error?d.message:d}),d)}finally{o&&o()}}async*createStreamGenerator(t,r){let a=t.body?.getReader();if(!a)throw new Error("No stream reader available");let i=new TextDecoder,s="",e=0,o=null,u=()=>{console.log("[DeepV Server] Stream cancelled by user - releasing reader and stopping consumption");try{a.cancel()}catch{}},d;r&&!r.aborted&&(d=u,r.addEventListener("abort",d));try{for(;;){if(r?.aborted){console.log("[DeepV Server] Stream generation cancelled by user - exiting loop"),o&&console.log("[DeepV Server] Partial token consumption recorded:",{inputTokens:o.promptTokenCount||0,outputTokens:o.candidatesTokenCount||0,totalTokens:o.totalTokenCount||0,stoppedReason:"user_cancelled",bytesReceived:e});break}let I;try{I=await this.withTimeout(a.read(),3e5,"[DeepV Server] Stream read timeout after 300s (no data received in this chunk)")}catch(F){if(F instanceof Error&&(F.name==="AbortError"||F.message.includes("cancelled"))){console.log("[DeepV Server] Stream read cancelled - exiting");break}if(F instanceof TypeError){let W=F.message.toLowerCase(),R=F?.cause?.code||F?.code;if(W.includes("terminated")||W.includes("socket hang up")||W.includes("connection closed")||W.includes("other side closed")||R&&["ECONNRESET","ECONNABORTED","EPIPE","ETIMEDOUT","UND_ERR_SOCKET"].includes(R)){let w=new Error(`Stream interrupted: Connection was terminated mid-stream. This may be caused by server restart or network issues. Please retry your request. (Original: ${F.message})`);throw w.isStreamInterrupt=!0,w.isRetryable=!0,w.bytesReceived=e,console.warn(`\u26A0\uFE0F [DeepV Server] Stream connection interrupted after ${e} bytes. Cause: ${F.message}`),w}}throw F}let{done:h,value:c}=I;if(h)break;e+=c.length,s+=i.decode(c,{stream:!0});let G=s.split(`
|
|
706
|
-
`);s=G.pop()||"";for(let F of G)if(F.startsWith("data: ")){let W=F.slice(6);if(W==="[DONE]")return;try{let R=JSON.parse(W);if(R.type==="connection_established")continue;if(R.error)throw new Error(R.error);R.usageMetadata&&(o=R.usageMetadata);let y=this.convertStreamChunkToGenAI(R);y&&(yield y)}catch(R){ar.warn("[DeepV Server] Stream chunk parse error",{data:W.substring(0,100)+"...",error:R instanceof Error?R.message:R})}}}}finally{d&&r&&r.removeEventListener("abort",d);try{a.releaseLock()}catch{}}}convertStreamChunkToGenAI(t){if(!t.candidates||!Array.isArray(t.candidates)||t.candidates.length===0)return null;let r={candidates:t.candidates,usageMetadata:t.usageMetadata};if(r.candidates?.[0]?.content?.parts){for(let a of r.candidates[0].content.parts)if(a.functionCall&&!a.functionCall.id){let i=`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;console.log(`[DeepV Server] \u8865\u5168\u7F3A\u5931\u7684\u5DE5\u5177 ID (Chunk): ${a.functionCall.name} -> ${i}`),a.functionCall.id=i}}return r.functionCalls||Object.defineProperty(r,"functionCalls",{get:function(){if(this.candidates?.[0]?.content?.parts?.length===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let a=this.candidates?.[0]?.content?.parts?.filter(i=>i.functionCall).map(i=>i.functionCall).filter(i=>i!==void 0);if(a?.length!==0)return a},enumerable:!1,configurable:!0}),r}mergeStreamContent(t,r){if(!t)return r;let a=t.candidates?.[0]?.content?.parts||[],i=r.candidates?.[0]?.content?.parts||[];if(i.length>0&&i[0].text){let s=a[a.length-1];s&&s.text&&!s.functionCall?s.text+=i[0].text:a.push(...i)}else if(i.length>0&&i[0].functionCall){let s=a[a.length-1],e=i[0];if(s&&s.functionCall){let o=s.functionCall,u=e.functionCall;u&&(u.name&&(o.name=u.name.trim()),u.id&&(o.id=u.id),u.args&&(typeof u.args=="string"&&typeof o.args=="string"?o.args+=u.args:typeof u.args=="object"&&u.args!==null?o.args={...typeof o.args=="object"?o.args:{},...u.args}:o.args=u.args))}else{let o={...e};if(o.functionCall&&!o.functionCall.id){let u=`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;console.log(`[DeepV Server] \u8865\u5168\u7F3A\u5931\u7684\u5DE5\u5177 ID: ${o.functionCall.name} -> ${u}`),o.functionCall.id=u}a.push(o)}}return r.usageMetadata&&(t.usageMetadata=r.usageMetadata),r.candidates?.[0]?.finishReason&&(t.candidates[0].finishReason=r.candidates[0].finishReason),t}buildUnifiedRequest(t,r){let a=xd.getModelForScene(r),i=this.config?.getModel(),s;return i&&as(i)?t.model&&as(t.model)?s=t.model:s=i:s=t.model||a||"auto",{model:s,contents:t.contents,config:{...t.config,httpOptions:{...t.config?.httpOptions,headers:{...t.config?.httpOptions?.headers,"X-Scene-Type":r,"X-Scene-Display":xd.getSceneDisplayName(r)}}}}}async*handleStreamError(t){this.handleError(t)}async countTokens(t){try{let r=t.model||this.config?.getModel()||"auto";if(as(r))return ar.debug("[DeepV Server] Custom model detected, token counting not supported"),{totalTokens:0};let a={model:r,contents:t.contents};(t.config?.systemInstruction||t.config?.tools)&&(a.config={},t.config.systemInstruction&&(a.config.systemInstruction=t.config.systemInstruction),t.config.tools&&(a.config.tools=t.config.tools));let i=await this.callUnifiedTokenCountAPI(a);return of.emitRealTimeToken({inputTokens:i.totalTokens||0,outputTokens:0,totalTokens:i.totalTokens||0,timestamp:Date.now()}),i}catch(r){let a=t.model||this.config?.getModel()||"auto";return as(a)?ar.debug("[DeepV Server] Token count not available for custom model, using fallback"):ar.error("[DeepV Server] Token count failed:",r),this.estimateTokensAsFailback(t)}}async callUnifiedTokenCountAPI(t){let r=await Io.getUserHeaders(),a=`${Io.getProxyServerUrl()}/v1/chat/count-tokens`;try{let i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(t)});if(!i.ok){let e=await i.text();throw i.status===401?(console.error("[DeepV Server] Token count 401 Unauthorized"),this.authHandler&&await this.authHandler(),new BI("Authentication required - please re-authenticate")):new Error(`Token count API failed (${i.status}): ${e}`)}let s=await i.json();return ar.debug("[DeepV Server] Token count response",{totalTokens:s.totalTokens}),{totalTokens:s.totalTokens||0}}catch(i){throw ar.error("[DeepV Server] Token count API call failed:",i),i}}estimateTokensAsFailback(t){try{let r=Array.isArray(t.contents)?t.contents:[{role:Pr.USER,parts:[{text:t.contents}]}],a=0,i=0,s=0,e=0;for(let c of r)if(typeof c=="object"&&c&&"parts"in c&&Array.isArray(c.parts)){for(let G of c.parts)if(typeof G=="object"&&G&&"text"in G&&typeof G.text=="string")a+=G.text.length,e++;else if(typeof G=="object"&&G&&"functionCall"in G&&G.functionCall){let F=G.functionCall,W=`[Tool: ${F.name}]`+JSON.stringify(F.args||{});a+=W.length,i++}else if(typeof G=="object"&&G&&"functionResponse"in G&&G.functionResponse){let R=`[Tool Result: ${G.functionResponse.response?.output||"result"}]`;a+=R.length+20,s++}}else typeof c=="string"&&(a+=c.length,e++);let o=JSON.stringify(r),u=/[\u4e00-\u9fff]/.test(o),d=/```|function|class|import|export|\{|\}|\[|\]/.test(o),I=4;return u?I=2:d&&(I=3),{totalTokens:Math.ceil(a/I)}}catch(r){return console.error("[DeepV Server] Fallback estimation error:",r),{totalTokens:1e3}}}async embedContent(t){throw new Error("Claude models do not support embedding content")}withTimeout(t,r,a){let i=null,s=new Promise((e,o)=>{i=setTimeout(()=>{o(new Error(a))},r)});return Promise.race([t,s]).finally(()=>{i!==null&&clearTimeout(i)})}}});function vSe(n,t){let r=n.getModel()||"auto",a={authType:t,proxy:n?.getProxy()};return t===is.USE_PROXY_AUTH,a}async function ZSe(n,t,r){let i={headers:{"User-Agent":`GeminiCLI/1.0.308 (${process.platform}; ${process.arch})`}};if(!0){let e=t.getCustomProxyServerUrl(),o;if(e)o=e,console.log(`[DeepX] Using custom proxy server: ${o}`);else{if(!tXe())throw new Error("DeepV Code server is required for all models but is not available. Please start the DeepV Code server or use proxy authentication.");o=FW(),console.log(`[DeepX] Connecting to DeepV Code server: ${o}`)}let u=process.env.GOOGLE_CLOUD_LOCATION||"us-central1",d=process.env.GOOGLE_CLOUD_PROJECT||"default-project";return new RJ(u,d,o,t)}throw new Error(`Error creating contentGenerator: Unsupported authType: ${n.authType}`)}var is,wme=ut(()=>{"use strict";gSe();VB();(function(n){n.USE_PROXY_AUTH="proxy-auth"})(is||(is={}))});var Cme,rQt=ut(()=>{"use strict";Cme=class{prompts=new Map;registerPrompt(t){if(this.prompts.has(t.name)){let r=`${t.serverName}_${t.name}`;console.warn(`Prompt with name "${t.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...t,name:r})}else this.prompts.set(t.name,t)}getAllPrompts(){return Array.from(this.prompts.values()).sort((t,r)=>t.name.localeCompare(r.name))}getPrompt(t){return this.prompts.get(t)}getPromptsByServer(t){let r=[];for(let a of this.prompts.values())a.serverName===t&&r.push(a);return r.sort((a,i)=>a.name.localeCompare(i.name))}removePromptsByServer(t){for(let[r,a]of this.prompts.entries())a.serverName===t&&this.prompts.delete(r)}}});function ON(n){let t={type:"subagent_update",data:n,timestamp:Date.now()};return JSON.stringify(t)}function aQt(n){let t={type:"text",data:n,timestamp:Date.now()};return JSON.stringify(t)}function Yme(n){try{let t=JSON.parse(n);if(t&&typeof t=="object"&&t.type&&t.data!==void 0)return t}catch{}return{type:"text",data:n,timestamp:Date.now()}}function xme(n){return n.type==="subagent_update"}function Vme(n){return n.type==="text"}var NSe=ut(()=>{"use strict";});var qr,Mr,$r,Ll=ut(()=>{"use strict";NSe();qr=class{name;displayName;description;icon;parameterSchema;isOutputMarkdown;forceMarkdown;canUpdateOutput;allowSubAgentUse;constructor(t,r,a,i,s,e=!0,o=!1,u=!1,d=!0){this.name=t,this.displayName=r,this.description=a,this.icon=i,this.parameterSchema=s,this.isOutputMarkdown=e,this.forceMarkdown=o,this.canUpdateOutput=u,this.allowSubAgentUse=d}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(t){return null}getDescription(t){return JSON.stringify(t)}shouldConfirmExecute(t,r){return Promise.resolve(!1)}toolLocations(t){return[]}};(function(n){n.ProceedOnce="proceed_once",n.ProceedAlways="proceed_always",n.ProceedAlwaysServer="proceed_always_server",n.ProceedAlwaysTool="proceed_always_tool",n.ProceedAlwaysProject="proceed_always_project",n.ModifyWithEditor="modify_with_editor",n.Cancel="cancel"})(Mr||(Mr={}));(function(n){n.FileSearch="fileSearch",n.Folder="folder",n.Globe="globe",n.Hammer="hammer",n.LightBulb="lightBulb",n.Pencil="pencil",n.Regex="regex",n.Terminal="terminal",n.Clipboard="clipboard",n.Tasks="tasks",n.Wrench="wrench",n.Trash="trash",n.List="list",n.Info="info"})($r||($r={}))});var Sl,ASe,ea,MW,bq=ut(()=>{(function(n){n.assertEqual=i=>{};function t(i){}n.assertIs=t;function r(i){throw new Error}n.assertNever=r,n.arrayToEnum=i=>{let s={};for(let e of i)s[e]=e;return s},n.getValidEnumValues=i=>{let s=n.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),e={};for(let o of s)e[o]=i[o];return n.objectValues(e)},n.objectValues=i=>n.objectKeys(i).map(function(s){return i[s]}),n.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&s.push(e);return s},n.find=(i,s)=>{for(let e of i)if(s(e))return e},n.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function a(i,s=" | "){return i.map(e=>typeof e=="string"?`'${e}'`:e).join(s)}n.joinValues=a,n.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(Sl||(Sl={}));(function(n){n.mergeShapes=(t,r)=>({...t,...r})})(ASe||(ASe={}));ea=Sl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),MW=n=>{switch(typeof n){case"undefined":return ea.undefined;case"string":return ea.string;case"number":return Number.isNaN(n)?ea.nan:ea.number;case"boolean":return ea.boolean;case"function":return ea.function;case"bigint":return ea.bigint;case"symbol":return ea.symbol;case"object":return Array.isArray(n)?ea.array:n===null?ea.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ea.promise:typeof Map<"u"&&n instanceof Map?ea.map:typeof Set<"u"&&n instanceof Set?ea.set:typeof Date<"u"&&n instanceof Date?ea.date:ea.object;default:return ea.unknown}}});var vr,A3r,Gf,Qme=ut(()=>{bq();vr=Sl.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),A3r=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Gf=class n extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(s){return s.message},a={_errors:[]},i=s=>{for(let e of s.issues)if(e.code==="invalid_union")e.unionErrors.map(i);else if(e.code==="invalid_return_type")i(e.returnTypeError);else if(e.code==="invalid_arguments")i(e.argumentsError);else if(e.path.length===0)a._errors.push(r(e));else{let o=a,u=0;for(;u<e.path.length;){let d=e.path[u];u===e.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(r(e))):o[d]=o[d]||{_errors:[]},o=o[d],u++}}};return i(this),a}static assert(t){if(!(t instanceof n))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Sl.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},a=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(t(i))}else a.push(t(i));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}};Gf.create=n=>new Gf(n)});var W3r,$5,WSe=ut(()=>{Qme();bq();W3r=(n,t)=>{let r;switch(n.code){case vr.invalid_type:n.received===ea.undefined?r="Required":r=`Expected ${n.expected}, received ${n.received}`;break;case vr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(n.expected,Sl.jsonStringifyReplacer)}`;break;case vr.unrecognized_keys:r=`Unrecognized key(s) in object: ${Sl.joinValues(n.keys,", ")}`;break;case vr.invalid_union:r="Invalid input";break;case vr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Sl.joinValues(n.options)}`;break;case vr.invalid_enum_value:r=`Invalid enum value. Expected ${Sl.joinValues(n.options)}, received '${n.received}'`;break;case vr.invalid_arguments:r="Invalid function arguments";break;case vr.invalid_return_type:r="Invalid function return type";break;case vr.invalid_date:r="Invalid date";break;case vr.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(r=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?r=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?r=`Invalid input: must end with "${n.validation.endsWith}"`:Sl.assertNever(n.validation):n.validation!=="regex"?r=`Invalid ${n.validation}`:r="Invalid";break;case vr.too_small:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:r="Invalid input";break;case vr.too_big:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?r=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:r="Invalid input";break;case vr.custom:r="Invalid input";break;case vr.invalid_intersection_types:r="Intersection results could not be merged";break;case vr.not_multiple_of:r=`Number must be a multiple of ${n.multipleOf}`;break;case vr.not_finite:r="Number must be finite";break;default:r=t.defaultError,Sl.assertNever(n)}return{message:r}},$5=W3r});function y3r(n){iQt=n}function wJ(){return iQt}var iQt,Hme=ut(()=>{WSe();iQt=$5});function Tr(n,t){let r=wJ(),a=fq({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,r,r===$5?void 0:$5].filter(i=>!!i)});n.common.issues.push(a)}var fq,F3r,hm,ei,_Q,pp,Xme,kme,Lw,CJ,ySe=ut(()=>{Hme();WSe();fq=n=>{let{data:t,path:r,errorMaps:a,issueData:i}=n,s=[...r,...i.path||[]],e={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",u=a.filter(d=>!!d).slice().reverse();for(let d of u)o=d(e,{data:t,defaultError:o}).message;return{...i,path:s,message:o}},F3r=[];hm=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let a=[];for(let i of r){if(i.status==="aborted")return ei;i.status==="dirty"&&t.dirty(),a.push(i.value)}return{status:t.value,value:a}}static async mergeObjectAsync(t,r){let a=[];for(let i of r){let s=await i.key,e=await i.value;a.push({key:s,value:e})}return n.mergeObjectSync(t,a)}static mergeObjectSync(t,r){let a={};for(let i of r){let{key:s,value:e}=i;if(s.status==="aborted"||e.status==="aborted")return ei;s.status==="dirty"&&t.dirty(),e.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof e.value<"u"||i.alwaysSet)&&(a[s.value]=e.value)}return{status:t.value,value:a}}},ei=Object.freeze({status:"aborted"}),_Q=n=>({status:"dirty",value:n}),pp=n=>({status:"valid",value:n}),Xme=n=>n.status==="aborted",kme=n=>n.status==="dirty",Lw=n=>n.status==="valid",CJ=n=>typeof Promise<"u"&&n instanceof Promise});var lQt=ut(()=>{});var Na,sQt=ut(()=>{(function(n){n.errToObj=t=>typeof t=="string"?{message:t}:t||{},n.toString=t=>typeof t=="string"?t:t?.message})(Na||(Na={}))});function _i(n){if(!n)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:i}=n;if(t&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(e,o)=>{let{message:u}=n;return e.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??a??o.defaultError}:e.code!=="invalid_type"?{message:o.defaultError}:{message:u??r??o.defaultError}},description:i}}function IQt(n){let t="[0-5]\\d";n.precision?t=`${t}\\.\\d{${n.precision}}`:n.precision==null&&(t=`${t}(\\.\\d+)?`);let r=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function D3r(n){return new RegExp(`^${IQt(n)}$`)}function dQt(n){let t=`${uQt}T${IQt(n)}`,r=[];return r.push(n.local?"Z?":"Z"),n.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function O3r(n,t){return!!((t==="v4"||!t)&&X3r.test(n)||(t==="v6"||!t)&&L3r.test(n))}function U3r(n,t){if(!x3r.test(n))return!1;try{let[r]=n.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(a));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function M3r(n,t){return!!((t==="v4"||!t)&&k3r.test(n)||(t==="v6"||!t)&&S3r.test(n))}function z3r(n,t){let r=(n.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a,s=Number.parseInt(n.toFixed(i).replace(".","")),e=Number.parseInt(t.toFixed(i).replace(".",""));return s%e/10**i}function YJ(n){if(n instanceof gf){let t={};for(let r in n.shape){let a=n.shape[r];t[r]=fv.create(YJ(a))}return new gf({...n._def,shape:()=>t})}else return n instanceof nE?new nE({...n._def,type:YJ(n.element)}):n instanceof fv?fv.create(YJ(n.unwrap())):n instanceof _W?_W.create(YJ(n.unwrap())):n instanceof zW?zW.create(n.items.map(t=>YJ(t))):n}function ESe(n,t){let r=MW(n),a=MW(t);if(n===t)return{valid:!0,data:n};if(r===ea.object&&a===ea.object){let i=Sl.objectKeys(t),s=Sl.objectKeys(n).filter(o=>i.indexOf(o)!==-1),e={...n,...t};for(let o of s){let u=ESe(n[o],t[o]);if(!u.valid)return{valid:!1};e[o]=u.data}return{valid:!0,data:e}}else if(r===ea.array&&a===ea.array){if(n.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<n.length;s++){let e=n[s],o=t[s],u=ESe(e,o);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===ea.date&&a===ea.date&&+n==+t?{valid:!0,data:n}:{valid:!1}}function hQt(n,t){return new i9({values:n,typeName:li.ZodEnum,..._i(t)})}function cQt(n,t){let r=typeof n=="function"?n(t):typeof n=="string"?{message:n}:n;return typeof r=="string"?{message:r}:r}function mQt(n,t={},r){return n?Bw.create().superRefine((a,i)=>{let s=n(a);if(s instanceof Promise)return s.then(e=>{if(!e){let o=cQt(t,a),u=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:u})}});if(!s){let e=cQt(t,a),o=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:o})}}):Bw.create()}var Gv,oQt,ol,E3r,R3r,w3r,C3r,Y3r,x3r,V3r,Q3r,H3r,FSe,X3r,k3r,L3r,S3r,B3r,J3r,uQt,T3r,Sw,PQ,jQ,KQ,qQ,xJ,$Q,e9,Bw,tE,UN,VJ,nE,gf,t9,eE,Lme,n9,zW,Sme,QJ,HJ,Bme,r9,a9,i9,l9,Jw,gv,fv,_W,s9,o9,XJ,_3r,Gq,gq,c9,P3r,li,j3r,pQt,bQt,K3r,q3r,fQt,$3r,eWr,tWr,nWr,rWr,aWr,iWr,lWr,sWr,oWr,cWr,uWr,IWr,dWr,hWr,mWr,pWr,bWr,fWr,GWr,gWr,vWr,ZWr,NWr,AWr,WWr,yWr,FWr,EWr,RWr,wWr,CWr,YWr,xWr,GQt=ut(()=>{Qme();Hme();sQt();ySe();bq();Gv=class{constructor(t,r,a,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=a,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},oQt=(n,t)=>{if(Lw(t))return{success:!0,data:t.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Gf(n.common.issues);return this._error=r,this._error}}};ol=class{get description(){return this._def.description}_getType(t){return MW(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:MW(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new hm,ctx:{common:t.parent.common,data:t.data,parsedType:MW(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(CJ(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let a=this.safeParse(t,r);if(a.success)return a.data;throw a.error}safeParse(t,r){let a={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:MW(t)},i=this._parseSync({data:t,path:a.path,parent:a});return oQt(a,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:MW(t)};if(!this["~standard"].async)try{let a=this._parseSync({data:t,path:[],parent:r});return Lw(a)?{value:a.value}:{issues:r.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(a=>Lw(a)?{value:a.value}:{issues:r.common.issues})}async parseAsync(t,r){let a=await this.safeParseAsync(t,r);if(a.success)return a.data;throw a.error}async safeParseAsync(t,r){let a={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:MW(t)},i=this._parse({data:t,path:a.path,parent:a}),s=await(CJ(i)?i:Promise.resolve(i));return oQt(a,s)}refine(t,r){let a=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let e=t(i),o=()=>s.addIssue({code:vr.custom,...a(i)});return typeof Promise<"u"&&e instanceof Promise?e.then(u=>u?!0:(o(),!1)):e?!0:(o(),!1)})}refinement(t,r){return this._refinement((a,i)=>t(a)?!0:(i.addIssue(typeof r=="function"?r(a,i):r),!1))}_refinement(t){return new gv({schema:this,typeName:li.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return fv.create(this,this._def)}nullable(){return _W.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nE.create(this)}promise(){return Jw.create(this,this._def)}or(t){return t9.create([this,t],this._def)}and(t){return n9.create(this,t,this._def)}transform(t){return new gv({..._i(this._def),schema:this,typeName:li.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new s9({..._i(this._def),innerType:this,defaultValue:r,typeName:li.ZodDefault})}brand(){return new Gq({typeName:li.ZodBranded,type:this,..._i(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new o9({..._i(this._def),innerType:this,catchValue:r,typeName:li.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return gq.create(this,t)}readonly(){return c9.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},E3r=/^c[^\s-]{8,}$/i,R3r=/^[0-9a-z]+$/,w3r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C3r=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Y3r=/^[a-z0-9_-]{21}$/i,x3r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,V3r=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Q3r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,H3r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",X3r=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,k3r=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,L3r=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,S3r=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,B3r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,J3r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uQt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",T3r=new RegExp(`^${uQt}$`);Sw=class n extends ol{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ea.string){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_type,expected:ea.string,received:s.parsedType}),ei}let a=new hm,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){let e=t.data.length>s.value,o=t.data.length<s.value;(e||o)&&(i=this._getOrReturnCtx(t,i),e?Tr(i,{code:vr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&Tr(i,{code:vr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")Q3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"email",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")FSe||(FSe=new RegExp(H3r,"u")),FSe.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"emoji",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")C3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"uuid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")Y3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"nanoid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")E3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"cuid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")R3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"cuid2",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")w3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"ulid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Tr(i,{validation:"url",code:vr.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"regex",code:vr.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?dQt(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?T3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?D3r(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?V3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"duration",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?O3r(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"ip",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?U3r(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"jwt",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?M3r(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"cidr",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?B3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"base64",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?J3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"base64url",code:vr.invalid_string,message:s.message}),a.dirty()):Sl.assertNever(s);return{status:a.value,value:t.data}}_regex(t,r,a){return this.refinement(i=>t.test(i),{validation:r,code:vr.invalid_string,...Na.errToObj(a)})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Na.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Na.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Na.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Na.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Na.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Na.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Na.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Na.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Na.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Na.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Na.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Na.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Na.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...Na.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Na.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Na.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Na.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Na.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Na.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Na.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Na.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Na.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Na.errToObj(r)})}nonempty(t){return this.min(1,Na.errToObj(t))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Sw.create=n=>new Sw({checks:[],typeName:li.ZodString,coerce:n?.coerce??!1,..._i(n)});PQ=class n extends ol{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ea.number){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_type,expected:ea.number,received:s.parsedType}),ei}let a,i=new hm;for(let s of this._def.checks)s.kind==="int"?Sl.isInteger(t.data)||(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?z3r(t.data,s.value)!==0&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.not_finite,message:s.message}),i.dirty()):Sl.assertNever(s);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Na.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Na.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Na.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Na.toString(r))}setLimit(t,r,a,i){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:a,message:Na.toString(i)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Na.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Na.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Na.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Na.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Na.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Na.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Na.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Na.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Na.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Sl.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(t===null||a.value<t)&&(t=a.value)}return Number.isFinite(r)&&Number.isFinite(t)}};PQ.create=n=>new PQ({checks:[],typeName:li.ZodNumber,coerce:n?.coerce||!1,..._i(n)});jQ=class n extends ol{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ea.bigint)return this._getInvalidInput(t);let a,i=new hm;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Sl.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Tr(r,{code:vr.invalid_type,expected:ea.bigint,received:r.parsedType}),ei}gte(t,r){return this.setLimit("min",t,!0,Na.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Na.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Na.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Na.toString(r))}setLimit(t,r,a,i){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:a,message:Na.toString(i)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Na.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Na.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Na.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Na.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Na.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};jQ.create=n=>new jQ({checks:[],typeName:li.ZodBigInt,coerce:n?.coerce??!1,..._i(n)});KQ=class extends ol{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ea.boolean){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.boolean,received:a.parsedType}),ei}return pp(t.data)}};KQ.create=n=>new KQ({typeName:li.ZodBoolean,coerce:n?.coerce||!1,..._i(n)});qQ=class n extends ol{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ea.date){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_type,expected:ea.date,received:s.parsedType}),ei}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_date}),ei}let a=new hm,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):Sl.assertNever(s);return{status:a.value,value:new Date(t.data.getTime())}}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Na.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Na.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};qQ.create=n=>new qQ({checks:[],coerce:n?.coerce||!1,typeName:li.ZodDate,..._i(n)});xJ=class extends ol{_parse(t){if(this._getType(t)!==ea.symbol){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.symbol,received:a.parsedType}),ei}return pp(t.data)}};xJ.create=n=>new xJ({typeName:li.ZodSymbol,..._i(n)});$Q=class extends ol{_parse(t){if(this._getType(t)!==ea.undefined){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.undefined,received:a.parsedType}),ei}return pp(t.data)}};$Q.create=n=>new $Q({typeName:li.ZodUndefined,..._i(n)});e9=class extends ol{_parse(t){if(this._getType(t)!==ea.null){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.null,received:a.parsedType}),ei}return pp(t.data)}};e9.create=n=>new e9({typeName:li.ZodNull,..._i(n)});Bw=class extends ol{constructor(){super(...arguments),this._any=!0}_parse(t){return pp(t.data)}};Bw.create=n=>new Bw({typeName:li.ZodAny,..._i(n)});tE=class extends ol{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pp(t.data)}};tE.create=n=>new tE({typeName:li.ZodUnknown,..._i(n)});UN=class extends ol{_parse(t){let r=this._getOrReturnCtx(t);return Tr(r,{code:vr.invalid_type,expected:ea.never,received:r.parsedType}),ei}};UN.create=n=>new UN({typeName:li.ZodNever,..._i(n)});VJ=class extends ol{_parse(t){if(this._getType(t)!==ea.undefined){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.void,received:a.parsedType}),ei}return pp(t.data)}};VJ.create=n=>new VJ({typeName:li.ZodVoid,..._i(n)});nE=class n extends ol{_parse(t){let{ctx:r,status:a}=this._processInputParams(t),i=this._def;if(r.parsedType!==ea.array)return Tr(r,{code:vr.invalid_type,expected:ea.array,received:r.parsedType}),ei;if(i.exactLength!==null){let e=r.data.length>i.exactLength.value,o=r.data.length<i.exactLength.value;(e||o)&&(Tr(r,{code:e?vr.too_big:vr.too_small,minimum:o?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),a.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Tr(r,{code:vr.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),a.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Tr(r,{code:vr.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((e,o)=>i.type._parseAsync(new Gv(r,e,r.path,o)))).then(e=>hm.mergeArray(a,e));let s=[...r.data].map((e,o)=>i.type._parseSync(new Gv(r,e,r.path,o)));return hm.mergeArray(a,s)}get element(){return this._def.type}min(t,r){return new n({...this._def,minLength:{value:t,message:Na.toString(r)}})}max(t,r){return new n({...this._def,maxLength:{value:t,message:Na.toString(r)}})}length(t,r){return new n({...this._def,exactLength:{value:t,message:Na.toString(r)}})}nonempty(t){return this.min(1,t)}};nE.create=(n,t)=>new nE({type:n,minLength:null,maxLength:null,exactLength:null,typeName:li.ZodArray,..._i(t)});gf=class n extends ol{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Sl.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ea.object){let d=this._getOrReturnCtx(t);return Tr(d,{code:vr.invalid_type,expected:ea.object,received:d.parsedType}),ei}let{status:a,ctx:i}=this._processInputParams(t),{shape:s,keys:e}=this._getCached(),o=[];if(!(this._def.catchall instanceof UN&&this._def.unknownKeys==="strip"))for(let d in i.data)e.includes(d)||o.push(d);let u=[];for(let d of e){let I=s[d],h=i.data[d];u.push({key:{status:"valid",value:d},value:I._parse(new Gv(i,h,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof UN){let d=this._def.unknownKeys;if(d==="passthrough")for(let I of o)u.push({key:{status:"valid",value:I},value:{status:"valid",value:i.data[I]}});else if(d==="strict")o.length>0&&(Tr(i,{code:vr.unrecognized_keys,keys:o}),a.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let I of o){let h=i.data[I];u.push({key:{status:"valid",value:I},value:d._parse(new Gv(i,h,i.path,I)),alwaysSet:I in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let I of u){let h=await I.key,c=await I.value;d.push({key:h,value:c,alwaysSet:I.alwaysSet})}return d}).then(d=>hm.mergeObjectSync(a,d)):hm.mergeObjectSync(a,u)}get shape(){return this._def.shape()}strict(t){return Na.errToObj,new n({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,a)=>{let i=this._def.errorMap?.(r,a).message??a.defaultError;return r.code==="unrecognized_keys"?{message:Na.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(t){return new n({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new n({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:li.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new n({...this._def,catchall:t})}pick(t){let r={};for(let a of Sl.objectKeys(t))t[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new n({...this._def,shape:()=>r})}omit(t){let r={};for(let a of Sl.objectKeys(this.shape))t[a]||(r[a]=this.shape[a]);return new n({...this._def,shape:()=>r})}deepPartial(){return YJ(this)}partial(t){let r={};for(let a of Sl.objectKeys(this.shape)){let i=this.shape[a];t&&!t[a]?r[a]=i:r[a]=i.optional()}return new n({...this._def,shape:()=>r})}required(t){let r={};for(let a of Sl.objectKeys(this.shape))if(t&&!t[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof fv;)s=s._def.innerType;r[a]=s}return new n({...this._def,shape:()=>r})}keyof(){return hQt(Sl.objectKeys(this.shape))}};gf.create=(n,t)=>new gf({shape:()=>n,unknownKeys:"strip",catchall:UN.create(),typeName:li.ZodObject,..._i(t)});gf.strictCreate=(n,t)=>new gf({shape:()=>n,unknownKeys:"strict",catchall:UN.create(),typeName:li.ZodObject,..._i(t)});gf.lazycreate=(n,t)=>new gf({shape:n,unknownKeys:"strip",catchall:UN.create(),typeName:li.ZodObject,..._i(t)});t9=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a=this._def.options;function i(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let e=s.map(o=>new Gf(o.ctx.common.issues));return Tr(r,{code:vr.invalid_union,unionErrors:e}),ei}if(r.common.async)return Promise.all(a.map(async s=>{let e={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:e}),ctx:e}})).then(i);{let s,e=[];for(let u of a){let d={...r,common:{...r.common,issues:[]},parent:null},I=u._parseSync({data:r.data,path:r.path,parent:d});if(I.status==="valid")return I;I.status==="dirty"&&!s&&(s={result:I,ctx:d}),d.common.issues.length&&e.push(d.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=e.map(u=>new Gf(u));return Tr(r,{code:vr.invalid_union,unionErrors:o}),ei}}get options(){return this._def.options}};t9.create=(n,t)=>new t9({options:n,typeName:li.ZodUnion,..._i(t)});eE=n=>n instanceof r9?eE(n.schema):n instanceof gv?eE(n.innerType()):n instanceof a9?[n.value]:n instanceof i9?n.options:n instanceof l9?Sl.objectValues(n.enum):n instanceof s9?eE(n._def.innerType):n instanceof $Q?[void 0]:n instanceof e9?[null]:n instanceof fv?[void 0,...eE(n.unwrap())]:n instanceof _W?[null,...eE(n.unwrap())]:n instanceof Gq||n instanceof c9?eE(n.unwrap()):n instanceof o9?eE(n._def.innerType):[],Lme=class n extends ol{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ea.object)return Tr(r,{code:vr.invalid_type,expected:ea.object,received:r.parsedType}),ei;let a=this.discriminator,i=r.data[a],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Tr(r,{code:vr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),ei)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,a){let i=new Map;for(let s of r){let e=eE(s.shape[t]);if(!e.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of e){if(i.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);i.set(o,s)}}return new n({typeName:li.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,..._i(a)})}};n9=class extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t),i=(s,e)=>{if(Xme(s)||Xme(e))return ei;let o=ESe(s.value,e.value);return o.valid?((kme(s)||kme(e))&&r.dirty(),{status:r.value,value:o.data}):(Tr(a,{code:vr.invalid_intersection_types}),ei)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,e])=>i(s,e)):i(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};n9.create=(n,t,r)=>new n9({left:n,right:t,typeName:li.ZodIntersection,..._i(r)});zW=class n extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.array)return Tr(a,{code:vr.invalid_type,expected:ea.array,received:a.parsedType}),ei;if(a.data.length<this._def.items.length)return Tr(a,{code:vr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ei;!this._def.rest&&a.data.length>this._def.items.length&&(Tr(a,{code:vr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...a.data].map((e,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new Gv(a,e,a.path,o)):null}).filter(e=>!!e);return a.common.async?Promise.all(s).then(e=>hm.mergeArray(r,e)):hm.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new n({...this._def,rest:t})}};zW.create=(n,t)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new zW({items:n,typeName:li.ZodTuple,rest:null,..._i(t)})};Sme=class n extends ol{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.object)return Tr(a,{code:vr.invalid_type,expected:ea.object,received:a.parsedType}),ei;let i=[],s=this._def.keyType,e=this._def.valueType;for(let o in a.data)i.push({key:s._parse(new Gv(a,o,a.path,o)),value:e._parse(new Gv(a,a.data[o],a.path,o)),alwaysSet:o in a.data});return a.common.async?hm.mergeObjectAsync(r,i):hm.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,a){return r instanceof ol?new n({keyType:t,valueType:r,typeName:li.ZodRecord,..._i(a)}):new n({keyType:Sw.create(),valueType:t,typeName:li.ZodRecord,..._i(r)})}},QJ=class extends ol{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.map)return Tr(a,{code:vr.invalid_type,expected:ea.map,received:a.parsedType}),ei;let i=this._def.keyType,s=this._def.valueType,e=[...a.data.entries()].map(([o,u],d)=>({key:i._parse(new Gv(a,o,a.path,[d,"key"])),value:s._parse(new Gv(a,u,a.path,[d,"value"]))}));if(a.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of e){let d=await u.key,I=await u.value;if(d.status==="aborted"||I.status==="aborted")return ei;(d.status==="dirty"||I.status==="dirty")&&r.dirty(),o.set(d.value,I.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let u of e){let d=u.key,I=u.value;if(d.status==="aborted"||I.status==="aborted")return ei;(d.status==="dirty"||I.status==="dirty")&&r.dirty(),o.set(d.value,I.value)}return{status:r.value,value:o}}}};QJ.create=(n,t,r)=>new QJ({valueType:t,keyType:n,typeName:li.ZodMap,..._i(r)});HJ=class n extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.set)return Tr(a,{code:vr.invalid_type,expected:ea.set,received:a.parsedType}),ei;let i=this._def;i.minSize!==null&&a.data.size<i.minSize.value&&(Tr(a,{code:vr.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&a.data.size>i.maxSize.value&&(Tr(a,{code:vr.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function e(u){let d=new Set;for(let I of u){if(I.status==="aborted")return ei;I.status==="dirty"&&r.dirty(),d.add(I.value)}return{status:r.value,value:d}}let o=[...a.data.values()].map((u,d)=>s._parse(new Gv(a,u,a.path,d)));return a.common.async?Promise.all(o).then(u=>e(u)):e(o)}min(t,r){return new n({...this._def,minSize:{value:t,message:Na.toString(r)}})}max(t,r){return new n({...this._def,maxSize:{value:t,message:Na.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};HJ.create=(n,t)=>new HJ({valueType:n,minSize:null,maxSize:null,typeName:li.ZodSet,..._i(t)});Bme=class n extends ol{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ea.function)return Tr(r,{code:vr.invalid_type,expected:ea.function,received:r.parsedType}),ei;function a(o,u){return fq({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wJ(),$5].filter(d=>!!d),issueData:{code:vr.invalid_arguments,argumentsError:u}})}function i(o,u){return fq({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wJ(),$5].filter(d=>!!d),issueData:{code:vr.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},e=r.data;if(this._def.returns instanceof Jw){let o=this;return pp(async function(...u){let d=new Gf([]),I=await o._def.args.parseAsync(u,s).catch(G=>{throw d.addIssue(a(u,G)),d}),h=await Reflect.apply(e,this,I);return await o._def.returns._def.type.parseAsync(h,s).catch(G=>{throw d.addIssue(i(h,G)),d})})}else{let o=this;return pp(function(...u){let d=o._def.args.safeParse(u,s);if(!d.success)throw new Gf([a(u,d.error)]);let I=Reflect.apply(e,this,d.data),h=o._def.returns.safeParse(I,s);if(!h.success)throw new Gf([i(I,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new n({...this._def,args:zW.create(t).rest(tE.create())})}returns(t){return new n({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,a){return new n({args:t||zW.create([]).rest(tE.create()),returns:r||tE.create(),typeName:li.ZodFunction,..._i(a)})}},r9=class extends ol{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};r9.create=(n,t)=>new r9({getter:n,typeName:li.ZodLazy,..._i(t)});a9=class extends ol{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Tr(r,{received:r.data,code:vr.invalid_literal,expected:this._def.value}),ei}return{status:"valid",value:t.data}}get value(){return this._def.value}};a9.create=(n,t)=>new a9({value:n,typeName:li.ZodLiteral,..._i(t)});i9=class n extends ol{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),a=this._def.values;return Tr(r,{expected:Sl.joinValues(a),received:r.parsedType,code:vr.invalid_type}),ei}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),a=this._def.values;return Tr(r,{received:r.data,code:vr.invalid_enum_value,options:a}),ei}return pp(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return n.create(t,{...this._def,...r})}exclude(t,r=this._def){return n.create(this.options.filter(a=>!t.includes(a)),{...this._def,...r})}};i9.create=hQt;l9=class extends ol{_parse(t){let r=Sl.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(t);if(a.parsedType!==ea.string&&a.parsedType!==ea.number){let i=Sl.objectValues(r);return Tr(a,{expected:Sl.joinValues(i),received:a.parsedType,code:vr.invalid_type}),ei}if(this._cache||(this._cache=new Set(Sl.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Sl.objectValues(r);return Tr(a,{received:a.data,code:vr.invalid_enum_value,options:i}),ei}return pp(t.data)}get enum(){return this._def.values}};l9.create=(n,t)=>new l9({values:n,typeName:li.ZodNativeEnum,..._i(t)});Jw=class extends ol{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ea.promise&&r.common.async===!1)return Tr(r,{code:vr.invalid_type,expected:ea.promise,received:r.parsedType}),ei;let a=r.parsedType===ea.promise?r.data:Promise.resolve(r.data);return pp(a.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Jw.create=(n,t)=>new Jw({type:n,typeName:li.ZodPromise,..._i(t)});gv=class extends ol{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===li.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:a}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:e=>{Tr(a,e),e.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let e=i.transform(a.data,s);if(a.common.async)return Promise.resolve(e).then(async o=>{if(r.value==="aborted")return ei;let u=await this._def.schema._parseAsync({data:o,path:a.path,parent:a});return u.status==="aborted"?ei:u.status==="dirty"?_Q(u.value):r.value==="dirty"?_Q(u.value):u});{if(r.value==="aborted")return ei;let o=this._def.schema._parseSync({data:e,path:a.path,parent:a});return o.status==="aborted"?ei:o.status==="dirty"?_Q(o.value):r.value==="dirty"?_Q(o.value):o}}if(i.type==="refinement"){let e=o=>{let u=i.refinement(o,s);if(a.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(a.common.async===!1){let o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return o.status==="aborted"?ei:(o.status==="dirty"&&r.dirty(),e(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>o.status==="aborted"?ei:(o.status==="dirty"&&r.dirty(),e(o.value).then(()=>({status:r.value,value:o.value}))))}if(i.type==="transform")if(a.common.async===!1){let e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!Lw(e))return ei;let o=i.transform(e.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(e=>Lw(e)?Promise.resolve(i.transform(e.value,s)).then(o=>({status:r.value,value:o})):ei);Sl.assertNever(i)}};gv.create=(n,t,r)=>new gv({schema:n,typeName:li.ZodEffects,effect:t,..._i(r)});gv.createWithPreprocess=(n,t,r)=>new gv({schema:t,effect:{type:"preprocess",transform:n},typeName:li.ZodEffects,..._i(r)});fv=class extends ol{_parse(t){return this._getType(t)===ea.undefined?pp(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};fv.create=(n,t)=>new fv({innerType:n,typeName:li.ZodOptional,..._i(t)});_W=class extends ol{_parse(t){return this._getType(t)===ea.null?pp(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_W.create=(n,t)=>new _W({innerType:n,typeName:li.ZodNullable,..._i(t)});s9=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a=r.data;return r.parsedType===ea.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};s9.create=(n,t)=>new s9({innerType:n,typeName:li.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,..._i(t)});o9=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return CJ(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Gf(a.common.issues)},input:a.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Gf(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};o9.create=(n,t)=>new o9({innerType:n,typeName:li.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,..._i(t)});XJ=class extends ol{_parse(t){if(this._getType(t)!==ea.nan){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.nan,received:a.parsedType}),ei}return{status:"valid",value:t.data}}};XJ.create=n=>new XJ({typeName:li.ZodNaN,..._i(n)});_3r=Symbol("zod_brand"),Gq=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}},gq=class n extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?ei:s.status==="dirty"?(r.dirty(),_Q(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{let i=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?ei:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:a.path,parent:a})}}static create(t,r){return new n({in:t,out:r,typeName:li.ZodPipeline})}},c9=class extends ol{_parse(t){let r=this._def.innerType._parse(t),a=i=>(Lw(i)&&(i.value=Object.freeze(i.value)),i);return CJ(r)?r.then(i=>a(i)):a(r)}unwrap(){return this._def.innerType}};c9.create=(n,t)=>new c9({innerType:n,typeName:li.ZodReadonly,..._i(t)});P3r={object:gf.lazycreate};(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(li||(li={}));j3r=(n,t={message:`Input not instance of ${n.name}`})=>mQt(r=>r instanceof n,t),pQt=Sw.create,bQt=PQ.create,K3r=XJ.create,q3r=jQ.create,fQt=KQ.create,$3r=qQ.create,eWr=xJ.create,tWr=$Q.create,nWr=e9.create,rWr=Bw.create,aWr=tE.create,iWr=UN.create,lWr=VJ.create,sWr=nE.create,oWr=gf.create,cWr=gf.strictCreate,uWr=t9.create,IWr=Lme.create,dWr=n9.create,hWr=zW.create,mWr=Sme.create,pWr=QJ.create,bWr=HJ.create,fWr=Bme.create,GWr=r9.create,gWr=a9.create,vWr=i9.create,ZWr=l9.create,NWr=Jw.create,AWr=gv.create,WWr=fv.create,yWr=_W.create,FWr=gv.createWithPreprocess,EWr=gq.create,RWr=()=>pQt().optional(),wWr=()=>bQt().optional(),CWr=()=>fQt().optional(),YWr={string:(n=>Sw.create({...n,coerce:!0})),number:(n=>PQ.create({...n,coerce:!0})),boolean:(n=>KQ.create({...n,coerce:!0})),bigint:(n=>jQ.create({...n,coerce:!0})),date:(n=>qQ.create({...n,coerce:!0}))},xWr=ei});var ju={};Lo(ju,{BRAND:()=>_3r,DIRTY:()=>_Q,EMPTY_PATH:()=>F3r,INVALID:()=>ei,NEVER:()=>xWr,OK:()=>pp,ParseStatus:()=>hm,Schema:()=>ol,ZodAny:()=>Bw,ZodArray:()=>nE,ZodBigInt:()=>jQ,ZodBoolean:()=>KQ,ZodBranded:()=>Gq,ZodCatch:()=>o9,ZodDate:()=>qQ,ZodDefault:()=>s9,ZodDiscriminatedUnion:()=>Lme,ZodEffects:()=>gv,ZodEnum:()=>i9,ZodError:()=>Gf,ZodFirstPartyTypeKind:()=>li,ZodFunction:()=>Bme,ZodIntersection:()=>n9,ZodIssueCode:()=>vr,ZodLazy:()=>r9,ZodLiteral:()=>a9,ZodMap:()=>QJ,ZodNaN:()=>XJ,ZodNativeEnum:()=>l9,ZodNever:()=>UN,ZodNull:()=>e9,ZodNullable:()=>_W,ZodNumber:()=>PQ,ZodObject:()=>gf,ZodOptional:()=>fv,ZodParsedType:()=>ea,ZodPipeline:()=>gq,ZodPromise:()=>Jw,ZodReadonly:()=>c9,ZodRecord:()=>Sme,ZodSchema:()=>ol,ZodSet:()=>HJ,ZodString:()=>Sw,ZodSymbol:()=>xJ,ZodTransformer:()=>gv,ZodTuple:()=>zW,ZodType:()=>ol,ZodUndefined:()=>$Q,ZodUnion:()=>t9,ZodUnknown:()=>tE,ZodVoid:()=>VJ,addIssueToContext:()=>Tr,any:()=>rWr,array:()=>sWr,bigint:()=>q3r,boolean:()=>fQt,coerce:()=>YWr,custom:()=>mQt,date:()=>$3r,datetimeRegex:()=>dQt,defaultErrorMap:()=>$5,discriminatedUnion:()=>IWr,effect:()=>AWr,enum:()=>vWr,function:()=>fWr,getErrorMap:()=>wJ,getParsedType:()=>MW,instanceof:()=>j3r,intersection:()=>dWr,isAborted:()=>Xme,isAsync:()=>CJ,isDirty:()=>kme,isValid:()=>Lw,late:()=>P3r,lazy:()=>GWr,literal:()=>gWr,makeIssue:()=>fq,map:()=>pWr,nan:()=>K3r,nativeEnum:()=>ZWr,never:()=>iWr,null:()=>nWr,nullable:()=>yWr,number:()=>bQt,object:()=>oWr,objectUtil:()=>ASe,oboolean:()=>CWr,onumber:()=>wWr,optional:()=>WWr,ostring:()=>RWr,pipeline:()=>EWr,preprocess:()=>FWr,promise:()=>NWr,quotelessJson:()=>A3r,record:()=>mWr,set:()=>bWr,setErrorMap:()=>y3r,strictObject:()=>cWr,string:()=>pQt,symbol:()=>eWr,transformer:()=>AWr,tuple:()=>hWr,undefined:()=>tWr,union:()=>uWr,unknown:()=>aWr,util:()=>Sl,void:()=>lWr});var RSe=ut(()=>{Hme();ySe();lQt();bq();GQt();Qme()});function Tn(n,t,r){function a(o,u){var d;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(d=o._zod).traits??(d.traits=new Set),o._zod.traits.add(n),t(o,u);for(let I in e.prototype)I in o||Object.defineProperty(o,I,{value:e.prototype[I].bind(o)});o._zod.constr=e,o._zod.def=u}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:n});function e(o){var u;let d=r?.Parent?new s:this;a(d,o),(u=d._zod).deferred??(u.deferred=[]);for(let I of d._zod.deferred)I();return d}return Object.defineProperty(e,"init",{value:a}),Object.defineProperty(e,Symbol.hasInstance,{value:o=>r?.Parent&&o instanceof r.Parent?!0:o?._zod?.traits?.has(n)}),Object.defineProperty(e,"name",{value:n}),e}function l1(n){return n&&Object.assign(Jme,n),Jme}var wSe,VWr,rE,Jme,kJ=ut(()=>{wSe=Object.freeze({status:"aborted"});VWr=Symbol("zod_brand"),rE=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jme={}});var _s={};Lo(_s,{BIGINT_FORMAT_RANGES:()=>vQt,Class:()=>YSe,NUMBER_FORMAT_RANGES:()=>SSe,aborted:()=>I9,allowsEval:()=>XSe,assert:()=>LWr,assertEqual:()=>QWr,assertIs:()=>XWr,assertNever:()=>kWr,assertNotEqual:()=>HWr,assignProp:()=>HSe,cached:()=>Zq,captureStackTrace:()=>Dme,cleanEnum:()=>KWr,cleanRegex:()=>Aq,clone:()=>MN,createTransparentProxy:()=>OWr,defineLazy:()=>Qc,esc:()=>u9,escapeRegex:()=>Tw,extend:()=>zWr,finalizeIssue:()=>zN,floatSafeRemainder:()=>QSe,getElementAtPath:()=>SWr,getEnumValues:()=>xSe,getLengthableOrigin:()=>Wq,getParsedType:()=>DWr,getSizableOrigin:()=>ZQt,isObject:()=>LJ,isPlainObject:()=>SJ,issue:()=>BSe,joinValues:()=>Tme,jsonStringifyReplacer:()=>VSe,merge:()=>_Wr,normalizeParams:()=>ka,nullish:()=>Nq,numKeys:()=>TWr,omit:()=>MWr,optionalKeys:()=>LSe,partial:()=>PWr,pick:()=>UWr,prefixIssues:()=>PW,primitiveTypes:()=>gQt,promiseAllObject:()=>BWr,propertyKeyTypes:()=>kSe,randomString:()=>JWr,required:()=>jWr,stringifyPrimitive:()=>Ome,unwrapMessage:()=>vq});function QWr(n){return n}function HWr(n){return n}function XWr(n){}function kWr(n){throw new Error}function LWr(n){}function xSe(n){let t=Object.values(n).filter(a=>typeof a=="number");return Object.entries(n).filter(([a,i])=>t.indexOf(+a)===-1).map(([a,i])=>i)}function Tme(n,t="|"){return n.map(r=>Ome(r)).join(t)}function VSe(n,t){return typeof t=="bigint"?t.toString():t}function Zq(n){return{get value(){{let r=n();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Nq(n){return n==null}function Aq(n){let t=n.startsWith("^")?1:0,r=n.endsWith("$")?n.length-1:n.length;return n.slice(t,r)}function QSe(n,t){let r=(n.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a,s=Number.parseInt(n.toFixed(i).replace(".","")),e=Number.parseInt(t.toFixed(i).replace(".",""));return s%e/10**i}function Qc(n,t,r){Object.defineProperty(n,t,{get(){{let i=r();return n[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(n,t,{value:i})},configurable:!0})}function HSe(n,t,r){Object.defineProperty(n,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function SWr(n,t){return t?t.reduce((r,a)=>r?.[a],n):n}function BWr(n){let t=Object.keys(n),r=t.map(a=>n[a]);return Promise.all(r).then(a=>{let i={};for(let s=0;s<t.length;s++)i[t[s]]=a[s];return i})}function JWr(n=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let a=0;a<n;a++)r+=t[Math.floor(Math.random()*t.length)];return r}function u9(n){return JSON.stringify(n)}function LJ(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function SJ(n){if(LJ(n)===!1)return!1;let t=n.constructor;if(t===void 0)return!0;let r=t.prototype;return!(LJ(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function TWr(n){let t=0;for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&t++;return t}function Tw(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function MN(n,t,r){let a=new n._zod.constr(t??n._zod.def);return(!t||r?.parent)&&(a._zod.parent=n),a}function ka(n){let t=n;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function OWr(n){let t;return new Proxy({},{get(r,a,i){return t??(t=n()),Reflect.get(t,a,i)},set(r,a,i,s){return t??(t=n()),Reflect.set(t,a,i,s)},has(r,a){return t??(t=n()),Reflect.has(t,a)},deleteProperty(r,a){return t??(t=n()),Reflect.deleteProperty(t,a)},ownKeys(r){return t??(t=n()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,a){return t??(t=n()),Reflect.getOwnPropertyDescriptor(t,a)},defineProperty(r,a,i){return t??(t=n()),Reflect.defineProperty(t,a,i)}})}function Ome(n){return typeof n=="bigint"?n.toString()+"n":typeof n=="string"?`"${n}"`:`${n}`}function LSe(n){return Object.keys(n).filter(t=>n[t]._zod.optin==="optional"&&n[t]._zod.optout==="optional")}function UWr(n,t){let r={},a=n._zod.def;for(let i in t){if(!(i in a.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=a.shape[i])}return MN(n,{...n._zod.def,shape:r,checks:[]})}function MWr(n,t){let r={...n._zod.def.shape},a=n._zod.def;for(let i in t){if(!(i in a.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return MN(n,{...n._zod.def,shape:r,checks:[]})}function zWr(n,t){if(!SJ(t))throw new Error("Invalid input to extend: expected a plain object");let r={...n._zod.def,get shape(){let a={...n._zod.def.shape,...t};return HSe(this,"shape",a),a},checks:[]};return MN(n,r)}function _Wr(n,t){return MN(n,{...n._zod.def,get shape(){let r={...n._zod.def.shape,...t._zod.def.shape};return HSe(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function PWr(n,t,r){let a=t._zod.def.shape,i={...a};if(r)for(let s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=n?new n({type:"optional",innerType:a[s]}):a[s])}else for(let s in a)i[s]=n?new n({type:"optional",innerType:a[s]}):a[s];return MN(t,{...t._zod.def,shape:i,checks:[]})}function jWr(n,t,r){let a=t._zod.def.shape,i={...a};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new n({type:"nonoptional",innerType:a[s]}))}else for(let s in a)i[s]=new n({type:"nonoptional",innerType:a[s]});return MN(t,{...t._zod.def,shape:i,checks:[]})}function I9(n,t=0){for(let r=t;r<n.issues.length;r++)if(n.issues[r]?.continue!==!0)return!0;return!1}function PW(n,t){return t.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(n),r})}function vq(n){return typeof n=="string"?n:n?.message}function zN(n,t,r){let a={...n,path:n.path??[]};if(!n.message){let i=vq(n.inst?._zod.def?.error?.(n))??vq(t?.error?.(n))??vq(r.customError?.(n))??vq(r.localeError?.(n))??"Invalid input";a.message=i}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function ZQt(n){return n instanceof Set?"set":n instanceof Map?"map":n instanceof File?"file":"unknown"}function Wq(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function BSe(...n){let[t,r,a]=n;return typeof t=="string"?{message:t,code:"custom",input:r,inst:a}:{...t}}function KWr(n){return Object.entries(n).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Dme,XSe,DWr,kSe,gQt,SSe,vQt,YSe,aE=ut(()=>{Dme=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};XSe=Zq(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let n=Function;return new n(""),!0}catch{return!1}});DWr=n=>{let t=typeof n;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(n)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(n)?"array":n===null?"null":n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?"promise":typeof Map<"u"&&n instanceof Map?"map":typeof Set<"u"&&n instanceof Set?"set":typeof Date<"u"&&n instanceof Date?"date":typeof File<"u"&&n instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},kSe=new Set(["string","number","symbol"]),gQt=new Set(["string","number","bigint","boolean","symbol","undefined"]);SSe={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},vQt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};YSe=class{constructor(...t){}}});function TSe(n,t=r=>r.message){let r={},a=[];for(let i of n.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):a.push(t(i));return{formErrors:a,fieldErrors:r}}function DSe(n,t){let r=t||function(s){return s.message},a={_errors:[]},i=s=>{for(let e of s.issues)if(e.code==="invalid_union"&&e.errors.length)e.errors.map(o=>i({issues:o}));else if(e.code==="invalid_key")i({issues:e.issues});else if(e.code==="invalid_element")i({issues:e.issues});else if(e.path.length===0)a._errors.push(r(e));else{let o=a,u=0;for(;u<e.path.length;){let d=e.path[u];u===e.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(r(e))):o[d]=o[d]||{_errors:[]},o=o[d],u++}}};return i(n),a}var NQt,Ume,JSe,OSe=ut(()=>{kJ();aE();NQt=(n,t)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:t,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(t,VSe,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},Ume=Tn("$ZodError",NQt),JSe=Tn("$ZodError",NQt,{Parent:Error})});var AQt,WQt,USe,yq,MSe,Mme,zSe=ut(()=>{kJ();OSe();aE();AQt=n=>(t,r,a,i)=>{let s=a?Object.assign(a,{async:!1}):{async:!1},e=t._zod.run({value:r,issues:[]},s);if(e instanceof Promise)throw new rE;if(e.issues.length){let o=new(i?.Err??n)(e.issues.map(u=>zN(u,s,l1())));throw Dme(o,i?.callee),o}return e.value},WQt=n=>async(t,r,a,i)=>{let s=a?Object.assign(a,{async:!0}):{async:!0},e=t._zod.run({value:r,issues:[]},s);if(e instanceof Promise&&(e=await e),e.issues.length){let o=new(i?.Err??n)(e.issues.map(u=>zN(u,s,l1())));throw Dme(o,i?.callee),o}return e.value},USe=n=>(t,r,a)=>{let i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new rE;return s.issues.length?{success:!1,error:new(n??Ume)(s.issues.map(e=>zN(e,i,l1())))}:{success:!0,data:s.value}},yq=USe(JSe),MSe=n=>async(t,r,a)=>{let i=a?Object.assign(a,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new n(s.issues.map(e=>zN(e,i,l1())))}:{success:!0,data:s.value}},Mme=MSe(JSe)});function QQt(){return new RegExp($Wr,"u")}function OQt(n){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${t}`:n.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${n.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function UQt(n){return new RegExp(`^${OQt(n)}$`)}function MQt(n){let t=OQt({precision:n.precision}),r=["Z"];n.local&&r.push(""),n.offset&&r.push("([+-]\\d{2}:\\d{2})");let a=`${t}(?:${r.join("|")})`;return new RegExp(`^${TQt}T(?:${a})$`)}var yQt,FQt,EQt,RQt,wQt,CQt,YQt,xQt,_Se,VQt,$Wr,HQt,XQt,kQt,LQt,SQt,PSe,BQt,JQt,TQt,DQt,zQt,_Qt,PQt,jQt,KQt,qQt,$Qt,e9t,_me=ut(()=>{yQt=/^[cC][^\s-]{8,}$/,FQt=/^[0-9a-z]+$/,EQt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,RQt=/^[0-9a-vA-V]{20}$/,wQt=/^[A-Za-z0-9]{27}$/,CQt=/^[a-zA-Z0-9_-]{21}$/,YQt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xQt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_Se=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,VQt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,$Wr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";HQt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,XQt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,kQt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,LQt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,SQt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,PSe=/^[A-Za-z0-9_-]*$/,BQt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,JQt=/^\+(?:[0-9]){6,14}[0-9]$/,TQt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",DQt=new RegExp(`^${TQt}$`);zQt=n=>{let t=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},_Qt=/^\d+n?$/,PQt=/^\d+$/,jQt=/^-?\d+(?:\.\d+)?/i,KQt=/true|false/i,qQt=/null/i,$Qt=/^[^A-Z]*$/,e9t=/^[^a-z]*$/});var bp,t9t,jSe,KSe,n9t,r9t,a9t,i9t,l9t,Fq,s9t,o9t,c9t,u9t,I9t,d9t,h9t,Pme=ut(()=>{kJ();_me();aE();bp=Tn("$ZodCheck",(n,t)=>{var r;n._zod??(n._zod={}),n._zod.def=t,(r=n._zod).onattach??(r.onattach=[])}),t9t={number:"number",bigint:"bigint",object:"date"},jSe=Tn("$ZodCheckLessThan",(n,t)=>{bp.init(n,t);let r=t9t[typeof t.value];n._zod.onattach.push(a=>{let i=a._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),n._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:r,code:"too_big",maximum:t.value,input:a.value,inclusive:t.inclusive,inst:n,continue:!t.abort})}}),KSe=Tn("$ZodCheckGreaterThan",(n,t)=>{bp.init(n,t);let r=t9t[typeof t.value];n._zod.onattach.push(a=>{let i=a._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),n._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:t.value,input:a.value,inclusive:t.inclusive,inst:n,continue:!t.abort})}}),n9t=Tn("$ZodCheckMultipleOf",(n,t)=>{bp.init(n,t),n._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.multipleOf=t.value)}),n._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):QSe(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:n,continue:!t.abort})}}),r9t=Tn("$ZodCheckNumberFormat",(n,t)=>{bp.init(n,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,s]=SSe[t.format];n._zod.onattach.push(e=>{let o=e._zod.bag;o.format=t.format,o.minimum=i,o.maximum=s,r&&(o.pattern=PQt)}),n._zod.check=e=>{let o=e.value;if(r){if(!Number.isInteger(o)){e.issues.push({expected:a,format:t.format,code:"invalid_type",input:o,inst:n});return}if(!Number.isSafeInteger(o)){o>0?e.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:a,continue:!t.abort}):e.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:a,continue:!t.abort});return}}o<i&&e.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:n,continue:!t.abort}),o>s&&e.issues.push({origin:"number",input:o,code:"too_big",maximum:s,inst:n})}}),a9t=Tn("$ZodCheckMaxLength",(n,t)=>{var r;bp.init(n,t),(r=n._zod.def).when??(r.when=a=>{let i=a.value;return!Nq(i)&&i.length!==void 0}),n._zod.onattach.push(a=>{let i=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(a._zod.bag.maximum=t.maximum)}),n._zod.check=a=>{let i=a.value;if(i.length<=t.maximum)return;let e=Wq(i);a.issues.push({origin:e,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:n,continue:!t.abort})}}),i9t=Tn("$ZodCheckMinLength",(n,t)=>{var r;bp.init(n,t),(r=n._zod.def).when??(r.when=a=>{let i=a.value;return!Nq(i)&&i.length!==void 0}),n._zod.onattach.push(a=>{let i=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(a._zod.bag.minimum=t.minimum)}),n._zod.check=a=>{let i=a.value;if(i.length>=t.minimum)return;let e=Wq(i);a.issues.push({origin:e,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:n,continue:!t.abort})}}),l9t=Tn("$ZodCheckLengthEquals",(n,t)=>{var r;bp.init(n,t),(r=n._zod.def).when??(r.when=a=>{let i=a.value;return!Nq(i)&&i.length!==void 0}),n._zod.onattach.push(a=>{let i=a._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),n._zod.check=a=>{let i=a.value,s=i.length;if(s===t.length)return;let e=Wq(i),o=s>t.length;a.issues.push({origin:e,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:n,continue:!t.abort})}}),Fq=Tn("$ZodCheckStringFormat",(n,t)=>{var r,a;bp.init(n,t),n._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=n._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:n,continue:!t.abort})}):(a=n._zod).check??(a.check=()=>{})}),s9t=Tn("$ZodCheckRegex",(n,t)=>{Fq.init(n,t),n._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:n,continue:!t.abort})}}),o9t=Tn("$ZodCheckLowerCase",(n,t)=>{t.pattern??(t.pattern=$Qt),Fq.init(n,t)}),c9t=Tn("$ZodCheckUpperCase",(n,t)=>{t.pattern??(t.pattern=e9t),Fq.init(n,t)}),u9t=Tn("$ZodCheckIncludes",(n,t)=>{bp.init(n,t);let r=Tw(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=a,n._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),n._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:n,continue:!t.abort})}}),I9t=Tn("$ZodCheckStartsWith",(n,t)=>{bp.init(n,t);let r=new RegExp(`^${Tw(t.prefix)}.*`);t.pattern??(t.pattern=r),n._zod.onattach.push(a=>{let i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),n._zod.check=a=>{a.value.startsWith(t.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:a.value,inst:n,continue:!t.abort})}}),d9t=Tn("$ZodCheckEndsWith",(n,t)=>{bp.init(n,t);let r=new RegExp(`.*${Tw(t.suffix)}$`);t.pattern??(t.pattern=r),n._zod.onattach.push(a=>{let i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),n._zod.check=a=>{a.value.endsWith(t.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:a.value,inst:n,continue:!t.abort})}}),h9t=Tn("$ZodCheckOverwrite",(n,t)=>{bp.init(n,t),n._zod.check=r=>{r.value=t.tx(r.value)}})});var jme,qSe=ut(()=>{jme=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let a=t.split(`
|
|
706
|
+
`);s=G.pop()||"";for(let F of G)if(F.startsWith("data: ")){let W=F.slice(6);if(W==="[DONE]")return;try{let R=JSON.parse(W);if(R.type==="connection_established")continue;if(R.error)throw new Error(R.error);R.usageMetadata&&(o=R.usageMetadata);let y=this.convertStreamChunkToGenAI(R);y&&(yield y)}catch(R){ar.warn("[DeepV Server] Stream chunk parse error",{data:W.substring(0,100)+"...",error:R instanceof Error?R.message:R})}}}}finally{d&&r&&r.removeEventListener("abort",d);try{a.releaseLock()}catch{}}}convertStreamChunkToGenAI(t){if(!t.candidates||!Array.isArray(t.candidates)||t.candidates.length===0)return null;let r={candidates:t.candidates,usageMetadata:t.usageMetadata};if(r.candidates?.[0]?.content?.parts){for(let a of r.candidates[0].content.parts)if(a.functionCall&&!a.functionCall.id){let i=`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;console.log(`[DeepV Server] \u8865\u5168\u7F3A\u5931\u7684\u5DE5\u5177 ID (Chunk): ${a.functionCall.name} -> ${i}`),a.functionCall.id=i}}return r.functionCalls||Object.defineProperty(r,"functionCalls",{get:function(){if(this.candidates?.[0]?.content?.parts?.length===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let a=this.candidates?.[0]?.content?.parts?.filter(i=>i.functionCall).map(i=>i.functionCall).filter(i=>i!==void 0);if(a?.length!==0)return a},enumerable:!1,configurable:!0}),r}mergeStreamContent(t,r){if(!t)return r;let a=t.candidates?.[0]?.content?.parts||[],i=r.candidates?.[0]?.content?.parts||[];if(i.length>0&&i[0].text){let s=a[a.length-1];s&&s.text&&!s.functionCall?s.text+=i[0].text:a.push(...i)}else if(i.length>0&&i[0].functionCall){let s=a[a.length-1],e=i[0];if(s&&s.functionCall){let o=s.functionCall,u=e.functionCall;u&&(u.name&&(o.name=u.name.trim()),u.id&&(o.id=u.id),u.args&&(typeof u.args=="string"&&typeof o.args=="string"?o.args+=u.args:typeof u.args=="object"&&u.args!==null?o.args={...typeof o.args=="object"?o.args:{},...u.args}:o.args=u.args))}else{let o={...e};if(o.functionCall&&!o.functionCall.id){let u=`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;console.log(`[DeepV Server] \u8865\u5168\u7F3A\u5931\u7684\u5DE5\u5177 ID: ${o.functionCall.name} -> ${u}`),o.functionCall.id=u}a.push(o)}}return r.usageMetadata&&(t.usageMetadata=r.usageMetadata),r.candidates?.[0]?.finishReason&&(t.candidates[0].finishReason=r.candidates[0].finishReason),t}buildUnifiedRequest(t,r){let a=xd.getModelForScene(r),i=this.config?.getModel(),s;return i&&as(i)?t.model&&as(t.model)?s=t.model:s=i:s=t.model||a||"auto",{model:s,contents:t.contents,config:{...t.config,httpOptions:{...t.config?.httpOptions,headers:{...t.config?.httpOptions?.headers,"X-Scene-Type":r,"X-Scene-Display":xd.getSceneDisplayName(r)}}}}}async*handleStreamError(t){this.handleError(t)}async countTokens(t){try{let r=t.model||this.config?.getModel()||"auto";if(as(r))return ar.debug("[DeepV Server] Custom model detected, token counting not supported"),{totalTokens:0};let a={model:r,contents:t.contents};(t.config?.systemInstruction||t.config?.tools)&&(a.config={},t.config.systemInstruction&&(a.config.systemInstruction=t.config.systemInstruction),t.config.tools&&(a.config.tools=t.config.tools));let i=await this.callUnifiedTokenCountAPI(a);return of.emitRealTimeToken({inputTokens:i.totalTokens||0,outputTokens:0,totalTokens:i.totalTokens||0,timestamp:Date.now()}),i}catch(r){let a=t.model||this.config?.getModel()||"auto";return as(a)?ar.debug("[DeepV Server] Token count not available for custom model, using fallback"):ar.error("[DeepV Server] Token count failed:",r),this.estimateTokensAsFailback(t)}}async callUnifiedTokenCountAPI(t){let r=await Io.getUserHeaders(),a=`${Io.getProxyServerUrl()}/v1/chat/count-tokens`;try{let i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(t)});if(!i.ok){let e=await i.text();throw i.status===401?(console.error("[DeepV Server] Token count 401 Unauthorized"),this.authHandler&&await this.authHandler(),new BI("Authentication required - please re-authenticate")):new Error(`Token count API failed (${i.status}): ${e}`)}let s=await i.json();return ar.debug("[DeepV Server] Token count response",{totalTokens:s.totalTokens}),{totalTokens:s.totalTokens||0}}catch(i){throw ar.error("[DeepV Server] Token count API call failed:",i),i}}estimateTokensAsFailback(t){try{let r=Array.isArray(t.contents)?t.contents:[{role:Pr.USER,parts:[{text:t.contents}]}],a=0,i=0,s=0,e=0;for(let c of r)if(typeof c=="object"&&c&&"parts"in c&&Array.isArray(c.parts)){for(let G of c.parts)if(typeof G=="object"&&G&&"text"in G&&typeof G.text=="string")a+=G.text.length,e++;else if(typeof G=="object"&&G&&"functionCall"in G&&G.functionCall){let F=G.functionCall,W=`[Tool: ${F.name}]`+JSON.stringify(F.args||{});a+=W.length,i++}else if(typeof G=="object"&&G&&"functionResponse"in G&&G.functionResponse){let R=`[Tool Result: ${G.functionResponse.response?.output||"result"}]`;a+=R.length+20,s++}}else typeof c=="string"&&(a+=c.length,e++);let o=JSON.stringify(r),u=/[\u4e00-\u9fff]/.test(o),d=/```|function|class|import|export|\{|\}|\[|\]/.test(o),I=4;return u?I=2:d&&(I=3),{totalTokens:Math.ceil(a/I)}}catch(r){return console.error("[DeepV Server] Fallback estimation error:",r),{totalTokens:1e3}}}async embedContent(t){throw new Error("Claude models do not support embedding content")}withTimeout(t,r,a){let i=null,s=new Promise((e,o)=>{i=setTimeout(()=>{o(new Error(a))},r)});return Promise.race([t,s]).finally(()=>{i!==null&&clearTimeout(i)})}}});function vSe(n,t){let r=n.getModel()||"auto",a={authType:t,proxy:n?.getProxy()};return t===is.USE_PROXY_AUTH,a}async function ZSe(n,t,r){let i={headers:{"User-Agent":`GeminiCLI/1.0.309 (${process.platform}; ${process.arch})`}};if(!0){let e=t.getCustomProxyServerUrl(),o;if(e)o=e,console.log(`[DeepX] Using custom proxy server: ${o}`);else{if(!tXe())throw new Error("DeepV Code server is required for all models but is not available. Please start the DeepV Code server or use proxy authentication.");o=FW(),console.log(`[DeepX] Connecting to DeepV Code server: ${o}`)}let u=process.env.GOOGLE_CLOUD_LOCATION||"us-central1",d=process.env.GOOGLE_CLOUD_PROJECT||"default-project";return new RJ(u,d,o,t)}throw new Error(`Error creating contentGenerator: Unsupported authType: ${n.authType}`)}var is,wme=ut(()=>{"use strict";gSe();VB();(function(n){n.USE_PROXY_AUTH="proxy-auth"})(is||(is={}))});var Cme,rQt=ut(()=>{"use strict";Cme=class{prompts=new Map;registerPrompt(t){if(this.prompts.has(t.name)){let r=`${t.serverName}_${t.name}`;console.warn(`Prompt with name "${t.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...t,name:r})}else this.prompts.set(t.name,t)}getAllPrompts(){return Array.from(this.prompts.values()).sort((t,r)=>t.name.localeCompare(r.name))}getPrompt(t){return this.prompts.get(t)}getPromptsByServer(t){let r=[];for(let a of this.prompts.values())a.serverName===t&&r.push(a);return r.sort((a,i)=>a.name.localeCompare(i.name))}removePromptsByServer(t){for(let[r,a]of this.prompts.entries())a.serverName===t&&this.prompts.delete(r)}}});function ON(n){let t={type:"subagent_update",data:n,timestamp:Date.now()};return JSON.stringify(t)}function aQt(n){let t={type:"text",data:n,timestamp:Date.now()};return JSON.stringify(t)}function Yme(n){try{let t=JSON.parse(n);if(t&&typeof t=="object"&&t.type&&t.data!==void 0)return t}catch{}return{type:"text",data:n,timestamp:Date.now()}}function xme(n){return n.type==="subagent_update"}function Vme(n){return n.type==="text"}var NSe=ut(()=>{"use strict";});var qr,Mr,$r,Ll=ut(()=>{"use strict";NSe();qr=class{name;displayName;description;icon;parameterSchema;isOutputMarkdown;forceMarkdown;canUpdateOutput;allowSubAgentUse;constructor(t,r,a,i,s,e=!0,o=!1,u=!1,d=!0){this.name=t,this.displayName=r,this.description=a,this.icon=i,this.parameterSchema=s,this.isOutputMarkdown=e,this.forceMarkdown=o,this.canUpdateOutput=u,this.allowSubAgentUse=d}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(t){return null}getDescription(t){return JSON.stringify(t)}shouldConfirmExecute(t,r){return Promise.resolve(!1)}toolLocations(t){return[]}};(function(n){n.ProceedOnce="proceed_once",n.ProceedAlways="proceed_always",n.ProceedAlwaysServer="proceed_always_server",n.ProceedAlwaysTool="proceed_always_tool",n.ProceedAlwaysProject="proceed_always_project",n.ModifyWithEditor="modify_with_editor",n.Cancel="cancel"})(Mr||(Mr={}));(function(n){n.FileSearch="fileSearch",n.Folder="folder",n.Globe="globe",n.Hammer="hammer",n.LightBulb="lightBulb",n.Pencil="pencil",n.Regex="regex",n.Terminal="terminal",n.Clipboard="clipboard",n.Tasks="tasks",n.Wrench="wrench",n.Trash="trash",n.List="list",n.Info="info"})($r||($r={}))});var Sl,ASe,ea,MW,bq=ut(()=>{(function(n){n.assertEqual=i=>{};function t(i){}n.assertIs=t;function r(i){throw new Error}n.assertNever=r,n.arrayToEnum=i=>{let s={};for(let e of i)s[e]=e;return s},n.getValidEnumValues=i=>{let s=n.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),e={};for(let o of s)e[o]=i[o];return n.objectValues(e)},n.objectValues=i=>n.objectKeys(i).map(function(s){return i[s]}),n.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&s.push(e);return s},n.find=(i,s)=>{for(let e of i)if(s(e))return e},n.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function a(i,s=" | "){return i.map(e=>typeof e=="string"?`'${e}'`:e).join(s)}n.joinValues=a,n.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(Sl||(Sl={}));(function(n){n.mergeShapes=(t,r)=>({...t,...r})})(ASe||(ASe={}));ea=Sl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),MW=n=>{switch(typeof n){case"undefined":return ea.undefined;case"string":return ea.string;case"number":return Number.isNaN(n)?ea.nan:ea.number;case"boolean":return ea.boolean;case"function":return ea.function;case"bigint":return ea.bigint;case"symbol":return ea.symbol;case"object":return Array.isArray(n)?ea.array:n===null?ea.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ea.promise:typeof Map<"u"&&n instanceof Map?ea.map:typeof Set<"u"&&n instanceof Set?ea.set:typeof Date<"u"&&n instanceof Date?ea.date:ea.object;default:return ea.unknown}}});var vr,A3r,Gf,Qme=ut(()=>{bq();vr=Sl.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),A3r=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Gf=class n extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(s){return s.message},a={_errors:[]},i=s=>{for(let e of s.issues)if(e.code==="invalid_union")e.unionErrors.map(i);else if(e.code==="invalid_return_type")i(e.returnTypeError);else if(e.code==="invalid_arguments")i(e.argumentsError);else if(e.path.length===0)a._errors.push(r(e));else{let o=a,u=0;for(;u<e.path.length;){let d=e.path[u];u===e.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(r(e))):o[d]=o[d]||{_errors:[]},o=o[d],u++}}};return i(this),a}static assert(t){if(!(t instanceof n))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Sl.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},a=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(t(i))}else a.push(t(i));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}};Gf.create=n=>new Gf(n)});var W3r,$5,WSe=ut(()=>{Qme();bq();W3r=(n,t)=>{let r;switch(n.code){case vr.invalid_type:n.received===ea.undefined?r="Required":r=`Expected ${n.expected}, received ${n.received}`;break;case vr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(n.expected,Sl.jsonStringifyReplacer)}`;break;case vr.unrecognized_keys:r=`Unrecognized key(s) in object: ${Sl.joinValues(n.keys,", ")}`;break;case vr.invalid_union:r="Invalid input";break;case vr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Sl.joinValues(n.options)}`;break;case vr.invalid_enum_value:r=`Invalid enum value. Expected ${Sl.joinValues(n.options)}, received '${n.received}'`;break;case vr.invalid_arguments:r="Invalid function arguments";break;case vr.invalid_return_type:r="Invalid function return type";break;case vr.invalid_date:r="Invalid date";break;case vr.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(r=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?r=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?r=`Invalid input: must end with "${n.validation.endsWith}"`:Sl.assertNever(n.validation):n.validation!=="regex"?r=`Invalid ${n.validation}`:r="Invalid";break;case vr.too_small:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:r="Invalid input";break;case vr.too_big:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?r=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:r="Invalid input";break;case vr.custom:r="Invalid input";break;case vr.invalid_intersection_types:r="Intersection results could not be merged";break;case vr.not_multiple_of:r=`Number must be a multiple of ${n.multipleOf}`;break;case vr.not_finite:r="Number must be finite";break;default:r=t.defaultError,Sl.assertNever(n)}return{message:r}},$5=W3r});function y3r(n){iQt=n}function wJ(){return iQt}var iQt,Hme=ut(()=>{WSe();iQt=$5});function Tr(n,t){let r=wJ(),a=fq({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,r,r===$5?void 0:$5].filter(i=>!!i)});n.common.issues.push(a)}var fq,F3r,hm,ei,_Q,pp,Xme,kme,Lw,CJ,ySe=ut(()=>{Hme();WSe();fq=n=>{let{data:t,path:r,errorMaps:a,issueData:i}=n,s=[...r,...i.path||[]],e={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",u=a.filter(d=>!!d).slice().reverse();for(let d of u)o=d(e,{data:t,defaultError:o}).message;return{...i,path:s,message:o}},F3r=[];hm=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let a=[];for(let i of r){if(i.status==="aborted")return ei;i.status==="dirty"&&t.dirty(),a.push(i.value)}return{status:t.value,value:a}}static async mergeObjectAsync(t,r){let a=[];for(let i of r){let s=await i.key,e=await i.value;a.push({key:s,value:e})}return n.mergeObjectSync(t,a)}static mergeObjectSync(t,r){let a={};for(let i of r){let{key:s,value:e}=i;if(s.status==="aborted"||e.status==="aborted")return ei;s.status==="dirty"&&t.dirty(),e.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof e.value<"u"||i.alwaysSet)&&(a[s.value]=e.value)}return{status:t.value,value:a}}},ei=Object.freeze({status:"aborted"}),_Q=n=>({status:"dirty",value:n}),pp=n=>({status:"valid",value:n}),Xme=n=>n.status==="aborted",kme=n=>n.status==="dirty",Lw=n=>n.status==="valid",CJ=n=>typeof Promise<"u"&&n instanceof Promise});var lQt=ut(()=>{});var Na,sQt=ut(()=>{(function(n){n.errToObj=t=>typeof t=="string"?{message:t}:t||{},n.toString=t=>typeof t=="string"?t:t?.message})(Na||(Na={}))});function _i(n){if(!n)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:i}=n;if(t&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(e,o)=>{let{message:u}=n;return e.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??a??o.defaultError}:e.code!=="invalid_type"?{message:o.defaultError}:{message:u??r??o.defaultError}},description:i}}function IQt(n){let t="[0-5]\\d";n.precision?t=`${t}\\.\\d{${n.precision}}`:n.precision==null&&(t=`${t}(\\.\\d+)?`);let r=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function D3r(n){return new RegExp(`^${IQt(n)}$`)}function dQt(n){let t=`${uQt}T${IQt(n)}`,r=[];return r.push(n.local?"Z?":"Z"),n.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function O3r(n,t){return!!((t==="v4"||!t)&&X3r.test(n)||(t==="v6"||!t)&&L3r.test(n))}function U3r(n,t){if(!x3r.test(n))return!1;try{let[r]=n.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(a));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function M3r(n,t){return!!((t==="v4"||!t)&&k3r.test(n)||(t==="v6"||!t)&&S3r.test(n))}function z3r(n,t){let r=(n.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a,s=Number.parseInt(n.toFixed(i).replace(".","")),e=Number.parseInt(t.toFixed(i).replace(".",""));return s%e/10**i}function YJ(n){if(n instanceof gf){let t={};for(let r in n.shape){let a=n.shape[r];t[r]=fv.create(YJ(a))}return new gf({...n._def,shape:()=>t})}else return n instanceof nE?new nE({...n._def,type:YJ(n.element)}):n instanceof fv?fv.create(YJ(n.unwrap())):n instanceof _W?_W.create(YJ(n.unwrap())):n instanceof zW?zW.create(n.items.map(t=>YJ(t))):n}function ESe(n,t){let r=MW(n),a=MW(t);if(n===t)return{valid:!0,data:n};if(r===ea.object&&a===ea.object){let i=Sl.objectKeys(t),s=Sl.objectKeys(n).filter(o=>i.indexOf(o)!==-1),e={...n,...t};for(let o of s){let u=ESe(n[o],t[o]);if(!u.valid)return{valid:!1};e[o]=u.data}return{valid:!0,data:e}}else if(r===ea.array&&a===ea.array){if(n.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<n.length;s++){let e=n[s],o=t[s],u=ESe(e,o);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===ea.date&&a===ea.date&&+n==+t?{valid:!0,data:n}:{valid:!1}}function hQt(n,t){return new i9({values:n,typeName:li.ZodEnum,..._i(t)})}function cQt(n,t){let r=typeof n=="function"?n(t):typeof n=="string"?{message:n}:n;return typeof r=="string"?{message:r}:r}function mQt(n,t={},r){return n?Bw.create().superRefine((a,i)=>{let s=n(a);if(s instanceof Promise)return s.then(e=>{if(!e){let o=cQt(t,a),u=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:u})}});if(!s){let e=cQt(t,a),o=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:o})}}):Bw.create()}var Gv,oQt,ol,E3r,R3r,w3r,C3r,Y3r,x3r,V3r,Q3r,H3r,FSe,X3r,k3r,L3r,S3r,B3r,J3r,uQt,T3r,Sw,PQ,jQ,KQ,qQ,xJ,$Q,e9,Bw,tE,UN,VJ,nE,gf,t9,eE,Lme,n9,zW,Sme,QJ,HJ,Bme,r9,a9,i9,l9,Jw,gv,fv,_W,s9,o9,XJ,_3r,Gq,gq,c9,P3r,li,j3r,pQt,bQt,K3r,q3r,fQt,$3r,eWr,tWr,nWr,rWr,aWr,iWr,lWr,sWr,oWr,cWr,uWr,IWr,dWr,hWr,mWr,pWr,bWr,fWr,GWr,gWr,vWr,ZWr,NWr,AWr,WWr,yWr,FWr,EWr,RWr,wWr,CWr,YWr,xWr,GQt=ut(()=>{Qme();Hme();sQt();ySe();bq();Gv=class{constructor(t,r,a,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=a,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},oQt=(n,t)=>{if(Lw(t))return{success:!0,data:t.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Gf(n.common.issues);return this._error=r,this._error}}};ol=class{get description(){return this._def.description}_getType(t){return MW(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:MW(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new hm,ctx:{common:t.parent.common,data:t.data,parsedType:MW(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(CJ(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let a=this.safeParse(t,r);if(a.success)return a.data;throw a.error}safeParse(t,r){let a={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:MW(t)},i=this._parseSync({data:t,path:a.path,parent:a});return oQt(a,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:MW(t)};if(!this["~standard"].async)try{let a=this._parseSync({data:t,path:[],parent:r});return Lw(a)?{value:a.value}:{issues:r.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(a=>Lw(a)?{value:a.value}:{issues:r.common.issues})}async parseAsync(t,r){let a=await this.safeParseAsync(t,r);if(a.success)return a.data;throw a.error}async safeParseAsync(t,r){let a={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:MW(t)},i=this._parse({data:t,path:a.path,parent:a}),s=await(CJ(i)?i:Promise.resolve(i));return oQt(a,s)}refine(t,r){let a=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let e=t(i),o=()=>s.addIssue({code:vr.custom,...a(i)});return typeof Promise<"u"&&e instanceof Promise?e.then(u=>u?!0:(o(),!1)):e?!0:(o(),!1)})}refinement(t,r){return this._refinement((a,i)=>t(a)?!0:(i.addIssue(typeof r=="function"?r(a,i):r),!1))}_refinement(t){return new gv({schema:this,typeName:li.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return fv.create(this,this._def)}nullable(){return _W.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nE.create(this)}promise(){return Jw.create(this,this._def)}or(t){return t9.create([this,t],this._def)}and(t){return n9.create(this,t,this._def)}transform(t){return new gv({..._i(this._def),schema:this,typeName:li.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new s9({..._i(this._def),innerType:this,defaultValue:r,typeName:li.ZodDefault})}brand(){return new Gq({typeName:li.ZodBranded,type:this,..._i(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new o9({..._i(this._def),innerType:this,catchValue:r,typeName:li.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return gq.create(this,t)}readonly(){return c9.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},E3r=/^c[^\s-]{8,}$/i,R3r=/^[0-9a-z]+$/,w3r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C3r=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Y3r=/^[a-z0-9_-]{21}$/i,x3r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,V3r=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Q3r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,H3r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",X3r=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,k3r=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,L3r=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,S3r=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,B3r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,J3r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uQt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",T3r=new RegExp(`^${uQt}$`);Sw=class n extends ol{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ea.string){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_type,expected:ea.string,received:s.parsedType}),ei}let a=new hm,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){let e=t.data.length>s.value,o=t.data.length<s.value;(e||o)&&(i=this._getOrReturnCtx(t,i),e?Tr(i,{code:vr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&Tr(i,{code:vr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")Q3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"email",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")FSe||(FSe=new RegExp(H3r,"u")),FSe.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"emoji",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")C3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"uuid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")Y3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"nanoid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")E3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"cuid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")R3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"cuid2",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")w3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"ulid",code:vr.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Tr(i,{validation:"url",code:vr.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"regex",code:vr.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?dQt(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?T3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?D3r(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?V3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"duration",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?O3r(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"ip",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?U3r(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"jwt",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?M3r(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"cidr",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?B3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"base64",code:vr.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?J3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Tr(i,{validation:"base64url",code:vr.invalid_string,message:s.message}),a.dirty()):Sl.assertNever(s);return{status:a.value,value:t.data}}_regex(t,r,a){return this.refinement(i=>t.test(i),{validation:r,code:vr.invalid_string,...Na.errToObj(a)})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Na.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Na.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Na.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Na.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Na.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Na.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Na.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Na.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Na.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Na.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Na.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Na.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Na.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...Na.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Na.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Na.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Na.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Na.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Na.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Na.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Na.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Na.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Na.errToObj(r)})}nonempty(t){return this.min(1,Na.errToObj(t))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Sw.create=n=>new Sw({checks:[],typeName:li.ZodString,coerce:n?.coerce??!1,..._i(n)});PQ=class n extends ol{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ea.number){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_type,expected:ea.number,received:s.parsedType}),ei}let a,i=new hm;for(let s of this._def.checks)s.kind==="int"?Sl.isInteger(t.data)||(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?z3r(t.data,s.value)!==0&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.not_finite,message:s.message}),i.dirty()):Sl.assertNever(s);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Na.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Na.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Na.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Na.toString(r))}setLimit(t,r,a,i){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:a,message:Na.toString(i)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Na.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Na.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Na.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Na.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Na.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Na.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Na.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Na.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Na.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Sl.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(t===null||a.value<t)&&(t=a.value)}return Number.isFinite(r)&&Number.isFinite(t)}};PQ.create=n=>new PQ({checks:[],typeName:li.ZodNumber,coerce:n?.coerce||!1,..._i(n)});jQ=class n extends ol{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ea.bigint)return this._getInvalidInput(t);let a,i=new hm;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(t,a),Tr(a,{code:vr.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Sl.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Tr(r,{code:vr.invalid_type,expected:ea.bigint,received:r.parsedType}),ei}gte(t,r){return this.setLimit("min",t,!0,Na.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Na.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Na.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Na.toString(r))}setLimit(t,r,a,i){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:a,message:Na.toString(i)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Na.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Na.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Na.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Na.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Na.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};jQ.create=n=>new jQ({checks:[],typeName:li.ZodBigInt,coerce:n?.coerce??!1,..._i(n)});KQ=class extends ol{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ea.boolean){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.boolean,received:a.parsedType}),ei}return pp(t.data)}};KQ.create=n=>new KQ({typeName:li.ZodBoolean,coerce:n?.coerce||!1,..._i(n)});qQ=class n extends ol{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ea.date){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_type,expected:ea.date,received:s.parsedType}),ei}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return Tr(s,{code:vr.invalid_date}),ei}let a=new hm,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),Tr(i,{code:vr.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):Sl.assertNever(s);return{status:a.value,value:new Date(t.data.getTime())}}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Na.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Na.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};qQ.create=n=>new qQ({checks:[],coerce:n?.coerce||!1,typeName:li.ZodDate,..._i(n)});xJ=class extends ol{_parse(t){if(this._getType(t)!==ea.symbol){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.symbol,received:a.parsedType}),ei}return pp(t.data)}};xJ.create=n=>new xJ({typeName:li.ZodSymbol,..._i(n)});$Q=class extends ol{_parse(t){if(this._getType(t)!==ea.undefined){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.undefined,received:a.parsedType}),ei}return pp(t.data)}};$Q.create=n=>new $Q({typeName:li.ZodUndefined,..._i(n)});e9=class extends ol{_parse(t){if(this._getType(t)!==ea.null){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.null,received:a.parsedType}),ei}return pp(t.data)}};e9.create=n=>new e9({typeName:li.ZodNull,..._i(n)});Bw=class extends ol{constructor(){super(...arguments),this._any=!0}_parse(t){return pp(t.data)}};Bw.create=n=>new Bw({typeName:li.ZodAny,..._i(n)});tE=class extends ol{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pp(t.data)}};tE.create=n=>new tE({typeName:li.ZodUnknown,..._i(n)});UN=class extends ol{_parse(t){let r=this._getOrReturnCtx(t);return Tr(r,{code:vr.invalid_type,expected:ea.never,received:r.parsedType}),ei}};UN.create=n=>new UN({typeName:li.ZodNever,..._i(n)});VJ=class extends ol{_parse(t){if(this._getType(t)!==ea.undefined){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.void,received:a.parsedType}),ei}return pp(t.data)}};VJ.create=n=>new VJ({typeName:li.ZodVoid,..._i(n)});nE=class n extends ol{_parse(t){let{ctx:r,status:a}=this._processInputParams(t),i=this._def;if(r.parsedType!==ea.array)return Tr(r,{code:vr.invalid_type,expected:ea.array,received:r.parsedType}),ei;if(i.exactLength!==null){let e=r.data.length>i.exactLength.value,o=r.data.length<i.exactLength.value;(e||o)&&(Tr(r,{code:e?vr.too_big:vr.too_small,minimum:o?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),a.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Tr(r,{code:vr.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),a.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Tr(r,{code:vr.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((e,o)=>i.type._parseAsync(new Gv(r,e,r.path,o)))).then(e=>hm.mergeArray(a,e));let s=[...r.data].map((e,o)=>i.type._parseSync(new Gv(r,e,r.path,o)));return hm.mergeArray(a,s)}get element(){return this._def.type}min(t,r){return new n({...this._def,minLength:{value:t,message:Na.toString(r)}})}max(t,r){return new n({...this._def,maxLength:{value:t,message:Na.toString(r)}})}length(t,r){return new n({...this._def,exactLength:{value:t,message:Na.toString(r)}})}nonempty(t){return this.min(1,t)}};nE.create=(n,t)=>new nE({type:n,minLength:null,maxLength:null,exactLength:null,typeName:li.ZodArray,..._i(t)});gf=class n extends ol{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Sl.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ea.object){let d=this._getOrReturnCtx(t);return Tr(d,{code:vr.invalid_type,expected:ea.object,received:d.parsedType}),ei}let{status:a,ctx:i}=this._processInputParams(t),{shape:s,keys:e}=this._getCached(),o=[];if(!(this._def.catchall instanceof UN&&this._def.unknownKeys==="strip"))for(let d in i.data)e.includes(d)||o.push(d);let u=[];for(let d of e){let I=s[d],h=i.data[d];u.push({key:{status:"valid",value:d},value:I._parse(new Gv(i,h,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof UN){let d=this._def.unknownKeys;if(d==="passthrough")for(let I of o)u.push({key:{status:"valid",value:I},value:{status:"valid",value:i.data[I]}});else if(d==="strict")o.length>0&&(Tr(i,{code:vr.unrecognized_keys,keys:o}),a.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let I of o){let h=i.data[I];u.push({key:{status:"valid",value:I},value:d._parse(new Gv(i,h,i.path,I)),alwaysSet:I in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let I of u){let h=await I.key,c=await I.value;d.push({key:h,value:c,alwaysSet:I.alwaysSet})}return d}).then(d=>hm.mergeObjectSync(a,d)):hm.mergeObjectSync(a,u)}get shape(){return this._def.shape()}strict(t){return Na.errToObj,new n({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,a)=>{let i=this._def.errorMap?.(r,a).message??a.defaultError;return r.code==="unrecognized_keys"?{message:Na.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(t){return new n({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new n({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:li.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new n({...this._def,catchall:t})}pick(t){let r={};for(let a of Sl.objectKeys(t))t[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new n({...this._def,shape:()=>r})}omit(t){let r={};for(let a of Sl.objectKeys(this.shape))t[a]||(r[a]=this.shape[a]);return new n({...this._def,shape:()=>r})}deepPartial(){return YJ(this)}partial(t){let r={};for(let a of Sl.objectKeys(this.shape)){let i=this.shape[a];t&&!t[a]?r[a]=i:r[a]=i.optional()}return new n({...this._def,shape:()=>r})}required(t){let r={};for(let a of Sl.objectKeys(this.shape))if(t&&!t[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof fv;)s=s._def.innerType;r[a]=s}return new n({...this._def,shape:()=>r})}keyof(){return hQt(Sl.objectKeys(this.shape))}};gf.create=(n,t)=>new gf({shape:()=>n,unknownKeys:"strip",catchall:UN.create(),typeName:li.ZodObject,..._i(t)});gf.strictCreate=(n,t)=>new gf({shape:()=>n,unknownKeys:"strict",catchall:UN.create(),typeName:li.ZodObject,..._i(t)});gf.lazycreate=(n,t)=>new gf({shape:n,unknownKeys:"strip",catchall:UN.create(),typeName:li.ZodObject,..._i(t)});t9=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a=this._def.options;function i(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let e=s.map(o=>new Gf(o.ctx.common.issues));return Tr(r,{code:vr.invalid_union,unionErrors:e}),ei}if(r.common.async)return Promise.all(a.map(async s=>{let e={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:e}),ctx:e}})).then(i);{let s,e=[];for(let u of a){let d={...r,common:{...r.common,issues:[]},parent:null},I=u._parseSync({data:r.data,path:r.path,parent:d});if(I.status==="valid")return I;I.status==="dirty"&&!s&&(s={result:I,ctx:d}),d.common.issues.length&&e.push(d.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=e.map(u=>new Gf(u));return Tr(r,{code:vr.invalid_union,unionErrors:o}),ei}}get options(){return this._def.options}};t9.create=(n,t)=>new t9({options:n,typeName:li.ZodUnion,..._i(t)});eE=n=>n instanceof r9?eE(n.schema):n instanceof gv?eE(n.innerType()):n instanceof a9?[n.value]:n instanceof i9?n.options:n instanceof l9?Sl.objectValues(n.enum):n instanceof s9?eE(n._def.innerType):n instanceof $Q?[void 0]:n instanceof e9?[null]:n instanceof fv?[void 0,...eE(n.unwrap())]:n instanceof _W?[null,...eE(n.unwrap())]:n instanceof Gq||n instanceof c9?eE(n.unwrap()):n instanceof o9?eE(n._def.innerType):[],Lme=class n extends ol{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ea.object)return Tr(r,{code:vr.invalid_type,expected:ea.object,received:r.parsedType}),ei;let a=this.discriminator,i=r.data[a],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Tr(r,{code:vr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),ei)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,a){let i=new Map;for(let s of r){let e=eE(s.shape[t]);if(!e.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of e){if(i.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);i.set(o,s)}}return new n({typeName:li.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,..._i(a)})}};n9=class extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t),i=(s,e)=>{if(Xme(s)||Xme(e))return ei;let o=ESe(s.value,e.value);return o.valid?((kme(s)||kme(e))&&r.dirty(),{status:r.value,value:o.data}):(Tr(a,{code:vr.invalid_intersection_types}),ei)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,e])=>i(s,e)):i(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};n9.create=(n,t,r)=>new n9({left:n,right:t,typeName:li.ZodIntersection,..._i(r)});zW=class n extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.array)return Tr(a,{code:vr.invalid_type,expected:ea.array,received:a.parsedType}),ei;if(a.data.length<this._def.items.length)return Tr(a,{code:vr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ei;!this._def.rest&&a.data.length>this._def.items.length&&(Tr(a,{code:vr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...a.data].map((e,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new Gv(a,e,a.path,o)):null}).filter(e=>!!e);return a.common.async?Promise.all(s).then(e=>hm.mergeArray(r,e)):hm.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new n({...this._def,rest:t})}};zW.create=(n,t)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new zW({items:n,typeName:li.ZodTuple,rest:null,..._i(t)})};Sme=class n extends ol{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.object)return Tr(a,{code:vr.invalid_type,expected:ea.object,received:a.parsedType}),ei;let i=[],s=this._def.keyType,e=this._def.valueType;for(let o in a.data)i.push({key:s._parse(new Gv(a,o,a.path,o)),value:e._parse(new Gv(a,a.data[o],a.path,o)),alwaysSet:o in a.data});return a.common.async?hm.mergeObjectAsync(r,i):hm.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,a){return r instanceof ol?new n({keyType:t,valueType:r,typeName:li.ZodRecord,..._i(a)}):new n({keyType:Sw.create(),valueType:t,typeName:li.ZodRecord,..._i(r)})}},QJ=class extends ol{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.map)return Tr(a,{code:vr.invalid_type,expected:ea.map,received:a.parsedType}),ei;let i=this._def.keyType,s=this._def.valueType,e=[...a.data.entries()].map(([o,u],d)=>({key:i._parse(new Gv(a,o,a.path,[d,"key"])),value:s._parse(new Gv(a,u,a.path,[d,"value"]))}));if(a.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of e){let d=await u.key,I=await u.value;if(d.status==="aborted"||I.status==="aborted")return ei;(d.status==="dirty"||I.status==="dirty")&&r.dirty(),o.set(d.value,I.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let u of e){let d=u.key,I=u.value;if(d.status==="aborted"||I.status==="aborted")return ei;(d.status==="dirty"||I.status==="dirty")&&r.dirty(),o.set(d.value,I.value)}return{status:r.value,value:o}}}};QJ.create=(n,t,r)=>new QJ({valueType:t,keyType:n,typeName:li.ZodMap,..._i(r)});HJ=class n extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.parsedType!==ea.set)return Tr(a,{code:vr.invalid_type,expected:ea.set,received:a.parsedType}),ei;let i=this._def;i.minSize!==null&&a.data.size<i.minSize.value&&(Tr(a,{code:vr.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&a.data.size>i.maxSize.value&&(Tr(a,{code:vr.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function e(u){let d=new Set;for(let I of u){if(I.status==="aborted")return ei;I.status==="dirty"&&r.dirty(),d.add(I.value)}return{status:r.value,value:d}}let o=[...a.data.values()].map((u,d)=>s._parse(new Gv(a,u,a.path,d)));return a.common.async?Promise.all(o).then(u=>e(u)):e(o)}min(t,r){return new n({...this._def,minSize:{value:t,message:Na.toString(r)}})}max(t,r){return new n({...this._def,maxSize:{value:t,message:Na.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};HJ.create=(n,t)=>new HJ({valueType:n,minSize:null,maxSize:null,typeName:li.ZodSet,..._i(t)});Bme=class n extends ol{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ea.function)return Tr(r,{code:vr.invalid_type,expected:ea.function,received:r.parsedType}),ei;function a(o,u){return fq({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wJ(),$5].filter(d=>!!d),issueData:{code:vr.invalid_arguments,argumentsError:u}})}function i(o,u){return fq({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wJ(),$5].filter(d=>!!d),issueData:{code:vr.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},e=r.data;if(this._def.returns instanceof Jw){let o=this;return pp(async function(...u){let d=new Gf([]),I=await o._def.args.parseAsync(u,s).catch(G=>{throw d.addIssue(a(u,G)),d}),h=await Reflect.apply(e,this,I);return await o._def.returns._def.type.parseAsync(h,s).catch(G=>{throw d.addIssue(i(h,G)),d})})}else{let o=this;return pp(function(...u){let d=o._def.args.safeParse(u,s);if(!d.success)throw new Gf([a(u,d.error)]);let I=Reflect.apply(e,this,d.data),h=o._def.returns.safeParse(I,s);if(!h.success)throw new Gf([i(I,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new n({...this._def,args:zW.create(t).rest(tE.create())})}returns(t){return new n({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,a){return new n({args:t||zW.create([]).rest(tE.create()),returns:r||tE.create(),typeName:li.ZodFunction,..._i(a)})}},r9=class extends ol{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};r9.create=(n,t)=>new r9({getter:n,typeName:li.ZodLazy,..._i(t)});a9=class extends ol{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Tr(r,{received:r.data,code:vr.invalid_literal,expected:this._def.value}),ei}return{status:"valid",value:t.data}}get value(){return this._def.value}};a9.create=(n,t)=>new a9({value:n,typeName:li.ZodLiteral,..._i(t)});i9=class n extends ol{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),a=this._def.values;return Tr(r,{expected:Sl.joinValues(a),received:r.parsedType,code:vr.invalid_type}),ei}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),a=this._def.values;return Tr(r,{received:r.data,code:vr.invalid_enum_value,options:a}),ei}return pp(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return n.create(t,{...this._def,...r})}exclude(t,r=this._def){return n.create(this.options.filter(a=>!t.includes(a)),{...this._def,...r})}};i9.create=hQt;l9=class extends ol{_parse(t){let r=Sl.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(t);if(a.parsedType!==ea.string&&a.parsedType!==ea.number){let i=Sl.objectValues(r);return Tr(a,{expected:Sl.joinValues(i),received:a.parsedType,code:vr.invalid_type}),ei}if(this._cache||(this._cache=new Set(Sl.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Sl.objectValues(r);return Tr(a,{received:a.data,code:vr.invalid_enum_value,options:i}),ei}return pp(t.data)}get enum(){return this._def.values}};l9.create=(n,t)=>new l9({values:n,typeName:li.ZodNativeEnum,..._i(t)});Jw=class extends ol{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ea.promise&&r.common.async===!1)return Tr(r,{code:vr.invalid_type,expected:ea.promise,received:r.parsedType}),ei;let a=r.parsedType===ea.promise?r.data:Promise.resolve(r.data);return pp(a.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Jw.create=(n,t)=>new Jw({type:n,typeName:li.ZodPromise,..._i(t)});gv=class extends ol{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===li.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:a}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:e=>{Tr(a,e),e.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let e=i.transform(a.data,s);if(a.common.async)return Promise.resolve(e).then(async o=>{if(r.value==="aborted")return ei;let u=await this._def.schema._parseAsync({data:o,path:a.path,parent:a});return u.status==="aborted"?ei:u.status==="dirty"?_Q(u.value):r.value==="dirty"?_Q(u.value):u});{if(r.value==="aborted")return ei;let o=this._def.schema._parseSync({data:e,path:a.path,parent:a});return o.status==="aborted"?ei:o.status==="dirty"?_Q(o.value):r.value==="dirty"?_Q(o.value):o}}if(i.type==="refinement"){let e=o=>{let u=i.refinement(o,s);if(a.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(a.common.async===!1){let o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return o.status==="aborted"?ei:(o.status==="dirty"&&r.dirty(),e(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>o.status==="aborted"?ei:(o.status==="dirty"&&r.dirty(),e(o.value).then(()=>({status:r.value,value:o.value}))))}if(i.type==="transform")if(a.common.async===!1){let e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!Lw(e))return ei;let o=i.transform(e.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(e=>Lw(e)?Promise.resolve(i.transform(e.value,s)).then(o=>({status:r.value,value:o})):ei);Sl.assertNever(i)}};gv.create=(n,t,r)=>new gv({schema:n,typeName:li.ZodEffects,effect:t,..._i(r)});gv.createWithPreprocess=(n,t,r)=>new gv({schema:t,effect:{type:"preprocess",transform:n},typeName:li.ZodEffects,..._i(r)});fv=class extends ol{_parse(t){return this._getType(t)===ea.undefined?pp(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};fv.create=(n,t)=>new fv({innerType:n,typeName:li.ZodOptional,..._i(t)});_W=class extends ol{_parse(t){return this._getType(t)===ea.null?pp(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_W.create=(n,t)=>new _W({innerType:n,typeName:li.ZodNullable,..._i(t)});s9=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a=r.data;return r.parsedType===ea.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};s9.create=(n,t)=>new s9({innerType:n,typeName:li.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,..._i(t)});o9=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return CJ(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Gf(a.common.issues)},input:a.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Gf(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};o9.create=(n,t)=>new o9({innerType:n,typeName:li.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,..._i(t)});XJ=class extends ol{_parse(t){if(this._getType(t)!==ea.nan){let a=this._getOrReturnCtx(t);return Tr(a,{code:vr.invalid_type,expected:ea.nan,received:a.parsedType}),ei}return{status:"valid",value:t.data}}};XJ.create=n=>new XJ({typeName:li.ZodNaN,..._i(n)});_3r=Symbol("zod_brand"),Gq=class extends ol{_parse(t){let{ctx:r}=this._processInputParams(t),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}},gq=class n extends ol{_parse(t){let{status:r,ctx:a}=this._processInputParams(t);if(a.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?ei:s.status==="dirty"?(r.dirty(),_Q(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{let i=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?ei:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:a.path,parent:a})}}static create(t,r){return new n({in:t,out:r,typeName:li.ZodPipeline})}},c9=class extends ol{_parse(t){let r=this._def.innerType._parse(t),a=i=>(Lw(i)&&(i.value=Object.freeze(i.value)),i);return CJ(r)?r.then(i=>a(i)):a(r)}unwrap(){return this._def.innerType}};c9.create=(n,t)=>new c9({innerType:n,typeName:li.ZodReadonly,..._i(t)});P3r={object:gf.lazycreate};(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(li||(li={}));j3r=(n,t={message:`Input not instance of ${n.name}`})=>mQt(r=>r instanceof n,t),pQt=Sw.create,bQt=PQ.create,K3r=XJ.create,q3r=jQ.create,fQt=KQ.create,$3r=qQ.create,eWr=xJ.create,tWr=$Q.create,nWr=e9.create,rWr=Bw.create,aWr=tE.create,iWr=UN.create,lWr=VJ.create,sWr=nE.create,oWr=gf.create,cWr=gf.strictCreate,uWr=t9.create,IWr=Lme.create,dWr=n9.create,hWr=zW.create,mWr=Sme.create,pWr=QJ.create,bWr=HJ.create,fWr=Bme.create,GWr=r9.create,gWr=a9.create,vWr=i9.create,ZWr=l9.create,NWr=Jw.create,AWr=gv.create,WWr=fv.create,yWr=_W.create,FWr=gv.createWithPreprocess,EWr=gq.create,RWr=()=>pQt().optional(),wWr=()=>bQt().optional(),CWr=()=>fQt().optional(),YWr={string:(n=>Sw.create({...n,coerce:!0})),number:(n=>PQ.create({...n,coerce:!0})),boolean:(n=>KQ.create({...n,coerce:!0})),bigint:(n=>jQ.create({...n,coerce:!0})),date:(n=>qQ.create({...n,coerce:!0}))},xWr=ei});var ju={};Lo(ju,{BRAND:()=>_3r,DIRTY:()=>_Q,EMPTY_PATH:()=>F3r,INVALID:()=>ei,NEVER:()=>xWr,OK:()=>pp,ParseStatus:()=>hm,Schema:()=>ol,ZodAny:()=>Bw,ZodArray:()=>nE,ZodBigInt:()=>jQ,ZodBoolean:()=>KQ,ZodBranded:()=>Gq,ZodCatch:()=>o9,ZodDate:()=>qQ,ZodDefault:()=>s9,ZodDiscriminatedUnion:()=>Lme,ZodEffects:()=>gv,ZodEnum:()=>i9,ZodError:()=>Gf,ZodFirstPartyTypeKind:()=>li,ZodFunction:()=>Bme,ZodIntersection:()=>n9,ZodIssueCode:()=>vr,ZodLazy:()=>r9,ZodLiteral:()=>a9,ZodMap:()=>QJ,ZodNaN:()=>XJ,ZodNativeEnum:()=>l9,ZodNever:()=>UN,ZodNull:()=>e9,ZodNullable:()=>_W,ZodNumber:()=>PQ,ZodObject:()=>gf,ZodOptional:()=>fv,ZodParsedType:()=>ea,ZodPipeline:()=>gq,ZodPromise:()=>Jw,ZodReadonly:()=>c9,ZodRecord:()=>Sme,ZodSchema:()=>ol,ZodSet:()=>HJ,ZodString:()=>Sw,ZodSymbol:()=>xJ,ZodTransformer:()=>gv,ZodTuple:()=>zW,ZodType:()=>ol,ZodUndefined:()=>$Q,ZodUnion:()=>t9,ZodUnknown:()=>tE,ZodVoid:()=>VJ,addIssueToContext:()=>Tr,any:()=>rWr,array:()=>sWr,bigint:()=>q3r,boolean:()=>fQt,coerce:()=>YWr,custom:()=>mQt,date:()=>$3r,datetimeRegex:()=>dQt,defaultErrorMap:()=>$5,discriminatedUnion:()=>IWr,effect:()=>AWr,enum:()=>vWr,function:()=>fWr,getErrorMap:()=>wJ,getParsedType:()=>MW,instanceof:()=>j3r,intersection:()=>dWr,isAborted:()=>Xme,isAsync:()=>CJ,isDirty:()=>kme,isValid:()=>Lw,late:()=>P3r,lazy:()=>GWr,literal:()=>gWr,makeIssue:()=>fq,map:()=>pWr,nan:()=>K3r,nativeEnum:()=>ZWr,never:()=>iWr,null:()=>nWr,nullable:()=>yWr,number:()=>bQt,object:()=>oWr,objectUtil:()=>ASe,oboolean:()=>CWr,onumber:()=>wWr,optional:()=>WWr,ostring:()=>RWr,pipeline:()=>EWr,preprocess:()=>FWr,promise:()=>NWr,quotelessJson:()=>A3r,record:()=>mWr,set:()=>bWr,setErrorMap:()=>y3r,strictObject:()=>cWr,string:()=>pQt,symbol:()=>eWr,transformer:()=>AWr,tuple:()=>hWr,undefined:()=>tWr,union:()=>uWr,unknown:()=>aWr,util:()=>Sl,void:()=>lWr});var RSe=ut(()=>{Hme();ySe();lQt();bq();GQt();Qme()});function Tn(n,t,r){function a(o,u){var d;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(d=o._zod).traits??(d.traits=new Set),o._zod.traits.add(n),t(o,u);for(let I in e.prototype)I in o||Object.defineProperty(o,I,{value:e.prototype[I].bind(o)});o._zod.constr=e,o._zod.def=u}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:n});function e(o){var u;let d=r?.Parent?new s:this;a(d,o),(u=d._zod).deferred??(u.deferred=[]);for(let I of d._zod.deferred)I();return d}return Object.defineProperty(e,"init",{value:a}),Object.defineProperty(e,Symbol.hasInstance,{value:o=>r?.Parent&&o instanceof r.Parent?!0:o?._zod?.traits?.has(n)}),Object.defineProperty(e,"name",{value:n}),e}function l1(n){return n&&Object.assign(Jme,n),Jme}var wSe,VWr,rE,Jme,kJ=ut(()=>{wSe=Object.freeze({status:"aborted"});VWr=Symbol("zod_brand"),rE=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jme={}});var _s={};Lo(_s,{BIGINT_FORMAT_RANGES:()=>vQt,Class:()=>YSe,NUMBER_FORMAT_RANGES:()=>SSe,aborted:()=>I9,allowsEval:()=>XSe,assert:()=>LWr,assertEqual:()=>QWr,assertIs:()=>XWr,assertNever:()=>kWr,assertNotEqual:()=>HWr,assignProp:()=>HSe,cached:()=>Zq,captureStackTrace:()=>Dme,cleanEnum:()=>KWr,cleanRegex:()=>Aq,clone:()=>MN,createTransparentProxy:()=>OWr,defineLazy:()=>Qc,esc:()=>u9,escapeRegex:()=>Tw,extend:()=>zWr,finalizeIssue:()=>zN,floatSafeRemainder:()=>QSe,getElementAtPath:()=>SWr,getEnumValues:()=>xSe,getLengthableOrigin:()=>Wq,getParsedType:()=>DWr,getSizableOrigin:()=>ZQt,isObject:()=>LJ,isPlainObject:()=>SJ,issue:()=>BSe,joinValues:()=>Tme,jsonStringifyReplacer:()=>VSe,merge:()=>_Wr,normalizeParams:()=>ka,nullish:()=>Nq,numKeys:()=>TWr,omit:()=>MWr,optionalKeys:()=>LSe,partial:()=>PWr,pick:()=>UWr,prefixIssues:()=>PW,primitiveTypes:()=>gQt,promiseAllObject:()=>BWr,propertyKeyTypes:()=>kSe,randomString:()=>JWr,required:()=>jWr,stringifyPrimitive:()=>Ome,unwrapMessage:()=>vq});function QWr(n){return n}function HWr(n){return n}function XWr(n){}function kWr(n){throw new Error}function LWr(n){}function xSe(n){let t=Object.values(n).filter(a=>typeof a=="number");return Object.entries(n).filter(([a,i])=>t.indexOf(+a)===-1).map(([a,i])=>i)}function Tme(n,t="|"){return n.map(r=>Ome(r)).join(t)}function VSe(n,t){return typeof t=="bigint"?t.toString():t}function Zq(n){return{get value(){{let r=n();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Nq(n){return n==null}function Aq(n){let t=n.startsWith("^")?1:0,r=n.endsWith("$")?n.length-1:n.length;return n.slice(t,r)}function QSe(n,t){let r=(n.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a,s=Number.parseInt(n.toFixed(i).replace(".","")),e=Number.parseInt(t.toFixed(i).replace(".",""));return s%e/10**i}function Qc(n,t,r){Object.defineProperty(n,t,{get(){{let i=r();return n[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(n,t,{value:i})},configurable:!0})}function HSe(n,t,r){Object.defineProperty(n,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function SWr(n,t){return t?t.reduce((r,a)=>r?.[a],n):n}function BWr(n){let t=Object.keys(n),r=t.map(a=>n[a]);return Promise.all(r).then(a=>{let i={};for(let s=0;s<t.length;s++)i[t[s]]=a[s];return i})}function JWr(n=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let a=0;a<n;a++)r+=t[Math.floor(Math.random()*t.length)];return r}function u9(n){return JSON.stringify(n)}function LJ(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function SJ(n){if(LJ(n)===!1)return!1;let t=n.constructor;if(t===void 0)return!0;let r=t.prototype;return!(LJ(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function TWr(n){let t=0;for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&t++;return t}function Tw(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function MN(n,t,r){let a=new n._zod.constr(t??n._zod.def);return(!t||r?.parent)&&(a._zod.parent=n),a}function ka(n){let t=n;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function OWr(n){let t;return new Proxy({},{get(r,a,i){return t??(t=n()),Reflect.get(t,a,i)},set(r,a,i,s){return t??(t=n()),Reflect.set(t,a,i,s)},has(r,a){return t??(t=n()),Reflect.has(t,a)},deleteProperty(r,a){return t??(t=n()),Reflect.deleteProperty(t,a)},ownKeys(r){return t??(t=n()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,a){return t??(t=n()),Reflect.getOwnPropertyDescriptor(t,a)},defineProperty(r,a,i){return t??(t=n()),Reflect.defineProperty(t,a,i)}})}function Ome(n){return typeof n=="bigint"?n.toString()+"n":typeof n=="string"?`"${n}"`:`${n}`}function LSe(n){return Object.keys(n).filter(t=>n[t]._zod.optin==="optional"&&n[t]._zod.optout==="optional")}function UWr(n,t){let r={},a=n._zod.def;for(let i in t){if(!(i in a.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=a.shape[i])}return MN(n,{...n._zod.def,shape:r,checks:[]})}function MWr(n,t){let r={...n._zod.def.shape},a=n._zod.def;for(let i in t){if(!(i in a.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return MN(n,{...n._zod.def,shape:r,checks:[]})}function zWr(n,t){if(!SJ(t))throw new Error("Invalid input to extend: expected a plain object");let r={...n._zod.def,get shape(){let a={...n._zod.def.shape,...t};return HSe(this,"shape",a),a},checks:[]};return MN(n,r)}function _Wr(n,t){return MN(n,{...n._zod.def,get shape(){let r={...n._zod.def.shape,...t._zod.def.shape};return HSe(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function PWr(n,t,r){let a=t._zod.def.shape,i={...a};if(r)for(let s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=n?new n({type:"optional",innerType:a[s]}):a[s])}else for(let s in a)i[s]=n?new n({type:"optional",innerType:a[s]}):a[s];return MN(t,{...t._zod.def,shape:i,checks:[]})}function jWr(n,t,r){let a=t._zod.def.shape,i={...a};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new n({type:"nonoptional",innerType:a[s]}))}else for(let s in a)i[s]=new n({type:"nonoptional",innerType:a[s]});return MN(t,{...t._zod.def,shape:i,checks:[]})}function I9(n,t=0){for(let r=t;r<n.issues.length;r++)if(n.issues[r]?.continue!==!0)return!0;return!1}function PW(n,t){return t.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(n),r})}function vq(n){return typeof n=="string"?n:n?.message}function zN(n,t,r){let a={...n,path:n.path??[]};if(!n.message){let i=vq(n.inst?._zod.def?.error?.(n))??vq(t?.error?.(n))??vq(r.customError?.(n))??vq(r.localeError?.(n))??"Invalid input";a.message=i}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function ZQt(n){return n instanceof Set?"set":n instanceof Map?"map":n instanceof File?"file":"unknown"}function Wq(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function BSe(...n){let[t,r,a]=n;return typeof t=="string"?{message:t,code:"custom",input:r,inst:a}:{...t}}function KWr(n){return Object.entries(n).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Dme,XSe,DWr,kSe,gQt,SSe,vQt,YSe,aE=ut(()=>{Dme=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};XSe=Zq(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let n=Function;return new n(""),!0}catch{return!1}});DWr=n=>{let t=typeof n;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(n)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(n)?"array":n===null?"null":n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?"promise":typeof Map<"u"&&n instanceof Map?"map":typeof Set<"u"&&n instanceof Set?"set":typeof Date<"u"&&n instanceof Date?"date":typeof File<"u"&&n instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},kSe=new Set(["string","number","symbol"]),gQt=new Set(["string","number","bigint","boolean","symbol","undefined"]);SSe={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},vQt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};YSe=class{constructor(...t){}}});function TSe(n,t=r=>r.message){let r={},a=[];for(let i of n.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):a.push(t(i));return{formErrors:a,fieldErrors:r}}function DSe(n,t){let r=t||function(s){return s.message},a={_errors:[]},i=s=>{for(let e of s.issues)if(e.code==="invalid_union"&&e.errors.length)e.errors.map(o=>i({issues:o}));else if(e.code==="invalid_key")i({issues:e.issues});else if(e.code==="invalid_element")i({issues:e.issues});else if(e.path.length===0)a._errors.push(r(e));else{let o=a,u=0;for(;u<e.path.length;){let d=e.path[u];u===e.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(r(e))):o[d]=o[d]||{_errors:[]},o=o[d],u++}}};return i(n),a}var NQt,Ume,JSe,OSe=ut(()=>{kJ();aE();NQt=(n,t)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:t,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(t,VSe,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},Ume=Tn("$ZodError",NQt),JSe=Tn("$ZodError",NQt,{Parent:Error})});var AQt,WQt,USe,yq,MSe,Mme,zSe=ut(()=>{kJ();OSe();aE();AQt=n=>(t,r,a,i)=>{let s=a?Object.assign(a,{async:!1}):{async:!1},e=t._zod.run({value:r,issues:[]},s);if(e instanceof Promise)throw new rE;if(e.issues.length){let o=new(i?.Err??n)(e.issues.map(u=>zN(u,s,l1())));throw Dme(o,i?.callee),o}return e.value},WQt=n=>async(t,r,a,i)=>{let s=a?Object.assign(a,{async:!0}):{async:!0},e=t._zod.run({value:r,issues:[]},s);if(e instanceof Promise&&(e=await e),e.issues.length){let o=new(i?.Err??n)(e.issues.map(u=>zN(u,s,l1())));throw Dme(o,i?.callee),o}return e.value},USe=n=>(t,r,a)=>{let i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new rE;return s.issues.length?{success:!1,error:new(n??Ume)(s.issues.map(e=>zN(e,i,l1())))}:{success:!0,data:s.value}},yq=USe(JSe),MSe=n=>async(t,r,a)=>{let i=a?Object.assign(a,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new n(s.issues.map(e=>zN(e,i,l1())))}:{success:!0,data:s.value}},Mme=MSe(JSe)});function QQt(){return new RegExp($Wr,"u")}function OQt(n){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${t}`:n.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${n.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function UQt(n){return new RegExp(`^${OQt(n)}$`)}function MQt(n){let t=OQt({precision:n.precision}),r=["Z"];n.local&&r.push(""),n.offset&&r.push("([+-]\\d{2}:\\d{2})");let a=`${t}(?:${r.join("|")})`;return new RegExp(`^${TQt}T(?:${a})$`)}var yQt,FQt,EQt,RQt,wQt,CQt,YQt,xQt,_Se,VQt,$Wr,HQt,XQt,kQt,LQt,SQt,PSe,BQt,JQt,TQt,DQt,zQt,_Qt,PQt,jQt,KQt,qQt,$Qt,e9t,_me=ut(()=>{yQt=/^[cC][^\s-]{8,}$/,FQt=/^[0-9a-z]+$/,EQt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,RQt=/^[0-9a-vA-V]{20}$/,wQt=/^[A-Za-z0-9]{27}$/,CQt=/^[a-zA-Z0-9_-]{21}$/,YQt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xQt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_Se=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,VQt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,$Wr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";HQt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,XQt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,kQt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,LQt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,SQt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,PSe=/^[A-Za-z0-9_-]*$/,BQt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,JQt=/^\+(?:[0-9]){6,14}[0-9]$/,TQt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",DQt=new RegExp(`^${TQt}$`);zQt=n=>{let t=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},_Qt=/^\d+n?$/,PQt=/^\d+$/,jQt=/^-?\d+(?:\.\d+)?/i,KQt=/true|false/i,qQt=/null/i,$Qt=/^[^A-Z]*$/,e9t=/^[^a-z]*$/});var bp,t9t,jSe,KSe,n9t,r9t,a9t,i9t,l9t,Fq,s9t,o9t,c9t,u9t,I9t,d9t,h9t,Pme=ut(()=>{kJ();_me();aE();bp=Tn("$ZodCheck",(n,t)=>{var r;n._zod??(n._zod={}),n._zod.def=t,(r=n._zod).onattach??(r.onattach=[])}),t9t={number:"number",bigint:"bigint",object:"date"},jSe=Tn("$ZodCheckLessThan",(n,t)=>{bp.init(n,t);let r=t9t[typeof t.value];n._zod.onattach.push(a=>{let i=a._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),n._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:r,code:"too_big",maximum:t.value,input:a.value,inclusive:t.inclusive,inst:n,continue:!t.abort})}}),KSe=Tn("$ZodCheckGreaterThan",(n,t)=>{bp.init(n,t);let r=t9t[typeof t.value];n._zod.onattach.push(a=>{let i=a._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),n._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:t.value,input:a.value,inclusive:t.inclusive,inst:n,continue:!t.abort})}}),n9t=Tn("$ZodCheckMultipleOf",(n,t)=>{bp.init(n,t),n._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.multipleOf=t.value)}),n._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):QSe(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:n,continue:!t.abort})}}),r9t=Tn("$ZodCheckNumberFormat",(n,t)=>{bp.init(n,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,s]=SSe[t.format];n._zod.onattach.push(e=>{let o=e._zod.bag;o.format=t.format,o.minimum=i,o.maximum=s,r&&(o.pattern=PQt)}),n._zod.check=e=>{let o=e.value;if(r){if(!Number.isInteger(o)){e.issues.push({expected:a,format:t.format,code:"invalid_type",input:o,inst:n});return}if(!Number.isSafeInteger(o)){o>0?e.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:a,continue:!t.abort}):e.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:a,continue:!t.abort});return}}o<i&&e.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:n,continue:!t.abort}),o>s&&e.issues.push({origin:"number",input:o,code:"too_big",maximum:s,inst:n})}}),a9t=Tn("$ZodCheckMaxLength",(n,t)=>{var r;bp.init(n,t),(r=n._zod.def).when??(r.when=a=>{let i=a.value;return!Nq(i)&&i.length!==void 0}),n._zod.onattach.push(a=>{let i=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(a._zod.bag.maximum=t.maximum)}),n._zod.check=a=>{let i=a.value;if(i.length<=t.maximum)return;let e=Wq(i);a.issues.push({origin:e,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:n,continue:!t.abort})}}),i9t=Tn("$ZodCheckMinLength",(n,t)=>{var r;bp.init(n,t),(r=n._zod.def).when??(r.when=a=>{let i=a.value;return!Nq(i)&&i.length!==void 0}),n._zod.onattach.push(a=>{let i=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(a._zod.bag.minimum=t.minimum)}),n._zod.check=a=>{let i=a.value;if(i.length>=t.minimum)return;let e=Wq(i);a.issues.push({origin:e,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:n,continue:!t.abort})}}),l9t=Tn("$ZodCheckLengthEquals",(n,t)=>{var r;bp.init(n,t),(r=n._zod.def).when??(r.when=a=>{let i=a.value;return!Nq(i)&&i.length!==void 0}),n._zod.onattach.push(a=>{let i=a._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),n._zod.check=a=>{let i=a.value,s=i.length;if(s===t.length)return;let e=Wq(i),o=s>t.length;a.issues.push({origin:e,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:n,continue:!t.abort})}}),Fq=Tn("$ZodCheckStringFormat",(n,t)=>{var r,a;bp.init(n,t),n._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=n._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:n,continue:!t.abort})}):(a=n._zod).check??(a.check=()=>{})}),s9t=Tn("$ZodCheckRegex",(n,t)=>{Fq.init(n,t),n._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:n,continue:!t.abort})}}),o9t=Tn("$ZodCheckLowerCase",(n,t)=>{t.pattern??(t.pattern=$Qt),Fq.init(n,t)}),c9t=Tn("$ZodCheckUpperCase",(n,t)=>{t.pattern??(t.pattern=e9t),Fq.init(n,t)}),u9t=Tn("$ZodCheckIncludes",(n,t)=>{bp.init(n,t);let r=Tw(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=a,n._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),n._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:n,continue:!t.abort})}}),I9t=Tn("$ZodCheckStartsWith",(n,t)=>{bp.init(n,t);let r=new RegExp(`^${Tw(t.prefix)}.*`);t.pattern??(t.pattern=r),n._zod.onattach.push(a=>{let i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),n._zod.check=a=>{a.value.startsWith(t.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:a.value,inst:n,continue:!t.abort})}}),d9t=Tn("$ZodCheckEndsWith",(n,t)=>{bp.init(n,t);let r=new RegExp(`.*${Tw(t.suffix)}$`);t.pattern??(t.pattern=r),n._zod.onattach.push(a=>{let i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),n._zod.check=a=>{a.value.endsWith(t.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:a.value,inst:n,continue:!t.abort})}}),h9t=Tn("$ZodCheckOverwrite",(n,t)=>{bp.init(n,t),n._zod.check=r=>{r.value=t.tx(r.value)}})});var jme,qSe=ut(()=>{jme=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let a=t.split(`
|
|
707
707
|
`).filter(e=>e),i=Math.min(...a.map(e=>e.length-e.trimStart().length)),s=a.map(e=>e.slice(i)).map(e=>" ".repeat(this.indent*2)+e);for(let e of s)this.content.push(e)}compile(){let t=Function,r=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,i.join(`
|
|
708
708
|
`))}}});var p9t,$Se=ut(()=>{p9t={major:4,minor:0,patch:0}});function O9t(n){if(n==="")return!0;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}function eyr(n){if(!PSe.test(n))return!1;let t=n.replace(/[-_]/g,a=>a==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return O9t(r)}function tyr(n,t=null){try{let r=n.split(".");if(r.length!==3)return!1;let[a]=r;if(!a)return!1;let i=JSON.parse(atob(a));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}function b9t(n,t,r){n.issues.length&&t.issues.push(...PW(r,n.issues)),t.value[r]=n.value}function Kme(n,t,r){n.issues.length&&t.issues.push(...PW(r,n.issues)),t.value[r]=n.value}function f9t(n,t,r,a){n.issues.length?a[r]===void 0?r in a?t.value[r]=void 0:t.value[r]=n.value:t.issues.push(...PW(r,n.issues)):n.value===void 0?r in a&&(t.value[r]=void 0):t.value[r]=n.value}function G9t(n,t,r,a){for(let i of n)if(i.issues.length===0)return t.value=i.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:n.map(i=>i.issues.map(s=>zN(s,a,l1())))}),t}function eBe(n,t){if(n===t)return{valid:!0,data:n};if(n instanceof Date&&t instanceof Date&&+n==+t)return{valid:!0,data:n};if(SJ(n)&&SJ(t)){let r=Object.keys(t),a=Object.keys(n).filter(s=>r.indexOf(s)!==-1),i={...n,...t};for(let s of a){let e=eBe(n[s],t[s]);if(!e.valid)return{valid:!1,mergeErrorPath:[s,...e.mergeErrorPath]};i[s]=e.data}return{valid:!0,data:i}}if(Array.isArray(n)&&Array.isArray(t)){if(n.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let a=0;a<n.length;a++){let i=n[a],s=t[a],e=eBe(i,s);if(!e.valid)return{valid:!1,mergeErrorPath:[a,...e.mergeErrorPath]};r.push(e.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function g9t(n,t,r){if(t.issues.length&&n.issues.push(...t.issues),r.issues.length&&n.issues.push(...r.issues),I9(n))return n;let a=eBe(t.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return n.value=a.data,n}function v9t(n,t){return n.value===void 0&&(n.value=t.defaultValue),n}function Z9t(n,t){return!n.issues.length&&n.value===void 0&&n.issues.push({code:"invalid_type",expected:"nonoptional",input:n.value,inst:t}),n}function N9t(n,t,r){return I9(n)?n:t.out._zod.run({value:n.value,issues:n.issues},r)}function A9t(n){return n.value=Object.freeze(n.value),n}function W9t(n,t,r,a){if(!n){let i={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(i.params=a._zod.def.params),t.issues.push(BSe(i))}}var Do,qme,ru,y9t,F9t,E9t,R9t,w9t,C9t,Y9t,x9t,V9t,Q9t,H9t,X9t,k9t,L9t,S9t,B9t,J9t,T9t,D9t,U9t,M9t,z9t,_9t,tBe,P9t,j9t,K9t,q9t,$9t,eHt,tHt,nHt,rHt,aHt,nBe,iHt,lHt,sHt,oHt,cHt,uHt,IHt,dHt,hHt,mHt,pHt,bHt,fHt,GHt,gHt,vHt=ut(()=>{Pme();kJ();qSe();zSe();_me();aE();$Se();aE();Do=Tn("$ZodType",(n,t)=>{var r;n??(n={}),n._zod.def=t,n._zod.bag=n._zod.bag||{},n._zod.version=p9t;let a=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&a.unshift(n);for(let i of a)for(let s of i._zod.onattach)s(n);if(a.length===0)(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let i=(s,e,o)=>{let u=I9(s),d;for(let I of e){if(I._zod.def.when){if(!I._zod.def.when(s))continue}else if(u)continue;let h=s.issues.length,c=I._zod.check(s);if(c instanceof Promise&&o?.async===!1)throw new rE;if(d||c instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await c,s.issues.length!==h&&(u||(u=I9(s,h)))});else{if(s.issues.length===h)continue;u||(u=I9(s,h))}}return d?d.then(()=>s):s};n._zod.run=(s,e)=>{let o=n._zod.parse(s,e);if(o instanceof Promise){if(e.async===!1)throw new rE;return o.then(u=>i(u,a,e))}return i(o,a,e)}}n["~standard"]={validate:i=>{try{let s=yq(n,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Mme(n,i).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),qme=Tn("$ZodString",(n,t)=>{Do.init(n,t),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??zQt(n._zod.bag),n._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:n}),r}}),ru=Tn("$ZodStringFormat",(n,t)=>{Fq.init(n,t),qme.init(n,t)}),y9t=Tn("$ZodGUID",(n,t)=>{t.pattern??(t.pattern=xQt),ru.init(n,t)}),F9t=Tn("$ZodUUID",(n,t)=>{if(t.version){let a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=_Se(a))}else t.pattern??(t.pattern=_Se());ru.init(n,t)}),E9t=Tn("$ZodEmail",(n,t)=>{t.pattern??(t.pattern=VQt),ru.init(n,t)}),R9t=Tn("$ZodURL",(n,t)=>{ru.init(n,t),n._zod.check=r=>{try{let a=r.value,i=new URL(a),s=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:BQt.source,input:r.value,inst:n,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:n,continue:!t.abort})),!a.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:n,continue:!t.abort})}}}),w9t=Tn("$ZodEmoji",(n,t)=>{t.pattern??(t.pattern=QQt()),ru.init(n,t)}),C9t=Tn("$ZodNanoID",(n,t)=>{t.pattern??(t.pattern=CQt),ru.init(n,t)}),Y9t=Tn("$ZodCUID",(n,t)=>{t.pattern??(t.pattern=yQt),ru.init(n,t)}),x9t=Tn("$ZodCUID2",(n,t)=>{t.pattern??(t.pattern=FQt),ru.init(n,t)}),V9t=Tn("$ZodULID",(n,t)=>{t.pattern??(t.pattern=EQt),ru.init(n,t)}),Q9t=Tn("$ZodXID",(n,t)=>{t.pattern??(t.pattern=RQt),ru.init(n,t)}),H9t=Tn("$ZodKSUID",(n,t)=>{t.pattern??(t.pattern=wQt),ru.init(n,t)}),X9t=Tn("$ZodISODateTime",(n,t)=>{t.pattern??(t.pattern=MQt(t)),ru.init(n,t)}),k9t=Tn("$ZodISODate",(n,t)=>{t.pattern??(t.pattern=DQt),ru.init(n,t)}),L9t=Tn("$ZodISOTime",(n,t)=>{t.pattern??(t.pattern=UQt(t)),ru.init(n,t)}),S9t=Tn("$ZodISODuration",(n,t)=>{t.pattern??(t.pattern=YQt),ru.init(n,t)}),B9t=Tn("$ZodIPv4",(n,t)=>{t.pattern??(t.pattern=HQt),ru.init(n,t),n._zod.onattach.push(r=>{let a=r._zod.bag;a.format="ipv4"})}),J9t=Tn("$ZodIPv6",(n,t)=>{t.pattern??(t.pattern=XQt),ru.init(n,t),n._zod.onattach.push(r=>{let a=r._zod.bag;a.format="ipv6"}),n._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:n,continue:!t.abort})}}}),T9t=Tn("$ZodCIDRv4",(n,t)=>{t.pattern??(t.pattern=kQt),ru.init(n,t)}),D9t=Tn("$ZodCIDRv6",(n,t)=>{t.pattern??(t.pattern=LQt),ru.init(n,t),n._zod.check=r=>{let[a,i]=r.value.split("/");try{if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:n,continue:!t.abort})}}});U9t=Tn("$ZodBase64",(n,t)=>{t.pattern??(t.pattern=SQt),ru.init(n,t),n._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),n._zod.check=r=>{O9t(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:n,continue:!t.abort})}});M9t=Tn("$ZodBase64URL",(n,t)=>{t.pattern??(t.pattern=PSe),ru.init(n,t),n._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),n._zod.check=r=>{eyr(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:n,continue:!t.abort})}}),z9t=Tn("$ZodE164",(n,t)=>{t.pattern??(t.pattern=JQt),ru.init(n,t)});_9t=Tn("$ZodJWT",(n,t)=>{ru.init(n,t),n._zod.check=r=>{tyr(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:n,continue:!t.abort})}}),tBe=Tn("$ZodNumber",(n,t)=>{Do.init(n,t),n._zod.pattern=n._zod.bag.pattern??jQt,n._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:n,...s?{received:s}:{}}),r}}),P9t=Tn("$ZodNumber",(n,t)=>{r9t.init(n,t),tBe.init(n,t)}),j9t=Tn("$ZodBoolean",(n,t)=>{Do.init(n,t),n._zod.pattern=KQt,n._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:n}),r}}),K9t=Tn("$ZodBigInt",(n,t)=>{Do.init(n,t),n._zod.pattern=_Qt,n._zod.parse=(r,a)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:n}),r}}),q9t=Tn("$ZodNull",(n,t)=>{Do.init(n,t),n._zod.pattern=qQt,n._zod.values=new Set([null]),n._zod.parse=(r,a)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:n}),r}}),$9t=Tn("$ZodAny",(n,t)=>{Do.init(n,t),n._zod.parse=r=>r}),eHt=Tn("$ZodUnknown",(n,t)=>{Do.init(n,t),n._zod.parse=r=>r}),tHt=Tn("$ZodNever",(n,t)=>{Do.init(n,t),n._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:n}),r)}),nHt=Tn("$ZodDate",(n,t)=>{Do.init(n,t),n._zod.parse=(r,a)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,s=i instanceof Date;return s&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...s?{received:"Invalid Date"}:{},inst:n}),r}});rHt=Tn("$ZodArray",(n,t)=>{Do.init(n,t),n._zod.parse=(r,a)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:n}),r;r.value=Array(i.length);let s=[];for(let e=0;e<i.length;e++){let o=i[e],u=t.element._zod.run({value:o,issues:[]},a);u instanceof Promise?s.push(u.then(d=>b9t(d,r,e))):b9t(u,r,e)}return s.length?Promise.all(s).then(()=>r):r}});aHt=Tn("$ZodObject",(n,t)=>{Do.init(n,t);let r=Zq(()=>{let h=Object.keys(t.shape);for(let G of h)if(!(t.shape[G]instanceof Do))throw new Error(`Invalid element at key "${G}": expected a Zod schema`);let c=LSe(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(c)}});Qc(n._zod,"propValues",()=>{let h=t.shape,c={};for(let G in h){let F=h[G]._zod;if(F.values){c[G]??(c[G]=new Set);for(let W of F.values)c[G].add(W)}}return c});let a=h=>{let c=new jme(["shape","payload","ctx"]),G=r.value,F=w=>{let A=u9(w);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};c.write("const input = payload.value;");let W=Object.create(null),R=0;for(let w of G.keys)W[w]=`key_${R++}`;c.write("const newResult = {}");for(let w of G.keys)if(G.optionalKeys.has(w)){let A=W[w];c.write(`const ${A} = ${F(w)};`);let E=u9(w);c.write(`
|
|
709
709
|
if (${A}.issues.length) {
|
|
@@ -1802,8 +1802,8 @@ ${JSON.stringify(Fe,null,4)}`);let ye=Fe;if(tI.string(ye.id)||tI.number(ye.id)){
|
|
|
1802
1802
|
|
|
1803
1803
|
`:Fe.error===void 0&&(ke=`No result returned.
|
|
1804
1804
|
|
|
1805
|
-
`)),ye){let _e=Fe.error?` Request failed: ${Fe.error.message} (${Fe.error.code}).`:"";f.log(`Received response '${ye.method} - (${Fe.id})' in ${Date.now()-ye.timerStart}ms.${_e}`,ke)}else f.log(`Received response ${Fe.id} without active response promise.`,ke)}else ie("receive-response",Fe)}function ie(Fe,ye){if(!f||A===bo.Off)return;let ke={isLSPMessage:!0,type:Fe,message:ye,timestamp:Date.now()};f.log(ke)}function se(){if(X())throw new XO(kae.Closed,"Connection is closed.");if(Q())throw new XO(kae.Disposed,"Connection is disposed.")}function ue(){if(k())throw new XO(kae.AlreadyListening,"Connection is already listening")}function me(){if(!k())throw new Error("Call listen() first.")}function he(Fe){return Fe===void 0?null:Fe}function We(Fe){if(Fe!==null)return Fe}function Re(Fe){return Fe!=null&&!Array.isArray(Fe)&&typeof Fe=="object"}function Ce(Fe,ye){switch(Fe){case oi.ParameterStructures.auto:return Re(ye)?We(ye):[he(ye)];case oi.ParameterStructures.byName:if(!Re(ye))throw new Error("Received parameters by name but param is not an object literal.");return We(ye);case oi.ParameterStructures.byPosition:return[he(ye)];default:throw new Error(`Unknown parameter structure ${Fe.toString()}`)}}function Ee(Fe,ye){let ke,_e=Fe.numberOfParams;switch(_e){case 0:ke=void 0;break;case 1:ke=Ce(Fe.parameterStructures,ye[0]);break;default:ke=[];for(let rt=0;rt<ye.length&&rt<_e;rt++)ke.push(he(ye[rt]));if(ye.length<_e)for(let rt=ye.length;rt<_e;rt++)ke.push(null);break}return ke}let Qe={sendNotification:(Fe,...ye)=>{se();let ke,_e;if(tI.string(Fe)){ke=Fe;let ot=ye[0],dt=0,Te=oi.ParameterStructures.auto;oi.ParameterStructures.is(ot)&&(dt=1,Te=ot);let Ue=ye.length,at=Ue-dt;switch(at){case 0:_e=void 0;break;case 1:_e=Ce(Te,ye[dt]);break;default:if(Te===oi.ParameterStructures.byName)throw new Error(`Received ${at} parameters for 'by Name' notification parameter structure.`);_e=ye.slice(dt,Ue).map(Se=>he(Se));break}}else{let ot=ye;ke=Fe.method,_e=Ee(Fe,ot)}let rt={jsonrpc:u,method:ke,params:_e};return q(rt),t.write(rt).catch(ot=>{throw i.error("Sending notification failed."),ot})},onNotification:(Fe,ye)=>{se();let ke;return tI.func(Fe)?h=Fe:ye&&(tI.string(Fe)?(ke=Fe,c.set(Fe,{type:void 0,handler:ye})):(ke=Fe.method,c.set(Fe.method,{type:Fe,handler:ye}))),{dispose:()=>{ke!==void 0?c.delete(ke):h=void 0}}},onProgress:(Fe,ye,ke)=>{if(G.has(ye))throw new Error(`Progress handler for token ${ye} already registered`);return G.set(ye,ke),{dispose:()=>{G.delete(ye)}}},sendProgress:(Fe,ye,ke)=>Qe.sendNotification(Xae.type,{token:ye,value:ke}),onUnhandledProgress:p.event,sendRequest:(Fe,...ye)=>{se(),me();let ke,_e,rt;if(tI.string(Fe)){ke=Fe;let Ue=ye[0],at=ye[ye.length-1],Se=0,tt=oi.ParameterStructures.auto;oi.ParameterStructures.is(Ue)&&(Se=1,tt=Ue);let Oe=ye.length;vnt.CancellationToken.is(at)&&(Oe=Oe-1,rt=at);let et=Oe-Se;switch(et){case 0:_e=void 0;break;case 1:_e=Ce(tt,ye[Se]);break;default:if(tt===oi.ParameterStructures.byName)throw new Error(`Received ${et} parameters for 'by Name' request parameter structure.`);_e=ye.slice(Se,Oe).map(ne=>he(ne));break}}else{let Ue=ye;ke=Fe.method,_e=Ee(Fe,Ue);let at=Fe.numberOfParams;rt=vnt.CancellationToken.is(Ue[at])?Ue[at]:void 0}let ot=s++,dt;rt&&(dt=rt.onCancellationRequested(()=>{let Ue=Z.sender.sendCancellation(Qe,ot);return Ue===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${ot}`),Promise.resolve()):Ue.catch(()=>{i.log(`Sending cancellation messages for id ${ot} failed`)})}));let Te={jsonrpc:u,id:ot,method:ke,params:_e};return j(Te),typeof Z.sender.enableCancellation=="function"&&Z.sender.enableCancellation(Te),new Promise(async(Ue,at)=>{let Se=et=>{Ue(et),Z.sender.cleanup(ot),dt?.dispose()},tt=et=>{at(et),Z.sender.cleanup(ot),dt?.dispose()},Oe={method:ke,timerStart:Date.now(),resolve:Se,reject:tt};try{R.set(ot,Oe),await t.write(Te)}catch(et){throw R.delete(ot),Oe.reject(new oi.ResponseError(oi.ErrorCodes.MessageWriteError,et.message?et.message:"Unknown reason")),i.error("Sending request failed."),et}})},onRequest:(Fe,ye)=>{se();let ke=null;return Ant.is(Fe)?(ke=void 0,d=Fe):tI.string(Fe)?(ke=null,ye!==void 0&&(ke=Fe,I.set(Fe,{handler:ye,type:void 0}))):ye!==void 0&&(ke=Fe.method,I.set(Fe.method,{type:Fe,handler:ye})),{dispose:()=>{ke!==null&&(ke!==void 0?I.delete(ke):d=void 0)}}},hasPendingResponse:()=>R.size>0,trace:async(Fe,ye,ke)=>{let _e=!1,rt=S1.Text;ke!==void 0&&(tI.boolean(ke)?_e=ke:(_e=ke.sendNotification||!1,rt=ke.traceFormat||S1.Text)),A=Fe,E=rt,A===bo.Off?f=void 0:f=ye,_e&&!X()&&!Q()&&await Qe.sendNotification(Wnt.type,{value:bo.toString(Fe)})},onError:v.event,onClose:N.event,onUnhandledNotification:m.event,onDispose:b.event,end:()=>{t.end()},dispose:()=>{if(Q())return;g=JA.Disposed,b.fire(void 0);let Fe=new oi.ResponseError(oi.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let ye of R.values())ye.reject(Fe);R=new Map,w=new Map,y=new Set,W=new Tmn.LinkedMap,tI.func(t.dispose)&&t.dispose(),tI.func(n.dispose)&&n.dispose()},listen:()=>{se(),ue(),g=JA.Listening,n.listen(B)},inspect:()=>{(0,Jmn.default)().console.log("inspect")}};return Qe.onNotification(uNe.type,Fe=>{if(A===bo.Off||!f)return;let ye=A===bo.Verbose||A===bo.Compact;f.log(Fe.message,ye?Fe.verbose:void 0)}),Qe.onNotification(Xae.type,Fe=>{let ye=G.get(Fe.token);ye?ye(Fe.value):p.fire(Fe)}),Qe}Ji.createMessageConnection=bIa});var bNe=ve(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.ProgressType=zn.ProgressToken=zn.createMessageConnection=zn.NullLogger=zn.ConnectionOptions=zn.ConnectionStrategy=zn.AbstractMessageBuffer=zn.WriteableStreamMessageWriter=zn.AbstractMessageWriter=zn.MessageWriter=zn.ReadableStreamMessageReader=zn.AbstractMessageReader=zn.MessageReader=zn.SharedArrayReceiverStrategy=zn.SharedArraySenderStrategy=zn.CancellationToken=zn.CancellationTokenSource=zn.Emitter=zn.Event=zn.Disposable=zn.LRUCache=zn.Touch=zn.LinkedMap=zn.ParameterStructures=zn.NotificationType9=zn.NotificationType8=zn.NotificationType7=zn.NotificationType6=zn.NotificationType5=zn.NotificationType4=zn.NotificationType3=zn.NotificationType2=zn.NotificationType1=zn.NotificationType0=zn.NotificationType=zn.ErrorCodes=zn.ResponseError=zn.RequestType9=zn.RequestType8=zn.RequestType7=zn.RequestType6=zn.RequestType5=zn.RequestType4=zn.RequestType3=zn.RequestType2=zn.RequestType1=zn.RequestType0=zn.RequestType=zn.Message=zn.RAL=void 0;zn.MessageStrategy=zn.CancellationStrategy=zn.CancellationSenderStrategy=zn.CancellationReceiverStrategy=zn.ConnectionError=zn.ConnectionErrors=zn.LogTraceNotification=zn.SetTraceNotification=zn.TraceFormat=zn.TraceValues=zn.Trace=void 0;var Dc=qtt();Object.defineProperty(zn,"Message",{enumerable:!0,get:function(){return Dc.Message}});Object.defineProperty(zn,"RequestType",{enumerable:!0,get:function(){return Dc.RequestType}});Object.defineProperty(zn,"RequestType0",{enumerable:!0,get:function(){return Dc.RequestType0}});Object.defineProperty(zn,"RequestType1",{enumerable:!0,get:function(){return Dc.RequestType1}});Object.defineProperty(zn,"RequestType2",{enumerable:!0,get:function(){return Dc.RequestType2}});Object.defineProperty(zn,"RequestType3",{enumerable:!0,get:function(){return Dc.RequestType3}});Object.defineProperty(zn,"RequestType4",{enumerable:!0,get:function(){return Dc.RequestType4}});Object.defineProperty(zn,"RequestType5",{enumerable:!0,get:function(){return Dc.RequestType5}});Object.defineProperty(zn,"RequestType6",{enumerable:!0,get:function(){return Dc.RequestType6}});Object.defineProperty(zn,"RequestType7",{enumerable:!0,get:function(){return Dc.RequestType7}});Object.defineProperty(zn,"RequestType8",{enumerable:!0,get:function(){return Dc.RequestType8}});Object.defineProperty(zn,"RequestType9",{enumerable:!0,get:function(){return Dc.RequestType9}});Object.defineProperty(zn,"ResponseError",{enumerable:!0,get:function(){return Dc.ResponseError}});Object.defineProperty(zn,"ErrorCodes",{enumerable:!0,get:function(){return Dc.ErrorCodes}});Object.defineProperty(zn,"NotificationType",{enumerable:!0,get:function(){return Dc.NotificationType}});Object.defineProperty(zn,"NotificationType0",{enumerable:!0,get:function(){return Dc.NotificationType0}});Object.defineProperty(zn,"NotificationType1",{enumerable:!0,get:function(){return Dc.NotificationType1}});Object.defineProperty(zn,"NotificationType2",{enumerable:!0,get:function(){return Dc.NotificationType2}});Object.defineProperty(zn,"NotificationType3",{enumerable:!0,get:function(){return Dc.NotificationType3}});Object.defineProperty(zn,"NotificationType4",{enumerable:!0,get:function(){return Dc.NotificationType4}});Object.defineProperty(zn,"NotificationType5",{enumerable:!0,get:function(){return Dc.NotificationType5}});Object.defineProperty(zn,"NotificationType6",{enumerable:!0,get:function(){return Dc.NotificationType6}});Object.defineProperty(zn,"NotificationType7",{enumerable:!0,get:function(){return Dc.NotificationType7}});Object.defineProperty(zn,"NotificationType8",{enumerable:!0,get:function(){return Dc.NotificationType8}});Object.defineProperty(zn,"NotificationType9",{enumerable:!0,get:function(){return Dc.NotificationType9}});Object.defineProperty(zn,"ParameterStructures",{enumerable:!0,get:function(){return Dc.ParameterStructures}});var Ent=ent();Object.defineProperty(zn,"LinkedMap",{enumerable:!0,get:function(){return Ent.LinkedMap}});Object.defineProperty(zn,"LRUCache",{enumerable:!0,get:function(){return Ent.LRUCache}});Object.defineProperty(zn,"Touch",{enumerable:!0,get:function(){return Ent.Touch}});var fIa=Cmn();Object.defineProperty(zn,"Disposable",{enumerable:!0,get:function(){return fIa.Disposable}});var Mmn=xO();Object.defineProperty(zn,"Event",{enumerable:!0,get:function(){return Mmn.Event}});Object.defineProperty(zn,"Emitter",{enumerable:!0,get:function(){return Mmn.Emitter}});var zmn=iNe();Object.defineProperty(zn,"CancellationTokenSource",{enumerable:!0,get:function(){return zmn.CancellationTokenSource}});Object.defineProperty(zn,"CancellationToken",{enumerable:!0,get:function(){return zmn.CancellationToken}});var _mn=xmn();Object.defineProperty(zn,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return _mn.SharedArraySenderStrategy}});Object.defineProperty(zn,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return _mn.SharedArrayReceiverStrategy}});var Rnt=Qmn();Object.defineProperty(zn,"MessageReader",{enumerable:!0,get:function(){return Rnt.MessageReader}});Object.defineProperty(zn,"AbstractMessageReader",{enumerable:!0,get:function(){return Rnt.AbstractMessageReader}});Object.defineProperty(zn,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return Rnt.ReadableStreamMessageReader}});var wnt=Smn();Object.defineProperty(zn,"MessageWriter",{enumerable:!0,get:function(){return wnt.MessageWriter}});Object.defineProperty(zn,"AbstractMessageWriter",{enumerable:!0,get:function(){return wnt.AbstractMessageWriter}});Object.defineProperty(zn,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return wnt.WriteableStreamMessageWriter}});var GIa=Bmn();Object.defineProperty(zn,"AbstractMessageBuffer",{enumerable:!0,get:function(){return GIa.AbstractMessageBuffer}});var Lm=Umn();Object.defineProperty(zn,"ConnectionStrategy",{enumerable:!0,get:function(){return Lm.ConnectionStrategy}});Object.defineProperty(zn,"ConnectionOptions",{enumerable:!0,get:function(){return Lm.ConnectionOptions}});Object.defineProperty(zn,"NullLogger",{enumerable:!0,get:function(){return Lm.NullLogger}});Object.defineProperty(zn,"createMessageConnection",{enumerable:!0,get:function(){return Lm.createMessageConnection}});Object.defineProperty(zn,"ProgressToken",{enumerable:!0,get:function(){return Lm.ProgressToken}});Object.defineProperty(zn,"ProgressType",{enumerable:!0,get:function(){return Lm.ProgressType}});Object.defineProperty(zn,"Trace",{enumerable:!0,get:function(){return Lm.Trace}});Object.defineProperty(zn,"TraceValues",{enumerable:!0,get:function(){return Lm.TraceValues}});Object.defineProperty(zn,"TraceFormat",{enumerable:!0,get:function(){return Lm.TraceFormat}});Object.defineProperty(zn,"SetTraceNotification",{enumerable:!0,get:function(){return Lm.SetTraceNotification}});Object.defineProperty(zn,"LogTraceNotification",{enumerable:!0,get:function(){return Lm.LogTraceNotification}});Object.defineProperty(zn,"ConnectionErrors",{enumerable:!0,get:function(){return Lm.ConnectionErrors}});Object.defineProperty(zn,"ConnectionError",{enumerable:!0,get:function(){return Lm.ConnectionError}});Object.defineProperty(zn,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return Lm.CancellationReceiverStrategy}});Object.defineProperty(zn,"CancellationSenderStrategy",{enumerable:!0,get:function(){return Lm.CancellationSenderStrategy}});Object.defineProperty(zn,"CancellationStrategy",{enumerable:!0,get:function(){return Lm.CancellationStrategy}});Object.defineProperty(zn,"MessageStrategy",{enumerable:!0,get:function(){return Lm.MessageStrategy}});var gIa=EY();zn.RAL=gIa.default});var Kmn=ve(Vnt=>{"use strict";Object.defineProperty(Vnt,"__esModule",{value:!0});var Pmn=vt("util"),RR=bNe(),fNe=class n extends RR.AbstractMessageBuffer{constructor(t="utf-8"){super(t)}emptyBuffer(){return n.emptyBuffer}fromString(t,r){return Buffer.from(t,r)}toString(t,r){return t instanceof Buffer?t.toString(r):new Pmn.TextDecoder(r).decode(t)}asNative(t,r){return r===void 0?t instanceof Buffer?t:Buffer.from(t):t instanceof Buffer?t.slice(0,r):Buffer.from(t,0,r)}allocNative(t){return Buffer.allocUnsafe(t)}};fNe.emptyBuffer=Buffer.allocUnsafe(0);var Cnt=class{constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),RR.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),RR.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),RR.Disposable.create(()=>this.stream.off("end",t))}onData(t){return this.stream.on("data",t),RR.Disposable.create(()=>this.stream.off("data",t))}},Ynt=class{constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),RR.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),RR.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),RR.Disposable.create(()=>this.stream.off("end",t))}write(t,r){return new Promise((a,i)=>{let s=e=>{e==null?a():i(e)};typeof t=="string"?this.stream.write(t,r,s):this.stream.write(t,s)})}end(){this.stream.end()}},jmn=Object.freeze({messageBuffer:Object.freeze({create:n=>new fNe(n)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(n,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(n,void 0,0),t.charset))}catch(r){return Promise.reject(r)}}}),decoder:Object.freeze({name:"application/json",decode:(n,t)=>{try{return n instanceof Buffer?Promise.resolve(JSON.parse(n.toString(t.charset))):Promise.resolve(JSON.parse(new Pmn.TextDecoder(t.charset).decode(n)))}catch(r){return Promise.reject(r)}}})}),stream:Object.freeze({asReadableStream:n=>new Cnt(n),asWritableStream:n=>new Ynt(n)}),console,timer:Object.freeze({setTimeout(n,t,...r){let a=setTimeout(n,t,...r);return{dispose:()=>clearTimeout(a)}},setImmediate(n,...t){let r=setImmediate(n,...t);return{dispose:()=>clearImmediate(r)}},setInterval(n,t,...r){let a=setInterval(n,t,...r);return{dispose:()=>clearInterval(a)}}})});function xnt(){return jmn}(function(n){function t(){RR.RAL.install(jmn)}n.install=t})(xnt||(xnt={}));Vnt.default=xnt});var epn=ve(Is=>{"use strict";var vIa=Is&&Is.__createBinding||(Object.create?(function(n,t,r,a){a===void 0&&(a=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(n,a,i)}):(function(n,t,r,a){a===void 0&&(a=r),n[a]=t[r]})),ZIa=Is&&Is.__exportStar||function(n,t){for(var r in n)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&vIa(t,n,r)};Object.defineProperty(Is,"__esModule",{value:!0});Is.createMessageConnection=Is.createServerSocketTransport=Is.createClientSocketTransport=Is.createServerPipeTransport=Is.createClientPipeTransport=Is.generateRandomPipeName=Is.StreamMessageWriter=Is.StreamMessageReader=Is.SocketMessageWriter=Is.SocketMessageReader=Is.PortMessageWriter=Is.PortMessageReader=Is.IPCMessageWriter=Is.IPCMessageReader=void 0;var kO=Kmn();kO.default.install();var qmn=vt("path"),NIa=vt("os"),AIa=vt("crypto"),vNe=vt("net"),B1=bNe();ZIa(bNe(),Is);var Qnt=class extends B1.AbstractMessageReader{constructor(t){super(),this.process=t;let r=this.process;r.on("error",a=>this.fireError(a)),r.on("close",()=>this.fireClose())}listen(t){return this.process.on("message",t),B1.Disposable.create(()=>this.process.off("message",t))}};Is.IPCMessageReader=Qnt;var Hnt=class extends B1.AbstractMessageWriter{constructor(t){super(),this.process=t,this.errorCount=0;let r=this.process;r.on("error",a=>this.fireError(a)),r.on("close",()=>this.fireClose)}write(t){try{return typeof this.process.send=="function"&&this.process.send(t,void 0,void 0,r=>{r?(this.errorCount++,this.handleError(r,t)):this.errorCount=0}),Promise.resolve()}catch(r){return this.handleError(r,t),Promise.reject(r)}}handleError(t,r){this.errorCount++,this.fireError(t,r,this.errorCount)}end(){}};Is.IPCMessageWriter=Hnt;var Xnt=class extends B1.AbstractMessageReader{constructor(t){super(),this.onData=new B1.Emitter,t.on("close",()=>this.fireClose),t.on("error",r=>this.fireError(r)),t.on("message",r=>{this.onData.fire(r)})}listen(t){return this.onData.event(t)}};Is.PortMessageReader=Xnt;var knt=class extends B1.AbstractMessageWriter{constructor(t){super(),this.port=t,this.errorCount=0,t.on("close",()=>this.fireClose()),t.on("error",r=>this.fireError(r))}write(t){try{return this.port.postMessage(t),Promise.resolve()}catch(r){return this.handleError(r,t),Promise.reject(r)}}handleError(t,r){this.errorCount++,this.fireError(t,r,this.errorCount)}end(){}};Is.PortMessageWriter=knt;var CX=class extends B1.ReadableStreamMessageReader{constructor(t,r="utf-8"){super((0,kO.default)().stream.asReadableStream(t),r)}};Is.SocketMessageReader=CX;var YX=class extends B1.WriteableStreamMessageWriter{constructor(t,r){super((0,kO.default)().stream.asWritableStream(t),r),this.socket=t}dispose(){super.dispose(),this.socket.destroy()}};Is.SocketMessageWriter=YX;var GNe=class extends B1.ReadableStreamMessageReader{constructor(t,r){super((0,kO.default)().stream.asReadableStream(t),r)}};Is.StreamMessageReader=GNe;var gNe=class extends B1.WriteableStreamMessageWriter{constructor(t,r){super((0,kO.default)().stream.asWritableStream(t),r)}};Is.StreamMessageWriter=gNe;var $mn=process.env.XDG_RUNTIME_DIR,WIa=new Map([["linux",107],["darwin",103]]);function yIa(){let n=(0,AIa.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${n}-sock`;let t;$mn?t=qmn.join($mn,`vscode-ipc-${n}.sock`):t=qmn.join(NIa.tmpdir(),`vscode-${n}.sock`);let r=WIa.get(process.platform);return r!==void 0&&t.length>r&&(0,kO.default)().console.warn(`WARNING: IPC handle "${t}" is longer than ${r} characters.`),t}Is.generateRandomPipeName=yIa;function FIa(n,t="utf-8"){let r,a=new Promise((i,s)=>{r=i});return new Promise((i,s)=>{let e=(0,vNe.createServer)(o=>{e.close(),r([new CX(o,t),new YX(o,t)])});e.on("error",s),e.listen(n,()=>{e.removeListener("error",s),i({onConnected:()=>a})})})}Is.createClientPipeTransport=FIa;function EIa(n,t="utf-8"){let r=(0,vNe.createConnection)(n);return[new CX(r,t),new YX(r,t)]}Is.createServerPipeTransport=EIa;function RIa(n,t="utf-8"){let r,a=new Promise((i,s)=>{r=i});return new Promise((i,s)=>{let e=(0,vNe.createServer)(o=>{e.close(),r([new CX(o,t),new YX(o,t)])});e.on("error",s),e.listen(n,"127.0.0.1",()=>{e.removeListener("error",s),i({onConnected:()=>a})})})}Is.createClientSocketTransport=RIa;function wIa(n,t="utf-8"){let r=(0,vNe.createConnection)(n,"127.0.0.1");return[new CX(r,t),new YX(r,t)]}Is.createServerSocketTransport=wIa;function CIa(n){let t=n;return t.read!==void 0&&t.addListener!==void 0}function YIa(n){let t=n;return t.write!==void 0&&t.addListener!==void 0}function xIa(n,t,r,a){r||(r=B1.NullLogger);let i=CIa(n)?new GNe(n):n,s=YIa(t)?new gNe(t):t;return B1.ConnectionStrategy.is(a)&&(a={connectionStrategy:a}),(0,B1.createMessageConnection)(i,s,r,a)}Is.createMessageConnection=xIa});var npn=ve((uJi,tpn)=>{"use strict";tpn.exports=epn()});import{pathToFileURL as VIa}from"node:url";import*as Lnt from"node:path";async function rpn(n){let r=(o=>o.replace(/^file:\/\/\/([A-Z]):\//,(u,d)=>`file:///${d.toLowerCase()}:/`))(VIa(n.root).href),a=(0,LO.createMessageConnection)(new LO.StreamMessageReader(n.server.process.stdout),new LO.StreamMessageWriter(n.server.process.stdin));a.onError(o=>{console.error(`[LSP][${n.serverID}] Connection error:`,o[0])}),a.onClose(()=>{console.log(`[LSP][${n.serverID}] Connection closed`)}),(process.env.DEEPV_LSP_DEBUG==="1"||process.env.DEEPV_LSP_DEBUG==="true")&&n.server.process?.stderr&&n.server.process.stderr.on("data",o=>{let u=o.toString("utf8").trimEnd();u&&console.log(`[LSP][${n.serverID}][stderr] ${u}`)}),a.onRequest("workspace/configuration",o=>(o.items||[]).map(()=>({}))),a.onRequest("client/registerCapability",()=>({})),a.onRequest("client/unregisterCapability",()=>({})),a.onRequest("window/workDoneProgress/create",()=>null),a.onRequest("workspace/semanticTokens/refresh",()=>null),a.onRequest("workspace/inlayHint/refresh",()=>null),a.onRequest("workspace/codeLens/refresh",()=>null),a.onRequest("workspace/diagnostic/refresh",()=>null),a.onRequest("window/showMessageRequest",o=>{let u=o?.actions;return Array.isArray(u)&&u.length>0?u[0]:null}),a.onRequest("workspace/applyEdit",()=>({applied:!0})),a.onRequest("workspace/workspaceFolders",()=>[{uri:r,name:Lnt.basename(n.root)}]),a.listen();let s={processId:process.pid,rootUri:r,capabilities:{window:{workDoneProgress:!0},textDocument:{synchronization:{dynamicRegistration:!0,willSave:!1,willSaveWaitUntil:!1,didSave:!0,didChange:1},hover:{contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!0,linkSupport:!0},references:{dynamicRegistration:!0},documentSymbol:{dynamicRegistration:!0,hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]}},implementation:{dynamicRegistration:!0,linkSupport:!0},typeDefinition:{dynamicRegistration:!0,linkSupport:!0},diagnostic:{dynamicRegistration:!0}},workspace:{workspaceFolders:!0,configuration:!0,symbol:{dynamicRegistration:!0,symbolKind:{valueSet:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]}}}},workspaceFolders:[{uri:r,name:Lnt.basename(n.root)}]},e=await a.sendRequest("initialize",s);return await a.sendNotification("initialized",{}),{serverID:n.serverID,root:n.root,connection:a,capabilities:e.capabilities}}async function apn(n){try{await n.connection.sendRequest("shutdown"),await n.connection.sendNotification("exit"),n.connection.dispose()}catch(t){console.error(`[LSP][${n.serverID}] Shutdown error:`,t)}}var LO,ipn=ut(()=>{"use strict";LO=Qt(npn(),1);});import*as J1 from"node:path";import*as ci from"node:fs";import*as lpn from"node:os";import*as spn from"node:zlib";import{spawn as ZNe,spawnSync as QIa}from"node:child_process";function upn(n){if(ci.existsSync(n)){for(let t of ci.readdirSync(n)){let r=J1.join(n,t);ci.statSync(r).isDirectory()?upn(r):ci.unlinkSync(r)}ci.rmdirSync(n)}}var opn,cpn,AI,Ipn=ut(()=>{"use strict";opn=Qt(pq(),1),cpn=Qt(oje(),1);AI=class{static LSP_DIR=J1.join(lpn.homedir(),".deepv","lsp");static findOnPath(t){let r=process.platform==="win32"?"where.exe":"which",i=(QIa(r,[t],{shell:!1,encoding:"utf8",windowsHide:!0}).stdout||"").toString().trim();if(!i)return null;for(let s of i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean))if(ci.existsSync(s))return s;return null}static async cleanBinaryCache(t){let r=J1.join(this.LSP_DIR,t);ci.existsSync(r)&&(console.log(`[LSP] Cleaning corrupted binary cache for ${t} at ${r}`),upn(r),console.log("[LSP] Cache cleaned successfully"))}static async ensureBinary(t,r,a){let i=a?.maxRetries??1,s=null;for(let e=0;e<=i;e++)try{let o=J1.join(this.LSP_DIR,t);return ci.existsSync(o)||ci.mkdirSync(o,{recursive:!0}),await r(o)}catch(o){s=o,e<i&&(console.log(`[LSP] Attempt ${e+1} failed: ${s.message}`),console.log(`[LSP] Cleaning cache and retrying (${i-e} retries left)...`),await this.cleanBinaryCache(t))}throw s||new Error(`Failed to ensure binary for ${t}`)}static async npmInstaller(t,r){return async a=>{let i=J1.join(a,"node_modules",".bin",r+(process.platform==="win32"?".cmd":""));return ci.existsSync(i)||(console.log(`[LSP] Installing ${t.join(", ")} via npm...`),ci.existsSync(J1.join(a,"package.json"))||ci.writeFileSync(J1.join(a,"package.json"),JSON.stringify({name:`deepv-lsp-${r}`,version:"1.0.0",private:!0})),await new Promise((s,e)=>{let o=process.platform==="win32",u=["install",...t,"--no-save"];(o?ZNe("cmd.exe",["/c","npm",...u],{cwd:a,shell:!1,stdio:"inherit"}):ZNe("npm",u,{cwd:a,shell:!1,stdio:"inherit"})).on("close",I=>{I===0?s():e(new Error(`npm install failed with code ${I}`))})})),i}}static async goInstaller(t,r,a="latest"){return async i=>{let s=process.platform,e=J1.join(i,r+(s==="win32"?".exe":""));if(ci.existsSync(e))return e;let o=this.findOnPath("go");if(!o)throw new Error(`[LSP] Go toolchain not found in PATH (required to install ${r}). Please install Go from https://go.dev/dl/ and ensure "go" is available in your PATH, or configure a preinstalled gopls via PATH/DEEPV_GOPLS_PATH.`);if(console.log(`[LSP] Installing ${r} via go install (${t}@${a})...`),await new Promise((u,d)=>{let I=ZNe(o,["install",`${t}@${a}`],{cwd:i,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,GOBIN:i}}),h="";I.stdout?.on("data",c=>{process.stdout.write(c)}),I.stderr?.on("data",c=>{let G=c.toString();h+=G,h.length>16384&&(h=h.slice(h.length-16384)),process.stderr.write(c)}),I.on("close",c=>{if(c===0)u();else{let G=h.trim();d(new Error(`[LSP] go install failed with code ${c}`+(G?`
|
|
1806
|
-
${G}`:"")))}}),I.on("error",c=>{d(new Error(`[LSP] Failed to spawn go (${o}): ${c.message}. Please ensure Go is installed and available in PATH.`))})}),!ci.existsSync(e))throw new Error(`[LSP] ${r} installation completed but binary not found at ${e}. This usually means Go did not honor GOBIN or the install failed silently.`);return e}}static async githubInstaller(t,r,a){return async i=>{let s=process.platform,e=process.arch,o=a(s,e),u=r+(s==="win32"?".exe":""),d=J1.join(i,u);if(ci.existsSync(d))return d;console.log(`[LSP] Downloading ${r} from GitHub ${t}/${r}...`);let I=`https://api.github.com/repos/${t}/${r}/releases/latest`,c=await(await(0,opn.request)(I,{headers:{"User-Agent":"DeepV-Code-Agent"}})).body.json(),G=c.assets.find(w=>typeof o=="string"?w.name===o:o.test(w.name));if(!G){let w=`${s}-${e}`,A=[];r==="rust-analyzer"&&(w==="win32-x64"?A.push(/rust-analyzer.*x86_64.*windows.*\.zip/i,/rust-analyzer.*x64.*windows.*\.zip/i,/rust-analyzer.*msvc.*\.zip/i):w==="win32-arm64"?A.push(/rust-analyzer.*aarch64.*windows.*\.zip/i):w==="darwin-x64"?A.push(/rust-analyzer.*x86_64.*apple-darwin.*\.gz/i,/rust-analyzer.*x86_64.*macos.*\.gz/i):w==="darwin-arm64"?A.push(/rust-analyzer.*aarch64.*apple-darwin.*\.gz/i,/rust-analyzer.*aarch64.*macos.*\.gz/i):w==="linux-x64"?A.push(/rust-analyzer.*x86_64.*linux.*\.gz/i,/rust-analyzer.*x86_64.*gnu.*\.gz/i):w==="linux-arm64"&&A.push(/rust-analyzer.*aarch64.*linux.*\.gz/i,/rust-analyzer.*aarch64.*gnu.*\.gz/i)),A.length>0&&(G=c.assets.find(E=>A.some(f=>f.test(E.name))))}if(!G){let w=c.assets.map(A=>A.name).join(", ");throw new Error(`Could not find a suitable binary for ${s}-${e} in ${t}/${r} releases. Available: ${w}`)}console.log(`[LSP] Downloading: ${G.name}`),console.log(`[LSP] File size: ${(G.size/1024/1024).toFixed(1)}MB`);let F=J1.join(i,G.name),W=Date.now(),R=0;if(await new Promise((w,A)=>{let E=process.platform==="win32"?"curl.exe":"curl",f=ZNe(E,["-L","--fail","-o",F,G.browser_download_url]),g="",v=setInterval(()=>{if(ci.existsSync(F)){let N=ci.statSync(F).size,m=(N/(G.size||1)*100).toFixed(1),p=(N/1024/1024).toFixed(1),b=(G.size/1024/1024).toFixed(1);console.log(`[LSP] \u2B07\uFE0F ${G.name}: ${p}MB / ${b}MB (${m}%)`),R=N,W=Date.now()}},2e3);f.stderr.on("data",N=>{g+=N.toString()}),f.on("close",N=>{clearInterval(v),N===0?w():(ci.existsSync(F)&&ci.unlinkSync(F),A(new Error(`[LSP] curl failed with code ${N}: ${g}`)))}),f.on("error",N=>{clearInterval(v),ci.existsSync(F)&&ci.unlinkSync(F),A(new Error(`[LSP] Failed to spawn curl: ${N.message}. curl may not be installed or available in PATH. Please install curl and add it to your system PATH.`))})}),!ci.existsSync(F))throw new Error(`[LSP] Downloaded file not found at ${F}. curl may have failed silently.`);let y=ci.statSync(F).size;if(y===0)throw ci.unlinkSync(F),new Error(`[LSP] Downloaded file is empty (0 bytes) for ${G.name}. The download URL may be invalid or temporarily unavailable. Please retry.`);if(console.log(`[LSP] Downloaded ${y} bytes (expected: ${G.size} bytes)`),G.name.endsWith(".gz")){console.log(`[LSP] Decompressing ${G.name}...`);let w=ci.readFileSync(F);try{let A=spn.gunzipSync(w);if(A.length===0)throw new Error("Decompressed data is empty");ci.writeFileSync(d,A)}catch(A){ci.unlinkSync(F);let E=A instanceof Error?A.message:String(A);throw new Error(`[LSP] Failed to decompress ${G.name}: ${E}. The file may be corrupted. Please retry.`)}ci.unlinkSync(F)}else if(G.name.endsWith(".zip")){console.log(`[LSP] Extracting ${G.name}...`);let w=ci.readFileSync(F);if(w.length<4)throw ci.unlinkSync(F),new Error(`[LSP] ZIP file is too small (${w.length} bytes) for ${G.name}. The download is corrupted. Please retry or check your network connection.`);if(w[0]!==80||w[1]!==75||w[2]!==3||w[3]!==4)throw ci.unlinkSync(F),new Error(`[LSP] ZIP file header is corrupted for ${G.name}. The download may have been interrupted. Please retry.`);let A;try{A=await cpn.default.loadAsync(w)}catch(N){ci.unlinkSync(F);let m=N instanceof Error?N.message:String(N);throw new Error(`[LSP] Failed to parse ZIP file ${G.name}: ${m}. The file may be corrupted. Please retry the download.`)}let E=u.toLowerCase(),g=Object.values(A.files).filter(N=>!N.dir).filter(N=>J1.posix.basename(N.name).toLowerCase()===E).sort((N,m)=>N.name.length-m.name.length)[0];if(!g)throw new Error(`Zip archive did not contain expected executable "${u}" for ${t}/${r}.`);let v=await g.async("nodebuffer");ci.writeFileSync(d,v),ci.unlinkSync(F)}else ci.renameSync(F,d);if(s!=="win32"&&ci.chmodSync(d,493),console.log(`[LSP] Binary installed at: ${d}`),console.log(`[LSP] Binary exists: ${ci.existsSync(d)}`),ci.existsSync(d)){let w=ci.statSync(d);console.log(`[LSP] Binary stats: size=${w.size}, mode=${(w.mode&parseInt("777",8)).toString(8)}`)}return d}}}});import*as V0 from"node:path";import*as IZ from"node:fs";import{spawn as CY}from"node:child_process";function SO(n,t,r){let i=process.platform==="win32"&&n.toLowerCase().endsWith(".cmd"),s={cwd:r.cwd,shell:!1,stdio:["pipe","pipe","pipe"]};if(i&&IZ.existsSync(n)){let o=IZ.readFileSync(n,"utf8").match(/%dp0%([^"]*\.m?js)/i);if(o){let u=V0.dirname(n),d=o[1].replace(/\\/g,V0.sep);d.startsWith(V0.sep)&&(d="."+d);let I=V0.resolve(u,d);if(IZ.existsSync(I))return CY(process.execPath,[I,...t],s)}return CY("cmd.exe",["/c",n,...t],s)}return CY(n,t,s)}var Sae,HIa,XIa,kIa,LIa,SIa,BIa,JIa,TIa,DIa,dpn,hpn=ut(()=>{"use strict";Ipn();Sae=(n,t)=>async r=>{let a=V0.normalize(V0.dirname(V0.resolve(r))),i=V0.normalize(V0.resolve(t)),s=(e,o)=>{let u=e.toLowerCase(),d=o.toLowerCase();return u.startsWith(d)||u===d};for(;s(a,i);){for(let o of n)if(IZ.existsSync(V0.join(a,o)))return a;let e=V0.normalize(V0.dirname(a));if(e===a)break;a=e}return i},HIa=n=>({id:"typescript-language-server",displayName:"TypeScript/JavaScript Language Server",extensions:[".ts",".tsx",".js",".jsx"],root:Sae(["package.json","tsconfig.json","jsconfig.json"],n),async spawn(t){let r=await AI.ensureBinary("typescript-language-server",await AI.npmInstaller(["typescript-language-server","typescript"],"typescript-language-server")),a=V0.join(V0.dirname(r),"..","..","typescript","lib","tsserver.js"),i=["--stdio"];return IZ.existsSync(a)&&i.push("--tsserver-path",a),{process:SO(r,i,{cwd:t})}}}),XIa=n=>({id:"pyright",displayName:"Python Language Server",extensions:[".py"],root:Sae(["pyproject.toml","setup.py","requirements.txt",".git"],n),async spawn(t){let r=await AI.ensureBinary("pyright",await AI.npmInstaller(["pyright"],"pyright-langserver"));return{process:SO(r,["--stdio"],{cwd:t})}}}),kIa=n=>({id:"rust-analyzer",displayName:"Rust Language Server",extensions:[".rs"],root:Sae(["Cargo.toml"],n),async spawn(t){let r=process.platform,a=process.arch;console.log(`[LSP] Detecting platform for rust-analyzer: platform=${r}, arch=${a}`);let i=await AI.githubInstaller("rust-lang","rust-analyzer",(o,u)=>{let d={"win32-x64":/rust-analyzer.*x86_64.*windows.*\.zip/i,"win32-arm64":/rust-analyzer.*aarch64.*windows.*\.zip/i,"darwin-x64":/rust-analyzer.*x86_64.*apple-darwin.*\.gz/i,"darwin-arm64":/rust-analyzer.*aarch64.*apple-darwin.*\.gz/i,"linux-x64":/rust-analyzer.*x86_64.*linux.*\.gz/i,"linux-arm64":/rust-analyzer.*aarch64.*linux.*\.gz/i},I=`${o}-${u}`,h=d[I]||/rust-analyzer-.*/;return console.log(`[LSP] Asset matcher for ${I}: ${h instanceof RegExp?h.source:h}`),h}),s=await AI.ensureBinary("rust-analyzer",i,{maxRetries:1});if(console.log(`[LSP] RustAnalyzer binary path: ${s}`),console.log(`[LSP] RustAnalyzer binary exists: ${IZ.existsSync(s)}`),IZ.existsSync(s)){let o=IZ.statSync(s);console.log(`[LSP] RustAnalyzer binary stats: size=${o.size}, isFile=${o.isFile()}, mode=${(o.mode&parseInt("777",8)).toString(8)}`)}console.log(`[LSP] RustAnalyzer spawning with cwd=${t}, args=[], shell=undefined`);let e=CY(s,[],{cwd:t});return console.log(`[LSP] RustAnalyzer spawn returned: pid=${e.pid}`),e.on("error",o=>{console.error("[LSP] RustAnalyzer process error:",{code:o.code,errno:o.errno,syscall:o.syscall,path:o.path,message:o.message})}),e.on("exit",(o,u)=>{console.log(`[LSP] RustAnalyzer process exited: code=${o}, signal=${u}`)}),{process:e}}}),LIa=n=>({id:"gopls",displayName:"Go Language Server",extensions:[".go"],root:Sae(["go.mod","go.sum"],n),async spawn(t){let r=process.env.DEEPV_GOPLS_PATH;if(r&&IZ.existsSync(r))return{process:CY(r,[],{cwd:t})};let a=AI.findOnPath("gopls");if(a)return{process:CY(a,[],{cwd:t})};let i=await AI.ensureBinary("gopls",await AI.goInstaller("golang.org/x/tools/gopls","gopls"),{maxRetries:1});return{process:CY(i,[],{cwd:t})}}}),SIa=n=>({id:"clangd",displayName:"C/C++ Language Server",extensions:[".c",".cpp",".h",".hpp",".cc"],root:Sae(["compile_commands.json","CMakeLists.txt",".git"],n),async spawn(t){let r=await AI.githubInstaller("clangd","clangd",(i,s)=>{let e=i==="win32"?"windows":i==="darwin"?"mac":"linux";return new RegExp(`clangd-${e}-.*\\.zip`)}),a=await AI.ensureBinary("clangd",r,{maxRetries:1});return{process:CY(a,[],{cwd:t})}}}),BIa=n=>({id:"vscode-langservers-extracted",displayName:"HTML/CSS/JSON/ESLint Language Server",extensions:[".html",".css",".json",".jsonc"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("vscode-langservers-extracted",await AI.npmInstaller(["vscode-langservers-extracted"],"vscode-html-language-server"));return{process:SO(r,["--stdio"],{cwd:t})}}}),JIa=n=>({id:"sql-language-server",displayName:"SQL Language Server",extensions:[".sql"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("sql-language-server",await AI.npmInstaller(["sql-language-server"],"sql-language-server"));return{process:SO(r,["up","--method","stdio"],{cwd:t})}}}),TIa=n=>({id:"dockerfile-language-server-nodejs",displayName:"Dockerfile Language Server",extensions:["Dockerfile",".dockerfile"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("dockerfile-language-server-nodejs",await AI.npmInstaller(["dockerfile-language-server-nodejs"],"docker-langserver"));return{process:SO(r,["--stdio"],{cwd:t})}}}),DIa=n=>({id:"yaml-language-server",displayName:"YAML Language Server",extensions:[".yaml",".yml"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("yaml-language-server",await AI.npmInstaller(["yaml-language-server"],"yaml-language-server"));return{process:SO(r,["--stdio"],{cwd:t})}}}),dpn=n=>[HIa(n),XIa(n),kIa(n),LIa(n),SIa(n),BIa(n),JIa(n),TIa(n),DIa(n)]});import*as wR from"node:path";import*as NNe from"node:fs";import{pathToFileURL as OIa}from"node:url";var Up,YY=ut(()=>{"use strict";ipn();hpn();Up=class{clients=new Map;servers;projectRoot;openedFiles=new Set;fileVersions=new Map;fileContents=new Map;freshClients=new Set;constructor(t){this.projectRoot=t,this.servers=dpn(t)}async getClientsForFile(t){let r=wR.extname(t).toLowerCase(),a=this.servers.filter(s=>s.extensions.includes(r)),i=[];for(let s of a){let e=await s.root(t),o=`${s.id}:${e}`;if(this.clients.has(o))i.push(this.clients.get(o));else try{console.log(`[LSP] Starting ${s.id} for root ${e}`);let{process:u}=await s.spawn(e);console.log(`[LSP] Process spawned: pid=${u.pid}, stdio=${JSON.stringify(u.stdio)}`);let d=await rpn({serverID:s.id,server:{process:u},root:e});this.clients.set(o,d),this.freshClients.add(d.serverID),i.push(d)}catch(u){let d=u instanceof Error?{message:u.message,stack:u.stack,code:u.code,errno:u.errno,syscall:u.syscall,path:u.path}:String(u);console.error(`[LSP] Failed to start ${s.id}:`,d);let I=u;(I.errno===-4094||I.code==="UNKNOWN")&&console.error(`[LSP] Binary file may be corrupted (errno=${I.errno}). Suggest deleting ${s.id} cache and reinitializing.`)}}return i}async syncDocument(t,r){let a=this.getUri(r),i=`${t.serverID}:${a}`,s=NNe.readFileSync(r,"utf8");if(!this.openedFiles.has(i))this.fileVersions.set(i,1),this.fileContents.set(i,s),await t.connection.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(r),version:1,text:s}}),this.openedFiles.add(i),await new Promise(e=>setTimeout(e,500));else{if(this.fileContents.get(i)===s)return;let o=(this.fileVersions.get(i)||1)+1;this.fileVersions.set(i,o),this.fileContents.set(i,s),await t.connection.sendNotification("textDocument/didChange",{textDocument:{uri:a,version:o},contentChanges:[{text:s}]})}}getLanguageId(t){switch(wR.extname(t).toLowerCase()){case".ts":case".tsx":return"typescript";case".js":case".jsx":return"javascript";case".go":return"go";case".py":return"python";case".rs":return"rust";default:return"plaintext"}}getUri(t){return OIa(wR.resolve(t)).href.replace(/^file:\/\/\/([A-Z]):\//,(a,i)=>`file:///${i.toLowerCase()}:/`)}async shutdown(){for(let t of this.clients.values())await apn(t);this.clients.clear(),this.openedFiles.clear()}async run(t,r,a){let i=process.env.DEEPV_LSP_DEBUG==="1"||process.env.DEEPV_LSP_DEBUG==="true",s=Number(process.env.DEEPV_LSP_REQUEST_TIMEOUT_MS),e=a?.timeoutMs??(Number.isFinite(s)&&s>0?s:15e3),o=a?.operationName??"request",u=wR.normalize(t),d=await this.getClientsForFile(u),I=await Promise.all(d.map(async c=>{await this.syncDocument(c,u),this.freshClients.has(c.serverID)&&(console.log(`[LSP][${c.serverID}] First request on fresh server, warming up for 3s...`),await new Promise(G=>setTimeout(G,3e3)),this.freshClients.delete(c.serverID));try{return await Promise.race([r(c),new Promise((F,W)=>{let R=setTimeout(()=>{clearTimeout(R),W(new Error(`[LSP][${c.serverID}] ${o} timed out after ${e}ms`))},e)})])}catch(G){if(i)console.error(`[LSP][${c.serverID}] Request failed:`,G);else{let F=G instanceof Error?G.message:String(G);F.includes("timed out after")?console.warn(F):console.error(`[LSP][${c.serverID}] Request failed:`,F)}return null}})),h=[];for(let c of I)c!==null&&h.push(c);return h}async getHover(t,r,a){return this.run(t,i=>i.connection.sendRequest("textDocument/hover",{textDocument:{uri:this.getUri(t)},position:{line:r,character:a}}),{operationName:"textDocument/hover"})}async getDefinition(t,r,a){return this.run(t,i=>i.connection.sendRequest("textDocument/definition",{textDocument:{uri:this.getUri(t)},position:{line:r,character:a}}),{operationName:"textDocument/definition"})}async getReferences(t,r,a){return this.run(t,async i=>{let s={textDocument:{uri:this.getUri(t)},position:{line:r,character:a},context:{includeDeclaration:!0}},e=await i.connection.sendRequest("textDocument/references",s);return(!e||e.length===0)&&(console.log(`[LSP][${i.serverID}] No references found, retrying in 3s...`),await new Promise(o=>setTimeout(o,3e3)),e=await i.connection.sendRequest("textDocument/references",s)),e},{operationName:"textDocument/references"})}async getImplementation(t,r,a){return this.run(t,async i=>{let s={textDocument:{uri:this.getUri(t)},position:{line:r,character:a}},e=await i.connection.sendRequest("textDocument/implementation",s);return(!e||e.length===0)&&(console.log(`[LSP][${i.serverID}] No implementation found, retrying in 3s...`),await new Promise(o=>setTimeout(o,3e3)),e=await i.connection.sendRequest("textDocument/implementation",s)),e},{operationName:"textDocument/implementation"})}async getDocumentSymbols(t){return this.run(t,r=>r.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:this.getUri(t)}}),{operationName:"textDocument/documentSymbol"})}async getWorkspaceSymbols(t){if(this.clients.size===0){console.log("[LSP] No active clients for workspace symbols, probing project...");let a=NNe.readdirSync(this.projectRoot,{recursive:!0}),i=[{ext:".ts",id:"typescript-language-server"},{ext:".py",id:"pyright"},{ext:".go",id:"gopls"},{ext:".rs",id:"rust-analyzer"},{ext:".js",id:"typescript-language-server"}];for(let s of i){let e=a.find(o=>o.endsWith(s.ext)&&!o.includes("node_modules")&&!o.includes("dist"));if(e){console.log(`[LSP] Detected ${s.ext} project, activating ${s.id}...`);let o=wR.join(this.projectRoot,e),u=await this.getClientsForFile(o);for(let d of u)await this.syncDocument(d,o);console.log(`[LSP] Waiting 5s for ${s.id} indexing...`),await new Promise(d=>setTimeout(d,5e3));break}}}let r=[];console.log(`[LSP] Searching workspace symbols for "${t}" across ${this.clients.size} clients...`);for(let a of this.clients.values())try{let i=await a.connection.sendRequest("workspace/symbol",{query:t});(!i||i.length===0)&&(console.log(`[LSP][${a.serverID}] No symbols yet, retrying in 3s...`),await new Promise(s=>setTimeout(s,3e3)),i=await a.connection.sendRequest("workspace/symbol",{query:t})),console.log(`[LSP][${a.serverID}] Found ${i?.length||0} symbols`),i&&r.push(i)}catch(i){console.error(`[LSP][${a.serverID}] Workspace symbols failed:`,i)}return r}async getDiagnostics(t){return[]}}});import*as mpn from"node:path";function UIa(n){return Snt||(Snt=new Up(n)),Snt}var Snt,xX,ppn=ut(()=>{"use strict";Ll();YY();wi();Snt=null;xX=class n extends qr{config;static Name="lsp_hover";constructor(t){super(n.Name,"LSP Hover","Get hover information (type info, documentation) for a specific position in a file using Language Server Protocol.",$r.LightBulb,{type:gn.OBJECT,properties:{filePath:{type:gn.STRING,description:"The absolute path to the file to inspect."},line:{type:gn.NUMBER,description:"The 1-based line number (as shown in editors)."},character:{type:gn.NUMBER,description:"The 1-based character offset on the line (as shown in editors)."}},required:["filePath","line","character"]}),this.config=t}validateToolParams(t){return!t.filePath||!mpn.isAbsolute(t.filePath)?"filePath must be an absolute path.":t.line<1||t.character<1?"line and character must be 1-based (>= 1).":null}async execute(t){let a=await UIa(this.config.getTargetDir()).getHover(t.filePath,t.line-1,t.character-1);if(a.length===0||!a[0])return{llmContent:"No hover information found. This might be because the position is on a keyword, or the LSP server is still indexing. Try moving the character offset to the symbol name.",returnDisplay:"No hover information found."};let i=a.map(s=>!s||!s.contents?"":Array.isArray(s.contents)?s.contents.map(e=>typeof e=="string"?e:e.value).join(`
|
|
1805
|
+
`)),ye){let _e=Fe.error?` Request failed: ${Fe.error.message} (${Fe.error.code}).`:"";f.log(`Received response '${ye.method} - (${Fe.id})' in ${Date.now()-ye.timerStart}ms.${_e}`,ke)}else f.log(`Received response ${Fe.id} without active response promise.`,ke)}else ie("receive-response",Fe)}function ie(Fe,ye){if(!f||A===bo.Off)return;let ke={isLSPMessage:!0,type:Fe,message:ye,timestamp:Date.now()};f.log(ke)}function se(){if(X())throw new XO(kae.Closed,"Connection is closed.");if(Q())throw new XO(kae.Disposed,"Connection is disposed.")}function ue(){if(k())throw new XO(kae.AlreadyListening,"Connection is already listening")}function me(){if(!k())throw new Error("Call listen() first.")}function he(Fe){return Fe===void 0?null:Fe}function We(Fe){if(Fe!==null)return Fe}function Re(Fe){return Fe!=null&&!Array.isArray(Fe)&&typeof Fe=="object"}function Ce(Fe,ye){switch(Fe){case oi.ParameterStructures.auto:return Re(ye)?We(ye):[he(ye)];case oi.ParameterStructures.byName:if(!Re(ye))throw new Error("Received parameters by name but param is not an object literal.");return We(ye);case oi.ParameterStructures.byPosition:return[he(ye)];default:throw new Error(`Unknown parameter structure ${Fe.toString()}`)}}function Ee(Fe,ye){let ke,_e=Fe.numberOfParams;switch(_e){case 0:ke=void 0;break;case 1:ke=Ce(Fe.parameterStructures,ye[0]);break;default:ke=[];for(let rt=0;rt<ye.length&&rt<_e;rt++)ke.push(he(ye[rt]));if(ye.length<_e)for(let rt=ye.length;rt<_e;rt++)ke.push(null);break}return ke}let Qe={sendNotification:(Fe,...ye)=>{se();let ke,_e;if(tI.string(Fe)){ke=Fe;let ot=ye[0],dt=0,Te=oi.ParameterStructures.auto;oi.ParameterStructures.is(ot)&&(dt=1,Te=ot);let Ue=ye.length,at=Ue-dt;switch(at){case 0:_e=void 0;break;case 1:_e=Ce(Te,ye[dt]);break;default:if(Te===oi.ParameterStructures.byName)throw new Error(`Received ${at} parameters for 'by Name' notification parameter structure.`);_e=ye.slice(dt,Ue).map(Se=>he(Se));break}}else{let ot=ye;ke=Fe.method,_e=Ee(Fe,ot)}let rt={jsonrpc:u,method:ke,params:_e};return q(rt),t.write(rt).catch(ot=>{throw i.error("Sending notification failed."),ot})},onNotification:(Fe,ye)=>{se();let ke;return tI.func(Fe)?h=Fe:ye&&(tI.string(Fe)?(ke=Fe,c.set(Fe,{type:void 0,handler:ye})):(ke=Fe.method,c.set(Fe.method,{type:Fe,handler:ye}))),{dispose:()=>{ke!==void 0?c.delete(ke):h=void 0}}},onProgress:(Fe,ye,ke)=>{if(G.has(ye))throw new Error(`Progress handler for token ${ye} already registered`);return G.set(ye,ke),{dispose:()=>{G.delete(ye)}}},sendProgress:(Fe,ye,ke)=>Qe.sendNotification(Xae.type,{token:ye,value:ke}),onUnhandledProgress:p.event,sendRequest:(Fe,...ye)=>{se(),me();let ke,_e,rt;if(tI.string(Fe)){ke=Fe;let Ue=ye[0],at=ye[ye.length-1],Se=0,tt=oi.ParameterStructures.auto;oi.ParameterStructures.is(Ue)&&(Se=1,tt=Ue);let Oe=ye.length;vnt.CancellationToken.is(at)&&(Oe=Oe-1,rt=at);let et=Oe-Se;switch(et){case 0:_e=void 0;break;case 1:_e=Ce(tt,ye[Se]);break;default:if(tt===oi.ParameterStructures.byName)throw new Error(`Received ${et} parameters for 'by Name' request parameter structure.`);_e=ye.slice(Se,Oe).map(ne=>he(ne));break}}else{let Ue=ye;ke=Fe.method,_e=Ee(Fe,Ue);let at=Fe.numberOfParams;rt=vnt.CancellationToken.is(Ue[at])?Ue[at]:void 0}let ot=s++,dt;rt&&(dt=rt.onCancellationRequested(()=>{let Ue=Z.sender.sendCancellation(Qe,ot);return Ue===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${ot}`),Promise.resolve()):Ue.catch(()=>{i.log(`Sending cancellation messages for id ${ot} failed`)})}));let Te={jsonrpc:u,id:ot,method:ke,params:_e};return j(Te),typeof Z.sender.enableCancellation=="function"&&Z.sender.enableCancellation(Te),new Promise(async(Ue,at)=>{let Se=et=>{Ue(et),Z.sender.cleanup(ot),dt?.dispose()},tt=et=>{at(et),Z.sender.cleanup(ot),dt?.dispose()},Oe={method:ke,timerStart:Date.now(),resolve:Se,reject:tt};try{R.set(ot,Oe),await t.write(Te)}catch(et){throw R.delete(ot),Oe.reject(new oi.ResponseError(oi.ErrorCodes.MessageWriteError,et.message?et.message:"Unknown reason")),i.error("Sending request failed."),et}})},onRequest:(Fe,ye)=>{se();let ke=null;return Ant.is(Fe)?(ke=void 0,d=Fe):tI.string(Fe)?(ke=null,ye!==void 0&&(ke=Fe,I.set(Fe,{handler:ye,type:void 0}))):ye!==void 0&&(ke=Fe.method,I.set(Fe.method,{type:Fe,handler:ye})),{dispose:()=>{ke!==null&&(ke!==void 0?I.delete(ke):d=void 0)}}},hasPendingResponse:()=>R.size>0,trace:async(Fe,ye,ke)=>{let _e=!1,rt=S1.Text;ke!==void 0&&(tI.boolean(ke)?_e=ke:(_e=ke.sendNotification||!1,rt=ke.traceFormat||S1.Text)),A=Fe,E=rt,A===bo.Off?f=void 0:f=ye,_e&&!X()&&!Q()&&await Qe.sendNotification(Wnt.type,{value:bo.toString(Fe)})},onError:v.event,onClose:N.event,onUnhandledNotification:m.event,onDispose:b.event,end:()=>{t.end()},dispose:()=>{if(Q())return;g=JA.Disposed,b.fire(void 0);let Fe=new oi.ResponseError(oi.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let ye of R.values())ye.reject(Fe);R=new Map,w=new Map,y=new Set,W=new Tmn.LinkedMap,tI.func(t.dispose)&&t.dispose(),tI.func(n.dispose)&&n.dispose()},listen:()=>{se(),ue(),g=JA.Listening,n.listen(B)},inspect:()=>{(0,Jmn.default)().console.log("inspect")}};return Qe.onNotification(uNe.type,Fe=>{if(A===bo.Off||!f)return;let ye=A===bo.Verbose||A===bo.Compact;f.log(Fe.message,ye?Fe.verbose:void 0)}),Qe.onNotification(Xae.type,Fe=>{let ye=G.get(Fe.token);ye?ye(Fe.value):p.fire(Fe)}),Qe}Ji.createMessageConnection=bIa});var bNe=ve(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.ProgressType=zn.ProgressToken=zn.createMessageConnection=zn.NullLogger=zn.ConnectionOptions=zn.ConnectionStrategy=zn.AbstractMessageBuffer=zn.WriteableStreamMessageWriter=zn.AbstractMessageWriter=zn.MessageWriter=zn.ReadableStreamMessageReader=zn.AbstractMessageReader=zn.MessageReader=zn.SharedArrayReceiverStrategy=zn.SharedArraySenderStrategy=zn.CancellationToken=zn.CancellationTokenSource=zn.Emitter=zn.Event=zn.Disposable=zn.LRUCache=zn.Touch=zn.LinkedMap=zn.ParameterStructures=zn.NotificationType9=zn.NotificationType8=zn.NotificationType7=zn.NotificationType6=zn.NotificationType5=zn.NotificationType4=zn.NotificationType3=zn.NotificationType2=zn.NotificationType1=zn.NotificationType0=zn.NotificationType=zn.ErrorCodes=zn.ResponseError=zn.RequestType9=zn.RequestType8=zn.RequestType7=zn.RequestType6=zn.RequestType5=zn.RequestType4=zn.RequestType3=zn.RequestType2=zn.RequestType1=zn.RequestType0=zn.RequestType=zn.Message=zn.RAL=void 0;zn.MessageStrategy=zn.CancellationStrategy=zn.CancellationSenderStrategy=zn.CancellationReceiverStrategy=zn.ConnectionError=zn.ConnectionErrors=zn.LogTraceNotification=zn.SetTraceNotification=zn.TraceFormat=zn.TraceValues=zn.Trace=void 0;var Dc=qtt();Object.defineProperty(zn,"Message",{enumerable:!0,get:function(){return Dc.Message}});Object.defineProperty(zn,"RequestType",{enumerable:!0,get:function(){return Dc.RequestType}});Object.defineProperty(zn,"RequestType0",{enumerable:!0,get:function(){return Dc.RequestType0}});Object.defineProperty(zn,"RequestType1",{enumerable:!0,get:function(){return Dc.RequestType1}});Object.defineProperty(zn,"RequestType2",{enumerable:!0,get:function(){return Dc.RequestType2}});Object.defineProperty(zn,"RequestType3",{enumerable:!0,get:function(){return Dc.RequestType3}});Object.defineProperty(zn,"RequestType4",{enumerable:!0,get:function(){return Dc.RequestType4}});Object.defineProperty(zn,"RequestType5",{enumerable:!0,get:function(){return Dc.RequestType5}});Object.defineProperty(zn,"RequestType6",{enumerable:!0,get:function(){return Dc.RequestType6}});Object.defineProperty(zn,"RequestType7",{enumerable:!0,get:function(){return Dc.RequestType7}});Object.defineProperty(zn,"RequestType8",{enumerable:!0,get:function(){return Dc.RequestType8}});Object.defineProperty(zn,"RequestType9",{enumerable:!0,get:function(){return Dc.RequestType9}});Object.defineProperty(zn,"ResponseError",{enumerable:!0,get:function(){return Dc.ResponseError}});Object.defineProperty(zn,"ErrorCodes",{enumerable:!0,get:function(){return Dc.ErrorCodes}});Object.defineProperty(zn,"NotificationType",{enumerable:!0,get:function(){return Dc.NotificationType}});Object.defineProperty(zn,"NotificationType0",{enumerable:!0,get:function(){return Dc.NotificationType0}});Object.defineProperty(zn,"NotificationType1",{enumerable:!0,get:function(){return Dc.NotificationType1}});Object.defineProperty(zn,"NotificationType2",{enumerable:!0,get:function(){return Dc.NotificationType2}});Object.defineProperty(zn,"NotificationType3",{enumerable:!0,get:function(){return Dc.NotificationType3}});Object.defineProperty(zn,"NotificationType4",{enumerable:!0,get:function(){return Dc.NotificationType4}});Object.defineProperty(zn,"NotificationType5",{enumerable:!0,get:function(){return Dc.NotificationType5}});Object.defineProperty(zn,"NotificationType6",{enumerable:!0,get:function(){return Dc.NotificationType6}});Object.defineProperty(zn,"NotificationType7",{enumerable:!0,get:function(){return Dc.NotificationType7}});Object.defineProperty(zn,"NotificationType8",{enumerable:!0,get:function(){return Dc.NotificationType8}});Object.defineProperty(zn,"NotificationType9",{enumerable:!0,get:function(){return Dc.NotificationType9}});Object.defineProperty(zn,"ParameterStructures",{enumerable:!0,get:function(){return Dc.ParameterStructures}});var Ent=ent();Object.defineProperty(zn,"LinkedMap",{enumerable:!0,get:function(){return Ent.LinkedMap}});Object.defineProperty(zn,"LRUCache",{enumerable:!0,get:function(){return Ent.LRUCache}});Object.defineProperty(zn,"Touch",{enumerable:!0,get:function(){return Ent.Touch}});var fIa=Cmn();Object.defineProperty(zn,"Disposable",{enumerable:!0,get:function(){return fIa.Disposable}});var Mmn=xO();Object.defineProperty(zn,"Event",{enumerable:!0,get:function(){return Mmn.Event}});Object.defineProperty(zn,"Emitter",{enumerable:!0,get:function(){return Mmn.Emitter}});var zmn=iNe();Object.defineProperty(zn,"CancellationTokenSource",{enumerable:!0,get:function(){return zmn.CancellationTokenSource}});Object.defineProperty(zn,"CancellationToken",{enumerable:!0,get:function(){return zmn.CancellationToken}});var _mn=xmn();Object.defineProperty(zn,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return _mn.SharedArraySenderStrategy}});Object.defineProperty(zn,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return _mn.SharedArrayReceiverStrategy}});var Rnt=Qmn();Object.defineProperty(zn,"MessageReader",{enumerable:!0,get:function(){return Rnt.MessageReader}});Object.defineProperty(zn,"AbstractMessageReader",{enumerable:!0,get:function(){return Rnt.AbstractMessageReader}});Object.defineProperty(zn,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return Rnt.ReadableStreamMessageReader}});var wnt=Smn();Object.defineProperty(zn,"MessageWriter",{enumerable:!0,get:function(){return wnt.MessageWriter}});Object.defineProperty(zn,"AbstractMessageWriter",{enumerable:!0,get:function(){return wnt.AbstractMessageWriter}});Object.defineProperty(zn,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return wnt.WriteableStreamMessageWriter}});var GIa=Bmn();Object.defineProperty(zn,"AbstractMessageBuffer",{enumerable:!0,get:function(){return GIa.AbstractMessageBuffer}});var Lm=Umn();Object.defineProperty(zn,"ConnectionStrategy",{enumerable:!0,get:function(){return Lm.ConnectionStrategy}});Object.defineProperty(zn,"ConnectionOptions",{enumerable:!0,get:function(){return Lm.ConnectionOptions}});Object.defineProperty(zn,"NullLogger",{enumerable:!0,get:function(){return Lm.NullLogger}});Object.defineProperty(zn,"createMessageConnection",{enumerable:!0,get:function(){return Lm.createMessageConnection}});Object.defineProperty(zn,"ProgressToken",{enumerable:!0,get:function(){return Lm.ProgressToken}});Object.defineProperty(zn,"ProgressType",{enumerable:!0,get:function(){return Lm.ProgressType}});Object.defineProperty(zn,"Trace",{enumerable:!0,get:function(){return Lm.Trace}});Object.defineProperty(zn,"TraceValues",{enumerable:!0,get:function(){return Lm.TraceValues}});Object.defineProperty(zn,"TraceFormat",{enumerable:!0,get:function(){return Lm.TraceFormat}});Object.defineProperty(zn,"SetTraceNotification",{enumerable:!0,get:function(){return Lm.SetTraceNotification}});Object.defineProperty(zn,"LogTraceNotification",{enumerable:!0,get:function(){return Lm.LogTraceNotification}});Object.defineProperty(zn,"ConnectionErrors",{enumerable:!0,get:function(){return Lm.ConnectionErrors}});Object.defineProperty(zn,"ConnectionError",{enumerable:!0,get:function(){return Lm.ConnectionError}});Object.defineProperty(zn,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return Lm.CancellationReceiverStrategy}});Object.defineProperty(zn,"CancellationSenderStrategy",{enumerable:!0,get:function(){return Lm.CancellationSenderStrategy}});Object.defineProperty(zn,"CancellationStrategy",{enumerable:!0,get:function(){return Lm.CancellationStrategy}});Object.defineProperty(zn,"MessageStrategy",{enumerable:!0,get:function(){return Lm.MessageStrategy}});var gIa=EY();zn.RAL=gIa.default});var Kmn=ve(Vnt=>{"use strict";Object.defineProperty(Vnt,"__esModule",{value:!0});var Pmn=vt("util"),RR=bNe(),fNe=class n extends RR.AbstractMessageBuffer{constructor(t="utf-8"){super(t)}emptyBuffer(){return n.emptyBuffer}fromString(t,r){return Buffer.from(t,r)}toString(t,r){return t instanceof Buffer?t.toString(r):new Pmn.TextDecoder(r).decode(t)}asNative(t,r){return r===void 0?t instanceof Buffer?t:Buffer.from(t):t instanceof Buffer?t.slice(0,r):Buffer.from(t,0,r)}allocNative(t){return Buffer.allocUnsafe(t)}};fNe.emptyBuffer=Buffer.allocUnsafe(0);var Cnt=class{constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),RR.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),RR.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),RR.Disposable.create(()=>this.stream.off("end",t))}onData(t){return this.stream.on("data",t),RR.Disposable.create(()=>this.stream.off("data",t))}},Ynt=class{constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),RR.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),RR.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),RR.Disposable.create(()=>this.stream.off("end",t))}write(t,r){return new Promise((a,i)=>{let s=e=>{e==null?a():i(e)};typeof t=="string"?this.stream.write(t,r,s):this.stream.write(t,s)})}end(){this.stream.end()}},jmn=Object.freeze({messageBuffer:Object.freeze({create:n=>new fNe(n)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(n,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(n,void 0,0),t.charset))}catch(r){return Promise.reject(r)}}}),decoder:Object.freeze({name:"application/json",decode:(n,t)=>{try{return n instanceof Buffer?Promise.resolve(JSON.parse(n.toString(t.charset))):Promise.resolve(JSON.parse(new Pmn.TextDecoder(t.charset).decode(n)))}catch(r){return Promise.reject(r)}}})}),stream:Object.freeze({asReadableStream:n=>new Cnt(n),asWritableStream:n=>new Ynt(n)}),console,timer:Object.freeze({setTimeout(n,t,...r){let a=setTimeout(n,t,...r);return{dispose:()=>clearTimeout(a)}},setImmediate(n,...t){let r=setImmediate(n,...t);return{dispose:()=>clearImmediate(r)}},setInterval(n,t,...r){let a=setInterval(n,t,...r);return{dispose:()=>clearInterval(a)}}})});function xnt(){return jmn}(function(n){function t(){RR.RAL.install(jmn)}n.install=t})(xnt||(xnt={}));Vnt.default=xnt});var epn=ve(Is=>{"use strict";var vIa=Is&&Is.__createBinding||(Object.create?(function(n,t,r,a){a===void 0&&(a=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(n,a,i)}):(function(n,t,r,a){a===void 0&&(a=r),n[a]=t[r]})),ZIa=Is&&Is.__exportStar||function(n,t){for(var r in n)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&vIa(t,n,r)};Object.defineProperty(Is,"__esModule",{value:!0});Is.createMessageConnection=Is.createServerSocketTransport=Is.createClientSocketTransport=Is.createServerPipeTransport=Is.createClientPipeTransport=Is.generateRandomPipeName=Is.StreamMessageWriter=Is.StreamMessageReader=Is.SocketMessageWriter=Is.SocketMessageReader=Is.PortMessageWriter=Is.PortMessageReader=Is.IPCMessageWriter=Is.IPCMessageReader=void 0;var kO=Kmn();kO.default.install();var qmn=vt("path"),NIa=vt("os"),AIa=vt("crypto"),vNe=vt("net"),B1=bNe();ZIa(bNe(),Is);var Qnt=class extends B1.AbstractMessageReader{constructor(t){super(),this.process=t;let r=this.process;r.on("error",a=>this.fireError(a)),r.on("close",()=>this.fireClose())}listen(t){return this.process.on("message",t),B1.Disposable.create(()=>this.process.off("message",t))}};Is.IPCMessageReader=Qnt;var Hnt=class extends B1.AbstractMessageWriter{constructor(t){super(),this.process=t,this.errorCount=0;let r=this.process;r.on("error",a=>this.fireError(a)),r.on("close",()=>this.fireClose)}write(t){try{return typeof this.process.send=="function"&&this.process.send(t,void 0,void 0,r=>{r?(this.errorCount++,this.handleError(r,t)):this.errorCount=0}),Promise.resolve()}catch(r){return this.handleError(r,t),Promise.reject(r)}}handleError(t,r){this.errorCount++,this.fireError(t,r,this.errorCount)}end(){}};Is.IPCMessageWriter=Hnt;var Xnt=class extends B1.AbstractMessageReader{constructor(t){super(),this.onData=new B1.Emitter,t.on("close",()=>this.fireClose),t.on("error",r=>this.fireError(r)),t.on("message",r=>{this.onData.fire(r)})}listen(t){return this.onData.event(t)}};Is.PortMessageReader=Xnt;var knt=class extends B1.AbstractMessageWriter{constructor(t){super(),this.port=t,this.errorCount=0,t.on("close",()=>this.fireClose()),t.on("error",r=>this.fireError(r))}write(t){try{return this.port.postMessage(t),Promise.resolve()}catch(r){return this.handleError(r,t),Promise.reject(r)}}handleError(t,r){this.errorCount++,this.fireError(t,r,this.errorCount)}end(){}};Is.PortMessageWriter=knt;var CX=class extends B1.ReadableStreamMessageReader{constructor(t,r="utf-8"){super((0,kO.default)().stream.asReadableStream(t),r)}};Is.SocketMessageReader=CX;var YX=class extends B1.WriteableStreamMessageWriter{constructor(t,r){super((0,kO.default)().stream.asWritableStream(t),r),this.socket=t}dispose(){super.dispose(),this.socket.destroy()}};Is.SocketMessageWriter=YX;var GNe=class extends B1.ReadableStreamMessageReader{constructor(t,r){super((0,kO.default)().stream.asReadableStream(t),r)}};Is.StreamMessageReader=GNe;var gNe=class extends B1.WriteableStreamMessageWriter{constructor(t,r){super((0,kO.default)().stream.asWritableStream(t),r)}};Is.StreamMessageWriter=gNe;var $mn=process.env.XDG_RUNTIME_DIR,WIa=new Map([["linux",107],["darwin",103]]);function yIa(){let n=(0,AIa.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${n}-sock`;let t;$mn?t=qmn.join($mn,`vscode-ipc-${n}.sock`):t=qmn.join(NIa.tmpdir(),`vscode-${n}.sock`);let r=WIa.get(process.platform);return r!==void 0&&t.length>r&&(0,kO.default)().console.warn(`WARNING: IPC handle "${t}" is longer than ${r} characters.`),t}Is.generateRandomPipeName=yIa;function FIa(n,t="utf-8"){let r,a=new Promise((i,s)=>{r=i});return new Promise((i,s)=>{let e=(0,vNe.createServer)(o=>{e.close(),r([new CX(o,t),new YX(o,t)])});e.on("error",s),e.listen(n,()=>{e.removeListener("error",s),i({onConnected:()=>a})})})}Is.createClientPipeTransport=FIa;function EIa(n,t="utf-8"){let r=(0,vNe.createConnection)(n);return[new CX(r,t),new YX(r,t)]}Is.createServerPipeTransport=EIa;function RIa(n,t="utf-8"){let r,a=new Promise((i,s)=>{r=i});return new Promise((i,s)=>{let e=(0,vNe.createServer)(o=>{e.close(),r([new CX(o,t),new YX(o,t)])});e.on("error",s),e.listen(n,"127.0.0.1",()=>{e.removeListener("error",s),i({onConnected:()=>a})})})}Is.createClientSocketTransport=RIa;function wIa(n,t="utf-8"){let r=(0,vNe.createConnection)(n,"127.0.0.1");return[new CX(r,t),new YX(r,t)]}Is.createServerSocketTransport=wIa;function CIa(n){let t=n;return t.read!==void 0&&t.addListener!==void 0}function YIa(n){let t=n;return t.write!==void 0&&t.addListener!==void 0}function xIa(n,t,r,a){r||(r=B1.NullLogger);let i=CIa(n)?new GNe(n):n,s=YIa(t)?new gNe(t):t;return B1.ConnectionStrategy.is(a)&&(a={connectionStrategy:a}),(0,B1.createMessageConnection)(i,s,r,a)}Is.createMessageConnection=xIa});var npn=ve((uJi,tpn)=>{"use strict";tpn.exports=epn()});import{pathToFileURL as VIa}from"node:url";import*as Lnt from"node:path";async function rpn(n){let r=(o=>o.replace(/^file:\/\/\/([A-Z])[:%3A]+\//i,(u,d)=>`file:///${d.toLowerCase()}%3A/`))(VIa(n.root).href),a=process.env.DEEPV_LSP_DEBUG==="1"||process.env.DEEPV_LSP_DEBUG==="true";a&&(console.log(`[LSP][${n.serverID}] Creating client for root: ${n.root}`),console.log(`[LSP][${n.serverID}] rootUri: ${r}`));let i=(0,LO.createMessageConnection)(new LO.StreamMessageReader(n.server.process.stdout),new LO.StreamMessageWriter(n.server.process.stdin));i.onError(o=>{console.error(`[LSP][${n.serverID}] Connection error:`,o[0])}),i.onClose(()=>{console.log(`[LSP][${n.serverID}] Connection closed`)}),i.onNotification("textDocument/publishDiagnostics",o=>{a&&console.log(`[LSP][${n.serverID}] textDocument/publishDiagnostics received for ${o.uri}: ${o.diagnostics?.length||0} items`)}),a&&n.server.process?.stderr&&n.server.process.stderr.on("data",o=>{let u=o.toString("utf8").trimEnd();u&&console.log(`[LSP][${n.serverID}][stderr] ${u}`)}),i.onRequest("workspace/configuration",o=>(o.items||[]).map(()=>({}))),i.onRequest("client/registerCapability",()=>({})),i.onRequest("client/unregisterCapability",()=>({})),i.onRequest("window/workDoneProgress/create",()=>null),i.onRequest("workspace/semanticTokens/refresh",()=>null),i.onRequest("workspace/inlayHint/refresh",()=>null),i.onRequest("workspace/codeLens/refresh",()=>null),i.onRequest("workspace/diagnostic/refresh",()=>null),i.onRequest("window/showMessageRequest",o=>{let u=o?.actions;return Array.isArray(u)&&u.length>0?u[0]:null}),i.onRequest("workspace/applyEdit",()=>({applied:!0})),i.onRequest("workspace/workspaceFolders",()=>[{uri:r,name:Lnt.basename(n.root)}]),i.listen();let s={processId:process.pid,rootPath:n.root,rootUri:r,capabilities:{window:{workDoneProgress:!0},textDocument:{synchronization:{dynamicRegistration:!0,willSave:!1,willSaveWaitUntil:!1,didSave:!0,didChange:1},hover:{contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!0,linkSupport:!0},references:{dynamicRegistration:!0},documentSymbol:{dynamicRegistration:!0,hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]}},implementation:{dynamicRegistration:!0,linkSupport:!0},typeDefinition:{dynamicRegistration:!0,linkSupport:!0},diagnostic:{dynamicRegistration:!0}},workspace:{workspaceFolders:!0,configuration:!0,symbol:{dynamicRegistration:!0,symbolKind:{valueSet:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]}}}},workspaceFolders:[{uri:r,name:Lnt.basename(n.root)}]},e=await i.sendRequest("initialize",s);return await i.sendNotification("initialized",{}),await i.sendNotification("workspace/didChangeConfiguration",{settings:{}}),{serverID:n.serverID,root:n.root,connection:i,capabilities:e.capabilities}}async function apn(n){try{await n.connection.sendRequest("shutdown"),await n.connection.sendNotification("exit"),n.connection.dispose()}catch(t){console.error(`[LSP][${n.serverID}] Shutdown error:`,t)}}var LO,ipn=ut(()=>{"use strict";LO=Qt(npn(),1);});import*as J1 from"node:path";import*as ci from"node:fs";import*as lpn from"node:os";import*as spn from"node:zlib";import{spawn as ZNe,spawnSync as QIa}from"node:child_process";function upn(n){if(ci.existsSync(n)){for(let t of ci.readdirSync(n)){let r=J1.join(n,t);ci.statSync(r).isDirectory()?upn(r):ci.unlinkSync(r)}ci.rmdirSync(n)}}var opn,cpn,AI,Ipn=ut(()=>{"use strict";opn=Qt(pq(),1),cpn=Qt(oje(),1);AI=class{static LSP_DIR=J1.join(lpn.homedir(),".deepv","lsp");static findOnPath(t){let r=process.platform==="win32"?"where.exe":"which",i=(QIa(r,[t],{shell:!1,encoding:"utf8",windowsHide:!0}).stdout||"").toString().trim();if(!i)return null;for(let s of i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean))if(ci.existsSync(s))return s;return null}static async cleanBinaryCache(t){let r=J1.join(this.LSP_DIR,t);ci.existsSync(r)&&(console.log(`[LSP] Cleaning corrupted binary cache for ${t} at ${r}`),upn(r),console.log("[LSP] Cache cleaned successfully"))}static async ensureBinary(t,r,a){let i=a?.maxRetries??1,s=null;for(let e=0;e<=i;e++)try{let o=J1.join(this.LSP_DIR,t);return ci.existsSync(o)||ci.mkdirSync(o,{recursive:!0}),await r(o)}catch(o){s=o,e<i&&(console.log(`[LSP] Attempt ${e+1} failed: ${s.message}`),console.log(`[LSP] Cleaning cache and retrying (${i-e} retries left)...`),await this.cleanBinaryCache(t))}throw s||new Error(`Failed to ensure binary for ${t}`)}static async npmInstaller(t,r){return async a=>{let i=J1.join(a,"node_modules",".bin",r+(process.platform==="win32"?".cmd":""));return ci.existsSync(i)||(console.log(`[LSP] Installing ${t.join(", ")} via npm...`),ci.existsSync(J1.join(a,"package.json"))||ci.writeFileSync(J1.join(a,"package.json"),JSON.stringify({name:`deepv-lsp-${r}`,version:"1.0.0",private:!0})),await new Promise((s,e)=>{let o=process.platform==="win32",u=["install",...t,"--no-save"];(o?ZNe("cmd.exe",["/c","npm",...u],{cwd:a,shell:!1,stdio:"inherit"}):ZNe("npm",u,{cwd:a,shell:!1,stdio:"inherit"})).on("close",I=>{I===0?s():e(new Error(`npm install failed with code ${I}`))})})),i}}static async goInstaller(t,r,a="latest"){return async i=>{let s=process.platform,e=J1.join(i,r+(s==="win32"?".exe":""));if(ci.existsSync(e))return e;let o=this.findOnPath("go");if(!o)throw new Error(`[LSP] Go toolchain not found in PATH (required to install ${r}). Please install Go from https://go.dev/dl/ and ensure "go" is available in your PATH, or configure a preinstalled gopls via PATH/DEEPV_GOPLS_PATH.`);if(console.log(`[LSP] Installing ${r} via go install (${t}@${a})...`),await new Promise((u,d)=>{let I=ZNe(o,["install",`${t}@${a}`],{cwd:i,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,GOBIN:i}}),h="";I.stdout?.on("data",c=>{process.stdout.write(c)}),I.stderr?.on("data",c=>{let G=c.toString();h+=G,h.length>16384&&(h=h.slice(h.length-16384)),process.stderr.write(c)}),I.on("close",c=>{if(c===0)u();else{let G=h.trim();d(new Error(`[LSP] go install failed with code ${c}`+(G?`
|
|
1806
|
+
${G}`:"")))}}),I.on("error",c=>{d(new Error(`[LSP] Failed to spawn go (${o}): ${c.message}. Please ensure Go is installed and available in PATH.`))})}),!ci.existsSync(e))throw new Error(`[LSP] ${r} installation completed but binary not found at ${e}. This usually means Go did not honor GOBIN or the install failed silently.`);return e}}static async githubInstaller(t,r,a){return async i=>{let s=process.platform,e=process.arch,o=a(s,e),u=r+(s==="win32"?".exe":""),d=J1.join(i,u);if(ci.existsSync(d))return d;console.log(`[LSP] Downloading ${r} from GitHub ${t}/${r}...`);let I=`https://api.github.com/repos/${t}/${r}/releases/latest`,c=await(await(0,opn.request)(I,{headers:{"User-Agent":"DeepV-Code-Agent"}})).body.json(),G=c.assets.find(w=>typeof o=="string"?w.name===o:o.test(w.name));if(!G){let w=`${s}-${e}`,A=[];r==="rust-analyzer"&&(w==="win32-x64"?A.push(/rust-analyzer.*x86_64.*windows.*\.zip/i,/rust-analyzer.*x64.*windows.*\.zip/i,/rust-analyzer.*msvc.*\.zip/i):w==="win32-arm64"?A.push(/rust-analyzer.*aarch64.*windows.*\.zip/i):w==="darwin-x64"?A.push(/rust-analyzer.*x86_64.*apple-darwin.*\.gz/i,/rust-analyzer.*x86_64.*macos.*\.gz/i):w==="darwin-arm64"?A.push(/rust-analyzer.*aarch64.*apple-darwin.*\.gz/i,/rust-analyzer.*aarch64.*macos.*\.gz/i):w==="linux-x64"?A.push(/rust-analyzer.*x86_64.*linux.*\.gz/i,/rust-analyzer.*x86_64.*gnu.*\.gz/i):w==="linux-arm64"&&A.push(/rust-analyzer.*aarch64.*linux.*\.gz/i,/rust-analyzer.*aarch64.*gnu.*\.gz/i)),A.length>0&&(G=c.assets.find(E=>A.some(f=>f.test(E.name))))}if(!G){let w=c.assets.map(A=>A.name).join(", ");throw new Error(`Could not find a suitable binary for ${s}-${e} in ${t}/${r} releases. Available: ${w}`)}console.log(`[LSP] Downloading: ${G.name}`),console.log(`[LSP] File size: ${(G.size/1024/1024).toFixed(1)}MB`);let F=J1.join(i,G.name),W=Date.now(),R=0;if(await new Promise((w,A)=>{let E=process.platform==="win32"?"curl.exe":"curl",f=ZNe(E,["-L","--fail","-o",F,G.browser_download_url]),g="",v=setInterval(()=>{if(ci.existsSync(F)){let N=ci.statSync(F).size,m=(N/(G.size||1)*100).toFixed(1),p=(N/1024/1024).toFixed(1),b=(G.size/1024/1024).toFixed(1);console.log(`[LSP] \u2B07\uFE0F ${G.name}: ${p}MB / ${b}MB (${m}%)`),R=N,W=Date.now()}},2e3);f.stderr.on("data",N=>{g+=N.toString()}),f.on("close",N=>{clearInterval(v),N===0?w():(ci.existsSync(F)&&ci.unlinkSync(F),A(new Error(`[LSP] curl failed with code ${N}: ${g}`)))}),f.on("error",N=>{clearInterval(v),ci.existsSync(F)&&ci.unlinkSync(F),A(new Error(`[LSP] Failed to spawn curl: ${N.message}. curl may not be installed or available in PATH. Please install curl and add it to your system PATH.`))})}),!ci.existsSync(F))throw new Error(`[LSP] Downloaded file not found at ${F}. curl may have failed silently.`);let y=ci.statSync(F).size;if(y===0)throw ci.unlinkSync(F),new Error(`[LSP] Downloaded file is empty (0 bytes) for ${G.name}. The download URL may be invalid or temporarily unavailable. Please retry.`);if(console.log(`[LSP] Downloaded ${y} bytes (expected: ${G.size} bytes)`),G.name.endsWith(".gz")){console.log(`[LSP] Decompressing ${G.name}...`);let w=ci.readFileSync(F);try{let A=spn.gunzipSync(w);if(A.length===0)throw new Error("Decompressed data is empty");ci.writeFileSync(d,A)}catch(A){ci.unlinkSync(F);let E=A instanceof Error?A.message:String(A);throw new Error(`[LSP] Failed to decompress ${G.name}: ${E}. The file may be corrupted. Please retry.`)}ci.unlinkSync(F)}else if(G.name.endsWith(".zip")){console.log(`[LSP] Extracting ${G.name}...`);let w=ci.readFileSync(F);if(w.length<4)throw ci.unlinkSync(F),new Error(`[LSP] ZIP file is too small (${w.length} bytes) for ${G.name}. The download is corrupted. Please retry or check your network connection.`);if(w[0]!==80||w[1]!==75||w[2]!==3||w[3]!==4)throw ci.unlinkSync(F),new Error(`[LSP] ZIP file header is corrupted for ${G.name}. The download may have been interrupted. Please retry.`);let A;try{A=await cpn.default.loadAsync(w)}catch(N){ci.unlinkSync(F);let m=N instanceof Error?N.message:String(N);throw new Error(`[LSP] Failed to parse ZIP file ${G.name}: ${m}. The file may be corrupted. Please retry the download.`)}let E=u.toLowerCase(),g=Object.values(A.files).filter(N=>!N.dir).filter(N=>J1.posix.basename(N.name).toLowerCase()===E).sort((N,m)=>N.name.length-m.name.length)[0];if(!g)throw new Error(`Zip archive did not contain expected executable "${u}" for ${t}/${r}.`);let v=await g.async("nodebuffer");ci.writeFileSync(d,v),ci.unlinkSync(F)}else ci.renameSync(F,d);if(s!=="win32"&&ci.chmodSync(d,493),console.log(`[LSP] Binary installed at: ${d}`),console.log(`[LSP] Binary exists: ${ci.existsSync(d)}`),ci.existsSync(d)){let w=ci.statSync(d);console.log(`[LSP] Binary stats: size=${w.size}, mode=${(w.mode&parseInt("777",8)).toString(8)}`)}return d}}}});import*as V0 from"node:path";import*as IZ from"node:fs";import{spawn as CY}from"node:child_process";function SO(n,t,r){let i=process.platform==="win32"&&n.toLowerCase().endsWith(".cmd"),s={cwd:r.cwd,shell:!1,stdio:["pipe","pipe","pipe"]};if(i&&IZ.existsSync(n)){let o=IZ.readFileSync(n,"utf8").match(/%dp0%([^"]*\.m?js)/i);if(o){let u=V0.dirname(n),d=o[1].replace(/\\/g,V0.sep);d.startsWith(V0.sep)&&(d="."+d);let I=V0.resolve(u,d);if(IZ.existsSync(I))return CY(process.execPath,[I,...t],s)}return CY("cmd.exe",["/c",n,...t],s)}return CY(n,t,s)}var Sae,HIa,XIa,kIa,LIa,SIa,BIa,JIa,TIa,DIa,dpn,hpn=ut(()=>{"use strict";Ipn();Sae=(n,t)=>async r=>{let a=V0.normalize(V0.dirname(V0.resolve(r))),i=V0.normalize(V0.resolve(t)),s=(e,o)=>{let u=e.toLowerCase(),d=o.toLowerCase();return u.startsWith(d)||u===d};for(;s(a,i);){for(let o of n)if(IZ.existsSync(V0.join(a,o)))return a;let e=V0.normalize(V0.dirname(a));if(e===a)break;a=e}return i},HIa=n=>({id:"typescript-language-server",displayName:"TypeScript/JavaScript Language Server",extensions:[".ts",".tsx",".js",".jsx"],root:Sae(["package.json","tsconfig.json","jsconfig.json"],n),async spawn(t){let r=await AI.ensureBinary("typescript-language-server",await AI.npmInstaller(["typescript-language-server","typescript"],"typescript-language-server")),a=V0.join(V0.dirname(r),"..","..","typescript","lib","tsserver.js"),i=["--stdio"];return IZ.existsSync(a)&&i.push("--tsserver-path",a),{process:SO(r,i,{cwd:t})}}}),XIa=n=>({id:"pyright",displayName:"Python Language Server",extensions:[".py"],root:Sae(["pyproject.toml","setup.py","requirements.txt","package.json"],n),async spawn(t){let r=await AI.ensureBinary("pyright",await AI.npmInstaller(["pyright"],"pyright-langserver"));return{process:SO(r,["--stdio"],{cwd:t})}}}),kIa=n=>({id:"rust-analyzer",displayName:"Rust Language Server",extensions:[".rs"],root:Sae(["Cargo.toml"],n),async spawn(t){let r=process.platform,a=process.arch;console.log(`[LSP] Detecting platform for rust-analyzer: platform=${r}, arch=${a}`);let i=await AI.githubInstaller("rust-lang","rust-analyzer",(o,u)=>{let d={"win32-x64":/rust-analyzer.*x86_64.*windows.*\.zip/i,"win32-arm64":/rust-analyzer.*aarch64.*windows.*\.zip/i,"darwin-x64":/rust-analyzer.*x86_64.*apple-darwin.*\.gz/i,"darwin-arm64":/rust-analyzer.*aarch64.*apple-darwin.*\.gz/i,"linux-x64":/rust-analyzer.*x86_64.*linux.*\.gz/i,"linux-arm64":/rust-analyzer.*aarch64.*linux.*\.gz/i},I=`${o}-${u}`,h=d[I]||/rust-analyzer-.*/;return console.log(`[LSP] Asset matcher for ${I}: ${h instanceof RegExp?h.source:h}`),h}),s=await AI.ensureBinary("rust-analyzer",i,{maxRetries:1});if(console.log(`[LSP] RustAnalyzer binary path: ${s}`),console.log(`[LSP] RustAnalyzer binary exists: ${IZ.existsSync(s)}`),IZ.existsSync(s)){let o=IZ.statSync(s);console.log(`[LSP] RustAnalyzer binary stats: size=${o.size}, isFile=${o.isFile()}, mode=${(o.mode&parseInt("777",8)).toString(8)}`)}console.log(`[LSP] RustAnalyzer spawning with cwd=${t}, args=[], shell=undefined`);let e=CY(s,[],{cwd:t});return console.log(`[LSP] RustAnalyzer spawn returned: pid=${e.pid}`),e.on("error",o=>{console.error("[LSP] RustAnalyzer process error:",{code:o.code,errno:o.errno,syscall:o.syscall,path:o.path,message:o.message})}),e.on("exit",(o,u)=>{console.log(`[LSP] RustAnalyzer process exited: code=${o}, signal=${u}`)}),{process:e}}}),LIa=n=>({id:"gopls",displayName:"Go Language Server",extensions:[".go"],root:Sae(["go.mod","go.sum"],n),async spawn(t){let r=process.env.DEEPV_GOPLS_PATH;if(r&&IZ.existsSync(r))return{process:CY(r,[],{cwd:t})};let a=AI.findOnPath("gopls");if(a)return{process:CY(a,[],{cwd:t})};let i=await AI.ensureBinary("gopls",await AI.goInstaller("golang.org/x/tools/gopls","gopls"),{maxRetries:1});return{process:CY(i,[],{cwd:t})}}}),SIa=n=>({id:"clangd",displayName:"C/C++ Language Server",extensions:[".c",".cpp",".h",".hpp",".cc"],root:Sae(["compile_commands.json","CMakeLists.txt",".git"],n),async spawn(t){let r=await AI.githubInstaller("clangd","clangd",(i,s)=>{let e=i==="win32"?"windows":i==="darwin"?"mac":"linux";return new RegExp(`clangd-${e}-.*\\.zip`)}),a=await AI.ensureBinary("clangd",r,{maxRetries:1});return{process:CY(a,[],{cwd:t})}}}),BIa=n=>({id:"vscode-langservers-extracted",displayName:"HTML/CSS/JSON/ESLint Language Server",extensions:[".html",".css",".json",".jsonc"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("vscode-langservers-extracted",await AI.npmInstaller(["vscode-langservers-extracted"],"vscode-html-language-server"));return{process:SO(r,["--stdio"],{cwd:t})}}}),JIa=n=>({id:"sql-language-server",displayName:"SQL Language Server",extensions:[".sql"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("sql-language-server",await AI.npmInstaller(["sql-language-server"],"sql-language-server"));return{process:SO(r,["up","--method","stdio"],{cwd:t})}}}),TIa=n=>({id:"dockerfile-language-server-nodejs",displayName:"Dockerfile Language Server",extensions:["Dockerfile",".dockerfile"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("dockerfile-language-server-nodejs",await AI.npmInstaller(["dockerfile-language-server-nodejs"],"docker-langserver"));return{process:SO(r,["--stdio"],{cwd:t})}}}),DIa=n=>({id:"yaml-language-server",displayName:"YAML Language Server",extensions:[".yaml",".yml"],root:async()=>n,async spawn(t){let r=await AI.ensureBinary("yaml-language-server",await AI.npmInstaller(["yaml-language-server"],"yaml-language-server"));return{process:SO(r,["--stdio"],{cwd:t})}}}),dpn=n=>[HIa(n),XIa(n),kIa(n),LIa(n),SIa(n),BIa(n),JIa(n),TIa(n),DIa(n)]});import*as wR from"node:path";import*as NNe from"node:fs";import{pathToFileURL as OIa}from"node:url";var Up,YY=ut(()=>{"use strict";ipn();hpn();Up=class{clients=new Map;servers;projectRoot;openedFiles=new Set;fileVersions=new Map;fileContents=new Map;freshClients=new Set;constructor(t){this.projectRoot=t,this.servers=dpn(t)}async getClientsForFile(t){let r=wR.extname(t).toLowerCase(),a=this.servers.filter(s=>s.extensions.includes(r)),i=[];for(let s of a){let e=await s.root(t),o=`${s.id}:${e}`;if(this.clients.has(o))i.push(this.clients.get(o));else try{console.log(`[LSP] Starting ${s.id} for root ${e}`);let{process:u}=await s.spawn(e);console.log(`[LSP] Process spawned: pid=${u.pid}, stdio=${JSON.stringify(u.stdio)}`);let d=await rpn({serverID:s.id,server:{process:u},root:e});this.clients.set(o,d),this.freshClients.add(d.serverID),i.push(d)}catch(u){let d=u instanceof Error?{message:u.message,stack:u.stack,code:u.code,errno:u.errno,syscall:u.syscall,path:u.path}:String(u);console.error(`[LSP] Failed to start ${s.id}:`,d);let I=u;(I.errno===-4094||I.code==="UNKNOWN")&&console.error(`[LSP] Binary file may be corrupted (errno=${I.errno}). Suggest deleting ${s.id} cache and reinitializing.`)}}return i}async syncDocument(t,r){let a=this.getUri(r),i=`${t.serverID}:${a}`,s=NNe.readFileSync(r,"utf8");if(!this.openedFiles.has(i))this.fileVersions.set(i,1),this.fileContents.set(i,s),await t.connection.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(r),version:1,text:s}}),this.openedFiles.add(i),await new Promise(e=>setTimeout(e,3e3));else{if(this.fileContents.get(i)===s)return;let o=(this.fileVersions.get(i)||1)+1;this.fileVersions.set(i,o),this.fileContents.set(i,s),await t.connection.sendNotification("textDocument/didChange",{textDocument:{uri:a,version:o},contentChanges:[{text:s}]})}}getLanguageId(t){switch(wR.extname(t).toLowerCase()){case".ts":case".tsx":return"typescript";case".js":case".jsx":return"javascript";case".go":return"go";case".py":return"python";case".rs":return"rust";default:return"plaintext"}}getUri(t){return OIa(wR.resolve(t)).href.replace(/^file:\/\/\/([A-Z])[:%3A]+\//i,(a,i)=>`file:///${i.toLowerCase()}%3A/`)}async shutdown(){for(let t of this.clients.values())await apn(t);this.clients.clear(),this.openedFiles.clear()}async run(t,r,a){let i=process.env.DEEPV_LSP_DEBUG==="1"||process.env.DEEPV_LSP_DEBUG==="true",s=Number(process.env.DEEPV_LSP_REQUEST_TIMEOUT_MS),e=a?.timeoutMs??(Number.isFinite(s)&&s>0?s:15e3),o=a?.operationName??"request",u=wR.normalize(t),d=await this.getClientsForFile(u),I=await Promise.all(d.map(async c=>{await this.syncDocument(c,u),this.freshClients.has(c.serverID)&&this.freshClients.delete(c.serverID);try{return await Promise.race([r(c),new Promise((F,W)=>{let R=setTimeout(()=>{clearTimeout(R),W(new Error(`[LSP][${c.serverID}] ${o} timed out after ${e}ms`))},e)})])}catch(G){if(i)console.error(`[LSP][${c.serverID}] Request failed:`,G);else{let F=G instanceof Error?G.message:String(G);F.includes("timed out after")?console.warn(F):console.error(`[LSP][${c.serverID}] Request failed:`,F)}return null}})),h=[];for(let c of I)c!==null&&h.push(c);return h}async getHover(t,r,a){return this.run(t,i=>i.connection.sendRequest("textDocument/hover",{textDocument:{uri:this.getUri(t)},position:{line:r,character:a}}),{operationName:"textDocument/hover"})}async getDefinition(t,r,a){return this.run(t,i=>i.connection.sendRequest("textDocument/definition",{textDocument:{uri:this.getUri(t)},position:{line:r,character:a}}),{operationName:"textDocument/definition"})}async getReferences(t,r,a){return this.run(t,async i=>{let s={textDocument:{uri:this.getUri(t)},position:{line:r,character:a},context:{includeDeclaration:!0}},e=await i.connection.sendRequest("textDocument/references",s);return(!e||e.length===0)&&(console.log(`[LSP][${i.serverID}] No references found, retrying in 3s...`),await new Promise(o=>setTimeout(o,3e3)),e=await i.connection.sendRequest("textDocument/references",s)),e},{operationName:"textDocument/references"})}async getImplementation(t,r,a){return this.run(t,async i=>{let s={textDocument:{uri:this.getUri(t)},position:{line:r,character:a}},e=await i.connection.sendRequest("textDocument/implementation",s);return(!e||e.length===0)&&(console.log(`[LSP][${i.serverID}] No implementation found, retrying in 3s...`),await new Promise(o=>setTimeout(o,3e3)),e=await i.connection.sendRequest("textDocument/implementation",s)),e},{operationName:"textDocument/implementation"})}async getDocumentSymbols(t){return this.run(t,r=>r.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:this.getUri(t)}}),{operationName:"textDocument/documentSymbol"})}async getWorkspaceSymbols(t){if(this.clients.size===0){console.log("[LSP] No active clients for workspace symbols, probing project...");let a=NNe.readdirSync(this.projectRoot,{recursive:!0}),i=[{ext:".ts",id:"typescript-language-server"},{ext:".py",id:"pyright"},{ext:".go",id:"gopls"},{ext:".rs",id:"rust-analyzer"},{ext:".js",id:"typescript-language-server"}];for(let s of i){let e=a.find(o=>o.endsWith(s.ext)&&!o.includes("node_modules")&&!o.includes("dist"));if(e){console.log(`[LSP] Detected ${s.ext} project, activating ${s.id}...`);let o=wR.join(this.projectRoot,e),u=await this.getClientsForFile(o);for(let d of u)await this.syncDocument(d,o);console.log(`[LSP] Waiting 5s for ${s.id} indexing...`),await new Promise(d=>setTimeout(d,5e3));break}}}let r=[];console.log(`[LSP] Searching workspace symbols for "${t}" across ${this.clients.size} clients...`);for(let a of this.clients.values())try{let i=await a.connection.sendRequest("workspace/symbol",{query:t});(!i||i.length===0)&&(console.log(`[LSP][${a.serverID}] No symbols yet, retrying in 3s...`),await new Promise(s=>setTimeout(s,3e3)),i=await a.connection.sendRequest("workspace/symbol",{query:t})),console.log(`[LSP][${a.serverID}] Found ${i?.length||0} symbols`),i&&r.push(i)}catch(i){console.error(`[LSP][${a.serverID}] Workspace symbols failed:`,i)}return r}async getDiagnostics(t){return[]}}});import*as mpn from"node:path";function UIa(n){return Snt||(Snt=new Up(n)),Snt}var Snt,xX,ppn=ut(()=>{"use strict";Ll();YY();wi();Snt=null;xX=class n extends qr{config;static Name="lsp_hover";constructor(t){super(n.Name,"LSP Hover","Get hover information (type info, documentation) for a specific position in a file using Language Server Protocol.",$r.LightBulb,{type:gn.OBJECT,properties:{filePath:{type:gn.STRING,description:"The absolute path to the file to inspect."},line:{type:gn.NUMBER,description:"The 1-based line number (as shown in editors)."},character:{type:gn.NUMBER,description:"The 1-based character offset on the line (as shown in editors)."}},required:["filePath","line","character"]}),this.config=t}validateToolParams(t){return!t.filePath||!mpn.isAbsolute(t.filePath)?"filePath must be an absolute path.":t.line<1||t.character<1?"line and character must be 1-based (>= 1).":null}async execute(t){let a=await UIa(this.config.getTargetDir()).getHover(t.filePath,t.line-1,t.character-1);if(a.length===0||!a[0])return{llmContent:"No hover information found. This might be because the position is on a keyword, or the LSP server is still indexing. Try moving the character offset to the symbol name.",returnDisplay:"No hover information found."};let i=a.map(s=>!s||!s.contents?"":Array.isArray(s.contents)?s.contents.map(e=>typeof e=="string"?e:e.value).join(`
|
|
1807
1807
|
|
|
1808
1808
|
`):typeof s.contents=="string"?s.contents:s.contents.value).filter(Boolean).join(`
|
|
1809
1809
|
---
|
|
@@ -4551,7 +4551,7 @@ The DEEPV.md file already exists with content. You MUST follow these steps:
|
|
|
4551
4551
|
`,t-1),[i,s]=g8a(r);return{line:a===-1?i:n.slice(0,a+1).match(/\n/g).length+i,column:t-a-1+s}}function Rmt(n,t,r){if(typeof n!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(t))throw new TypeError("Index parameter should be an integer");if(t<0||t>n.length)throw new RangeError("Index out of bounds");return v8a(n,t,r)}var Z8a=n=>`\\u{${n.codePointAt(0).toString(16)}}`,wmt=class n extends Error{name="JSONError";fileName;#e;#t;#n;#r;#a;constructor(t){if(typeof t=="string")super(),this.#n=t;else{let{jsonParseError:r,fileName:a,input:i}=t;super(void 0,{cause:r}),this.#e=i,this.#t=r,this.fileName=a}Error.captureStackTrace?.(this,n)}get message(){this.#n??=`${A8a(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:t}=this;return`${this.#n}${this.fileName?` in ${this.fileName}`:""}${t?`
|
|
4552
4552
|
|
|
4553
4553
|
${t}
|
|
4554
|
-
`:""}`}set message(t){this.#n=t}#i(t){if(!this.#t)return;let r=this.#e,a=N8a(r,this.#t.message);if(a)return(0,jJn.codeFrameColumns)(r,{start:a},{highlightCode:t})}get codeFrame(){return this.#r??=this.#i(!0),this.#r}get rawCodeFrame(){return this.#a??=this.#i(!1),this.#a}},N8a=(n,t)=>{let r=t.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:a,line:i,column:s}=r.groups;return i&&s?{line:Number(i),column:Number(s)}:Rmt(n,Number(a),{oneBased:!0})},A8a=n=>n.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,r,a)=>`"${a}"(${Z8a(a)})`);function Cmt(n,t,r){typeof t=="string"&&(r=t,t=void 0);try{return JSON.parse(n,t)}catch(a){throw new wmt({jsonParseError:a,fileName:r,input:n})}}var z8n=Qt(U8n(),1);import{fileURLToPath as ZTa}from"node:url";function M8n(n){return n instanceof URL?ZTa(n):n}var WTa=n=>ATa.resolve(M8n(n)??".","package.json"),yTa=(n,t)=>{let r=typeof n=="string"?Cmt(n):n;return t&&(0,z8n.default)(r),r};async function _8n({cwd:n,normalize:t=!0}={}){let r=await NTa.readFile(WTa(n),"utf8");return yTa(r,t)}async function P8n(n){let t=await yJn("package.json",n);if(t)return{packageJson:await _8n({...n,cwd:FTa.dirname(t)}),path:t}}import{fileURLToPath as ETa}from"url";import RTa from"path";var wTa=ETa(import.meta.url),CTa=RTa.dirname(wTa),L4e;async function qz(){if(L4e)return L4e;let n=await P8n({cwd:CTa});if(n)return L4e=n.packageJson,L4e}async function Ux(){let n=await qz();return"1.0.
|
|
4554
|
+
`:""}`}set message(t){this.#n=t}#i(t){if(!this.#t)return;let r=this.#e,a=N8a(r,this.#t.message);if(a)return(0,jJn.codeFrameColumns)(r,{start:a},{highlightCode:t})}get codeFrame(){return this.#r??=this.#i(!0),this.#r}get rawCodeFrame(){return this.#a??=this.#i(!1),this.#a}},N8a=(n,t)=>{let r=t.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:a,line:i,column:s}=r.groups;return i&&s?{line:Number(i),column:Number(s)}:Rmt(n,Number(a),{oneBased:!0})},A8a=n=>n.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,r,a)=>`"${a}"(${Z8a(a)})`);function Cmt(n,t,r){typeof t=="string"&&(r=t,t=void 0);try{return JSON.parse(n,t)}catch(a){throw new wmt({jsonParseError:a,fileName:r,input:n})}}var z8n=Qt(U8n(),1);import{fileURLToPath as ZTa}from"node:url";function M8n(n){return n instanceof URL?ZTa(n):n}var WTa=n=>ATa.resolve(M8n(n)??".","package.json"),yTa=(n,t)=>{let r=typeof n=="string"?Cmt(n):n;return t&&(0,z8n.default)(r),r};async function _8n({cwd:n,normalize:t=!0}={}){let r=await NTa.readFile(WTa(n),"utf8");return yTa(r,t)}async function P8n(n){let t=await yJn("package.json",n);if(t)return{packageJson:await _8n({...n,cwd:FTa.dirname(t)}),path:t}}import{fileURLToPath as ETa}from"url";import RTa from"path";var wTa=ETa(import.meta.url),CTa=RTa.dirname(wTa),L4e;async function qz(){if(L4e)return L4e;let n=await P8n({cwd:CTa});if(n)return L4e=n.packageJson,L4e}async function Ux(){let n=await qz();return"1.0.309"}vi();import E6 from"node:process";sr();var j8n={name:"about",description:He("command.about.description"),kind:"built-in",action:async n=>{let t=E6.platform,r="no sandbox";E6.env.SANDBOX&&E6.env.SANDBOX!=="sandbox-exec"?r=E6.env.SANDBOX:E6.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${E6.env.SEATBELT_PROFILE||"unknown"})`);let a=n.services.config?.getModel()||"Unknown",i=await Ux(),s=n.services.settings.merged.selectedAuthType||"",e=E6.env.GOOGLE_CLOUD_PROJECT||"",o={type:"about",cliVersion:i,osVersion:t,sandboxEnv:r,modelVersion:a,selectedAuthType:s,gcpProject:e};n.ui.addItem(o,Date.now())}};vi();sr();var K8n={name:"auth",description:He("command.auth.description"),kind:"built-in",action:(n,t)=>({type:"dialog",dialog:"auth"})};vi();sr();var q8n={name:"clear",description:He("command.clear.description"),kind:"built-in",action:async(n,t)=>{n.ui.setDebugMessage("Clearing terminal screen."),n.ui.clear()}};vi();sr();var $8n={name:"compress",altNames:["summarize"],description:He("command.compress.description"),kind:"built-in",action:async n=>{let{ui:t}=n,r=n.services.config?.getGeminiClient();if(t.pendingItem){t.addItem({type:"error",text:"Already compressing, wait for previous request to complete"},Date.now());return}if(r?.isCompressionInProgress()){t.addItem({type:"error",text:"Compression already in progress at client level, please wait"},Date.now());return}t.addItem({type:"info",text:He("command.compress.starting")},Date.now());let a={type:"compression",compression:{isPending:!0,originalTokenCount:null,newTokenCount:null}};try{t.setPendingItem(a);let i=`compress-${Date.now()}`,s=await r?.tryCompressChat(i,new AbortController().signal,!0);s?t.addItem({type:"compression",compression:{isPending:!1,originalTokenCount:s.originalTokenCount,newTokenCount:s.newTokenCount}},Date.now()):t.addItem({type:"error",text:"Failed to compress chat history."},Date.now())}catch(i){t.addItem({type:"error",text:`Failed to compress chat history: ${i instanceof Error?i.message:String(i)}`},Date.now())}finally{t.setPendingItem(null)}}};vi();sr();cr();pu();var lTn={name:"config",altNames:["settings","preferences"],description:He("command.config.description"),kind:"built-in",action:async(n,t)=>{let{config:r,settings:a}=n.services,i=t.trim().toLowerCase();if(!r||!a)return{type:"message",messageType:"error",content:He("error.config.not.loaded")};if(!i)return{type:"dialog",dialog:"settings-menu"};let[s,...e]=i.split(/\s+/),o=e.join(" ");switch(s){case"theme":case"t":return{type:"dialog",dialog:"theme"};case"editor":case"e":return{type:"dialog",dialog:"editor"};case"model":case"m":return eTn(n,o);case"vim":case"v":return await tTn(n);case"agent-style":case"agent":case"a":return await nTn(n,o);case"yolo":case"y":return rTn(n,o);case"healthy-use":case"healthy":case"h":return aTn(n,o);case"language":case"lang":case"l":return await iTn(n,o);case"help":return YTa(n);default:return{type:"message",messageType:"error",content:jt("command.config.unknown.subcommand",{subcommand:s})+`
|
|
4555
4555
|
|
|
4556
4556
|
`+S4e()}}},subCommands:[{name:"theme",altNames:["t"],description:He("theme.name"),kind:"built-in",action:()=>({type:"dialog",dialog:"theme"})},{name:"editor",altNames:["e"],description:He("command.editor.description"),kind:"built-in",action:()=>({type:"dialog",dialog:"editor"})},{name:"model",altNames:["m"],description:He("model.command.description"),kind:"built-in",action:async(n,t)=>eTn(n,t)},{name:"vim",altNames:["v"],description:He("command.vim.description"),kind:"built-in",action:async n=>tTn(n)},{name:"agent-style",altNames:["agent","a"],description:He("command.agentStyle.description"),kind:"built-in",action:async(n,t)=>nTn(n,t)},{name:"yolo",altNames:["y"],description:He("command.yolo.description"),kind:"built-in",action:(n,t)=>rTn(n,t)},{name:"healthy-use",altNames:["healthy","h"],description:He("command.healthyUse.description"),kind:"built-in",action:(n,t)=>aTn(n,t)},{name:"language",altNames:["lang","l"],description:He("config.menu.language"),kind:"built-in",action:async(n,t)=>iTn(n,t)}],completion:async(n,t)=>["theme","editor","model","vim","agent-style","yolo","healthy-use","language","help","t","e","m","v","a","y","h","l"].filter(a=>a.toLowerCase().startsWith(t.toLowerCase()))};async function YTa(n){let{config:t,settings:r}=n.services;if(!t||!r)return{type:"message",messageType:"error",content:He("error.config.not.loaded")};let a=r.merged.vimMode||!1,i=t.getAgentStyle(),s=t.getApprovalMode(),e=t.getHealthyUseEnabled(),o=r.merged.preferredLanguage||He("config.value.default"),u=I=>{switch(I){case"codex":return"\u26A1";case"cursor":return"\u2197\uFE0F";case"augment":return"\u{1F680}";case"claude-code":return"\u2733\uFE0F";case"antigravity":return"\u{1F308}";case"windsurf":return"\u{1F30A}";default:return"\u{1D4E5}"}};return{type:"message",messageType:"info",content:`\u2699\uFE0F ${He("command.config.description")}
|
|
4557
4557
|
|